*   $Id$:
 * }}
 * 
 */
if (!defined('CON_FRAMEWORK')) {
    die('Illegal call');
}
$plugin_name = 'newsletter';
##################################
# Initialization
##################################
$oPage = new cPage();
$oUser = new cApiUser($auth->auth["uid"]);
$oClientLang = new cApiClientLanguage(false, $client, $lang);
// Get idCatArt to check, if we may send a test newsletter
$lIDCatArt = (int) $oClientLang->getProperty("newsletter", "idcatart");
// Specify fields for search, sort and validation. Design makes enhancements
// using plugins possible (currently not implemented). If you are changing things here,
// remember to update include.newsletter_left_top.php, also.
// field:	Field name in the db
// caption:	Shown field name (-> user)
// base:	Elements from core code (other type may be: "plugin")
// sort: 	Element can be used to be sorted by
// search:	Element can be used to search in
$aFields = array();
$aFields["name"] = array("field" => "name", "caption" => i18n("Name", $plugin_name), "type" => "base,sort,search");
##################################
# Store settings/Get basic data
##################################
if (isset($_REQUEST['action_html']) && $_REQUEST['action_html'] == 'save_newsletter_properties' && $perm->have_perm_area_action($area, "news_html_settings")) {
    // Storing settings
 /**
  * If newsletter is HTML newsletter and necessary data available
  * returns final HTML message
  * @return string HTML message
  */
 public function getHTMLMessage()
 {
     global $lang, $client, $cfgClient, $contenido;
     if ($this->get("type") == "html" && $this->get("idart") > 0 && $this->htmlArticleExists()) {
         // Article ID
         $iIDArt = $this->get("idart");
         // Category ID
         $oClientLang = new cApiClientLanguage(false, $client, $lang);
         $iIDCat = $oClientLang->getProperty("newsletter", "html_newsletter_idcat");
         unset($oClientLang);
         // Get http username and password, if frontend is protected
         $oClient = new cApiClient($client);
         $sHTTPUserName = $oClient->getProperty("newsletter", "html_username");
         $sHTTPPassword = $oClient->getProperty("newsletter", "html_password");
         unset($oClient);
         // Get HTML
         if ($iIDArt > 0 && $iIDCat > 0) {
             // Check, if newsletter is online and set temporarely online, otherwise
             $bSetOffline = false;
             $oArticles = new cApiArticleLanguageCollection();
             $oArticles->setWhere("idlang", $this->get("idlang"));
             $oArticles->setWhere("idart", $this->get("idart"));
             $oArticles->query();
             if ($oArticle = $oArticles->next()) {
                 if ($oArticle->get("online") == 0) {
                     $bSetOffline = true;
                     $oArticle->set("online", 1);
                     $oArticle->store();
                 }
                 unset($oArticle);
             }
             unset($oArticles);
             $sFile = "front_content.php?client={$client}&lang={$lang}&idcat={$iIDCat}&idart={$iIDArt}&noex=1&send=1";
             $aURL = parse_url($cfgClient[$client]['path']['htmlpath']);
             // TODO: Other schemes than http should be tested before use!
             if ($aURL["scheme"] == "https") {
                 $iPort = 443;
                 $sTarget = "ssl://" . $aURL["host"];
             } else {
                 $iPort = 80;
                 $sTarget = $aURL["host"];
             }
             if ($aURL["port"]) {
                 $iPort = $aURL["port"];
             }
             $iErrorNo = 0;
             $sErrorMsg = "";
             if ($iHandler = fsockopen($sTarget, $iPort, $iErrorNo, $sErrorMsg, 30)) {
                 // If you use HTTP 1.1 you may get chunked data... you could solve
                 // this easily by using HTTP 1.0, but then you get a problem with
                 // virtual servers, as HTTP 1.0 doesn't use the host information...
                 fputs($iHandler, "GET " . $aURL["path"] . $sFile . " HTTP/1.1\r\n");
                 fputs($iHandler, "Host: " . $aURL["host"] . "\r\n");
                 // Maybe the website has been protected using .htaccess, then login
                 if ($sHTTPUserName != "" && $sHTTPPassword != "") {
                     fputs($iHandler, "Authorization: Basic " . base64_encode("{$sHTTPUserName}:{$sHTTPPassword}") . "\r\n");
                 }
                 fputs($iHandler, "Referer: http://" . $aURL["host"] . "\r\n");
                 fputs($iHandler, "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)\r\n");
                 fputs($iHandler, "Connection: close\r\n\r\n");
                 // Get the HTTP header and body separately
                 $sHTML = "";
                 $sHeader = "";
                 $bBody = false;
                 while (!feof($iHandler)) {
                     // $sLine = fgets($iHandler, 4096);
                     $sLine = fgets($iHandler, 1024);
                     if ($bBody) {
                         $sHTML .= $sLine;
                     } else {
                         if ($sLine == "\r\n") {
                             $bBody = true;
                         } else {
                             $sHeader .= $sLine;
                         }
                     }
                 }
                 fclose($iHandler);
                 $sHTML = $this->_deChunkHTTPBody($sHeader, $sHTML);
                 // Remove base tag
                 $sHTML = preg_replace('/<base href=(.*?)>/is', '', $sHTML, 1);
                 // Make URLs absolute
                 $sHTML = preg_replace_callback('/(url)\\((\'|\\")?(http:\\/\\/|https:\\/\\/|ftp:\\/\\/)?([A-Za-z0-9#\\.?\\-=_&\\/]*)[\'|\\"]?\\)/', array($this, "_callbackReplaceUrl"), $sHTML);
                 $sHTML = preg_replace_callback('/\\b(src|href|ftp)[ ]*=[ ]*"(http:\\/\\/|https:\\/\\/|ftp:\\/\\/)?([A-Za-z0-9#\\.?\\-=_&\\/]*)"/', array($this, "_callbackReplaceUrl"), $sHTML);
                 // Now replace anchor tags to the newsletter article itself just by the anchor
                 $sHTML = preg_replace("/(href|src)\\=(\"|\\')" . str_replace('/', '\\/', $cfgClient[$client]['path']['htmlpath']) . "front_content.php?idart=" . $iIDArt . "(.*)#(.*)(\"|\\')/", "\$1=" . "\$2" . "#" . "\$4" . "\$5", $sHTML);
                 // Now correct mailto tags
                 $sHTML = str_replace($cfgClient[$client]['path']['htmlpath'] . 'mailto:', 'mailto:', $sHTML);
                 $sReturn = $sHTML;
             } else {
                 if ($contenido) {
                     // Use i18n only in backend
                     $sErrorText = i18n("There was a problem getting the newsletter article using http. Error: %s (%s)", $plugin_name);
                 } else {
                     $sErrorText = "There was a problem getting the newsletter article using http. Error: %s (%s)";
                 }
                 $this->_sError = sprintf($sErrorText, $sErrorMsg, $iErrorNo);
                 $sReturn = false;
             }
             // Set previously offline article back to offline
             if ($bSetOffline) {
                 $oArticles = new cApiArticleLanguageCollection();
                 $oArticles->setWhere("idlang", $this->get("idlang"));
                 $oArticles->setWhere("idart", $this->get("idart"));
                 $oArticles->query();
                 if ($oArticle = $oArticles->next()) {
                     $oArticle->set("online", 0);
                     $oArticle->store();
                 }
                 unset($oArticle);
                 unset($oArticles);
             }
             return $sReturn;
         } else {
             return false;
         }
     } else {
         return false;
     }
 }
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
$iHTMLTemplateIDCat = (int) $oClientLang->getProperty("newsletter", "html_template_idcat");
if ($iHTMLTemplateIDCat < 0) {
    $iHTMLTemplateIDCat = 0;
}
$oSelHTMLTemplateIDCat->setDefault($iHTMLTemplateIDCat);
// Get html newsletter article category
$iHTMLNewsletterIDCat = (int) $oClientLang->getProperty("newsletter", "html_newsletter_idcat");
if ($iHTMLNewsletterIDCat < 0) {
    $iHTMLNewsletterIDCat = 0;
}
$oSelHTMLNewsletterIDCat->setDefault($iHTMLNewsletterIDCat);
// Global HTML newsletter option
$bHTMLNewsletter = false;
if ($iHTMLTemplateIDCat > 0 && $iHTMLNewsletterIDCat > 0 && $oClientLang->getProperty("newsletter", "html_newsletter") == "true") {
    // If necessary idcats are not specified or the option is disabled,
    // then HTML are not used
 // changing the html article, give the user only read access right for the newsletter
 // article category - the article will be shown also, if he doesn't have any rights at all...
 if ($action == "news_save" && $perm->have_perm_area_action("news", $action)) {
     // Changing e.g. \' back to ' (magic_quotes)
     $sMessage = Contenido_Security::unescapeDB($_REQUEST["txtMessage"]);
     $oNewsletter->set("message", $sMessage);
     if ($oNewsletter->get("template_idart") != $_REQUEST["selTemplate"]) {
         if ($oNewsletter->get("idart") > 0) {
             // Template has been changed: Delete old article
             // (this discards the current html content as it deletes the existing newsletter article)
             conDeleteArt($oNewsletter->get("idart"));
             $iIDArt = 0;
         }
         if ($_REQUEST["selTemplate"] > 0) {
             // Template has been changed, but specified: Store template article as new newsletter article
             $iIDArt = conCopyArticle($_REQUEST["selTemplate"], $oClientLang->getProperty("newsletter", "html_newsletter_idcat"), sprintf(i18n("Newsletter: %s", $plugin_name), $oNewsletter->get("name")));
             conMakeOnline($iIDArt, $lang);
             // Article has to be online for sending...
         }
         $oNewsletter->set("idart", $iIDArt);
         $oNewsletter->set("template_idart", $_REQUEST["selTemplate"]);
     }
     $oNewsletter->store();
 } else {
     if ($oNewsletter->get("idart") > 0) {
         // Check, if html message article and template article are still available
         $oArticles = new cApiArticleLanguageCollection();
         $oArticles->setWhere("idlang", $lang);
         $oArticles->setWhere("idart", $oNewsletter->get("idart"));
         $oArticles->query();
         if ($oArticles->count() == 0) {