Ejemplo n.º 1
0
 static function checkAddress(&$values)
 {
     if (!isset($values['street_address']) || !isset($values['city']) && !isset($values['state_province']) && !isset($values['postal_code'])) {
         return false;
     }
     require_once 'CRM/Core/BAO/Preferences.php';
     $userID = CRM_Core_BAO_Preferences::value('address_standardization_userid');
     $url = CRM_Core_BAO_Preferences::value('address_standardization_url');
     if (empty($userID) || empty($url)) {
         return false;
     }
     $address2 = str_replace(',', '', $values['street_address']);
     $XMLQuery = '<AddressValidateRequest USERID="' . $userID . '"><Address ID="0"><Address1>' . $values['supplemental_address_1'] . '</Address1><Address2>' . $address2 . '</Address2><City>' . $values['city'] . '</City><State>' . $values['state_province'] . '</State><Zip5>' . $values['postal_code'] . '</Zip5><Zip4>' . $values['postal_code_suffix'] . '</Zip4></Address></AddressValidateRequest>';
     require_once 'HTTP/Request.php';
     $request =& new HTTP_Request();
     $request->setURL($url);
     $request->addQueryString('API', 'Verify');
     $request->addQueryString('XML', $XMLQuery);
     $response = $request->sendRequest();
     $session =& CRM_Core_Session::singleton();
     $code = $request->getResponseCode();
     if ($code != 200) {
         $session->setStatus(ts('USPS Address Lookup Failed with HTTP status code: $code'));
         return false;
     }
     $responseBody = $request->getResponseBody();
     $xml = simplexml_load_string($responseBody);
     if (is_null($xml) || is_null($xml->Address)) {
         $session->setStatus(ts('Your USPS API Lookup has Failed.'));
         return false;
     }
     if ($xml->Number == '80040b1a') {
         $session->setStatus(ts('Your USPS API Authorization has Failed.'));
         return false;
     }
     if (array_key_exists('Error', $xml->Address)) {
         $session->setStatus(ts('Address not found in USPS database.'));
         return false;
     }
     $values['street_address'] = (string) $xml->Address->Address2;
     $values['city'] = (string) $xml->Address->City;
     $values['state_province'] = (string) $xml->Address->State;
     $values['postal_code'] = (string) $xml->Address->Zip5;
     $values['postal_code_suffix'] = (string) $xml->Address->Zip4;
     if (array_key_exists('Address1', $xml->Address)) {
         $values['supplemental_address_1'] = (string) $xml->Address->Address1;
     }
     return true;
 }
