/**
  * @Given /^the newsletter subscription for "([^"]*)" (should|should not) be verified$/
  */
 public function theNewsletterSubscriptionForIsVerified($email, $shouldOrNot = '')
 {
     $recipient = \Recipient::get()->filter('Email', $email)->First();
     assertNotNull($recipient, 'Could not find Recipient with ' . $email);
     $assertion = $shouldOrNot == 'should' ? 'assertTrue' : 'assertFalse';
     $assertion((bool) $recipient->Verified);
 }
 /**
  * Creates a single new log item
  * @param $idnewsjob    integer ID of corresponding newsletter send job
  * @param $idnewsrcp    integer ID of recipient
  * @param $rcp_name    string    Name of the recipient (-> recipient may be deleted)
  * @param $rcp_email    string    E-Mail of the recipient (-> recipient may be deleted)
  */
 public function create($idnewsjob, $idnewsrcp)
 {
     global $client, $lang, $auth;
     $idnewsjob = Contenido_Security::toInteger($idnewsjob);
     $idnewsrcp = Contenido_Security::toInteger($idnewsrcp);
     $client = Contenido_Security::toInteger($client);
     $lang = Contenido_Security::toInteger($lang);
     $this->resetQuery();
     $this->setWhere("idnewsjob", $idnewsjob);
     $this->setWhere("idnewsrcp", $idnewsrcp);
     $this->query();
     if ($oItem = $this->next()) {
         return $oItem;
     }
     $oRecipient = new Recipient();
     if ($oRecipient->loadByPrimaryKey($idnewsrcp)) {
         $oItem = parent::create();
         $oItem->set("idnewsjob", $idnewsjob);
         $oItem->set("idnewsrcp", $idnewsrcp);
         $sEMail = $oRecipient->get("email");
         $sName = $oRecipient->get("name");
         if ($sName == "") {
             $oItem->set("rcpname", $sEMail);
         } else {
             $oItem->set("rcpname", $sName);
         }
         $oItem->set("rcpemail", $sEMail);
         $oItem->set("rcphash", $oRecipient->get("hash"));
         $oItem->set("rcpnewstype", $oRecipient->get("news_type"));
         $oItem->set("status", "pending");
         $oItem->set("created", date("Y-m-d H:i:s"), false);
         $oItem->store();
         return $oItem;
     } else {
         return false;
     }
 }
 /**
  * emailing admin and or running custom code to update newsletter status
  * @param DataObject $order Order
  * @return Boolean
  **/
 public function doStep(Order $order)
 {
     $billingAddress = $order->BillingAddress();
     $member = $order->Member();
     if ($member && $billingAddress) {
         $recipient = Recipient::get()->filter(array("Email" => $billingAddress->Email))->first();
         if (!$recipient) {
             $recipient = Recipient::create();
             $recipient->Email = $billingAddress->Email;
         }
         $recipient->FirstName = $billingAddress->FirstName;
         $recipient->Surname = $billingAddress->Surname;
         $recipient->write();
         $mailingListToAdd = $member->MailingLists();
         DB::query("DELETE FROM MailingList_Recipients WHERE RecipientID = " . $recipient->ID . ";");
         if ($mailingListToAdd->count()) {
             $recipientsMailingLists = $recipient->MailingLists();
             $recipientsMailingLists->addMany($mailingListToAdd->map("ID", "ID")->toArray());
             if ($this->SendMessageToAdmin) {
                 $member = $order->Member();
                 if ($member) {
                     if ($member->NewsletterSignup) {
                         $from = Order_Email::get_from_email();
                         $subject = _t("NewsletterSignup.NEWSLETTERREGISTRATIONUPDATE", "newsletter registration update");
                         $billingAddressOutput = "";
                         if ($billingAddress) {
                             $billingAddressOutput = $billingAddress->renderWith("Order_AddressBilling");
                         }
                         $body = "\n\t\t\t\t\t\t\t\t" . _t("NewsletterSignup.EMAIL", "Email") . ": <strong>" . $member->Email . "</strong>" . "<br /><br />" . _t("NewsletterSignup.SIGNUP", "Signed Up") . ": <strong>" . ($member->NewsletterSignup ? _t("NewsletterSignup.YES", "Yes") : _t("NewsletterSignup.NO", "No")) . "</strong>" . "<br /><br />" . $billingAddressOutput;
                         $email = new Email($from, $to = Order_Email::get_from_email(), $subject, $body);
                         $email->send();
                         //copy!
                         if ($this->SendCopyTo) {
                             $email = new Email($from, $to = $this->SendCopyTo, $subject, $body);
                             $email->send();
                         }
                     }
                     //this can be used to connect with third parties (e.g. )
                 }
             }
         }
         $this->extend("updateNewsletterStatus", $member, $recipient);
     }
     return true;
 }
 /** Send an email with a link to unsubscribe from all this user's newsletters */
 public function sendUnsubscribeLink(SS_HTTPRequest $request)
 {
     //get the form object (we just need its name to set the session message)
     $form = NewsletterContentControllerExtension::getUnsubscribeFormObject($this);
     $email = Convert::raw2sql($request->requestVar('email'));
     $recipient = Recipient::get()->filter('Email', $email)->First();
     if ($recipient) {
         //get the IDs of all the Mailing Lists this user is subscribed to
         $lists = $recipient->MailingLists()->column('ID');
         $listIDs = implode(',', $lists);
         $days = UnsubscribeController::get_days_unsubscribe_link_alive();
         if ($recipient->ValidateHash) {
             $recipient->ValidateHashExpired = date('Y-m-d H:i:s', time() + 86400 * $days);
             $recipient->write();
         } else {
             $recipient->generateValidateHashAndStore($days);
         }
         $templateData = array('FirstName' => $recipient->FirstName, 'UnsubscribeLink' => Director::absoluteBaseURL() . "unsubscribe/index/" . $recipient->ValidateHash . "/{$listIDs}");
         //send unsubscribe link email
         $email = new Email();
         $email->setTo($recipient->Email);
         $from = Email::getAdminEmail();
         $email->setFrom($from);
         $email->setTemplate('UnsubscribeLinkEmail');
         $email->setSubject(_t('Newsletter.ConfirmUnsubscribeSubject', "Confirmation of your unsubscribe request"));
         $email->populateTemplate($templateData);
         $email->send();
         $form->sessionMessage(_t('Newsletter.GoodEmailMessage', 'You have been sent an email containing an unsubscribe link'), "good");
     } else {
         //not found Recipient, just reload the form
         $form->sessionMessage(_t('Newsletter.BadEmailMessage', 'Email address not found'), "bad");
     }
     Controller::curr()->redirectBack();
 }
 /**
  * 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;
     }
 }
    if (!$timeframe) {
        $timeframe = 30;
    }
    $purgedrecipients = $oRecipients->purge($timeframe);
    /* backslashdollar: There is a problem translating \$ - it is either not recognized or translated correctly (using poEdit) */
    if ($purgedrecipients > 0) {
        $sNotis = $notification->messageBox("info", sprintf(str_replace("backslashdollar", "\$", i18n("%1backslashdollard recipients, which hasn't been confirmed since more than %2backslashdollard days has been removed.", $plugin_name)), $purgedrecipients, $timeframe), 0);
    } else {
        $sNotis = $notification->messageBox("info", sprintf(str_replace("backslashdollar", "\$", i18n("There are no recipients, which hasn't been confirmed since more than %2backslashdollard days has been removed.", $plugin_name)), 0, $timeframe), 0);
    }
    $recipient = new Recipient();
    $oPage->setReload();
} else {
    $recipient = new Recipient($idrecipient);
}
if ($recipient->virgin == false && $recipient->get("idclient") == $client && $recipient->get("idlang") == $lang) {
    if ($action == "recipients_save" && $perm->have_perm_area_action($area, $action)) {
        $oPage->setReload();
        $aMessages = array();
        $name = stripslashes($name);
        $email = stripslashes($email);
        $confirmed = (int) $confirmed;
        $deactivated = (int) $deactivated;
        $newstype = (int) $newstype;
        $recipient->set("name", $name);
        if (!isValidMail($email)) {
            $aMessages[] = i18n("Please specify a valid e-mail address", $plugin_name);
        } else {
            $email = strtolower($email);
            // e-mail always in lower case
            if ($recipient->get("email") != $email) {
 function processQueue($newsletterID, $lockFile)
 {
     set_time_limit(0);
     //no time limit for running process
     if (!empty($newsletterID)) {
         $newsletter = Newsletter::get()->byID($newsletterID);
         if (!empty($newsletter)) {
             //try to clean up any stuck items
             $this->cleanUpStalledQueue($newsletterID);
             // Start a transaction
             $conn = DB::getConn();
             if ($conn->supportsTransactions()) {
                 $conn->transactionStart();
             }
             $queueItemsList = array();
             try {
                 //get the first X items to process
                 $queueItems = SendRecipientQueue::get()->filter(array('NewsletterID' => $newsletterID, 'Status' => 'Scheduled'))->sort('Created ASC')->limit(self::$items_to_batch_process);
                 //set them all to "in process" at once
                 foreach ($queueItems as $item) {
                     $item->Status = 'InProgress';
                     $queueItemsList[] = $item->write();
                 }
                 // Commit transaction
                 if ($conn->supportsTransactions()) {
                     $conn->transactionEnd();
                 }
             } catch (Exception $e) {
                 // Rollback
                 if ($conn->supportsTransactions()) {
                     $conn->transactionRollback();
                 }
                 //retry the processing
                 SS_Log::log(new Exception("newsletter send out restart because of error"), SS_Log::ERR);
                 $this->processQueueOnShutdown($newsletterID);
             }
             //fetch the queue items from the database again (after writing in-process to them)
             $queueItems2 = null;
             if (!empty($queueItemsList)) {
                 $queueItems2 = SendRecipientQueue::get()->filter(array('ID' => $queueItemsList));
             }
             //do the actual mail out
             if (!empty($queueItems2) && $queueItems2->count() > 0) {
                 //fetch all the recipients at once in one query
                 $recipients = Recipient::get()->filter(array('ID' => $queueItems2->column('RecipientID')));
                 if ($recipients->count() > 0) {
                     $recipientsMap = array();
                     foreach ($recipients as $r) {
                         $recipientsMap[$r->ID] = $r;
                     }
                     //send out the mails
                     foreach ($queueItems2 as $item) {
                         try {
                             $item->send($newsletter, $recipientsMap[$item->RecipientID]);
                         } catch (Exception $e) {
                             $item->Status = 'Failed';
                             $item->write();
                         }
                     }
                 }
                 unlink($lockFile);
                 //do more processing, in case there are more items to process, do nothing if we've reached the end
                 $this->processQueueOnShutdown($newsletterID);
                 //wait to avoid overloading the email server with too many emails that look like spam
                 if (!empty(self::$throttle_batch_delay)) {
                     sleep(self::$throttle_batch_delay);
                 }
             } else {
                 //mark the send process as complete
                 $newsletter->SentDate = SS_Datetime::now()->getValue();
                 $newsletter->Status = 'Sent';
                 $newsletter->write();
                 unlink($lockFile);
             }
         }
     }
 }
 /**
  * Subscribes a given email address to the {@link NewsletterType} associated
  * with this page
  *
  * @param array
  * @param Form
  * @param SS_HTTPRequest
  *
  * @return Redirection
  */
 public function doSubscribe($data, $form, $request)
 {
     if (!isset($data['Email'])) {
         $form->addErrorMessage('Email', _t('Newsletter.ValidEmail', 'Please enter your email address'));
         return $this->redirectBack();
     } elseif (!Email::is_valid_address($data['Email'])) {
         $form->addErrorMessage('Email', _t('Newsletter.InvalidEmailAddress', '"{field}" field is invalid', array('field' => 'Email')));
         return $this->redirectBack();
     }
     // check to see if member already exists
     $recipient = Recipient::get()->find('Email', $data['Email']);
     if (!$recipient) {
         $recipient = new Recipient();
         $recipient->Verified = false;
         //set new recipient as un-verified, if they subscribe through the website
     }
     $form->saveInto($recipient);
     $recipient->write();
     $days = self::get_days_verification_link_alive();
     if ($recipient->ValidateHash) {
         $recipient->ValidateHashExpired = date('Y-m-d H:i:s', time() + 86400 * $days);
         //extend the expiry date
         //default 2 days for validating
         $recipient->write();
     } else {
         $recipient->generateValidateHashAndStore($days);
         //default 2 days for validating
     }
     $mailinglists = new ArrayList();
     if (isset($data["NewsletterSelection"])) {
         foreach ($data["NewsletterSelection"] as $listID) {
             $mailinglist = DataObject::get_by_id("MailingList", $listID);
             if ($mailinglist && $mailinglist->exists()) {
                 //remove recipient from unsubscribe if needed
                 //$this->removeUnsubscribe($newsletterType,$recipient);
                 $mailinglists->push($mailinglist);
                 $recipient->MailingLists()->add($mailinglist);
             }
         }
     } else {
         // if the page has associate with one newsletter type, it won't appear in front form, but the
         // recipient needs to be added to the related mailling list.
         if ($this->MailingLists && ($listIDs = explode(",", $this->MailingLists))) {
             foreach ($listIDs as $listID) {
                 $mailinglist = DataObject::get_by_id("MailingList", $listID);
                 if ($mailinglist && $mailinglist->exists()) {
                     //remove recipient from unsubscribe records if the recipient
                     // unsubscribed from mailing list before
                     //$this->removeUnsubscribe($mailingList,$recipient);
                     $mailinglists->push($mailinglist);
                     $recipient->MailingLists()->add($mailinglist);
                 }
             }
         } else {
             user_error('No Newsletter type selected to subscribe to', E_USER_WARNING);
         }
     }
     $recipientInfoSection = $form->Fields()->fieldByName('MemberInfoSection')->FieldList();
     $emailableFields = new FieldList();
     if ($recipientInfoSection) {
         foreach ($recipientInfoSection as $field) {
             if (is_array($field->Value()) && is_a($field, 'SimpleImageField')) {
                 $funcName = $field->Name();
                 $value = $recipient->{$funcName}()->CMSThumbnail()->Tag();
                 $field->EmailalbeValue = $value;
             } else {
                 $field->EmailalbeValue = $field->Value();
             }
             $emailableFields->push($field);
         }
     }
     $templateData = array('FirstName' => $recipient->FirstName, 'MemberInfoSection' => $emailableFields, 'MailingLists' => $mailinglists, 'SubscriptionVerificationLink' => Controller::join_links($this->Link('subscribeverify'), "/" . $recipient->ValidateHash), 'HashText' => substr($recipient->ValidateHash, 0, 10) . "******" . substr($recipient->ValidateHash, -10), 'SiteConfig' => $this->SiteConfig(), 'DaysExpired' => SubscriptionPage::get_days_verification_link_alive());
     //Send Verification Email
     $email = new Email();
     $email->setTo($recipient->Email);
     $from = $this->NotificationEmailFrom ? $this->NotificationEmailFrom : Email::getAdminEmail();
     $email->setFrom($from);
     $email->setTemplate('SubscriptionVerificationEmail');
     $email->setSubject(_t('Newsletter.VerifySubject', "Thanks for subscribing to our mailing lists, please verify your email"));
     $email->populateTemplate($templateData);
     $email->send();
     $url = $this->Link('submitted') . "/" . $recipient->ID;
     $this->redirect($url);
 }
 /**
  * @param $mailbox
  * @param $emailID
  * @param $isBounce
  */
 private function isBounced($mailbox, $emailID, $isBounce)
 {
     $stripTags = array('<', '>');
     // Some servers reply with "<*****@*****.**>", so, let's strip that.
     $to = str_replace($stripTags, array('', ''), $isBounce[1]);
     $error = $isBounce[2];
     /** @var Recipient $recipient */
     $recipient = Recipient::get()->filter(array("Email" => $to))->first();
     if ($recipient->BouncedCount == self::$blacklistLimit) {
         // When we reach the blacklistLimit, just blacklist this address.
         $recipient->BlacklistedEmail = true;
         $recipient->write();
     } else {
         // Otherwise, just up the bouncedCount.
         $recipient->BouncedCount = $recipient->BouncedCount + 1;
         $recipient->write();
         /** @var NewsletterEmailBounceRecord $record Record this bounce in the NewsletterEmailBounceRecord class. */
         $record = NewsletterEmailBounceRecord::get()->filter(array("BounceEmail" => $to));
         if (!$record->count()) {
             $record = NewsletterEmailBounceRecord::create();
             $record->BounceEmail = $to;
             $record->BounceMessage = $error;
             $record->RecipientID = $recipient->ID;
         } else {
             $record = $record->first();
         }
         $record->LastBounceTime = SS_Datetime::create()->now();
         $record->write();
     }
     // Set the e-mail flag
     imap_setflag_full($mailbox, $emailID, '\\flagged', ST_UID);
     // Also mark it for deletion.
     imap_delete($mailbox, $emailID, ST_UID);
     // And up the bounces counter.
     $this->bounces = $this->bounces + 1;
 }
 /**
  * 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;
     }
 }