Ejemplo n.º 1
0
 /**
  * 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);
 }
Ejemplo n.º 2
0
 /**
  * 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);
 }
 /**
  *
  *  _getTokens parses out all of the tokens that have been
  *  included in the html and text bodies of the email
  *  we get the tokens and then separate them into an
  *  internal structure named tokens that has the same
  *  form as the static tokens property(?) of the CRM_Utils_Token class.
  *  The difference is that there might be repeated token names as we want the
  *  structures to represent the order in which tokens were found from left to right, top to bottom.
  *
  *
  * @param string $prop name of the property that holds the text that we want to scan for tokens (html, text).
  *   Name of the property that holds the text that we want to scan for tokens (html, text).
  *
  * @return void
  */
 private function _getTokens($prop)
 {
     $templates = $this->getTemplates();
     $newTokens = CRM_Utils_Token::getTokens($templates[$prop]);
     foreach ($newTokens as $type => $names) {
         if (!isset($this->tokens[$prop][$type])) {
             $this->tokens[$prop][$type] = array();
         }
         foreach ($names as $key => $name) {
             $this->tokens[$prop][$type][] = $name;
         }
     }
 }
Ejemplo n.º 4
0
 /**
  * @param array $params
  *
  * @throws Exception
  */
 public static function updateGreeting($params)
 {
     $contactType = $params['ct'];
     $greeting = $params['gt'];
     $valueID = $id = CRM_Utils_Array::value('id', $params);
     $force = CRM_Utils_Array::value('force', $params);
     $limit = CRM_Utils_Array::value('limit', $params);
     // if valueID is not passed use default value
     if (!$valueID) {
         $valueID = $id = self::defaultGreeting($contactType, $greeting);
     }
     $filter = array('contact_type' => $contactType, 'greeting_type' => $greeting);
     $allGreetings = CRM_Core_PseudoConstant::greeting($filter);
     $originalGreetingString = $greetingString = CRM_Utils_Array::value($valueID, $allGreetings);
     if (!$greetingString) {
         CRM_Core_Error::fatal(ts('Incorrect greeting value id %1, or no default greeting for this contact type and greeting type.', array(1 => $valueID)));
     }
     // build return properties based on tokens
     $greetingTokens = CRM_Utils_Token::getTokens($greetingString);
     $tokens = CRM_Utils_Array::value('contact', $greetingTokens);
     $greetingsReturnProperties = array();
     if (is_array($tokens)) {
         $greetingsReturnProperties = array_fill_keys(array_values($tokens), 1);
     }
     // Process ALL contacts only when force=1 or force=2 is passed. Else only contacts with NULL greeting or addressee value are updated.
     $processAll = $processOnlyIdSet = FALSE;
     if ($force == 1) {
         $processAll = TRUE;
     } elseif ($force == 2) {
         $processOnlyIdSet = TRUE;
     }
     //FIXME : apiQuery should handle these clause.
     $filterContactFldIds = $filterIds = array();
     $idFldName = $displayFldName = NULL;
     if (in_array($greeting, CRM_Contact_BAO_Contact::$_greetingTypes)) {
         $idFldName = $greeting . '_id';
         $displayFldName = $greeting . '_display';
     }
     if ($idFldName) {
         $queryParams = array(1 => array($contactType, 'String'));
         // if $force == 1 then update all contacts else only
         // those with NULL greeting or addressee value CRM-9476
         if ($processAll) {
             $sql = "SELECT DISTINCT id, {$idFldName} FROM civicrm_contact WHERE contact_type = %1 ";
         } else {
             $sql = "\n          SELECT DISTINCT id, {$idFldName}\n          FROM civicrm_contact\n          WHERE contact_type = %1\n          AND ({$idFldName} IS NULL\n          OR ( {$idFldName} IS NOT NULL AND ({$displayFldName} IS NULL OR {$displayFldName} = '')) )";
         }
         if ($limit) {
             $sql .= " LIMIT 0, %2";
             $queryParams += array(2 => array($limit, 'Integer'));
         }
         $dao = CRM_Core_DAO::executeQuery($sql, $queryParams);
         while ($dao->fetch()) {
             $filterContactFldIds[$dao->id] = $dao->{$idFldName};
             if (!CRM_Utils_System::isNull($dao->{$idFldName})) {
                 $filterIds[$dao->id] = $dao->{$idFldName};
             }
         }
     }
     if (empty($filterContactFldIds)) {
         $filterContactFldIds[] = 0;
     }
     // retrieve only required contact information
     $extraParams[] = array('contact_type', '=', $contactType, 0, 0);
     // we do token replacement in the replaceGreetingTokens hook
     list($greetingDetails) = CRM_Utils_Token::getTokenDetails(array_keys($filterContactFldIds), $greetingsReturnProperties, FALSE, FALSE, $extraParams);
     // perform token replacement and build update SQL
     $contactIds = array();
     $cacheFieldQuery = "UPDATE civicrm_contact SET {$greeting}_display = CASE id ";
     foreach ($greetingDetails as $contactID => $contactDetails) {
         if (!$processAll && !array_key_exists($contactID, $filterContactFldIds)) {
             continue;
         }
         if ($processOnlyIdSet && !array_key_exists($contactID, $filterIds)) {
             continue;
         }
         if ($id) {
             $greetingString = $originalGreetingString;
             $contactIds[] = $contactID;
         } else {
             if ($greetingBuffer = CRM_Utils_Array::value($filterContactFldIds[$contactID], $allGreetings)) {
                 $greetingString = $greetingBuffer;
             }
         }
         self::processGreetingTemplate($greetingString, $contactDetails, $contactID, 'CRM_UpdateGreeting');
         $greetingString = CRM_Core_DAO::escapeString($greetingString);
         $cacheFieldQuery .= " WHEN {$contactID} THEN '{$greetingString}' ";
         $allContactIds[] = $contactID;
     }
     if (!empty($allContactIds)) {
         $cacheFieldQuery .= " ELSE {$greeting}_display\n                              END;";
         if (!empty($contactIds)) {
             // need to update greeting _id field.
             // reset greeting _custom
             $resetCustomGreeting = '';
             if ($valueID != 4) {
                 $resetCustomGreeting = ", {$greeting}_custom = NULL ";
             }
             $queryString = "\nUPDATE civicrm_contact\nSET {$greeting}_id = {$valueID}\n    {$resetCustomGreeting}\nWHERE id IN (" . implode(',', $contactIds) . ")";
             CRM_Core_DAO::executeQuery($queryString);
         }
         // now update cache field
         CRM_Core_DAO::executeQuery($cacheFieldQuery);
     }
 }