Ejemplo n.º 2
0
 function upgrade($rev)
 {
     // fix CRM-5270: if civicrm_report_instance.description is localised,
     // recreate it based on the first locale’s description_xx_YY contents
     // and drop all the description_xx_YY columns
     if (!CRM_Core_DAO::checkFieldExists('civicrm_report_instance', 'description')) {
         require_once 'CRM/Core/DAO/Domain.php';
         $domain = new CRM_Core_DAO_Domain();
         $domain->find(true);
         $locales = explode(CRM_Core_DAO::VALUE_SEPARATOR, $domain->locales);
         CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_report_instance ADD description VARCHAR(255)");
         CRM_Core_DAO::executeQuery("UPDATE civicrm_report_instance SET description = description_{$locales[0]}");
         CRM_Core_DAO::executeQuery("DROP TRIGGER civicrm_report_instance_before_insert");
         foreach ($locales as $locale) {
             CRM_Core_DAO::executeQuery("DROP VIEW civicrm_report_instance_{$locale}");
             CRM_Core_DAO::executeQuery("ALTER TABLE civicrm_report_instance DROP description_{$locale}");
         }
     }
     //We execute some part of php after sql and then again sql
     //So using conditions for skipping some part of sql CRM-4575
     $upgrade =& new CRM_Upgrade_Form();
     //Run the SQL file (1)
     $upgrade->processSQL($rev);
     //replace  with ; in report instance
     $sql = "UPDATE civicrm_report_instance \n                       SET form_values = REPLACE(form_values,'#',';') ";
     CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
     //delete unnecessary activities
     $bulkEmailID = CRM_Core_OptionGroup::getValue('activity_type', 'Bulk Email', 'name');
     if ($bulkEmailID) {
         $mailingActivityIds = array();
         $query = " \n            SELECT max( ca.id ) as aid, \n                   ca.source_record_id sid\n            FROM civicrm_activity ca\n            WHERE ca.activity_type_id = %1 \n            GROUP BY ca.source_record_id";
         $params = array(1 => array($bulkEmailID, 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($query, $params);
         while ($dao->fetch()) {
             $updateQuery = "\n                UPDATE civicrm_activity_target cat, civicrm_activity ca \n                    SET cat.activity_id = {$dao->aid}  \n                WHERE ca.source_record_id IS NOT NULL   AND\n                      ca.activity_type_id = %1          AND \n                      ca.id <> {$dao->aid}              AND \n                      ca.source_record_id = {$dao->sid} AND \n                      ca.id = cat.activity_id";
             $updateParams = array(1 => array($bulkEmailID, 'Integer'));
             CRM_Core_DAO::executeQuery($updateQuery, $updateParams);
             $deleteQuery = " \n                DELETE ca.* \n                FROM civicrm_activity ca \n                WHERE ca.source_record_id IS NOT NULL  AND \n                      ca.activity_type_id = %1         AND \n                      ca.id <> {$dao->aid}             AND \n                      ca.source_record_id = {$dao->sid}";
             $deleteParams = array(1 => array($bulkEmailID, 'Integer'));
             CRM_Core_DAO::executeQuery($deleteQuery, $deleteParams);
         }
     }
     //CRM-4453
     //lets insert column in civicrm_aprticipant table
     $query = "\n        ALTER TABLE `civicrm_participant` \n            ADD `fee_currency` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL COMMENT '3 character string, value derived from config setting.' AFTER `discount_id`";
     CRM_Core_DAO::executeQuery($query);
     //get currency from contribution table if exists/default
     //insert currency when fee_amount != NULL or event is paid.
     $query = "\n        SELECT  civicrm_participant.id \n        FROM    civicrm_participant\n            LEFT JOIN  civicrm_event \n                   ON ( civicrm_participant.event_id = civicrm_event.id )\n        WHERE  civicrm_participant.fee_amount IS NOT NULL OR \n               civicrm_event.is_monetary = 1";
     $participant = CRM_Core_DAO::executeQuery($query);
     while ($participant->fetch()) {
         $query = "\n            SELECT civicrm_contribution.currency \n            FROM   civicrm_contribution, \n                   civicrm_participant_payment\n            WHERE  civicrm_contribution.id = civicrm_participant_payment.contribution_id AND  \n                   civicrm_participant_payment.participant_id = {$participant->id}";
         $currencyID = CRM_Core_DAO::singleValueQuery($query);
         if (!$currencyID) {
             $config =& CRM_Core_Config::singleton();
             $currencyID = $config->defaultCurrency;
         }
         //finally update participant record.
         CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $participant->id, 'fee_currency', $currencyID);
     }
     //CRM-4575
     //check whether {contact.name} is set in mailing labels
     require_once 'CRM/Core/BAO/Preferences.php';
     $mailingFormat = CRM_Core_BAO_Preferences::value('mailing_format');
     $addNewAddressee = true;
     if (strpos($mailingFormat, '{contact.contact_name}') === false) {
         $addNewAddressee = false;
     } else {
         //else compare individual name format with default individual addressee.
         $individualNameFormat = CRM_Core_BAO_Preferences::value('individual_name_format');
         $defaultAddressee = CRM_Core_OptionGroup::values('addressee', false, false, false, " AND v.filter = 1 AND v.is_default =  1", 'label');
         if (array_search($individualNameFormat, $defaultAddressee) !== false) {
             $addNewAddressee = false;
         }
     }
     require_once 'CRM/Utils/System.php';
     $docURL = CRM_Utils_System::docURL2('Update Greetings and Address Data for Contacts', false, null, null, 'color: white; text-decoration: underline;');
     if ($addNewAddressee) {
         //otherwise insert new token in addressee and set as a default
         $addresseeGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'addressee', 'id', 'name');
         $optionValueParams = array('label' => $individualNameFormat, 'is_active' => 1, 'contactOptions' => 1, 'filter' => 1, 'is_default' => 1, 'reset_default_for' => array('filter' => "0, 1"));
         $action = CRM_Core_Action::ADD;
         $addresseeGroupParams = array('name' => 'addressee');
         $fieldValues = array('option_group_id' => $addresseeGroupId);
         $weight = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues);
         $optionValueParams['weight'] = $weight;
         $addresseeToken = CRM_Core_OptionValue::addOptionValue($optionValueParams, $addresseeGroupParams, $action, $optionId = null);
         $afterUpgradeMessage = ts("During this upgrade, Postal Addressee values have been stored for each contact record using the system default format - %2.You will need to run the included command-line script to update your Individual contact records to use the \"Individual Name Format\" previously specified for your site %1", array(1 => $docURL, 2 => array_pop($defaultAddressee)));
     } else {
         $afterUpgradeMessage = ts("Email Greeting, Postal Greeting and Postal Addressee values have been stored for all contact records based on the system default formats. If you want to use a different format for any of these contact fields - you can run the provided command line script to update contacts to a different format %1 ", array(1 => $docURL));
     }
     //replace contact.contact_name with contact.addressee in civicrm_preference.mailing_format
     $updateQuery = "\n        UPDATE civicrm_preferences \n               SET `mailing_format` = \n                    replace(`mailing_format`, '{contact.contact_name}','{contact.addressee}')";
     CRM_Core_DAO::executeQuery($updateQuery);
     //drop column individual_name_format
     $alterQuery = "\n        ALTER TABLE `civicrm_preferences`\n              DROP `individual_name_format`";
     CRM_Core_DAO::executeQuery($alterQuery);
     //set status message for default greetings
     $template =& CRM_Core_Smarty::singleton();
     $template->assign('afterUpgradeMessage', $afterUpgradeMessage);
 }
 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... ";
 }
