public function setUp()
 {
     parent::setUp();
     require_once 'CRM/Core/Smarty.php';
     // Templates should normally be file names, but for unit-testing it's handy to use "string:" notation
     require_once 'CRM/Core/Smarty/resources/String.php';
     civicrm_smarty_register_string_resource();
 }
Example #2
0
 public function __construct($name)
 {
     // Templates injected into regions should normally be file names, but sometimes inline notation is handy.
     require_once 'CRM/Core/Smarty/resources/String.php';
     civicrm_smarty_register_string_resource();
     $this->_name = $name;
     $this->_snippets = array();
     // Placeholder which represents any of the default content generated by the main Smarty template
     $this->add(array('name' => 'default', 'type' => 'markup', 'markup' => '', 'weight' => 0));
     $this->_isSorted = TRUE;
 }
 public function setUp()
 {
     parent::setUp();
     list($this->basedir, $this->container, $this->mapper) = $this->_createMapper();
     $cache = new CRM_Utils_Cache_Arraycache(array());
     $this->res = new CRM_Core_Resources($this->mapper, $cache, NULL);
     $this->res->setCacheCode('resTest');
     CRM_Core_Resources::singleton($this->res);
     // Templates injected into regions should normally be file names, but for unit-testing it's handy to use "string:" notation
     require_once 'CRM/Core/Smarty/resources/String.php';
     civicrm_smarty_register_string_resource();
 }
Example #4
0
 /** 
  * run this page (figure out the action needed and perform it).
  * 
  * @return void
  */
 function run()
 {
     require_once 'CRM/Mailing/BAO/Mailing.php';
     $session =& CRM_Core_Session::singleton();
     $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', CRM_Core_DAO::$_nullObject, false, 'text');
     $type = CRM_Utils_Request::retrieve('type', 'String', CRM_Core_DAO::$_nullObject, false, 'text');
     $options = array();
     $session->getVars($options, "CRM_Mailing_Controller_Send_{$qfKey}");
     //get the options if control come from search context, CRM-3711
     if (empty($options)) {
         $session->getVars($options, "CRM_Contact_Controller_Search_{$qfKey}");
     }
     // FIXME: the below and CRM_Mailing_Form_Test::testMail()
     // should be refactored
     $fromEmail = null;
     $mailing =& new CRM_Mailing_BAO_Mailing();
     if (!empty($options)) {
         $mailing->id = $options['mailing_id'];
         $fromEmail = $options['from_email'];
     }
     $mailing->find(true);
     CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
     if (defined('CIVICRM_MAIL_SMARTY')) {
         require_once 'CRM/Core/Smarty/resources/String.php';
         civicrm_smarty_register_string_resource();
     }
     // get and format attachments
     require_once 'CRM/Core/BAO/File.php';
     $attachments =& CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
     //get details of contact with token value including Custom Field Token Values.CRM-3734
     $returnProperties = $mailing->getReturnProperties();
     $params = array('contact_id' => $session->get('userID'));
     $details = $mailing->getDetails($params, $returnProperties);
     $mime =& $mailing->compose(null, null, null, $session->get('userID'), $fromEmail, $fromEmail, true, $details[0][$session->get('userID')], $attachments);
     // there doesn't seem to be a way to get to Mail_Mime's text and HTML
     // parts, so we steal a peek at Mail_Mime's private properties, render
     // them and exit
     // note that preview does not display any attachments
     $mime->get();
     if ($type == 'html') {
         header('Content-Type: text/html; charset=utf-8');
         print $mime->_htmlbody;
     } else {
         header('Content-Type: text/plain; charset=utf-8');
         print $mime->_txtbody;
     }
     exit;
 }
Example #5
0
 public static function registerStringResource()
 {
     require_once 'CRM/Core/Smarty/resources/String.php';
     civicrm_smarty_register_string_resource();
 }
