/**
  * Creates a newsletter job
  * @param $name        string    Specifies the name of the newsletter, the same name may be used more than once
  * @param $idnews    integer Newsletter id
  */
 public function create($iIDNews, $iIDCatArt, $sName = "")
 {
     global $client, $lang, $cfg, $cfgClient, $auth;
     $oNewsletter = new Newsletter();
     if ($oNewsletter->loadByPrimaryKey($iIDNews)) {
         $iIDNews = Contenido_Security::toInteger($iIDNews);
         $iIDCatArt = Contenido_Security::toInteger($iIDCatArt);
         $lang = Contenido_Security::toInteger($lang);
         $client = Contenido_Security::toInteger($client);
         $sName = Contenido_Security::escapeDB($sName, null);
         $oItem = parent::create();
         $oItem->set("idnews", $iIDNews);
         $oItem->set("idclient", $client);
         $oItem->set("idlang", $lang);
         if ($sName == "") {
             $oItem->set("name", $oNewsletter->get("name"));
         } else {
             $oItem->set("name", $sName);
         }
         $oItem->set("type", $oNewsletter->get("type"));
         $oItem->set("use_cronjob", $oNewsletter->get("use_cronjob"));
         $oLang = new cApiLanguage($lang);
         $oItem->set("encoding", $oLang->get("encoding"));
         unset($oLang);
         $oItem->set("idart", $oNewsletter->get("idart"));
         $oItem->set("subject", $oNewsletter->get("subject"));
         // Precompile messages
         #$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 ? '?' : '&';
         $sMessageText = $oNewsletter->get("message");
         // 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);
         }
         $oNewsletter->_replaceTag($sMessageText, false, "unsubscribe", $sPath . "unsubscribe={KEY}");
         $oNewsletter->_replaceTag($sMessageText, false, "change", $sPath . "change={KEY}");
         $oNewsletter->_replaceTag($sMessageText, false, "stop", $sPath . "stop={KEY}");
         $oNewsletter->_replaceTag($sMessageText, false, "goon", $sPath . "goon={KEY}");
         $oItem->set("message_text", $sMessageText);
         if ($oNewsletter->get("type") == "text") {
             // Text newsletter, no html message
             $sMessageHTML = "";
         } else {
             // HTML newsletter, get article content
             $sMessageHTML = $oNewsletter->getHTMLMessage();
             if ($sMessageHTML) {
                 $oNewsletter->_replaceTag($sMessageHTML, true, "name", "MAIL_NAME");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "number", "MAIL_NUMBER");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "date", "MAIL_DATE");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "time", "MAIL_TIME");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "unsubscribe", $sPath . "unsubscribe={KEY}");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "change", $sPath . "change={KEY}");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "stop", $sPath . "stop={KEY}");
                 $oNewsletter->_replaceTag($sMessageHTML, true, "goon", $sPath . "goon={KEY}");
                 // Replace plugin tags by simple MAIL_ tags
                 if (getSystemProperty("newsletter", "newsletter-recipients-plugin") == "true") {
                     if (is_array($cfg['plugins']['recipients'])) {
                         foreach ($cfg['plugins']['recipients'] as $sPlugin) {
                             plugin_include("recipients", $sPlugin . "/" . $sPlugin . ".php");
                             if (function_exists("recipients_" . $sPlugin . "_wantedVariables")) {
                                 $aPluginVars = array();
                                 $aPluginVars = call_user_func("recipients_" . $sPlugin . "_wantedVariables");
                                 foreach ($aPluginVars as $sPluginVar) {
                                     $oNewsletter->_replaceTag($sMessageHTML, true, $sPluginVar, "MAIL_" . strtoupper($sPluginVar));
                                 }
                             }
                         }
                     }
                 }
             } else {
                 // There was a problem getting html message (maybe article deleted)
                 // Cancel job generation
                 return false;
             }
         }
         $oItem->set("message_html", $sMessageHTML);
         $oItem->set("newsfrom", $oNewsletter->get("newsfrom"));
         if ($oNewsletter->get("newsfromname") == "") {
             $oItem->set("newsfromname", $oNewsletter->get("newsfrom"));
         } else {
             $oItem->set("newsfromname", $oNewsletter->get("newsfromname"));
         }
         $oItem->set("newsdate", date("Y-m-d H:i:s"), false);
         //$oNewsletter->get("newsdate"));
         $oItem->set("dispatch", $oNewsletter->get("dispatch"));
         $oItem->set("dispatch_count", $oNewsletter->get("dispatch_count"));
         $oItem->set("dispatch_delay", $oNewsletter->get("dispatch_delay"));
         // Store "send to" info in serialized array (just info)
         $aSendInfo = array();
         $aSendInfo[] = $oNewsletter->get("send_to");
         switch ($oNewsletter->get("send_to")) {
             case "selection":
                 $oGroups = new RecipientGroupCollection();
                 $oGroups->setWhere("idnewsgroup", unserialize($oNewsletter->get("send_ids")), "IN");
                 $oGroups->setOrder("groupname");
                 $oGroups->query();
                 #$oGroups->select("idnewsgroup IN ('" . implode("','", unserialize($oNewsletter->get("send_ids"))) . "')", "", "groupname");
                 while ($oGroup = $oGroups->next()) {
                     $aSendInfo[] = $oGroup->get("groupname");
                 }
                 unset($oGroup);
                 unset($oGroups);
                 break;
             case "single":
                 if (is_numeric($oNewsletter->get("send_ids"))) {
                     $oRcp = new Recipient($oNewsletter->get("send_ids"));
                     if ($oRcp->get("name") == "") {
                         $aSendInfo[] = $oRcp->get("email");
                     } else {
                         $aSendInfo[] = $oRcp->get("name");
                     }
                     $aSendInfo[] = $oRcp->get("email");
                     unset($oRcp);
                 }
                 break;
             default:
         }
         $oItem->set("send_to", serialize($aSendInfo), false);
         $oItem->set("created", date("Y-m-d H:i:s"), false);
         $oItem->set("author", $auth->auth["uid"]);
         $oItem->set("authorname", $auth->auth["uname"]);
         unset($oNewsletter);
         // Not needed anymore
         // Adds log items for all recipients and returns recipient count
         $oLogs = new cNewsletterLogCollection();
         $iRecipientCount = $oLogs->initializeJob($oItem->get($oItem->primaryKey), $iIDNews);
         unset($oLogs);
         $oItem->set("rcpcount", $iRecipientCount);
         $oItem->set("sendcount", 0);
         $oItem->set("status", 1);
         // Waiting for sending; note, that status will be set to 9, if $iRecipientCount = 0 in store() method
         $oItem->store();
         return $oItem;
     } else {
         return false;
     }
 }
