/** * Load letter from DB, load SMTP settings * TODO: Move this to NewsletterModel or NewsletterModelEntity * * @param <string> $name - id of a letter * * @return object - letter * @since 1.0 */ public static function loadLetter($id = false) { $letter = JTable::getInstance('Newsletter', 'NewsletterTable'); $letter->load((int) $id); // If letter absent then fail. if (!$letter) { return false; } $letter = (object) $letter->getProperties(); $letter->params = (array) json_decode($letter->params); if (empty($letter->params['encoding'])) { $letter->params['encoding'] = 'utf-8'; } PlaceholderHelper::setPlaceholders($letter->params); $profileEntity = JModel::getInstance('Smtpprofile', 'NewsletterModelEntity'); $profileEntity->load((int) $letter->smtp_profile_id); $letter->smtp_profile = $profileEntity->toObject(); // Set data when using J! SMTP profile if ($letter->smtp_profile_id == NewsletterModelEntitySmtpprofile::JOOMLA_SMTP_ID) { if (!empty($letter->params['newsletter_from_email'])) { $letter->smtp_profile->from_email = $letter->params['newsletter_from_email']; } if (!empty($letter->params['newsletter_from_name'])) { $letter->smtp_profile->from_name = $letter->params['newsletter_from_name']; } if (!empty($letter->params['newsletter_to_email'])) { $letter->smtp_profile->reply_to_email = $letter->params['newsletter_to_email']; } if (!empty($letter->params['newsletter_to_name'])) { $letter->smtp_profile->reply_to_name = $letter->params['newsletter_to_name']; } } return $letter; }
/** * Set all data of the current subscriber as he has been logined in system * Don't trigger any plugins events * * @param int the subscriber id (not j! user id) * * @return boolean * @since 1.0 */ public static function emulateUser($params) { if (empty($params['email']) && empty($params['subscriber_id'])) { return false; } $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('*'); $query->from('#__newsletter_subscribers'); if (!empty($params['email'])) { $query->where('email="' . $params['email'] . '"'); } if (!empty($params['subscriber_id'])) { $query->where('subscriber_id="' . (int) $params['subscriber_id'] . '"'); } $db->setQuery($query); $subscriber = $db->loadObject(); $user = JUser::getInstance(); if (!empty($subscriber->user_id)) { // Get a database object $user->load($subscriber->user_id); } // bind data if (!empty($subscriber->subscriber_id)) { $user->set('subscriber_id', $subscriber->subscriber_id); $user->set('name', $subscriber->name); $user->set('email', $subscriber->email); $user->set('subscription_key', $subscriber->subscription_key); } // Mark the user as logged in $user->set('guest', 0); $user->set('isRoot', true); // Register the needed session variables $session = JFactory::getSession(); $session->set('user', $user); $session->set('registry', null); // fetch the dynamic data for placeholders PlaceholderHelper::setPlaceholders(array('username' => $user->name, 'useremail' => $user->email, 'userid' => !empty($subscriber->subscriber_id) ? $user->subscriber_id : null, 'subscription key' => !empty($user->subscription_key) ? $user->subscription_key : null)); return $user; }
/** * Outputs the template to the browser. * * @param boolean $cache If true, cache the output * @param array $params Associative array of attributes * * @return The rendered data * @since 1.0 */ public function render($caching = false, $params = array()) { try { // first pass of rendering. $this->parse(); $this->_template->content = $this->_renderTemplate(); // The second pass. Some dynamic data can contain placeholders. // In other words - placeholders in placeholders... $this->_parseTemplate(); $this->_template->content = $this->_renderTemplate(); $this->_parseTemplate(); $this->_template->content = $this->_renderTemplate(); // Set absolute links $this->repairLinks($this->_template->content); // Trigger plugins (GA and so on) $this->triggerEvent('onafterrender'); // Add tracking by com_newsletter if (!empty($this->tracking)) { $this->track($this->_template->content, PlaceholderHelper::getPlaceholder('subscription key'), $params['newsletter_id']); } return $this->_template->content; } catch (Exception $e) { return false; } }
/** * The main send of one letter to one or mode recipients. * The mail content generates for each user * * TODO: Need to refactor it all to: * sendNewsletterToSubscriber($nid, $sid, $options) * sentNewsletterToEmail($nid, array $emailAndName, $options) * sentLetterToEmail(array $letterData, array $emailAndName, $options) * * @param array $params newsletter_id, subscriber(object), type ('html'|'plain'), tracking(bool) * * @return object * @since 1.0 */ public function send($params = null) { // load letter to send.... if (empty($params['newsletter_id'])) { $msg = 'Newsletter id is absent. There is nothing to send.'; $this->setError($msg); throw new Exception($msg); } if (empty($params['subscriber'])) { $msg = 'Subscriber is absent. There is no one to send.'; $this->setError($msg); throw new Exception($msg); } if (empty($params['tracking'])) { $params['tracking'] = false; } // Load newsletter... $letter = JModel::getInstance('Newsletter', 'NewsletterModelEntity'); if (!$letter->load($params['newsletter_id'])) { $msg = 'Loading letter error or newsletter_id is not defined. Id:' . $params['newsletter_id']; $this->setError($msg); throw new Exception($msg); } // Load newsletter's SMTP profile... $smtpProfile = JModel::getInstance('Smtpprofile', 'NewsletterModelEntity'); if (!$smtpProfile->load($letter->smtp_profile_id)) { $msg = 'Cant load SMTP profile with id: ' . $letter->smtp_profile_id; $this->setError($msg); throw new Exception($msg); } // Load mailbox profile bound to loaded SMTP profile... $mailboxProfile = JModel::getInstance('Mailboxprofile', 'NewsletterModelEntity'); if (!$mailboxProfile->load($smtpProfile->mailbox_profile_id)) { LogHelper::addWarning('COM_NEWSLETTER_CANT_LOAD_MAILBOX_CANT_SET_SOME_HEADERS', LogHelper::CAT_MAILER, array('Mailbox profile id' => $smtpProfile->mailbox_profile_id, 'SMTP profile' => $smtpProfile->smtp_profile_name)); } // Now we have newsletter, subscriber, SMTP profile and, probably, Mailbox profile. // So we can start to send... // Use the phpMailer exceptions $sender = new MigurMailerSender(array('exceptions' => true)); $subscriber = $params['subscriber']; $type = MailHelper::filterType(!empty($params['type']) ? $params['type'] : null); if (!$type) { $msg = 'The type "' . $type . '" is not supported'; $this->setError($msg); throw new Exception($msg); } // emulate user environment SubscriberHelper::saveRealUser(); if (!SubscriberHelper::emulateUser(array('email' => $subscriber->email))) { $msg = 'The user "' . $subscriber->email . '" is absent'; $this->setError($msg); throw new Exception($msg); } PlaceholderHelper::setPlaceholder('newsletter id', $letter->newsletter_id); // render the content of letter for each user $letter->content = $this->render(array('type' => $type, 'newsletter_id' => $letter->newsletter_id, 'tracking' => true)); $letter->subject = $this->renderSubject($letter->subject); $letter->encoding = $letter->params->encoding; SubscriberHelper::restoreRealUser(); // Result object $res = new StdClass(); $res->state = false; $res->errors = array(); $res->content = $letter->content; if ($letter->content === false) { return $res; } // Add custom headers // Set the email to bounce if (!empty($mailboxProfile->username)) { $sender->AddCustomHeader('Return-Path:' . $mailboxProfile->username); $sender->AddCustomHeader('Return-Receipt-To:' . $mailboxProfile->username); $sender->AddCustomHeader('Errors-To:' . $mailboxProfile->username); } // Add info about newsleerter and subscriber $sender->AddCustomHeader(MailHelper::APPLICATION_HEADER); $sender->AddCustomHeader(MailHelper::EMAIL_NAME_HEADER . ':' . $letter->name); $sender->AddCustomHeader(MailHelper::NEWSLETTER_ID_HEADER . ':' . $params['newsletter_id']); $sender->AddCustomHeader(MailHelper::SUBSCRIBER_ID_HEADER . ':' . $subscriber->subscriber_id); // Get attachments $atts = DownloadHelper::getByNewsletterId($params['newsletter_id']); if (!$smtpProfile->isJoomlaProfile()) { $fromName = $smtpProfile->from_name; $fromEmail = $smtpProfile->from_email; $toName = $smtpProfile->reply_to_name; $toEmail = $smtpProfile->reply_to_email; } else { $jConfig = new JConfig(); $fromName = isset($letter->params->from_name) ? $letter->params->from_name : $jConfig->fromname; $fromEmail = isset($letter->params->from_email) ? $letter->params->from_email : $jConfig->mailfrom; $toName = isset($letter->params->to_name) ? $letter->params->to_name : $jConfig->fromname; $toEmail = isset($letter->params->to_email) ? $letter->params->to_email : $jConfig->mailfrom; } // Check if we dan determine all parameters... if (empty($fromName) || empty($fromEmail) || empty($toName) || empty($toEmail)) { LogHelper::addWarning('COM_NEWSLETTER_MAILER_CANT_DETERMINE SOME FROMTO', LogHelper::CAT_MAILER, array('From name' => $fromName, 'From email' => $fromEmail, 'Reply to name' => $toName, 'Reply to email' => $toEmail, 'SMTP profile' => $smtpProfile->smtp_profile_name, 'Newsletter' => $letter->name)); } try { // send the unique letter to each recipient $sendRes = $sender->send(array('letter' => $letter->toObject(), 'attach' => $atts, 'emails' => array($subscriber), 'smtpProfile' => $smtpProfile->toObject(), 'fromName' => $fromName, 'fromEmail' => $fromEmail, 'toName' => $toName, 'toEmail' => $toEmail, 'type' => $type, 'tracking' => $params['tracking'])); // If sending failed if (!$sendRes && !empty($sender->ErrorInfo)) { throw new Exception($sender->ErrorInfo); } } catch (Exception $e) { $error = JError::getError('unset'); if (!empty($error)) { $msg = $error->get('message'); $this->setError($msg); $res->errors[] = $msg; } $res->errors[] = $e->getMessage(); LogHelper::addError('COM_NEWSLETTER_MAILER_SEND_ERROR', LogHelper::CAT_MAILER, array('Error' => $e->getMessage(), 'Email' => $subscriber->email, 'Mail type' => $type, 'SMTP profile' => $smtpProfile->smtp_profile_name, 'Newsletter' => $letter->name)); return $res; } $res->state = true; return $res; }
/** * The method to bind subscriber to J! user. * To test <b>?option=com_newsletter&task=subscribe.subscribe&newsletter-name=index.php * @return void * @since 1.0 */ public function subscribe() { // Initialise variables. $app = JFactory::getApplication(); $user = JFactory::getUser(); $db = JFactory::getDbo(); // Get variables from request $name = JRequest::getString('newsletter-name', null); $email = JRequest::getString('newsletter-email', null); $html = (int) JRequest::getInt('newsletter-html', null); $listsIds = DataHelper::toArrayOfInts(JRequest::getVar('newsletter-lists', array())); $fbenabled = JRequest::getInt('fbenabled', array()); //$sendto = JRequest::getVar('sendto'); // Check token, d_i_e on error. JRequest::checkToken() or jexit('Invalid Token'); if (empty($name) || empty($email) || !in_array($html, array(0, 1)) || empty($listsIds)) { jexit('One or more parameters is missing'); } $comParams = JComponentHelper::getComponent('com_newsletter')->params; $isNew = false; // Let's check if we can create user as confirmed $confirmed = $comParams->get('users_autoconfirm') == '1'; // try to get user data from FB $fbAppId = $comParams->get('fbappid'); $fbSecret = $comParams->get('fbsecret'); if (!empty($fbAppId) && !empty($fbSecret) && !empty($fbenabled)) { $me = SubscriberHelper::getFbMe($fbAppId, $fbSecret); if (!empty($me->email) && $me->email == $email) { $confirmed = true; } } // If it is a user's email $emailsAreEqual = false; if (!empty($user->id) && $user->email == $email) { $confirmed = true; $emailsAreEqual = true; } // Get from db $subscriber = JModel::getInstance('Subscriber', 'NewsletterModelEntity'); $subscriber->load(array('email' => $email)); // If subscriber does not exist then create it if (!$subscriber->getId()) { $subscriber->create(array('name' => $name, 'email' => $email, 'state' => '1', 'html' => $html, 'user_id' => $emailsAreEqual ? $user->id : 0, 'confirmed' => $confirmed)); } else { // Update subscriber if ($confirmed == true) { // Confirm subscriber and // ALL ITS ASSIGNINGS TO LISTS $subscriber->confirm(); } if ($emailsAreEqual) { // If user is authorized $subscriber->user_id = $user->id; $subscriber->save(); } } // Add subscribers to lists, ignore if already in db $assignedListsIds = array(); foreach ($listsIds as $list) { if (!$subscriber->isInList($list)) { $subscriber->assignToList($list); $assignedListsIds[] = $list; } } // Get lists we assigned $listManager = JModel::getInstance('Lists', 'NewsletterModel'); $lists = $listManager->getItemsByIds($assignedListsIds); // Add to history all subscriptions foreach ($lists as $list) { $history = JTable::getInstance('history', 'NewsletterTable'); $history->save(array('subscriber_id' => $subscriber->getId(), 'list_id' => $list->list_id, 'newsletter_id' => NULL, 'action' => NewsletterTableHistory::ACTION_SIGNEDUP, 'date' => date('Y-m-d H:i:s'), 'text' => addslashes($list->name))); unset($history); } // Triggering the automailing process. $amManager = new NewsletterAutomailingManager(); $amManager->processSubscription(array('subscriberId' => $subscriber->subscriber_id)); // If subscriber is confirmed then no need to send emails. $message = JText::sprintf('Thank you %s for subscribing to our Newsletter!', $name); if (!$subscriber->isConfirmed()) { // Let's send newsletters $mailer = new MigurMailer(); foreach ($lists as $list) { try { $newsletter = JModel::getInstance('Newsletter', 'NewsletterModelEntity'); $newsletter->loadAsWelcoming($list->send_at_reg); PlaceholderHelper::setPlaceholder('listname', $list->name); $res = $mailer->send(array('type' => $newsletter->isFallback() ? 'plain' : $subscriber->getType(), 'subscriber' => $subscriber->toObject(), 'newsletter_id' => $newsletter->newsletter_id, 'tracking' => true)); if ($res->state) { $message = JText::sprintf('Thank you %s for subscribing to our Newsletter! You will need to confirm your subscription. There should be an email in your inbox in a few minutes!', $name); LogHelper::addMessage('COM_NEWSLETTER_WELLCOMING_NEWSLETTER_SENT_SUCCESSFULLY', LogHelper::CAT_SUBSCRIPTION, array('Email' => $subscriber->email, 'Newsletter' => $newsletter->name)); } else { throw new Exception(json_encode($res->errors)); } } catch (Exception $e) { LogHelper::addError('COM_NEWSLETTER_WELCOMING_SEND_FAILED', LogHelper::CAT_SUBSCRIPTION, array('Error' => $e->getMessage(), 'Email' => $subscriber->email, 'Newsletter' => $newsletter->name)); } } } jexit($message); }
/** * Get all column placeholders from templice. * Something like table_width1 or table_height2. * * @param string $tid Filename of template * * @return array Array of names of placeholdedrs */ public function getColumnPlaceholders($content) { $placeholders = PlaceholderHelper::fetchFromString($content); $res = array(); // Let's find column placeholders foreach ($placeholders as $ph) { if (preg_match('/^(width_column.*)|(height_column.*)$/', $ph)) { $res[] = $ph; } } return $res; }
/** * Initializes the helper * * @param boolean $force - to force initialization or not * * @return boolean * @since 1.0 */ protected static function _init($force = false) { if (!self::$_initialized || $force) { self::$placeholders = array(); self::$placeholders['username'] = array('data' => null, 'default' => ""); self::$placeholders['useremail'] = array('data' => null, 'default' => ""); self::$placeholders['userid'] = array('data' => null, 'default' => 0); self::$placeholders['image_top.alt'] = array('data' => null, 'default' => 'The top image'); self::$placeholders['image_bottom.alt'] = array('data' => null, 'default' => 'The bottom image'); self::$placeholders['sitename'] = array('data' => null, 'default' => JFactory::getConfig()->get('sitename')); self::$placeholders['table_background'] = array('data' => null, 'default' => '#FFFFFF'); self::$placeholders['text_color'] = array('data' => null, 'default' => '#000000'); self::$placeholders['unsubscription link'] = array('data' => null, 'default' => JUri::getInstance()->toString(array('host', 'scheme')) . JRoute::_('index.php?option=com_newsletter&task=subscribe.showunsubscribe', false) . '&uid=[subscription key]&nid=[newsletter id]', 'class' => 'link'); self::$placeholders['confirmation link'] = array('data' => null, 'default' => JUri::getInstance()->toString(array('host', 'scheme')) . JRoute::_('index.php?option=com_newsletter&task=subscribe.confirm', false) . '&id=[subscription key]', 'class' => 'link'); self::$_initialized = true; } return true; }
/** * Load a template file * * @param string $template The name of the template * @param string $filename The actual filename * * @return string The contents of the template * @since 1.0 */ protected function _loadTemplate($id) { // Try to find the newsletter by id. // Supported both standard and custom $model = JModel::getInstance("Template", "NewsletterModel"); $template = $model->getTemplateBy($id, 'preserve positions!'); if (!$template) { $this->setError($model->getError()); return false; } $template->params = $this->_mapParams($template->params); PlaceholderHelper::setPlaceholders($template->params); return $template; }
/** * Renders a module script and returns the results as a string * * @param string $name The name of the module to render * @param array $attribs Associative array of values * * @return string The output of the script * @since 1.0 */ public function render($name, $attribs = array(), $content = null) { return PlaceholderHelper::render($name, 'plain'); }