Example #6
0
 /**
  * Send an email from the specified template based on an array of params
  *
  * @param array $params  a string-keyed array of function params, see function body for details
  *
  * @return array  of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates
  */
 static function sendTemplate($params)
 {
     $defaults = array('groupName' => null, 'valueName' => null, 'contactId' => null, 'tplParams' => array(), 'from' => null, 'toName' => null, 'toEmail' => null, 'cc' => null, 'bcc' => null, 'replyTo' => null, 'attachments' => null, 'isTest' => false);
     $params = array_merge($defaults, $params);
     if (!$params['groupName'] or !$params['valueName']) {
         CRM_Core_Error::fatal(ts("Message template's option group and/or option value missing."));
     }
     // fetch the three elements from the db based on option_group and option_value names
     $query = 'SELECT msg_subject subject, msg_text text, msg_html html
               FROM civicrm_msg_template mt
               JOIN civicrm_option_value ov ON workflow_id = ov.id
               JOIN civicrm_option_group og ON ov.option_group_id = og.id
               WHERE og.name = %1 AND ov.name = %2 AND mt.is_default = 1';
     $sqlParams = array(1 => array($params['groupName'], 'String'), 2 => array($params['valueName'], 'String'));
     $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
     $dao->fetch();
     if (!$dao->N) {
         CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName'])));
     }
     $subject = $dao->subject;
     $text = $dao->text;
     $html = $dao->html;
     // add the test banner (if requested)
     if ($params['isTest']) {
         $query = "SELECT msg_subject subject, msg_text text, msg_html html\n                      FROM civicrm_msg_template mt\n                      JOIN civicrm_option_value ov ON workflow_id = ov.id\n                      JOIN civicrm_option_group og ON ov.option_group_id = og.id\n                      WHERE og.name = 'msg_tpl_workflow_meta' AND ov.name = 'test_preview' AND mt.is_default = 1";
         $testDao = CRM_Core_DAO::executeQuery($query);
         $testDao->fetch();
         $subject = $testDao->subject . $subject;
         $text = $testDao->text . $text;
         $html = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $html);
     }
     // replace tokens in the three elements
     require_once 'CRM/Utils/Token.php';
     require_once 'CRM/Core/BAO/Domain.php';
     require_once 'api/v2/Contact.php';
     require_once 'CRM/Mailing/BAO/Mailing.php';
     $domain = CRM_Core_BAO_Domain::getDomain();
     if ($params['contactId']) {
         $contactParams = array('contact_id' => $params['contactId']);
         $contact =& civicrm_contact_get($contactParams);
     }
     // replace tokens in subject as if it was the text body
     foreach (array('subject' => 'text', 'text' => 'text', 'html' => 'html') as $type => $tokenType) {
         if (!${$type}) {
             continue;
         }
         // skip all of the below if the given part is missing
         $bodyType = "body_{$tokenType}";
         $mailing = new CRM_Mailing_BAO_Mailing();
         $mailing->{$bodyType} = ${$type};
         $tokens = $mailing->getTokens();
         ${$type} = CRM_Utils_Token::replaceDomainTokens(${$type}, $domain, true, $tokens[$tokenType]);
         if ($params['contactId']) {
             ${$type} = CRM_Utils_Token::replaceContactTokens(${$type}, $contact, false, $tokens[$tokenType]);
         }
     }
     // strip whitespace from ends and turn into a single line
     $subject = "{strip}{$subject}{/strip}";
     // parse the three elements with Smarty
     require_once 'CRM/Core/Smarty/resources/String.php';
     civicrm_smarty_register_string_resource();
     $smarty =& CRM_Core_Smarty::singleton();
     foreach ($params['tplParams'] as $name => $value) {
         $smarty->assign($name, $value);
     }
     foreach (array('subject', 'text', 'html') as $elem) {
         ${$elem} = $smarty->fetch("string:{${$elem}}");
     }
     // send the template, honouring the target user’s preferences (if any)
     $sent = false;
     if ($params['toEmail']) {
         $contactParams = array('email' => $params['toEmail']);
         $contact =& civicrm_contact_get($contactParams);
         $prefs = array_pop($contact);
         if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') {
             $text = null;
         }
         if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') {
             $html = null;
         }
         require_once 'CRM/Utils/Mail.php';
         $sent = CRM_Utils_Mail::send($params['from'], $params['toName'], $params['toEmail'], $subject, $text, $params['cc'], $params['bcc'], $params['replyTo'], $html, $params['attachments']);
     }
     return array($sent, $subject, $text, $html);
 }