Ejemplo n.º 4
0
 /**
  * class constructor
  *
  * @return CRM_Core_Smarty
  * @access private
  */
 function __construct()
 {
     parent::__construct();
     $config =& CRM_Core_Config::singleton();
     if (isset($config->customTemplateDir) && $config->customTemplateDir) {
         $this->template_dir = array($config->customTemplateDir, $config->templateDir);
     } else {
         $this->template_dir = $config->templateDir;
     }
     $this->compile_dir = $config->templateCompileDir;
     //Check for safe mode CRM-2207
     if (ini_get('safe_mode')) {
         $this->use_sub_dirs = false;
     } else {
         $this->use_sub_dirs = true;
     }
     $this->plugins_dir = array($config->smartyDir . 'plugins', $config->pluginsDir);
     // add the session and the config here
     $session =& CRM_Core_Session::singleton();
     $this->assign_by_ref('config', $config);
     $this->assign_by_ref('session', $session);
     // check default editor and assign to template, store it in session to reduce db calls
     $defaultWysiwygEditor = $session->get('defaultWysiwygEditor');
     if (!$defaultWysiwygEditor && !CRM_Core_Config::isUpgradeMode()) {
         require_once 'CRM/Core/BAO/Preferences.php';
         $defaultWysiwygEditor = CRM_Core_BAO_Preferences::value('editor_id');
         $session->set('defaultWysiwygEditor', $defaultWysiwygEditor);
     }
     $this->assign('defaultWysiwygEditor', $defaultWysiwygEditor);
     global $tsLocale;
     $this->assign('langSwitch', CRM_Core_I18n::languages(true));
     $this->assign('tsLocale', $tsLocale);
     //check if logged in use has access CiviCRM permission and build menu
     require_once 'CRM/Core/Permission.php';
     $buildNavigation = CRM_Core_Permission::check('access CiviCRM');
     $this->assign('buildNavigation', $buildNavigation);
     if (!CRM_Core_Config::isUpgradeMode() && $buildNavigation) {
         require_once 'CRM/Core/BAO/Navigation.php';
         $contactID = $session->get('userID');
         if ($contactID) {
             $navigation =& CRM_Core_BAO_Navigation::createNavigation($contactID);
             $this->assign('navigation', $navigation);
         }
     }
     $this->register_function('crmURL', array('CRM_Utils_System', 'crmURL'));
     $printerFriendly = CRM_Utils_System::makeURL('snippet', false, false) . '2';
     $this->assign('printerFriendly', $printerFriendly);
 }
Ejemplo n.º 5
0
 /**
  * Function to get the count of  contact loctions
  * 
  * @param int $contactId contact id
  *
  * @return int $locationCount max locations for the contact
  * @static
  * @access public
  */
 static function maxLocations($contactId)
 {
     // find the system config related location blocks
     require_once 'CRM/Core/BAO/Preferences.php';
     $locationCount = CRM_Core_BAO_Preferences::value('location_count');
     $contactLocations = array();
     // find number of location blocks for this contact and adjust value accordinly
     // get location type from email
     $query = "\n( SELECT location_type_id FROM civicrm_email   WHERE contact_id = {$contactId} )\nUNION\n( SELECT location_type_id FROM civicrm_phone   WHERE contact_id = {$contactId} )\nUNION\n( SELECT location_type_id FROM civicrm_im      WHERE contact_id = {$contactId} )\nUNION\n( SELECT location_type_id FROM civicrm_address WHERE contact_id = {$contactId} )\n";
     $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
     $locCount = $dao->N;
     if ($locCount && $locationCount < $locCount) {
         $locationCount = $locCount;
     }
     return $locationCount;
 }