Ejemplo n.º 5
0
 /**
  * Get html and cache results.
  *
  * @param $url
  *
  * @return array|NULL
  *   array of gettingStarted items; or NULL if not available
  */
 public function _getHtml($url)
 {
     $httpClient = new CRM_Utils_HttpClient(self::CHECK_TIMEOUT);
     list($status, $html) = $httpClient->get($url);
     if ($status !== CRM_Utils_HttpClient::STATUS_OK) {
         return NULL;
     }
     $tokensList = CRM_Utils_Token::getTokens($html);
     $this->replaceLinkToken($tokensList, $html);
     if ($html) {
         CRM_Core_BAO_Cache::setItem($html, 'dashboard', 'gettingStarted');
     }
     return $html;
 }
 public function updateGreeting()
 {
     $config = CRM_Core_Config::singleton();
     $contactType = CRM_Utils_Request::retrieve('ct', 'String', CRM_Core_DAO::$_nullArray, FALSE, NULL, 'REQUEST');
     if (!in_array($contactType, array('Individual', 'Household', 'Organization'))) {
         CRM_Core_Error::fatal(ts('Invalid Contact Type.'));
     }
     $greeting = CRM_Utils_Request::retrieve('gt', 'String', CRM_Core_DAO::$_nullArray, FALSE, NULL, 'REQUEST');
     if (!in_array($greeting, array('email_greeting', 'postal_greeting', 'addressee'))) {
         CRM_Core_Error::fatal(ts('Invalid Greeting Type.'));
     }
     if (in_array($greeting, array('email_greeting', 'postal_greeting')) && $contactType == 'Organization') {
         CRM_Core_Error::fatal(ts('You cannot use %1 for contact type %2.', array(1 => $greeting, 2 => $contactType)));
     }
     $valueID = $id = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullArray, FALSE, NULL, 'REQUEST');
     // if valueID is not passed use default value
     if (!$valueID) {
         require_once 'CRM/Core/OptionGroup.php';
         $contactTypeFilters = array(1 => 'Individual', 2 => 'Household', 3 => 'Organization');
         $filter = CRM_Utils_Array::key($contactType, $contactTypeFilters);
         $defaulValueID = CRM_Core_OptionGroup::values($greeting, NULL, NULL, NULL, " AND is_default = 1 AND ( filter = {$filter} OR filter = 0 )", "value");
         $valueID = array_pop($defaulValueID);
     }
     $filter = array('contact_type' => $contactType, 'greeting_type' => $greeting);
     $allGreetings = CRM_Core_PseudoConstant::greeting($filter);
     $originalGreetingString = $greetingString = CRM_Utils_Array::value($valueID, $allGreetings);
     if (!$greetingString) {
         CRM_Core_Error::fatal(ts('Incorrect greeting value id %1.', array(1 => $valueID)));
     }
     // build return properties based on tokens
     require_once 'CRM/Utils/Token.php';
     $greetingTokens = CRM_Utils_Token::getTokens($greetingString);
     $tokens = CRM_Utils_Array::value('contact', $greetingTokens);
     $greetingsReturnProperties = array();
     if (is_array($tokens)) {
         $greetingsReturnProperties = array_fill_keys(array_values($tokens), 1);
     }
     //process all contacts only when force pass.
     $force = CRM_Utils_Request::retrieve('force', 'String', CRM_Core_DAO::$_nullArray, FALSE, NULL, 'REQUEST');
     $processAll = $processOnlyIdSet = FALSE;
     if (in_array($force, array(1, 'true'))) {
         $processAll = TRUE;
     } elseif ($force == 2) {
         $processOnlyIdSet = TRUE;
     }
     //FIXME : apiQuery should handle these clause.
     $filterContactFldIds = $filterIds = array();
     if (!$processAll) {
         $idFldName = $displayFldName = NULL;
         if ($greeting == 'email_greeting' || $greeting == 'postal_greeting' || $greeting == 'addressee') {
             $idFldName = $greeting . '_id';
             $displayFldName = $greeting . '_display';
         }
         if ($idFldName) {
             $sql = "\nSELECT DISTINCT id, {$idFldName}\n  FROM civicrm_contact\n WHERE contact_type = %1\n   AND ( {$idFldName} IS NULL OR\n         ( {$idFldName} IS NOT NULL AND {$displayFldName} IS NULL ) )\n   ";
             $dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($contactType, 'String')));
             while ($dao->fetch()) {
                 $filterContactFldIds[$dao->id] = $dao->{$idFldName};
                 if (!CRM_Utils_System::isNull($dao->{$idFldName})) {
                     $filterIds[$dao->id] = $dao->{$idFldName};
                 }
             }
         }
         if (empty($filterContactFldIds)) {
             $filterContactFldIds[] = 0;
         }
     }
     if (empty($filterContactFldIds)) {
         return;
     }
     // retrieve only required contact information
     require_once 'CRM/Utils/Token.php';
     $extraParams[] = array('contact_type', '=', $contactType, 0, 0);
     // we do token replacement in the replaceGreetingTokens hook
     list($greetingDetails) = CRM_Utils_Token::getTokenDetails(array_keys($filterContactFldIds), $greetingsReturnProperties, FALSE, FALSE, $extraParams);
     // perform token replacement and build update SQL
     $contactIds = array();
     $cacheFieldQuery = "UPDATE civicrm_contact SET {$greeting}_display = CASE id ";
     foreach ($greetingDetails as $contactID => $contactDetails) {
         if (!$processAll && !array_key_exists($contactID, $filterContactFldIds)) {
             continue;
         }
         if ($processOnlyIdSet) {
             if (!array_key_exists($contactID, $filterIds)) {
                 continue;
             }
             if ($id) {
                 $greetingString = $originalGreetingString;
                 $contactIds[] = $contactID;
             } else {
                 if ($greetingBuffer = CRM_Utils_Array::value($filterContactFldIds[$contactID], $allGreetings)) {
                     $greetingString = $greetingBuffer;
                 }
             }
             $allContactIds[] = $contactID;
         } else {
             $greetingString = $originalGreetingString;
             if ($greetingBuffer = CRM_Utils_Array::value($filterContactFldIds[$contactID], $allGreetings)) {
                 $greetingString = $greetingBuffer;
             } else {
                 $contactIds[] = $contactID;
             }
         }
         CRM_Contact_BAO_Contact_Utils::processGreetingTemplate($greetingString, $contactDetails, $contactID, 'CRM_UpdateGreeting');
         $greetingString = CRM_Core_DAO::escapeString($greetingString);
         $cacheFieldQuery .= " WHEN {$contactID} THEN '{$greetingString}' ";
         $allContactIds[] = $contactID;
     }
     if (!empty($allContactIds)) {
         $cacheFieldQuery .= " ELSE {$greeting}_display\n                              END;";
         if (!empty($contactIds)) {
             // need to update greeting _id field.
             $queryString = "\nUPDATE civicrm_contact\n   SET {$greeting}_id = {$valueID}\n WHERE id IN (" . implode(',', $contactIds) . ")";
             CRM_Core_DAO::executeQuery($queryString);
         }
         // now update cache field
         CRM_Core_DAO::executeQuery($cacheFieldQuery);
     }
 }