function sendInvoiceMail($email, $displayName, $fromEmail, $fileName, $filePathName, $obj, $contactID, $contribution)
{
    ## getting contact detail
    require_once 'api/v2/Contact.php';
    $contactParams = array('id' => $contactID);
    $contact =& civicrm_contact_get($contactParams);
    ## Check the contribution type to work out which email template we should be using
    //print_r($contribution); exit;
    $contributionTypeId = $contribution->contribution_type_id;
    if ($contributionTypeId == '2') {
        ##  Contribution Type - Membership
        $emailTemplateName = 'Membership Invoice';
        $params['bcc'] = '*****@*****.**';
    }
    if ($contributionTypeId == '4') {
        ##  Contribution Type - Events
        $emailTemplateName = 'Participant Invoice';
        $params['bcc'] = '*****@*****.**';
    }
    ## getting invoice mail template
    $query = "SELECT * FROM civicrm_msg_template WHERE msg_title = '{$emailTemplateName}' AND is_active=1";
    $dao = CRM_Core_DAO::executeQuery($query);
    if (!$dao->fetch()) {
        print "Not able to get Email Template";
        exit;
    }
    $text = $dao->msg_text;
    $html = $dao->msg_html;
    $subject = $dao->msg_subject;
    ###################################################
    require_once "CRM/Mailing/BAO/Mailing.php";
    $mailing = new CRM_Mailing_BAO_Mailing();
    $mailing->body_text = $text;
    $mailing->body_html = $html;
    $tokens = $mailing->getTokens();
    require_once "CRM/Utils/Token.php";
    $subject = CRM_Utils_Token::replaceDomainTokens($subject, $domain, true, $tokens['text']);
    $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, true, $tokens['text']);
    $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']);
    if ($contactID) {
        $subject = CRM_Utils_Token::replaceContactTokens($subject, $contact, false, $tokens['text']);
        $text = CRM_Utils_Token::replaceContactTokens($text, $contact, false, $tokens['text']);
        $html = CRM_Utils_Token::replaceContactTokens($html, $contact, false, $tokens['html']);
    }
    // parse the three elements with Smarty
    require_once 'CRM/Core/Smarty/resources/String.php';
    civicrm_smarty_register_string_resource();
    $smarty =& CRM_Core_Smarty::singleton();
    foreach ($params['tplParams'] as $name => $value) {
        $smarty->assign($name, $value);
    }
    ###################################################
    $params['text'] = $text;
    $params['html'] = $html;
    $params['subject'] = $subject;
    // assigning from email
    $params['from'] = $fromEmail;
    #### live ###### uncomment it
    $params['toName'] = $displayName;
    $params['toEmail'] = $email;
    #### test ###### comment it
    #$params['toName']       = "Test";
    #$params['toEmail']      = '*****@*****.**';
    # Left this in as hard coded for now as the default from email address doesn't seem to work
    # We can probably do something with the contribution type for the from email addresses
    $params['from'] = '*****@*****.**';
    $attach = array('fullPath' => $filePathName, 'mime_type' => 'pdf', 'cleanName' => $fileName);
    ## Commented out to test if attachments are causing the problem
    $params['attachments'] = array($fileName => $attach);
    require_once 'CRM/Utils/Mail.php';
    // Comment to abort sending email
    $sent = CRM_Utils_Mail::send($params);
    if ($sent) {
        echo "<br />Invoice sent <b>successfully</b> - {$email}</b><br /><br />";
        ## Insert a record into Log table - civicrm_mtl_invoice_log
        $contribution_id = $contribution->id;
    } else {
        echo "<br />Invoice sent <b>faliure</b> - <b>{$email}</b>{$sent->message}<br /><br />";
    }
    //please comment this before setting up in LIVE
    //exit;
}
Example #8
0
 /**
  * Send the mailing
  *
  * @param object $mailer        A Mail object to send the messages
  * @return void
  * @access public
  */
 public function deliver(&$mailer, $testParams = null)
 {
     require_once 'CRM/Mailing/BAO/Mailing.php';
     $mailing =& new CRM_Mailing_BAO_Mailing();
     $mailing->id = $this->mailing_id;
     $mailing->find(true);
     $eq =& new CRM_Mailing_Event_BAO_Queue();
     $eqTable = CRM_Mailing_Event_BAO_Queue::getTableName();
     $emailTable = CRM_Core_BAO_Email::getTableName();
     $contactTable = CRM_Contact_BAO_Contact::getTableName();
     $edTable = CRM_Mailing_Event_BAO_Delivered::getTableName();
     $ebTable = CRM_Mailing_Event_BAO_Bounce::getTableName();
     $query = "  SELECT      {$eqTable}.id,\n                                {$emailTable}.email as email,\n                                {$eqTable}.contact_id,\n                                {$eqTable}.hash\n                    FROM        {$eqTable}\n                    INNER JOIN  {$emailTable}\n                            ON  {$eqTable}.email_id = {$emailTable}.id\n                    LEFT JOIN   {$edTable}\n                            ON  {$eqTable}.id = {$edTable}.event_queue_id\n                    LEFT JOIN   {$ebTable}\n                            ON  {$eqTable}.id = {$ebTable}.event_queue_id\n                    WHERE       {$eqTable}.job_id = " . $this->id . "\n                        AND     {$edTable}.id IS null\n                        AND     {$ebTable}.id IS null";
     $eq->query($query);
     static $config = null;
     $mailsProcessed = 0;
     if ($config == null) {
         $config =& CRM_Core_Config::singleton();
     }
     $job_date = CRM_Utils_Date::isoToMysql($this->scheduled_date);
     $fields = array();
     if (!empty($testParams)) {
         $mailing->from_name = ts('CiviCRM Test Mailer (%1)', array(1 => $mailing->from_name));
         $mailing->subject = ts('Test Mailing:') . ' ' . $mailing->subject;
     }
     CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
     // get and format attachments
     require_once 'CRM/Core/BAO/File.php';
     $attachments =& CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
     if (defined('CIVICRM_MAIL_SMARTY')) {
         require_once 'CRM/Core/Smarty/resources/String.php';
         civicrm_smarty_register_string_resource();
     }
     // make sure that there's no more than $config->mailerBatchLimit mails processed in a run
     while ($eq->fetch()) {
         // if ( ( $mailsProcessed % 100 ) == 0 ) {
         // CRM_Utils_System::xMemory( "$mailsProcessed: " );
         // }
         if ($config->mailerBatchLimit > 0 && $mailsProcessed >= $config->mailerBatchLimit) {
             $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
             return false;
         }
         $mailsProcessed++;
         $fields[] = array('id' => $eq->id, 'hash' => $eq->hash, 'contact_id' => $eq->contact_id, 'email' => $eq->email);
         if (count($fields) == self::MAX_CONTACTS_TO_PROCESS) {
             $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
             if (!$isDelivered) {
                 return $isDelivered;
             }
             $fields = array();
         }
     }
     $isDelivered = $this->deliverGroup($fields, $mailing, $mailer, $job_date, $attachments);
     return $isDelivered;
 }
