/** * 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; }
/** * 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'); }
/** * 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'); }
/** * 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)))); }
/** * 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; }
/** * Function to actually build the form * * @return void * @access public */ function buildQuickForm() { if ($this->_action & CRM_CORE_ACTION_DELETE) { $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete Profile Field'), 'spacing' => ' ', 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel')))); return; } if (isset($this->_id)) { $params = array('id' => $this->_id); CRM_Core_BAO_UFField::retrieve($params, $defaults); $defaults['field_name'] = array($defaults['field_type'], $defaults['field_name'], $defaults['location_type_id'], $defaults['phone_type']); $this->_gid = $defaults['uf_group_id']; } else { $defaults['is_active'] = 1; } if ($this->_action & CRM_CORE_ACTION_ADD) { $uf =& new CRM_Core_DAO(); $sql = "SELECT weight FROM civicrm_uf_field WHERE uf_group_id = " . $this->_gid . " ORDER BY weight DESC LIMIT 0, 1"; $uf->query($sql); while ($uf->fetch()) { $defaults['weight'] = $uf->weight + 1; } if (empty($defaults['weight'])) { $defaults['weight'] = 1; } } // lets trim all the whitespace $this->applyFilter('__ALL__', 'trim'); //hidden field to catch the group id in profile $this->add('hidden', 'group_id', $this->_gid); //hidden field to catch the field id in profile $this->add('hidden', 'field_id', $this->_id); $fields = array(); $fields['Individual'] =& CRM_Contact_BAO_Contact::exportableFields('Individual'); $fields['Household'] =& CRM_Contact_BAO_Contact::exportableFields('Household'); $fields['Organization'] =& CRM_Contact_BAO_Contact::exportableFields('Organization'); $contribFields =& CRM_Contribute_BAO_Contribution::getContributionFields(); if (!empty($contribFields)) { $fields['Contribution'] =& $contribFields; } foreach ($fields as $key => $value) { foreach ($value as $key1 => $value1) { $this->_mapperFields[$key][$key1] = $value1['title']; $hasLocationTypes[$key][$key1] = $value1['hasLocationType']; } } require_once 'CRM/Core/BAO/LocationType.php'; $this->_location_types =& CRM_Core_PseudoConstant::locationType(); $defaultLocationType =& CRM_Core_BAO_LocationType::getDefault(); /* FIXME: dirty hack to make the default option show up first. This * avoids a mozilla browser bug with defaults on dynamically constructed * selector widgets. */ if ($defaultLocationType) { $defaultLocation = $this->_location_types[$defaultLocationType->id]; unset($this->_location_types[$defaultLocationType->id]); $this->_location_types = array($defaultLocationType->id => $defaultLocation) + $this->_location_types; } $sel1 = array('' => '-select-') + CRM_Core_SelectValues::contactType(); if (!empty($contribFields)) { $sel1['Contribution'] = 'Contributions'; } foreach ($sel1 as $key => $sel) { if ($key) { $sel2[$key] = $this->_mapperFields[$key]; } } $sel3[''] = null; $phoneTypes = CRM_Core_SelectValues::phoneType(); foreach ($sel1 as $k => $sel) { if ($k) { foreach ($this->_location_types as $key => $value) { $sel4[$k]['phone'][$key] =& $phoneTypes; } } } foreach ($sel1 as $k => $sel) { if ($k) { foreach ($this->_mapperFields[$k] as $key => $value) { if ($hasLocationTypes[$k][$key]) { $sel3[$k][$key] = $this->_location_types; } else { $sel3[$key] = null; } } } } $this->_defaults = array(); $js = "<script type='text/javascript'>\n"; $formName = "document.{$this->_name}"; $sel =& $this->addElement('hierselect', "field_name", ts('Field Name'), 'onclick="showLabel();"'); $formValues = array(); //$formValues = $this->controller->exportValues( $this->_name ); $formValues = $_POST; // using $_POST since export values don't give values on first submit if (empty($formValues)) { for ($k = 1; $k < 4; $k++) { if (!$defaults['field_name'][$k]) { $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n"; } } } else { foreach ($formValues['field_name'] as $value) { for ($k = 1; $k < 4; $k++) { if (!$formValues['field_name'][$k]) { $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n"; } } } } $sel->setOptions(array($sel1, $sel2, $sel3, $sel4)); $js .= "</script>\n"; $this->assign('initHideBoxes', $js); $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::ufVisibility(), true); // should the field appear in selector? $this->add('checkbox', 'in_selector', ts('In Selector?')); // weight $this->add('text', 'weight', ts('Weight'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'weight'), true); $this->addRule('weight', ts(' is a numeric field'), 'numeric'); $this->add('textarea', 'help_post', ts('Field Help'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'help_post')); // listings title $this->add('text', 'listings_title', ts('Listings Title'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'listings_title')); $this->addRule('listings_title', ts('Please enter a valid title for this field when displayed in user listings.'), 'title'); $this->add('checkbox', 'is_required', ts('Required?')); $this->add('checkbox', 'is_active', ts('Active?')); $this->add('checkbox', 'is_searchable', ts('Searchable?')); $this->add('checkbox', 'is_view', ts('View Only?')); // $this->add( 'checkbox', 'is_registration', ts( 'Display in Registration Form?' ) ); //$this->add( 'checkbox', 'is_match' , ts( 'Key to Match Contacts?' ) ); $this->add('text', 'label', ts('Field Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'label')); // add buttons $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel')))); $this->addFormRule(array('CRM_UF_Form_Field', 'formRule')); // if view mode pls freeze it with the done button. if ($this->_action & CRM_CORE_ACTION_VIEW) { $this->freeze(); $this->addElement('button', 'done', ts('Done'), array('onClick' => "location.href='civicrm/admin/uf/group/field?reset=1&action=browse&gid=" . $this->_gid . "'")); } $this->setDefaults($defaults); }
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')))); }
/** * Process the form when submitted * * @return void * @access public */ public function postProcess() { require_once 'CRM/Core/BAO/Domain.php'; $params = array(); $params = $this->exportValues(); $params['entity_id'] = $this->_id; $params['entity_table'] = CRM_Core_BAO_Domain::getTableName(); $domain = CRM_Core_BAO_Domain::edit($params, $this->_id); require_once 'CRM/Core/BAO/LocationType.php'; $defaultLocationType =& CRM_Core_BAO_LocationType::getDefault(); $location = array(); $params['address'][1]['location_type_id'] = $defaultLocationType->id; $params['phone'][1]['location_type_id'] = $defaultLocationType->id; $params['email'][1]['location_type_id'] = $defaultLocationType->id; $location = CRM_Core_BAO_Location::create($params, true, 'domain'); $params['loc_block_id'] = $location['id']; require_once 'CRM/Core/BAO/Domain.php'; CRM_Core_BAO_Domain::edit($params, $this->_id); //set domain from email address, CRM-3552 $emailName = '"' . $params['email_name'] . '"<' . $params['email_address'] . '>'; $emailParams = array('label' => $emailName, 'description' => $params['description'], 'is_active' => 1, 'is_default' => 1); $groupParams = array('name' => 'from_email_address'); //get the option value wt. if ($this->_fromEmailId) { $action = $this->_action; $emailParams['weight'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $this->_fromEmailId, 'weight'); } else { //add from email address. $action = CRM_Core_Action::ADD; require_once 'CRM/Utils/Weight.php'; $grpId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'from_email_address', 'id', 'name'); $fieldValues = array('option_group_id' => $grpId); $emailParams['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_OptionValue', $fieldValues); } require_once 'CRM/Core/OptionValue.php'; //reset default within domain. $emailParams['reset_default_for'] = array('domain_id' => CRM_Core_Config::domainID()); CRM_Core_OptionValue::addOptionValue($emailParams, $groupParams, $action, $this->_fromEmailId); CRM_Core_Session::setStatus(ts('Domain information for \'%1\' has been saved.', array(1 => $domain->name))); $session =& CRM_Core_Session::singleton(); $session->replaceUserContext(CRM_Utils_System::url('civicrm/admin', 'reset=1')); }
/** * 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); }
/** * @todo Write sth * @todo Serious FIXMES in the code! File issues. */ function civicrm_contact_update(&$params, $create_new = FALSE) { _civicrm_initialize(); try { civicrm_api_check_permission(__FUNCTION__, $params, TRUE); } catch (Exception $e) { return civicrm_create_error($e->getMessage()); } require_once 'CRM/Utils/Array.php'; $entityId = CRM_Utils_Array::value('contact_id', $params, NULL); if (!CRM_Utils_Array::value('contact_type', $params) && $entityId) { $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($entityId); } $dupeCheck = CRM_Utils_Array::value('dupe_check', $params, FALSE); $values = civicrm_contact_check_params($params, $dupeCheck); if ($values) { return $values; } if ($create_new) { // Make sure nothing is screwed up before we create a new contact if (!empty($entityId)) { return civicrm_create_error('Cannot create new contact when contact_id is present'); } if (empty($params['contact_type'])) { return civicrm_create_error('Contact Type not specified'); } // 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 ($homeUrl = 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' => $homeUrl)); } // FIXME: Some legacy support cruft, should get rid of this in 3.1 $change = array('individual_prefix' => 'prefix', 'prefix' => 'prefix_id', 'individual_suffix' => 'suffix', 'suffix' => 'suffix_id', 'gender' => 'gender_id'); foreach ($change as $field => $changeAs) { if (array_key_exists($field, $params)) { $params[$changeAs] = $params[$field]; unset($params[$field]); } } // End legacy support cruft 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_greeting_format_params($params); if (civicrm_error($error)) { return $error; } $values = array(); if (!($csType = CRM_Utils_Array::value('contact_sub_type', $params)) && $entityId) { require_once 'CRM/Contact/BAO/Contact.php'; $csType = CRM_Contact_BAO_Contact::getContactSubType($entityId); } $customValue = civicrm_contact_check_custom_params($params, $csType); if ($customValue) { return $customValue; } _civicrm_custom_format_params($params, $values, $params['contact_type'], $entityId); $params = array_merge($params, $values); $contact =& _civicrm_contact_update($params, $entityId); if (is_a($contact, 'CRM_Core_Error')) { return civicrm_create_error($contact->_errors[0]['message']); } else { $values = array(); $values['contact_id'] = $contact->id; $values['is_error'] = 0; } return $values; }
/** * Function to actually build the form * * @return void * @access public */ public function buildQuickForm() { if ($this->_action & CRM_Core_Action::DELETE) { $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete Profile Field'), 'spacing' => ' ', 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel')))); return; } if (isset($this->_id)) { $params = array('id' => $this->_id); CRM_Core_BAO_UFField::retrieve($params, $defaults); // set it to null if so (avoids crappy E_NOTICE errors below $defaults['location_type_id'] = CRM_Utils_Array::value('location_type_id', $defaults); $specialFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'county', 'phone', 'email', 'im', 'address_name'); if (!$defaults['location_type_id'] && in_array($defaults['field_name'], $specialFields)) { $defaults['location_type_id'] = 0; } $defaults['field_name'] = array($defaults['field_type'], $defaults['field_name'], $defaults['location_type_id'], CRM_Utils_Array::value('phone_type_id', $defaults)); $this->_gid = $defaults['uf_group_id']; } else { $defaults['is_active'] = 1; } if ($this->_action & CRM_Core_Action::ADD) { $fieldValues = array('uf_group_id' => $this->_gid); $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_UFField', $fieldValues); } // lets trim all the whitespace $this->applyFilter('__ALL__', 'trim'); //hidden field to catch the group id in profile $this->add('hidden', 'group_id', $this->_gid); //hidden field to catch the field id in profile $this->add('hidden', 'field_id', $this->_id); $fields = array(); $fields['Individual'] =& CRM_Contact_BAO_Contact::importableFields('Individual', false, false, true); $fields['Household'] =& CRM_Contact_BAO_Contact::importableFields('Household', false, false, true); $fields['Organization'] =& CRM_Contact_BAO_Contact::importableFields('Organization', false, false, true); // add current employer for individuals $fields['Individual']['current_employer'] = array('name' => 'organization_name', 'title' => ts('Current Employer')); // unset unwanted fields $unsetFieldArray = array('note', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom', 'id'); foreach ($unsetFieldArray as $value) { unset($fields['Individual'][$value]); unset($fields['Household'][$value]); unset($fields['Organization'][$value]); } require_once 'CRM/Core/BAO/Preferences.php'; $addressOptions = CRM_Core_BAO_Preferences::valueOptions('address_options', true, null, true); if (!$addressOptions['county']) { unset($fields['Individual']['county']); unset($fields['Household']['county']); unset($fields['Organization']['county']); } //build the common contact fields array CRM-3037. foreach ($fields['Individual'] as $key => $value) { if (CRM_Utils_Array::value($key, $fields['Household']) && CRM_Utils_Array::value($key, $fields['Organization'])) { $fields['Contact'][$key] = $value; //as we move common fields to contacts. There fore these fields //are unset from resoective array's. unset($fields['Individual'][$key]); unset($fields['Household'][$key]); unset($fields['Organization'][$key]); } } // add current employer for individuals $fields['Contact']['id'] = array('name' => 'id', 'title' => ts('Internal Contact ID')); unset($fields['Contact']['contact_type']); // since we need a hierarchical list to display contact types & subtypes, // this is what we going to display in first selector $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(false, false); unset($contactTypes['']); // include Subtypes For Profile $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo(); foreach ($subTypes as $name => $val) { //custom fields for sub type $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($name); if (array_key_exists($val['parent'], $fields)) { $fields[$name] = $fields[$val['parent']] + $subTypeFields; } else { $fields[$name] = $subTypeFields; } } unset($subTypes); if (CRM_Core_Permission::access('Quest')) { require_once 'CRM/Quest/BAO/Student.php'; $fields['Student'] =& CRM_Quest_BAO_Student::exportableFields(); } if (CRM_Core_Permission::access('CiviContribute')) { $contribFields =& CRM_Contribute_BAO_Contribution::getContributionFields(); if (!empty($contribFields)) { unset($contribFields['is_test']); unset($contribFields['is_pay_later']); unset($contribFields['contribution_id']); $fields['Contribution'] =& $contribFields; } } if (CRM_Core_Permission::access('CiviEvent')) { require_once 'CRM/Event/BAO/Query.php'; $participantFields =& CRM_Event_BAO_Query::getParticipantFields(true); if (!empty($participantFields)) { unset($participantFields['external_identifier']); unset($participantFields['event_id']); unset($participantFields['participant_contact_id']); unset($participantFields['participant_is_test']); unset($participantFields['participant_fee_level']); unset($participantFields['participant_id']); unset($participantFields['participant_is_pay_later']); $fields['Participant'] =& $participantFields; } } if (CRM_Core_Permission::access('CiviMember')) { require_once 'CRM/Member/BAO/Membership.php'; $membershipFields =& CRM_Member_BAO_Membership::getMembershipFields(); unset($membershipFields['membership_id']); unset($membershipFields['join_date']); unset($membershipFields['membership_start_date']); unset($membershipFields['membership_type_id']); unset($membershipFields['membership_end_date']); unset($membershipFields['member_is_test']); unset($membershipFields['is_override']); unset($membershipFields['status_id']); unset($membershipFields['member_is_pay_later']); $fields['Membership'] =& $membershipFields; } $noSearchable = array(); foreach ($fields as $key => $value) { foreach ($value as $key1 => $value1) { //CRM-2676, replacing the conflict for same custom field name from different custom group. require_once 'CRM/Core/BAO/CustomField.php'; if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key1)) { $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id'); $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title'); $this->_mapperFields[$key][$key1] = $value1['title'] . ' :: ' . $customGroupName; } else { $this->_mapperFields[$key][$key1] = $value1['title']; } $hasLocationTypes[$key][$key1] = CRM_Utils_Array::value('hasLocationType', $value1); // hide the 'is searchable' field for 'File' custom data if (isset($value1['data_type']) && isset($value1['html_type']) && ($value1['data_type'] == 'File' && $value1['html_type'] == 'File' || $value1['data_type'] == 'Link' && $value1['html_type'] == 'Link')) { if (!in_array($value1['title'], $noSearchable)) { $noSearchable[] = $value1['title']; } } } } $this->assign('noSearchable', $noSearchable); require_once 'CRM/Core/BAO/LocationType.php'; $this->_location_types =& CRM_Core_PseudoConstant::locationType(); $defaultLocationType =& CRM_Core_BAO_LocationType::getDefault(); /* FIXME: dirty hack to make the default option show up first. This * avoids a mozilla browser bug with defaults on dynamically constructed * selector widgets. */ if ($defaultLocationType) { $defaultLocation = $this->_location_types[$defaultLocationType->id]; unset($this->_location_types[$defaultLocationType->id]); $this->_location_types = array($defaultLocationType->id => $defaultLocation) + $this->_location_types; } $this->_location_types = array('Primary') + $this->_location_types; $contactTypes = !empty($contactTypes) ? array('Contact' => 'Contacts') + $contactTypes : array(); $sel1 = array('' => '- select -') + $contactTypes; if (CRM_Core_Permission::access('Quest')) { $sel1['Student'] = 'Students'; } if (CRM_Core_Permission::access('CiviEvent')) { $sel1['Participant'] = 'Participants'; } if (!empty($contribFields)) { $sel1['Contribution'] = 'Contributions'; } if (!empty($membershipFields)) { $sel1['Membership'] = 'Membership'; } foreach ($sel1 as $key => $sel) { if ($key) { $sel2[$key] = $this->_mapperFields[$key]; } } $sel3[''] = null; $phoneTypes = CRM_Core_PseudoConstant::phoneType(); ksort($phoneTypes); foreach ($sel1 as $k => $sel) { if ($k) { foreach ($this->_location_types as $key => $value) { $sel4[$k]['phone'][$key] =& $phoneTypes; } } } foreach ($sel1 as $k => $sel) { if ($k) { if (is_array($this->_mapperFields[$k])) { foreach ($this->_mapperFields[$k] as $key => $value) { if ($hasLocationTypes[$k][$key]) { $sel3[$k][$key] = $this->_location_types; } else { $sel3[$key] = null; } } } } } $this->_defaults = array(); $js = "<script type='text/javascript'>\n"; $formName = "document.{$this->_name}"; $alreadyMixProfile = false; if (CRM_Core_BAO_UFField::checkProfileType($this->_gid)) { $alreadyMixProfile = true; } $this->assign('alreadyMixProfile', $alreadyMixProfile); $attributes = array('onclick' => "showLabel();mixProfile();", 'onblur' => 'showLabel();mixProfile();'); $sel =& $this->addElement('hierselect', "field_name", ts('Field Name'), $attributes); $formValues = array(); $formValues = $this->exportValues(); if (empty($formValues)) { for ($k = 1; $k < 4; $k++) { if (!$defaults['field_name'][$k]) { $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n"; } } } else { if (!empty($formValues['field_name'])) { foreach ($formValues['field_name'] as $value) { for ($k = 1; $k < 4; $k++) { if (!isset($formValues['field_name'][$k]) || !$formValues['field_name'][$k]) { $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n"; } else { $js .= "{$formName}['field_name[{$k}]'].style.display = '';\n"; } } } } else { for ($k = 1; $k < 4; $k++) { if (!isset($defaults['field_name'][$k])) { $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n"; } } } } foreach ($sel2 as $k => $v) { if (is_array($sel2[$k])) { asort($sel2[$k]); } } $sel->setOptions(array($sel1, $sel2, $sel3, $sel4)); $js .= "</script>\n"; $this->assign('initHideBoxes', $js); $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::ufVisibility(), true, array("onChange" => "showHideSeletorSearch(this.value);")); //CRM-4363 $js = array('onclick' => "mixProfile();"); // should the field appear in selectors (as a column)? $this->add('checkbox', 'in_selector', ts('Results Column?'), null, null, $js); $this->add('checkbox', 'is_searchable', ts('Searchable?'), null, null, $js); // weight $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'weight'), true); $this->addRule('weight', ts('is a numeric field'), 'numeric'); $this->add('textarea', 'help_post', ts('Field Help'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'help_post')); // listings title $this->add('text', 'listings_title', ts('Listings Title'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'listings_title')); $this->addRule('listings_title', ts('Please enter a valid title for this field when displayed in user listings.'), 'title'); $this->add('checkbox', 'is_required', ts('Required?')); $this->add('checkbox', 'is_active', ts('Active?')); $this->add('checkbox', 'is_view', ts('View Only?')); // $this->add( 'checkbox', 'is_registration', ts( 'Display in Registration Form?' ) ); //$this->add( 'checkbox', 'is_match' , ts( 'Key to Match Contacts?' ) ); $this->add('text', 'label', ts('Field Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'label')); $js = null; if ($this->_hasSearchableORInSelector) { $js = array('onclick' => "return verify( );"); } // add buttons $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'isDefault' => true, 'js' => $js), array('type' => 'next', 'name' => ts('Save and New'), 'subName' => 'new', 'js' => $js), array('type' => 'cancel', 'name' => ts('Cancel')))); $this->addFormRule(array('CRM_UF_Form_Field', 'formRule'), $this); // if view mode pls freeze it with the done button. if ($this->_action & CRM_Core_Action::VIEW) { $this->freeze(); $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/uf/group/field?reset=1&action=browse&gid=" . $this->_gid . "'")); } $this->setDefaults($defaults); }
/** * Send the emails. * * @param int $contactID * Contact id. * @param array $values * Associated array of fields. * @param bool $isTest * If in test mode. * @param bool $returnMessageText * Return the message text instead of sending the mail. * * @param null $fieldTypes * * @return void */ public static function sendMail($contactID, $values, $isTest = FALSE, $returnMessageText = FALSE, $fieldTypes = NULL) { $gIds = $params = array(); $email = NULL; if (isset($values['custom_pre_id'])) { $preProfileType = CRM_Core_BAO_UFField::getProfileType($values['custom_pre_id']); if ($preProfileType == 'Membership' && !empty($values['membership_id'])) { $params['custom_pre_id'] = array(array('member_id', '=', $values['membership_id'], 0, 0)); } elseif ($preProfileType == 'Contribution' && !empty($values['contribution_id'])) { $params['custom_pre_id'] = array(array('contribution_id', '=', $values['contribution_id'], 0, 0)); } $gIds['custom_pre_id'] = $values['custom_pre_id']; } if (isset($values['custom_post_id'])) { $postProfileType = CRM_Core_BAO_UFField::getProfileType($values['custom_post_id']); if ($postProfileType == 'Membership' && !empty($values['membership_id'])) { $params['custom_post_id'] = array(array('member_id', '=', $values['membership_id'], 0, 0)); } elseif ($postProfileType == 'Contribution' && !empty($values['contribution_id'])) { $params['custom_post_id'] = array(array('contribution_id', '=', $values['contribution_id'], 0, 0)); } $gIds['custom_post_id'] = $values['custom_post_id']; } if (!empty($values['is_for_organization'])) { if (!empty($values['membership_id'])) { $params['onbehalf_profile'] = array(array('member_id', '=', $values['membership_id'], 0, 0)); } elseif (!empty($values['contribution_id'])) { $params['onbehalf_profile'] = array(array('contribution_id', '=', $values['contribution_id'], 0, 0)); } } //check whether it is a test drive if ($isTest && !empty($params['custom_pre_id'])) { $params['custom_pre_id'][] = array('contribution_test', '=', 1, 0, 0); } if ($isTest && !empty($params['custom_post_id'])) { $params['custom_post_id'][] = array('contribution_test', '=', 1, 0, 0); } if (!$returnMessageText && !empty($gIds)) { //send notification email if field values are set (CRM-1941) foreach ($gIds as $key => $gId) { if ($gId) { $email = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify'); if ($email) { $val = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $contactID, CRM_Utils_Array::value($key, $params), TRUE); CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val); } } } } if (!empty($values['is_email_receipt']) || !empty($values['onbehalf_dupe_alert']) || $returnMessageText) { $template = CRM_Core_Smarty::singleton(); // get the billing location type if (!array_key_exists('related_contact', $values)) { $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate'); $billingLocationTypeId = array_search('Billing', $locationTypes); } else { // presence of related contact implies onbehalf of org case, // where location type is set to default. $locType = CRM_Core_BAO_LocationType::getDefault(); $billingLocationTypeId = $locType->id; } if (!array_key_exists('related_contact', $values)) { list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID, FALSE, $billingLocationTypeId); } // get primary location email if no email exist( for billing location). if (!$email) { list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID); } if (empty($displayName)) { list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID); } //for display profile need to get individual contact id, //hence get it from related_contact if on behalf of org true CRM-3767 //CRM-5001 Contribution/Membership:: On Behalf of Organization, //If profile GROUP contain the Individual type then consider the //profile is of Individual ( including the custom data of membership/contribution ) //IF Individual type not present in profile then it is consider as Organization data. $userID = $contactID; if ($preID = CRM_Utils_Array::value('custom_pre_id', $values)) { if (!empty($values['related_contact'])) { $preProfileTypes = CRM_Core_BAO_UFGroup::profileGroups($preID); //@todo - following line should not refer to undefined $postProfileTypes? figure out way to test if (in_array('Individual', $preProfileTypes) || in_array('Contact', $postProfileTypes)) { //Take Individual contact ID $userID = CRM_Utils_Array::value('related_contact', $values); } } self::buildCustomDisplay($preID, 'customPre', $userID, $template, $params['custom_pre_id']); } $userID = $contactID; if ($postID = CRM_Utils_Array::value('custom_post_id', $values)) { if (!empty($values['related_contact'])) { $postProfileTypes = CRM_Core_BAO_UFGroup::profileGroups($postID); if (in_array('Individual', $postProfileTypes) || in_array('Contact', $postProfileTypes)) { //Take Individual contact ID $userID = CRM_Utils_Array::value('related_contact', $values); } } self::buildCustomDisplay($postID, 'customPost', $userID, $template, $params['custom_post_id']); } if (isset($values['honor'])) { $honorValues = $values['honor']; CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($template, $honorValues['honor_profile_values'], $honorValues['honor_profile_id'], $honorValues['honor_id']); } $title = isset($values['title']) ? $values['title'] : CRM_Contribute_PseudoConstant::contributionPage($values['contribution_page_id']); // set email in the template here $tplParams = array('email' => $email, 'receiptFromEmail' => CRM_Utils_Array::value('receipt_from_email', $values), 'contactID' => $contactID, 'displayName' => $displayName, 'contributionID' => CRM_Utils_Array::value('contribution_id', $values), 'contributionOtherID' => CRM_Utils_Array::value('contribution_other_id', $values), 'lineItem' => CRM_Utils_Array::value('lineItem', $values), 'priceSetID' => CRM_Utils_Array::value('priceSetID', $values), 'title' => $title, 'isShare' => CRM_Utils_Array::value('is_share', $values), 'thankyou_title' => CRM_Utils_Array::value('thankyou_title', $values)); if ($contributionTypeId = CRM_Utils_Array::value('financial_type_id', $values)) { $tplParams['contributionTypeId'] = $contributionTypeId; $tplParams['contributionTypeName'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionTypeId); } if ($contributionPageId = CRM_Utils_Array::value('id', $values)) { $tplParams['contributionPageId'] = $contributionPageId; } // address required during receipt processing (pdf and email receipt) if ($displayAddress = CRM_Utils_Array::value('address', $values)) { $tplParams['address'] = $displayAddress; } // CRM-6976 $originalCCReceipt = CRM_Utils_Array::value('cc_receipt', $values); // cc to related contacts of contributor OR the one who // signs up. Is used for cases like - on behalf of // contribution / signup ..etc if (array_key_exists('related_contact', $values)) { list($ccDisplayName, $ccEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($values['related_contact']); $ccMailId = "{$ccDisplayName} <{$ccEmail}>"; //@todo - this is the only place in this function where $values is altered - but I can't find any evidence it is used $values['cc_receipt'] = !empty($values['cc_receipt']) ? $values['cc_receipt'] . ',' . $ccMailId : $ccMailId; // reset primary-email in the template $tplParams['email'] = $ccEmail; $tplParams['onBehalfName'] = $displayName; $tplParams['onBehalfEmail'] = $email; $ufJoinParams = array('module' => 'onBehalf', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $values['id']); $OnBehalfProfile = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); $profileId = $OnBehalfProfile[0]; $userID = $contactID; self::buildCustomDisplay($profileId, 'onBehalfProfile', $userID, $template, $params['onbehalf_profile'], $fieldTypes); } // use either the contribution or membership receipt, based on whether it’s a membership-related contrib or not $sendTemplateParams = array('groupName' => !empty($values['isMembership']) ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution', 'valueName' => !empty($values['isMembership']) ? 'membership_online_receipt' : 'contribution_online_receipt', 'contactId' => $contactID, 'tplParams' => $tplParams, 'isTest' => $isTest, 'PDFFilename' => 'receipt.pdf'); if ($returnMessageText) { list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); return array('subject' => $subject, 'body' => $message, 'to' => $displayName, 'html' => $html); } if ($values['is_email_receipt']) { $sendTemplateParams['from'] = CRM_Utils_Array::value('receipt_from_name', $values) . ' <' . $values['receipt_from_email'] . '>'; $sendTemplateParams['toName'] = $displayName; $sendTemplateParams['toEmail'] = $email; $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values); $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values); //send email with pdf invoice $template = CRM_Core_Smarty::singleton(); $taxAmt = $template->get_template_vars('dataArray'); $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue); if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) { $sendTemplateParams['isEmailPdf'] = TRUE; $sendTemplateParams['contributionId'] = $values['contribution_id']; } list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } // send duplicate alert, if dupe match found during on-behalf-of processing. if (!empty($values['onbehalf_dupe_alert'])) { $sendTemplateParams['groupName'] = 'msg_tpl_workflow_contribution'; $sendTemplateParams['valueName'] = 'contribution_dupalert'; $sendTemplateParams['from'] = ts('Automatically Generated') . " <{$values['receipt_from_email']}>"; $sendTemplateParams['toName'] = CRM_Utils_Array::value('receipt_from_name', $values); $sendTemplateParams['toEmail'] = CRM_Utils_Array::value('receipt_from_email', $values); $sendTemplateParams['tplParams']['onBehalfID'] = $contactID; $sendTemplateParams['tplParams']['receiptMessage'] = $message; // fix cc and reset back to original, CRM-6976 $sendTemplateParams['cc'] = $originalCCReceipt; CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } } }
/** * 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')); } }
/** * 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; }
/** * 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; }
/** * Function to process the form * * @access public * * @return None */ public function postProcess() { $params = $this->controller->exportValues($this->getName()); if (!$this->_contactID && isset($params['cms_create_account'])) { foreach ($params as $key => $value) { if (substr($key, 0, 5) == 'email' && !empty($value)) { list($fieldName, $locTypeId) = CRM_Utils_System::explode('-', $key, 2); $isPrimary = 0; if ($locTypeId == 'Primary') { $locTypeDefault = CRM_Core_BAO_LocationType::getDefault(); $locTypeId = NULL; if ($locTypeDefault) { $locTypeId = $locTypeDefault->id; } $isPrimary = 1; } $params['email'] = array(); $params['email'][1]['email'] = $value; $params['email'][1]['location_type_id'] = $locTypeId; $params['email'][1]['is_primary'] = $isPrimary; } } } $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual'); $dedupeParams['check_permission'] = FALSE; $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', 'Unsupervised'); if ($ids) { $this->_contactID = $ids['0']; } $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $this->_fields, $this->_contactID); $this->set('contactID', $contactID); if (!empty($params['email'])) { $params['email'] = $params['email'][1]['email']; } CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email'); }
/** * 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; }
/** * check duplicate contacts based on de-deupe parameters */ function _civicrm_api3_deprecated_check_contact_dedupe($params) { static $cIndieFields = NULL; static $defaultLocationId = NULL; $contactType = $params['contact_type']; if ($cIndieFields == NULL) { require_once 'CRM/Contact/BAO/Contact.php'; $cTempIndieFields = CRM_Contact_BAO_Contact::importableFields($contactType); $cIndieFields = $cTempIndieFields; require_once "CRM/Core/BAO/LocationType.php"; $defaultLocation = CRM_Core_BAO_LocationType::getDefault(); // set the value to default location id else set to 1 if (!($defaultLocationId = (int) $defaultLocation->id)) { $defaultLocationId = 1; } } require_once 'CRM/Contact/BAO/Query.php'; $locationFields = CRM_Contact_BAO_Query::$_locationSpecificFields; $contactFormatted = array(); foreach ($params as $key => $field) { if ($field == NULL || $field === '') { continue; } if (is_array($field)) { foreach ($field as $value) { $break = FALSE; if (is_array($value)) { foreach ($value as $name => $testForEmpty) { if ($name !== 'phone_type' && ($testForEmpty === '' || $testForEmpty == NULL)) { $break = TRUE; break; } } } else { $break = TRUE; } if (!$break) { _civicrm_api3_deprecated_add_formatted_param($value, $contactFormatted); } } continue; } $value = array($key => $field); // check if location related field, then we need to add primary location type if (in_array($key, $locationFields)) { $value['location_type_id'] = $defaultLocationId; } elseif (array_key_exists($key, $cIndieFields)) { $value['contact_type'] = $contactType; } _civicrm_api3_deprecated_add_formatted_param($value, $contactFormatted); } $contactFormatted['contact_type'] = $contactType; return _civicrm_api3_deprecated_duplicate_formatted_contact($contactFormatted); }
/** * 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); }
/** * 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 */ static function setDefaultValues(&$form) { $defaults = array(); if ($form->_context == 'caseActivity') { return $defaults; } list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime'); // set default case status, case type, encounter medium, location type and phone type defaults are set in DB $caseStatus = CRM_Core_OptionGroup::values('case_status', FALSE, FALSE, FALSE, 'AND is_default = 1'); if (count($caseStatus) == 1) { $defaults['status_id'] = key($caseStatus); } // set default case type passed in url if ($form->_caseTypeId) { $caseType = $form->_caseTypeId; } else { // set default case type if only one of it exists $caseType = CRM_Core_OptionGroup::values('case_type', FALSE, FALSE, FALSE, 'AND is_default = 1'); if (count($caseType) == 1) { $caseType = key($caseType); } } $defaults['case_type_id'] = $caseType; $medium = CRM_Core_OptionGroup::values('encounter_medium', FALSE, FALSE, FALSE, 'AND is_default = 1'); if (count($medium) == 1) { $defaults['medium_id'] = key($medium); } $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; }
/** * 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); $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); }
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); }
/** * 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; }
/** * 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'); }
/** * 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; } } }
/** * 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; } }