Overview

Packages

  • Core
    • Authentication
    • Backend
    • Cache
    • CEC
    • Chain
    • ContentType
    • Database
    • Datatype
    • Debug
    • Exception
    • Frontend
      • Search
      • URI
      • Util
    • GenericDB
      • Model
    • GUI
      • HTML
    • I18N
    • LayoutHandler
    • Log
    • Security
    • Session
    • Util
    • Validation
    • Versioning
    • XML
  • Module
    • ContentSitemapHtml
    • ContentSitemapXml
    • ContentUserForum
    • NavigationMain
    • NavigationTop
  • mpAutoloaderClassMap
  • None
  • Plugin
    • ContentAllocation
    • CronjobOverview
    • FormAssistant
    • FrontendLogic
    • FrontendUsers
    • Linkchecker
    • ModRewrite
    • Newsletter
    • Repository
      • FrontendNavigation
      • KeywordDensity
    • SearchSolr
    • SmartyWrapper
    • UrlShortener
    • UserForum
    • Workflow
  • PluginManager
  • Setup
    • Form
    • GUI
    • Helper
      • Environment
      • Filesystem
      • MySQL
      • PHP
    • UpgradeJob

Classes

  • Newsletter
  • NewsletterCollection
  • NewsletterJob
  • NewsletterJobCollection
  • NewsletterLog
  • NewsletterLogCollection
  • NewsletterRecipient
  • NewsletterRecipientCollection
  • NewsletterRecipientGroup
  • NewsletterRecipientGroupCollection
  • NewsletterRecipientGroupMember
  • NewsletterRecipientGroupMemberCollection
  • Overview
  • Package
  • Class
  • Tree
  • Deprecated
  • Todo
  1: <?php
  2: /**
  3:  * This file contains the Newsletter recipient class.
  4:  *
  5:  * @package Plugin
  6:  * @subpackage Newsletter
  7:  * @version SVN Revision $Rev:$
  8:  *
  9:  * @author Bjoern Behrens
 10:  * @copyright four for business AG <www.4fb.de>
 11:  * @license http://www.contenido.org/license/LIZENZ.txt
 12:  * @link http://www.4fb.de
 13:  * @link http://www.contenido.org
 14:  */
 15: 
 16: defined('CON_FRAMEWORK') || die('Illegal call: Missing framework initialization - request aborted.');
 17: 
 18: /**
 19:  * Newsletter recipient class.
 20:  *
 21:  * @package Plugin
 22:  * @subpackage Newsletter
 23:  */
 24: class NewsletterCollection extends ItemCollection
 25: {
 26:     /**
 27:      * Constructor Function
 28:      * @param none
 29:      */
 30:     public function __construct()
 31:     {
 32:         global $cfg;
 33:         parent::__construct($cfg["tab"]["news"], "idnews");
 34:         $this->_setItemClass("Newsletter");
 35:     }
 36: 
 37:     /**
 38:      * Creates a new newsletter
 39:      * @param $name string specifies the newsletter name
 40:      */
 41:     public function create($sName)
 42:     {
 43:         global $client, $lang, $auth;
 44: 
 45:         $sName  = cSecurity::escapeDB($sName, null);
 46:         $client = cSecurity::toInteger($client);
 47:         $lang   = cSecurity::toInteger($lang);
 48: 
 49:         // Check if the newsletter name already exists
 50:         $this->resetQuery;
 51:         $this->setWhere("idclient", $client);
 52:         $this->setWhere("idlang", $lang);
 53:         $this->setWhere("name", $sName);
 54:         $this->query();
 55: 
 56:         if ($this->next()) {
 57:             return $this->create($sName."_".substr(md5(rand()), 0, 10));
 58:         }
 59: 
 60:         $oItem = parent::createNewItem();
 61:         $oItem->set("idclient", $client);
 62:         $oItem->set("idlang", $lang);
 63:         $oItem->set("name", $sName);
 64:         $oItem->set("created", date('Y-m-d H:i:s'), false);
 65:         $oItem->set("author", cSecurity::escapeDB($auth->auth["uid"], null));
 66: 
 67:         $oItem->store();
 68: 
 69:         return $oItem;
 70:     }
 71: 
 72:     /**
 73:      * Duplicates the newsletter specified by $itemID
 74:      * @param $itemID integer specifies the newsletter id
 75:      */
 76:     public function duplicate($iItemID)
 77:     {
 78:         global $client, $lang, $auth;
 79: 
 80:         $client = cSecurity::toInteger($client);
 81:         $lang   = cSecurity::toInteger($lang);
 82: 
 83:         cInclude("includes", "functions.con.php");
 84: 
 85:         $oBaseItem = new Newsletter();
 86:         $oBaseItem->loadByPrimaryKey($iItemID);
 87: 
 88:         $oItem = parent::createNewItem();
 89:         $oItem->set("name", $oBaseItem->get("name")."_".substr(md5(rand()), 0, 10));
 90: 
 91:         $iIDArt = 0;
 92:         if ($oBaseItem->get("type") == "html" && $oBaseItem->get("idart") > 0 && $oBaseItem->get("template_idart") > 0) {
 93:             $oClientLang = new cApiClientLanguage(false, $client, $lang);
 94: 
 95:             if ($oClientLang->getProperty("newsletter", "html_newsletter") == "true") {
 96:                 $iIDArt = conCopyArticle($oBaseItem->get("idart"),
 97:                                          $oClientLang->getProperty("newsletter", "html_newsletter_idcat"),
 98:                                          sprintf(i18n("Newsletter: %s"), $oItem->get("name")));
 99:                 conMakeOnline($iIDArt, $lang); // Article has to be online for sending...
100:             }
101:             unset($oClientLang);
102:         }
103:         $oItem->set("idart", $iIDArt);
104:         $oItem->set("template_idart", $oBaseItem->get("template_idart"));
105:         $oItem->set("idclient", $client);
106:         $oItem->set("idlang", $lang);
107:         $oItem->set("welcome", 0);
108:         $oItem->set("type", $oBaseItem->get("type"));
109:         $oItem->set("subject", $oBaseItem->get("subject"));
110:         $oItem->set("message", $oBaseItem->get("message"));
111:         $oItem->set("newsfrom", $oBaseItem->get("newsfrom"));
112:         $oItem->set("newsfromname", $oBaseItem->get("newsfromname"));
113:         $oItem->set("newsdate", date("Y-m-d H:i:s"), false); // But more or less deprecated
114:         $oItem->set("use_cronjob", $oBaseItem->get("use_cronjob"));
115:         $oItem->set("send_to", $oBaseItem->get("send_to"));
116:         $oItem->set("send_ids", $oBaseItem->get("send_ids"));
117:         $oItem->set("dispatch", $oBaseItem->get("dispatch"));
118:         $oItem->set("dispatch_count", $oBaseItem->get("dispatch_count"));
119:         $oItem->set("dispatch_delay", $oBaseItem->get("dispatch_delay"));
120:         $oItem->set("author", $auth->auth["uid"]);
121:         $oItem->set("created", date('Y-m-d H:i:s'), false);
122: 
123:         // Copy properties, runtime on-demand allocation of the properties object
124:         if (!is_object($this->properties)) {
125:             $this->properties = new cApiPropertyCollection();
126:         }
127:         $this->properties->setWhere("idclient", $client);
128:         $this->properties->setWhere("itemtype", $this->primaryKey);
129:         $this->properties->setWhere("itemid", $iItemID);
130:         $this->properties->query();
131: 
132:         while ($oPropertyItem = $this->properties->next()) {
133:             $oItem->setProperty($oPropertyItem->get("type"), $oPropertyItem->get("name"), $oPropertyItem->get("value"), $client);
134:         }
135: 
136:         $oItem->store();
137: 
138:         return $oItem;
139:     }
140: }
141: 
142: /**
143:  * Single Newsletter Item
144:  */
145: class Newsletter extends Item
146: {
147:     /**
148:      * @var string Error storage
149:      * @access private
150:      */
151:     protected $_sError;
152: 
153:     /**
154:      * Constructor Function
155:      * @param  mixed  $mId  Specifies the ID of item to load
156:      */
157:     public function __construct($mId = false)
158:     {
159:         global $cfg;
160:         parent::__construct($cfg["tab"]["news"], "idnews");
161:         $this->_sError = "";
162:         if ($mId !== false) {
163:             $this->loadByPrimaryKey($mId);
164:         }
165:     }
166: 
167:     /**
168:      * Overriden store()-Method to set modified and modifiedby data and
169:      * to ensure, that there is only one welcome newsletter
170:      */
171:     public function store()
172:     {
173:         global $client, $lang, $auth;
174: 
175:         $client = cSecurity::toInteger($client);
176:         $lang     = cSecurity::toInteger($lang);
177: 
178:         $this->set("modified", date('Y-m-d H:i:s'), false);
179:         $this->set("modifiedby", $auth->auth["uid"]);
180: 
181:         if ($this->get("welcome") == 1) {
182:             $oItems = new NewsletterCollection();
183:             $oItems->setWhere("idclient", $client);
184:             $oItems->setWhere("idlang", $lang);
185:             $oItems->setWhere("welcome", 1);
186:             $oItems->setWhere("idnews", $this->get("idnews"), "<>");
187:             $oItems->query();
188: 
189:             while ($oItem = $oItems->next()) {
190:                 $oItem->set("welcome", 0);
191:                 $oItem->store();
192:             }
193:             unset($oItem);
194:             unset($oItems);
195:         }
196: 
197:         return parent::store();
198:     }
199: 
200:     /**
201:      * Replaces newsletter tag (e.g. MAIL_NAME) with data.
202:      * If code is just text using str_replace; if it is HTML by using regular expressions
203:      * @param string    sCode    Code, where the tags will be replaced (by reference)
204:      * @param bool        bIsHTML    Is code HTML?
205:      * @param string    sField    Field name, without MAIL_ (e.g. just "name")
206:      * @param string    sData    Data
207:      * @access private
208:      */
209:     public function _replaceTag(&$sCode, $bIsHTML, $sField, $sData)
210:     {
211:         if ($sCode && !$bIsHTML) {
212:             $sCode = str_replace("MAIL_".strtoupper($sField), $sData, $sCode);
213:         } else if ($sCode) {
214:             // Extract certain tag
215:             $sRegExp   = '/\[mail\s*([^]]+)\s*name=(?:"|&quot;)'.$sField.'(?:"|&quot;)\s*(.*?)\s*\]((?:.|\s)+?)\[\/mail\]/i';
216:             $aMatch    = array();
217:             $iMatches  = preg_match($sRegExp, $sCode, $aMatch) ;
218: 
219:             if ($iMatches > 0) {
220:                 // $aMatch contains parameter info from left [1] or right [2] to name="field"
221:                 $sParameter = $aMatch[1] . $aMatch[2];
222:                 $sMessage   = $aMatch[3];
223:                 $sRegExp    = '/\s*(.*?)\s*=\s*(?:"|&quot;)(.*?)(?:"|&quot;)\s*/i';
224:                 $aMatch     = array();
225: 
226:                 if (preg_match_all($sRegExp, $sParameter, $aMatch) > 0) {
227:                     // Store parameter data as assoziative array
228:                     $aParameter = array_combine($aMatch[1], $aMatch[2]);
229:                     unset($aMatch); // $aMatch not needed anymore
230: 
231:                     if (!array_key_exists("type", $aParameter)) {
232:                         $aParameter["type"] = "text";
233:                     }
234: 
235:                     switch ($aParameter["type"]) {
236:                         case "link":
237:                             # TODO: Works everything fine?
238:                             # The current code makes it possible to do something like
239:                             # [mail ...]Some text here, then the link: [MAIL_STOP] and more text[/mail]
240:                             #
241:                             # If the other lines will be used, you don't need to
242:                             # set [MAIL_xy] and the message between the [mail]-tags will
243:                             # be used as link text (instead of using the tag parameter "text")
244: 
245:                             $sText = $aParameter["text"];
246: 
247:                             if ($sText == "") {
248:                                 $sText = $sData;
249:                             }
250:                             if ($sMessage == "") {
251:                                 $sMessage = $sData;
252:                             }
253: 
254:                             // Remove not needed parameters from the parameters list
255:                             // everything else goes into the link as parameters
256:                             unset($aParameter["type"]);
257:                             unset($aParameter["text"]);
258: 
259:                             $sParameter = "";
260:                             if (count($aParameter) > 0) {
261:                                 foreach ($aParameter as $sKey => $sValue) {
262:                                     $sParameter .= ' '.$sKey . '="' . $sValue . '"';
263:                                 }
264:                             }
265:                             $sMessage    = str_replace("MAIL_".strtoupper($sField), '<a href="'.conHtmlentities($sData).'"'.$sParameter.'>'.$sText.'</a>', $sMessage);
266:                             #$sMessage    = '<a href="'.conHtmlentities($sData).'"'.$sParameter.'>'.$sMessage.'</a>';
267:                             break;
268:                         default:
269:                             $sMessage    = str_replace("MAIL_".strtoupper($sField), $sData, $sMessage);
270:                             #$sMessage    = $sData;
271:                     }
272: 
273:                     $sRegExp = '/\[mail[^]]+name=(?:"|&quot;)'.$sField.'(?:"|&quot;).*?\].*?\[\/mail\]/is';
274:                     $sCode   = preg_replace($sRegExp, $sMessage, $sCode, -1);
275:                     // Just to replace "text"-tags in HTML message also, just in case...
276:                     $sCode   = str_replace("MAIL_".strtoupper($sField), $sData, $sCode);
277:                 }
278:             }
279:         }
280:     }
281: 
282:     /* TODO: HerrB: Remove or insert some functionality */
283:     protected function _getNewsletterTagData($sHTML, $sTag)
284:     {
285:         //$sRegExp = "/<newsletter[^>](.*?)>.*?<\/newsletter>/i";
286:         //$sRegExp = "/\[mail[^\]](.*?)>.*?\[\/mail\]/i";
287:         #\[mail[^\]]((name="(?P<name>.*?)")|(type="(?P<type>.*?)"))\](?P<content>.*?)\[\/mail\]
288:         #\[mail[^\]]((name=(?P<name>[^"]*.*?[^"]*))|(type="(?P<type>.*?)"))\](?P<content>.*?)\[\/mail\]
289: 
290:         /* RegExp explanation:
291:          * Match the character "[" literally �\[�
292:          * Match the characters "mail" literally �mail�
293:          * Match "whitespace characters" (spaces, tabs, line breaks, etc.) after "mail" �\s*�
294:          * Match the regular expression below and capture its match into backreference number 1 �([^]]+)�
295:          * Match any character that is not a "]" �[^]]+�
296:          *       Between one and unlimited times, as many times as possible, giving back as needed (greedy) �+�
297:          * Match the character "]" literally �\]�
298:          * Match the regular expression below and capture its match into backreference number 2 �((?:.|\s)+?)�
299:          *    Match the regular expression below �(?:.|\s)+?�
300:          *       Between one and unlimited times, as few times as possible, expanding as needed (lazy) �+?�
301:          *       Match either the regular expression below (attempting the next alternative only if this one fails) �.�
302:          *          Match any single character that is not a line break character �.�
303:          *       Or match regular expression number 2 below (the entire group fails if this one fails to match) �\s�
304:          *          Match a single character that is a "whitespace character" (spaces, tabs, line breaks, etc.) �\s�
305:          * Match the character "[" literally �\[�
306:          * Match the characters "/mail" literally �/mail�
307:          * Match the character "]" literally �\]�
308:          * Ignore case (i), . includes new lines (s)
309:          **/
310: 
311:         /*
312:         $sRegExp = '/\[mail\s*([^]]+)\]((?:.|\s)+?)\[\/mail\]/is';
313:         $aMatch = array();
314:         preg_match_all($sRegExp, $sHTML, $aMatch, PREG_SET_ORDER);
315:         print_r ($aMatch);
316: 
317:         // Auf bestimmten Typ matchen
318:         $sRegExp = '/\[mail.*?name="name".*?\]((?:.|\s)+?)\[\/mail\]/is';
319:         $aMatch = array();
320:         preg_match_all($sRegExp, $sHTML, $aMatch, PREG_SET_ORDER);
321:         print_r ($aMatch); */
322: 
323:         // Parameter auseinandernehmen (ohne PREG_SET_ORDER)
324:         #$sRegExp = '/\s*(.*?)\s*=\s*"(.*?)"\s*/i';
325:         #$aMatch = array();
326:         #preg_match_all($sRegExp, $sHTML, $aMatch);
327:         #print_r ($aMatch);
328:     }
329: 
330:     protected function _deChunkHTTPBody($sHeader, $sBody, $sEOL = "\r\n")
331:     {
332:         // Based on code from jbr at ya-right dot com, posted on http://www.php.net
333:         // as user comment on fsockopen documentation (2007-05-01)
334: 
335:         // Analyze header
336:         $aParts = preg_split("/\r?\n/", $sHeader, -1, PREG_SPLIT_NO_EMPTY);
337: 
338:         $aHeader = array();
339:         for ($i = 0;$i < sizeof ($aParts); $i++) {
340:             if ($i != 0) {
341:                 $iPos       = strpos($aParts[$i], ':');
342:                 $sParameter = strtolower (str_replace(' ', '', substr ($aParts[$i], 0, $iPos)));
343:                 $sValue     = trim(substr($aParts[$i], ($iPos + 1)));
344:             } else {
345:                 $sField      = 'status';
346:                 $aParameters = explode(' ', $aParts[$i]);
347:                 $sParameter  = $aParameters[1];
348:             }
349: 
350:             if ($sParameter == 'set-cookie') {
351:                 $aHeader['cookies'][] = $sValue;
352:             } else if ($sParameter == 'content-type') {
353:                 if (($iPos = strpos($sValue, ';')) !== false) {
354:                     $aHeader[$sParameter] = substr($sValue, 0, $iPos);
355:                 } else {
356:                     $aHeader[$sParameter] = $sValue;
357:                 }
358:             } else {
359:                 $aHeader[$sParameter] = $sValue;
360:             }
361:         }
362: 
363:         // Get dechunked and decompressed body
364:         $iEOLLen = strlen($sEOL);
365: 
366:         $sBuffer = '';
367:         if (isset($aHeader['transfer-encoding']) && $aHeader['transfer-encoding'] == 'chunked') {
368:             do {
369:                 $sBody    = ltrim ($sBody);
370:                 $iPos     = strpos($sBody, $sEOL);
371:                 $iDataLen = hexdec (substr($sBody, 0, $iPos));
372: 
373:                 if (isset($aHeader['content-encoding'])) {
374:                     $sBuffer .= gzinflate(substr($sBody, ($iPos + $iEOLLen + 10), $iDataLen));
375:                 } else {
376:                     $sBuffer .= substr($sBody, ($iPos + $iEOLLen), $iDataLen);
377:                 }
378: 
379:                 $sBody      = substr ($sBody, ($iPos + $iDataLen + $iEOLLen));
380:                 $sRemaining = trim ($sBody);
381: 
382:             } while (!empty($sRemaining));
383:         } else if (isset($aHeader['content-encoding'])) {
384:             $sBuffer = gzinflate(substr($sBody, 10));
385:         } else {
386:             $sBuffer = $sBody; // Not chunked, not compressed
387:         }
388: 
389:         return $sBuffer;
390:     }
391: 
392:     /**
393:      * If newsletter is HTML newsletter and necessary data available
394:      * returns final HTML message
395:      * @return string HTML message
396:      */
397:     public function getHTMLMessage()
398:     {
399:         global $lang, $client, $contenido;
400:         $frontendURL = cRegistry::getFrontendUrl();
401: 
402:         if ($this->get("type") == "html" && $this->get("idart") > 0 && $this->htmlArticleExists()) {
403: 
404:             // Article ID
405:             $iIDArt = $this->get("idart");
406: 
407:             // Category ID
408:             $oClientLang = new cApiClientLanguage(false, $client, $lang);
409:             $iIDCat      = $oClientLang->getProperty("newsletter", "html_newsletter_idcat");
410:             unset($oClientLang);
411: 
412:             // Get http username and password, if frontend is protected
413:             $oClient = new cApiClient($client);
414:             $sHTTPUserName = $oClient->getProperty("newsletter", "html_username");
415:             $sHTTPPassword = $oClient->getProperty("newsletter", "html_password");
416:             unset($oClient);
417: 
418:             // Get HTML
419:             if ($iIDArt > 0 && $iIDCat > 0) {
420:                 // Check, if newsletter is online and set temporarely online, otherwise
421:                 $bSetOffline = false;
422:                 $oArticles = new cApiArticleLanguageCollection;
423:                 $oArticles->setWhere("idlang", $this->get("idlang"));
424:                 $oArticles->setWhere("idart", $this->get("idart"));
425:                 $oArticles->query();
426: 
427:                 if ($oArticle = $oArticles->next()) {
428:                     if ($oArticle->get("online") == 0) {
429:                         $bSetOffline = true;
430:                         $oArticle->set("online", 1);
431:                         $oArticle->store();
432:                     }
433:                     unset($oArticle);
434:                 }
435:                 unset($oArticles);
436: 
437:                 $sFile = "front_content.php?client=$client&lang=$lang&idcat=$iIDCat&idart=$iIDArt&noex=1&send=1";
438:                 $aURL  = parse_url($frontendURL);
439: 
440:                 // TODO: Other schemes than http should be tested before use!
441:                 if ($aURL["scheme"] == "https") {
442:                     $iPort   = 443;
443:                     $sTarget = "ssl://".$aURL["host"];
444:                 } else {
445:                     $iPort   = 80;
446:                     $sTarget = $aURL["host"];
447:                 }
448:                 if ($aURL["port"]) {
449:                     $iPort   = $aURL["port"];
450:                 }
451: 
452:                 $iErrorNo    = 0;
453:                 $sErrorMsg   = "";
454:                 if ($iHandler = fsockopen($sTarget, $iPort, $iErrorNo, $sErrorMsg, 30)) {
455:                     // If you use HTTP 1.1 you may get chunked data... you could solve
456:                     // this easily by using HTTP 1.0, but then you get a problem with
457:                     // virtual servers, as HTTP 1.0 doesn't use the host information...
458:                     fputs($iHandler, "GET ".$aURL["path"].$sFile." HTTP/1.1\r\n");
459:                     fputs($iHandler, "Host: ".$aURL["host"]."\r\n");
460: 
461:                     // Maybe the website has been protected using .htaccess, then login
462:                     if ($sHTTPUserName != "" && $sHTTPPassword != "") {
463:                         fputs($iHandler, "Authorization: Basic " . base64_encode("$sHTTPUserName:$sHTTPPassword") . "\r\n");
464:                     }
465: 
466:                     fputs($iHandler, "Referer: http://".$aURL["host"]."\r\n");
467:                     fputs($iHandler, "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)\r\n");
468:                     fputs($iHandler, "Connection: close\r\n\r\n");
469: 
470:                     // Get the HTTP header and body separately
471:                     $sHTML   = "";
472:                     $sHeader = "";
473:                     $bBody   = false;
474:                     while (!feof($iHandler)) {
475:                         // $sLine = fgets($iHandler, 4096);
476:                         $sLine = fgets($iHandler, 1024);
477:                         if ($bBody) {
478:                             $sHTML .= $sLine;
479:                         } else if ($sLine == "\r\n") {
480:                             $bBody = true;
481:                         } else {
482:                             $sHeader .= $sLine;
483:                         }
484:                     }
485:                     fclose ($iHandler);
486: 
487:                     $sHTML = $this->_deChunkHTTPBody($sHeader, $sHTML);
488: 
489:                     // If someone likes to use anchors in html newsletters (*sigh*)
490:                     // the base href tag has to be removed - that means, we have to fix
491:                     // all source paths manually...
492:                     if (getEffectiveSetting('newsletter', 'remove_base_tag', "false") == "true") {
493:                         // Remove base tag
494:                         $sHTML = preg_replace('/<base href=(.*?)>/is', '', $sHTML, 1);
495: 
496:                         // Fix source path
497:                         // TODO: Test any URL specification that may exist under the sun...
498:                         $sHTML = preg_replace('/[sS[rR][cC][ ]*=[ ]*"([^h][^t][^t][^p][^:].*)"/', 'rc="'.$frontendURL.'$1"', $sHTML);
499:                         $sHTML = preg_replace('/[hH][rR][eE][fF][ ]*=[ ]*"([^h][^t][^t][^p][^:][A-Za-z0-9#\.?\-=_&]*)"/', 'href="'.$frontendURL.'$1"', $sHTML);
500:                         $sHTML = preg_replace('/url\((.*)\)/', 'url('. $frontendURL.'$1)', $sHTML);
501: 
502:                         // Now replace anchor tags to the newsletter article itself just by the anchor
503:                         $sHTML = str_replace($frontendURL . "front_content.php?idart=".$iIDArt."#", "#", $sHTML);
504:                     }
505: 
506:                     $sReturn = $sHTML;
507:                 } else {
508:                     if ($contenido) { // Use i18n only in backend
509:                         $sErrorText = i18n("There was a problem getting the newsletter article using http. Error: %s (%s)");
510:                     } else {
511:                         $sErrorText = "There was a problem getting the newsletter article using http. Error: %s (%s)";
512:                     }
513: 
514:                     $this->_sError = sprintf($sErrorText, $sErrorMsg, $iErrorNo);
515:                     $sReturn = false;
516:                 }
517: 
518:                 // Set previously offline article back to offline
519:                 if ($bSetOffline) {
520:                     $oArticles = new cApiArticleLanguageCollection();
521:                     $oArticles->setWhere("idlang", $this->get("idlang"));
522:                     $oArticles->setWhere("idart", $this->get("idart"));
523:                     $oArticles->query();
524: 
525:                     if ($oArticle = $oArticles->next()) {
526:                         $oArticle->set("online", 0);
527:                         $oArticle->store();
528:                     }
529:                     unset($oArticle);
530:                     unset($oArticles);
531:                 }
532: 
533:                 return $sReturn;
534:             } else {
535:                 return false;
536:             }
537:         } else {
538:             return false;
539:         }
540:     }
541: 
542:     /**
543:      * Checks, if html newsletter article still exists
544:      * @return bool
545:      */
546:     public function htmlArticleExists()
547:     {
548:         if ($this->get("idart") > 0) {
549:             $oArticles = new cApiArticleLanguageCollection();
550:             $oArticles->setWhere("idlang", $this->get("idlang"));
551:             $oArticles->setWhere("idart", $this->get("idart"));
552:             $oArticles->query();
553: 
554:             if ($oArticles->count() > 0) {
555:                 $bReturn = true;
556:             } else {
557:                 $bReturn = false;
558:             }
559: 
560:             unset($oArticles);
561:         } else {
562:             $bReturn = false;
563:         }
564: 
565:         return $bReturn;
566:     }
567: 
568:     /**
569:      * Sends test newsletter directly to specified email address
570:      * @param integer  $iIDCatArt        idcatart of newsletter handler article
571:      * @param string   $sEMail           Recipient email address
572:      * @param string   $sName            Optional: Recipient name
573:      * @param bool     $bSimulatePlugin  If recipient plugin activated, include plugins
574:      *                                   and simulate values from plugins
575:      * @param string   $sEncoding        Message (and header) encoding, e.g. iso-8859-1
576:      */
577:     public function sendEMail($iIDCatArt, $sEMail, $sName = "", $bSimulatePlugins = true, $sEncoding = "iso-8859-1")
578:     {
579:         global $lang, $client, $cfg, $cfgClient, $contenido;
580: 
581:         // Initialization
582:         if ($sName == "") {
583:             $sName = $sEMail;
584:         }
585: 
586:         $oLanguage = new cApiLanguage($lang);
587:         $sFormatDate = $oLanguage->getProperty("dateformat", "date");
588:         $sFormatTime = $oLanguage->getProperty("dateformat", "time");
589:         unset($oLanguage);
590: 
591:         if ($sFormatDate == "") {
592:             $sFormatDate = "%d.%m.%Y";
593:         }
594:         if ($sFormatTime == "") {
595:             $sFormatTime = "%H:%M";
596:         }
597: 
598:         // Get newsletter data
599:         $sFrom            = $this->get("newsfrom");
600:         $sFromName        = $this->get("newsfromname");
601:         if ($sFromName == "") {
602:             $sFromName    = $sFrom;
603:         }
604:         $sSubject        = $this->get("subject");
605:         $sMessageText    = $this->get("message");
606: 
607:         $bIsHTML        = false;
608:         if ($this->get("type") == "html") {
609:             $sMessageHTML    = $this->getHTMLMessage();
610: 
611:             if ($sMessageHTML === false) {
612:                 // There was a problem getting the html message (maybe article
613:                 // deleted). Exit with error instead of sending as text message only
614: 
615:                 if ($contenido) { // Use i18n only in backend
616:                     $sError = i18n("Newsletter to %s could not be sent: No html message available");
617:                 } else {
618:                     $sError = "Newsletter to %s could not be sent: No html message available";
619:                 }
620:                 $this->_sError = $sName." (".$sEMail."): ".sprintf($sError, $sEMail);
621:                 return false;
622:             } else {
623:                 $bIsHTML = true;
624:             }
625:         }
626: 
627:         // Preventing double lines in mail, you may wish to disable this function on windows servers
628:         if (!getSystemProperty("newsletter", "disable-rn-replacement")) {
629:             $sMessageText = str_replace("\r\n", "\n", $sMessageText);
630:         }
631: 
632:         // Simulate key, an alphanumeric string of 30 characters
633:         $sKey    = str_repeat("key", 10);
634:         $sPath    = cRegistry::getFrontendUrl() . "front_content.php?changelang=".$lang."&idcatart=".$iIDCatArt."&";
635: 
636:         // Replace message tags (text message)
637:         $this->_replaceTag($sMessageText, false, "name", $sName);
638:         $this->_replaceTag($sMessageText, false, "number", 1);
639:         $this->_replaceTag($sMessageText, false, "date", strftime($sFormatDate));
640:         $this->_replaceTag($sMessageText, false, "time", strftime($sFormatTime));
641:         $this->_replaceTag($sMessageText, false, "unsubscribe", $sPath."unsubscribe=".$sKey);
642:         $this->_replaceTag($sMessageText, false, "change", $sPath."change=".$sKey);
643:         $this->_replaceTag($sMessageText, false, "stop", $sPath."stop=".$sKey);
644:         $this->_replaceTag($sMessageText, false, "goon", $sPath."goon=".$sKey);
645: 
646:         // Replace message tags (html message)
647:         if ($bIsHTML) {
648:             $this->_replaceTag($sMessageHTML, true, "name", $sName);
649:             $this->_replaceTag($sMessageHTML, true, "number", 1);
650:             $this->_replaceTag($sMessageHTML, true, "date", strftime($sFormatDate));
651:             $this->_replaceTag($sMessageHTML, true, "time", strftime($sFormatTime));
652:             $this->_replaceTag($sMessageHTML, true, "unsubscribe", $sPath."unsubscribe=".$sKey);
653:             $this->_replaceTag($sMessageHTML, true, "change", $sPath."change=".$sKey);
654:             $this->_replaceTag($sMessageHTML, true, "stop", $sPath."stop=".$sKey);
655:             $this->_replaceTag($sMessageHTML, true, "goon", $sPath."goon=".$sKey);
656:         }
657: 
658:         if ($bSimulatePlugins) {
659:             // Enabling plugin interface
660:             if (getSystemProperty("newsletter", "newsletter-recipients-plugin") == "true") {
661:                 if (is_array($cfg['plugins']['recipients'])) {
662:                     foreach ($cfg['plugins']['recipients'] as $sPlugin) {
663:                         plugin_include("recipients", $sPlugin."/".$sPlugin.".php");
664:                         if (function_exists("recipients_".$sPlugin."_wantedVariables")) {
665:                             $aPluginVars = array();
666:                             $aPluginVars = call_user_func("recipients_".$sPlugin."_wantedVariables");
667: 
668:                             foreach ($aPluginVars as $sPluginVar) {
669:                                 // Replace tags in text message
670:                                 $this->_replaceTag($sMessageText, false, $sPluginVar, ":: ".$sPlugin.": ".$sPluginVar." ::");
671:                                 // Replace tags in html message
672:                                 if ($bIsHTML) {
673:                                     $this->_replaceTag($sMessageHTML, true,     $sPluginVar, ":: ".$sPlugin.": ".$sPluginVar." ::");
674:                                 }
675:                             }
676:                         }
677:                     }
678:                 }
679:             } else {
680:                 setSystemProperty("newsletter", "newsletter-recipients-plugin", "false");
681:             }
682:         }
683: 
684:         if (!isValidMail($sEMail) || strtolower($sEMail) == "sysadmin@ihresite.de") {
685:             // No valid destination mail address specified
686:             if ($contenido) { // Use i18n only in backend
687:                 $sError = i18n("Newsletter to %s could not be sent: No valid e-mail address");
688:             } else {
689:                 $sError = "Newsletter to %s could not be sent: No valid e-mail address";
690:             }
691:             $this->_sError = $sName." (".$sEMail."): ".sprintf($sError, $sEMail);
692:             return false;
693:         } else {
694:             if ($bIsHTML) {
695:                 $body = $sMessageHTML;
696:             } else {
697:                 $body = $sMessageText."\n\n";
698:             }
699:             if ($bIsHTML) {
700:                 $contentType = 'text/html';
701:             } else {
702:                 $contentType = 'text/plain';
703:             }
704: 
705:             $mailer = new cMailer();
706:             $message = Swift_Message::newInstance($sSubject, $body, $contentType, $sEncoding);
707:             $message->setFrom($sFrom, $sFromName);
708:             $message->setTo($sEMail);
709:             $result = $mailer->send($message);
710: 
711:             if (!$result) {
712:                 if ($contenido) { // Use i18n only in backend
713:                     $sError = i18n("Newsletter to %s could not be sent");
714:                 } else {
715:                     $sError = "Newsletter to %s could not be sent";
716:                 }
717:                 $this->_sError = $sName." (".$sEMail."): ".sprintf($sError, $sEMail);
718:                 return false;
719:             } else {
720:                 return true;
721:             }
722:         }
723:     }
724: 
725:     /**
726:      * Sends test newsletter directly to specified recipients (single or group)
727:      *
728:      * Note: Sending in chunks not supported! Only usable for tests and only a few
729:      * recipients.
730:      *
731:      * @param integer  $iIDCatArt     idcatart of newsletter handler article
732:      * @param integer  $iIDNewsRcp    If specified, newsletter recipient id, ignored, if group specified
733:      * @param integer  $iIDNewsGroup  If specified, newsletter recipient group id
734:      * @param array    $aSendRcps     As reference: Filled with a list of succesfull recipients
735:      * @param string   $sEncoding     Message (and header) encoding, e.g. iso-8859-1
736:      */
737:     public function sendDirect($iIDCatArt, $iIDNewsRcp = false, $iIDNewsGroup = false, &$aSendRcps, $sEncoding = "iso-8859-1")
738:     {
739:         global $lang, $client, $cfg, $cfgClient, $contenido, $recipient;
740: 
741:         // Initialization
742:         $aMessages  = array();
743: 
744:         $oLanguage = new cApiLanguage($lang);
745:         unset($oLanguage);
746: 
747:         if ($sFormatDate == "") {
748:             $sFormatDate = "%d.%m.%Y";
749:         }
750:         if ($sFormatTime == "") {
751:             $sFormatTime = "%H:%M";
752:         }
753: 
754:         $sPath = cRegistry::getFrontendUrl() . "front_content.php?changelang=".$lang."&idcatart=".$iIDCatArt."&";
755: 
756:         // Get newsletter data
757:         $sFrom     = $this->get("newsfrom");
758:         $sFromName = $this->get("newsfromname");
759:         if ($sFromName == "") {
760:             $sFromName = $sFrom;
761:         }
762:         $sSubject     = $this->get("subject");
763:         $sMessageText = $this->get("message");
764: 
765:         $bIsHTML      = false;
766:         if ($this->get("type") == "html") {
767:             $sMessageHTML    = $this->getHTMLMessage();
768: 
769:             if ($sMessageHTML === false) {
770:                 // There was a problem getting the html message (maybe article
771:                 // deleted). Exit with error instead of sending as text message only
772: 
773:                 if ($contenido) { // Use i18n only in backend
774:                     $sError = i18n("Newsletter could not be sent: No html message available");
775:                 } else {
776:                     $sError = "Newsletter could not be sent: No html message available";
777:                 }
778:                 $this->_sError = $sError;
779:                 return false;
780:             } else {
781:                 $bIsHTML = true;
782:             }
783:         }
784: 
785:         // Preventing double lines in mail, you may wish to disable this function on windows servers
786:         if (!getSystemProperty("newsletter", "disable-rn-replacement")) {
787:             $sMessageText = str_replace("\r\n", "\n", $sMessageText);
788:         }
789: 
790:         // Single replacements
791:         // Replace message tags (text message)
792:         $this->_replaceTag($sMessageText, false, "date", strftime($sFormatDate));
793:         $this->_replaceTag($sMessageText, false, "time", strftime($sFormatTime));
794: 
795:         // Replace message tags (html message)
796:         if ($bIsHTML) {
797:             $this->_replaceTag($sMessageHTML, true, "date", strftime($sFormatDate));
798:             $this->_replaceTag($sMessageHTML, true, "time", strftime($sFormatTime));
799:         }
800: 
801:         // Enabling plugin interface
802:         if (getSystemProperty("newsletter", "newsletter-recipients-plugin") == "true") {
803:             $bPluginEnabled = true;
804:             $aPlugins       = array();
805: 
806:             if (is_array($cfg['plugins']['recipients'])) {
807:                 foreach ($cfg['plugins']['recipients'] as $sPlugin) {
808:                     plugin_include("recipients", $sPlugin."/".$sPlugin.".php");
809:                     if (function_exists("recipients_".$sPlugin."_wantedVariables")) {
810:                         $aPlugins[$sPlugin] = call_user_func("recipients_".$sPlugin."_wantedVariables");
811:                     }
812:                 }
813:             }
814:         } else {
815:             setSystemProperty("newsletter", "newsletter-recipients-plugin", "false");
816:             $bPluginEnabled = false;
817:         }
818: 
819:         $aRecipients = array();
820:         if ($iIDNewsGroup !== false) {
821:             $oGroupMembers = new RecipientGroupMemberCollection;
822:             $aRecipients = $oGroupMembers->getRecipientsInGroup ($iIDNewsGroup, false);
823:         } else if ($iIDNewsRcp !== false) {
824:             $aRecipients[] = $iIDNewsRcp;
825:         }
826: 
827:         $iCount = count($aRecipients);
828:         if ($iCount > 0) {
829:             $this->_replaceTag($sMessageText, false, "number", $iCount);
830: 
831:             // Replace message tags (html message)
832:             if ($bIsHTML) {
833:                 $this->_replaceTag($sMessageHTML, true,     "number", $iCount);
834:             }
835: 
836:             foreach ($aRecipients as $iID) {
837:                 $sRcpMsgText = $sMessageText;
838:                 $sRcpMsgHTML = $sMessageHTML;
839: 
840:                 // Don't change name of $recipient variable as it is used in plugins!
841:                 $recipient   = new Recipient;
842:                 $recipient->loadByPrimaryKey($iID);
843: 
844:                 $sEMail  = $recipient->get("email");
845:                 $sName   = $recipient->get("name");
846:                 if (empty ($sName)) {
847:                     $sName = $sEMail;
848:                 }
849:                 $sKey    = $recipient->get("hash");
850: 
851:                 $bSendHTML = false;
852:                 if ($recipient->get("news_type") == 1) {
853:                     $bSendHTML = true; // Recipient accepts html newsletter
854:                 }
855: 
856:                 $this->_replaceTag($sRcpMsgText, false, "name", $sName);
857:                 $this->_replaceTag($sRcpMsgText, false, "unsubscribe", $sPath."unsubscribe=".$sKey);
858:                 $this->_replaceTag($sRcpMsgText, false, "change", $sPath."change=".$sKey);
859:                 $this->_replaceTag($sRcpMsgText, false, "stop", $sPath."stop=".$sKey);
860:                 $this->_replaceTag($sRcpMsgText, false, "goon", $sPath."goon=".$sKey);
861: 
862:                 // Replace message tags (html message)
863:                 if ($bIsHTML && $bSendHTML) {
864:                     $this->_replaceTag($sRcpMsgHTML, true, "name", $sName);
865:                     $this->_replaceTag($sRcpMsgHTML, true, "unsubscribe", $sPath."unsubscribe=".$sKey);
866:                     $this->_replaceTag($sRcpMsgHTML, true, "change", $sPath."change=".$sKey);
867:                     $this->_replaceTag($sRcpMsgHTML, true, "stop", $sPath."stop=".$sKey);
868:                     $this->_replaceTag($sRcpMsgHTML, true, "goon", $sPath."goon=".$sKey);
869:                 }
870: 
871:                 if ($bPluginEnabled) {
872:                     foreach ($aPlugins as $sPlugin => $aPluginVar) {
873:                         foreach ($aPluginVar as $sPluginVar) {
874:                             // Replace tags in text message
875:                             $this->_replaceTag($sRcpMsgText, false, $sPluginVar, call_user_func("recipients_".$sPlugin."_getvalue", $sPluginVar));
876:                             // Replace tags in html message
877:                             if ($bIsHTML && $bSendHTML) {
878:                                 $this->_replaceTag($sRcpMsgHTML, true, $sPluginVar, call_user_func("recipients_".$sPlugin."_getvalue", $sPluginVar));
879:                             }
880:                         }
881:                     }
882:                 }
883: 
884:                 if (strlen($sKey) != 30) { // Prevents sending without having a key
885:                     if ($contenido) { // Use i18n only in backend
886:                         $sError = i18n("Newsletter to %s could not be sent: Recipient has an incompatible or empty key");
887:                     } else {
888:                         $sError = "Newsletter to %s could not be sent: Recipient has an incompatible or empty key";
889:                     }
890:                     $aMessages[] = $sName." (".$sEMail."): ".sprintf($sError, $sEMail);
891:                 } else if (!isValidMail($sEMail)) {
892:                     if ($contenido) { // Use i18n only in backend
893:                         $sError = i18n("Newsletter to %s could not be sent: No valid e-mail address specified");
894:                     } else {
895:                         $sError = "Newsletter to %s could not be sent: No valid e-mail address specified";
896:                     }
897:                     $aMessages[] = $sName." (".$sEMail."): ".sprintf($sError, $sEMail);
898:                 } else {
899:                     if ($bIsHTML && $bSendHTML) {
900:                         $body = $sRcpMsgHTML;
901:                     } else {
902:                         $body = $sRcpMsgText."\n\n";
903:                     }
904: 
905:                     if ($bIsHTML && $bSendHTML) {
906:                         $contentType = 'text/html';
907:                     } else {
908:                         $contentType = 'text/plain';
909:                     }
910: 
911:                     $mailer = new cMailer();
912:                     $message = Swift_Message::newInstance($sSubject, $body, $contentType, $sEncoding);
913:                     $message->setFrom($sFrom, $sFromName);
914:                     $message->setTo($sEMail);
915:                     $result = $mailer->send($message);
916: 
917:                     if ($result) {
918:                         $aSendRcps[] = $sName." (".$sEMail.")";
919:                     } else {
920:                         if ($contenido) { // Use i18n only in backend
921:                             $sError = i18n("Newsletter to %s could not be sent");
922:                         } else {
923:                             $sError = "Newsletter to %s could not be sent";
924:                         }
925:                         $aMessages[] = $sName." (".$sEMail."): ".sprintf($sError, $sEMail);
926:                     }
927:                 }
928:             }
929:         } else {
930:             if ($contenido) { // Use i18n only in backend
931:                 $sError = i18n("No recipient with specified recipient/group id %s/%s found");
932:             } else {
933:                 $sError = "No recipient with specified recpient/group id %s/%s found";
934:             }
935:             $aMessages[] = sprintf($sError, $iIDNewsRcp, $iIDNewsGroup);
936:         }
937: 
938:         if (count($aMessages) > 0) {
939:             $this->_sError = implode("<br>", $aMessages);
940:             return false;
941:         } else {
942:             return true;
943:         }
944:     }
945: }
946: 
CMS CONTENIDO 4.9.0 API documentation generated by ApiGen 2.8.0