Ejemplo n.º 7
0
 /**
  * @param int $contactId
  * @param $email
  * @param int $messageTemplateID
  * @param $from
  *
  * @return bool|NULL
  */
 public static function sendReminder($contactId, $email, $messageTemplateID, $from)
 {
     $messageTemplates = new CRM_Core_DAO_MessageTemplate();
     $messageTemplates->id = $messageTemplateID;
     $domain = CRM_Core_BAO_Domain::getDomain();
     $result = NULL;
     $hookTokens = array();
     if ($messageTemplates->find(TRUE)) {
         $body_text = $messageTemplates->msg_text;
         $body_html = $messageTemplates->msg_html;
         $body_subject = $messageTemplates->msg_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;
         }
         //CRM-5734
         // get tokens to be replaced
         $tokens = array_merge(CRM_Utils_Token::getTokens($body_text), CRM_Utils_Token::getTokens($body_html), CRM_Utils_Token::getTokens($body_subject));
         // get replacement text for these tokens
         $returnProperties = array("preferred_mail_format" => 1);
         if (isset($tokens['contact'])) {
             foreach ($tokens['contact'] as $key => $value) {
                 $returnProperties[$value] = 1;
             }
         }
         list($details) = CRM_Utils_Token::getTokenDetails(array($contactId), $returnProperties, NULL, NULL, FALSE, $tokens, 'CRM_Core_BAO_MessageTemplate');
         $contact = reset($details);
         // call token hook
         $hookTokens = array();
         CRM_Utils_Hook::tokens($hookTokens);
         $categories = array_keys($hookTokens);
         // do replacements in text and html body
         $type = array('html', 'text');
         foreach ($type as $key => $value) {
             $bodyType = "body_{$value}";
             if (${$bodyType}) {
                 CRM_Utils_Token::replaceGreetingTokens(${$bodyType}, NULL, $contact['contact_id']);
                 ${$bodyType} = CRM_Utils_Token::replaceDomainTokens(${$bodyType}, $domain, TRUE, $tokens, TRUE);
                 ${$bodyType} = CRM_Utils_Token::replaceContactTokens(${$bodyType}, $contact, FALSE, $tokens, FALSE, TRUE);
                 ${$bodyType} = CRM_Utils_Token::replaceComponentTokens(${$bodyType}, $contact, $tokens, TRUE);
                 ${$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}}");
         }
         // do replacements in message subject
         $messageSubject = CRM_Utils_Token::replaceContactTokens($body_subject, $contact, FALSE, $tokens);
         $messageSubject = CRM_Utils_Token::replaceDomainTokens($messageSubject, $domain, TRUE, $tokens);
         $messageSubject = CRM_Utils_Token::replaceComponentTokens($messageSubject, $contact, $tokens, 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);
     }
     $messageTemplates->free();
     return $result;
 }