Example #9
0
 /** 
  * run this page (figure out the action needed and perform it).
  * 
  * @return void
  */
 function run($id = null, $print = true)
 {
     if (is_numeric($id)) {
         $this->_mailingID = $id;
     } else {
         $print = true;
         $this->_mailingID = CRM_Utils_Request::retrieve('id', 'Integer', CRM_Core_DAO::$_nullObject, true);
     }
     $session =& CRM_Core_Session::singleton();
     $this->_contactID = $session->get('userID');
     require_once 'CRM/Mailing/BAO/Mailing.php';
     $this->_mailing = new CRM_Mailing_BAO_Mailing();
     $this->_mailing->id = $this->_mailingID;
     require_once 'CRM/Core/Error.php';
     if (!$this->_mailing->find(true)) {
         CRM_Core_Error::statusBounce(ts('You do not have the necessary permission to approve this mailing.'));
     }
     CRM_Mailing_BAO_Mailing::tokenReplace($this->_mailing);
     if (defined('CIVICRM_MAIL_SMARTY')) {
         require_once 'CRM/Core/Smarty/resources/String.php';
         civicrm_smarty_register_string_resource();
     }
     // get and format attachments
     require_once 'CRM/Core/BAO/File.php';
     $attachments =& CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $this->_mailing->id);
     //get details of contact with token value including Custom Field Token Values.CRM-3734
     $returnProperties = $this->_mailing->getReturnProperties();
     $params = array('contact_id' => $this->_contactID);
     $details = $this->_mailing->getDetails($params, $returnProperties);
     $mime =& $this->_mailing->compose(null, null, null, $this->_contactID, $fromEmail, $fromEmail, true, $details[0][$this->_contactID], $attachments);
     if (isset($this->_mailing->body_html)) {
         $header = 'Content-Type: text/html; charset=utf-8';
         $content = $mime->getHTMLBody();
     } else {
         $header = 'Content-Type: text/plain; charset=utf-8';
         $content = $mime->getTXTBody();
     }
     if ($print) {
         header($header);
         print $content;
         CRM_Utils_System::civiExit();
     } else {
         return $content;
     }
 }