Ejemplo n.º 6
0
 /**
  * If the return Properties are set in a hierarchy, traverse the hierarchy to get
  * the return values
  *
  * @return void 
  * @access public 
  */
 function addHierarchicalElements()
 {
     if (!CRM_Utils_Array::value('location', $this->_returnProperties)) {
         return;
     }
     if (!is_array($this->_returnProperties['location'])) {
         return;
     }
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     $processed = array();
     $index = 0;
     // CRM_Core_Error::debug( 'd', $this->_fields );
     // CRM_Core_Error::debug( 'r', $this->_returnProperties );
     $addressCustomFields = CRM_Core_BAO_CustomField::getFieldsForImport('Address');
     $addressCustomFieldIds = array();
     foreach ($this->_returnProperties['location'] as $name => $elements) {
         $lCond = self::getPrimaryCondition($name);
         if (!$lCond) {
             $locationTypeId = array_search($name, $locationTypes);
             if ($locationTypeId === false) {
                 continue;
             }
             $lCond = "location_type_id = {$locationTypeId}";
             $this->_useDistinct = true;
             //commented for CRM-3256
             $this->_useGroupBy = true;
         }
         $name = str_replace(' ', '_', $name);
         $tName = "{$name}-location_type";
         $ltName = "`{$name}-location_type`";
         $this->_select["{$tName}_id"] = "`{$tName}`.id as `{$tName}_id`";
         $this->_select["{$tName}"] = "`{$tName}`.name as `{$tName}`";
         $this->_element["{$tName}_id"] = 1;
         $this->_element["{$tName}"] = 1;
         $locationTypeName = $tName;
         $locationTypeJoin = array();
         $addAddress = false;
         $addWhereCount = 0;
         foreach ($elements as $elementFullName => $dontCare) {
             $index++;
             $elementName = $elementCmpName = $elementFullName;
             if (substr($elementCmpName, 0, 5) == 'phone') {
                 $elementCmpName = 'phone';
             }
             if (in_array($elementCmpName, array_keys($addressCustomFields))) {
                 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($elementCmpName)) {
                     $addressCustomFieldIds[$cfID][$name] = 1;
                 }
             }
             //add address table only once
             if ((in_array($elementCmpName, self::$_locationSpecificFields) || !empty($addressCustomFieldIds)) && !$addAddress && !in_array($elementCmpName, array('email', 'phone', 'im', 'openid'))) {
                 $tName = "{$name}-address";
                 $aName = "`{$name}-address`";
                 $this->_select["{$tName}_id"] = "`{$tName}`.id as `{$tName}_id`";
                 $this->_element["{$tName}_id"] = 1;
                 $addressJoin = "\nLEFT JOIN civicrm_address {$aName} ON ({$aName}.contact_id = contact_a.id AND {$aName}.{$lCond})";
                 $this->_tables[$tName] = $addressJoin;
                 $locationTypeJoin[$tName] = " ( {$aName}.location_type_id = {$ltName}.id ) ";
                 $processed[$aName] = 1;
                 $addAddress = true;
             }
             $cond = $elementType = '';
             if (strpos($elementName, '-') !== false) {
                 // this is either phone, email or IM
                 list($elementName, $elementType) = explode('-', $elementName);
                 if ($elementName != 'phone' && $elementName != 'im') {
                     $cond = self::getPrimaryCondition($elementType);
                 }
                 if (!$cond && $elementName == 'phone') {
                     $cond = "phone_type_id = '{$elementType}'";
                 } else {
                     if (!$cond && $elementName == 'im') {
                         // IM service provider id, CRM-3140
                         $cond = "provider_id = '{$elementType}'";
                     }
                 }
                 $elementType = '-' . $elementType;
             }
             $field = CRM_Utils_Array::value($elementName, $this->_fields);
             // hack for profile, add location id
             if (!$field) {
                 if ($elementType && !is_numeric($elementType)) {
                     //fix for CRM-882( to handle phone types )
                     if (is_numeric($name)) {
                         $field =& CRM_Utils_Array::value($elementName . "-Primary{$elementType}", $this->_fields);
                     } else {
                         $field =& CRM_Utils_Array::value($elementName . "-{$locationTypeId}{$elementType}", $this->_fields);
                     }
                 } else {
                     if (is_numeric($name)) {
                         //this for phone type to work
                         if ($elementName == "phone") {
                             $field =& CRM_Utils_Array::value($elementName . "-Primary" . $elementType, $this->_fields);
                         } else {
                             $field =& CRM_Utils_Array::value($elementName . "-Primary", $this->_fields);
                         }
                     } else {
                         //this is for phone type to work for profile edit
                         if ($elementName == "phone") {
                             $field =& CRM_Utils_Array::value($elementName . "-{$locationTypeId}{$elementType}", $this->_fields);
                         } else {
                             $field =& CRM_Utils_Array::value($elementName . "-{$locationTypeId}", $this->_fields);
                         }
                     }
                 }
             }
             // check if there is a value, if so also add to where Clause
             $addWhere = false;
             if ($this->_params) {
                 $nm = $elementName;
                 if (isset($locationTypeId)) {
                     $nm .= "-{$locationTypeId}";
                 }
                 if (!is_numeric($elementType)) {
                     $nm .= "{$elementType}";
                 }
                 foreach ($this->_params as $id => $values) {
                     if ($values[0] == $nm || in_array($elementName, array('phone', 'im')) && strpos($values[0], $nm) !== false) {
                         $addWhere = true;
                         $addWhereCount++;
                         break;
                     }
                 }
             }
             if ($field && isset($field['where'])) {
                 list($tableName, $fieldName) = explode('.', $field['where'], 2);
                 $tName = $name . '-' . substr($tableName, 8) . $elementType;
                 $fieldName = $fieldName;
                 if (isset($tableName)) {
                     $this->_select["{$tName}_id"] = "`{$tName}`.id as `{$tName}_id`";
                     $this->_element["{$tName}_id"] = 1;
                     if (substr($tName, -15) == '-state_province') {
                         // FIXME: hack to fix CRM-1900
                         require_once 'CRM/Core/BAO/Preferences.php';
                         $a = CRM_Core_BAO_Preferences::value('address_format');
                         if (substr_count($a, 'state_province_name') > 0) {
                             $this->_select["{$name}-{$elementFullName}"] = "`{$tName}`.name as `{$name}-{$elementFullName}`";
                         } else {
                             $this->_select["{$name}-{$elementFullName}"] = "`{$tName}`.abbreviation as `{$name}-{$elementFullName}`";
                         }
                     } else {
                         if (substr($elementFullName, 0, 2) == 'im') {
                             $provider = "{$name}-{$elementFullName}-provider_id";
                             $this->_select[$provider] = "`{$tName}`.provider_id as `{$name}-{$elementFullName}-provider_id`";
                             $this->_element[$provider] = 1;
                         }
                         $this->_select["{$name}-{$elementFullName}"] = "`{$tName}`.{$fieldName} as `{$name}-{$elementFullName}`";
                     }
                     $this->_element["{$name}-{$elementFullName}"] = 1;
                     if (!CRM_Utils_Array::value("`{$tName}`", $processed)) {
                         $processed["`{$tName}`"] = 1;
                         $newName = $tableName . '_' . $index;
                         switch ($tableName) {
                             case 'civicrm_phone':
                             case 'civicrm_email':
                             case 'civicrm_im':
                             case 'civicrm_openid':
                                 $this->_tables[$tName] = "\nLEFT JOIN {$tableName} `{$tName}` ON contact_a.id = `{$tName}`.contact_id AND `{$tName}`.{$lCond}";
                                 // this special case to add phone type
                                 if ($cond) {
                                     $this->_tables[$tName] .= " AND `{$tName}`.{$cond} ";
                                 }
                                 //build locationType join
                                 $locationTypeJoin[$tName] = " ( `{$tName}`.location_type_id = {$ltName}.id )";
                                 if ($addWhere) {
                                     $this->_whereTables[$tName] = $this->_tables[$tName];
                                 }
                                 break;
                             case 'civicrm_state_province':
                                 $this->_tables[$tName] = "\nLEFT JOIN {$tableName} `{$tName}` ON `{$tName}`.id = {$aName}.state_province_id";
                                 if ($addWhere) {
                                     $this->_whereTables["{$name}-address"] = $addressJoin;
                                     $this->_whereTables[$tName] = $this->_tables[$tName];
                                 }
                                 break;
                             case 'civicrm_country':
                                 $this->_tables[$newName] = "\nLEFT JOIN {$tableName} `{$tName}` ON `{$tName}`.id = {$aName}.country_id";
                                 if ($addWhere) {
                                     $this->_whereTables["{$name}-address"] = $addressJoin;
                                     $this->_whereTables[$newName] = $this->_tables[$newName];
                                 }
                                 break;
                             case 'civicrm_county':
                                 $this->_tables[$newName] = "\nLEFT JOIN {$tableName} `{$tName}` ON `{$tName}`.id = {$aName}.county_id";
                                 if ($addWhere) {
                                     $this->_whereTables["{$name}-address"] = $addressJoin;
                                     $this->_whereTables[$newName] = $this->_tables[$newName];
                                 }
                                 break;
                             default:
                                 if ($addWhere) {
                                     $this->_whereTables["{$name}-address"] = $addressJoin;
                                 }
                                 break;
                         }
                     }
                 }
             }
         }
         // add location type  join
         $ltypeJoin = "\nLEFT JOIN civicrm_location_type {$ltName} ON ( " . implode('OR', $locationTypeJoin) . " )";
         $this->_tables[$locationTypeName] = $ltypeJoin;
         // table should be present in $this->_whereTables,
         // to add its condition in location type join, CRM-3939.
         if ($addWhereCount) {
             $locClause = array();
             foreach ($this->_whereTables as $tableName => $clause) {
                 if (CRM_Utils_Array::value($tableName, $locationTypeJoin)) {
                     $locClause[] = $locationTypeJoin[$tableName];
                 }
             }
             if (!empty($locClause)) {
                 $this->_whereTables[$locationTypeName] = "\nLEFT JOIN civicrm_location_type {$ltName} ON ( " . implode('OR', $locClause) . " )";
             }
         }
     }
     if (!empty($addressCustomFieldIds)) {
         require_once 'CRM/Core/BAO/CustomQuery.php';
         $cfIDs = $addressCustomFieldIds;
         $customQuery = new CRM_Core_BAO_CustomQuery($cfIDs);
         foreach ($addressCustomFieldIds as $cfID => $locTypeName) {
             foreach ($locTypeName as $name => $dnc) {
                 $fieldName = "{$name}-custom_{$cfID}";
                 $tName = "{$name}-address-custom";
                 $aName = "`{$name}-address-custom`";
                 $this->_select["{$tName}_id"] = "`{$tName}`.id as `{$tName}_id`";
                 $this->_element["{$tName}_id"] = 1;
                 $this->_select[$fieldName] = "`{$tName}`.{$customQuery->_fields[$cfID]['column_name']} as `{$fieldName}`";
                 $this->_element[$fieldName] = 1;
                 $this->_tables[$tName] = "\nLEFT JOIN {$customQuery->_fields[$cfID]['table_name']} {$aName} ON ({$aName}.entity_id = `{$name}-address`.id)";
             }
         }
     }
 }
