/**
  * Deletes all corresponding informations to this workflow and delegate call to parent
  * @param integer $idWorkflow - id of workflow to delete
  */
 function delete($idWorkflow)
 {
     global $cfg;
     $oDb = new DB_Contenido();
     $aItemIdsDelete = array();
     $sSql = 'SELECT idworkflowitem FROM ' . $cfg["tab"]["workflow_items"] . ' WHERE idworkflow = ' . Contenido_Security::toInteger($idWorkflow) . ';';
     $oDb->query($sSql);
     while ($oDb->next_record()) {
         array_push($aItemIdsDelete, Contenido_Security::escapeDB($oDb->f('idworkflowitem'), $oDb));
     }
     $aUserSequencesDelete = array();
     $sSql = 'SELECT idusersequence FROM ' . $cfg["tab"]["workflow_user_sequences"] . ' WHERE idworkflowitem in (' . implode(',', $aItemIdsDelete) . ');';
     $oDb->query($sSql);
     while ($oDb->next_record()) {
         array_push($aUserSequencesDelete, Contenido_Security::escapeDB($oDb->f('idusersequence'), $oDb));
     }
     $sSql = 'DELETE FROM ' . $cfg["tab"]["workflow_user_sequences"] . ' WHERE idworkflowitem in (' . implode(',', $aItemIdsDelete) . ');';
     $oDb->query($sSql);
     $sSql = 'DELETE FROM ' . $cfg["tab"]["workflow_actions"] . ' WHERE idworkflowitem in (' . implode(',', $aItemIdsDelete) . ');';
     $oDb->query($sSql);
     $sSql = 'DELETE FROM ' . $cfg["tab"]["workflow_items"] . ' WHERE idworkflow = ' . Contenido_Security::toInteger($idWorkflow) . ';';
     $oDb->query($sSql);
     $sSql = 'DELETE FROM ' . $cfg["tab"]["workflow_allocation"] . ' WHERE idworkflow = ' . Contenido_Security::toInteger($idWorkflow) . ';';
     $oDb->query($sSql);
     $sSql = 'DELETE FROM ' . $cfg["tab"]["workflow_art_allocation"] . ' WHERE idusersequence in (' . implode(',', $aUserSequencesDelete) . ');';
     $oDb->query($sSql);
     parent::delete($idWorkflow);
 }
 /**
  * Search articles by catgories without start articles
  * @param array $aCategories
  * @param int $iOffset
  * @param int $iNumOfRows
  * @param string $sResultType element of {article_id, object}
  *
  * @return array of articles
  */
 function findMatchingContentByCategories($aCategories = array(), $iOffset = 0, $iNumOfRows = 0, $sResultType = '')
 {
     for ($i = 0; $i < count($aCategories); $i++) {
         if (!is_int((int) $aCategories[$i]) or !$aCategories[$i] > 0) {
             return array();
         }
     }
     $sql = $this->_buildQuery_MatchingContentByCategories($aCategories, $iOffset, $iNumOfRows);
     $this->db->query($sql);
     $aResult = array();
     while ($oRow = $this->db->getResultObject()) {
         if ($sResultType == 'article_language_id') {
             $aResult[] = $oRow->idartlang;
         } else {
             $aResult[] = $oRow;
         }
     }
     return $aResult;
 }
                `sortorder` int(10) NOT NULL DEFAULT "0",
                PRIMARY KEY (`idpica_alloc`)
            )';
    $db->query($sql);
    $sql = 'CREATE TABLE `' . $cfg['sql']['sqlprefix'] . '_pica_alloc_con` (
                `idpica_alloc` int(10) NOT NULL DEFAULT "0",
                `idartlang` int(10) NOT NULL DEFAULT "0",
                PRIMARY KEY (`idpica_alloc`,`idartlang`)
            )';
    $db->query($sql);
    $sql = 'CREATE TABLE `' . $cfg['sql']['sqlprefix'] . '_pica_lang` (
                `idpica_alloc` int(10) NOT NULL DEFAULT "0",
                `idlang` int(10) NOT NULL DEFAULT "0",
                `name` varchar(255) DEFAULT NULL,
                `online` tinyint(1) NOT NULL DEFAULT "0",
                PRIMARY KEY (`idpica_alloc`,`idlang`)
            )';
    $db->query($sql);
}
if (!$db) {
    $db = new DB_Contenido();
}
$sql = 'SELECT idpica_alloc
        FROM ' . $cfg['sql']['sqlprefix'] . '_pica_alloc
        LIMIT 0, 1';