Example #10
0
 /**
  * send the message to all the contacts and also insert a
  * contact activity in each contacts record
  *
  * @param array  $contactDetails the array of contact details to send the email
  * @param string $subject      the subject of the message
  * @param string $message      the message contents
  * @param string $emailAddress use this 'to' email address instead of the default Primary address
  * @param int    $userID       use this userID if set
  * @param string $from
  * @param array  $attachments  the array of attachments if any
  * @param string $cc           cc recepient
  * @param string $bcc          bcc recepient
  * @param array $contactIds    contact ids   
  * @return array               ( sent, activityId) if any email is sent and activityId
  * @access public
  * @static
  */
 static function sendEmail(&$contactDetails, &$subject, &$text, &$html, $emailAddress, $userID = null, $from = null, $attachments = null, $cc = null, $bcc = null, &$contactIds)
 {
     // get the contact details of logged in contact, which we set as from email
     if ($userID == null) {
         $session =& CRM_Core_Session::singleton();
         $userID = $session->get('userID');
     }
     list($fromDisplayName, $fromEmail, $fromDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($userID);
     if (!$fromEmail) {
         return array(count($contactDetails), 0, count($contactDetails));
     }
     if (!trim($fromDisplayName)) {
         $fromDisplayName = $fromEmail;
     }
     //CRM-4575
     //token replacement of addressee/email/postal greetings
     // get the tokens added in subject and message
     $messageToken = self::getTokens($text);
     $subjectToken = self::getTokens($subject);
     $messageToken = array_merge($messageToken, self::getTokens($html));
     require_once 'CRM/Utils/Mail.php';
     if (!$from) {
         $from = "{$fromDisplayName} <{$fromEmail}>";
     }
     //create the meta level record first ( email activity )
     $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name');
     $activityParams = array('source_contact_id' => $userID, 'activity_type_id' => $activityTypeID, 'activity_date_time' => date('YmdHis'), 'subject' => $subject, 'details' => $text ? $text : $html, 'status_id' => 2);
     // add the attachments to activity params here
     if ($attachments) {
         // first process them
         $activityParams = array_merge($activityParams, $attachments);
     }
     $activity = self::create($activityParams);
     // get the set of attachments from where they are stored
     $attachments =& CRM_Core_BAO_File::getEntityFile('civicrm_activity', $activity->id);
     $returnProperties = array();
     if (isset($messageToken['contact'])) {
         foreach ($messageToken['contact'] as $key => $value) {
             $returnProperties[$value] = 1;
         }
     }
     if (isset($subjectToken['contact'])) {
         foreach ($subjectToken['contact'] as $key => $value) {
             if (!isset($returnProperties[$value])) {
                 $returnProperties[$value] = 1;
             }
         }
     }
     // get token details for contacts, call only if tokens are used
     $details = array();
     if (!empty($returnProperties)) {
         require_once 'CRM/Mailing/BAO/Mailing.php';
         $mailing = new CRM_Mailing_BAO_Mailing();
         list($details) = $mailing->getDetails($contactIds, $returnProperties);
     }
     // call token hook
     $tokens = array();
     CRM_Utils_Hook::tokens($tokens);
     $categories = array_keys($tokens);
     if (defined('CIVICRM_MAIL_SMARTY')) {
         $smarty =& CRM_Core_Smarty::singleton();
         require_once 'CRM/Core/Smarty/resources/String.php';
         civicrm_smarty_register_string_resource();
     }
     require_once 'CRM/Utils/Token.php';
     $sent = $notSent = array();
     foreach ($contactDetails as $values) {
         $contactId = $values['contact_id'];
         $emailAddress = $values['email'];
         if (!empty($details) && is_array($details["{$contactId}"])) {
             // unset email from details since it always returns primary email address
             unset($details["{$contactId}"]['email']);
             unset($details["{$contactId}"]['email_id']);
             $values = array_merge($values, $details["{$contactId}"]);
         }
         $tokenSubject = CRM_Utils_Token::replaceContactTokens($subject, $values, false, $subjectToken);
         $tokenSubject = CRM_Utils_Token::replaceHookTokens($tokenSubject, $values, $categories, false);
         //CRM-4539
         if ($values['preferred_mail_format'] == 'Text' || $values['preferred_mail_format'] == 'Both') {
             $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, false, $messageToken);
             $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, false);
         } else {
             $tokenText = null;
         }
         if ($values['preferred_mail_format'] == 'HTML' || $values['preferred_mail_format'] == 'Both') {
             $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, true, $messageToken);
             $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, true);
         } else {
             $tokenHtml = null;
         }
         if (defined('CIVICRM_MAIL_SMARTY')) {
             // also add the contact tokens to the template
             $smarty->assign_by_ref('contact', $values);
             $tokenText = $smarty->fetch("string:{$tokenText}");
             $tokenHtml = $smarty->fetch("string:{$tokenHtml}");
         }
         $sent = false;
         if (self::sendMessage($from, $userID, $contactId, $tokenSubject, $tokenText, $tokenHtml, $emailAddress, $activity->id, $attachments, $cc, $bcc)) {
             $sent = true;
         }
     }
     return array($sent, $activity->id);
 }
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return None
  */
 static function postProcess(&$form)
 {
     $formValues = $form->controller->exportValues($form->getName());
     // process message template
     require_once 'CRM/Core/BAO/MessageTemplates.php';
     if (CRM_Utils_Array::value('saveTemplate', $formValues) || CRM_Utils_Array::value('updateTemplate', $formValues)) {
         $messageTemplate = array('msg_text' => NULL, 'msg_html' => $formValues['html_message'], 'msg_subject' => NULL, 'is_active' => true);
         if ($formValues['saveTemplate']) {
             $messageTemplate['msg_title'] = $formValues['saveTemplateName'];
             CRM_Core_BAO_MessageTemplates::add($messageTemplate);
         }
         if ($formValues['template'] && $formValues['updateTemplate']) {
             $messageTemplate['id'] = $formValues['template'];
             unset($messageTemplate['msg_title']);
             CRM_Core_BAO_MessageTemplates::add($messageTemplate);
         }
     }
     require_once 'dompdf/dompdf_config.inc.php';
     $html = '<html><head><style>body { margin: 56px; }</style></head><body>';
     require_once 'api/v2/Contact.php';
     require_once 'CRM/Utils/Token.php';
     $tokens = array();
     CRM_Utils_Hook::tokens($tokens);
     $categories = array_keys($tokens);
     $html_message = $formValues['html_message'];
     //time being hack to strip '&nbsp;'
     //from particular letter line, CRM-6798
     self::formatMessage($html_message);
     require_once 'CRM/Activity/BAO/Activity.php';
     $messageToken = CRM_Activity_BAO_Activity::getTokens($html_message);
     $returnProperties = array();
     if (isset($messageToken['contact'])) {
         foreach ($messageToken['contact'] as $key => $value) {
             $returnProperties[$value] = 1;
         }
     }
     require_once 'CRM/Mailing/BAO/Mailing.php';
     $mailing = new CRM_Mailing_BAO_Mailing();
     if (defined('CIVICRM_MAIL_SMARTY')) {
         require_once 'CRM/Core/Smarty/resources/String.php';
         civicrm_smarty_register_string_resource();
     }
     $first = TRUE;
     foreach ($form->_contactIds as $item => $contactId) {
         $params = array('contact_id' => $contactId);
         list($contact) = $mailing->getDetails($params, $returnProperties, false);
         if (civicrm_error($contact)) {
             $notSent[] = $contactId;
             continue;
         }
         $tokenHtml = CRM_Utils_Token::replaceContactTokens($html_message, $contact[$contactId], true, $messageToken);
         $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $contact[$contactId], $categories, true);
         if (defined('CIVICRM_MAIL_SMARTY')) {
             $smarty = CRM_Core_Smarty::singleton();
             // also add the contact tokens to the template
             $smarty->assign_by_ref('contact', $contact);
             $tokenHtml = $smarty->fetch("string:{$tokenHtml}");
         }
         if ($first == TRUE) {
             $first = FALSE;
             $html .= $tokenHtml;
         } else {
             $html .= "<div STYLE='page-break-after: always'></div>{$tokenHtml}";
         }
     }
     $html .= '</body></html>';
     require_once 'CRM/Activity/BAO/Activity.php';
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Print PDF Letter', 'name');
     $activityParams = array('source_contact_id' => $userID, 'activity_type_id' => $activityTypeID, 'activity_date_time' => date('YmdHis'), 'details' => $html_message);
     if ($form->_activityId) {
         $activityParams += array('id' => $form->_activityId);
     }
     if ($form->_cid) {
         $activity = CRM_Activity_BAO_Activity::create($activityParams);
     } else {
         // create  Print PDF activity for each selected contact. CRM-6886
         $activityIds = array();
         foreach ($form->_contactIds as $contactId) {
             $activityID = CRM_Activity_BAO_Activity::create($activityParams);
             $activityIds[$contactId] = $activityID->id;
         }
     }
     foreach ($form->_contactIds as $contactId) {
         $activityTargetParams = array('activity_id' => empty($activity->id) ? $activityIds[$contactId] : $activity->id, 'target_contact_id' => $contactId);
         CRM_Activity_BAO_Activity::createActivityTarget($activityTargetParams);
     }
     require_once 'CRM/Utils/PDF/Utils.php';
     CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", 'portrait', 'letter');
     // we need to call the hook manually here since we redirect and never
     // go back to CRM/Core/Form.php
     CRM_Utils_Hook::postProcess(get_class($form), $form);
     CRM_Utils_System::civiExit(1);
 }