$oSelSortBy = new cHTMLSelectElement("sortby");
foreach ($aFields as $sKey => $aData) {
    if (strpos($aData["type"], "sort") !== false) {
        $oOption = new cHTMLOptionElement($aData["caption"], $aData["field"]);
        $oSelSortBy->addOptionElement($aData["field"], $oOption);
    }
}
$oSelSortBy->setDefault("name");
$oSelSortOrder = new cHTMLSelectElement("sortorder");
$oSelSortOrder->autoFill(array("ASC" => i18n("Ascending", $plugin_name), "DESC" => i18n("Descending", $plugin_name)));
$oSelSortOrder->setDefault("ASC");
$oSelRestrictGroup = new cHTMLSelectElement("restrictgroup");
$oOption = new cHTMLOptionElement(i18n("-- All groups --", $plugin_name), "--all--");
$oSelRestrictGroup->addOptionElement("all", $oOption);
// Fetch recipient groups
$oRGroups = new RecipientGroupCollection();
$oRGroups->setWhere("idclient", $client);
$oRGroups->setWhere("idlang", $lang);
$oRGroups->setOrder("defaultgroup DESC, groupname ASC");
$oRGroups->query();
$i = 1;
while ($oRGroup = $oRGroups->next()) {
    if ($oRGroup->get("defaultgroup") == 1) {
        $sGroupname = $oRGroup->get("groupname") . "*";
    } else {
        $sGroupname = $oRGroup->get("groupname");
    }
    $oOption = new cHTMLOptionElement($sGroupname, $oRGroup->get("idnewsgroup"));
    $oSelRestrictGroup->addOptionElement($i, $oOption);
    $i++;
}
    if ($perm->have_perm_area_action($area, "news_create")) {
        $oLnkCopy = new Link();
        $oLnkCopy->setMultiLink("news", "", "news", "news_duplicate");
        $oLnkCopy->setCustom("idnewsletter", $idnewsletter);
        $oLnkCopy->setAlt($aMsg["CopyTitle"]);
        $oLnkCopy->setContent('<img src="' . $cfg['path']['images'] . 'but_copy.gif" border="0" title="' . $aMsg["CopyTitle"] . '" alt="' . $aMsg["CopyTitle"] . '">');
        $oMenu->setActions($iMenu, 'copy', $oLnkCopy->render());
    }
    if ($perm->have_perm_area_action($area, "news_delete")) {
        $sDelete = '<a title="' . $aMsg["DelTitle"] . '" href="javascript://" onclick="showDelMsg(' . $idnewsletter . ',\'' . addslashes($sName) . '\')"><img src="' . $cfg['path']['images'] . 'delete.gif" border="0" title="' . $aMsg["DelTitle"] . '" alt="' . $aMsg["DelTitle"] . '"></a>';
        $oMenu->setActions($iMenu, 'delete', $sDelete);
    }
}
// Check destination for sending test newsletter
if ($_REQUEST["selTestDestination"] > 0 && $perm->have_perm_area_action($area, "news_send_test")) {
    $oRcpGroups = new RecipientGroupCollection();
    $oRcpGroups->setWhere("idclient", $client);
    $oRcpGroups->setWhere("idlang", $lang);
    $oRcpGroups->setWhere($oRcpGroups->primaryKey, $_REQUEST["selTestDestination"]);
    $oRcpGroups->query();
    if ($oRcpGroup = $oRcpGroups->next()) {
        $sSendTestTarget = sprintf(i18n("Recipient group: %s", $plugin_name), $oRcpGroup->get("groupname"));
    }
    unset($oRcpGroups);
}
$aMsg["SendTestDescr"] = sprintf(i18n("Do you really want to send the newsletter to:<br><strong>%s</strong>", $plugin_name), $sSendTestTarget);
$sExecScript = '
	<script type="text/javascript">
		var sid = "' . $sess->id . '";

		// Create messageBox instance
 * 
 * {@internal 
 *   created 2004-08-01, Björn Behrens (HerrB)
 *   modified 2008-06-27, Dominik Ziegler, add security fix
 *
 *   $Id$:
 * }}
 * 
 */
