/** * Send a reponse email informing the contact of the groups to which he/she * has been resubscribed. * * @param string $queue_id The queue event ID * @param array $groups List of group IDs * @param bool $is_domain Is this domain-level? * @param int $job The job ID * @return void * @access public * @static */ public static function send_resub_response($queue_id, $groups, $is_domain = false, $job) { // param is_domain is not supported as of now. $config = CRM_Core_Config::singleton(); $domain =& CRM_Core_BAO_Domain::getDomain(); $jobTable = CRM_Mailing_BAO_Job::getTableName(); $mailingTable = CRM_Mailing_DAO_Mailing::getTableName(); $contacts = CRM_Contact_DAO_Contact::getTableName(); $email = CRM_Core_DAO_Email::getTableName(); $queue = CRM_Mailing_Event_BAO_Queue::getTableName(); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $dao = new CRM_Mailing_BAO_Mailing(); $dao->query(" SELECT * FROM {$mailingTable} \n INNER JOIN {$jobTable} ON\n {$jobTable}.mailing_id = {$mailingTable}.id \n WHERE {$jobTable}.id = {$job}"); $dao->fetch(); $component = new CRM_Mailing_BAO_Component(); $component->id = $dao->resubscribe_id; $component->find(true); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $eq = new CRM_Core_DAO(); $eq->query("SELECT {$contacts}.preferred_mail_format as format,\n {$contacts}.id as contact_id,\n {$email}.email as email,\n {$queue}.hash as hash\n FROM {$contacts}\n INNER JOIN {$queue} ON {$queue}.contact_id = {$contacts}.id\n INNER JOIN {$email} ON {$queue}.email_id = {$email}.id\n WHERE {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')); $eq->fetch(); foreach ($groups as $key => $value) { if (!$value) { unset($groups[$key]); } } $message = new Mail_mime("\n"); list($addresses, $urls) = CRM_Mailing_BAO_Mailing::getVerpAndUrls($job, $queue_id, $eq->hash, $eq->email); $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); require_once 'CRM/Utils/Token.php'; if ($eq->format == 'HTML' || $eq->format == 'Both') { $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']); $html = CRM_Utils_Token::replaceResubscribeTokens($html, $domain, $groups, true, $eq->contact_id, $eq->hash); $html = CRM_Utils_Token::replaceActionTokens($html, $addresses, $urls, true, $tokens['html']); $html = CRM_Utils_Token::replaceMailingTokens($html, $dao, null, $tokens['html']); $message->setHTMLBody($html); } if (!$html || $eq->format == 'Text' || $eq->format == 'Both') { $text = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['text']); $text = CRM_Utils_Token::replaceResubscribeTokens($text, $domain, $groups, false, $eq->contact_id, $eq->hash); $text = CRM_Utils_Token::replaceActionTokens($text, $addresses, $urls, false, $tokens['text']); $text = CRM_Utils_Token::replaceMailingTokens($text, $dao, null, $tokens['text']); $message->setTxtBody($text); } require_once 'CRM/Core/BAO/MailSettings.php'; $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $eq->email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); $b =& CRM_Utils_Mail::setMimeParams($message); $h =& $message->headers($headers); $mailer =& $config->getMailer(); PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); if (is_object($mailer)) { $mailer->send($eq->email, $h, $b); CRM_Core_Error::setCallback(); } }
/** * Send a response email informing the contact of the groups from which he. * has been unsubscribed. * * @param string $queue_id * The queue event ID. * @param array $groups * List of group IDs. * @param bool $is_domain * Is this domain-level?. * @param int $job * The job ID. */ public static function send_unsub_response($queue_id, $groups, $is_domain = FALSE, $job) { $config = CRM_Core_Config::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); $jobObject = new CRM_Mailing_BAO_MailingJob(); $jobTable = $jobObject->getTableName(); $mailingObject = new CRM_Mailing_DAO_Mailing(); $mailingTable = $mailingObject->getTableName(); $contactsObject = new CRM_Contact_DAO_Contact(); $contacts = $contactsObject->getTableName(); $emailObject = new CRM_Core_DAO_Email(); $email = $emailObject->getTableName(); $queueObject = new CRM_Mailing_Event_BAO_Queue(); $queue = $queueObject->getTableName(); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $dao = new CRM_Mailing_BAO_Mailing(); $dao->query(" SELECT * FROM {$mailingTable}\n INNER JOIN {$jobTable} ON\n {$jobTable}.mailing_id = {$mailingTable}.id\n WHERE {$jobTable}.id = {$job}"); $dao->fetch(); $component = new CRM_Mailing_BAO_Component(); if ($is_domain) { $component->id = $dao->optout_id; } else { $component->id = $dao->unsubscribe_id; } $component->find(TRUE); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $eq = new CRM_Core_DAO(); $eq->query("SELECT {$contacts}.preferred_mail_format as format,\n {$contacts}.id as contact_id,\n {$email}.email as email,\n {$queue}.hash as hash\n FROM {$contacts}\n INNER JOIN {$queue} ON {$queue}.contact_id = {$contacts}.id\n INNER JOIN {$email} ON {$queue}.email_id = {$email}.id\n WHERE {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')); $eq->fetch(); if ($groups) { foreach ($groups as $key => $value) { if (!$value) { unset($groups[$key]); } } } $message = new Mail_mime("\n"); list($addresses, $urls) = CRM_Mailing_BAO_Mailing::getVerpAndUrls($job, $queue_id, $eq->hash, $eq->email); $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); if ($eq->format == 'HTML' || $eq->format == 'Both') { $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceUnsubscribeTokens($html, $domain, $groups, TRUE, $eq->contact_id, $eq->hash); $html = CRM_Utils_Token::replaceActionTokens($html, $addresses, $urls, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceMailingTokens($html, $dao, NULL, $tokens['html']); $message->setHTMLBody($html); } if (!$html || $eq->format == 'Text' || $eq->format == 'Both') { $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceUnsubscribeTokens($text, $domain, $groups, FALSE, $eq->contact_id, $eq->hash); $text = CRM_Utils_Token::replaceActionTokens($text, $addresses, $urls, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceMailingTokens($text, $dao, NULL, $tokens['text']); $message->setTxtBody($text); } $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $eq->email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); CRM_Mailing_BAO_Mailing::addMessageIdHeader($headers, 'u', $job, $queue_id, $eq->hash); $b = CRM_Utils_Mail::setMimeParams($message); $h = $message->headers($headers); $mailer = \Civi::service('pear_mail'); if (is_object($mailer)) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $mailer->send($eq->email, $h, $b); unset($errorScope); } }
/** * 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 * Array of four parameters: a boolean whether the email was sent, and the subject, text and HTML templates */ public static function sendTemplate($params) { $defaults = array('groupName' => NULL, 'valueName' => NULL, 'messageTemplateID' => NULL, 'contactId' => NULL, 'tplParams' => array(), 'from' => NULL, 'toName' => NULL, 'toEmail' => NULL, 'cc' => NULL, 'bcc' => NULL, 'replyTo' => NULL, 'attachments' => NULL, 'isTest' => FALSE, 'PDFFilename' => NULL); $params = array_merge($defaults, $params); CRM_Utils_Hook::alterMailParams($params, 'messageTemplate'); if ((!$params['groupName'] || !$params['valueName']) && !$params['messageTemplateID']) { CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing.")); } if ($params['messageTemplateID']) { // fetch the three elements from the db based on id $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template mt WHERE mt.id = %1 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['messageTemplateID'], 'String')); } else { // 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, pdf_format_id format 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) { if ($params['messageTemplateID']) { CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID']))); } else { CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName']))); } } $mailContent = array('subject' => $dao->subject, 'text' => $dao->text, 'html' => $dao->html, 'format' => $dao->format); $dao->free(); CRM_Utils_Hook::alterMailContent($mailContent); // 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(); $mailContent['subject'] = $testDao->subject . $mailContent['subject']; $mailContent['text'] = $testDao->text . $mailContent['text']; $mailContent['html'] = preg_replace('/<body(.*)$/im', "<body\\1\n{$testDao->html}", $mailContent['html']); $testDao->free(); } // replace tokens in the three elements (in subject as if it was the text body) $domain = CRM_Core_BAO_Domain::getDomain(); $hookTokens = array(); $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->subject = $mailContent['subject']; $mailing->body_text = $mailContent['text']; $mailing->body_html = $mailContent['html']; $tokens = $mailing->getTokens(); CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); $contactID = CRM_Utils_Array::value('contactId', $params); if ($contactID) { $contactParams = array('contact_id' => $contactID); $returnProperties = array(); if (isset($tokens['subject']['contact'])) { foreach ($tokens['subject']['contact'] as $name) { $returnProperties[$name] = 1; } } if (isset($tokens['text']['contact'])) { foreach ($tokens['text']['contact'] as $name) { $returnProperties[$name] = 1; } } if (isset($tokens['html']['contact'])) { foreach ($tokens['html']['contact'] as $name) { $returnProperties[$name] = 1; } } // @todo CRM-17253 don't resolve contact details if there are no tokens // effectively comment out this next (performance-expensive) line // but unfortunately testing is a bit think on the ground to that needs to // be added. list($contact) = CRM_Utils_Token::getTokenDetails($contactParams, $returnProperties, FALSE, FALSE, NULL, CRM_Utils_Token::flattenTokens($tokens), 'CRM_Core_BAO_MessageTemplate'); $contact = $contact[$contactID]; } $mailContent['subject'] = CRM_Utils_Token::replaceDomainTokens($mailContent['subject'], $domain, FALSE, $tokens['text'], TRUE); $mailContent['text'] = CRM_Utils_Token::replaceDomainTokens($mailContent['text'], $domain, FALSE, $tokens['text'], TRUE); $mailContent['html'] = CRM_Utils_Token::replaceDomainTokens($mailContent['html'], $domain, TRUE, $tokens['html'], TRUE); if ($contactID) { $mailContent['subject'] = CRM_Utils_Token::replaceContactTokens($mailContent['subject'], $contact, FALSE, $tokens['text'], FALSE, TRUE); $mailContent['text'] = CRM_Utils_Token::replaceContactTokens($mailContent['text'], $contact, FALSE, $tokens['text'], FALSE, TRUE); $mailContent['html'] = CRM_Utils_Token::replaceContactTokens($mailContent['html'], $contact, FALSE, $tokens['html'], FALSE, TRUE); $contactArray = array($contactID => $contact); CRM_Utils_Hook::tokenValues($contactArray, array($contactID), NULL, CRM_Utils_Token::flattenTokens($tokens), 'CRM_Core_BAO_MessageTemplate'); $contact = $contactArray[$contactID]; $mailContent['subject'] = CRM_Utils_Token::replaceHookTokens($mailContent['subject'], $contact, $categories, TRUE); $mailContent['text'] = CRM_Utils_Token::replaceHookTokens($mailContent['text'], $contact, $categories, TRUE); $mailContent['html'] = CRM_Utils_Token::replaceHookTokens($mailContent['html'], $contact, $categories, TRUE); } // strip whitespace from ends and turn into a single line $mailContent['subject'] = "{strip}{$mailContent['subject']}{/strip}"; // parse the three elements with Smarty $smarty = CRM_Core_Smarty::singleton(); foreach ($params['tplParams'] as $name => $value) { $smarty->assign($name, $value); } foreach (array('subject', 'text', 'html') as $elem) { $mailContent[$elem] = $smarty->fetch("string:{$mailContent[$elem]}"); } // send the template, honouring the target user’s preferences (if any) $sent = FALSE; // create the params array $params['subject'] = $mailContent['subject']; $params['text'] = $mailContent['text']; $params['html'] = $mailContent['html']; if ($params['toEmail']) { $contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1)); list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams); $prefs = array_pop($contact); if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') { $params['text'] = NULL; } if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') { $params['html'] = NULL; } $config = CRM_Core_Config::singleton(); if (isset($params['isEmailPdf']) && $params['isEmailPdf'] == 1) { $pdfHtml = CRM_Contribute_BAO_ContributionPage::addInvoicePdfToEmail($params['contributionId'], $params['contactId']); if (empty($params['attachments'])) { $params['attachments'] = array(); } $params['attachments'][] = CRM_Utils_Mail::appendPDF('Invoice.pdf', $pdfHtml, $mailContent['format']); } $pdf_filename = ''; if ($config->doNotAttachPDFReceipt && $params['PDFFilename'] && $params['html']) { if (empty($params['attachments'])) { $params['attachments'] = array(); } $params['attachments'][] = CRM_Utils_Mail::appendPDF($params['PDFFilename'], $params['html'], $mailContent['format']); if (isset($params['tplParams']['email_comment'])) { $params['html'] = $params['tplParams']['email_comment']; $params['text'] = strip_tags($params['tplParams']['email_comment']); } } $sent = CRM_Utils_Mail::send($params); if ($pdf_filename) { unlink($pdf_filename); } } return array($sent, $mailContent['subject'], $mailContent['text'], $mailContent['html']); }
static function civicrm_direct_debit_civicrm_pageRun_produceSetUpLetter($mandate_id, $contact_id, $default_template, $return_content = false, $contribution_id, $first_collectionDate) { //$sql = "SELECT * FROM civicrm_value_bank_details WHERE id = %1"; //$params = array( 1 => array( $entity_id , 'Integer' )); //$dao = CRM_Core_DAO::executeQuery( $sql, $params ); //$dao->fetch( ) //$contribution_id = $dao->entity_id; ## Get the contribution details //require_once 'CRM/Contribute/DAO/Contribution.php'; //$contribution_dao =& new CRM_Contribute_DAO_Contribution( ); //$contribution_dao->get($contribution_id); //$contribution_date = $contribution_dao->receive_date; //$contribution_date = strtotime(date("d/m/Y", strtotime($contribution_date))); //$contribution_date = date('mdY', $contribution_date); //require_once 'CRM/Core/DAO'; $fiscal_template = $default_template; $date = date('d/m/y'); //$amount = $dao->amount; require_once 'CRM/Contribute/DAO/Contribution.php'; $contrib_dao = new CRM_Contribute_DAO_Contribution(); $contrib_dao->id = $contribution_id; $contrib_dao->find(true); require_once "api/v2/Contact.php"; $contactParams = array('id' => $contact_id); $contact =& civicrm_contact_get($contactParams); require_once "CRM/Mailing/BAO/Mailing.php"; $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->body_text = $fiscal_template; $mailing->body_html = $fiscal_template; $tokens = $mailing->getTokens(); //print_r ($tokens);exit; require_once "CRM/Utils/Token.php"; if ($contact_id) { $fiscal_template = CRM_Utils_Token::replaceContactTokens($fiscal_template, $contact, false, $tokens['html']); } //$address = preg_replace("/\n/","<br>",$dao->address); $mandate_sql = "SELECT * FROM civicrm_value_bank_details bd WHERE bd.id = %1"; $mandate_params = array(1 => array($mandate_id, 'Integer')); $mandate_dao = CRM_Core_DAO::executeQuery($mandate_sql, $mandate_params); $mandate_dao->fetch(); $day_of_collection = $_ENV['collectionDayArray'][$mandate_dao->collection_day] . " of every month"; $fiscal_template = str_replace('{invoice_number}', $receipt_number, $fiscal_template); $fiscal_template = str_replace('{invoice_date}', $date, $fiscal_template); $fiscal_template = str_replace('{amount}', $contrib_dao->total_amount, $fiscal_template); $fiscal_template = str_replace('{first_collection_date}', $first_collectionDate, $fiscal_template); $fiscal_template = str_replace('{day_of_collection}', $day_of_collection, $fiscal_template); $fiscal_template = str_replace('{account_name}', $mandate_dao->account_name, $fiscal_template); $fiscal_template = str_replace('{account_number}', $mandate_dao->account_number, $fiscal_template); $fiscal_template = str_replace('{sort_code}', $mandate_dao->sort_code, $fiscal_template); $final_template = $fiscal_template; //$final_template .= "<div STYLE='page-break-after: always'></div>"; //echo $final_template;exit; $file_name = "SetUp_Letter_" . $contact_id . ".pdf"; $fileContent = self::civicrm_direct_debit_civicrm_pageRun_html2pdf($final_template, $file_name, "external"); require_once "CRM/Core/Config.php"; $config =& CRM_Core_Config::singleton(); $csv_path = $config->customFileUploadDir; //$csv_path = "sites/default/files/civicrm/custom"; $filePathName = "{$csv_path}/{$file_name}"; $handle = fopen($filePathName, 'w'); file_put_contents($filePathName, $fileContent); fclose($handle); return array('content' => $final_template, 'file_name' => $file_name); /*if ($return_content) return $final_template; else return $file_name;*/ }
/** * @param $contactId * @param $to * @param $scheduleID * @param $from * @param $tokenParams * * @return bool|null * @throws CRM_Core_Exception */ static function sendReminder($contactId, $to, $scheduleID, $from, $tokenParams) { $email = $to['email']; $phoneNumber = $to['phone']; $schedule = new CRM_Core_DAO_ActionSchedule(); $schedule->id = $scheduleID; $domain = CRM_Core_BAO_Domain::getDomain(); $result = NULL; $hookTokens = array(); if ($schedule->find(TRUE)) { $body_text = $schedule->body_text; $body_html = $schedule->body_html; $sms_body_text = $schedule->sms_body_text; $body_subject = $schedule->subject; if (!$body_text) { $body_text = CRM_Utils_String::htmlToText($body_html); } $params = array(array('contact_id', '=', $contactId, 0, 0)); list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params); //CRM-4524 $contact = reset($contact); if (!$contact || is_a($contact, 'CRM_Core_Error')) { return NULL; } // merge activity tokens with contact array $contact = array_merge($contact, $tokenParams); //CRM-5734 CRM_Utils_Hook::tokenValues($contact, $contactId); CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); $type = array('body_html' => 'html', 'body_text' => 'text', 'sms_body_text' => 'text'); foreach ($type as $bodyType => $value) { $dummy_mail = new CRM_Mailing_BAO_Mailing(); if ($bodyType == 'sms_body_text') { $dummy_mail->body_text = ${$bodyType}; } else { $dummy_mail->{${$bodyType}} = ${$bodyType}; } $tokens = $dummy_mail->getTokens(); if (${$bodyType}) { CRM_Utils_Token::replaceGreetingTokens(${$bodyType}, NULL, $contact['contact_id']); ${$bodyType} = CRM_Utils_Token::replaceDomainTokens(${$bodyType}, $domain, TRUE, $tokens[$value], TRUE); ${$bodyType} = CRM_Utils_Token::replaceContactTokens(${$bodyType}, $contact, FALSE, $tokens[$value], FALSE, TRUE); ${$bodyType} = CRM_Utils_Token::replaceComponentTokens(${$bodyType}, $contact, $tokens[$value], TRUE, FALSE); ${$bodyType} = CRM_Utils_Token::replaceHookTokens(${$bodyType}, $contact, $categories, TRUE); } } $html = $body_html; $text = $body_text; $sms_text = $sms_body_text; $smarty = CRM_Core_Smarty::singleton(); foreach (array('text', 'html', 'sms_text') as $elem) { ${$elem} = $smarty->fetch("string:{${$elem}}"); } $matches = array(); preg_match_all('/(?<!\\{|\\\\)\\{(\\w+\\.\\w+)\\}(?!\\})/', $body_subject, $matches, PREG_PATTERN_ORDER); $subjectToken = NULL; if ($matches[1]) { foreach ($matches[1] as $token) { list($type, $name) = preg_split('/\\./', $token, 2); if ($name) { if (!isset($subjectToken[$type])) { $subjectToken[$type] = array(); } $subjectToken[$type][] = $name; } } } $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken); $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $subjectToken); $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $subjectToken, TRUE); $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE); $messageSubject = $smarty->fetch("string:{$messageSubject}"); if ($schedule->mode == 'SMS' or $schedule->mode == 'User_Preference') { $session = CRM_Core_Session::singleton(); $userID = $session->get('userID') ? $session->get('userID') : $contactId; $smsParams = array('To' => $phoneNumber, 'provider_id' => $schedule->sms_provider_id, 'activity_subject' => $messageSubject); $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'SMS', 'name'); $activityParams = array('source_contact_id' => $userID, 'activity_type_id' => $activityTypeID, 'activity_date_time' => date('YmdHis'), 'subject' => $messageSubject, 'details' => $sms_text, 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name')); $activity = CRM_Activity_BAO_Activity::create($activityParams); CRM_Activity_BAO_Activity::sendSMSMessage($contactId, $sms_text, $html, $smsParams, $activity->id, $userID); } if ($schedule->mode == 'Email' or $schedule->mode == 'User_Preference') { // set up the parameters for CRM_Utils_Mail::send $mailParams = array('groupName' => 'Scheduled Reminder Sender', 'from' => $from, 'toName' => $contact['display_name'], 'toEmail' => $email, 'subject' => $messageSubject, 'entity' => 'action_schedule', 'entity_id' => $scheduleID); if (!$html || $contact['preferred_mail_format'] == 'Text' || $contact['preferred_mail_format'] == 'Both') { // render the & entities in text mode, so that the links work $mailParams['text'] = str_replace('&', '&', $text); } if ($html && ($contact['preferred_mail_format'] == 'HTML' || $contact['preferred_mail_format'] == 'Both')) { $mailParams['html'] = $html; } $result = CRM_Utils_Mail::send($mailParams); } } $schedule->free(); return $result; }
/** * 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, 'messageTemplateID' => NULL, 'contactId' => NULL, 'tplParams' => array(), 'from' => NULL, 'toName' => NULL, 'toEmail' => NULL, 'cc' => NULL, 'bcc' => NULL, 'replyTo' => NULL, 'attachments' => NULL, 'isTest' => FALSE, 'PDFFilename' => NULL); $params = array_merge($defaults, $params); if ((!$params['groupName'] || !$params['valueName']) && !$params['messageTemplateID']) { CRM_Core_Error::fatal(ts("Message template's option group and/or option value or ID missing.")); } if ($params['messageTemplateID']) { // fetch the three elements from the db based on id $query = 'SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template mt WHERE mt.id = %1 AND mt.is_default = 1'; $sqlParams = array(1 => array($params['messageTemplateID'], 'String')); } else { // 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, pdf_format_id format 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) { if ($params['messageTemplateID']) { CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID']))); } else { 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; $format = $dao->format; $dao->free(); // 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); $testDao->free(); } // replace tokens in the three elements (in subject as if it was the text body) $domain = CRM_Core_BAO_Domain::getDomain(); $hookTokens = array(); $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->body_text = $text; $mailing->body_html = $html; $tokens = $mailing->getTokens(); CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); $contactID = CRM_Utils_Array::value('contactId', $params); if ($contactID) { $contactParams = array('contact_id' => $contactID); $returnProperties = array(); if (isset($tokens['text']['contact'])) { foreach ($tokens['text']['contact'] as $name) { $returnProperties[$name] = 1; } } if (isset($tokens['html']['contact'])) { foreach ($tokens['html']['contact'] as $name) { $returnProperties[$name] = 1; } } list($contact) = CRM_Utils_Token::getTokenDetails($contactParams, $returnProperties, FALSE, FALSE, NULL, CRM_Utils_Token::flattenTokens($tokens), 'CRM_Core_BAO_MessageTemplate'); $contact = $contact[$contactID]; } $subject = CRM_Utils_Token::replaceDomainTokens($subject, $domain, TRUE, $tokens['text'], TRUE); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, TRUE, $tokens['text'], TRUE); $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html'], TRUE); if ($contactID) { $subject = CRM_Utils_Token::replaceContactTokens($subject, $contact, FALSE, $tokens['text'], FALSE, TRUE); $text = CRM_Utils_Token::replaceContactTokens($text, $contact, FALSE, $tokens['text'], FALSE, TRUE); $html = CRM_Utils_Token::replaceContactTokens($html, $contact, FALSE, $tokens['html'], FALSE, TRUE); $contactArray = array($contactID => $contact); CRM_Utils_Hook::tokenValues($contactArray, array($contactID), NULL, CRM_Utils_Token::flattenTokens($tokens), 'CRM_Core_BAO_MessageTemplate'); $contact = $contactArray[$contactID]; $subject = CRM_Utils_Token::replaceHookTokens($subject, $contact, $categories, TRUE); $text = CRM_Utils_Token::replaceHookTokens($text, $contact, $categories, TRUE); $html = CRM_Utils_Token::replaceHookTokens($html, $contact, $categories, TRUE); } // strip whitespace from ends and turn into a single line $subject = "{strip}{$subject}{/strip}"; // parse the three elements with Smarty $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; // create the params array $params['subject'] = $subject; $params['text'] = $text; $params['html'] = $html; if ($params['toEmail']) { $contactParams = array(array('email', 'LIKE', $params['toEmail'], 0, 1)); list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($contactParams); $prefs = array_pop($contact); if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'HTML') { $params['text'] = NULL; } if (isset($prefs['preferred_mail_format']) and $prefs['preferred_mail_format'] == 'Text') { $params['html'] = NULL; } $config = CRM_Core_Config::singleton(); $pdf_filename = ''; if ($config->doNotAttachPDFReceipt && $params['PDFFilename'] && $params['html']) { $pdf_filename = $config->templateCompileDir . CRM_Utils_File::makeFileName($params['PDFFilename']); //FIXME : CRM-7894 //xmlns attribute is required in XHTML but it is invalid in HTML, //Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default, //and will be added to the <html> tag even if you do not include it. $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\\s]+["\'])(.+)?(>)/', '\\1\\3\\4', $params['html']); file_put_contents($pdf_filename, CRM_Utils_PDF_Utils::html2pdf($html, $params['PDFFilename'], TRUE, $format)); if (empty($params['attachments'])) { $params['attachments'] = array(); } $params['attachments'][] = array('fullPath' => $pdf_filename, 'mime_type' => 'application/pdf', 'cleanName' => $params['PDFFilename']); } $sent = CRM_Utils_Mail::send($params); if ($pdf_filename) { unlink($pdf_filename); } } return array($sent, $subject, $text, $html); }
/** * Send an automated response. * * @param object $mailing * The mailing object. * @param int $queue_id * The queue ID. * @param string $replyto * Optional reply-to from the reply. * * @return void */ private static function autoRespond(&$mailing, $queue_id, $replyto) { $config = CRM_Core_Config::singleton(); $contacts = CRM_Contact_DAO_Contact::getTableName(); $email = CRM_Core_DAO_Email::getTableName(); $queue = CRM_Mailing_Event_DAO_Queue::getTableName(); $eq = new CRM_Core_DAO(); $eq->query("SELECT {$contacts}.preferred_mail_format as format,\n {$email}.email as email,\n {$queue}.job_id as job_id,\n {$queue}.hash as hash\n FROM {$contacts}\n INNER JOIN {$queue} ON {$queue}.contact_id = {$contacts}.id\n INNER JOIN {$email} ON {$queue}.email_id = {$email}.id\n WHERE {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')); $eq->fetch(); $to = empty($replyto) ? $eq->email : $replyto; $component = new CRM_Mailing_BAO_Component(); $component->id = $mailing->reply_id; $component->find(TRUE); $message = new Mail_Mime("\n"); $domain = CRM_Core_BAO_Domain::getDomain(); list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail(); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'To' => $to, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); /* TODO: do we need reply tokens? */ $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); if ($eq->format == 'HTML' || $eq->format == 'Both') { $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceMailingTokens($html, $mailing, NULL, $tokens['html']); $message->setHTMLBody($html); } if (!$html || $eq->format == 'Text' || $eq->format == 'Both') { $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceMailingTokens($text, $mailing, NULL, $tokens['text']); $message->setTxtBody($text); } $b = CRM_Utils_Mail::setMimeParams($message); $h = $message->headers($headers); CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 'a', $eq->job_id, queue_id, $eq->hash); $mailer = $config->getMailer(); if (is_object($mailer)) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $mailer->send($to, $h, $b); unset($errorScope); } }
/** * Function for validation * * @param array $params (ref.) an assoc array of name/value pairs * * @param $files * @param $self * * @return mixed true or array of errors * @access public * @static */ static function formRule($params, $files, $self) { if (!empty($_POST['_qf_Import_refresh'])) { return TRUE; } $errors = array(); $template = CRM_Core_Smarty::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->id = $self->_mailingID; $mailing->find(TRUE); $session = CRM_Core_Session::singleton(); $values = array('contact_id' => $session->get('userID'), 'version' => 3); require_once 'api/api.php'; $contact = civicrm_api('contact', 'get', $values); //CRM-4524 $contact = reset($contact['values']); $verp = array_flip(array('optOut', 'reply', 'unsubscribe', 'resubscribe', 'owner')); foreach ($verp as $key => $value) { $verp[$key]++; } $urls = array_flip(array('forward', 'optOutUrl', 'unsubscribeUrl', 'resubscribeUrl')); foreach ($urls as $key => $value) { $urls[$key]++; } $skipTextFile = $self->get('skipTextFile'); if (!$params['upload_type']) { if (!isset($files['textFile']) || !file_exists($files['textFile']['tmp_name'])) { if (!$skipTextFile) { $errors['textFile'] = ts('Please provide a Text'); } } } else { if (empty($params['text_message'])) { $errors['text_message'] = ts('Please provide a Text'); } else { if (!empty($params['text_message'])) { $messageCheck = CRM_Utils_Array::value('text_message', $params); if ($messageCheck && strlen($messageCheck) > CRM_SMS_Provider::MAX_SMS_CHAR) { $errors['text_message'] = ts("You can configure the SMS message body up to %1 characters", array(1 => CRM_SMS_Provider::MAX_SMS_CHAR)); } } } if (!empty($params['saveTemplate']) && empty($params['saveTemplateName'])) { $errors['saveTemplateName'] = ts('Please provide a Template Name.'); } } if ($params['upload_type'] || file_exists(CRM_Utils_Array::value('tmp_name', $files['textFile'])) || !$params['upload_type'] && $params['text_message']) { if (!$params['upload_type']) { $str = file_get_contents($files['textFile']['tmp_name']); $name = $files['textFile']['name']; } else { $str = $params['text_message']; $name = 'text message'; } $dataErrors = array(); /* Do a full token replacement on a dummy verp, the current * contact and domain, and the first organization. */ // here we make a dummy mailing object so that we // can retrieve the tokens that we need to replace // so that we do get an invalid token error // this is qute hacky and I hope that there might // be a suggestion from someone on how to // make it a bit more elegant $dummy_mail = new CRM_Mailing_BAO_Mailing(); $mess = "body_text"; $dummy_mail->{$mess} = $str; $tokens = $dummy_mail->getTokens(); $str = CRM_Utils_Token::replaceSubscribeInviteTokens($str); $str = CRM_Utils_Token::replaceDomainTokens($str, $domain, NULL, $tokens['text']); $str = CRM_Utils_Token::replaceMailingTokens($str, $mailing, NULL, $tokens['text']); $str = CRM_Utils_Token::replaceOrgTokens($str, $org); $str = CRM_Utils_Token::replaceActionTokens($str, $verp, $urls, NULL, $tokens['text']); $str = CRM_Utils_Token::replaceContactTokens($str, $contact, NULL, $tokens['text']); $unmatched = CRM_Utils_Token::unmatchedTokens($str); $contentCheck = CRM_Utils_String::htmlToText($str); if (!empty($unmatched) && 0) { foreach ($unmatched as $token) { $dataErrors[] = '<li>' . ts('Invalid token code') . ' {' . $token . '}</li>'; } } if (strlen($contentCheck) > CRM_SMS_Provider::MAX_SMS_CHAR) { $dataErrors[] = '<li>' . ts('The body of the SMS cannot exceed %1 characters.', array(1 => CRM_SMS_Provider::MAX_SMS_CHAR)) . '</li>'; } if (!empty($dataErrors)) { $errors['textFile'] = ts('The following errors were detected in %1:', array(1 => $name)) . ' <ul>' . implode('', $dataErrors) . '</ul>'; } } $templateName = CRM_Core_BAO_MessageTemplate::getMessageTemplates(); if (!empty($params['saveTemplate']) && in_array(CRM_Utils_Array::value('saveTemplateName', $params), $templateName)) { $errors['saveTemplate'] = ts('Duplicate Template Name.'); } return empty($errors) ? TRUE : $errors; }
/** * Confirm a pending subscription * * @param int $contact_id The id of the contact * @param int $subscribe_id The id of the subscription event * @param string $hash The hash * @return boolean True on success * @access public * @static */ public static function confirm($contact_id, $subscribe_id, $hash) { require_once 'CRM/Mailing/Event/BAO/Subscribe.php'; $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash); if (!$se) { return false; } require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); $ce = new CRM_Mailing_Event_BAO_Confirm(); $ce->event_subscribe_id = $se->id; $ce->time_stamp = date('YmdHis'); $ce->save(); require_once 'CRM/Contact/BAO/GroupContact.php'; CRM_Contact_BAO_GroupContact::updateGroupMembershipStatus($contact_id, $se->group_id, 'Email', $ce->id); $transaction->commit(); $config = CRM_Core_Config::singleton(); require_once 'CRM/Core/BAO/Domain.php'; $domain =& CRM_Core_BAO_Domain::getDomain(); list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail(); require_once 'CRM/Contact/BAO/Contact/Location.php'; list($display_name, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($se->contact_id); require_once 'CRM/Contact/DAO/Group.php'; $group = new CRM_Contact_DAO_Group(); $group->id = $se->group_id; $group->find(true); require_once 'CRM/Mailing/BAO/Component.php'; $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Welcome'; $component->find(true); require_once 'CRM/Core/BAO/MailSettings.php'; $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'To' => $email, 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } require_once 'CRM/Mailing/BAO/Mailing.php'; $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); require_once 'CRM/Utils/Token.php'; $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']); $html = CRM_Utils_Token::replaceWelcomeTokens($html, $group->title, true); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, false, $tokens['text']); $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->title, false); $message = new Mail_mime("\n"); $message->setHTMLBody($html); $message->setTxtBody($text); $b =& CRM_Utils_Mail::setMimeParams($message); $h =& $message->headers($headers); $mailer =& $config->getMailer(); require_once 'CRM/Mailing/BAO/Mailing.php'; PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); if (is_object($mailer)) { $mailer->send($email, $h, $b); CRM_Core_Error::setCallback(); } return $group->title; }
/** * Process the user submitted custom data values. * * @access public * * @return void */ public function postProcess() { parent::postProcess(); // this is special case when we create contact using Dialog box if ($this->_context == 'dialog') { $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_id, 'display_name'); $sortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_id, 'sort_name'); $returnArray = array('contactID' => $this->_id, 'displayName' => $displayName, 'sortName' => $sortName, 'newContactSuccess' => TRUE); echo json_encode($returnArray); CRM_Utils_System::civiExit(); } //for delete record handling if (!CRM_Utils_Array::value($this->_deleteButtonName, $_POST)) { CRM_Core_Session::setStatus(ts('Your information has been saved.'), ts('Thank you.'), 'success'); } $session = CRM_Core_Session::singleton(); // only replace user context if we do not have a postURL if (!$this->_postURL) { $gidString = $this->_gid; if (!empty($this->_profileIds)) { $gidString = implode(',', $this->_profileIds); } $urlParams = "reset=1&id={$this->_id}&gid={$gidString}"; if ($this->_isContactActivityProfile && $this->_activityId) { $urlParams .= "&aid={$this->_activityId}"; } // Get checksum if present if ($this->get('cs')) { $urlParams .= "&cs=" . $this->get('cs'); } elseif (!CRM_Contact_BAO_Contact_Permission::allow($this->_id)) { $urlParams .= "&cs=" . CRM_Contact_BAO_Contact_Utils::generateChecksum($this->_id); } $url = CRM_Utils_System::url('civicrm/profile/view', $urlParams); } else { // Replace tokens from post URL $contactParams = array('contact_id' => $this->_id, 'version' => 3); $contact = civicrm_api('contact', 'get', $contactParams); $contact = reset($contact['values']); $dummyMail = new CRM_Mailing_BAO_Mailing(); $dummyMail->body_text = $this->_postURL; $tokens = $dummyMail->getTokens(); $url = CRM_Utils_Token::replaceContactTokens($this->_postURL, $contact, FALSE, CRM_Utils_Array::value('text', $tokens)); } $session->replaceUserContext($url); }
/** * Replace tokens. * * Get mailing object and replaces subscribeInvite, domain and mailing tokens. * * @param CRM_Mailing_BAO_Mailing $mailing */ public static function tokenReplace(&$mailing) { $domain = CRM_Core_BAO_Domain::getDomain(); foreach (array('text', 'html') as $type) { $tokens = $mailing->getTokens(); if (isset($mailing->templates[$type])) { $mailing->templates[$type] = CRM_Utils_Token::replaceSubscribeInviteTokens($mailing->templates[$type]); $mailing->templates[$type] = CRM_Utils_Token::replaceDomainTokens($mailing->templates[$type], $domain, $type == 'html' ? TRUE : FALSE, $tokens[$type]); $mailing->templates[$type] = CRM_Utils_Token::replaceMailingTokens($mailing->templates[$type], $mailing, NULL, $tokens[$type]); } } }
/** * Ask a contact for subscription confirmation (opt-in) * * @param string $email The email address * @return void * @access public */ public function send_confirm_request($email) { $config = CRM_Core_Config::singleton(); require_once 'CRM/Core/BAO/Domain.php'; $domain =& CRM_Core_BAO_Domain::getDomain(); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); require_once 'CRM/Core/BAO/MailSettings.php'; $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart(); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); require_once 'CRM/Utils/Verp.php'; $confirm = implode($config->verpSeparator, array($localpart . 'c', $this->contact_id, $this->id, $this->hash)) . "@{$emailDomain}"; require_once 'CRM/Contact/BAO/Group.php'; $group = new CRM_Contact_BAO_Group(); $group->id = $this->group_id; $group->find(true); require_once 'CRM/Mailing/BAO/Component.php'; $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Subscribe'; $component->find(true); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'To' => $email, 'Reply-To' => $confirm, 'Return-Path' => "do-not-reply@{$emailDomain}"); $url = CRM_Utils_System::url('civicrm/mailing/confirm', "reset=1&cid={$this->contact_id}&sid={$this->id}&h={$this->hash}", true); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } require_once 'CRM/Mailing/BAO/Mailing.php'; $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); require_once 'CRM/Utils/Token.php'; $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']); $html = CRM_Utils_Token::replaceSubscribeTokens($html, $group->title, $url, true); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, false, $tokens['text']); $text = CRM_Utils_Token::replaceSubscribeTokens($text, $group->title, $url, false); // render the & entities in text mode, so that the links work $text = str_replace('&', '&', $text); $message = new Mail_mime("\n"); $message->setHTMLBody($html); $message->setTxtBody($text); $b =& CRM_Utils_Mail::setMimeParams($message); $h =& $message->headers($headers); $mailer =& $config->getMailer(); require_once 'CRM/Mailing/BAO/Mailing.php'; PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); if (is_object($mailer)) { $mailer->send($email, $h, $b); CRM_Core_Error::setCallback(); } }
static function sendReminder($contactId, $email, $scheduleID, $from, $tokenParams) { $schedule = new CRM_Core_DAO_ActionSchedule(); $schedule->id = $scheduleID; $domain = CRM_Core_BAO_Domain::getDomain(); $result = NULL; $hookTokens = array(); if ($schedule->find(TRUE)) { $body_text = $schedule->body_text; $body_html = $schedule->body_html; $body_subject = $schedule->subject; if (!$body_text) { $body_text = CRM_Utils_String::htmlToText($body_html); } $params = array(array('contact_id', '=', $contactId, 0, 0)); list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params); //CRM-4524 $contact = reset($contact); if (!$contact || is_a($contact, 'CRM_Core_Error')) { return NULL; } // merge activity tokens with contact array $contact = array_merge($contact, $tokenParams); //CRM-5734 CRM_Utils_Hook::tokenValues($contact, $contactId); CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); $type = array('html', 'text'); foreach ($type as $key => $value) { $dummy_mail = new CRM_Mailing_BAO_Mailing(); $bodyType = "body_{$value}"; $dummy_mail->{$bodyType} = ${$bodyType}; $tokens = $dummy_mail->getTokens(); if (${$bodyType}) { CRM_Utils_Token::replaceGreetingTokens(${$bodyType}, NULL, $contact['contact_id']); ${$bodyType} = CRM_Utils_Token::replaceDomainTokens(${$bodyType}, $domain, TRUE, $tokens[$value], TRUE); ${$bodyType} = CRM_Utils_Token::replaceContactTokens(${$bodyType}, $contact, FALSE, $tokens[$value], FALSE, TRUE); ${$bodyType} = CRM_Utils_Token::replaceComponentTokens(${$bodyType}, $contact, $tokens[$value], TRUE, FALSE); ${$bodyType} = CRM_Utils_Token::replaceHookTokens(${$bodyType}, $contact, $categories, TRUE); } } $html = $body_html; $text = $body_text; $smarty = CRM_Core_Smarty::singleton(); foreach (array('text', 'html') as $elem) { ${$elem} = $smarty->fetch("string:{${$elem}}"); } $matches = array(); preg_match_all('/(?<!\\{|\\\\)\\{(\\w+\\.\\w+)\\}(?!\\})/', $body_subject, $matches, PREG_PATTERN_ORDER); $subjectToken = NULL; if ($matches[1]) { foreach ($matches[1] as $token) { list($type, $name) = preg_split('/\\./', $token, 2); if ($name) { if (!isset($subjectToken['contact'])) { $subjectToken['contact'] = array(); } $subjectToken['contact'][] = $name; } } } $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $subjectToken); $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens[$value]); $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $tokens[$value], TRUE); $messageSubject = CRM_Utils_Token::replaceHookTokens($messageSubject, $contact, $categories, TRUE); $messageSubject = $smarty->fetch("string:{$messageSubject}"); // set up the parameters for CRM_Utils_Mail::send $mailParams = array('groupName' => 'Scheduled Reminder Sender', 'from' => $from, 'toName' => $contact['display_name'], 'toEmail' => $email, 'subject' => $messageSubject); if (!$html || $contact['preferred_mail_format'] == 'Text' || $contact['preferred_mail_format'] == 'Both') { // render the & entities in text mode, so that the links work $mailParams['text'] = str_replace('&', '&', $text); } if ($html && ($contact['preferred_mail_format'] == 'HTML' || $contact['preferred_mail_format'] == 'Both')) { $mailParams['html'] = $html; } $result = CRM_Utils_Mail::send($mailParams); } $schedule->free(); return $result; }
/** * Process the user submitted custom data values. * * * @return void */ public function postProcess() { parent::postProcess(); $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_id, 'display_name'); $sortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_id, 'sort_name'); $this->ajaxResponse['label'] = $sortName; // When saving (not deleting) and not in an ajax popup if (empty($_POST[$this->_deleteButtonName]) && $this->_context != 'dialog') { CRM_Core_Session::setStatus(ts('Your information has been saved.'), ts('Thank you.'), 'success'); } $session = CRM_Core_Session::singleton(); // only replace user context if we do not have a postURL if (!$this->_postURL) { $gidString = $this->_gid; if (!empty($this->_profileIds)) { $gidString = implode(',', $this->_profileIds); } $urlParams = "reset=1&id={$this->_id}&gid={$gidString}"; if ($this->_isContactActivityProfile && $this->_activityId) { $urlParams .= "&aid={$this->_activityId}"; } // Get checksum if present if ($this->get('cs')) { $urlParams .= "&cs=" . $this->get('cs'); } elseif (!CRM_Contact_BAO_Contact_Permission::allow($this->_id)) { $urlParams .= "&cs=" . CRM_Contact_BAO_Contact_Utils::generateChecksum($this->_id); } $url = CRM_Utils_System::url('civicrm/profile/view', $urlParams); } else { // Replace tokens from post URL $contactParams = array('contact_id' => $this->_id, 'version' => 3); $contact = civicrm_api('contact', 'get', $contactParams); $contact = reset($contact['values']); $dummyMail = new CRM_Mailing_BAO_Mailing(); $dummyMail->body_text = $this->_postURL; $tokens = $dummyMail->getTokens(); $url = CRM_Utils_Token::replaceContactTokens($this->_postURL, $contact, FALSE, CRM_Utils_Array::value('text', $tokens)); } $session->replaceUserContext($url); }
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; }
/** * Ask a contact for subscription confirmation (opt-in) * * @param string $email * The email address. * * @return void */ public function send_confirm_request($email) { $config = CRM_Core_Config::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart(); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $confirm = implode($config->verpSeparator, array($localpart . 'c', $this->contact_id, $this->id, $this->hash)) . "@{$emailDomain}"; $group = new CRM_Contact_BAO_Group(); $group->id = $this->group_id; $group->find(TRUE); $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Subscribe'; $component->find(TRUE); $headers = array('Subject' => $component->subject, 'From' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'To' => $email, 'Reply-To' => $confirm, 'Return-Path' => "do-not-reply@{$emailDomain}"); $url = CRM_Utils_System::url('civicrm/mailing/confirm', "reset=1&cid={$this->contact_id}&sid={$this->id}&h={$this->hash}", TRUE); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceSubscribeTokens($html, $group->title, $url, TRUE); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceSubscribeTokens($text, $group->title, $url, FALSE); // render the & entities in text mode, so that the links work $text = str_replace('&', '&', $text); $message = new Mail_mime("\n"); $message->setHTMLBody($html); $message->setTxtBody($text); $b = CRM_Utils_Mail::setMimeParams($message); $h = $message->headers($headers); CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 's', $this->contact_id, $this->id, $this->hash); $mailer = \Civi::service('pear_mail'); if (is_object($mailer)) { $errorScope = CRM_Core_TemporaryErrorScope::ignoreException(); $mailer->send($email, $h, $b); unset($errorScope); } }
/** * 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); }
/** * Validation. * * @param array $params * (ref.) an assoc array of name/value pairs. * * @param $files * @param $self * * @return bool|array * mixed true or array of errors */ public static function formRule($params, $files, $self) { if (!empty($_POST['_qf_Import_refresh'])) { return TRUE; } $errors = array(); $template = CRM_Core_Smarty::singleton(); if (isset($params['html_message'])) { $htmlMessage = str_replace(array("\n", "\r"), ' ', $params['html_message']); $htmlMessage = str_replace("'", "\\'", $htmlMessage); $template->assign('htmlContent', $htmlMessage); } $domain = CRM_Core_BAO_Domain::getDomain(); $mailing = new CRM_Mailing_BAO_Mailing(); $mailing->id = $self->_mailingID; $mailing->find(TRUE); $session = CRM_Core_Session::singleton(); $values = array('contact_id' => $session->get('userID'), 'version' => 3); require_once 'api/api.php'; $contact = civicrm_api('contact', 'get', $values); //CRM-4524 $contact = reset($contact['values']); $verp = array_flip(array('optOut', 'reply', 'unsubscribe', 'resubscribe', 'owner')); foreach ($verp as $key => $value) { $verp[$key]++; } $urls = array_flip(array('forward', 'optOutUrl', 'unsubscribeUrl', 'resubscribeUrl')); foreach ($urls as $key => $value) { $urls[$key]++; } // set $header and $footer foreach (array('header', 'footer') as $part) { ${$part} = array(); if ($params["{$part}_id"]) { //echo "found<p>"; $component = new CRM_Mailing_BAO_Component(); $component->id = $params["{$part}_id"]; $component->find(TRUE); ${$part}['textFile'] = $component->body_text; ${$part}['htmlFile'] = $component->body_html; $component->free(); } else { ${$part}['htmlFile'] = ${$part}['textFile'] = ''; } } $skipTextFile = $self->get('skipTextFile'); $skipHtmlFile = $self->get('skipHtmlFile'); if (!$params['upload_type']) { if ((!isset($files['textFile']) || !file_exists($files['textFile']['tmp_name'])) && (!isset($files['htmlFile']) || !file_exists($files['htmlFile']['tmp_name']))) { if (!($skipTextFile || $skipHtmlFile)) { $errors['textFile'] = ts('Please provide either a Text or HTML formatted message - or both.'); } } } else { if (empty($params['text_message']) && empty($params['html_message'])) { $errors['html_message'] = ts('Please provide either a Text or HTML formatted message - or both.'); } if (!empty($params['saveTemplate']) && empty($params['saveTemplateName'])) { $errors['saveTemplateName'] = ts('Please provide a Template Name.'); } } foreach (array('text', 'html') as $file) { if (!$params['upload_type'] && !file_exists(CRM_Utils_Array::value('tmp_name', $files[$file . 'File']))) { continue; } if ($params['upload_type'] && !$params[$file . '_message']) { continue; } if (!$params['upload_type']) { $str = file_get_contents($files[$file . 'File']['tmp_name']); $name = $files[$file . 'File']['name']; } else { $str = $params[$file . '_message']; $str = $file == 'html' ? str_replace('%7B', '{', str_replace('%7D', '}', $str)) : $str; $name = $file . ' message'; } /* append header/footer */ $str = $header[$file . 'File'] . $str . $footer[$file . 'File']; $dataErrors = array(); /* First look for missing tokens */ if (!CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'disable_mandatory_tokens_check')) { $err = CRM_Utils_Token::requiredTokens($str); if ($err !== TRUE) { foreach ($err as $token => $desc) { $dataErrors[] = '<li>' . ts('This message is missing a required token - {%1}: %2', array(1 => $token, 2 => $desc)) . '</li>'; } } } /* Do a full token replacement on a dummy verp, the current * contact and domain, and the first organization. */ // here we make a dummy mailing object so that we // can retrieve the tokens that we need to replace // so that we do get an invalid token error // this is qute hacky and I hope that there might // be a suggestion from someone on how to // make it a bit more elegant $dummy_mail = new CRM_Mailing_BAO_Mailing(); $mess = "body_{$file}"; $dummy_mail->{$mess} = $str; $tokens = $dummy_mail->getTokens(); $str = CRM_Utils_Token::replaceSubscribeInviteTokens($str); $str = CRM_Utils_Token::replaceDomainTokens($str, $domain, NULL, $tokens[$file]); $str = CRM_Utils_Token::replaceMailingTokens($str, $mailing, NULL, $tokens[$file]); $str = CRM_Utils_Token::replaceOrgTokens($str, $org); $str = CRM_Utils_Token::replaceActionTokens($str, $verp, $urls, NULL, $tokens[$file]); $str = CRM_Utils_Token::replaceContactTokens($str, $contact, NULL, $tokens[$file]); $unmatched = CRM_Utils_Token::unmatchedTokens($str); if (!empty($unmatched) && 0) { foreach ($unmatched as $token) { $dataErrors[] = '<li>' . ts('Invalid token code') . ' {' . $token . '}</li>'; } } if (!empty($dataErrors)) { $errors[$file . 'File'] = ts('The following errors were detected in %1:', array(1 => $name)) . ' <ul>' . implode('', $dataErrors) . '</ul><br /><a href="' . CRM_Utils_System::docURL2('Sample CiviMail Messages', TRUE, NULL, NULL, NULL, "wiki") . '" target="_blank">' . ts('More information on required tokens...') . '</a>'; } } $templateName = CRM_Core_BAO_MessageTemplate::getMessageTemplates(); if (!empty($params['saveTemplate']) && in_array(CRM_Utils_Array::value('saveTemplateName', $params), $templateName)) { $errors['saveTemplate'] = ts('Duplicate Template Name.'); } return empty($errors) ? TRUE : $errors; }
/** * global validation rules for the form * * @param array $fields posted values of the form * * @return array list of errors to be posted back to the form * @static * @access public */ static function formRule($fields) { $errors = array(); // Validate include/exclude groups, mailings // Start if (isset($fields['includeGroups']) && isset($fields['excludeGroups']) && is_array($fields['excludeGroups'])) { $checkGroups = array(); $checkGroups = in_array($fields['includeGroups'], $fields['excludeGroups']); if (!empty($checkGroups)) { $errors['excludeGroups'] = ts('Cannot have same groups in Include Group(s) and Exclude Group(s).'); } } if (isset($fields['includeMailings']) && is_array($fields['includeMailings']) && isset($fields['excludeMailings']) && is_array($fields['excludeMailings'])) { $checkMailings = array(); $checkMailings = array_intersect($fields['includeMailings'], $fields['excludeMailings']); if (!empty($checkMailings)) { $errors['excludeMailings'] = ts('Cannot have same mail in Include mailing(s) and Exclude mailing(s).'); } } if (!empty($fields['search_id']) && empty($fields['group_id'])) { $errors['group_id'] = ts('You must select a group to filter on'); } if (empty($fields['search_id']) && !empty($fields['group_id'])) { $errors['search_id'] = ts('You must select a search to filter'); } // End // Validate message template html/text // Start $errors = array(); $template = CRM_Core_Smarty::singleton(); if (isset($fields['html_message'])) { $htmlMessage = str_replace(array("\n", "\r"), ' ', $fields['html_message']); $htmlMessage = str_replace("'", "\\'", $htmlMessage); $template->assign('htmlContent', $htmlMessage); } $domain = CRM_Core_BAO_Domain::getDomain(); $session = CRM_Core_Session::singleton(); $values = array('contact_id' => $session->get('userID'), 'version' => 3); require_once 'api/api.php'; $contact = civicrm_api('contact', 'get', $values); //CRM-4524 $contact = reset($contact['values']); $verp = array_flip(array('optOut', 'reply', 'unsubscribe', 'resubscribe', 'owner')); foreach ($verp as $key => $value) { $verp[$key]++; } $urls = array_flip(array('forward', 'optOutUrl', 'unsubscribeUrl', 'resubscribeUrl')); foreach ($urls as $key => $value) { $urls[$key]++; } // set $header and $footer foreach (array('header', 'footer') as $part) { ${$part} = array(); if ($fields["{$part}_id"]) { //echo "found<p>"; $component = new CRM_Mailing_BAO_Component(); $component->id = $fields["{$part}_id"]; $component->find(TRUE); ${$part}['textFile'] = $component->body_text; ${$part}['htmlFile'] = $component->body_html; $component->free(); } else { ${$part}['htmlFile'] = ${$part}['textFile'] = ''; } } if (!CRM_Utils_Array::value('text_message', $fields) && !CRM_Utils_Array::value('html_message', $fields)) { $errors['html_message'] = ts('Please provide either a Text or HTML formatted message - or both.'); } foreach (array('text', 'html') as $file) { $str = $fields[$file . '_message']; $str = $file == 'html' ? str_replace('%7B', '{', str_replace('%7D', '}', $str)) : $str; $name = $file . ' message'; /* append header/footer */ $str = $header[$file . 'File'] . $str . $footer[$file . 'File']; $dataErrors = array(); /* First look for missing tokens */ $err = CRM_Utils_Token::requiredTokens($str); if ($err !== TRUE) { foreach ($err as $token => $desc) { $dataErrors[] = '<li>' . ts('This message is missing a required token - {%1}: %2', array(1 => $token, 2 => $desc)) . '</li>'; } } /* Do a full token replacement on a dummy verp, the current * contact and domain, and the first organization. */ // here we make a dummy mailing object so that we // can retrieve the tokens that we need to replace // so that we do get an invalid token error // this is qute hacky and I hope that there might // be a suggestion from someone on how to // make it a bit more elegant $dummy_mail = new CRM_Mailing_BAO_Mailing(); $mess = "body_{$file}"; $dummy_mail->{$mess} = $str; $tokens = $dummy_mail->getTokens(); $str = CRM_Utils_Token::replaceSubscribeInviteTokens($str); $str = CRM_Utils_Token::replaceDomainTokens($str, $domain, NULL, $tokens[$file]); $str = CRM_Utils_Token::replaceMailingTokens($str, $mailing, NULL, $tokens[$file]); $str = CRM_Utils_Token::replaceOrgTokens($str, $org); $str = CRM_Utils_Token::replaceActionTokens($str, $verp, $urls, NULL, $tokens[$file]); $str = CRM_Utils_Token::replaceContactTokens($str, $contact, NULL, $tokens[$file]); $unmatched = CRM_Utils_Token::unmatchedTokens($str); if (!empty($unmatched) && 0) { foreach ($unmatched as $token) { $dataErrors[] = '<li>' . ts('Invalid token code') . ' {' . $token . '}</li>'; } } if (!empty($dataErrors)) { $errors[$file . '_message'] = ts('The following errors were detected in %1:', array(1 => $name)) . ' <ul>' . implode('', $dataErrors) . '</ul><br /><a href="' . CRM_Utils_System::docURL2('Sample CiviMail Messages', TRUE, NULL, NULL, NULL, "wiki") . '" target="_blank">' . ts('More information on required tokens...') . '</a>'; } } // End return empty($errors) ? TRUE : $errors; }
/** * Confirm a pending subscription * * @param int $contact_id The id of the contact * @param int $subscribe_id The id of the subscription event * @param string $hash The hash * * @return boolean True on success * @access public * @static */ public static function confirm($contact_id, $subscribe_id, $hash) { $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash); if (!$se) { return FALSE; } // before we proceed lets just check if this contact is already 'Added' // if so, we should ignore this request and hence avoid sending multiple // emails - CRM-11157 $details = CRM_Contact_BAO_GroupContact::getMembershipDetail($contact_id, $se->group_id); if ($details && $details->status == 'Added') { // This contact is already subscribed // lets return the group title return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $se->group_id, 'title'); } $transaction = new CRM_Core_Transaction(); $ce = new CRM_Mailing_Event_BAO_Confirm(); $ce->event_subscribe_id = $se->id; $ce->time_stamp = date('YmdHis'); $ce->save(); CRM_Contact_BAO_GroupContact::addContactsToGroup(array($contact_id), $se->group_id, 'Email', 'Added', $ce->id); $transaction->commit(); $config = CRM_Core_Config::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail(); list($display_name, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($se->contact_id); $group = new CRM_Contact_DAO_Group(); $group->id = $se->group_id; $group->find(TRUE); $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Welcome'; $component->find(TRUE); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceWelcomeTokens($html, $group->title, TRUE); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->title, FALSE); $mailParams = array('groupName' => 'Mailing Event ' . $component->component_type, 'subject' => $component->subject, 'from' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'toEmail' => $email, 'toName' => $display_name, 'replyTo' => "do-not-reply@{$emailDomain}", 'returnPath' => "do-not-reply@{$emailDomain}", 'html' => $html, 'text' => $text); // send - ignore errors because the desired status change has already been successful $unused_result = CRM_Utils_Mail::send($mailParams); return $group->title; }
/** * Send an automated response * * @param object $mailing The mailing object * @param int $queue_id The queue ID * @param string $replyto Optional reply-to from the reply * @return void * @access private * @static */ private static function autoRespond(&$mailing, $queue_id, $replyto) { $config = CRM_Core_Config::singleton(); $contacts = CRM_Contact_DAO_Contact::getTableName(); $email = CRM_Core_DAO_Email::getTableName(); $queue = CRM_Mailing_Event_DAO_Queue::getTableName(); $eq = new CRM_Core_DAO(); $eq->query("SELECT {$contacts}.preferred_mail_format as format,\n {$email}.email as email\n FROM {$contacts}\n INNER JOIN {$queue} ON {$queue}.contact_id = {$contacts}.id\n INNER JOIN {$email} ON {$queue}.email_id = {$email}.id\n WHERE {$queue}.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')); $eq->fetch(); $to = empty($replyto) ? $eq->email : $replyto; $component = new CRM_Mailing_BAO_Component(); $component->id = $mailing->reply_id; $component->find(true); $message = new Mail_Mime("\n"); require_once 'CRM/Core/BAO/Domain.php'; $domain =& CRM_Core_BAO_Domain::getDomain(); list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail(); require_once 'CRM/Core/BAO/MailSettings.php'; $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $headers = array('Subject' => $component->subject, 'To' => $to, 'From' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'Reply-To' => "do-not-reply@{$emailDomain}", 'Return-Path' => "do-not-reply@{$emailDomain}"); /* TODO: do we need reply tokens? */ $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } require_once 'CRM/Mailing/BAO/Mailing.php'; $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); if ($eq->format == 'HTML' || $eq->format == 'Both') { require_once 'CRM/Utils/Token.php'; $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true, $tokens['html']); $html = CRM_Utils_Token::replaceMailingTokens($html, $mailing, null, $tokens['html']); $message->setHTMLBody($html); } if (!$html || $eq->format == 'Text' || $eq->format == 'Both') { require_once 'CRM/Utils/Token.php'; $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, false, $tokens['text']); $text = CRM_Utils_Token::replaceMailingTokens($text, $mailing, null, $tokens['text']); $message->setTxtBody($text); } $b =& CRM_Utils_Mail::setMimeParams($message); $h =& $message->headers($headers); $mailer =& $config->getMailer(); PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); if (is_object($mailer)) { $mailer->send($to, $h, $b); CRM_Core_Error::setCallback(); } }