Ejemplo n.º 7
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
     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);
 }
Ejemplo n.º 8
0
 /**
  * format an address string from address fields and a format string
  *
  * Format an address basing on the address fields provided.
  * Use Preferences::address_format if there's no format specified.
  *
  * @param array   $fields            the address fields
  * @param string  $format            the desired address format
  * @param boolean $microformat       if true indicates, the address to be built in hcard-microformat standard.
  * @param boolean $mailing           if true indicates, the call has been made from mailing label
  * @param boolean $individualFormat  if true indicates, the call has been made for the contact of type 'individual'
  *
  * @return string  formatted address string
  *
  * @static
  */
 static function format($fields, $format = null, $microformat = false, $mailing = false, $individualFormat = false, $tokenFields = null)
 {
     static $config = null;
     require_once 'CRM/Core/BAO/Preferences.php';
     if (!$format) {
         $format = CRM_Core_BAO_Preferences::value('address_format');
         $format = str_replace('contact.', "", $format);
     }
     if ($mailing) {
         $format = CRM_Core_BAO_Preferences::value('mailing_format');
         $format = str_replace('contact.', "", $format);
     }
     $formatted = $format;
     $fullPostalCode = CRM_Utils_Array::value('postal_code', $fields);
     if (!empty($fields['postal_code_suffix'])) {
         $fullPostalCode .= "-{$fields['postal_code_suffix']}";
     }
     // make sure that some of the fields do have values
     $emptyFields = array('supplemental_address_1', 'supplemental_address_2', 'state_province_name', 'county');
     foreach ($emptyFields as $f) {
         if (!isset($fields[$f])) {
             $fields[$f] = null;
         }
     }
     $contactName = CRM_Utils_Array::value('display_name', $fields);
     if (!$individualFormat) {
         require_once "CRM/Contact/BAO/Contact.php";
         if (isset($fields['id'])) {
             $type = CRM_Contact_BAO_Contact::getContactType($fields['id']);
         } else {
             $type = 'Individual';
         }
         if ($type == 'Individual') {
             $contactName = CRM_Utils_Array::value('addressee_display', $fields);
         }
     }
     if (!$microformat) {
         $replacements = array('display_name' => CRM_Utils_Array::value('display_name', $fields), 'individual_prefix' => CRM_Utils_Array::value('individual_prefix', $fields), 'first_name' => CRM_Utils_Array::value('first_name', $fields), 'middle_name' => CRM_Utils_Array::value('middle_name', $fields), 'last_name' => CRM_Utils_Array::value('last_name', $fields), 'individual_suffix' => CRM_Utils_Array::value('individual_suffix', $fields), 'address_name' => CRM_Utils_Array::value('address_name', $fields), 'street_address' => CRM_Utils_Array::value('street_address', $fields), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', $fields), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', $fields), 'city' => CRM_Utils_Array::value('city', $fields), 'state_province_name' => CRM_Utils_Array::value('state_province_name', $fields), 'county' => CRM_Utils_Array::value('county', $fields), 'state_province' => CRM_Utils_Array::value('state_province', $fields), 'postal_code' => $fullPostalCode, 'country' => CRM_Utils_Array::value('country', $fields), 'world_region' => CRM_Utils_Array::value('world_region', $fields), 'geo_code_1' => CRM_Utils_Array::value('geo_code_1', $fields), 'geo_code_2' => CRM_Utils_Array::value('geo_code_2', $fields), 'current_employer' => CRM_Utils_Array::value('current_employer', $fields), 'nick_name' => CRM_Utils_Array::value('nick_name', $fields), 'email' => CRM_Utils_Array::value('email', $fields), 'im' => CRM_Utils_Array::value('im', $fields), 'do_not_email' => CRM_Utils_Array::value('do_not_email', $fields), 'do_not_phone' => CRM_Utils_Array::value('do_not_phone', $fields), 'do_not_mail' => CRM_Utils_Array::value('do_not_mail', $fields), 'do_not_sms' => CRM_Utils_Array::value('do_not_sms', $fields), 'do_not_trade' => CRM_Utils_Array::value('do_not_trade', $fields), 'job_title' => CRM_Utils_Array::value('job_title', $fields), 'birth_date' => CRM_Utils_Array::value('birth_date', $fields), 'gender' => CRM_Utils_Array::value('gender', $fields), 'is_opt_out' => CRM_Utils_Array::value('is_opt_out', $fields), 'home_URL' => CRM_Utils_Array::value('home_URL', $fields), 'preferred_mail_format' => CRM_Utils_Array::value('preferred_mail_format', $fields), 'phone' => CRM_Utils_Array::value('phone', $fields), 'home_URL' => CRM_Utils_Array::value('home_URL', $fields), 'contact_source' => CRM_Utils_Array::value('contact_source', $fields), 'external_identifier' => CRM_Utils_Array::value('external_identifier', $fields), 'contact_id' => CRM_Utils_Array::value('id', $fields), 'household_name' => CRM_Utils_Array::value('display_name', $fields), 'organization_name' => CRM_Utils_Array::value('display_name', $fields), 'legal_name' => CRM_Utils_Array::value('legal_name', $fields), 'preferred_communication_method' => CRM_Utils_Array::value('preferred_communication_method', $fields), 'addressee' => CRM_Utils_Array::value('addressee_display', $fields), 'email_greeting' => CRM_Utils_Array::value('email_greeting_display', $fields), 'postal_greeting' => CRM_Utils_Array::value('postal_greeting_display', $fields));
     } else {
         $replacements = array('address_name' => "<span class=\"address-name\">" . $fields['address_name'] . "</span>", 'street_address' => "<span class=\"street-address\">" . $fields['street_address'] . "</span>", 'supplemental_address_1' => "<span class=\"extended-address\">" . $fields['supplemental_address_1'] . "</span>", 'supplemental_address_2' => $fields['supplemental_address_2'], 'city' => "<span class=\"locality\">" . $fields['city'] . "</span>", 'state_province_name' => "<span class=\"region\">" . $fields['state_province_name'] . "</span>", 'county' => "<span class=\"region\">" . $fields['county'], 'state_province' => "<span class=\"region\">" . $fields['state_province'] . "</span>", 'postal_code' => "<span class=\"postal-code\">" . $fullPostalCode . "</span>", 'country' => "<span class=\"country-name\">" . $fields['country'] . "</span>", 'world_region' => "<span class=\"region\">" . $fields['world_region'] . "</span>");
         // erase all empty ones, so we dont get blank lines
         foreach (array_keys($replacements) as $key) {
             if ($key != 'postal_code' && CRM_Utils_Array::value($key, $fields) == null) {
                 $replacements[$key] = '';
             }
         }
         if (empty($fullPostalCode)) {
             $replacements['postal_code'] = '';
         }
     }
     // replacements in case of Custom Token
     if (stristr($formatted, 'custom_')) {
         $customToken = array_keys($fields);
         foreach ($customToken as $value) {
             if (substr($value, 0, 7) == 'custom_') {
                 $replacements["{$value}"] = $fields["{$value}"];
             }
         }
     }
     // also sub all token fields
     if ($tokenFields) {
         foreach ($tokenFields as $token) {
             $replacements["{$token}"] = CRM_Utils_Array::value("{$token}", $fields);
         }
     }
     // for every token, replace {fooTOKENbar} with fooVALUEbar if
     // the value is not empty, otherwise drop the whole {fooTOKENbar}
     foreach ($replacements as $token => $value) {
         if ($value) {
             $formatted = preg_replace("/{([^{}]*)\\b{$token}\\b([^{}]*)}/u", "\${1}{$value}\${2}", $formatted);
         } else {
             $formatted = preg_replace("/{[^{}]*\\b{$token}\\b[^{}]*}/u", '', $formatted);
         }
     }
     // drop any {...} constructs from lines' ends
     if (!$microformat) {
         $formatted = "\n{$formatted}\n";
     } else {
         if ($microformat == 1) {
             $formatted = "\n<div class=\"location vcard\"><span class=\"adr\">\n{$formatted}</span></div>\n";
         } else {
             $formatted = "\n<div class=\"vcard\"><span class=\"adr\">{$formatted}</span></div>\n";
         }
     }
     $formatted = preg_replace('/\\n{[^{}]*}/u', "\n", $formatted);
     $formatted = preg_replace('/{[^{}]*}\\n/u', "\n", $formatted);
     // if there are any 'sibling' {...} constructs, replace them with the
     // contents of the first one; for example, when there's no state_province:
     // 1. {city}{, }{state_province}{ }{postal_code}
     // 2. San Francisco{, }{ }12345
     // 3. San Francisco, 12345
     $formatted = preg_replace('/{([^{}]*)}({[^{}]*})+/u', '\\1', $formatted);
     // drop any remaining curly braces leaving their contents
     $formatted = str_replace(array('{', '}'), '', $formatted);
     // drop any empty lines left after the replacements
     $formatted = preg_replace('/^[ \\t]*[\\r\\n]+/m', '', $formatted);
     if (!$microformat) {
         $finalFormatted = $formatted;
     } else {
         // remove \n from each line and only add at the end
         // this hack solves formatting issue, when we convert nl2br
         $lines = array();
         $count = 1;
         $finalFormatted = null;
         $formattedArray = explode("\n", $formatted);
         $formattedArray = array_filter($formattedArray);
         foreach ($formattedArray as $line) {
             $line = trim($line);
             if ($line) {
                 if ($count > 1 && $count < count($formattedArray)) {
                     $line = "{$line}\n";
                 }
                 $finalFormatted .= $line;
                 $count++;
             }
         }
     }
     return $finalFormatted;
 }
