/**
 * Prepare and run debugbar on code output
 *
 * @param string $code to prepare
 * @return string $code
 */
function run_debugbar($code)
{
    // build data for general stuff
    $generalData = array('idart' => cRegistry::getArticleId(), 'idlang' => cRegistry::getLanguageId(), 'idcat' => cRegistry::getCategoryId(), 'idartlang' => cRegistry::getArticleLanguageId(), 'auth' => cRegistry::getAuth(), 'idclient' => cRegistry::getClientId(), 'frontendpath' => cRegistry::getFrontendPath(), 'frontendurl' => cRegistry::getFrontendUrl(), 'session' => cRegistry::getSession());
    // build collectors data
    $configCollector = new ConfigCollector(cRegistry::getConfig());
    $clientConfigCollector = new ClientConfigCollector(cRegistry::getClientConfig());
    $generalCollector = new GeneralCollector($generalData);
    $debugbar = new ContenidoDebugBar();
    // add tabs to debugbar based on configuration
    if (getSystemProperty("dbg", "dbg_request") == 1) {
        $debugbar->addCollector(new RequestDataCollector());
    }
    if (getSystemProperty("dbg", "dbg_config") == 1) {
        $debugbar->addCollector($configCollector);
    }
    if (getSystemProperty("dbg", "dbg_clientconfig") == 1) {
        $debugbar->addCollector($clientConfigCollector);
    }
    if (getSystemProperty("dbg", "dbg_generalinfo") == 1) {
        $debugbar->addCollector($generalCollector);
    }
    if (getSystemProperty("dbg", "dbg_messages") == 1) {
        $debugbar->addCollector(new MessagesCollector());
        $oMessage = DebugbarMessage::getInstance();
        foreach ($oMessage->getMessages() as $message) {
            $debugbar["messages"]->addMessage($message);
        }
    }
    if (getSystemProperty("dbg", "dbg_exceptions") == 1) {
        $debugbar->addCollector(new ExceptionsCollector());
    }
    if (getSystemProperty("dbg", "dbg_dbqueries") == 1) {
        global $cfg;
        if ($cfg['db']["enableProfiling"] === true) {
            $dbQueryCollector = new DbQueryCollector(cRegistry::getDb()->getProfileData());
            $debugbar->addCollector($dbQueryCollector);
        }
    }
    // add default collectors
    $debugbar->addCollector(new MemoryCollector());
    $debugbar->addCollector(new TimeDataCollector());
    // add debugbar code to the page
    $debugbarRenderer = $debugbar->getJavascriptRenderer();
    $baseUrl = cRegistry::getBackendUrl() . 'plugins/debugbar/vendor/maximebf/debugbar/src/DebugBar/Resources';
    $debugbarRenderer->setBaseUrl($baseUrl);
    if (preg_match("#</head>#", $code)) {
        $code = preg_replace("#</head>#", $debugbarRenderer->renderHead() . "</head>", $code, 1);
    }
    if (preg_match("#</body>#", $code)) {
        $code = preg_replace("#</body>#", $debugbarRenderer->render() . "</body>", $code, 1);
    }
    return $code;
}
 public function runJob()
 {
     global $cfg, $cfgClient, $client, $recipient;
     $iCount = 0;
     if ($this->get("status") == 2) {
         // Job is currently running, check start time and restart if
         // started 5 minutes ago
         $dStart = strtotime($this->get("started"));
         $dNow = time();
         if ($dNow - $dStart > 5 * 60) {
             $this->set("status", 1);
             $this->set("started", "0000-00-00 00:00:00", false);
             $oLogs = new cNewsletterLogCollection();
             $oLogs->setWhere("idnewsjob", $this->get($this->primaryKey));
             $oLogs->setWhere("status", "sending");
             $oLogs->query();
             while ($oLog = $oLogs->next()) {
                 $oLog->set("status", "error (sending)");
                 $oLog->store();
             }
         }
     }
     if ($this->get("status") == 1) {
         // Job waiting for sending
         $this->set("status", 2);
         $this->set("started", date("Y-m-d H:i:s"), false);
         $this->store();
         // Initialization
         $aMessages = array();
         $oLanguage = new cApiLanguage($this->get("idlang"));
         $sFormatDate = $oLanguage->getProperty("dateformat", "date");
         $sFormatTime = $oLanguage->getProperty("dateformat", "time");
         unset($oLanguage);
         if ($sFormatDate == "") {
             $sFormatDate = 'Y-m-d';
         }
         if ($sFormatTime == "") {
             $sFormatTime = 'h:i a';
         }
         // Get newsletter data
         $sFrom = $this->get("newsfrom");
         $sFromName = $this->get("newsfromname");
         $sSubject = $this->get("subject");
         $sMessageText = $this->get("message_text");
         $sMessageHTML = $this->get("message_html");
         $dNewsDate = strtotime($this->get("newsdate"));
         $sEncoding = $this->get("encoding");
         $bIsHTML = false;
         if ($this->get("type") == "html" && $sMessageHTML != "") {
             $bIsHTML = true;
         }
         $bDispatch = false;
         if ($this->get("dispatch") == 1) {
             $bDispatch = true;
         }
         // Single replacements
         // Replace message tags (text message)
         $sMessageText = str_replace("MAIL_DATE", date($sFormatDate, $dNewsDate), $sMessageText);
         $sMessageText = str_replace("MAIL_TIME", date($sFormatTime, $dNewsDate), $sMessageText);
         $sMessageText = str_replace("MAIL_NUMBER", $this->get("rcpcount"), $sMessageText);
         // Replace message tags (html message)
         if ($bIsHTML) {
             $sMessageHTML = str_replace("MAIL_DATE", date($sFormatDate, $dNewsDate), $sMessageHTML);
             $sMessageHTML = str_replace("MAIL_TIME", date($sFormatTime, $dNewsDate), $sMessageHTML);
             $sMessageHTML = str_replace("MAIL_NUMBER", $this->get("rcpcount"), $sMessageHTML);
             # Link to online article -->
             if (!is_object($db)) {
                 $db = new DB_Contenido();
             }
             $sql = 'SELECT idart
                     FROM ' . $cfg['tab']['news'] . '
                     WHERE (idnews=' . $this->get('idnews') . ')';
             $db->query($sql);
             $db->next_record();
             $news_idart = $db->f('idart');
             $link = Contenido_Url::getInstance()->build(array('idart' => $news_idart, 'client' => $this->get('idclient'), 'lang' => $this->get("idlang"), 'nl' => $this->get('idnewsjob'), 'rcp' => '{RCP}'), true);
             $p1 = strpos($sMessageHTML, '<body');
             if ($p1 !== false) {
                 $p1 = strpos($sMessageHTML, '>', $p1) + 1;
             } else {
                 $p1 = 0;
             }
             $sOnlineText = getEffectiveSetting('newsletter-online-text', $this->get("idlang"), 'If the newsletter is not shown properly, please click here to view the online version.');
             $sMessageHTML = substr($sMessageHTML, 0, $p1) . '<div style="text-align: center; background-color: #FFF;"><a href="' . $link . '" style="font-weight: bold;">' . $sOnlineText . '</a></div>' . substr($sMessageHTML, $p1);
             # <-- Link to online article
             // Remove base tag
             $sMessageHTML = preg_replace('/<base href=(.*?)>/is', '', $sMessageHTML, 1);
             // Fix source path
             // TODO: Test any URL specification that may exist under the sun...
             $sMainURL = Contenido_Url::getInstance()->build(array('idcat' => getEffectiveSetting('navigation', 'idcat-home', 1), 'client' => $this->get('idclient'), 'lang' => $this->get("idlang")), true);
             $sSelfURL = Contenido_Url::getInstance()->build(array('idart' => $this->get("idart"), 'client' => $this->get('idclient'), 'lang' => $this->get("idlang")), true);
             $sMessageHTML = preg_replace("/(href|src)\\=(\"|\\')([^(http|#)])(\\/)?/", "\$1=" . "\$2" . $sMainURL . "\$3", $sMessageHTML);
             $sMessageHTML = preg_replace('/url\\([\\"\'](.*)[\\"\']\\)/', 'url(\'' . $sMainURL . '$1\')', $sMessageHTML);
             $sMessageHTML = str_replace('/cms//', '/', $sMessageHTML);
             // Now replace anchor tags to the newsletter article itself just by the anchor
             $sMessageHTML = preg_replace("/(href|src)\\=(\"|\\')" . str_replace('/', '\\/', $sSelfURL) . "(.*)#(.*)(\"|\\')/", "\$1=" . "\$2" . "#" . "\$4" . "\$5", $sMessageHTML);
             // Now correct mailto tags
             $sMessageHTML = str_replace($sMainURL . 'mailto:', 'mailto:', $sMessageHTML);
             # Remove the <noscript> info from the newsletter message
             $sMessageHTML = str_replace(array('This website is powered by drugCMS, the Content Management System with addictive potential.', 'For more info and download visit <a href="http://www.drugcms.org">www.drugcms.org</a>.', 'drugCMS is made in Germany.'), '', $sMessageHTML);
         }
         // Enabling plugin interface
         $bPluginEnabled = false;
         if (getSystemProperty("newsletter", "newsletter-recipients-plugin") == "true") {
             $bPluginEnabled = true;
             $aPlugins = array();
             if (is_array($cfg['plugins']['recipients'])) {
                 foreach ($cfg['plugins']['recipients'] as $sPlugin) {
                     plugin_include("recipients", $sPlugin . "/" . $sPlugin . ".php");
                     if (function_exists("recipients_" . $sPlugin . "_wantedVariables")) {
                         $aPlugins[$sPlugin] = call_user_func("recipients_" . $sPlugin . "_wantedVariables");
                     }
                 }
             }
         }
         // Get recipients (from log table)
         if (!is_object($oLogs)) {
             $oLogs = new cNewsletterLogCollection();
         } else {
             $oLogs->resetQuery();
         }
         $oLogs->setWhere("idnewsjob", $this->get($this->primaryKey));
         $oLogs->setWhere("status", "pending");
         if ($bDispatch) {
             $oLogs->setLimit(0, $this->get("dispatch_count"));
         }
         $oLogs->query();
         while ($oLog = $oLogs->next()) {
             $iCount++;
             $oLog->set("status", "sending");
             $oLog->store();
             $sRcpMsgText = $sMessageText;
             $sRcpMsgHTML = $sMessageHTML;
             $sKey = $oLog->get("rcphash");
             $sEMail = $oLog->get("rcpemail");
             $bSendHTML = false;
             if ($oLog->get("rcpnewstype") == 1) {
                 $bSendHTML = true;
                 // Recipient accepts html newsletter
             }
             if (strlen($sKey) == 30) {
                 // Prevents sending without having a key
                 $sRcpMsgText = str_replace("{KEY}", $sKey, $sRcpMsgText);
                 $sRcpMsgText = str_replace("MAIL_MAIL", $sEMail, $sRcpMsgText);
                 $sRcpMsgText = str_replace("MAIL_NAME", $oLog->get("rcpname"), $sRcpMsgText);
                 // Replace message tags (html message)
                 if ($bIsHTML && $bSendHTML) {
                     $sRcpMsgHTML = str_replace("{KEY}", $sKey, $sRcpMsgHTML);
                     $sRcpMsgHTML = str_replace("MAIL_MAIL", $sEMail, $sRcpMsgHTML);
                     $sRcpMsgHTML = str_replace("MAIL_NAME", $oLog->get("rcpname"), $sRcpMsgHTML);
                     $sRcpMsgHTML = str_replace(urlencode('{RCP}'), $sKey, $sRcpMsgHTML);
                 }
                 if ($bPluginEnabled) {
                     // Don't change name of $recipient variable as it is used in plugins!
                     $recipient = new Recipient();
                     $recipient->loadByPrimaryKey($oLog->get("idnewsrcp"));
                     foreach ($aPlugins as $sPlugin => $aPluginVar) {
                         foreach ($aPluginVar as $sPluginVar) {
                             // Replace tags in text message
                             $sRcpMsgText = str_replace("MAIL_" . strtoupper($sPluginVar), call_user_func("recipients_" . $sPlugin . "_getvalue", $sPluginVar), $sRcpMsgText);
                             // Replace tags in html message
                             if ($bIsHTML && $bSendHTML) {
                                 $sRcpMsgHTML = str_replace("MAIL_" . strtoupper($sPluginVar), call_user_func("recipients_" . $sPlugin . "_getvalue", $sPluginVar), $sRcpMsgHTML);
                             }
                         }
                     }
                     unset($recipient);
                 }
                 $oMail = new PHPMailer();
                 $oMail->CharSet = $sEncoding;
                 $oMail->IsHTML($bIsHTML && $bSendHTML);
                 $oMail->From = $sFrom;
                 $oMail->FromName = $sFromName;
                 $oMail->AddAddress($sEMail);
                 # Mailer Configuration -->
                 $sMailer = strtolower(getEffectiveSetting('newsletter', 'mailer'));
                 $sHost = getEffectiveSetting('newsletter', 'host');
                 $iPort = intval(getEffectiveSetting('newsletter', 'port'));
                 $sUsername = getEffectiveSetting('newsletter', 'username');
                 $sPassword = getEffectiveSetting('newsletter', 'password');
                 if (strlen($sMailer) == 0) {
                     $sMailer = strtolower(getEffectiveSetting('email', 'mailer'));
                     $sHost = getEffectiveSetting('email', 'host');
                     $iPort = intval(getEffectiveSetting('email', 'port'));
                     $sUsername = getEffectiveSetting('email', 'username');
                     $sPassword = getEffectiveSetting('email', 'password');
                 }
                 if (strlen($sMailer) == 0) {
                     setSystemProperty('newsletter', 'mailer', 'mail');
                     $sMailer = 'mail';
                 }
                 if (strlen($sHost) == 0) {
                     setSystemProperty('newsletter', 'host', '');
                 }
                 if ($iPort == 0) {
                     setSystemProperty('newsletter', 'port', '25');
                     $iPort = 25;
                 }
                 if (strlen($sUsername) == 0) {
                     setSystemProperty('newsletter', 'username', '');
                 }
                 if (strlen($sPassword) == 0) {
                     setSystemProperty('newsletter', 'password', '');
                 }
                 $oMail->Mailer = $sMailer;
                 if ($sMailer == 'smtp') {
                     $oMail->SMTPAuth = true;
                     $oMail->Host = $sHost;
                     $oMail->Port = $iPort;
                     $oMail->Username = $sUsername;
                     $oMail->Password = $sPassword;
                 }
                 # <-- Mailer Configuration
                 $oMail->Subject = $sSubject;
                 if ($bIsHTML && $bSendHTML) {
                     $oMail->Body = $sRcpMsgHTML;
                     $oMail->AltBody = $sRcpMsgText . "\n\n";
                 } else {
                     $oMail->Body = $sRcpMsgText . "\n\n";
                 }
                 if ($oMail->Send()) {
                     $oLog->set("status", "successful");
                     $oLog->set("sent", date("Y-m-d H:i:s"), false);
                 } else {
                     $oLog->set("status", "error (sending)");
                 }
             } else {
                 $oLog->set("status", "error (key)");
             }
             $oLog->store();
         }
         $this->set("sendcount", $this->get("sendcount") + $iCount);
         if ($iCount == 0 || !$bDispatch) {
             // No recipients remaining, job finished
             $this->set("status", 9);
             $this->set("finished", date("Y-m-d H:i:s"), false);
         } else {
             if ($bDispatch) {
                 // Check, if there are recipients remaining - stops job faster
                 $oLogs->resetQuery();
                 $oLogs->setWhere("idnewsjob", $this->get($this->primaryKey));
                 $oLogs->setWhere("status", "pending");
                 $oLogs->setLimit(0, $this->get("dispatch_count"));
                 $oLogs->query();
                 if ($oLogs->next()) {
                     // Remaining recipients found, set job back to pending
                     $this->set("status", 1);
                     $this->set("started", "0000-00-00 00:00:00", false);
                 } else {
                     // No remaining recipients, job finished
                     $this->set("status", 9);
                     $this->set("finished", date("Y-m-d H:i:s"), false);
                 }
             } else {
                 // Set job back to pending
                 $this->set("status", 1);
                 $this->set("started", "0000-00-00 00:00:00", false);
             }
         }
         $this->store();
     }
     return $iCount;
 }
 $oCkbConfirmed = new cHTMLCheckbox("confirmed", "1");
 $oCkbConfirmed->setChecked($recipient->get("confirmed"));
 $oCkbDeactivated = new cHTMLCheckbox("deactivated", "1");
 $oCkbDeactivated->setChecked($recipient->get("deactivated"));
 $oSelNewsType = new cHTMLSelectElement("newstype");
 $oOption = new cHTMLOptionElement(i18n("Text only", $plugin_name), "0");
 $oSelNewsType->addOptionElement(0, $oOption);
 $oOption = new cHTMLOptionElement(i18n("HTML and text", $plugin_name), "1");
 $oSelNewsType->addOptionElement(1, $oOption);
 $oSelNewsType->setDefault($recipient->get("news_type"));
 $oForm->add(i18n("Name", $plugin_name), $oTxtName->render());
 $oForm->add(i18n("E-Mail", $plugin_name), $oTxtEMail->render());
 $oForm->add(i18n("Confirmed", $plugin_name), $oCkbConfirmed->toHTML(false) . " (" . $recipient->get("confirmeddate") . ")");
 $oForm->add(i18n("Deactivated", $plugin_name), $oCkbDeactivated->toHTML(false));
 $oForm->add(i18n("Message type", $plugin_name), $oSelNewsType->render());
 $aPluginOrder = trim_array(explode(",", getSystemProperty("plugin", "recipients-pluginorder")));
 // Check out if there are any plugins
 if (is_array($aPluginOrder)) {
     foreach ($aPluginOrder as $sPlugin) {
         if (function_exists("recipients_" . $sPlugin . "_getTitle") && function_exists("recipients_" . $sPlugin . "_display")) {
             $aPluginTitle = call_user_func("recipients_" . $sPlugin . "_getTitle");
             $aPluginDisplay = call_user_func("recipients_" . $sPlugin . "_display", $recipient);
             if (is_array($aPluginTitle) && is_array($aPluginDisplay)) {
                 foreach ($aPluginTitle as $sKey => $sValue) {
                     $oForm->add($sValue, $aPluginDisplay[$sKey]);
                 }
             } else {
                 if (is_array($aPluginTitle) || is_array($aPluginDisplay)) {
                     $oForm->add(i18n("WARNING", $plugin_name), sprintf(i18n("The plugin %s delivered an array for the displayed titles, but did not return an array for the contents.", $plugin_name), $sPlugin));
                 } else {
                     $oForm->add($aPluginTitle, $aPluginDisplay);
 /**
  * Sends test newsletter directly to specified recipients (single or group)
  *
  * Note: Sending in chunks not supported! Only usable for tests and only a few
  * recipients.
  *
  * @param integer  $iIDCatArt     idcatart of newsletter handler article
  * @param integer  $iIDNewsRcp    If specified, newsletter recipient id, ignored, if group specified
  * @param integer  $iIDNewsGroup  If specified, newsletter recipient group id
  * @param array    $aSendRcps     As reference: Filled with a list of succesfull recipients
  * @param string   $sEncoding     Message (and header) encoding, e.g. iso-8859-1
  */
 public function sendDirect($iIDCatArt, $iIDNewsRcp = false, $iIDNewsGroup = false, &$aSendRcps, $sEncoding = "iso-8859-1")
 {
     global $lang, $client, $cfg, $cfgClient, $contenido, $recipient;
     // Initialization
     $aMessages = array();
     $oLanguage = new cApiLanguage($lang);
     $sFormatDate = $oLanguage->getProperty("dateformat", "date");
     $sFormatTime = $oLanguage->getProperty("dateformat", "time");
     unset($oLanguage);
     if ($sFormatDate == "") {
         $sFormatDate = 'Y-m-d';
     }
     if ($sFormatTime == "") {
         $sFormatTime = 'h:i a';
     }
     #$sPath = $cfgClient[$client]["path"]["htmlpath"]."front_content.php?changelang=".$lang."&idcatart=".$iIDCatArt."&";
     $sPath = Contenido_Url::getInstance()->build(array('idcatart' => $iIDCatArt, 'client' => $client, 'lang' => $lang), true);
     $sPath .= strpos($sPath, '?') === false ? '?' : '&';
     // Get newsletter data
     $sFrom = $this->get("newsfrom");
     $sFromName = $this->get("newsfromname");
     if ($sFromName == "") {
         $sFromName = $sFrom;
     }
     $sSubject = $this->get("subject");
     $sMessageText = $this->get("message");
     $bIsHTML = false;
     if ($this->get("type") == "html") {
         $sMessageHTML = $this->getHTMLMessage();
         if ($sMessageHTML === false) {
             // There was a problem getting the html message (maybe article
             // deleted). Exit with error instead of sending as text message only
             if ($contenido) {
                 // Use i18n only in backend
                 $sError = i18n("Newsletter could not be sent: No html message available", $plugin_name);
             } else {
                 $sError = "Newsletter could not be sent: No html message available";
             }
             $this->_sError = $sError;
             return false;
         } else {
             $bIsHTML = true;
         }
     }
     // Preventing double lines in mail, you may wish to disable this function on windows servers
     if (!getSystemProperty("newsletter", "disable-rn-replacement")) {
         $sMessageText = str_replace("\r\n", "\n", $sMessageText);
     }
     // Single replacements
     // Replace message tags (text message)
     $this->_replaceTag($sMessageText, false, "date", date($sFormatDate));
     $this->_replaceTag($sMessageText, false, "time", date($sFormatTime));
     // Replace message tags (html message)
     if ($bIsHTML) {
         $this->_replaceTag($sMessageHTML, true, "date", date($sFormatDate));
         $this->_replaceTag($sMessageHTML, true, "time", date($sFormatTime));
     }
     // Enabling plugin interface
     if (getSystemProperty("newsletter", "newsletter-recipients-plugin") == "true") {
         $bPluginEnabled = true;
         $aPlugins = array();
         if (is_array($cfg['plugins']['recipients'])) {
             foreach ($cfg['plugins']['recipients'] as $sPlugin) {
                 plugin_include("recipients", $sPlugin . "/" . $sPlugin . ".php");
                 if (function_exists("recipients_" . $sPlugin . "_wantedVariables")) {
                     $aPlugins[$sPlugin] = call_user_func("recipients_" . $sPlugin . "_wantedVariables");
                 }
             }
         }
     } else {
         setSystemProperty("newsletter", "newsletter-recipients-plugin", "false");
         $bPluginEnabled = false;
     }
     $aRecipients = array();
     if ($iIDNewsGroup !== false) {
         $oGroupMembers = new RecipientGroupMemberCollection();
         $aRecipients = $oGroupMembers->getRecipientsInGroup($iIDNewsGroup, false);
     } else {
         if ($iIDNewsRcp !== false) {
             $aRecipients[] = $iIDNewsRcp;
         }
     }
     $iCount = count($aRecipients);
     if ($iCount > 0) {
         $this->_replaceTag($sMessageText, false, "number", $iCount);
         // Replace message tags (html message)
         if ($bIsHTML) {
             $this->_replaceTag($sMessageHTML, true, "number", $iCount);
         }
         foreach ($aRecipients as $iID) {
             $sRcpMsgText = $sMessageText;
             $sRcpMsgHTML = $sMessageHTML;
             // Don't change name of $recipient variable as it is used in plugins!
             $recipient = new Recipient();
             $recipient->loadByPrimaryKey($iID);
             $sEMail = $recipient->get("email");
             $sName = $recipient->get("name");
             if (empty($sName)) {
                 $sName = $sEMail;
             }
             $sKey = $recipient->get("hash");
             $bSendHTML = false;
             if ($recipient->get("news_type") == 1) {
                 $bSendHTML = true;
                 // Recipient accepts html newsletter
             }
             $this->_replaceTag($sRcpMsgText, false, "name", $sName);
             $this->_replaceTag($sRcpMsgText, false, "unsubscribe", $sPath . "unsubscribe=" . $sKey);
             $this->_replaceTag($sRcpMsgText, false, "change", $sPath . "change=" . $sKey);
             $this->_replaceTag($sRcpMsgText, false, "stop", $sPath . "stop=" . $sKey);
             $this->_replaceTag($sRcpMsgText, false, "goon", $sPath . "goon=" . $sKey);
             // Replace message tags (html message)
             if ($bIsHTML && $bSendHTML) {
                 $this->_replaceTag($sRcpMsgHTML, true, "name", $sName);
                 $this->_replaceTag($sRcpMsgHTML, true, "unsubscribe", $sPath . "unsubscribe=" . $sKey);
                 $this->_replaceTag($sRcpMsgHTML, true, "change", $sPath . "change=" . $sKey);
                 $this->_replaceTag($sRcpMsgHTML, true, "stop", $sPath . "stop=" . $sKey);
                 $this->_replaceTag($sRcpMsgHTML, true, "goon", $sPath . "goon=" . $sKey);
                 # Link to online article -->
                 if (!is_object($db)) {
                     $db = new DB_Contenido();
                 }
                 $sql = 'SELECT idart
                         FROM ' . $cfg['tab']['news'] . '
                         WHERE (idnews=' . $this->get('idnews') . ')';
                 $db->query($sql);
                 $db->next_record();
                 $news_idart = $db->f('idart');
                 $link = Contenido_Url::getInstance()->build(array('idart' => $news_idart, 'client' => $this->get('idclient'), 'lang' => $this->get("idlang"), 'rcp' => $sKey), true);
                 $p1 = strpos($sMessageHTML, '<body');
                 if ($p1 !== false) {
                     $p1 = strpos($sMessageHTML, '>', $p1) + 1;
                 } else {
                     $p1 = 0;
                 }
                 $sOnlineText = getEffectiveSetting('newsletter-online-text', $this->get("idlang"), 'If the newsletter is not shown properly, please click here to view the online version.');
                 $sMessageHTML = substr($sMessageHTML, 0, $p1) . '<div style="text-align: center; background-color: #FFF;"><a href="' . $link . '" style="font-weight: bold;">' . $sOnlineText . '</a></div>' . substr($sMessageHTML, $p1);
                 # <-- Link to online article
                 // Remove base tag
                 $sMessageHTML = preg_replace('/<base href=(.*?)>/is', '', $sMessageHTML, 1);
                 // Fix source path
                 // TODO: Test any URL specification that may exist under the sun...
                 $sMainURL = Contenido_Url::getInstance()->build(array('idcat' => getEffectiveSetting('navigation', 'idcat-home', 1), 'client' => $this->get('idclient'), 'lang' => $this->get("idlang")), true);
                 $sSelfURL = Contenido_Url::getInstance()->build(array('idart' => $this->get("idart"), 'client' => $this->get('idclient'), 'lang' => $this->get("idlang")), true);
                 $sMessageHTML = preg_replace("/(href|src)\\=(\"|\\')([^(http|#)])(\\/)?/", "\$1=" . "\$2" . $sMainURL . "\$3", $sMessageHTML);
                 $sMessageHTML = preg_replace('/url\\([\\"\'](.*)[\\"\']\\)/', 'url(\'' . $sMainURL . '$1\')', $sMessageHTML);
                 $sMessageHTML = str_replace('/cms//', '/', $sMessageHTML);
                 // Now replace anchor tags to the newsletter article itself just by the anchor
                 $sMessageHTML = preg_replace("/(href|src)\\=(\"|\\')" . str_replace('/', '\\/', $sSelfURL) . "(.*)#(.*)(\"|\\')/", "\$1=" . "\$2" . "#" . "\$4" . "\$5", $sMessageHTML);
                 // Now correct mailto tags
                 $sMessageHTML = str_replace($sMainURL . 'mailto:', 'mailto:', $sMessageHTML);
                 # Remove the <noscript> info from the newsletter message
                 $sMessageHTML = str_replace(array('This website is powered by drugCMS, the Content Management System with addictive potential.', 'For more info and download visit <a href="http://www.drugcms.org">www.drugcms.org</a>.', 'drugCMS is made in Germany.'), '', $sMessageHTML);
             }
             if ($bPluginEnabled) {
                 foreach ($aPlugins as $sPlugin => $aPluginVar) {
                     foreach ($aPluginVar as $sPluginVar) {
                         // Replace tags in text message
                         $this->_replaceTag($sRcpMsgText, false, $sPluginVar, call_user_func("recipients_" . $sPlugin . "_getvalue", $sPluginVar));
                         // Replace tags in html message
                         if ($bIsHTML && $bSendHTML) {
                             $this->_replaceTag($sRcpMsgHTML, true, $sPluginVar, call_user_func("recipients_" . $sPlugin . "_getvalue", $sPluginVar));
                         }
                     }
                 }
             }
             if (strlen($sKey) != 30) {
                 // Prevents sending without having a key
                 if ($contenido) {
                     // Use i18n only in backend
                     $sError = i18n("Newsletter to %s could not be sent: Recipient has an incompatible or empty key", $plugin_name);
                 } else {
                     $sError = "Newsletter to %s could not be sent: Recipient has an incompatible or empty key";
                 }
                 $aMessages[] = $sName . " (" . $sEMail . "): " . sprintf($sError, $sEMail);
             } else {
                 if (!isValidMail($sEMail)) {
                     if ($contenido) {
                         // Use i18n only in backend
                         $sError = i18n("Newsletter to %s could not be sent: No valid e-mail address specified", $plugin_name);
                     } else {
                         $sError = "Newsletter to %s could not be sent: No valid e-mail address specified";
                     }
                     $aMessages[] = $sName . " (" . $sEMail . "): " . sprintf($sError, $sEMail);
                 } else {
                     $oMail = new PHPMailer();
                     $oMail->CharSet = $sEncoding;
                     $oMail->IsHTML($bIsHTML && $bSendHTML);
                     $oMail->From = $sFrom;
                     $oMail->FromName = $sFromName;
                     $oMail->AddAddress($sEMail);
                     # Mailer Configuration -->
                     $sMailer = strtolower(getEffectiveSetting('newsletter', 'mailer'));
                     $sHost = getEffectiveSetting('newsletter', 'host');
                     $iPort = intval(getEffectiveSetting('newsletter', 'port'));
                     $sUsername = getEffectiveSetting('newsletter', 'username');
                     $sPassword = getEffectiveSetting('newsletter', 'password');
                     if (strlen($sMailer) == 0) {
                         $sMailer = strtolower(getEffectiveSetting('email', 'mailer'));
                         $sHost = getEffectiveSetting('email', 'host');
                         $iPort = intval(getEffectiveSetting('email', 'port'));
                         $sUsername = getEffectiveSetting('email', 'username');
                         $sPassword = getEffectiveSetting('email', 'password');
                     }
                     if (strlen($sMailer) == 0) {
                         setClientProperty('email', 'mailer', 'mail');
                         $sMailer = 'mail';
                     }
                     if (strlen($sHost) == 0) {
                         setClientProperty('email', 'host', '');
                     }
                     if ($iPort == 0) {
                         setClientProperty('email', 'port', '25');
                         $iPort = 25;
                     }
                     if (strlen($sUsername) == 0) {
                         setClientProperty('email', 'username', '');
                     }
                     if (strlen($sPassword) == 0) {
                         setClientProperty('email', 'password', '');
                     }
                     $oMail->Mailer = $sMailer;
                     if ($sMailer == 'smtp') {
                         $oMail->SMTPAuth = true;
                         $oMail->Host = $sHost;
                         $oMail->Port = $iPort;
                         $oMail->Username = $sUsername;
                         $oMail->Password = $sPassword;
                     }
                     # <-- Mailer Configuration
                     $oMail->Subject = $sSubject;
                     if ($bIsHTML && $bSendHTML) {
                         $oMail->Body = $sRcpMsgHTML;
                         $oMail->AltBody = $sRcpMsgText . "\n\n";
                     } else {
                         $oMail->Body = $sRcpMsgText . "\n\n";
                     }
                     if ($oMail->Send()) {
                         $aSendRcps[] = $sName . " (" . $sEMail . ")";
                     } else {
                         if ($contenido) {
                             // Use i18n only in backend
                             $sError = i18n("Newsletter to %s could not be sent", $plugin_name);
                         } else {
                             $sError = "Newsletter to %s could not be sent";
                         }
                         $aMessages[] = $sName . " (" . $sEMail . "): " . sprintf($sError, $sEMail);
                     }
                 }
             }
         }
     } else {
         if ($contenido) {
             // Use i18n only in backend
             $sError = i18n("No recipient with specified recipient/group id %s/%s found", $plugin_name);
         } else {
             $sError = "No recipient with specified recpient/group id %s/%s found";
         }
         $aMessages[] = sprintf($sError, $iIDNewsRcp, $iIDNewsGroup);
     }
     if (count($aMessages) > 0) {
         $this->_sError = implode("<br />", $aMessages);
         return false;
     } else {
         return true;
     }
 }
    $_REQUEST["sortby"] = "name";
    // Default sort by field, possible values see above
}
if (!$bSearchInFound) {
    $_REQUEST["searchin"] = "--all--";
}
// Free memory
unset($oUser);
unset($oClient);
##################################
# Get data
##################################
$oRecipients = new RecipientCollection();
// Updating keys, if activated; all recipients of all clients!
$sMsg = "";
if (getSystemProperty("newsletter", "updatekeys")) {
    $iUpdatedRecipients = $oRecipients->updateKeys();
    $sMsg = $notification->returnNotification("info", sprintf(i18n("%d recipients, with no or incompatible key has been updated. Deactivate update function.", $plugin_name), $iUpdatedRecipients));
}
$oRecipients->setWhere("recipientcollection.idclient", $client);
$oRecipients->setWhere("recipientcollection.idlang", $lang);
// sort by and sort order
$oRecipients->setOrder("recipientcollection." . $_REQUEST["sortby"] . " " . $_REQUEST["sortorder"]);
// Show group
if ($_REQUEST["restrictgroup"] != "--all--") {
    $oRecipients->link("RecipientGroupMemberCollection");
    $oRecipients->setWhere("RecipientGroupMemberCollection.idnewsgroup", $_REQUEST["restrictgroup"]);
}
// Search for
if ($_REQUEST["filter"] != "") {
    if ($_REQUEST["searchin"] == "--all--" || $_REQUEST["searchin"] == "") {
             }
         }
     }
 }
 $oForm = new UI_Table_Form("frmNewsletterMsg");
 $oForm->setVar("frame", $frame);
 $oForm->setVar("area", $area);
 $oForm->setVar("action", "news_save");
 $oForm->setVar("idnewsletter", $idnewsletter);
 $oForm->setWidth("100%");
 $oForm->addHeader(sprintf(i18n("Edit newsletter message (%s)", $plugin_name), $oNewsletter->get("name")));
 $oForm->add(i18n("Subject", $plugin_name), $oNewsletter->get("subject"));
 $sTagInfoText = '<a href="javascript:fncShowHide(\'idTagInfoText\');"><strong>' . i18n("Tag information", $plugin_name) . '</strong></a>' . '<div id="idTagInfoText" style="display: none"><br /><b>' . i18n("Special message tags (will be replaced when sending)", $plugin_name) . ':</b><br>' . 'MAIL_NAME: ' . i18n("Name of the recipient", $plugin_name) . '<br />' . 'MAIL_DATE: ' . i18n("Date, when the mail has been sent", $plugin_name) . '<br />' . 'MAIL_TIME: ' . i18n("Time, when the mail has been sent", $plugin_name) . '<br />' . 'MAIL_NUMBER: ' . i18n("Number of recipients", $plugin_name) . '<br />' . 'MAIL_UNSUBSCRIBE: ' . i18n("Link to unsubscribe", $plugin_name) . '<br />' . 'MAIL_STOP: ' . i18n("Link to pause the subscription", $plugin_name) . '<br />' . 'MAIL_GOON: ' . i18n("Link to resume the subscription", $plugin_name);
 $sTagInfoHTML = '<a href="javascript:fncShowHide(\'idTagInfoHTML\');"><strong>' . i18n("Tag information", $plugin_name) . '</strong></a>' . '<div id="idTagInfoHTML" style="display: none"><br /><b>' . i18n("Special message tags (will be replaced when sending, {..} = optional)", $plugin_name) . ":</b><br />" . '[mail name="name" type="text"]{text}MAIL_NAME{text}[/mail]: ' . i18n("Name of the recipient", $plugin_name) . "<br />" . '[mail name="date" type="text"]{text}MAIL_DATE{text}[/mail]: ' . i18n("Date, when the mail has been sent", $plugin_name) . "<br />" . '[mail name="time" type="text"]{text}MAIL_TIME{text}[/mail]: ' . i18n("Time, when the mail has been sent", $plugin_name) . "<br />" . '[mail name="number" type="text"]{text}MAIL_NUMBER{text}[/mail]: ' . i18n("Number of recipients", $plugin_name) . "<br />" . '[mail name="unsubscribe" type="link" {text="' . i18n("Link text", $plugin_name) . '" }]{text}MAIL_UNSUBSCRIBE{text}[/mail]: ' . i18n("Link to unsubscribe", $plugin_name) . "<br />" . '[mail name="stop" type="link" {text="' . i18n("Link text", $plugin_name) . '" }]{text}MAIL_STOP{text}[/mail]: ' . i18n("Link to pause the subscription", $plugin_name) . "<br />" . '[mail name="goon" type="link" {text="' . i18n("Link text", $plugin_name) . '" }]{text}MAIL_GOON{text}[/mail]: ' . i18n("Link to resume the subscription", $plugin_name);
 // Mention plugin interface
 if (getSystemProperty("newsletter", "newsletter-recipients-plugin") == "true") {
     $sTagInfoText .= "<br /><br /><strong>" . i18n("Additional message tags from recipients plugins:", $plugin_name) . "</strong><br />";
     $sTagInfoHTML .= "<br /><br /><strong>" . i18n("Additional message tags from recipients plugins:", $plugin_name) . "</strong><br />";
     if (is_array($cfg['plugins']['recipients'])) {
         foreach ($cfg['plugins']['recipients'] as $plugin) {
             plugin_include("recipients", $plugin . "/" . $plugin . ".php");
             if (function_exists("recipients_" . $plugin . "_wantedVariables")) {
                 $aPluginVars = call_user_func("recipients_" . $plugin . "_wantedVariables");
                 foreach ($aPluginVars as $sPluginVar) {
                     $sTagInfoText .= 'MAIL_' . strtoupper($sPluginVar) . '<br />';
                     $sTagInfoHTML .= '[mail name="' . strtolower($sPluginVar) . '" type="text"][/mail]<br />';
                 }
             }
         }
     }
 } else {
 /**
  * Overriden store function to send mails 
  * @param none
  */
 function store()
 {
     global $cfg, $encoding, $lang;
     $sMailhost = getSystemProperty('system', 'mail_host');
     if ($sMailhost == '') {
         $sMailhost = 'localhost';
     }
     //modified : 2008-06-25 - use php mailer class instead of mail()
     $oMail = new PHPMailer();
     $oMail->CharSet = isset($encoding[$lang]) ? $encoding[$lang] : 'UTF-8';
     $oMail->Host = $sMailhost;
     $oMail->IsHTML(0);
     $oMail->WordWrap = 1000;
     $oMail->IsMail();
     if (array_key_exists("idusersequence", $this->modifiedValues)) {
         $usersequence = new WorkflowUserSequence();
         $usersequence->loadByPrimaryKey($this->values["idusersequence"]);
         $email = $usersequence->get("emailnoti");
         $escal = $usersequence->get("escalationnoti");
         if ($email == 1 || $escal == 1) {
             /* Grab the required informations */
             $curEditor = getGroupOrUserName($usersequence->get("iduser"));
             $idartlang = $this->get("idartlang");
             $timeunit = $usersequence->get("timeunit");
             $timelimit = $usersequence->get("timelimit");
             $db = new DB_Contenido();
             $sql = "SELECT author, title, idart FROM " . $cfg["tab"]["art_lang"] . " WHERE idartlang = '" . Contenido_Security::escapeDB($idartlang, $db) . "'";
             $db->query($sql);
             if ($db->next_record()) {
                 $idart = $db->f("idart");
                 $title = $db->f("title");
                 $author = $db->f("author");
             }
             /* Extract category */
             $sql = "SELECT idcat FROM " . $cfg["tab"]["cat_art"] . " WHERE idart = '" . Contenido_Security::escapeDB($idart, $db) . "'";
             $db->query($sql);
             if ($db->next_record()) {
                 $idcat = $db->f("idcat");
             }
             $sql = "SELECT name FROM " . $cfg["tab"]["cat_lang"] . " WHERE idcat = '" . Contenido_Security::escapeDB($idcat, $db) . "'";
             $db->query($sql);
             if ($db->next_record()) {
                 $catname = $db->f("name");
             }
             $starttime = $this->get("starttime");
             $starttime = strtotime(substr_replace(substr(substr($starttime, 0, 2) . chunk_split(substr($starttime, 2, 6), 2, "-") . chunk_split(substr($starttime, 8), 2, ":"), 0, 19), " ", 10, 1));
             switch ($timeunit) {
                 case "Seconds":
                     $maxtime = $starttime + $timelimit;
                     break;
                 case "Minutes":
                     $maxtime = $starttime + $timelimit * 60;
                     break;
                 case "Hours":
                     $maxtime = $starttime + $timelimit * 3600;
                     break;
                 case "Days":
                     $maxtime = $starttime + $timelimit * 86400;
                     break;
                 case "Weeks":
                     $maxtime = $starttime + $timelimit * 604800;
                     break;
                 case "Months":
                     $maxtime = $starttime + $timelimit * 2678400;
                     break;
                 case "Years":
                     $maxtime = $starttime + $timelimit * 31536000;
                     break;
                 default:
                     $maxtime = $starttime + $timelimit;
             }
             if ($email == 1) {
                 $email = i18n("Hello %s,\n\n" . "you are assigned as the next editor for the Article %s.\n\n" . "More informations:\n" . "Article: %s\n" . "Category: %s\n" . "Editor: %s\n" . "Author: %s\n" . "Editable from: %s\n" . "Editable to: %s\n");
                 $filledMail = sprintf($email, $curEditor, $title, $title, $catname, $curEditor, $author, date("Y-m-d H:i:s", $starttime), date("Y-m-d H:i:s", $maxtime));
                 $user = new User();
                 if (isGroup($usersequence->get("iduser"))) {
                     $sql = "select idgroupuser, user_id FROM " . $cfg["tab"]["groupmembers"] . " WHERE\n            \t\t\t\t\t\tgroup_id = '" . Contenido_Security::escapeDB($usersequence->get("iduser"), $db) . "'";
                     $db->query($sql);
                     while ($db->next_record()) {
                         $user->loadUserByUserID($db->f("user_id"));
                         //modified : 2008-06-25 - use php mailer class instead of mail()
                         $oMail->AddAddress($user->getField("email"), "");
                         $oMail->Subject = stripslashes(i18n('Workflow notification', "workflow"));
                         $oMail->Body = $filledMail;
                         $oMail->Send();
                     }
                 } else {
                     $user->loadUserByUserID($usersequence->get("iduser"));
                     //modified : 2008-06-25 - use php mailer class instead of mail()
                     $oMail->AddAddress($user->getField("email"), "");
                     $oMail->Subject = stripslashes(i18n('Workflow notification', "workflow"));
                     $oMail->Body = $filledMail;
                     $oMail->Send();
                 }
             } else {
                 $email = "Hello %s,\n\n" . "you are assigned as the escalator for the Article %s.\n\n" . "More informations:\n" . "Article: %s\n" . "Category: %s\n" . "Editor: %s\n" . "Author: %s\n" . "Editable from: %s\n" . "Editable to: %s\n";
                 $filledMail = sprintf($email, $curEditor, $title, $title, $catname, $curEditor, $author, date("Y-m-d H:i:s", $starttime), date("Y-m-d H:i:s", $maxtime));
                 $user = new User();
                 if (isGroup($usersequence->get("iduser"))) {
                     $sql = "select idgroupuser, user_id FROM " . $cfg["tab"]["groupmembers"] . " WHERE\n            \t\t\t\t\t\tgroup_id = '" . Contenido_Security::escapeDB($usersequence->get("iduser"), $db) . "'";
                     $db->query($sql);
                     while ($db->next_record()) {
                         $user->loadUserByUserID($db->f("user_id"));
                         echo "mail to " . $user->getField("email") . "<br>";
                         //modified : 2008-06-25 - use php mailer class instead of mail()
                         $oMail->AddAddress($user->getField("email"), "");
                         $oMail->Subject = stripslashes(i18n('Workflow escalation', "workflow"));
                         $oMail->Body = $filledMail;
                         $oMail->Send();
                     }
                 } else {
                     $user->loadUserByUserID($usersequence->get("iduser"));
                     echo "mail to " . $user->getField("email") . "<br>";
                     //modified : 2008-06-25 - use php mailer class instead of mail()
                     $oMail->AddAddress($user->getField("email"), "");
                     $oMail->Subject = stripslashes(i18n('Workflow escalation', "workflow"));
                     $oMail->Body = $filledMail;
                     $oMail->Send();
                 }
             }
         }
     }
     return parent::store();
 }