if (!$db->query($sql)) {
    picaCreateDbTables($db, $cfg);
}
plugin_include('content_allocation', 'includes/functions.chains.php');
$_cecRegistry->addChainFunction("Contenido.Article.RegisterCustomTab", "pica_RegisterCustomTab");
$_cecRegistry->addChainFunction("Contenido.Article.GetCustomTabProperties", "pica_GetCustomTabProperties");
 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;
 }
$oSelHTMLTemplateIDCat = new cHTMLSelectElement("selHTMLTemplateCat");
$oSelHTMLTemplateIDCat->setStyle("width: 220px;");
$oSelHTMLNewsletterIDCat = new cHTMLSelectElement("selHTMLNewsletterCat");
$oSelHTMLNewsletterIDCat->setStyle("width: 220px;");
$oOptionTemplate = new cHTMLOptionElement("--" . i18n("Please select", $plugin_name) . "--", 0);
$oSelHTMLTemplateIDCat->addOptionElement(0, $oOptionTemplate);
$oOptionNewsletter = new cHTMLOptionElement("--" . i18n("Please select", $plugin_name) . "--", 0);
$oSelHTMLNewsletterIDCat->addOptionElement(0, $oOptionNewsletter);
$sSQL = "SELECT tblCat.idcat AS idcat, tblCatLang.name AS name, tblCatTree.level AS level, ";
$sSQL .= "tblCatLang.visible AS visible, tblCatLang.public AS public FROM ";
$sSQL .= $cfg["tab"]["cat"] . " AS tblCat, " . $cfg["tab"]["cat_lang"] . " AS tblCatLang, ";
$sSQL .= $cfg["tab"]["cat_tree"] . " AS tblCatTree ";
$sSQL .= "WHERE tblCat.idclient = '" . Contenido_Security::toInteger($client) . "' AND tblCatLang.idlang = '" . Contenido_Security::toInteger($lang) . "' AND ";
$sSQL .= "tblCatLang.idcat = tblCat.idcat AND tblCatTree.idcat = tblCat.idcat ";
$sSQL .= "ORDER BY tblCatTree.idtree";
$oDB->query($sSQL);
while ($oDB->next_record()) {
    $sSpaces = "&nbsp;&nbsp;";
    for ($i = 0; $i < $oDB->f("level"); $i++) {
        $sSpaces .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    }
    $oOptionTemplate = new cHTMLOptionElement($sSpaces . $oDB->f("name"), $oDB->f("idcat"));
    $oOptionNewsletter = new cHTMLOptionElement($sSpaces . $oDB->f("name"), $oDB->f("idcat"));
    if ($oDB->f("visible") == 0 || $oDB->f("public") == 0) {
        $oOptionTemplate->setStyle("color: #666666;");
        $oOptionNewsletter->setStyle("color: #666666;");
    }
    $oSelHTMLTemplateIDCat->addOptionElement($oDB->f("idcat"), $oOptionTemplate);
    $oSelHTMLNewsletterIDCat->addOptionElement($oDB->f("idcat"), $oOptionNewsletter);
}
// Get html template category
 /**
  * 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;
     }
 }
function restore_tables($file, $first_line = 0)
{
    global $cfg;
    $iStart = time();
    $iMET = 2;
    #(intval(ini_get('max_execution_time')) - 10); # We need some time for other tasks
    $db = new DB_Contenido();
    $current_line = 0;
    # Open the backup file
    $gz = substr($file, -3) == '.gz';
    $len = filesize($file);
    if ($gz) {
        if (!($handle = gzopen($file, 'r'))) {
            return false;
        }
    } else {
        if (!($handle = fopen($file, 'r'))) {
            return false;
        }
    }
    # Process the file line by line
    while (true) {
        while ($current_line < $first_line) {
            if ($gz) {
                $line = trim(gzgets($handle, $len));
            } else {
                $line = trim(fgets($handle, $len));
            }
            $current_line++;
        }
        if ($gz) {
            $line = trim(gzgets($handle, $len));
            if (gzeof($handle)) {
                return true;
            }
        } else {
            $line = trim(fgets($handle, $len));
            if (feof($handle)) {
                return true;
            }
        }
        $current_line++;
        if (strlen($line) && substr($line, 0, 2) != '--') {
            /*
                        if ((substr(trim($line), 0, 10) == 'DROP TABLE') && ($current_line != ($first_line + 1))) {
                            # New table definition
                            $current_line --;
                            return (int) $current_line;
                        }
            */
            while (substr(trim($line), -1) != ';') {
                if ($gz) {
                    $line .= ' ' . trim(gzgets($handle, $len));
                } else {
                    $line .= ' ' . trim(fgets($handle, $len));
                }
                $current_line++;
            }
            if (!$db->query($line)) {
                echo 'Error ' . $db->getErrorNumber() . ': ' . $db->getErrorMessage() . '<br />';
                return false;
            }
        }
        # Time management
        if (time() - $iStart >= $iMET) {
            return (int) $current_line;
        }
    }
    return true;
}
 function _fetchItemNameLang($idpica_alloc)
 {
     $oDB = new DB_Contenido();
     // temp instance
     $sSQL = "SELECT name, idlang, online FROM " . $this->table['pica_lang'] . " WHERE idpica_alloc = " . Contenido_Security::toInteger($idpica_alloc) . " AND idlang = " . Contenido_Security::toInteger($this->lang);
     $oDB->query($sSQL);
     $aResult = array();
     if ($oDB->next_record()) {
         // item found for this language
         $aResult['name'] = $this->_outFilter($oDB->f('name'));
         $aResult['idlang'] = $oDB->f('idlang');
         $aResult['online'] = $oDB->f('online');
     } else {
         // no item in this language found
         // fetch alternative language name
         // HerrB, 2008-04-21: Get all translations, try to use defaultLang translation, use
         // first available, otherwise. Only using defaultLang results in "ghost" elements, if
         // created in a non-default language. See CON-110 for details.
         $sSQL = "SELECT name, idlang, online FROM " . $this->table['pica_lang'] . " WHERE idpica_alloc = " . Contenido_Security::toInteger($idpica_alloc) . " ORDER BY idlang";
         $oDB->query($sSQL);
         $aNames = array();
         while ($oDB->next_record()) {
             $sKey = "k" . $oDB->f('idlang');
             $aNames[$sKey] = array();
             $aNames[$sKey]['name'] = $this->_outFilter($oDB->f('name'));
             $aNames[$sKey]['idlang'] = $oDB->f('idlang');
             $aNames[$sKey]['online'] = $oDB->f('online');
         }
         if ($aNames["k" . $this->defaultLang]) {
             // defaultLang translation available
             $aResult = $aNames["k" . $this->defaultLang];
         } else {
             // no defaultLang translation available, use first in line (reset returns first element)
             $aResult = reset($aNames);
         }
     }
     unset($oDB);
     unset($aNames);
     return $aResult;
 }