Ejemplo n.º 9
0
 /**
  * Provide addressSequence
  *
  * @param
  * @return string
  */
 public function addressSequence()
 {
     require_once 'CRM/Core/BAO/Preferences.php';
     return CRM_Core_BAO_Preferences::value('address_sequence');
 }
Ejemplo n.º 10
0
 function addWysiwyg($name, $label, $attributes, $forceTextarea = false)
 {
     // 1. Get configuration option for editor (tinymce, ckeditor, pure textarea)
     // 2. Based on the option, initialise proper editor
     require_once 'CRM/Core/BAO/Preferences.php';
     $editor = strtolower(CRM_Utils_Array::value(CRM_Core_BAO_Preferences::value('editor_id'), CRM_Core_PseudoConstant::wysiwygEditor()));
     if (!$editor || $forceTextarea) {
         $editor = 'textarea';
     }
     if ($editor == 'joomla default editor') {
         $editor = 'joomlaeditor';
     }
     $this->addElement($editor, $name, $label, $attributes);
     $this->assign('editor', $editor);
 }
Ejemplo n.º 11
0
 /**
  * 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;
 }
Ejemplo n.º 12
0
 /**
  * format the address params to have reasonable values
  *
  * @param array  $params         (reference ) an assoc array of name/value pairs
  *
  * @return void
  * @access public
  * @static
  */
 static function fixAddress(&$params)
 {
     if (CRM_Utils_Array::value('billing_street_address', $params)) {
         //Check address is comming from online contribution / registration page
         //Fixed :CRM-5076
         $billing = array('street_address' => 'billing_street_address', 'city' => 'billing_city', 'postal_code' => 'billing_postal_code', 'state_province' => 'billing_state_province', 'state_province_id' => 'billing_state_province_id', 'country' => 'billing_country', 'country_id' => 'billing_country_id');
         foreach ($billing as $key => $val) {
             if ($value = CRM_Utils_Array::value($val, $params)) {
                 if (CRM_Utils_Array::value($key, $params)) {
                     unset($params[$val]);
                 } else {
                     //add new key and removed old
                     $params[$key] = $value;
                     unset($params[$val]);
                 }
             }
         }
     }
     /* Split the zip and +4, if it's in US format */
     if (CRM_Utils_Array::value('postal_code', $params) && preg_match('/^(\\d{4,5})[+-](\\d{4})$/', $params['postal_code'], $match)) {
         $params['postal_code'] = $match[1];
         $params['postal_code_suffix'] = $match[2];
     }
     // add country id if not set
     if ((!isset($params['country_id']) || !is_numeric($params['country_id'])) && isset($params['country'])) {
         $country =& new CRM_Core_DAO_Country();
         $country->name = $params['country'];
         if (!$country->find(true)) {
             $country->name = null;
             $country->iso_code = $params['country'];
             $country->find(true);
         }
         $params['country_id'] = $country->id;
     }
     // add state_id if state is set
     if ((!isset($params['state_province_id']) || !is_numeric($params['state_province_id'])) && isset($params['state_province'])) {
         if (!empty($params['state_province'])) {
             $state_province =& new CRM_Core_DAO_StateProvince();
             $state_province->name = $params['state_province'];
             // add country id if present
             if (isset($params['country_id'])) {
                 $state_province->country_id = $params['country_id'];
             }
             if (!$state_province->find(true)) {
                 $state_province->name = null;
                 $state_province->abbreviation = $params['state_province'];
                 $state_province->find(true);
             }
             $params['state_province_id'] = $state_province->id;
         } else {
             $params['state_province_id'] = 'null';
         }
     }
     // currently copy values populates empty fields with the string "null"
     // and hence need to check for the string null
     if (isset($params['state_province_id']) && is_numeric($params['state_province_id']) && (!isset($params['country_id']) || empty($params['country_id']))) {
         // since state id present and country id not present, hence lets populate it
         // jira issue http://issues.civicrm.org/jira/browse/CRM-56
         $params['country_id'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_StateProvince', $params['state_province_id'], 'country_id');
     }
     //special check to ignore non numeric values if they are not
     //detected by formRule(sometimes happens due to internet latency), also allow user to unselect state/country
     if (isset($params['state_province_id'])) {
         if (!trim($params['state_province_id'])) {
             $params['state_province_id'] = 'null';
         } else {
             if (!is_numeric($params['state_province_id']) || (int) $params['state_province_id'] < 1000) {
                 // CRM-3393 ( the hacky 1000 check)
                 $params['state_province_id'] = 'null';
             }
         }
     }
     if (isset($params['country_id'])) {
         if (!trim($params['country_id'])) {
             $params['country_id'] = 'null';
         } else {
             if (!is_numeric($params['country_id']) || (int) $params['country_id'] < 1000) {
                 // CRM-3393 ( the hacky 1000 check)
                 $params['country_id'] = 'null';
             }
         }
     }
     // add state and country names from the ids
     if (isset($params['state_province_id']) && is_numeric($params['state_province_id'])) {
         $params['state_province'] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params['state_province_id']);
     }
     if (isset($params['country_id']) && is_numeric($params['country_id'])) {
         $params['country'] = CRM_Core_PseudoConstant::country($params['country_id']);
     }
     $config =& CRM_Core_Config::singleton();
     require_once 'CRM/Core/BAO/Preferences.php';
     $asp = CRM_Core_BAO_Preferences::value('address_standardization_provider');
     // clean up the address via USPS web services if enabled
     if ($asp === 'USPS') {
         require_once 'CRM/Utils/Address/USPS.php';
         CRM_Utils_Address_USPS::checkAddress($params);
     }
     // add latitude and longitude and format address if needed
     if (!empty($config->geocodeMethod)) {
         require_once str_replace('_', DIRECTORY_SEPARATOR, $config->geocodeMethod) . '.php';
         eval($config->geocodeMethod . '::format( $params );');
     }
 }