Overview

Packages

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