function backup_tables($file, $host, $user, $pass, $name, $current_table = '', $current_row = 0)
{
    global $cfg;
    $iStart = time();
    $iMET = 2;
    #(intval(ini_get('max_execution_time')) - 10); # We need some time for other tasks
    $db = new DB_Contenido();
    # Open the output file
    $gz = extension_loaded('zlib');
    if ($gz) {
        if (!($handle = gzopen($file . '.gz', 'a'))) {
            return false;
        }
    } else {
        if (!($handle = fopen($file, 'a'))) {
            return false;
        }
    }
    if (strlen($current_table) == 0) {
        # Create the header
        $return = '-- drugCMS SQL Dump' . "\n";
        $return .= '-- drugCMS ' . $cfg['version'] . "\n";
        $return .= '-- (c) 2013-' . date('Y') . ' Spider IT Deutschland' . "\n";
        $return .= '--' . "\n";
        $return .= '-- Host: ' . $host . "\n";
        $return .= '-- Backup creation date: ' . date('r') . "\n";
        $ver = $db->server_info();
        $return .= '-- Server version: ' . $ver['description'] . "\n";
        $return .= '-- PHP version: ' . phpversion() . "\n";
        $return .= "\n";
        $return .= 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' . "\n";
        $return .= "\n";
        $return .= '--' . "\n";
        $return .= '-- Database: `' . $name . '`' . "\n";
        $return .= '--';
        if ($gz) {
            gzwrite($handle, $return);
        } else {
            fwrite($handle, $return);
        }
        $return = '';
    }
    # Get all the tables
    $tables = array();
    $result = $db->query('SHOW TABLES');
    while ($db->next_record()) {
        $tables[] = $db->f(0);
    }
    # Loop through the tables
    $bOK = false;
    foreach ($tables as $table) {
        if (strlen($current_table) && !$bOK) {
            if ($table == $current_table) {
                $bOK = true;
            }
        } else {
            $bOK = true;
        }
        if ($bOK) {
            if ($current_row == 0) {
                $return .= "\n";
                $return .= "\n";
                $return .= '--  --------------------------------------------------------' . "\n";
                $return .= "\n";
                $return .= '--' . "\n";
                $return .= '-- Table structure for table `' . $table . '`' . "\n";
                $return .= '--' . "\n";
                $return .= "\n";
                if (in_array(substr($table, strlen($cfg['sql']['sqlprefix'])), array('_online_user', '_phplib_active_sessions'))) {
                    # Don't drop these tables as the current user would be logged out
                    # while restoring the database, stopping the restore process
                    $db->query('SHOW CREATE TABLE `' . $table . '`');
                    $db->next_record();
                    $row2 = $db->toArray(DB_SQL_Abstract::FETCH_NUMERIC);
                    $return .= str_replace('CREATE TABLE `', 'CREATE TABLE IF NOT EXISTS `', $row2[1]) . ";\n";
                } else {
                    $return .= 'DROP TABLE IF EXISTS `' . $table . '`;' . "\n";
                    $db->query('SHOW CREATE TABLE `' . $table . '`');
                    $db->next_record();
                    $row2 = $db->toArray(DB_SQL_Abstract::FETCH_NUMERIC);
                    $return .= $row2[1] . ";\n";
                }
                if ($gz) {
                    gzwrite($handle, $return);
                } else {
                    fwrite($handle, $return);
                }
                $return = '';
                # Only backup data which is supposed to be permanent
                if (!in_array(substr($table, strlen($cfg['sql']['sqlprefix'])), array('_code', '_inuse', '_online_user', '_phplib_active_sessions'))) {
                    $return .= "\n";
                    $return .= '--' . "\n";
                    $return .= '-- Data for table `' . $table . '`' . "\n";
                    $return .= '--' . "\n";
                }
            }
            # Only backup data which is supposed to be permanent
            if (!in_array(substr($table, strlen($cfg['sql']['sqlprefix'])), array('_code', '_inuse', '_online_user', '_phplib_active_sessions'))) {
                # Get the key (first) column in the table (we sort it on this to export
                # each row just once if we split because of the time management)
                $db->query('SHOW COLUMNS FROM ' . $table);
                $db->next_record();
                $row = $db->toArray(DB_SQL_Abstract::FETCH_NUMERIC);
                $key_column = $row[0];
                # Get the amount of rows in this table
                $db->query('SELECT COUNT(' . $key_column . ') AS num_rows FROM ' . $table);
                $db->next_record();
                $num_rows = $db->f('num_rows');
                # Get the columns
                $db->query('SELECT * FROM ' . $table . ' ORDER BY ' . $key_column . ' LIMIT 0, 1');
                if ($db->next_record()) {
                    $row = $db->toArray(DB_SQL_Abstract::FETCH_BOTH);
                    $return .= "\n";
                    $return .= 'INSERT INTO `' . $table . '` (';
                    $keys = array();
                    foreach ($row as $key => $value) {
                        if (!is_numeric($key)) {
                            $keys[] = '`' . $key . '`';
                        }
                    }
                    $return .= implode(', ', $keys);
                    $return .= ') VALUES';
                }
                # Query the data
                $db->query('SELECT * FROM ' . $table . ' ORDER BY ' . $key_column . ' LIMIT ' . $current_row . ', ' . ($num_rows - $current_row));
                $num_fields = $db->num_fields();
                while ($db->next_record()) {
                    $row = $db->toArray(DB_SQL_Abstract::FETCH_BOTH);
                    $return .= "\n" . '(';
                    for ($i = 0; $i < $num_fields; $i++) {
                        if (!isset($row[$i])) {
                            $return .= 'NULL';
                        } elseif (is_numeric($row[$i])) {
                            $return .= $row[$i];
                        } else {
                            $return .= "'" . str_replace(array("'", '\\', "\r", "\n"), array("''", '\\\\', "\\r", "\\n"), $row[$i]) . "'";
                        }
                        if ($i < $num_fields - 1) {
                            $return .= ', ';
                        }
                    }
                    $return .= ')';
                    $current_row++;
                    # Time management
                    if (time() - $iStart >= $iMET) {
                        $return .= ';';
                        if ($gz) {
                            gzwrite($handle, $return);
                        } else {
                            fwrite($handle, $return);
                        }
                        return array('table' => $table, 'row' => $current_row);
                    } elseif (strlen($return) > 30000) {
                        $return .= ';';
                        if ($gz) {
                            gzwrite($handle, $return);
                        } else {
                            fwrite($handle, $return);
                        }
                        $return = "\n" . 'INSERT INTO `' . $table . '` (';
                        $return .= implode(', ', $keys);
                        $return .= ') VALUES';
                    } else {
                        $return .= ',';
                    }
                }
                $return = strlen($return) > 1 && substr($return, -1) == ',' ? substr($return, 0, -1) . ';' : '';
                if ($gz) {
                    gzwrite($handle, $return);
                } else {
                    fwrite($handle, $return);
                }
                $return = '';
                $current_row = 0;
                # Reset for the next table
            }
        }
    }
    # Set the code generation flag on restoring
    $return .= "\n";
    $return .= "\n";
    $return .= "\n";
    $return .= '--  --------------------------------------------------------' . "\n";
    $return .= "\n";
    $return .= '--' . "\n";
    $return .= '-- Set the code generation flag on restoring' . "\n";
    $return .= '--' . "\n";
    $return .= "\n";
    $return .= 'UPDATE `' . $cfg['sql']['sqlprefix'] . '_cat_art` SET `createcode` = 1;';
    //save file
    if ($gz) {
        gzwrite($handle, $return . "\n");
        gzclose($handle);
    } else {
        fwrite($handle, $return . "\n");
        fclose($handle);
    }
    return true;
}
 /**
  * setCatLang sets the idcatlang for the current item. Should
  * only be called by the create function.
  * @param int $idcatlang idcatlang to set.
  */
 function setCatLang($idcatlang)
 {
     global $cfg;
     $allocations = new WorkflowAllocations();
     $allocations->select("idcatlang = '{$idcatlang}'");
     if ($allocations->next() !== false) {
         $this->lasterror = i18n("Category already has a workflow assigned", "workflow");
         return false;
     }
     $db = new DB_Contenido();
     $sql = "SELECT idcatlang FROM " . $cfg["tab"]["cat_lang"] . " WHERE idcatlang = '" . Contenido_Security::toInteger($idcatlang) . "'";
     $db->query($sql);
     if (!$db->next_record()) {
         $this->lasterror = i18n("Category doesn't exist, assignment failed", "workflow");
         return false;
     }
     parent::setField("idcatlang", $idcatlang);
     parent::store();
     return true;
 }
        $wfu->select("idusersequence = '{$value}'");
        if ($obj = $wfu->next()) {
            $userids[$key] = $obj->get("iduser");
        }
    }
}
if (is_array($userids)) {
    foreach ($userids as $key => $value) {
        $isCurrent[$key] = false;
        if ($usershow == $value) {
            $isCurrent[$key] = true;
        }
        if ($users->loadUserByUserID($value) == false) {
            /* Yes, it's a group. Let's try to load the group members! */
            $sql = "SELECT user_id FROM " . $cfg["tab"]["groupmembers"] . "\n                WHERE group_id = '" . $value . "'";
            $db2->query(Contenido_Security::escapeDB($sql, $db2));
            while ($db2->next_record()) {
                if ($db2->f("user_id") == $usershow) {
                    $isCurrent[$key] = true;
                }
            }
        } else {
            if ($value == $usershow) {
                $isCurrent[$key] = true;
            }
        }
        if ($lastusersequence[$key] == $usersequence[$key]) {
            $isCurrent[$key] = false;
        }
    }
}
                `idnewsrcp` int(10) NOT NULL DEFAULT "0",
                `idclient` int(10) NOT NULL DEFAULT "0",
                `idlang` int(10) NOT NULL DEFAULT "0",
                `email` varchar(255) DEFAULT NULL,
                `confirmed` tinyint(1) NOT NULL DEFAULT "0",
                `confirmeddate` datetime NOT NULL DEFAULT "0000-00-00 00:00:00",
                `lastaction` varchar(32) DEFAULT NULL,
                `name` varchar(255) DEFAULT NULL,
                `hash` varchar(32) NOT NULL,
                `deactivated` tinyint(1) NOT NULL DEFAULT "0",
                `news_type` tinyint(1) NOT NULL DEFAULT "0",
                `author` varchar(32) NOT NULL,
                `created` datetime NOT NULL DEFAULT "0000-00-00 00:00:00",
                `lastmodified` datetime NOT NULL DEFAULT "0000-00-00 00:00:00",
                `modifiedby` varchar(32) NOT NULL,
                PRIMARY KEY (`idnewsrcp`)
            )';
    $db->query($sql);
}
if (!$db) {
    $db = new DB_Contenido();
}
#$sql = 'SELECT idnews
#        FROM ' . $cfg['sql']['sqlprefix'] . '_news
#        LIMIT 0, 1';
#if (!$db->query($sql)) {
$sql = 'SHOW TABLES LIKE "' . $cfg['sql']['sqlprefix'] . '_news"';
$db->query($sql);
if (!$db->num_rows()) {
    pinlCreateDbTables($db, $cfg);
}