Ejemplo n.º 8
0
 /**
  * Build badges parameters before actually creating badges.
  *
  * @param array $params
  *   Associated array of submitted values.
  * @param CRM_Core_Form $form
  *
  * @return void
  */
 public static function buildBadges(&$params, &$form)
 {
     // get name badge layout info
     $layoutInfo = CRM_Badge_BAO_Layout::buildLayout($params);
     // split/get actual field names from token and individual contact image URLs
     $returnProperties = array();
     if (!empty($layoutInfo['data']['token'])) {
         foreach ($layoutInfo['data']['token'] as $index => $value) {
             $element = '';
             if ($value) {
                 $token = CRM_Utils_Token::getTokens($value);
                 if (key($token) == 'contact') {
                     $element = $token['contact'][0];
                 } elseif (key($token) == 'event') {
                     $element = $token['event'][0];
                     //FIX ME - we need to standardize event token names
                     if (substr($element, 0, 6) != 'event_') {
                         $element = 'event_' . $element;
                     }
                 } elseif (key($token) == 'participant') {
                     $element = $token['participant'][0];
                 }
                 // build returnproperties for query
                 $returnProperties[$element] = 1;
             }
             // add actual field name to row element
             $layoutInfo['data']['rowElements'][$index] = $element;
         }
     }
     // add additional required fields for query execution
     $additionalFields = array('participant_register_date', 'participant_id', 'event_id', 'contact_id', 'image_URL');
     foreach ($additionalFields as $field) {
         $returnProperties[$field] = 1;
     }
     if ($form->_single) {
         $queryParams = NULL;
     } else {
         $queryParams = $form->get('queryParams');
     }
     $query = new CRM_Contact_BAO_Query($queryParams, $returnProperties, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_EVENT);
     list($select, $from, $where, $having) = $query->query();
     if (empty($where)) {
         $where = "WHERE {$form->_componentClause}";
     } else {
         $where .= " AND {$form->_componentClause}";
     }
     $sortOrder = NULL;
     if ($form->get(CRM_Utils_Sort::SORT_ORDER)) {
         $sortOrder = $form->get(CRM_Utils_Sort::SORT_ORDER);
         if (!empty($sortOrder)) {
             $sortOrder = " ORDER BY {$sortOrder}";
         }
     }
     $queryString = "{$select} {$from} {$where} {$having} {$sortOrder}";
     $dao = CRM_Core_DAO::executeQuery($queryString);
     $rows = array();
     while ($dao->fetch()) {
         $query->convertToPseudoNames($dao);
         $rows[$dao->participant_id] = array();
         foreach ($returnProperties as $key => $dontCare) {
             $value = isset($dao->{$key}) ? $dao->{$key} : NULL;
             // Format custom fields
             if (strstr($key, 'custom_') && isset($value)) {
                 $value = CRM_Core_BAO_CustomField::getDisplayValue($value, substr($key, 7), $query->_options, $dao->contact_id);
             }
             $rows[$dao->participant_id][$key] = $value;
         }
     }
     $eventBadgeClass = new CRM_Badge_BAO_Badge();
     $eventBadgeClass->createLabels($rows, $layoutInfo);
 }
Ejemplo n.º 9
0
 /**
  * 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;
 }
 /**
  * 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);
 }
Ejemplo n.º 11
0
 /**
  * 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;
 }
Ejemplo n.º 12
0
 /**
  * Register a string for which we'll need to merge in tokens.
  *
  * @param string $name
  *   Ex: 'subject', 'body_html'.
  * @param string $value
  *   Ex: '<p>Hello {contact.name}</p>'.
  * @param string $format
  *   Ex: 'text/html'.
  * @return TokenProcessor
  */
 public function addMessage($name, $value, $format)
 {
     $this->messages[$name] = array('string' => $value, 'format' => $format, 'tokens' => \CRM_Utils_Token::getTokens($value));
     return $this;
 }
 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;
 }
Ejemplo n.º 14
0
 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);
 }
Ejemplo n.º 15
0
 /**
  * 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 '&nbsp;'
     //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);
 }