Example #12
0
 /**
  * Compose a message
  *
  * @param int $job_id           ID of the Job associated with this message
  * @param int $event_queue_id   ID of the EventQueue
  * @param string $hash          Hash of the EventQueue
  * @param string $contactId     ID of the Contact
  * @param string $email         Destination address
  * @param string $recipient     To: of the recipient
  * @param boolean $test         Is this mailing a test?
  * @param boolean $isForward    Is this mailing compose for forward?
  * @param string  $fromEmail    email address of who is forwardinf it.
  * @return object               The mail object
  * @access public
  */
 public function &compose($job_id, $event_queue_id, $hash, $contactId, $email, &$recipient, $test, $contactDetails, &$attachments, $isForward = false, $fromEmail = null)
 {
     require_once 'api/v2/Contact.php';
     require_once 'CRM/Utils/Token.php';
     require_once 'CRM/Activity/BAO/Activity.php';
     $config = CRM_Core_Config::singleton();
     $knownTokens = $this->getTokens();
     if ($this->_domain == null) {
         require_once 'CRM/Core/BAO/Domain.php';
         $this->_domain =& CRM_Core_BAO_Domain::getDomain();
     }
     list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward);
     //set from email who is forwarding it and not original one.
     if ($fromEmail) {
         unset($headers['From']);
         $headers['From'] = "<{$fromEmail}>";
     }
     if (defined('CIVICRM_MAIL_SMARTY')) {
         require_once 'CRM/Core/Smarty/resources/String.php';
         civicrm_smarty_register_string_resource();
     }
     if ($contactDetails) {
         $contact = $contactDetails;
     } else {
         $params = array('contact_id' => $contactId);
         $contact =& civicrm_contact_get($params);
         //CRM-4524
         $contact = reset($contact);
         if (!$contact || is_a($contact, 'CRM_Core_Error')) {
             return null;
         }
         // also call the hook to get contact details
         require_once 'CRM/Utils/Hook.php';
         CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id);
     }
     $pTemplates = $this->getPreparedTemplates();
     $pEmails = array();
     foreach ($pTemplates as $type => $pTemplate) {
         $html = $type == 'html' ? true : false;
         $pEmails[$type] = array();
         $pEmail =& $pEmails[$type];
         $template =& $pTemplates[$type]['template'];
         $tokens =& $pTemplates[$type]['tokens'];
         $idx = 0;
         if (!empty($tokens)) {
             foreach ($tokens as $idx => $token) {
                 $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id);
                 array_push($pEmail, $template[$idx]);
                 array_push($pEmail, $token_data);
             }
         } else {
             array_push($pEmail, $template[$idx]);
         }
         if (isset($template[$idx + 1])) {
             array_push($pEmail, $template[$idx + 1]);
         }
     }
     $html = null;
     if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) {
         $html =& $pEmails['html'];
     }
     $text = null;
     if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) {
         $text =& $pEmails['text'];
     }
     // push the tracking url on to the html email if necessary
     if ($this->open_tracking && $html) {
         array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL . "extern/open.php?q={$event_queue_id}\" width='1' height='1' alt='' border='0'>");
     }
     $message = new Mail_mime("\n");
     if (defined('CIVICRM_MAIL_SMARTY')) {
         $smarty = CRM_Core_Smarty::singleton();
         // also add the contact tokens to the template
         $smarty->assign_by_ref('contact', $contact);
     }
     $mailParams = $headers;
     if ($text && ($test || $contact['preferred_mail_format'] == 'Text' || $contact['preferred_mail_format'] == 'Both' || $contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))) {
         $textBody = join('', $text);
         if (defined('CIVICRM_MAIL_SMARTY')) {
             $smarty->security = true;
             $textBody = $smarty->fetch("string:{$textBody}");
             $smarty->security = false;
         }
         $mailParams['text'] = $textBody;
     }
     if ($html && ($test || ($contact['preferred_mail_format'] == 'HTML' || $contact['preferred_mail_format'] == 'Both'))) {
         $htmlBody = join('', $html);
         if (defined('CIVICRM_MAIL_SMARTY')) {
             $smarty->security = true;
             $htmlBody = $smarty->fetch("string:{$htmlBody}");
             $smarty->security = false;
         }
         $mailParams['html'] = $htmlBody;
     }
     $mailParams['attachments'] = $attachments;
     $mailingSubject = CRM_Utils_Array::value('subject', $pEmails);
     if (is_array($mailingSubject)) {
         $mailingSubject = join('', $mailingSubject);
     }
     $mailParams['Subject'] = $mailingSubject;
     $mailParams['toName'] = $contact['display_name'];
     $mailParams['toEmail'] = $email;
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::alterMailParams($mailParams);
     if (!empty($mailParams['text'])) {
         $message->setTxtBody($mailParams['text']);
     }
     if (!empty($mailParams['html'])) {
         $message->setHTMLBody($mailParams['html']);
     }
     if (!empty($mailParams['attachments'])) {
         foreach ($mailParams['attachments'] as $fileID => $attach) {
             $message->addAttachment($attach['fullPath'], $attach['mime_type'], $attach['cleanName']);
         }
     }
     $headers['To'] = "{$mailParams['toName']} <{$mailParams['toEmail']}>";
     $headers['Precedence'] = 'bulk';
     // Will test in the mail processor if the X-VERP is set in the bounced email.
     // (As an option to replace real VERP for those that can't set it up)
     $headers['X-CiviMail-Bounce'] = $verp['bounce'];
     //CRM-5058
     //token replacement of subject
     $headers['Subject'] = $mailingSubject;
     CRM_Utils_Mail::setMimeParams($message);
     $headers = $message->headers($headers);
     //get formatted recipient
     $recipient = $headers['To'];
     // make sure we unset a lot of stuff
     unset($verp);
     unset($urls);
     unset($params);
     unset($contact);
     unset($ids);
     return $message;
 }