/** * Load token data. * * @param TokenValueEvent $e * @throws TokenException */ public function onEvaluate(TokenValueEvent $e) { // For reasons unknown, replaceHookTokens requires a pre-computed list of // hook *categories* (aka entities aka namespaces). We'll cache // this in the TokenProcessor's context. $hookTokens = array(); \CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); $e->getTokenProcessor()->context['hookTokenCategories'] = $categories; $messageTokens = $e->getTokenProcessor()->getMessageTokens(); foreach ($e->getRows() as $row) { if (empty($row->context['contact'])) { $params = array(array('contact_id', '=', $row->context['contactId'], 0, 0)); list($contact, $_) = \CRM_Contact_BAO_Query::apiQuery($params); $contact = reset($contact); //CRM-4524 if (!$contact || is_a($contact, 'CRM_Core_Error')) { // FIXME: Need to differentiate errors which kill the batch vs the individual row. throw new TokenException("Failed to generate token data. Invalid contact ID: " . $row->context['contactId']); } } else { $contact = $row->context['contact']; } if (!empty($row->context['tmpTokenParams'])) { // merge activity tokens with contact array // this is pretty weird. $contact = array_merge($contact, $row->context['tmpTokenParams']); } // Note: This is a small contract change from the past; data should be missing // less randomly. //\CRM_Utils_Hook::tokenValues($contact, $row->context['contactId']); \CRM_Utils_Hook::tokenValues($contact, $row->context['contactId'], empty($row->context['mailingJob']) ? NULL : $row->context['mailingJob']->id, $messageTokens, $row->context['controller']); $row->context('contact', $contact); } }
/** * Function is used to format the individual contact values. * * @param array $params * (reference ) an assoc array of name/value pairs. * @param CRM $contact * Contact object. * * @return CRM_Contact_BAO_Contact */ public static function format(&$params, &$contact) { if (!self::dataExists($params)) { return NULL; } // "null" value for example is passed by dedupe merge in order to empty. // Display name computation shouldn't consider such values. foreach (array('first_name', 'middle_name', 'last_name', 'nick_name', 'formal_title') as $displayField) { if (CRM_Utils_Array::value($displayField, $params) == "null") { $params[$displayField] = ''; } } $sortName = $displayName = ''; $firstName = CRM_Utils_Array::value('first_name', $params, ''); $middleName = CRM_Utils_Array::value('middle_name', $params, ''); $lastName = CRM_Utils_Array::value('last_name', $params, ''); $nickName = CRM_Utils_Array::value('nick_name', $params, ''); $prefix_id = CRM_Utils_Array::value('prefix_id', $params, ''); $suffix_id = CRM_Utils_Array::value('suffix_id', $params, ''); $formalTitle = CRM_Utils_Array::value('formal_title', $params, ''); // get prefix and suffix names $prefix = $suffix = NULL; if ($prefix_id) { $params['individual_prefix'] = $prefix = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'prefix_id', $prefix_id); } if ($suffix_id) { $params['individual_suffix'] = $suffix = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'suffix_id', $suffix_id); } $params['is_deceased'] = CRM_Utils_Array::value('is_deceased', $params, FALSE); $individual = NULL; if ($contact->id) { $individual = new CRM_Contact_BAO_Contact(); $individual->id = $contact->id; if ($individual->find(TRUE)) { //lets allow to update single name field though preserveDBName //but if db having null value and params contain value, CRM-4330. $useDBNames = array(); foreach (array('last', 'middle', 'first', 'nick') as $name) { $dbName = "{$name}_name"; $value = $individual->{$dbName}; // the db has name values if ($value && !empty($params['preserveDBName'])) { $useDBNames[] = $name; } } foreach (array('prefix', 'suffix') as $name) { $dbName = "{$name}_id"; $value = $individual->{$dbName}; if ($value && !empty($params['preserveDBName'])) { $useDBNames[] = $name; } } if ($individual->formal_title && !empty($params['preserveDBName'])) { $useDBNames[] = 'formal_title'; } // CRM-4430 //1. preserve db name if want //2. lets get value from param if exists. //3. if not in params, lets get from db. foreach (array('last', 'middle', 'first', 'nick') as $name) { $phpName = "{$name}Name"; $dbName = "{$name}_name"; $value = $individual->{$dbName}; if (in_array($name, $useDBNames)) { $params[$dbName] = $value; $contact->{$dbName} = $value; ${$phpName} = $value; } elseif (array_key_exists($dbName, $params)) { ${$phpName} = $params[$dbName]; } elseif ($value) { ${$phpName} = $value; } } foreach (array('prefix', 'suffix') as $name) { $dbName = "{$name}_id"; $value = $individual->{$dbName}; if (in_array($name, $useDBNames)) { $params[$dbName] = $value; $contact->{$dbName} = $value; if ($value) { ${$name} = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $dbName, $value); } else { ${$name} = NULL; } } elseif (array_key_exists($dbName, $params)) { // CRM-5278 if (!empty($params[$dbName])) { ${$name} = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $dbName, $params[$dbName]); } } elseif ($value) { ${$name} = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $dbName, $value); } } if (in_array('formal_title', $useDBNames)) { $params['formal_title'] = $individual->formal_title; $contact->formal_title = $individual->formal_title; $formalTitle = $individual->formal_title; } elseif (array_key_exists('formal_title', $params)) { $formalTitle = $params['formal_title']; } elseif ($individual->formal_title) { $formalTitle = $individual->formal_title; } } } //first trim before further processing. foreach (array('lastName', 'firstName', 'middleName') as $fld) { ${$fld} = trim(${$fld}); } if ($lastName || $firstName || $middleName) { // make sure we have values for all the name fields. $formatted = $params; $nameParams = array('first_name' => $firstName, 'middle_name' => $middleName, 'last_name' => $lastName, 'nick_name' => $nickName, 'individual_suffix' => $suffix, 'individual_prefix' => $prefix, 'prefix_id' => $prefix_id, 'suffix_id' => $suffix_id, 'formal_title' => $formalTitle); // make sure we have all the name fields. foreach ($nameParams as $name => $value) { if (empty($formatted[$name]) && $value) { $formatted[$name] = $value; } } $tokens = array(); CRM_Utils_Hook::tokens($tokens); $tokenFields = array(); foreach ($tokens as $catTokens) { foreach ($catTokens as $token => $label) { $tokenFields[] = $token; } } //build the sort name. $format = Civi::settings()->get('sort_name_format'); $sortName = CRM_Utils_Address::format($formatted, $format, FALSE, FALSE, TRUE, $tokenFields); $sortName = trim($sortName); //build the display name. $format = Civi::settings()->get('display_name_format'); $displayName = CRM_Utils_Address::format($formatted, $format, FALSE, FALSE, TRUE, $tokenFields); $displayName = trim($displayName); } //start further check for email. if (empty($sortName) || empty($displayName)) { $email = NULL; if (!empty($params['email']) && is_array($params['email'])) { foreach ($params['email'] as $emailBlock) { if (isset($emailBlock['is_primary'])) { $email = $emailBlock['email']; break; } } } $uniqId = CRM_Utils_Array::value('user_unique_id', $params); if (!$email && $contact->id) { $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contact->id); } } //now set the names. $names = array('displayName' => 'display_name', 'sortName' => 'sort_name'); foreach ($names as $value => $name) { if (empty(${$value})) { if ($email) { ${$value} = $email; } elseif ($uniqId) { ${$value} = $uniqId; } elseif (!empty($params[$name])) { ${$value} = $params[$name]; } elseif ($displayName) { ${$value} = $displayName; } } //finally if we could not pass anything lets keep db. if (!empty(${$value})) { $contact->{$name} = ${$value}; } } $format = CRM_Utils_Date::getDateFormat('birth'); if ($date = CRM_Utils_Array::value('birth_date', $params)) { if (in_array($format, array('dd-mm', 'mm/dd'))) { $separator = '/'; if ($format == 'dd-mm') { $separator = '-'; } $date = $date . $separator . '1902'; } elseif (in_array($format, array('yy-mm'))) { $date = $date . '-01'; } elseif (in_array($format, array('M yy'))) { $date = $date . '-01'; } elseif (in_array($format, array('yy'))) { $date = $date . '-01-01'; } $contact->birth_date = CRM_Utils_Date::processDate($date); } elseif ($contact->birth_date) { $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date); } if ($date = CRM_Utils_Array::value('deceased_date', $params)) { if (in_array($format, array('dd-mm', 'mm/dd'))) { $separator = '/'; if ($format == 'dd-mm') { $separator = '-'; } $date = $date . $separator . '1902'; } elseif (in_array($format, array('yy-mm'))) { $date = $date . '-01'; } elseif (in_array($format, array('M yy'))) { $date = $date . '-01'; } elseif (in_array($format, array('yy'))) { $date = $date . '-01-01'; } $contact->deceased_date = CRM_Utils_Date::processDate($date); } elseif ($contact->deceased_date) { $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date); } if ($middle_name = CRM_Utils_Array::value('middle_name', $params)) { $contact->middle_name = $middle_name; } return $contact; }
/** * part of the post process which prepare and extract information from the template * * @access protected * * @return array( $categories, $html_message, $messageToken, $returnProperties ) */ protected static function processMessageTemplate(&$form) { $formValues = $form->controller->exportValues($form->getName()); // process message template 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); $messageTemplate['pdf_format_id'] = 'null'; if (CRM_Utils_Array::value('bind_format', $formValues) && $formValues['format_id'] > 0) { $messageTemplate['pdf_format_id'] = $formValues['format_id']; } if (CRM_Utils_Array::value('saveTemplate', $formValues) && $formValues['saveTemplate']) { $messageTemplate['msg_title'] = $formValues['saveTemplateName']; CRM_Core_BAO_MessageTemplates::add($messageTemplate); } if (CRM_Utils_Array::value('updateTemplate', $formValues) && $formValues['template'] && $formValues['updateTemplate']) { $messageTemplate['id'] = $formValues['template']; unset($messageTemplate['msg_title']); CRM_Core_BAO_MessageTemplates::add($messageTemplate); } } elseif (CRM_Utils_Array::value('template', $formValues) > 0) { if (CRM_Utils_Array::value('bind_format', $formValues) && $formValues['format_id'] > 0) { $query = "UPDATE civicrm_msg_template SET pdf_format_id = {$formValues['format_id']} WHERE id = {$formValues['template']}"; } else { $query = "UPDATE civicrm_msg_template SET pdf_format_id = NULL WHERE id = {$formValues['template']}"; } CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); } if (CRM_Utils_Array::value('update_format', $formValues)) { $bao = new CRM_Core_BAO_PdfFormat(); $bao->savePdfFormat($formValues, $formValues['format_id']); } $html = array(); $tokens = array(); CRM_Utils_Hook::tokens($tokens); $categories = array_keys($tokens); $html_message = $formValues['html_message']; //time being hack to strip ' ' //from particular letter line, CRM-6798 self::formatMessage($html_message); $messageToken = CRM_Utils_Token::getTokens($html_message); $returnProperties = array(); if (isset($messageToken['contact'])) { foreach ($messageToken['contact'] as $key => $value) { $returnProperties[$value] = 1; } } return array($formValues, $categories, $html_message, $messageToken, $returnProperties); }
/** * Get token list from mailing format & contacts * @param unknown_type $contacts * @return unknown */ function getTokenData(&$contacts) { $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'mailing_format'); $tokens = $tokenFields = array(); $messageToken = CRM_Utils_Token::getTokens($mailingFormat); // also get all token values CRM_Utils_Hook::tokenValues($contacts, array_keys($contacts), NULL, $messageToken, 'CRM_Contact_Form_Task_LabelCommon'); CRM_Utils_Hook::tokens($tokens); foreach ($tokens as $category => $catTokens) { foreach ($catTokens as $token => $tokenName) { $tokenFields[] = $token; } } return $tokenFields; }
static function sendSMS(&$contactDetails, &$activityParams, &$smsParams = array(), &$contactIds, $userID = NULL) { if ($userID == NULL) { $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); } $text =& $activityParams['text_message']; $html =& $activityParams['html_message']; // CRM-4575 // token replacement of addressee/email/postal greetings // get the tokens added in subject and message $messageToken = CRM_Utils_Token::getTokens($text); $messageToken = array_merge($messageToken, CRM_Utils_Token::getTokens($html)); //create the meta level record first ( sms activity ) $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'SMS', 'name'); // CRM-6265: save both text and HTML parts in details (if present) if ($html and $text) { $details = "-ALTERNATIVE ITEM 0-\n{$html}\n-ALTERNATIVE ITEM 1-\n{$text}\n-ALTERNATIVE END-\n"; } else { $details = $html ? $html : $text; } $activitySubject = $activityParams['activity_subject']; $activityParams = array('source_contact_id' => $userID, 'activity_type_id' => $activityTypeID, 'activity_date_time' => date('YmdHis'), 'subject' => $activitySubject, 'details' => $details, 'status_id' => 2); $activity = self::create($activityParams); $activityID = $activity->id; $returnProperties = array(); if (isset($messageToken['contact'])) { foreach ($messageToken['contact'] as $key => $value) { $returnProperties[$value] = 1; } } // get token details for contacts, call only if tokens are used $details = array(); if (!empty($returnProperties)) { list($details) = CRM_Utils_Token::getTokenDetails($contactIds, $returnProperties, NULL, NULL, FALSE, $messageToken, 'CRM_Activity_BAO_Activity'); } // call token hook $tokens = array(); CRM_Utils_Hook::tokens($tokens); $categories = array_keys($tokens); $escapeSmarty = $sent = FALSE; foreach ($contactDetails as $values) { $contactId = $values['contact_id']; 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}"]); } $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty); $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty); $tokenHtml = CRM_Utils_Token::replaceContactTokens($html, $values, TRUE, $messageToken, FALSE, $escapeSmarty); $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $values, $categories, TRUE, $escapeSmarty); $smsParams['To'] = $values['phone']; if (self::sendSMSMessage($contactId, $tokenText, $tokenHtml, $smsParams, $activityID)) { // even a single successful delivery should set this falg to true $sent = TRUE; } } return array($sent, $activity->id); }
/** * process the form after the input has been submitted and validated * * @access public * * @return void */ public function postProcess() { $fv = $this->controller->exportValues($this->_name); $config = CRM_Core_Config::singleton(); $locName = NULL; //get the address format sequence from the config file $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'mailing_format'); $sequence = CRM_Utils_Address::sequence($mailingFormat); foreach ($sequence as $v) { $address[$v] = 1; } if (array_key_exists('postal_code', $address)) { $address['postal_code_suffix'] = 1; } //build the returnproperties $returnProperties = array('display_name' => 1, 'contact_type' => 1); $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'mailing_format'); $mailingFormatProperties = array(); if ($mailingFormat) { $mailingFormatProperties = self::getReturnProperties($mailingFormat); $returnProperties = array_merge($returnProperties, $mailingFormatProperties); } //we should not consider addressee for data exists, CRM-6025 if (array_key_exists('addressee', $mailingFormatProperties)) { unset($mailingFormatProperties['addressee']); } $customFormatProperties = array(); if (stristr($mailingFormat, 'custom_')) { foreach ($mailingFormatProperties as $token => $true) { if (substr($token, 0, 7) == 'custom_') { if (empty($customFormatProperties[$token])) { $customFormatProperties[$token] = $mailingFormatProperties[$token]; } } } } if (!empty($customFormatProperties)) { $returnProperties = array_merge($returnProperties, $customFormatProperties); } if (isset($fv['merge_same_address'])) { // we need first name/last name for summarising to avoid spillage $returnProperties['first_name'] = 1; $returnProperties['last_name'] = 1; } $individualFormat = FALSE; /* * CRM-8338: replace ids of household members with the id of their household * so we can merge labels by household. */ if (isset($fv['merge_same_household'])) { $this->mergeContactIdsByHousehold(); $individualFormat = TRUE; } //get the contacts information $params = array(); if (!empty($fv['location_type_id'])) { $locType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $locName = $locType[$fv['location_type_id']]; $location = array('location' => array("{$locName}" => $address)); $returnProperties = array_merge($returnProperties, $location); $params[] = array('location_type', '=', array($fv['location_type_id'] => 1), 0, 0); } else { $returnProperties = array_merge($returnProperties, $address); } $rows = array(); foreach ($this->_contactIds as $key => $contactID) { $params[] = array(CRM_Core_Form::CB_PREFIX . $contactID, '=', 1, 0, 0); } // fix for CRM-2651 if (!empty($fv['do_not_mail'])) { $params[] = array('do_not_mail', '=', 0, 0, 0); } // fix for CRM-2613 $params[] = array('is_deceased', '=', 0, 0, 0); $custom = array(); foreach ($returnProperties as $name => $dontCare) { $cfID = CRM_Core_BAO_CustomField::getKeyID($name); if ($cfID) { $custom[] = $cfID; } } //get the total number of contacts to fetch from database. $numberofContacts = count($this->_contactIds); $query = new CRM_Contact_BAO_Query($params, $returnProperties); $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts); $messageToken = CRM_Utils_Token::getTokens($mailingFormat); // also get all token values CRM_Utils_Hook::tokenValues($details[0], $this->_contactIds, NULL, $messageToken, 'CRM_Contact_Form_Task_Label'); $tokens = array(); CRM_Utils_Hook::tokens($tokens); $tokenFields = array(); foreach ($tokens as $category => $catTokens) { foreach ($catTokens as $token => $tokenName) { $tokenFields[] = $token; } } foreach ($this->_contactIds as $value) { foreach ($custom as $cfID) { if (isset($details[0][$value]["custom_{$cfID}"])) { $details[0][$value]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($details[0][$value]["custom_{$cfID}"], $cfID, $details[1]); } } $contact = CRM_Utils_Array::value($value, $details['0']); if (is_a($contact, 'CRM_Core_Error')) { return NULL; } // we need to remove all the "_id" unset($contact['contact_id']); if ($locName && !empty($contact[$locName])) { // If location type is not primary, $contact contains // one more array as "$contact[$locName] = array( values... )" if (!$this->tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) { continue; } unset($contact[$locName]); if (!empty($contact['county_id'])) { unset($contact['county_id']); } foreach ($contact as $field => $fieldValue) { $rows[$value][$field] = $fieldValue; } $valuesothers = array(); $paramsothers = array('contact_id' => $value); $valuesothers = CRM_Core_BAO_Location::getValues($paramsothers, $valuesothers); if (!empty($fv['location_type_id'])) { foreach ($valuesothers as $vals) { if (CRM_Utils_Array::value('location_type_id', $vals) == CRM_Utils_Array::value('location_type_id', $fv)) { foreach ($vals as $k => $v) { if (in_array($k, array('email', 'phone', 'im', 'openid'))) { if ($k == 'im') { $rows[$value][$k] = $v['1']['name']; } else { $rows[$value][$k] = $v['1'][$k]; } $rows[$value][$k . '_id'] = $v['1']['id']; } } } } } } else { if (!$this->tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) { continue; } if (!empty($contact['addressee_display'])) { $contact['addressee_display'] = trim($contact['addressee_display']); } if (!empty($contact['addressee'])) { $contact['addressee'] = $contact['addressee_display']; } // now create the rows for generating mailing labels foreach ($contact as $field => $fieldValue) { $rows[$value][$field] = $fieldValue; } } } if (isset($fv['merge_same_address'])) { $this->mergeSameAddress($rows); $individualFormat = TRUE; } // format the addresses according to CIVICRM_ADDRESS_FORMAT (CRM-1327) foreach ($rows as $id => $row) { if ($commMethods = CRM_Utils_Array::value('preferred_communication_method', $row)) { $val = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $commMethods)); $comm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method'); $temp = array(); foreach ($val as $vals) { $temp[] = $comm[$vals]; } $row['preferred_communication_method'] = implode(', ', $temp); } $row['id'] = $id; $formatted = CRM_Utils_Address::format($row, 'mailing_format', FALSE, TRUE, $individualFormat, $tokenFields); // CRM-2211: UFPDF doesn't have bidi support; use the PECL fribidi package to fix it. // On Ubuntu (possibly Debian?) be aware of http://pecl.php.net/bugs/bug.php?id=12366 // Due to FriBidi peculiarities, this can't be called on // a multi-line string, hence the explode+implode approach. if (function_exists('fribidi_log2vis')) { $lines = explode("\n", $formatted); foreach ($lines as $i => $line) { $lines[$i] = fribidi_log2vis($line, FRIBIDI_AUTO, FRIBIDI_CHARSET_UTF8); } $formatted = implode("\n", $lines); } $rows[$id] = array($formatted); } //call function to create labels self::createLabel($rows, $fv['label_name']); CRM_Utils_System::civiExit(1); }
public function updateConstructedNames() { require_once 'CRM/Utils/Address.php'; require_once 'CRM/Core/BAO/Preferences.php'; require_once 'CRM/Core/DAO.php'; require_once 'CRM/Core/PseudoConstant.php'; require_once 'CRM/Contact/BAO/Contact.php'; //handle individuals using settings in the system $query = "SELECT * FROM civicrm_contact WHERE contact_type = 'Individual';"; $dao = CRM_Core_DAO::executeQuery($query); $prefixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'); $suffixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'); $tokens = array(); CRM_Utils_Hook::tokens($tokens); $tokenFields = array(); foreach ($tokens as $category => $catTokens) { foreach ($catTokens as $token) { $tokenFields[] = $token; } } //determine sort name construction $sortFormat = CRM_Core_BAO_Preferences::value('sort_name_format'); $sortFormat = str_replace('contact.', '', $sortFormat); //determine display name construction $displayFormat = CRM_Core_BAO_Preferences::value('display_name_format'); $displayFormat = str_replace('contact.', '', $displayFormat); while ($dao->fetch()) { $contactID = $dao->id; $params = array('first_name' => $dao->first_name, 'middle_name' => $dao->middle_name, 'last_name' => $dao->last_name, 'prefix_id' => $dao->prefix_id, 'suffix_id' => $dao->suffix_id); $params['individual_prefix'] = $prefixes[$dao->prefix_id]; $params['individual_suffix'] = $suffixes[$dao->suffix_id]; $sortName = CRM_Utils_Address::format($params, $sortFormat, FALSE, FALSE, TRUE, $tokenFields); $sortName = trim(CRM_Core_DAO::escapeString($sortName)); $displayName = CRM_Utils_Address::format($params, $displayFormat, FALSE, FALSE, TRUE, $tokenFields); $displayName = trim(CRM_Core_DAO::escapeString($displayName)); //check for email if (empty($sortName) || empty($displayName)) { $email = NULL; $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contactID); if (empty($email)) { $email = $contactID; } if (empty($sortName)) { $sortName = $email; } if (empty($displayName)) { $displayName = $email; } } //update record $updateQuery = "UPDATE civicrm_contact SET display_name = '{$displayName}', sort_name = '{$sortName}' WHERE id = {$contactID};"; CRM_Core_DAO::executeQuery($updateQuery); } //end indiv echo "\n Individuals recached... "; //set organizations $query = "UPDATE civicrm_contact\n\t\t SET display_name = organization_name,\n\t\t\t\t sort_name = organization_name\n\t\t\t WHERE contact_type = 'Organization';"; $dao = CRM_Core_DAO::executeQuery($query); echo "\n Organizations recached... "; //set households $query = "UPDATE civicrm_contact\n\t\t SET display_name = household_name,\n\t\t\t\t sort_name = household_name\n\t\t\t WHERE contact_type = 'Household';"; $dao = CRM_Core_DAO::executeQuery($query); echo "\n Households recached... "; }
/** * different type of Contact Tokens * * @static * return array */ static function &contactTokens() { static $tokens = null; if (!$tokens) { require_once 'CRM/Contact/BAO/Contact.php'; require_once 'CRM/Core/BAO/CustomField.php'; $additionalFields = array('checksum' => array('title' => ts('Checksum')), 'contact_id' => array('title' => ts('Internal Contact ID'))); $exportFields = array_merge(CRM_Contact_BAO_Contact::exportableFields(), $additionalFields); $values = array_merge(array_keys($exportFields)); unset($values[0]); //FIXME:skipping some tokens for time being. $skipTokens = array('is_bulkmail', 'group', 'tag', 'contact_sub_type', 'note', 'is_deceased', 'deceased_date', 'legal_identifier', 'contact_sub_type', 'user_unique_id'); $customFields = array(); $customFields = CRM_Core_BAO_CustomField::getFields('Individual'); foreach ($values as $key => $val) { if (in_array($val, $skipTokens)) { continue; } //keys for $tokens should be constant. $token Values are changed for Custom Fields. CRM-3734 if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($val)) { $tokens["{contact.{$val}}"] = $customFields[$customFieldId]['label'] . " :: " . $customFields[$customFieldId]['groupTitle']; } else { $tokens["{contact.{$val}}"] = $exportFields[$val]['title']; } } // might as well get all the hook tokens to require_once 'CRM/Utils/Hook.php'; $hookTokens = array(); CRM_Utils_Hook::tokens($hookTokens); foreach ($hookTokens as $category => $tokenValues) { foreach ($tokenValues as $key => $value) { if (is_numeric($key)) { $key = $value; } if (!preg_match('/^\\{[^\\}]+\\}$/', $key)) { $key = '{' . $key . '}'; } if (preg_match('/^\\{([^\\}]+)\\}$/', $value, $matches)) { $value = $matches[1]; } $tokens[$key] = $value; } } } return $tokens; }
/** * 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']; 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(); $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 ($first == TRUE) { $first = FALSE; $html .= $tokenHtml; } else { $html .= "<div STYLE='page-break-after: always'></div>{$tokenHtml}"; } } $html .= '</body></html>'; require_once 'CRM/Utils/PDF/Utils.php'; CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", 'portrait'); exit(1); }
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; }
/** * 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); }
/** * Function is used to format the individual contact values * * @param array $params (reference ) an assoc array of name/value pairs * @param array $contact contact object * * @return object CRM_Contact_BAO_Contact object * @access public * @static */ static function format(&$params, &$contact) { if (!self::dataExists($params)) { return; } $sortName = $displayName = ""; $firstName = CRM_Utils_Array::value('first_name', $params, ''); $middleName = CRM_Utils_Array::value('middle_name', $params, ''); $lastName = CRM_Utils_Array::value('last_name', $params, ''); $prefix_id = CRM_Utils_Array::value('prefix_id', $params, ''); $suffix_id = CRM_Utils_Array::value('suffix_id', $params, ''); // get prefix and suffix names $prefixes = CRM_Core_PseudoConstant::individualPrefix(); $suffixes = CRM_Core_PseudoConstant::individualSuffix(); $prefix = $suffix = null; if ($prefix_id) { $prefix = $prefixes[$prefix_id]; $params['individual_prefix'] = $prefix; } if ($suffix_id) { $suffix = $suffixes[$suffix_id]; $params['individual_suffix'] = $suffix; } $params['is_deceased'] = CRM_Utils_Array::value('is_deceased', $params, false); $individual = null; if ($contact->id) { $individual = new CRM_Contact_BAO_Contact(); $individual->id = $contact->id; if ($individual->find(true)) { //lets allow to update single name field though preserveDBName //but if db having null value and params contain value, CRM-4330. $useDBNames = array(); foreach (array('last', 'middle', 'first') as $name) { $dbName = "{$name}_name"; $value = $individual->{$dbName}; // the db has name values if ($value && CRM_Utils_Array::value('preserveDBName', $params)) { $useDBNames[] = $name; } } foreach (array('prefix', 'suffix') as $name) { $dbName = "{$name}_id"; $value = $individual->{$dbName}; if ($value && CRM_Utils_Array::value('preserveDBName', $params)) { $useDBNames[] = $name; } } // CRM-4430 //1. preserve db name if want //2. lets get value from param if exists. //3. if not in params, lets get from db. foreach (array('last', 'middle', 'first') as $name) { $phpName = "{$name}Name"; $dbName = "{$name}_name"; $value = $individual->{$dbName}; if (in_array($name, $useDBNames)) { $params[$dbName] = $value; $contact->{$dbName} = $value; ${$phpName} = $value; } else { if (array_key_exists($dbName, $params)) { ${$phpName} = $params[$dbName]; } else { if ($value) { ${$phpName} = $value; } } } } foreach (array('prefix', 'suffix') as $name) { $phpName = $name; $dbName = "{$name}_id"; $vals = "{$name}es"; $value = $individual->{$dbName}; if (in_array($name, $useDBNames)) { $params[$dbName] = $value; $contact->{$dbName} = $value; if ($value) { $temp = ${$vals}; ${$phpName} = $temp[$value]; } else { ${$phpName} = null; } } else { if (array_key_exists($dbName, $params)) { $temp = ${$vals}; // CRM-5278 if (!empty($params[$dbName])) { ${$phpName} = CRM_Utils_Array::value($params[$dbName], $temp); } } else { if ($value) { $temp = ${$vals}; ${$phpName} = $temp[$value]; } } } } } } //first trim before further processing. foreach (array('lastName', 'firstName', 'middleName') as $fld) { ${$fld} = trim(${$fld}); } if ($lastName || $firstName || $middleName) { // make sure we have values for all the name fields. $formatted = $params; $nameParams = array('first_name' => $firstName, 'middle_name' => $middleName, 'last_name' => $lastName, 'individual_suffix' => $suffix, 'individual_prefix' => $prefix, 'prefix_id' => $prefix_id, 'suffix_id' => $suffix_id); // make sure we have all the name fields. foreach ($nameParams as $name => $value) { if (!CRM_Utils_Array::value($name, $formatted) && $value) { $formatted[$name] = $value; } } // make sure we have values for all the name fields. $formatted = $params; $nameParams = array('first_name' => $firstName, 'middle_name' => $middleName, 'last_name' => $lastName, 'individual_suffix' => $suffix, 'individual_prefix' => $prefix, 'prefix_id' => $prefix_id, 'suffix_id' => $suffix_id); // make sure we have all the name fields. foreach ($nameParams as $name => $value) { if (!CRM_Utils_Array::value($name, $formatted) && $value) { $formatted[$name] = $value; } } $tokens = array(); CRM_Utils_Hook::tokens($tokens); $tokenFields = array(); foreach ($tokens as $category => $catTokens) { foreach ($catTokens as $token) { $tokenFields[] = $token; } } require_once 'CRM/Utils/Address.php'; require_once 'CRM/Core/BAO/Preferences.php'; //build the sort name. $format = CRM_Core_BAO_Preferences::value('sort_name_format'); $format = str_replace('contact.', '', $format); $sortName = CRM_Utils_Address::format($formatted, $format, false, false, true, $tokenFields); $sortName = trim($sortName); //build the display name. $format = CRM_Core_BAO_Preferences::value('display_name_format'); $format = str_replace('contact.', '', $format); $displayName = CRM_Utils_Address::format($formatted, $format, false, false, true, $tokenFields); $displayName = trim($displayName); } //start further check for email. if (empty($sortName) || empty($displayName)) { $email = null; if (CRM_Utils_Array::value('email', $params) && is_array($params['email'])) { foreach ($params['email'] as $emailBlock) { if (isset($emailBlock['is_primary'])) { $email = $emailBlock['email']; break; } } } $uniqId = CRM_Utils_Array::value('user_unique_id', $params); if (!$email && $contact->id) { $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contact->id); } } //now set the names. $names = array('sortName' => 'sort_name', 'displayName' => 'display_name'); foreach ($names as $value => $name) { if (empty(${$value})) { if ($email) { ${$value} = $email; } else { if ($uniqId) { ${$value} = $uniqId; } } } //finally if we could not pass anything lets keep db. if (!empty(${$value})) { $contact->{$name} = ${$value}; } } $format = CRM_Utils_Date::getDateFormat('birth'); if ($date = CRM_Utils_Array::value('birth_date', $params)) { if (in_array($format, array('dd-mm', 'mm/dd'))) { $separator = '/'; if ($format == 'dd-mm') { $separator = '-'; } $date = $date . $separator . '1902'; } else { if (in_array($format, array('yy-mm'))) { $date = $date . '-01'; } else { if (in_array($format, array('M yy'))) { $date = '01 ' . $date; } else { if (in_array($format, array('yy'))) { $date = $date . '-01-01'; } } } } $contact->birth_date = CRM_Utils_Date::processDate($date); } else { if ($contact->birth_date) { $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date); } } if ($date = CRM_Utils_Array::value('deceased_date', $params)) { if (in_array($format, array('dd-mm', 'mm/dd'))) { $separator = '/'; if ($format == 'dd-mm') { $separator = '-'; } $date = $date . $separator . '1902'; } else { if (in_array($format, array('yy-mm'))) { $date = $date . '-01'; } else { if (in_array($format, array('M yy'))) { $date = '01 ' . $date; } else { if (in_array($format, array('yy'))) { $date = $date . '-01-01'; } } } } $contact->deceased_date = CRM_Utils_Date::processDate($date); } else { if ($contact->deceased_date) { $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date); } } if ($middle_name = CRM_Utils_Array::value('middle_name', $params)) { $contact->middle_name = $middle_name; } return $contact; }
protected function replaceTokens($input, $contact_id) { //get contact $params = array(array('contact_id', '=', $contact_id, 0, 0)); list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params); $contact = reset($contact); if (!$contact || is_a($contact, 'CRM_Core_Error')) { throw new API_Exception('Could not find contact with ID: ' . $params['contact_id']); } $tokens = CRM_Utils_Token::getTokens($input); // get replacement text for these tokens $returnProperties = array('sort_name' => 1, 'email' => 1, 'do_not_email' => 1, 'is_deceased' => 1, 'on_hold' => 1, 'display_name' => 1, 'preferred_mail_format' => 1); if (isset($tokens['contact'])) { foreach ($tokens['contact'] as $key => $value) { $returnProperties[$value] = 1; } } list($details) = CRM_Utils_Token::getTokenDetails(array($contact_id), $returnProperties, false, false, null, $tokens); $contact = reset($details); // call token hook $hookTokens = array(); CRM_Utils_Hook::tokens($hookTokens); $categories = array_keys($hookTokens); CRM_Utils_Token::replaceGreetingTokens($input, NULL, $contact['contact_id']); $input = CRM_Utils_Token::replaceDomainTokens($input, $domain, true, $tokens, true); $input = CRM_Utils_Token::replaceContactTokens($input, $contact, false, $tokens, false, true); $input = CRM_Utils_Token::replaceComponentTokens($input, $contact, $tokens, true); $input = CRM_Utils_Token::replaceHookTokens($input, $contact, $categories, true); return $input; }
/** * Different type of Contact Tokens. * * @return array */ public static function contactTokens() { static $tokens = NULL; if (!$tokens) { $additionalFields = array('checksum' => array('title' => ts('Checksum')), 'contact_id' => array('title' => ts('Internal Contact ID'))); $exportFields = array_merge(CRM_Contact_BAO_Contact::exportableFields(), $additionalFields); $values = array_merge(array_keys($exportFields)); unset($values[0]); //FIXME:skipping some tokens for time being. $skipTokens = array('is_bulkmail', 'group', 'tag', 'contact_sub_type', 'note', 'is_deceased', 'deceased_date', 'legal_identifier', 'contact_sub_type', 'user_unique_id'); $customFields = CRM_Core_BAO_CustomField::getFields(array('Individual', 'Address')); $legacyTokenNames = array_flip(CRM_Utils_Token::legacyContactTokens()); foreach ($values as $val) { if (in_array($val, $skipTokens)) { continue; } //keys for $tokens should be constant. $token Values are changed for Custom Fields. CRM-3734 $customFieldId = CRM_Core_BAO_CustomField::getKeyID($val); if ($customFieldId) { // CRM-15191 - if key is not in $customFields then the field is disabled and should be ignored if (!empty($customFields[$customFieldId])) { $tokens["{contact.{$val}}"] = $customFields[$customFieldId]['label'] . " :: " . $customFields[$customFieldId]['groupTitle']; } } else { // Support legacy token names $tokenName = CRM_Utils_Array::value($val, $legacyTokenNames, $val); $tokens["{contact.{$tokenName}}"] = $exportFields[$val]['title']; } } // Get all the hook tokens too $hookTokens = array(); CRM_Utils_Hook::tokens($hookTokens); foreach ($hookTokens as $tokenValues) { foreach ($tokenValues as $key => $value) { if (is_numeric($key)) { $key = $value; } if (!preg_match('/^\\{[^\\}]+\\}$/', $key)) { $key = '{' . $key . '}'; } if (preg_match('/^\\{([^\\}]+)\\}$/', $value, $matches)) { $value = $matches[1]; } $tokens[$key] = $value; } } } return $tokens; }
/** * 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 ' ' //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); }
/** * 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']); }
/** * 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); }
/** * Returns an array that denotes the type of token that we are dealing with * we use the type later on when we are doing a token replacement lookup * * @param string $token * The token for which we will be doing adata lookup. * * @return array * An array that holds the token itself and the type. * the type will tell us which function to use for the data lookup * if we need to do a lookup at all */ public function &getDataFunc($token) { static $_categories = NULL; static $_categoryString = NULL; if (!$_categories) { $_categories = array('domain' => NULL, 'action' => NULL, 'mailing' => NULL, 'contact' => NULL); CRM_Utils_Hook::tokens($_categories); $_categoryString = implode('|', array_keys($_categories)); } $funcStruct = array('type' => NULL, 'token' => $token); $matches = array(); if (preg_match('/^href/i', $token) || preg_match('/^http/i', $token)) { // it is a url so we need to check to see if there are any tokens embedded // if so then call this function again to get the token dataFunc // and assign the type 'embedded' so that the data retrieving function // will know what how to handle this token. if (preg_match_all('/(\\{\\w+\\.\\w+\\})/', $token, $matches)) { $funcStruct['type'] = 'embedded_url'; $funcStruct['embed_parts'] = $funcStruct['token'] = array(); foreach ($matches[1] as $match) { $preg_token = '/' . preg_quote($match, '/') . '/'; $list = preg_split($preg_token, $token, 2); $funcStruct['embed_parts'][] = $list[0]; $token = $list[1]; $funcStruct['token'][] = $this->getDataFunc($match); } // fixed truncated url, CRM-7113 if ($token) { $funcStruct['embed_parts'][] = $token; } } else { $funcStruct['type'] = 'url'; } } elseif (preg_match('/^\\{(' . $_categoryString . ')\\.(\\w+)\\}$/', $token, $matches)) { $funcStruct['type'] = $matches[1]; $funcStruct['token'] = $matches[2]; } elseif (preg_match('/\\\\\\{(\\w+\\.\\w+)\\\\\\}|\\{\\{(\\w+\\.\\w+)\\}\\}/', $token, $matches)) { // we are an escaped token // so remove the escape chars $unescaped_token = preg_replace('/\\{\\{|\\}\\}|\\\\\\{|\\\\\\}/', '', $matches[0]); $funcStruct['token'] = '{' . $unescaped_token . '}'; } return $funcStruct; }
/** * Get token list from mailing format & contacts * @param array $contacts * @return array */ public static function getTokenData(&$contacts) { $mailingFormat = Civi::settings()->get('mailing_format'); $tokens = $tokenFields = array(); $messageToken = CRM_Utils_Token::getTokens($mailingFormat); // also get all token values CRM_Utils_Hook::tokenValues($contacts, array_keys($contacts), NULL, $messageToken, 'CRM_Contact_Form_Task_LabelCommon'); CRM_Utils_Hook::tokens($tokens); foreach ($tokens as $category => $catTokens) { foreach ($catTokens as $token => $tokenName) { $tokenFields[] = $token; } } return $tokenFields; }
/** * @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; }
/** * process the form after the input has been submitted and validated * * @access public * @return void */ public function postProcess() { $fv = $this->controller->exportValues($this->_name); $config =& CRM_Core_Config::singleton(); $locName = null; //get the address format sequence from the config file require_once 'CRM/Core/BAO/Preferences.php'; $sequence = CRM_Core_BAO_Preferences::value('mailing_sequence'); foreach ($sequence as $v) { $address[$v] = 1; } if (array_key_exists('postal_code', $address)) { $address['postal_code_suffix'] = 1; } //build the returnproperties $returnProperties = array('display_name' => 1); $mailingFormat = CRM_Core_BAO_Preferences::value('mailing_format'); $mailingFormatProperties = array(); if ($mailingFormat) { $mailingFormatProperties = self::getReturnProperties($mailingFormat); $returnProperties = array_merge($returnProperties, $mailingFormatProperties); } $customFormatProperties = array(); if (stristr($mailingFormat, 'custom_')) { foreach ($mailingFormatProperties as $token => $true) { if (substr($token, 0, 7) == 'custom_') { if (!CRM_Utils_Array::value($token, $customFormatProperties)) { $customFormatProperties[$token] = $mailingFormatProperties[$token]; } } } } if (!empty($customFormatProperties)) { $returnProperties = array_merge($returnProperties, $customFormatProperties); } //get the contacts information $params = array(); if (CRM_Utils_Array::value('location_type_id', $fv)) { $locType = CRM_Core_PseudoConstant::locationType(); $locName = $locType[$fv['location_type_id']]; $location = array('location' => array("{$locName}" => $address)); $returnProperties = array_merge($returnProperties, $location); $params[] = array('location_type', '=', array($fv['location_type_id'] => 1), 0, 0); } else { $returnProperties = array_merge($returnProperties, $address); } $rows = array(); foreach ($this->_contactIds as $key => $contactID) { $params[] = array(CRM_Core_Form::CB_PREFIX . $contactID, '=', 1, 0, 0); } // fix for CRM-2651 if (CRM_Utils_Array::value('do_not_mail', $fv)) { $params[] = array('do_not_mail', '=', 0, 0, 0); } // fix for CRM-2613 $params[] = array('is_deceased', '=', 0, 0, 0); $custom = array(); foreach ($returnProperties as $name => $dontCare) { $cfID = CRM_Core_BAO_CustomField::getKeyID($name); if ($cfID) { $custom[] = $cfID; } } //get the total number of contacts to fetch from database. $numberofContacts = count($this->_contactIds); require_once 'CRM/Contact/BAO/Query.php'; $query =& new CRM_Contact_BAO_Query($params, $returnProperties); $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts); // also get all token values require_once 'CRM/Utils/Hook.php'; CRM_Utils_Hook::tokenValues($details[0], $this->_contactIds); $tokens = array(); CRM_Utils_Hook::tokens($tokens); $tokenFields = array(); foreach ($tokens as $category => $catTokens) { foreach ($catTokens as $token) { $tokenFields[] = $token; } } foreach ($this->_contactIds as $value) { foreach ($custom as $cfID) { if (isset($details[0][$value]["custom_{$cfID}"])) { $details[0][$value]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($details[0][$value]["custom_{$cfID}"], $cfID, $details[1]); } } $contact = CRM_Utils_Array::value($value, $details['0']); if (is_a($contact, 'CRM_Core_Error')) { return null; } // we need to remove all the "_id" unset($contact['contact_id']); if ($locName && CRM_Utils_Array::value($locName, $contact)) { // If location type is not primary, $contact contains // one more array as "$contact[$locName] = array( values... )" $found = false; // we should replace all the tokens that are set in mailing label format foreach ($mailingFormatProperties as $key => $dontCare) { if (CRM_Utils_Array::value($key, $contact)) { $found = true; break; } } if (!$found) { continue; } unset($contact[$locName]); if (CRM_Utils_Array::value('county_id', $contact)) { unset($contact['county_id']); } foreach ($contact as $field => $fieldValue) { $rows[$value][$field] = $fieldValue; } $valuesothers = array(); $paramsothers = array('contact_id' => $value); require_once 'CRM/Core/BAO/Location.php'; $valuesothers = CRM_Core_BAO_Location::getValues($paramsothers, $valuesothers); if (CRM_Utils_Array::value('location_type_id', $fv)) { foreach ($valuesothers as $vals) { if ($vals['location_type_id'] == CRM_Utils_Array::value('location_type_id', $fv)) { foreach ($vals as $k => $v) { if (in_array($k, array('email', 'phone', 'im', 'openid'))) { if ($k == 'im') { $rows[$value][$k] = $v['1']['name']; } else { $rows[$value][$k] = $v['1'][$k]; } $rows[$value][$k . '_id'] = $v['1']['id']; } } } } } } else { $found = false; // we should replace all the tokens that are set in mailing label format foreach ($mailingFormatProperties as $key => $dontCare) { if (CRM_Utils_Array::value($key, $contact)) { $found = true; break; } } if (!$found) { continue; } if (CRM_Utils_Array::value('addressee', $contact)) { $contact['addressee'] = $contact['addressee_display']; } // now create the rows for generating mailing labels foreach ($contact as $field => $fieldValue) { $rows[$value][$field] = $fieldValue; } } } $individualFormat = false; if (isset($fv['merge_same_address'])) { $this->mergeSameAddress($rows); $individualFormat = true; } // format the addresses according to CIVICRM_ADDRESS_FORMAT (CRM-1327) require_once 'CRM/Utils/Address.php'; foreach ($rows as $id => $row) { if ($commMethods = CRM_Utils_Array::value('preferred_communication_method', $row)) { require_once 'CRM/Core/PseudoConstant.php'; $val = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $commMethods)); $comm = CRM_Core_PseudoConstant::pcm(); $temp = array(); foreach ($val as $vals) { $temp[] = $comm[$vals]; } $row['preferred_communication_method'] = implode(', ', $temp); } $row['id'] = $id; $formatted = CRM_Utils_Address::format($row, 'mailing_format', false, true, $individualFormat, $tokenFields); // CRM-2211: UFPDF doesn't have bidi support; use the PECL fribidi package to fix it. // On Ubuntu (possibly Debian?) be aware of http://pecl.php.net/bugs/bug.php?id=12366 // Due to FriBidi peculiarities, this can't be called on // a multi-line string, hence the explode+implode approach. if (function_exists('fribidi_log2vis')) { $lines = explode("\n", $formatted); foreach ($lines as $i => $line) { $lines[$i] = fribidi_log2vis($line, FRIBIDI_AUTO, FRIBIDI_CHARSET_UTF8); } $formatted = implode("\n", $lines); } $rows[$id] = array($formatted); } //call function to create labels self::createLabel($rows, $fv['label_id']); exit(1); }
/** * Send SMS. * * @param array $contactDetails * @param array $activityParams * @param array $smsParams * @param $contactIds * @param int $userID * * @return array * @throws CRM_Core_Exception */ public static function sendSMS(&$contactDetails, &$activityParams, &$smsParams = array(), &$contactIds, $userID = NULL) { if ($userID == NULL) { $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); } $text =& $activityParams['sms_text_message']; // CRM-4575 // token replacement of addressee/email/postal greetings // get the tokens added in subject and message $messageToken = CRM_Utils_Token::getTokens($text); // Create the meta level record first ( sms activity ) $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'SMS', 'name'); $details = $text; $activitySubject = $activityParams['activity_subject']; $activityParams = array('source_contact_id' => $userID, 'activity_type_id' => $activityTypeID, 'activity_date_time' => date('YmdHis'), 'subject' => $activitySubject, 'details' => $details, 'status_id' => 2); $activity = self::create($activityParams); $activityID = $activity->id; $returnProperties = array(); if (isset($messageToken['contact'])) { foreach ($messageToken['contact'] as $key => $value) { $returnProperties[$value] = 1; } } // call token hook $tokens = array(); CRM_Utils_Hook::tokens($tokens); $categories = array_keys($tokens); // get token details for contacts, call only if tokens are used $details = array(); if (!empty($returnProperties) || !empty($tokens)) { list($details) = CRM_Utils_Token::getTokenDetails($contactIds, $returnProperties, NULL, NULL, FALSE, $messageToken, 'CRM_Activity_BAO_Activity'); } $success = 0; $escapeSmarty = FALSE; $errMsgs = array(); foreach ($contactDetails as $values) { $contactId = $values['contact_id']; 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}"]); } $tokenText = CRM_Utils_Token::replaceContactTokens($text, $values, FALSE, $messageToken, FALSE, $escapeSmarty); $tokenText = CRM_Utils_Token::replaceHookTokens($tokenText, $values, $categories, FALSE, $escapeSmarty); // Only send if the phone is of type mobile $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name'); if ($values['phone_type_id'] == CRM_Utils_Array::value('Mobile', $phoneTypes)) { $smsParams['To'] = $values['phone']; } else { $smsParams['To'] = ''; } $sendResult = self::sendSMSMessage($contactId, $tokenText, $smsParams, $activityID, $userID); if (PEAR::isError($sendResult)) { // Collect all of the PEAR_Error objects $errMsgs[] = $sendResult; } else { $success++; } } // If at least one message was sent and no errors // were generated then return a boolean value of TRUE. // Otherwise, return FALSE (no messages sent) or // and array of 1 or more PEAR_Error objects. $sent = FALSE; if ($success > 0 && count($errMsgs) == 0) { $sent = TRUE; } elseif (count($errMsgs) > 0) { $sent = $errMsgs; } return array($sent, $activity->id, $success); }
/** * Part of the post process which prepare and extract information from the template. * * * @param array $formValues * * @return array * [$categories, $html_message, $messageToken, $returnProperties] */ public static function processMessageTemplate($formValues) { $html_message = CRM_Utils_Array::value('html_message', $formValues); // process message template if (!empty($formValues['saveTemplate']) || !empty($formValues['updateTemplate'])) { $messageTemplate = array('msg_text' => NULL, 'msg_html' => $formValues['html_message'], 'msg_subject' => NULL, 'is_active' => TRUE); $messageTemplate['pdf_format_id'] = 'null'; if (!empty($formValues['bind_format']) && $formValues['format_id']) { $messageTemplate['pdf_format_id'] = $formValues['format_id']; } if (!empty($formValues['saveTemplate']) && $formValues['saveTemplate']) { $messageTemplate['msg_title'] = $formValues['saveTemplateName']; CRM_Core_BAO_MessageTemplate::add($messageTemplate); } if (!empty($formValues['updateTemplate']) && $formValues['template'] && $formValues['updateTemplate']) { $messageTemplate['id'] = $formValues['template']; unset($messageTemplate['msg_title']); CRM_Core_BAO_MessageTemplate::add($messageTemplate); } } elseif (CRM_Utils_Array::value('template', $formValues) > 0) { if (!empty($formValues['bind_format']) && $formValues['format_id']) { $query = "UPDATE civicrm_msg_template SET pdf_format_id = {$formValues['format_id']} WHERE id = {$formValues['template']}"; } else { $query = "UPDATE civicrm_msg_template SET pdf_format_id = NULL WHERE id = {$formValues['template']}"; } CRM_Core_DAO::executeQuery($query); $documentInfo = CRM_Core_BAO_File::getEntityFile('civicrm_msg_template', $formValues['template']); foreach ((array) $documentInfo as $info) { list($html_message, $formValues['document_type']) = CRM_Utils_PDF_Document::docReader($info['fullPath'], $info['mime_type']); $formValues['document_file_path'] = $info['fullPath']; } } elseif (!empty($formValues['document_file'])) { list($html_message, $formValues['document_type']) = CRM_Utils_PDF_Document::docReader($formValues['document_file']['name'], $formValues['document_file']['type']); $formValues['document_file_path'] = $formValues['document_file']['name']; } if (!empty($formValues['update_format'])) { $bao = new CRM_Core_BAO_PdfFormat(); $bao->savePdfFormat($formValues, $formValues['format_id']); } $tokens = array(); CRM_Utils_Hook::tokens($tokens); $categories = array_keys($tokens); //time being hack to strip ' ' //from particular letter line, CRM-6798 self::formatMessage($html_message); $messageToken = CRM_Utils_Token::getTokens($html_message); $returnProperties = array(); if (isset($messageToken['contact'])) { foreach ($messageToken['contact'] as $key => $value) { $returnProperties[$value] = 1; } } return array($formValues, $categories, $html_message, $messageToken, $returnProperties); }