if (!defined('CON_FRAMEWORK')) {
    die('Illegal call');
}
$plugin_name = 'newsletter';
// Initialization
$oPage = new cPage();
$oRGroups = new RecipientGroupCollection();
$oRGroupMembers = new RecipientGroupMemberCollection();
$oRGroup = new RecipientGroup();
$aFields = array();
$aFields["name"] = array("field" => "name", "caption" => i18n("Name", $plugin_name), "type" => "base,sort,search");
$aFields["email"] = array("field" => "email", "caption" => i18n("E-Mail", $plugin_name), "type" => "base,sort,search");
$aFields["confirmed"] = array("field" => "confirmed", "caption" => i18n("Confirmed", $plugin_name), "type" => "base");
$aFields["deactivated"] = array("field" => "deactivated", "caption" => i18n("Deactivated", $plugin_name), "type" => "base");
if ($action == "recipientgroup_create" && $perm->have_perm_area_action($area, $action)) {
    $oRGroup = $oRGroups->create(" " . i18n("-- new group --", $plugin_name));
    $_REQUEST["idrecipientgroup"] = $oRGroup->get("idnewsgroup");
    $oPage->setReload();
    $sRefreshLeftTopScript = '<script type="text/javascript">top.content.left.left_top.refreshGroupOption(\'' . $_REQUEST["idrecipientgroup"] . '\', \'add\')</script>';
    $oPage->addScript('refreshlefttop', $sRefreshLeftTopScript);
} elseif ($action == "recipientgroup_delete" && $perm->have_perm_area_action($area, $action)) {
    $oRGroups->delete($_REQUEST["idrecipientgroup"]);
 /**
  * Overriden store() method to ensure, that there is only one default group
  **/
 public function store()
 {
     global $client, $lang;
     $client = Contenido_Security::toInteger($client);
     $lang = Contenido_Security::toInteger($lang);
     if ($this->get("defaultgroup") == 1) {
         $oItems = new RecipientGroupCollection();
         $oItems->setWhere("idclient", $client);
         $oItems->setWhere("idlang", $lang);
         $oItems->setWhere("defaultgroup", 1);
         $oItems->setWhere("idnewsgroup", $this->get("idnewsgroup"), "<>");
         $oItems->query();
         while ($oItem = $oItems->next()) {
             $oItem->set("defaultgroup", 0);
             $oItem->store();
         }
     }
     parent::store();
 }
 /**
  * Creates a new recipient
  * @param string  $sEMail        Specifies the e-mail adress
  * @param string  $sName         Specifies the recipient name (optional)
  * @param int     $iConfirmed    Specifies, if the recipient is confirmed (optional)
  * @param string  $sJoinID       Specifies additional recipient group ids to join (optional, e.g. 47,12,...)
  * @param int     $iMessageType  Specifies the message type for the recipient (0 = text, 1 = html)
  */
 public function create($sEMail, $sName = "", $iConfirmed = 0, $sJoinID = "", $iMessageType = 0, $bAddToDefaultGroup = true)
 {
     global $client, $lang, $auth;
     $iConfirmed = (int) $iConfirmed;
     $iMessageType = (int) $iMessageType;
     /* Check if the e-mail adress already exists */
     $email = strtolower($email);
     // e-mail always lower case
     $this->setWhere("idclient", $client);
     $this->setWhere("idlang", $lang);
     $this->setWhere("email", $sEMail);
     $this->query();
     if ($this->next()) {
         return $this->create($sEMail . "_" . substr(md5(rand()), 0, 10), $sName, 0, $sJoinID, $iMessageType);
         // 0: Deactivate 'confirmed'
     }
     $oItem = parent::create();
     $oItem->set("idclient", $client);
     $oItem->set("idlang", $lang);
     $oItem->set("name", $sName);
     $oItem->set("email", $sEMail);
     $oItem->set("hash", substr(md5(rand()), 0, 17) . uniqid(""));
     // Generating UID, 30 characters
     $oItem->set("confirmed", $iConfirmed);
     $oItem->set("news_type", $iMessageType);
     if ($iConfirmed) {
         $oItem->set("confirmeddate", date("Y-m-d H:i:s"), false);
     }
     $oItem->set("deactivated", 0);
     $oItem->set("created", date("Y-m-d H:i:s"), false);
     $oItem->set("author", $auth->auth["uid"]);
     $oItem->store();
     $iIDRcp = $oItem->get("idnewsrcp");
     // Getting internal id of new recipient
     if ($bAddToDefaultGroup) {
         // Add this recipient to the default recipient group (if available)
         $oGroups = new RecipientGroupCollection();
         $oGroupMembers = new RecipientGroupMemberCollection();
         $oGroups->setWhere("idclient", $client);
         $oGroups->setWhere("idlang", $lang);
         $oGroups->setWhere("defaultgroup", 1);
         $oGroups->query();
         while ($oGroup = $oGroups->next()) {
             $iIDGroup = $oGroup->get("idnewsgroup");
             $oGroupMembers->create($iIDGroup, $iIDRcp);
         }
     }
     // Add to other recipient groups as well? Do so!
     if ($sJoinID != "") {
         $aJoinID = explode(",", $sJoinID);
         if (count($aJoinID) > 0) {
             foreach ($aJoinID as $iIDGroup) {
                 $oGroupMembers->create($iIDGroup, $iIDRcp);
             }
         }
     }
     return $oItem;
 }
            $aPluginFields = call_user_func("recipients_" . $sPlugin . "_wantedVariables");
            foreach ($aPluginFields as $sField) {
                //if ($_REQUEST["ckb".$sField]) {
                $aFields[$sField] = strtolower(str_replace(" ", "", $aPluginTitles[$sField]));
                $aFieldDetails[$sField]["fieldtype"] = "plugin";
                $aFieldDetails[$sField]["mandatory"] = false;
                $aFieldDetails[$sField]["type"] = "string";
                $aFieldDetails[$sField]["link"] = $sPlugin;
                $aFieldDetails[$sField]["col"] = -1;
                //}
            }
        }
    }
}
// Get groups
$oRcpGroups = new RecipientGroupCollection();
$oRcpGroups->setWhere("idclient", $client);
$oRcpGroups->setWhere("idlang", $lang);
$oRcpGroups->setOrder("groupname");
$oRcpGroups->query();
while ($oRcpGroup = $oRcpGroups->next()) {
    $sField = "g" . $oRcpGroup->get($oRcpGroup->primaryKey);
    $sGroupName = $oRcpGroup->get("groupname");
    $sGroupName = str_replace(" ", "", $sGroupName);
    $sGroupName = str_replace("\t", "", $sGroupName);
    $sGroupName = str_replace("\n", "", $sGroupName);
    $sGroupName = str_replace("\r", "", $sGroupName);
    $sGroupName = str_replace("", "", $sGroupName);
    $sGroupName = str_replace("\v;", "", $sGroupName);
    // Only PHP5!
    //$sGroupName = str_replace(str_split(" \t\n\r\0\x0B;"), "", $oRcpGroup->get("groupname"));
}
// Sort order
if ($_REQUEST["sortorder"] != "DESC") {
    $_REQUEST["sortorder"] = "ASC";
}
// Don't need to check sort by and search in criteria - just set it
$_REQUEST["sortby"] = "groupname";
// Default sort by field, possible values see above
$_REQUEST["searchin"] = "--all--";
// Free memory
unset($oUser);
unset($oClient);
##################################
# Get data
##################################
$oRcpGroups = new RecipientGroupCollection();
$oRcpGroups->setWhere("idclient", $client);
$oRcpGroups->setWhere("idlang", $lang);
if ($_REQUEST["filter"] != "") {
    if ($_REQUEST["searchin"] == "--all--" || $_REQUEST["searchin"] == "") {
        foreach ($aFields as $sKey => $aData) {
            if (strpos($aData["type"], "search") !== false) {
                $oRcpGroups->setWhereGroup("filter", $aData["field"], $_REQUEST["filter"], "LIKE");
            }
        }
        $oRcpGroups->setInnerGroupCondition("filter", "OR");
    } else {
        $oRcpGroups->setWhere($_REQUEST["searchin"], $_REQUEST["filter"], "LIKE");
    }
}
if ($_REQUEST["elemperpage"] > 0) {