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