/** * Process the form submission. */ public function postProcess() { CRM_Utils_System::flushCache('CRM_Core_DAO_LocationType'); if ($this->_action & CRM_Core_Action::DELETE) { CRM_Core_BAO_LocationType::del($this->_id); CRM_Core_Session::setStatus(ts('Selected Location type has been deleted.'), ts('Record Deleted'), 'success'); return; } // store the submitted values in an array $params = $this->exportValues(); $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE); $params['is_default'] = CRM_Utils_Array::value('is_default', $params, FALSE); // action is taken depending upon the mode $locationType = new CRM_Core_DAO_LocationType(); $locationType->name = $params['name']; $locationType->display_name = $params['display_name']; $locationType->vcard_name = $params['vcard_name']; $locationType->description = $params['description']; $locationType->is_active = $params['is_active']; $locationType->is_default = $params['is_default']; if ($params['is_default']) { $query = "UPDATE civicrm_location_type SET is_default = 0"; CRM_Core_DAO::executeQuery($query); } if ($this->_action & CRM_Core_Action::UPDATE) { $locationType->id = $this->_id; } $locationType->save(); CRM_Core_Session::setStatus(ts("The location type '%1' has been saved.", array(1 => $locationType->name)), ts('Saved'), 'success'); }
/** * Function to process the form * * @access public * @return None */ function postProcess() { if ($this->_action & CRM_CORE_ACTION_DELETE) { CRM_Core_BAO_LocationType::del($this->_id); CRM_Core_Session::setStatus(ts('Selected Location type has been deleted.')); } else { // store the submitted values in an array $params = $this->exportValues(); $params['is_active'] = CRM_Utils_Array::value('is_active', $params, false); $params['is_default'] = CRM_Utils_Array::value('is_default', $params, false); // action is taken depending upon the mode $locationType =& new CRM_Core_DAO_LocationType(); $locationType->domain_id = CRM_Core_Config::domainID(); $locationType->name = $params['name']; $locationType->vcard_name = $params['vcard_name']; $locationType->description = $params['description']; $locationType->is_active = $params['is_active']; $locationType->is_default = $params['is_default']; if ($params['is_default']) { $unsetDefault =& new CRM_Core_DAO(); $query = 'UPDATE civicrm_location_type SET is_default = 0'; $unsetDefault->query($query); } if ($this->_action & CRM_CORE_ACTION_UPDATE) { $locationType->id = $this->_id; } $locationType->save(); CRM_Core_Session::setStatus(ts('The location type "%1" has been saved.', array(1 => $locationType->name))); } }
/** * This function sets the default values for the form. For edit/view mode * the default values are retrieved from the database * * @access public * @return None */ function setDefaultValues(&$form) { $defaults = array(); if ($form->_context == 'caseActivity') { return $defaults; } require_once 'CRM/Utils/Date.php'; list($defaults['start_date']) = CRM_Utils_Date::setDateDefaults(); // set case status to 'ongoing' $defaults['status_id'] = 1; // set default encounter medium, location type and phone type defaults are set in DB require_once "CRM/Core/OptionGroup.php"; $medium = CRM_Core_OptionGroup::values('encounter_medium', false, false, false, 'AND is_default = 1'); if (count($medium) == 1) { $defaults['medium_id'] = key($medium); } require_once 'CRM/Core/BAO/LocationType.php'; $defaultLocationType =& CRM_Core_BAO_LocationType::getDefault(); if ($defaultLocationType->id) { $defaults['location[1][location_type_id]'] = $defaultLocationType->id; } $phoneType = CRM_Core_OptionGroup::values('phone_type', false, false, false, 'AND is_default = 1'); if (count($phoneType) == 1) { $defaults['location[1][phone][1][phone_type_id]'] = key($phoneType); } return $defaults; }
/** * Function to process the form * * @access public * @return None */ public function postProcess() { if ($this->_action & CRM_Core_Action::DELETE) { CRM_Core_BAO_LocationType::del($this->_id); CRM_Core_Session::setStatus(ts('Selected Location type has been deleted.')); return; } // store the submitted values in an array $params = $this->exportValues(); $params['is_active'] = CRM_Utils_Array::value('is_active', $params, false); $params['is_default'] = CRM_Utils_Array::value('is_default', $params, false); // action is taken depending upon the mode $locationType =& new CRM_Core_DAO_LocationType(); $locationType->name = $params['name']; $locationType->vcard_name = $params['vcard_name']; $locationType->description = $params['description']; $locationType->is_active = $params['is_active']; $locationType->is_default = $params['is_default']; if ($params['is_default']) { $query = "UPDATE civicrm_location_type SET is_default = 0"; CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); } if ($this->_action & CRM_Core_Action::UPDATE) { $locationType->id = $this->_id; } $locationType->save(); CRM_Core_Session::setStatus(ts('The location type \'%1\' has been saved.', array(1 => $locationType->name))); }
/** * Create or update a contact (note you should always call this via civicrm_api() & never directly) * * @param array $params input parameters * * Allowed @params array keys are: * {@getfields contact_create} * * * @example ContactCreate.php Example of Create Call * * @return array API Result Array * * @static void * @access public */ function civicrm_api3_contact_create($params) { $contactID = CRM_Utils_Array::value('contact_id', $params, CRM_Utils_Array::value('id', $params)); $dupeCheck = CRM_Utils_Array::value('dupe_check', $params, FALSE); $values = _civicrm_api3_contact_check_params($params, $dupeCheck); if ($values) { return $values; } if (empty($contactID)) { // If we get here, we're ready to create a new contact if (($email = CRM_Utils_Array::value('email', $params)) && !is_array($params['email'])) { require_once 'CRM/Core/BAO/LocationType.php'; $defLocType = CRM_Core_BAO_LocationType::getDefault(); $params['email'] = array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => $defLocType->id ? $defLocType->id : 1)); } } if (CRM_Utils_Array::value('home_url', $params)) { require_once 'CRM/Core/PseudoConstant.php'; $websiteTypes = CRM_Core_PseudoConstant::websiteType(); $params['website'] = array(1 => array('website_type_id' => key($websiteTypes), 'url' => $params['home_url'])); } if (isset($params['suffix_id']) && !is_numeric($params['suffix_id'])) { $params['suffix_id'] = array_search($params['suffix_id'], CRM_Core_PseudoConstant::individualSuffix()); } if (isset($params['prefix_id']) && !is_numeric($params['prefix_id'])) { $params['prefix_id'] = array_search($params['prefix_id'], CRM_Core_PseudoConstant::individualPrefix()); } if (isset($params['gender_id']) && !is_numeric($params['gender_id'])) { $params['gender_id'] = array_search($params['gender_id'], CRM_Core_PseudoConstant::gender()); } $error = _civicrm_api3_greeting_format_params($params); if (civicrm_error($error)) { return $error; } $values = array(); $entityId = $contactID; if (!CRM_Utils_Array::value('contact_type', $params) && $entityId) { $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($entityId); } if (!isset($params['contact_sub_type']) && $entityId) { require_once 'CRM/Contact/BAO/Contact.php'; $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($entityId); } _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $entityId); $params = array_merge($params, $values); $contact = _civicrm_api3_contact_update($params, $contactID); if (is_a($contact, 'CRM_Core_Error')) { return civicrm_api3_create_error($contact->_errors[0]['message']); } else { $values = array(); _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id]); } return civicrm_api3_create_success($values, $params, 'Contact', 'create'); }
/** * Sets up the fixture, for example, opens a network connection. * * This method is called before a test is executed. */ protected function setUp() { parent::setUp(); $this->useTransaction(TRUE); // taken from form code - couldn't find good method to use $params['entity_id'] = 1; $params['entity_table'] = CRM_Core_BAO_Domain::getTableName(); $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); $domContact = $this->callAPISuccess('contact', 'create', array('contact_type' => 'Organization', 'organization_name' => 'new org', 'api.phone.create' => array('location_type_id' => $defaultLocationType->id, 'phone_type_id' => 1, 'phone' => '456-456'), 'api.address.create' => array('location_type_id' => $defaultLocationType->id, 'street_address' => '45 Penny Lane'), 'api.email.create' => array('location_type_id' => $defaultLocationType->id, 'email' => '*****@*****.**'))); $this->callAPISuccess('domain', 'create', array('id' => 1, 'contact_id' => $domContact['id'])); $this->params = array('name' => 'A-team domain', 'description' => 'domain of chaos', 'domain_version' => '4.2', 'contact_id' => $domContact['id']); }
/** * Create or update a Contact. * * @param array $params * Input parameters. * * @throws API_Exception * * @return array * API Result Array */ function civicrm_api3_contact_create($params) { $contactID = CRM_Utils_Array::value('contact_id', $params, CRM_Utils_Array::value('id', $params)); if ($contactID && !empty($params['check_permissions']) && !CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::EDIT)) { throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify contact record'); } $dupeCheck = CRM_Utils_Array::value('dupe_check', $params, FALSE); $values = _civicrm_api3_contact_check_params($params, $dupeCheck); if ($values) { return $values; } if (array_key_exists('api_key', $params) && !empty($params['check_permissions'])) { if (CRM_Core_Permission::check('edit api keys') || CRM_Core_Permission::check('administer CiviCRM')) { // OK } elseif ($contactID && CRM_Core_Permission::check('edit own api keys') && CRM_Core_Session::singleton()->get('userID') == $contactID) { // OK } else { throw new \Civi\API\Exception\UnauthorizedException('Permission denied to modify api key'); } } if (!$contactID) { // If we get here, we're ready to create a new contact if (($email = CRM_Utils_Array::value('email', $params)) && !is_array($params['email'])) { $defLocType = CRM_Core_BAO_LocationType::getDefault(); $params['email'] = array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => $defLocType->id ? $defLocType->id : 1)); } } if (!empty($params['home_url'])) { $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'); $params['website'] = array(1 => array('website_type_id' => key($websiteTypes), 'url' => $params['home_url'])); } _civicrm_api3_greeting_format_params($params); $values = array(); if (empty($params['contact_type']) && $contactID) { $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($contactID); } if (!isset($params['contact_sub_type']) && $contactID) { $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($contactID); } _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID); $params = array_merge($params, $values); //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao $contact = _civicrm_api3_contact_update($params, $contactID); if (is_a($contact, 'CRM_Core_Error')) { throw new API_Exception($contact->_errors[0]['message']); } else { $values = array(); _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id]); } return civicrm_api3_create_success($values, $params, 'Contact', 'create'); }
/** * Get billing fields required for this processor. * * We apply the existing default of returning fields only for payment processor type 1. Processors can override to * alter. * * @param int $billingLocationID * * @return array */ public function getBillingAddressFields($billingLocationID = NULL) { if (!$billingLocationID) { // Note that although the billing id is passed around the forms the idea that it would be anything other than // the result of the function below doesn't seem to have eventuated. // So taking this as a param is possibly something to be removed in favour of the standard default. $billingLocationID = CRM_Core_BAO_LocationType::getBilling(); } // Only handle pseudo-profile billing for now. if ($this->billingProfile == 'billing') { // @todo - use profile api to retrieve this - either as pseudo-profile or (better) set up billing // as a reserved profile in the DB and (even better) allow the profile to be selected // on the form instead of just 'billing for pay=later bool' return array('first_name' => 'billing_first_name', 'middle_name' => 'billing_middle_name', 'last_name' => 'billing_last_name', 'street_address' => "billing_street_address-{$billingLocationID}", 'city' => "billing_city-{$billingLocationID}", 'country' => "billing_country_id-{$billingLocationID}", 'state_province' => "billing_state_province_id-{$billingLocationID}", 'postal_code' => "billing_postal_code-{$billingLocationID}"); } else { return array(); } }
/** * Register a subscription event. Create a new contact if one does not * already exist. * * @param int $domain_id The domain id of the new subscription * @param int $group_id The group id to subscribe to * @param string $email The email address of the (new) contact * @return int|null $se_id The id of the subscription event, null on failure * @access public * @static */ function &subscribe($domain_id, $group_id, $email) { /* First, find out if the contact already exists */ $params = array('email' => $email, 'domain_id' => $domain_id); require_once 'CRM/Core/BAO/UFGroup.php'; $contact_id = CRM_Core_BAO_UFGroup::findContact($params); CRM_Core_DAO::transaction('BEGIN'); if (is_a($contact_id, CRM_Core_Error)) { require_once 'CRM/Core/BAO/LocationType.php'; /* If the contact does not exist, create one. */ $formatted = array('contact_type' => 'Individual'); $value = array('email' => $email, 'location_type' => CRM_Core_BAO_LocationType::getDefaultID()); _crm_add_formatted_param($value, $formatted); $contact =& crm_create_contact_formatted($formatted, CRM_IMPORT_PARSER_DUPLICATE_SKIP); if (is_a($contact, CRM_Core_Error)) { return null; } $contact_id = $contact->id; } require_once 'CRM/Core/BAO/Email.php'; require_once 'CRM/Core/BAO/Location.php'; require_once 'CRM/Contact/BAO/Contact.php'; /* Get the primary email id from the contact to use as a hash input */ $dao =& new CRM_Core_DAO(); $emailTable = CRM_Core_BAO_Email::getTableName(); $locTable = CRM_Core_BAO_Location::getTableName(); $contactTable = CRM_Contact_BAO_Contact::getTableName(); $dao->query("SELECT {$emailTable}.id as email_id\n FROM {$emailTable}\n INNER JOIN {$locTable}\n ON {$emailTable}.location_id = {$locTable}.id\n WHERE {$emailTable}.is_primary = 1\n AND {$locTable}.is_primary = 1\n AND {$locTable}.entity_table = '{$contactTable}'\n AND {$locTable}.entity_id = " . CRM_Utils_Type::escape($contact_id, 'Integer')); $dao->fetch(); $se =& new CRM_Mailing_Event_BAO_Subscribe(); $se->group_id = $group_id; $se->contact_id = $contact_id; $se->time_stamp = date('YmdHis'); $se->hash = sha1("{$group_id}:{$contact_id}:{$dao->email_id}"); $se->save(); $contacts = array($contact_id); require_once 'CRM/Contact/BAO/GroupContact.php'; CRM_Contact_BAO_GroupContact::addContactsToGroup($contacts, $group_id, 'Email', 'Pending', $se->id); CRM_Core_DAO::transaction('COMMIT'); return $se; }
/** * Create or update a Contact. * * @param array $params * Input parameters. * * @throws API_Exception * * @return array * API Result Array */ function civicrm_api3_contact_create($params) { $contactID = CRM_Utils_Array::value('contact_id', $params, CRM_Utils_Array::value('id', $params)); $dupeCheck = CRM_Utils_Array::value('dupe_check', $params, FALSE); $values = _civicrm_api3_contact_check_params($params, $dupeCheck); if ($values) { return $values; } if (!$contactID) { // If we get here, we're ready to create a new contact if (($email = CRM_Utils_Array::value('email', $params)) && !is_array($params['email'])) { $defLocType = CRM_Core_BAO_LocationType::getDefault(); $params['email'] = array(1 => array('email' => $email, 'is_primary' => 1, 'location_type_id' => $defLocType->id ? $defLocType->id : 1)); } } if (!empty($params['home_url'])) { $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'); $params['website'] = array(1 => array('website_type_id' => key($websiteTypes), 'url' => $params['home_url'])); } _civicrm_api3_greeting_format_params($params); $values = array(); if (empty($params['contact_type']) && $contactID) { $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($contactID); } if (!isset($params['contact_sub_type']) && $contactID) { $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($contactID); } _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID); $params = array_merge($params, $values); //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao $contact = _civicrm_api3_contact_update($params, $contactID); if (is_a($contact, 'CRM_Core_Error')) { throw new API_Exception($contact->_errors[0]['message']); } else { $values = array(); _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id]); } return civicrm_api3_create_success($values, $params, 'Contact', 'create'); }
function testCreateContactFromMailchimpRequest() { $request_data = CRM_CiviMailchimp_Page_WebhookTest::sampleRequestSubscribeOrProfileUpdate(); $contact = CRM_CiviMailchimp_Utils::createContactFromMailchimpRequest($request_data); $location_type = CRM_Core_BAO_LocationType::getDefault(); $this->assertEquals('Individual', $contact->contact_type); $this->assertEquals($request_data['merges']['FNAME'], $contact->first_name); $this->assertEquals($request_data['merges']['LNAME'], $contact->last_name); $this->assertEquals($request_data['email'], $contact->email[0]->email); $this->assertEquals(1, $contact->email[0]->is_primary); $this->assertEquals($location_type->id, $contact->email[0]->location_type_id); }
/** * Build the form object. * * @return void */ public function buildQuickForm() { $this->add('hidden', 'gid', $this->_gid); switch ($this->_mode) { case self::MODE_CREATE: case self::MODE_EDIT: case self::MODE_REGISTER: CRM_Utils_Hook::buildProfile($this->_ufGroup['name']); break; case self::MODE_SEARCH: CRM_Utils_Hook::searchProfile($this->_ufGroup['name']); break; default: } //lets have single status message, CRM-4363 $return = FALSE; $statusMessage = NULL; if ($this->_multiRecord & CRM_Core_Action::ADD && $this->_maxRecordLimit) { return; } if ($this->_multiRecord & CRM_Core_Action::DELETE) { if (!$this->_recordExists) { CRM_Core_Session::setStatus(ts('The record %1 doesnot exists', array(1 => $this->_recordId)), ts('Record doesnot exists'), 'alert'); } else { $this->assign('deleteRecord', TRUE); } return; } CRM_Core_BAO_Address::checkContactSharedAddressFields($this->_fields, $this->_id); // we should not allow component and mix profiles in search mode if ($this->_mode != self::MODE_REGISTER) { //check for mix profile fields (eg: individual + other contact type) if (CRM_Core_BAO_UFField::checkProfileType($this->_gid)) { if ($this->_mode & self::MODE_EDIT && $this->_isContactActivityProfile) { $errors = self::validateContactActivityProfile($this->_activityId, $this->_id, $this->_gid); if (!empty($errors)) { $statusMessage = array_pop($errors); $return = TRUE; } } else { $statusMessage = ts('Profile search, view and edit are not supported for Profiles which include fields for more than one record type.'); $return = TRUE; } } $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid); if ($this->_id) { $contactTypes = CRM_Contact_BAO_Contact::getContactTypes($this->_id); $contactType = $contactTypes[0]; array_shift($contactTypes); $contactSubtypes = $contactTypes; $profileSubType = FALSE; if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) { $profileSubType = $profileType; $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType); } if ($profileType != 'Contact' && !$this->_isContactActivityProfile && ($profileSubType && !empty($contactSubtypes) && !in_array($profileSubType, $contactSubtypes) || $profileType != $contactType)) { $return = TRUE; if (!$statusMessage) { $statusMessage = ts("This profile is configured for contact type '%1'. It cannot be used to edit contacts of other types.", array(1 => $profileSubType ? $profileSubType : $profileType)); } } } if (in_array($profileType, array("Membership", "Participant", "Contribution"))) { $return = TRUE; if (!$statusMessage) { $statusMessage = ts('Profile is not configured for the selected action.'); } } } //lets have single status message, $this->assign('statusMessage', $statusMessage); if ($return) { return FALSE; } $this->assign('id', $this->_id); $this->assign('mode', $this->_mode); $this->assign('action', $this->_action); $this->assign('fields', $this->_fields); $this->assign('fieldset', isset($this->_fieldset) ? $this->_fieldset : ""); // should we restrict what we display $admin = TRUE; if ($this->_mode == self::MODE_EDIT) { $admin = FALSE; // show all fields that are visibile: // if we are a admin OR the same user OR acl-user with access to the profile // or we have checksum access to this contact (i.e. the user without a login) - CRM-5909 if (CRM_Core_Permission::check('administer users') || $this->_id == $this->_currentUserID || $this->_isPermissionedChecksum || in_array($this->_gid, CRM_ACL_API::group(CRM_Core_Permission::EDIT, NULL, 'civicrm_uf_group', CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id')))) { $admin = TRUE; } } // if false, user is not logged-in. $anonUser = FALSE; if (!$this->_currentUserID) { $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); $primaryLocationType = $defaultLocationType->id; $anonUser = TRUE; } $this->assign('anonUser', $anonUser); $addCaptcha = array(); $emailPresent = FALSE; // add the form elements foreach ($this->_fields as $name => $field) { // make sure that there is enough permission to expose this field if (!$admin && $field['visibility'] == 'User and User Admin Only') { unset($this->_fields[$name]); continue; } // since the CMS manages the email field, suppress the email display if in // register mode which occur within the CMS form if ($this->_mode == self::MODE_REGISTER && substr($name, 0, 5) == 'email') { unset($this->_fields[$name]); continue; } list($prefixName, $index) = CRM_Utils_System::explode('-', $name, 2); CRM_Core_BAO_UFGroup::buildProfile($this, $field, $this->_mode); if ($field['add_to_group_id']) { $addToGroupId = $field['add_to_group_id']; } //build array for captcha if ($field['add_captcha']) { $addCaptcha[$field['group_id']] = $field['add_captcha']; } if ($name == 'email-Primary' || ($name == 'email-' . isset($primaryLocationType) ? $primaryLocationType : "")) { $emailPresent = TRUE; $this->_mail = $name; } } // add captcha only for create mode. if ($this->_mode == self::MODE_CREATE) { // suppress captcha for logged in users only if ($this->_currentUserID) { $this->_isAddCaptcha = FALSE; } elseif (!$this->_isAddCaptcha && !empty($addCaptcha)) { $this->_isAddCaptcha = TRUE; } if ($this->_gid) { $dao = new CRM_Core_DAO_UFGroup(); $dao->id = $this->_gid; $dao->addSelect(); $dao->addSelect('is_update_dupe'); if ($dao->find(TRUE)) { if ($dao->is_update_dupe) { $this->_isUpdateDupe = $dao->is_update_dupe; } } } } else { $this->_isAddCaptcha = FALSE; } //finally add captcha to form. if ($this->_isAddCaptcha) { $captcha = CRM_Utils_ReCAPTCHA::singleton(); $captcha->add($this); } $this->assign("isCaptcha", $this->_isAddCaptcha); if ($this->_mode != self::MODE_SEARCH) { if (isset($addToGroupId)) { $this->_ufGroup['add_to_group_id'] = $addToGroupId; } } //let's do set defaults for the profile $this->setDefaultsValues(); $action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, NULL); if ($this->_mode == self::MODE_CREATE) { CRM_Core_BAO_CMSUser::buildForm($this, $this->_gid, $emailPresent, $action); } else { $this->assign('showCMS', FALSE); } $this->assign('groupId', $this->_gid); // if view mode pls freeze it with the done button. if ($this->_action & CRM_Core_Action::VIEW) { $this->freeze(); } if ($this->_context == 'dialog') { $this->addElement('submit', $this->_duplicateButtonName, ts('Save Matching Contact')); } }
function blockSetDefaults(&$defaults) { $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant::locationType()), 'is_int'); sort($locationTypeKeys); // get the default location type require_once 'CRM/Core/BAO/LocationType.php'; $locationType = CRM_Core_BAO_LocationType::getDefault(); // unset primary location type $primaryLocationTypeIdKey = CRM_Utils_Array::key($locationType->id, $locationTypeKeys); unset($locationTypeKeys[$primaryLocationTypeIdKey]); // reset the array sequence $locationTypeKeys = array_values($locationTypeKeys); // get default phone and im provider id. require_once 'CRM/Core/OptionGroup.php'; $defPhoneTypeId = key(CRM_Core_OptionGroup::values('phone_type', false, false, false, ' AND is_default = 1')); $defIMProviderId = key(CRM_Core_OptionGroup::values('instant_messenger_service', false, false, false, ' AND is_default = 1')); $allBlocks = $this->_blocks; if (array_key_exists('Address', $this->_editOptions)) { $allBlocks['Address'] = $this->_editOptions['Address']; } $config =& CRM_Core_Config::singleton(); foreach ($allBlocks as $blockName => $label) { $name = strtolower($blockName); if (array_key_exists($name, $defaults) && !CRM_Utils_System::isNull($defaults[$name])) { continue; } for ($instance = 1; $instance <= $this->get($blockName . "_Block_Count"); $instance++) { //set location to primary for first one. if ($instance == 1) { $defaults[$name][$instance]['is_primary'] = true; $defaults[$name][$instance]['location_type_id'] = $locationType->id; } else { $locTypeId = isset($locationTypeKeys[$instance - 1]) ? $locationTypeKeys[$instance - 1] : $locationType->id; $defaults[$name][$instance]['location_type_id'] = $locTypeId; } //set default country if ($name == 'address' && $config->defaultContactCountry) { $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry; } //set default phone type. if ($name == 'phone' && $defPhoneTypeId) { $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId; } //set default im provider. if ($name == 'im' && $defIMProviderId) { $defaults[$name][$instance]['provider_id'] = $defIMProviderId; } } } // set defaults for country-state widget if (CRM_Utils_Array::value('address', $defaults) && is_array($defaults['address'])) { require_once 'CRM/Contact/Form/Edit/Address.php'; foreach ($defaults['address'] as $blockId => $values) { CRM_Contact_Form_Edit_Address::fixStateSelect($this, "address[{$blockId}][country_id]", "address[{$blockId}][state_province_id]", CRM_Utils_Array::value('country_id', $values, $config->defaultContactCountry)); } } }
/** * Set defaults for the form. * * @return array */ public function setDefaultValues() { $defaults = $this->_values; $config = CRM_Core_Config::singleton(); //set address block defaults if (!empty($defaults['address'])) { CRM_Contact_Form_Edit_Address::setDefaultValues($defaults, $this); } else { // get the default location type $locationType = CRM_Core_BAO_LocationType::getDefault(); if ($this->_locBlockNo == 1) { $address['is_primary'] = TRUE; $address['location_type_id'] = $locationType->id; } $address['country_id'] = $config->defaultContactCountry; $defaults['address'][$this->_locBlockNo] = $address; } return $defaults; }
/** * Build the form object. */ public function buildQuickForm() { //to save the current mappings if (!$this->get('savedMapping')) { $saveDetailsName = ts('Save this field mapping'); $this->applyFilter('saveMappingName', 'trim'); $this->add('text', 'saveMappingName', ts('Name')); $this->add('text', 'saveMappingDesc', ts('Description')); } else { $savedMapping = $this->get('savedMapping'); list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue, $mappingWebsiteType) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping); //get loaded Mapping Fields $mappingName = CRM_Utils_Array::value(1, $mappingName); $mappingContactType = CRM_Utils_Array::value(1, $mappingContactType); $mappingLocation = CRM_Utils_Array::value(1, $mappingLocation); $mappingPhoneType = CRM_Utils_Array::value(1, $mappingPhoneType); $mappingImProvider = CRM_Utils_Array::value(1, $mappingImProvider); $mappingRelation = CRM_Utils_Array::value(1, $mappingRelation); $mappingWebsiteType = CRM_Utils_Array::value(1, $mappingWebsiteType); $this->assign('loadedMapping', $savedMapping); $this->set('loadedMapping', $savedMapping); $params = array('id' => $savedMapping); $temp = array(); $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp); $this->assign('savedName', $mappingDetails->name); $this->add('hidden', 'mappingId', $savedMapping); $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL); $saveDetailsName = ts('Save as a new field mapping'); $this->add('text', 'saveMappingName', ts('Name')); $this->add('text', 'saveMappingDesc', ts('Description')); } $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)")); $this->addFormRule(array('CRM_Contact_Import_Form_MapField', 'formRule')); //-------- end of saved mapping stuff --------- $defaults = array(); $mapperKeys = array_keys($this->_mapperFields); $hasColumnNames = !empty($this->_columnNames); $columnPatterns = $this->get('columnPatterns'); $dataPatterns = $this->get('dataPatterns'); $hasLocationTypes = $this->get('fieldTypes'); $this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); // Pass default location to js if ($defaultLocationType) { $this->assign('defaultLocationType', $defaultLocationType->id); $this->assign('defaultLocationTypeLabel', $this->_location_types[$defaultLocationType->id]); } /* Initialize all field usages to false */ foreach ($mapperKeys as $key) { $this->_fieldUsed[$key] = FALSE; } $sel1 = $this->_mapperFields; $sel2[''] = NULL; $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'); foreach ($this->_location_types as $key => $value) { $sel3['phone'][$key] =& $phoneTypes; //build array for IM service provider type for contact $sel3['im'][$key] =& $imProviders; } $sel4 = NULL; // store and cache all relationship types $contactRelation = new CRM_Contact_DAO_RelationshipType(); $contactRelation->find(); while ($contactRelation->fetch()) { $contactRelationCache[$contactRelation->id] = array(); $contactRelationCache[$contactRelation->id]['contact_type_a'] = $contactRelation->contact_type_a; $contactRelationCache[$contactRelation->id]['contact_sub_type_a'] = $contactRelation->contact_sub_type_a; $contactRelationCache[$contactRelation->id]['contact_type_b'] = $contactRelation->contact_type_b; $contactRelationCache[$contactRelation->id]['contact_sub_type_b'] = $contactRelation->contact_sub_type_b; } $highlightedFields = $highlightedRelFields = array(); $highlightedFields['email'] = 'All'; $highlightedFields['external_identifier'] = 'All'; $highlightedFields['first_name'] = 'Individual'; $highlightedFields['last_name'] = 'Individual'; $highlightedFields['household_name'] = 'Household'; $highlightedFields['organization_name'] = 'Organization'; foreach ($mapperKeys as $key) { // check if there is a _a_b or _b_a in the key if (strpos($key, '_a_b') || strpos($key, '_b_a')) { list($id, $first, $second) = explode('_', $key); } else { $id = $first = $second = NULL; } if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') { $cType = $contactRelationCache[$id]["contact_type_{$second}"]; //CRM-5125 for contact subtype specific relationshiptypes $cSubType = NULL; if (!empty($contactRelationCache[$id]["contact_sub_type_{$second}"])) { $cSubType = $contactRelationCache[$id]["contact_sub_type_{$second}"]; } if (!$cType) { $cType = 'All'; } $relatedFields = array(); $relatedFields = CRM_Contact_BAO_Contact::importableFields($cType); unset($relatedFields['']); $values = array(); foreach ($relatedFields as $name => $field) { $values[$name] = $field['title']; if (isset($hasLocationTypes[$name])) { $sel3[$key][$name] = $this->_location_types; } elseif ($name == 'url') { $sel3[$key][$name] = $websiteTypes; } else { $sel3[$name] = NULL; } } //fix to append custom group name to field name, CRM-2676 if (empty($this->_formattedFieldNames[$cType]) || $cType == $this->_contactType) { $this->_formattedFieldNames[$cType] = $this->formatCustomFieldName($values); } $this->_formattedFieldNames[$cType] = array_merge($values, $this->_formattedFieldNames[$cType]); //Modified the Relationship fields if the fields are //present in dedupe rule if ($this->_onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK && !empty($this->_dedupeFields[$cType]) && is_array($this->_dedupeFields[$cType])) { static $cTypeArray = array(); if ($cType != $this->_contactType && !in_array($cType, $cTypeArray)) { foreach ($this->_dedupeFields[$cType] as $val) { if ($valTitle = CRM_Utils_Array::value($val, $this->_formattedFieldNames[$cType])) { $this->_formattedFieldNames[$cType][$val] = $valTitle . ' (match to contact)'; } } $cTypeArray[] = $cType; } } foreach ($highlightedFields as $k => $v) { if ($v == $cType || $v == 'All') { $highlightedRelFields[$key][] = $k; } } $this->assign('highlightedRelFields', $highlightedRelFields); $sel2[$key] = $this->_formattedFieldNames[$cType]; if (!empty($cSubType)) { //custom fields for sub type $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($cSubType); if (!empty($subTypeFields)) { $subType = NULL; foreach ($subTypeFields as $customSubTypeField => $details) { $subType[$customSubTypeField] = $details['title']; $sel2[$key] = array_merge($sel2[$key], $this->formatCustomFieldName($subType)); } } } foreach ($this->_location_types as $k => $value) { $sel4[$key]['phone'][$k] =& $phoneTypes; //build array of IM service provider for related contact $sel4[$key]['im'][$k] =& $imProviders; } } else { $options = NULL; if (!empty($hasLocationTypes[$key])) { $options = $this->_location_types; } elseif ($key == 'url') { $options = $websiteTypes; } $sel2[$key] = $options; } } $js = "<script type='text/javascript'>\n"; $formName = 'document.forms.' . $this->_name; //used to warn for mismatch column count or mismatch mapping $warning = 0; for ($i = 0; $i < $this->_columnCount; $i++) { $sel =& $this->addElement('hierselect', "mapper[{$i}]", ts('Mapper for Field %1', array(1 => $i)), NULL); $jsSet = FALSE; if ($this->get('savedMapping')) { if (isset($mappingName[$i])) { if ($mappingName[$i] != ts('- do not import -')) { if (isset($mappingRelation[$i])) { // relationship mapping switch ($this->get('contactType')) { case CRM_Import_Parser::CONTACT_INDIVIDUAL: $contactType = 'Individual'; break; case CRM_Import_Parser::CONTACT_HOUSEHOLD: $contactType = 'Household'; break; case CRM_Import_Parser::CONTACT_ORGANIZATION: $contactType = 'Organization'; } //CRM-5125 $contactSubType = NULL; if ($this->get('contactSubType')) { $contactSubType = $this->get('contactSubType'); } $relations = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $contactType, FALSE, 'label', TRUE, $contactSubType); foreach ($relations as $key => $var) { if ($key == $mappingRelation[$i]) { $relation = $key; break; } } $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$i])); $websiteTypeId = isset($mappingWebsiteType[$i]) ? $mappingWebsiteType[$i] : NULL; $locationId = isset($mappingLocation[$i]) ? $mappingLocation[$i] : 0; $phoneType = isset($mappingPhoneType[$i]) ? $mappingPhoneType[$i] : NULL; //get provider id from saved mappings $imProvider = isset($mappingImProvider[$i]) ? $mappingImProvider[$i] : NULL; if ($websiteTypeId) { $defaults["mapper[{$i}]"] = array($relation, $contactDetails, $websiteTypeId); if (!$websiteTypeId) { $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n"; } } else { // default for IM/phone when mapping with relation is true $typeId = NULL; if (isset($phoneType)) { $typeId = $phoneType; } elseif (isset($imProvider)) { $typeId = $imProvider; } $defaults["mapper[{$i}]"] = array($relation, $contactDetails, $locationId, $typeId); if (!$locationId) { $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n"; } } // fix for edge cases, CRM-4954 if ($contactDetails == 'image_url') { $contactDetails = str_replace('url', 'URL', $contactDetails); } if (!$contactDetails) { $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n"; } if (!$phoneType && !$imProvider) { $js .= "{$formName}['mapper[{$i}][3]'].style.display = 'none';\n"; } //$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n"; $jsSet = TRUE; } else { $mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]); $websiteTypeId = isset($mappingWebsiteType[$i]) ? $mappingWebsiteType[$i] : NULL; $locationId = isset($mappingLocation[$i]) ? $mappingLocation[$i] : 0; $phoneType = isset($mappingPhoneType[$i]) ? $mappingPhoneType[$i] : NULL; // get IM service provider id $imProvider = isset($mappingImProvider[$i]) ? $mappingImProvider[$i] : NULL; if ($websiteTypeId) { if (!$websiteTypeId) { $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n"; } $defaults["mapper[{$i}]"] = array($mappingHeader[0], $websiteTypeId); } else { if (!$locationId) { $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n"; } //default for IM/phone without related contact $typeId = NULL; if (isset($phoneType)) { $typeId = $phoneType; } elseif (isset($imProvider)) { $typeId = $imProvider; } $defaults["mapper[{$i}]"] = array($mappingHeader[0], $locationId, $typeId); } if (!$phoneType && !$imProvider) { $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n"; } $js .= "{$formName}['mapper[{$i}][3]'].style.display = 'none';\n"; $jsSet = TRUE; } } else { $defaults["mapper[{$i}]"] = array(); } if (!$jsSet) { for ($k = 1; $k < 4; $k++) { $js .= "{$formName}['mapper[{$i}][{$k}]'].style.display = 'none';\n"; } } } else { // this load section to help mapping if we ran out of saved columns when doing Load Mapping $js .= "swapOptions({$formName}, 'mapper[{$i}]', 0, 3, 'hs_mapper_0_');\n"; if ($hasColumnNames) { $defaults["mapper[{$i}]"] = array($this->defaultFromColumnName($this->_columnNames[$i], $columnPatterns)); } else { $defaults["mapper[{$i}]"] = array($this->defaultFromData($dataPatterns, $i)); } } //end of load mapping } else { $js .= "swapOptions({$formName}, 'mapper[{$i}]', 0, 3, 'hs_mapper_0_');\n"; if ($hasColumnNames) { // do array search first to see if has mapped key $columnKey = ''; $columnKey = array_search($this->_columnNames[$i], $this->_mapperFields); if (isset($this->_fieldUsed[$columnKey])) { $defaults["mapper[{$i}]"] = $columnKey; $this->_fieldUsed[$key] = TRUE; } else { // Infer the default from the column names if we have them $defaults["mapper[{$i}]"] = array($this->defaultFromColumnName($this->_columnNames[$i], $columnPatterns), 0); } } else { // Otherwise guess the default from the form of the data $defaults["mapper[{$i}]"] = array($this->defaultFromData($dataPatterns, $i), 0); } } $sel->setOptions(array($sel1, $sel2, $sel3, $sel4)); } $js .= "</script>\n"; $this->assign('initHideBoxes', $js); //set warning if mismatch in more than if (isset($mappingName) && $this->_columnCount != count($mappingName)) { $warning++; } if ($warning != 0 && $this->get('savedMapping')) { $session = CRM_Core_Session::singleton(); $session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.')); } else { $session = CRM_Core_Session::singleton(); $session->setStatus(NULL); } $this->setDefaults($defaults); $this->addButtons(array(array('type' => 'back', 'name' => ts('Previous')), array('type' => 'next', 'name' => ts('Continue'), 'spacing' => ' ', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel')))); }
/** * Create a new forward event, create a new contact if necessary */ static function &forward($job_id, $queue_id, $hash, $forward_email, $fromEmail = null, $comment = null) { $q =& CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash); $successfulForward = false; if (!$q) { return $successfulForward; } /* Find the email address/contact, if it exists */ $contact = CRM_Contact_BAO_Contact::getTableName(); $location = CRM_Core_BAO_Location::getTableName(); $email = CRM_Core_BAO_Email::getTableName(); $queueTable = CRM_Mailing_Event_BAO_Queue::getTableName(); $job = CRM_Mailing_BAO_Job::getTableName(); $mailing = CRM_Mailing_BAO_Mailing::getTableName(); $forward = self::getTableName(); $domain =& CRM_Core_BAO_Domain::getDomain(); $dao =& new CRM_Core_Dao(); $dao->query("\n SELECT {$contact}.id as contact_id,\n {$email}.id as email_id,\n {$contact}.do_not_email as do_not_email,\n {$queueTable}.id as queue_id\n FROM ({$email}, {$job} as temp_job)\n INNER JOIN {$contact}\n ON {$email}.contact_id = {$contact}.id\n LEFT JOIN {$queueTable}\n ON {$email}.id = {$queueTable}.email_id\n LEFT JOIN {$job}\n ON {$queueTable}.job_id = {$job}.id\n AND temp_job.mailing_id = {$job}.mailing_id\n WHERE {$queueTable}.job_id = {$job_id}\n AND {$email}.email = '" . CRM_Utils_Type::escape($forward_email, 'String') . "'"); $dao->fetch(); require_once 'CRM/Core/Transaction.php'; $transaction = new CRM_Core_Transaction(); if (isset($dao->queue_id) || $dao->do_not_email == 1) { /* We already sent this mailing to $forward_email, or we should * never email this contact. Give up. */ return $successfulForward; } require_once 'api/v2/Contact.php'; $contact_params = array('email' => $forward_email); $count = civicrm_contact_search_count($contact_params); if ($count == 0) { require_once 'CRM/Core/BAO/LocationType.php'; /* If the contact does not exist, create one. */ $formatted = array('contact_type' => 'Individual'); $locationType = CRM_Core_BAO_LocationType::getDefault(); $value = array('email' => $forward_email, 'location_type_id' => $locationType->id); _civicrm_add_formatted_param($value, $formatted); require_once 'CRM/Import/Parser.php'; $formatted['onDuplicate'] = CRM_Import_Parser::DUPLICATE_SKIP; $formatted['fixAddress'] = true; $contact =& civicrm_contact_format_create($formatted); if (civicrm_error($contact, CRM_Core_Error)) { return $successfulForward; } $contact_id = $contact['id']; } $email =& new CRM_Core_DAO_Email(); $email->email = $forward_email; $email->find(true); $email_id = $email->id; if (!$contact_id) { $contact_id = $email->contact_id; } /* Create a new queue event */ $queue_params = array('email_id' => $email_id, 'contact_id' => $contact_id, 'job_id' => $job_id); $queue =& CRM_Mailing_Event_BAO_Queue::create($queue_params); $forward =& new CRM_Mailing_Event_BAO_Forward(); $forward->time_stamp = date('YmdHis'); $forward->event_queue_id = $queue_id; $forward->dest_queue_id = $queue->id; $forward->save(); $dao->reset(); $dao->query(" SELECT {$job}.mailing_id as mailing_id \n FROM {$job}\n WHERE {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer')); $dao->fetch(); $mailing_obj =& new CRM_Mailing_BAO_Mailing(); $mailing_obj->id = $dao->mailing_id; $mailing_obj->find(true); $config =& CRM_Core_Config::singleton(); $mailer =& $config->getMailer(); $recipient = null; $attachments = null; $message =& $mailing_obj->compose($job_id, $queue->id, $queue->hash, $queue->contact_id, $forward_email, $recipient, false, null, $attachments, true, $fromEmail); //append comment if added while forwarding. if (count($comment)) { $message->_txtbody = $comment['body_text'] . $message->_txtbody; if (CRM_Utils_Array::value('body_html', $comment)) { $message->_htmlbody = $comment['body_html'] . '<br />---------------Original message---------------------<br />' . $message->_htmlbody; } } $body = $message->get(); $headers = $message->headers(); PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Core_Error', 'nullHandler')); $result = null; if (is_object($mailer)) { $result = $mailer->send($recipient, $headers, $body); CRM_Core_Error::setCallback(); } $params = array('event_queue_id' => $queue->id, 'job_id' => $job_id, 'hash' => $queue->hash); if (is_a($result, PEAR_Error)) { /* Register the bounce event */ $params = array_merge($params, CRM_Mailing_BAO_BouncePattern::match($result->getMessage())); CRM_Mailing_Event_BAO_Bounce::create($params); } else { $successfulForward = true; /* Register the delivery event */ CRM_Mailing_Event_BAO_Delivered::create($params); } $transaction->commit(); return $successfulForward; }
/** * Format profile contact parameters. * * @param array $params * @param $fields * @param int $contactID * @param int $ufGroupId * @param null $ctype * @param bool $skipCustom * * @return array */ public static function formatProfileContactParams(&$params, &$fields, $contactID = NULL, $ufGroupId = NULL, $ctype = NULL, $skipCustom = FALSE) { $data = $contactDetails = array(); // get the contact details (hier) if ($contactID) { list($details, $options) = self::getHierContactDetails($contactID, $fields); $contactDetails = $details[$contactID]; $data['contact_type'] = CRM_Utils_Array::value('contact_type', $contactDetails); $data['contact_sub_type'] = CRM_Utils_Array::value('contact_sub_type', $contactDetails); } else { //we should get contact type only if contact if ($ufGroupId) { $data['contact_type'] = CRM_Core_BAO_UFField::getProfileType($ufGroupId); //special case to handle profile with only contact fields if ($data['contact_type'] == 'Contact') { $data['contact_type'] = 'Individual'; } elseif (CRM_Contact_BAO_ContactType::isaSubType($data['contact_type'])) { $data['contact_type'] = CRM_Contact_BAO_ContactType::getBasicType($data['contact_type']); } } elseif ($ctype) { $data['contact_type'] = $ctype; } else { $data['contact_type'] = 'Individual'; } } //fix contact sub type CRM-5125 if (array_key_exists('contact_sub_type', $params) && !empty($params['contact_sub_type'])) { $data['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, (array) $params['contact_sub_type']) . CRM_Core_DAO::VALUE_SEPARATOR; } elseif (array_key_exists('contact_sub_type_hidden', $params) && !empty($params['contact_sub_type_hidden'])) { // if profile was used, and had any subtype, we obtain it from there $data['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, (array) $params['contact_sub_type_hidden']) . CRM_Core_DAO::VALUE_SEPARATOR; } if ($ctype == 'Organization') { $data['organization_name'] = CRM_Utils_Array::value('organization_name', $contactDetails); } elseif ($ctype == 'Household') { $data['household_name'] = CRM_Utils_Array::value('household_name', $contactDetails); } $locationType = array(); $count = 1; if ($contactID) { //add contact id $data['contact_id'] = $contactID; $primaryLocationType = self::getPrimaryLocationType($contactID); } else { $defaultLocation = CRM_Core_BAO_LocationType::getDefault(); $defaultLocationId = $defaultLocation->id; } // get the billing location type $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate'); $billingLocationTypeId = array_search('Billing', $locationTypes); $blocks = array('email', 'phone', 'im', 'openid'); $multiplFields = array('url'); // prevent overwritten of formatted array, reset all block from // params if it is not in valid format (since import pass valid format) foreach ($blocks as $blk) { if (array_key_exists($blk, $params) && !is_array($params[$blk])) { unset($params[$blk]); } } $primaryPhoneLoc = NULL; $session = CRM_Core_Session::singleton(); foreach ($params as $key => $value) { $fieldName = $locTypeId = $typeId = NULL; list($fieldName, $locTypeId, $typeId) = CRM_Utils_System::explode('-', $key, 3); //store original location type id $actualLocTypeId = $locTypeId; if ($locTypeId == 'Primary') { if ($contactID) { if (in_array($fieldName, $blocks)) { $locTypeId = self::getPrimaryLocationType($contactID, FALSE, $fieldName); } else { $locTypeId = self::getPrimaryLocationType($contactID, FALSE, 'address'); } $primaryLocationType = $locTypeId; } else { $locTypeId = $defaultLocationId; } } if (is_numeric($locTypeId) && !in_array($fieldName, $multiplFields) && substr($fieldName, 0, 7) != 'custom_') { $index = $locTypeId; if (is_numeric($typeId)) { $index .= '-' . $typeId; } if (!in_array($index, $locationType)) { $locationType[$count] = $index; $count++; } $loc = CRM_Utils_Array::key($index, $locationType); $blockName = in_array($fieldName, $blocks) ? $fieldName : 'address'; $data[$blockName][$loc]['location_type_id'] = $locTypeId; //set is_billing true, for location type "Billing" if ($locTypeId == $billingLocationTypeId) { $data[$blockName][$loc]['is_billing'] = 1; } if ($contactID) { //get the primary location type if ($locTypeId == $primaryLocationType) { $data[$blockName][$loc]['is_primary'] = 1; } } elseif ($locTypeId == $defaultLocationId) { $data[$blockName][$loc]['is_primary'] = 1; } if (in_array($fieldName, array('phone'))) { if ($typeId) { $data['phone'][$loc]['phone_type_id'] = $typeId; } else { $data['phone'][$loc]['phone_type_id'] = ''; } $data['phone'][$loc]['phone'] = $value; //special case to handle primary phone with different phone types // in this case we make first phone type as primary if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) { $primaryPhoneLoc = $loc; } if ($loc != $primaryPhoneLoc) { unset($data['phone'][$loc]['is_primary']); } } elseif ($fieldName == 'phone_ext') { $data['phone'][$loc]['phone_ext'] = $value; } elseif ($fieldName == 'email') { $data['email'][$loc]['email'] = $value; } elseif ($fieldName == 'im') { if (isset($params[$key . '-provider_id'])) { $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id']; } if (strpos($key, '-provider_id') !== FALSE) { $data['im'][$loc]['provider_id'] = $params[$key]; } else { $data['im'][$loc]['name'] = $value; } } elseif ($fieldName == 'openid') { $data['openid'][$loc]['openid'] = $value; } else { if ($fieldName === 'state_province') { // CRM-3393 if (is_numeric($value) && (int) $value >= 1000) { $data['address'][$loc]['state_province_id'] = $value; } elseif (empty($value)) { $data['address'][$loc]['state_province_id'] = ''; } else { $data['address'][$loc]['state_province'] = $value; } } elseif ($fieldName === 'country') { // CRM-3393 if (is_numeric($value) && (int) $value >= 1000) { $data['address'][$loc]['country_id'] = $value; } elseif (empty($value)) { $data['address'][$loc]['country_id'] = ''; } else { $data['address'][$loc]['country'] = $value; } } elseif ($fieldName === 'county') { $data['address'][$loc]['county_id'] = $value; } elseif ($fieldName == 'address_name') { $data['address'][$loc]['name'] = $value; } elseif (substr($fieldName, 0, 14) === 'address_custom') { $data['address'][$loc][substr($fieldName, 8)] = $value; } else { $data['address'][$loc][$fieldName] = $value; } } } else { if (substr($key, 0, 4) === 'url-') { $websiteField = explode('-', $key); $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1]; $data['website'][$websiteField[1]]['url'] = $value; } elseif (in_array($key, self::$_greetingTypes, TRUE)) { //save email/postal greeting and addressee values if any, CRM-4575 $data[$key . '_id'] = $value; } elseif (!$skipCustom && ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key))) { // for autocomplete transfer hidden value instead of label if ($params[$key] && isset($params[$key . '_id'])) { $value = $params[$key . '_id']; } // we need to append time with date if ($params[$key] && isset($params[$key . '_time'])) { $value .= ' ' . $params[$key . '_time']; } // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128 if (($session->get('authSrc') & CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN) == 0 && ($value == '' || !isset($value))) { continue; } $valueId = NULL; if (!empty($params['customRecordValues'])) { if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) { foreach ($params['customRecordValues'] as $recId => $customFields) { if (is_array($customFields) && !empty($customFields)) { foreach ($customFields as $customFieldName) { if ($customFieldName == $key) { $valueId = $recId; break; } } } } } } $type = $data['contact_type']; if (!empty($data['contact_sub_type'])) { $type = $data['contact_sub_type']; $type = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($type, CRM_Core_DAO::VALUE_SEPARATOR)); // generally a contact even if, has multiple subtypes the parent-type is going to be one only // and since formatCustomField() would be interested in parent type, lets consider only one subtype // as the results going to be same. $type = $type[0]; } CRM_Core_BAO_CustomField::formatCustomField($customFieldId, $data['custom'], $value, $type, $valueId, $contactID); } elseif ($key == 'edit') { continue; } else { if ($key == 'location') { foreach ($value as $locationTypeId => $field) { foreach ($field as $block => $val) { if ($block == 'address' && array_key_exists('address_name', $val)) { $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name']; } } } } if ($key == 'phone' && isset($params['phone_ext'])) { $data[$key] = $value; foreach ($value as $cnt => $phoneBlock) { if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) { $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext'); } } } elseif (in_array($key, array('nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id')) && ($value == '' || !isset($value)) && ($session->get('authSrc') & CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN) == 0) { // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value // to avoid update with empty values continue; } else { $data[$key] = $value; } } } } if (!isset($data['contact_type'])) { $data['contact_type'] = 'Individual'; } //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone) $privacy = CRM_Core_SelectValues::privacy(); foreach ($privacy as $key => $value) { if (array_key_exists($key, $fields)) { // do not reset values for existing contacts, if fields are added to a profile if (array_key_exists($key, $params)) { $data[$key] = $params[$key]; if (empty($params[$key])) { $data[$key] = 0; } } elseif (!$contactID) { $data[$key] = 0; } } } return array($data, $contactDetails); }
/** * Register a subscription event. Create a new contact if one does not * already exist. * * @param int $group_id * The group id to subscribe to. * @param string $email * The email address of the (new) contact. * @param int $contactId * Currently used during event registration/contribution. * Specifically to avoid linking group to wrong duplicate contact * during event registration. * @param string $context * * @return int|null * $se_id The id of the subscription event, null on failure */ public static function &subscribe($group_id, $email, $contactId = NULL, $context = NULL) { // CRM-1797 - allow subscription only to public groups $params = array('id' => (int) $group_id); $defaults = array(); $contact_id = NULL; $success = NULL; $bao = CRM_Contact_BAO_Group::retrieve($params, $defaults); if ($bao && substr($bao->visibility, 0, 6) != 'Public' && $context != 'profile') { return $success; } $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower'; $email = $strtolower($email); // process the query only if no contactId if ($contactId) { $contact_id = $contactId; } else { /* First, find out if the contact already exists */ $query = "\n SELECT DISTINCT contact_a.id as contact_id\n FROM civicrm_contact contact_a\nLEFT JOIN civicrm_email ON contact_a.id = civicrm_email.contact_id\n WHERE civicrm_email.email = %1 AND contact_a.is_deleted = 0"; $params = array(1 => array($email, 'String')); $dao = CRM_Core_DAO::executeQuery($query, $params); $id = array(); // lets just use the first contact id we got if ($dao->fetch()) { $contact_id = $dao->contact_id; } $dao->free(); } $transaction = new CRM_Core_Transaction(); if (!$contact_id) { require_once 'CRM/Utils/DeprecatedUtils.php'; /* If the contact does not exist, create one. */ $formatted = array('contact_type' => 'Individual', 'version' => 3); $locationType = CRM_Core_BAO_LocationType::getDefault(); $value = array('email' => $email, 'location_type_id' => $locationType->id); _civicrm_api3_deprecated_add_formatted_param($value, $formatted); $formatted['onDuplicate'] = CRM_Import_Parser::DUPLICATE_SKIP; $formatted['fixAddress'] = TRUE; require_once 'api/api.php'; $contact = civicrm_api('contact', 'create', $formatted); if (civicrm_error($contact)) { return $success; } $contact_id = $contact['id']; } elseif (!is_numeric($contact_id) && (int) $contact_id > 0) { // make sure contact_id is numeric return $success; } /* Get the primary email id from the contact to use as a hash input */ $dao = new CRM_Core_DAO(); $query = "\nSELECT civicrm_email.id as email_id\n FROM civicrm_email\n WHERE civicrm_email.email = %1\n AND civicrm_email.contact_id = %2"; $params = array(1 => array($email, 'String'), 2 => array($contact_id, 'Integer')); $dao = CRM_Core_DAO::executeQuery($query, $params); if (!$dao->fetch()) { CRM_Core_Error::fatal('Please file an issue with the backtrace'); return $success; } $se = new CRM_Mailing_Event_BAO_Subscribe(); $se->group_id = $group_id; $se->contact_id = $contact_id; $se->time_stamp = date('YmdHis'); $se->hash = substr(sha1("{$group_id}:{$contact_id}:{$dao->email_id}:" . time()), 0, 16); $se->save(); $contacts = array($contact_id); CRM_Contact_BAO_GroupContact::addContactsToGroup($contacts, $group_id, 'Email', 'Pending', $se->id); $transaction->commit(); return $se; }
/** * retrieve the default location_type * * @param NULL * * @return object The default location type object on success, * null otherwise * @static * @access public */ static function &getDefault() { if (self::$_defaultLocationType == null) { $params = array('is_default' => 1); $defaults = array(); self::$_defaultLocationType = self::retrieve($params, $defaults); } return self::$_defaultLocationType; }
/** * Form submission of new/edit contact is processed. * * @access public * * @return void */ public function postProcess() { // store the submitted values in an array $params = $this->controller->exportValues($this->_name); $locType = CRM_Core_BAO_LocationType::getDefault(); foreach (array('phone', 'email', 'address') as $locFld) { if (!empty($this->_defaults[$locFld]) && $this->_defaults[$locFld][1]['location_type_id']) { $params[$locFld][1]['is_primary'] = $this->_defaults[$locFld][1]['is_primary']; $params[$locFld][1]['location_type_id'] = $this->_defaults[$locFld][1]['location_type_id']; } else { $params[$locFld][1]['is_primary'] = 1; $params[$locFld][1]['location_type_id'] = $locType->id; } } $params['contact_type'] = $this->_contactType; $params['contact_id'] = $this->_contactId; $contact = CRM_Contact_BAO_Contact::create($params, TRUE); // set status message. if ($this->_contactId) { $message = ts('%1 has been updated.', array(1 => $contact->display_name)); } else { $message = ts('%1 has been created.', array(1 => $contact->display_name)); } CRM_Core_Session::setStatus($message, ts('Contact Saved'), 'success'); }
/** * set defaults for the form * * @return void * @access public */ public function setDefaultValues() { $defaults = $this->_values; $config = CRM_Core_Config::singleton(); //set address block defaults if (CRM_Utils_Array::value('address', $defaults)) { CRM_Contact_Form_Edit_Address::setDefaultValues($defaults, $this); } else { // get the default location type $locationType = CRM_Core_BAO_LocationType::getDefault(); if ($this->_locBlockNo == 1) { $address['is_primary'] = TRUE; $address['location_type_id'] = $locationType->id; } $address['country_id'] = $config->defaultContactCountry; $defaults['address'][$this->_locBlockNo] = $address; } $values = $defaults['address'][$this->_locBlockNo]; CRM_Contact_Form_Edit_Address::fixStateSelect($this, "address[{$this->_locBlockNo}][country_id]", "address[{$this->_locBlockNo}][state_province_id]", "address[{$this->_locBlockNo}][county_id]", CRM_Utils_Array::value('country_id', $values, $config->defaultContactCountry), CRM_Utils_Array::value('state_province_id', $values)); return $defaults; }
/** * Get pseudo profile 'billing'. * * This is a function to help us 'pretend' billing is a profile & treat it like it is one. * It gets standard credit card address fields etc * Note this is 'better' that the inbuilt version as it will pull in fallback values * billing location -> is_billing -> primary * * Note that that since the existing code for deriving a blank profile is not easily accessible our * interim solution is just to return an empty array * * @param array $params * * @return array */ function _civicrm_api3_profile_getbillingpseudoprofile(&$params) { $locationTypeID = CRM_Core_BAO_LocationType::getBilling(); if (empty($params['contact_id'])) { $config = CRM_Core_Config::singleton(); $blanks = array('billing_first_name' => '', 'billing_middle_name' => '', 'billing_last_name' => '', 'email-' . $locationTypeID => '', 'billing_email-' . $locationTypeID => '', 'billing_city-' . $locationTypeID => '', 'billing_postal_code-' . $locationTypeID => '', 'billing_street_address-' . $locationTypeID => '', 'billing_country_id-' . $locationTypeID => $config->defaultContactCountry, 'billing_state_province_id-' . $locationTypeID => $config->defaultContactStateProvince); return $blanks; } $addressFields = array('street_address', 'city', 'state_province_id', 'country_id', 'postal_code'); $result = civicrm_api3('contact', 'getsingle', array('id' => $params['contact_id'], 'api.address.get.1' => array('location_type_id' => 'Billing', 'return' => $addressFields), 'api.address.get.2' => array('is_billing' => TRUE, 'return' => $addressFields), 'api.email.get.1' => array('location_type_id' => 'Billing'), 'api.email.get.2' => array('is_billing' => TRUE), 'return' => 'api.email.get, api.address.get, api.address.getoptions, country, state_province, email, first_name, last_name, middle_name, ' . implode($addressFields, ','))); $values = array('billing_first_name' => $result['first_name'], 'billing_middle_name' => $result['middle_name'], 'billing_last_name' => $result['last_name']); if (!empty($result['api.address.get.1']['count'])) { foreach ($addressFields as $fieldname) { $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.1']['values'][0][$fieldname]) ? $result['api.address.get.1']['values'][0][$fieldname] : ''; } } elseif (!empty($result['api.address.get.2']['count'])) { foreach ($addressFields as $fieldname) { $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result['api.address.get.2']['values'][0][$fieldname]) ? $result['api.address.get.2']['values'][0][$fieldname] : ''; } } else { foreach ($addressFields as $fieldname) { $values['billing_' . $fieldname . '-' . $locationTypeID] = isset($result[$fieldname]) ? $result[$fieldname] : ''; } } if (!empty($result['api.email.get.1']['count'])) { $values['billing-email' . '-' . $locationTypeID] = $result['api.email.get.1']['values'][0]['email']; } elseif (!empty($result['api.email.get.2']['count'])) { $values['billing-email' . '-' . $locationTypeID] = $result['api.email.get.2']['values'][0]['email']; } else { $values['billing-email' . '-' . $locationTypeID] = $result['email']; } // return both variants of email to reflect inconsistencies in form layer $values['email' . '-' . $locationTypeID] = $values['billing-email' . '-' . $locationTypeID]; return $values; }
/** * Function to set variables up before form is built * * @return void * @access public */ public function preProcess() { $config = CRM_Core_Config::singleton(); parent::preProcess(); // lineItem isn't set until Register postProcess $this->_lineItem = $this->get('lineItem'); $this->_paymentProcessor = $this->get('paymentProcessor'); if ($this->_contributeMode == 'express') { // rfp == redirect from paypal $rfp = CRM_Utils_Request::retrieve('rfp', 'Boolean', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET'); if ($rfp) { $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this); $expressParams = $payment->getExpressCheckoutDetails($this->get('token')); $this->_params['payer'] = $expressParams['payer']; $this->_params['payer_id'] = $expressParams['payer_id']; $this->_params['payer_status'] = $expressParams['payer_status']; CRM_Core_Payment_Form::mapParams($this->_bltID, $expressParams, $this->_params, FALSE); // fix state and country id if present if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"]) && $this->_params["billing_state_province_id-{$this->_bltID}"]) { $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]); } if (!empty($this->_params["billing_country_id-{$this->_bltID}"]) && $this->_params["billing_country_id-{$this->_bltID}"]) { $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]); } // set a few other parameters for PayPal $this->_params['token'] = $this->get('token'); $this->_params['amount'] = $this->get('amount'); if (!empty($this->_membershipBlock)) { $this->_params['selectMembership'] = $this->get('selectMembership'); } // we use this here to incorporate any changes made by folks in hooks $this->_params['currencyID'] = $config->defaultCurrency; $this->_params['payment_action'] = 'Sale'; // also merge all the other values from the profile fields $values = $this->controller->exportValues('Main'); $skipFields = array('amount', 'amount_other', "billing_street_address-{$this->_bltID}", "billing_city-{$this->_bltID}", "billing_state_province_id-{$this->_bltID}", "billing_postal_code-{$this->_bltID}", "billing_country_id-{$this->_bltID}"); foreach ($values as $name => $value) { // skip amount field if (!in_array($name, $skipFields)) { $this->_params[$name] = $value; } } $this->set('getExpressCheckoutDetails', $this->_params); } else { $this->_params = $this->get('getExpressCheckoutDetails'); } } else { $this->_params = $this->controller->exportValues('Main'); if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) { $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]); } if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) { $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]); } if (isset($this->_params['credit_card_exp_date'])) { $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params); $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params); } $this->_params['ip_address'] = CRM_Utils_System::ipAddress(); $this->_params['amount'] = $this->get('amount'); $this->_useForMember = $this->get('useForMember'); if (isset($this->_params['amount'])) { $priceField = new CRM_Price_DAO_PriceField(); $priceField->price_set_id = $this->_params['priceSetId']; $priceField->orderBy('weight'); $priceField->find(); $contriPriceId = NULL; $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params['priceSetId'], 'is_quick_config'); while ($priceField->fetch()) { if ($priceField->name == "contribution_amount") { $contriPriceId = $priceField->id; } if ($isQuickConfig && !empty($this->_params["price_{$priceField->id}"])) { if ($this->_values['fee'][$priceField->id]['html_type'] != 'Text') { $this->_params['amount_level'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_params["price_{$priceField->id}"], 'label'); } if ($priceField->name == "membership_amount") { $this->_params['selectMembership'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_params["price_{$priceField->id}"], 'membership_type_id'); } } elseif (CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock) && !empty($this->_values['fee'][$priceField->id]) && $this->_values['fee'][$priceField->id]['name'] == "other_amount" && CRM_Utils_Array::value("price_{$contriPriceId}", $this->_params) < 1 && empty($this->_params["price_{$priceField->id}"])) { $this->_params['amount'] = null; } } } $this->_params['currencyID'] = $config->defaultCurrency; $this->_params['payment_action'] = 'Sale'; } $this->_params['is_pay_later'] = $this->get('is_pay_later'); $this->assign('is_pay_later', $this->_params['is_pay_later']); if ($this->_params['is_pay_later']) { $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']); } // if onbehalf-of-organization if (!empty($this->_params['hidden_onbehalf_profile'])) { if (!empty($this->_params['org_option']) && !empty($this->_params['organization_id'])) { if (!empty($this->_params['onbehalfof_id'])) { $this->_params['organization_id'] = $this->_params['onbehalfof_id']; } } $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name']; $addressBlocks = array('street_address', 'city', 'state_province', 'postal_code', 'country', 'supplemental_address_1', 'supplemental_address_2', 'supplemental_address_3', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'address_name'); $blocks = array('email', 'phone', 'im', 'url', 'openid'); foreach ($this->_params['onbehalf'] as $loc => $value) { $field = $typeId = NULL; if (strstr($loc, '-')) { list($field, $locType) = explode('-', $loc); } if (in_array($field, $addressBlocks)) { if ($locType == 'Primary') { $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); $locType = $defaultLocationType->id; } if ($field == 'country') { $value = CRM_Core_PseudoConstant::countryIsoCode($value); } elseif ($field == 'state_province') { $value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value); } $isPrimary = 1; if (isset($this->_params['onbehalf_location']['address']) && count($this->_params['onbehalf_location']['address']) > 0) { $isPrimary = 0; } $this->_params['onbehalf_location']['address'][$locType][$field] = $value; if (empty($this->_params['onbehalf_location']['address'][$locType]['is_primary'])) { $this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary; } $this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType; } elseif (in_array($field, $blocks)) { if (!$typeId || is_numeric($typeId)) { $blockName = $fieldName = $field; $locationType = 'location_type_id'; if ($locType == 'Primary') { $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); $locationValue = $defaultLocationType->id; } else { $locationValue = $locType; } $locTypeId = ''; $phoneExtField = array(); if ($field == 'url') { $blockName = 'website'; $locationType = 'website_type_id'; $locationValue = CRM_Utils_Array::value("{$loc}-website_type_id", $this->_params['onbehalf']); } elseif ($field == 'im') { $fieldName = 'name'; $locTypeId = 'provider_id'; $typeId = $this->_params['onbehalf']["{$loc}-provider_id"]; } elseif ($field == 'phone') { list($field, $locType, $typeId) = explode('-', $loc); $locTypeId = 'phone_type_id'; //check if extension field exists $extField = str_replace('phone', 'phone_ext', $loc); if (isset($this->_params['onbehalf'][$extField])) { $phoneExtField = array('phone_ext' => $this->_params['onbehalf'][$extField]); } } $isPrimary = 1; if (isset($this->_params['onbehalf_location'][$blockName]) && count($this->_params['onbehalf_location'][$blockName]) > 0) { $isPrimary = 0; } if ($locationValue) { $blockValues = array($fieldName => $value, $locationType => $locationValue, 'is_primary' => $isPrimary); if ($locTypeId) { $blockValues = array_merge($blockValues, array($locTypeId => $typeId)); } if (!empty($phoneExtField)) { $blockValues = array_merge($blockValues, $phoneExtField); } $this->_params['onbehalf_location'][$blockName][] = $blockValues; } } } elseif (strstr($loc, 'custom')) { if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) { $value = $this->_params['onbehalf']["{$loc}_id"]; } $this->_params['onbehalf_location']["{$loc}"] = $value; } else { if ($loc == 'contact_sub_type') { $this->_params['onbehalf_location'][$loc] = $value; } else { $this->_params['onbehalf_location'][$field] = $value; } } } } elseif (!empty($this->_values['is_for_organization'])) { // no on behalf of an organization, CRM-5519 // so reset loc blocks from main params. foreach (array('phone', 'email', 'address') as $blk) { if (isset($this->_params[$blk])) { unset($this->_params[$blk]); } } } // if auto renew checkbox is set, initiate a open-ended recurring membership if ((!empty($this->_params['selectMembership']) || !empty($this->_params['priceSetId'])) && !empty($this->_paymentProcessor['is_recur']) && CRM_Utils_Array::value('auto_renew', $this->_params) && empty($this->_params['is_recur']) && empty($this->_params['frequency_interval'])) { $this->_params['is_recur'] = $this->_values['is_recur'] = 1; // check if price set is not quick config if (!empty($this->_params['priceSetId']) && !$isQuickConfig) { list($this->_params['frequency_interval'], $this->_params['frequency_unit']) = CRM_Price_BAO_PriceSet::getRecurDetails($this->_params['priceSetId']); } else { // FIXME: set interval and unit based on selected membership type $this->_params['frequency_interval'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'duration_interval'); $this->_params['frequency_unit'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'duration_unit'); } } if ($this->_pcpId) { $params = $this->processPcp($this, $this->_params); $this->_params = $params; } $this->_params['invoiceID'] = $this->get('invoiceID'); //carry campaign from profile. if (array_key_exists('contribution_campaign_id', $this->_params)) { $this->_params['campaign_id'] = $this->_params['contribution_campaign_id']; } // assign contribution page id to the template so we can add css class for it $this->assign('contributionPageID', $this->_id); $this->set('params', $this->_params); }
/** * Set the post action values for the block. * * php is lame and u cannot call functions from static initializers * hence this hack * * @param int $id * * @return void */ private static function setTemplateValues($id) { switch ($id) { case self::CREATE_NEW: self::setTemplateShortcutValues(); break; case self::DASHBOARD: self::setTemplateDashboardValues(); break; case self::ADD: $defaultLocation = CRM_Core_BAO_LocationType::getDefault(); $defaultPrimaryLocationId = $defaultLocation->id; $values = array('postURL' => CRM_Utils_System::url('civicrm/contact/add', 'reset=1&ct=Individual'), 'primaryLocationType' => $defaultPrimaryLocationId); foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) { $values[$greeting . '_id'] = CRM_Contact_BAO_Contact_Utils::defaultGreeting('Individual', $greeting); } self::setProperty(self::ADD, 'templateValues', $values); break; case self::LANGSWITCH: // gives the currentPath without trailing empty lcMessages to be completed $values = array('queryString' => CRM_Utils_System::getLinksUrl('lcMessages', TRUE, FALSE, FALSE)); self::setProperty(self::LANGSWITCH, 'templateValues', $values); break; case self::FULLTEXT_SEARCH: $urlArray = array('fullTextSearchID' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', 'CRM_Contact_Form_Search_Custom_FullText', 'value', 'name')); self::setProperty(self::FULLTEXT_SEARCH, 'templateValues', $urlArray); break; case self::RECENTLY_VIEWED: $recent = CRM_Utils_Recent::get(); self::setProperty(self::RECENTLY_VIEWED, 'templateValues', array('recentlyViewed' => $recent)); break; case self::EVENT: self::setTemplateEventValues(); break; } }
/** * Function used to send notification mail to pcp owner. * * This is used by contribution and also event PCPs. * * @param object $contribution * @param object $contributionSoft * Contribution object. */ public static function pcpNotifyOwner($contribution, $contributionSoft) { $params = array('id' => $contributionSoft->pcp_id); CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo); $ownerNotifyID = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id'); if ($ownerNotifyID != CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'no_notifications', 'name') && ($ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'owner_chooses', 'name') && CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id, 'is_notify') || $ownerNotifyID == CRM_Core_OptionGroup::getValue('pcp_owner_notify', 'all_owners', 'name'))) { $pcpInfoURL = CRM_Utils_System::url('civicrm/pcp/info', "reset=1&id={$contributionSoft->pcp_id}", TRUE, NULL, FALSE, TRUE); // set email in the template here if (CRM_Core_BAO_LocationType::getBilling()) { list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id, FALSE, CRM_Core_BAO_LocationType::getBilling()); } // get primary location email if no email exist( for billing location). if (!$email) { list($donorName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contribution->contact_id); } list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contributionSoft->contact_id); $tplParams = array('page_title' => $pcpInfo['title'], 'receive_date' => $contribution->receive_date, 'total_amount' => $contributionSoft->amount, 'donors_display_name' => $donorName, 'donors_email' => $email, 'pcpInfoURL' => $pcpInfoURL, 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll, 'currency' => $contributionSoft->currency); $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'pcp_owner_notify', 'contactId' => $contributionSoft->contact_id, 'toEmail' => $ownerEmail, 'toName' => $ownerName, 'from' => "{$domainValues['0']} <{$domainValues['1']}>", 'tplParams' => $tplParams, 'PDFFilename' => 'receipt.pdf'); CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } }
/** * Format fields for dupe Contact Matching. * * @param array $params * * @param int $contactId * * @return array * associated formatted array */ public static function formatFields($params, $contactId = NULL) { if ($contactId) { // get the primary location type id and email list($name, $primaryEmail, $primaryLocationType) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactId); } else { $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); $primaryLocationType = $defaultLocationType->id; } $data = array(); $locationType = array(); $count = 1; $primaryLocation = 0; foreach ($params as $key => $value) { list($fieldName, $locTypeId, $phoneTypeId) = explode('-', $key); if ($locTypeId == 'Primary') { $locTypeId = $primaryLocationType; } if (is_numeric($locTypeId)) { if (!in_array($locTypeId, $locationType)) { $locationType[$count] = $locTypeId; $count++; } $loc = CRM_Utils_Array::key($locTypeId, $locationType); $data['location'][$loc]['location_type_id'] = $locTypeId; // if we are getting in a new primary email, dont overwrite the new one if ($locTypeId == $primaryLocationType) { if (!empty($params['email-' . $primaryLocationType])) { $data['location'][$loc]['email'][$loc]['email'] = $fields['email-' . $primaryLocationType]; } elseif (isset($primaryEmail)) { $data['location'][$loc]['email'][$loc]['email'] = $primaryEmail; } $primaryLocation++; } if ($loc == 1) { $data['location'][$loc]['is_primary'] = 1; } if ($fieldName == 'phone') { if ($phoneTypeId) { $data['location'][$loc]['phone'][$loc]['phone_type_id'] = $phoneTypeId; } else { $data['location'][$loc]['phone'][$loc]['phone_type_id'] = ''; } $data['location'][$loc]['phone'][$loc]['phone'] = $value; } elseif ($fieldName == 'email') { $data['location'][$loc]['email'][$loc]['email'] = $value; } elseif ($fieldName == 'im') { $data['location'][$loc]['im'][$loc]['name'] = $value; } else { if ($fieldName === 'state_province') { $data['location'][$loc]['address']['state_province_id'] = $value; } elseif ($fieldName === 'country') { $data['location'][$loc]['address']['country_id'] = $value; } else { $data['location'][$loc]['address'][$fieldName] = $value; } } } else { // TODO: prefix, suffix and gender translation may no longer be necessary - check inputs if ($key === 'individual_suffix') { $data['suffix_id'] = $value; } elseif ($key === 'individual_prefix') { $data['prefix_id'] = $value; } elseif ($key === 'gender') { $data['gender_id'] = $value; } elseif (substr($key, 0, 6) === 'custom') { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { //fix checkbox if ($customFields[$customFieldID]['html_type'] == 'CheckBox') { $value = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($value)); } // fix the date field if ($customFields[$customFieldID]['data_type'] == 'Date') { $date = CRM_Utils_Date::format($value); if (!$date) { $date = ''; } $value = $date; } $data['custom'][$customFieldID] = array('id' => $id, 'value' => $value, 'extends' => $customFields[$customFieldID]['extends'], 'type' => $customFields[$customFieldID]['data_type'], 'custom_field_id' => $customFieldID); } } elseif ($key == 'edit') { continue; } else { $data[$key] = $value; } } } if (!$primaryLocation) { $loc++; $data['location'][$loc]['email'][$loc]['email'] = $primaryEmail; } return $data; }
/** * Set defaults for the form. * * @return array */ public function setDefaultValues() { $defaults = array(); if (!empty($this->_openids)) { foreach ($this->_openids as $id => $value) { $defaults['openid'][$id] = $value; } } else { // get the default location type $locationType = CRM_Core_BAO_LocationType::getDefault(); $defaults['openid'][1]['location_type_id'] = $locationType->id; } return $defaults; }
/** * Set variables up before form is built. */ public function preProcess() { $config = CRM_Core_Config::singleton(); parent::preProcess(); // lineItem isn't set until Register postProcess $this->_lineItem = $this->get('lineItem'); $this->_paymentProcessor = $this->get('paymentProcessor'); $this->_params = $this->controller->exportValues('Main'); $this->_params['ip_address'] = CRM_Utils_System::ipAddress(); $this->_params['amount'] = $this->get('amount'); if (isset($this->_params['amount'])) { $this->setFormAmountFields($this->_params['priceSetId']); } $this->_params['tax_amount'] = $this->get('tax_amount'); $this->_useForMember = $this->get('useForMember'); if (isset($this->_params['credit_card_exp_date'])) { $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params); $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params); } $this->_params['currencyID'] = $config->defaultCurrency; if (!empty($this->_membershipBlock)) { $this->_params['selectMembership'] = $this->get('selectMembership'); } if (!empty($this->_paymentProcessor) && $this->_paymentProcessor['object']->supports('preApproval')) { $preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters')); $this->_params = array_merge($this->_params, $preApprovalParams); } // We may have fetched some billing details from the getPreApprovalDetails function so we // want to ensure we set this after that function has been called. CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $this->_params, FALSE); if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) { $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]); } if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) { $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]); } $this->_params['is_pay_later'] = $this->get('is_pay_later'); $this->assign('is_pay_later', $this->_params['is_pay_later']); if ($this->_params['is_pay_later']) { $this->assign('pay_later_receipt', $this->_values['pay_later_receipt']); } // if onbehalf-of-organization if (!empty($this->_values['onbehalf_profile_id']) && !empty($this->_params['onbehalf']['organization_name'])) { // CRM-15182 $this->_params['organization_id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_params['onbehalf']['organization_name'], 'id', 'display_name'); $this->_params['organization_name'] = $this->_params['onbehalf']['organization_name']; $addressBlocks = array('street_address', 'city', 'state_province', 'postal_code', 'country', 'supplemental_address_1', 'supplemental_address_2', 'supplemental_address_3', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'address_name'); $blocks = array('email', 'phone', 'im', 'url', 'openid'); foreach ($this->_params['onbehalf'] as $loc => $value) { $field = $typeId = NULL; if (strstr($loc, '-')) { list($field, $locType) = explode('-', $loc); } if (in_array($field, $addressBlocks)) { if ($locType == 'Primary') { $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); $locType = $defaultLocationType->id; } if ($field == 'country') { $value = CRM_Core_PseudoConstant::countryIsoCode($value); } elseif ($field == 'state_province') { $value = CRM_Core_PseudoConstant::stateProvinceAbbreviation($value); } $isPrimary = 1; if (isset($this->_params['onbehalf_location']['address']) && count($this->_params['onbehalf_location']['address']) > 0) { $isPrimary = 0; } $this->_params['onbehalf_location']['address'][$locType][$field] = $value; if (empty($this->_params['onbehalf_location']['address'][$locType]['is_primary'])) { $this->_params['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary; } $this->_params['onbehalf_location']['address'][$locType]['location_type_id'] = $locType; } elseif (in_array($field, $blocks)) { if (!$typeId || is_numeric($typeId)) { $blockName = $fieldName = $field; $locationType = 'location_type_id'; if ($locType == 'Primary') { $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); $locationValue = $defaultLocationType->id; } else { $locationValue = $locType; } $locTypeId = ''; $phoneExtField = array(); if ($field == 'url') { $blockName = 'website'; $locationType = 'website_type_id'; list($field, $locationValue) = explode('-', $loc); } elseif ($field == 'im') { $fieldName = 'name'; $locTypeId = 'provider_id'; $typeId = $this->_params['onbehalf']["{$loc}-provider_id"]; } elseif ($field == 'phone') { list($field, $locType, $typeId) = explode('-', $loc); $locTypeId = 'phone_type_id'; //check if extension field exists $extField = str_replace('phone', 'phone_ext', $loc); if (isset($this->_params['onbehalf'][$extField])) { $phoneExtField = array('phone_ext' => $this->_params['onbehalf'][$extField]); } } $isPrimary = 1; if (isset($this->_params['onbehalf_location'][$blockName]) && count($this->_params['onbehalf_location'][$blockName]) > 0) { $isPrimary = 0; } if ($locationValue) { $blockValues = array($fieldName => $value, $locationType => $locationValue, 'is_primary' => $isPrimary); if ($locTypeId) { $blockValues = array_merge($blockValues, array($locTypeId => $typeId)); } if (!empty($phoneExtField)) { $blockValues = array_merge($blockValues, $phoneExtField); } $this->_params['onbehalf_location'][$blockName][] = $blockValues; } } } elseif (strstr($loc, 'custom')) { if ($value && isset($this->_params['onbehalf']["{$loc}_id"])) { $value = $this->_params['onbehalf']["{$loc}_id"]; } $this->_params['onbehalf_location']["{$loc}"] = $value; } else { if ($loc == 'contact_sub_type') { $this->_params['onbehalf_location'][$loc] = $value; } else { $this->_params['onbehalf_location'][$field] = $value; } } } } elseif (!empty($this->_values['is_for_organization'])) { // no on behalf of an organization, CRM-5519 // so reset loc blocks from main params. foreach (array('phone', 'email', 'address') as $blk) { if (isset($this->_params[$blk])) { unset($this->_params[$blk]); } } } $this->setRecurringMembershipParams(); if ($this->_pcpId) { $params = $this->processPcp($this, $this->_params); $this->_params = $params; } $this->_params['invoiceID'] = $this->get('invoiceID'); //carry campaign from profile. if (array_key_exists('contribution_campaign_id', $this->_params)) { $this->_params['campaign_id'] = $this->_params['contribution_campaign_id']; } // assign contribution page id to the template so we can add css class for it $this->assign('contributionPageID', $this->_id); $this->set('params', $this->_params); }
/** * Do the set default related to location type id, * primary location, default country */ public function blockSetDefaults(&$defaults) { $locationTypeKeys = array_filter(array_keys(CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id')), 'is_int'); sort($locationTypeKeys); // get the default location type $locationType = CRM_Core_BAO_LocationType::getDefault(); // unset primary location type $primaryLocationTypeIdKey = CRM_Utils_Array::key($locationType->id, $locationTypeKeys); unset($locationTypeKeys[$primaryLocationTypeIdKey]); // reset the array sequence $locationTypeKeys = array_values($locationTypeKeys); // get default phone and im provider id. $defPhoneTypeId = key(CRM_Core_OptionGroup::values('phone_type', FALSE, FALSE, FALSE, ' AND is_default = 1')); $defIMProviderId = key(CRM_Core_OptionGroup::values('instant_messenger_service', FALSE, FALSE, FALSE, ' AND is_default = 1')); $defWebsiteTypeId = key(CRM_Core_OptionGroup::values('website_type', FALSE, FALSE, FALSE, ' AND is_default = 1')); $allBlocks = $this->_blocks; if (array_key_exists('Address', $this->_editOptions)) { $allBlocks['Address'] = $this->_editOptions['Address']; } $config = CRM_Core_Config::singleton(); foreach ($allBlocks as $blockName => $label) { $name = strtolower($blockName); $hasPrimary = $updateMode = FALSE; // user is in update mode. if (array_key_exists($name, $defaults) && !CRM_Utils_System::isNull($defaults[$name])) { $updateMode = TRUE; } for ($instance = 1; $instance <= $this->get($blockName . '_Block_Count'); $instance++) { // make we require one primary block, CRM-5505 if ($updateMode) { if (!$hasPrimary) { $hasPrimary = CRM_Utils_Array::value('is_primary', CRM_Utils_Array::value($instance, $defaults[$name])); } continue; } //set location to primary for first one. if ($instance == 1) { $hasPrimary = TRUE; $defaults[$name][$instance]['is_primary'] = TRUE; $defaults[$name][$instance]['location_type_id'] = $locationType->id; } else { $locTypeId = isset($locationTypeKeys[$instance - 1]) ? $locationTypeKeys[$instance - 1] : $locationType->id; $defaults[$name][$instance]['location_type_id'] = $locTypeId; } //set default country if ($name == 'address' && $config->defaultContactCountry) { $defaults[$name][$instance]['country_id'] = $config->defaultContactCountry; } //set default state/province if ($name == 'address' && $config->defaultContactStateProvince) { $defaults[$name][$instance]['state_province_id'] = $config->defaultContactStateProvince; } //set default phone type. if ($name == 'phone' && $defPhoneTypeId) { $defaults[$name][$instance]['phone_type_id'] = $defPhoneTypeId; } //set default website type. if ($name == 'website' && $defWebsiteTypeId) { $defaults[$name][$instance]['website_type_id'] = $defWebsiteTypeId; } //set default im provider. if ($name == 'im' && $defIMProviderId) { $defaults[$name][$instance]['provider_id'] = $defIMProviderId; } } if (!$hasPrimary) { $defaults[$name][1]['is_primary'] = TRUE; } } }
/** * Add fields to $profileAddressFields as appropriate. * profileAddressFields is assigned to the template to tell it * what fields are in the profile address * that potentially should be copied to the Billing fields * we want to give precedence to * 1) Billing & * 2) then Primary designated as 'Primary * 3) location_type is primary * 4) if none of these apply then it just uses the first one * * as this will be used to * transfer profile address data to billing fields * http://issues.civicrm.org/jira/browse/CRM-5869 * * @param string $key * Field key - e.g. street_address-Primary, first_name. * @param array $profileAddressFields * Array of profile fields that relate to address fields. * @param array $profileFilter * Filter to apply to profile fields - expected usage is to only fill based on. * the bottom profile per CRM-13726 * * @return bool * Can the address block be hidden safe in the knowledge all fields are elsewhere collected (see CRM-15118) */ public static function assignAddressField($key, &$profileAddressFields, $profileFilter) { $billing_id = CRM_Core_BAO_LocationType::getBilling(); list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2); $profileFields = civicrm_api3('uf_field', 'get', array_merge($profileFilter, array('is_active' => 1, 'return' => 'field_name, is_required', 'options' => array('limit' => 0)))); //check for valid fields ( fields that are present in billing block ) $validBillingFields = array('first_name', 'middle_name', 'last_name', 'street_address', 'supplemental_address_1', 'city', 'state_province', 'postal_code', 'country'); $requiredBillingFields = array_diff($validBillingFields, array('middle_name', 'supplemental_address_1')); $validProfileFields = array(); $requiredProfileFields = array(); foreach ($profileFields['values'] as $field) { if (in_array($field['field_name'], $validBillingFields)) { $validProfileFields[] = $field['field_name']; } if ($field['is_required']) { $requiredProfileFields[] = $field['field_name']; } } if (!in_array($prefixName, $validProfileFields)) { return FALSE; } if (!empty($index) && (!CRM_Utils_array::value($prefixName, $profileAddressFields) || $index == $billing_id || $index == 'Primary' && $profileAddressFields[$prefixName] != $billing_id || $index == CRM_Core_BAO_LocationType::getDefault()->id && $profileAddressFields[$prefixName] != $billing_id && $profileAddressFields[$prefixName] != 'Primary')) { $profileAddressFields[$prefixName] = $index; } $potentiallyMissingRequiredFields = array_diff($requiredBillingFields, $requiredProfileFields); CRM_Core_Resources::singleton()->addSetting(array('billing' => array('billingProfileIsHideable' => empty($potentiallyMissingRequiredFields)))); }