/** * Function to set variables up before form is built * * @return void */ function preProcess(&$form) { $form->_addBlockName = CRM_Utils_Request::retrieve('block', 'String', CRM_Core_DAO::$_nullObject); $additionalblockCount = CRM_Utils_Request::retrieve('count', 'Positive', CRM_Core_DAO::$_nullObject); $form->assign("addBlock", false); if ($form->_addBlockName && $additionalblockCount) { $form->assign("addBlock", true); $form->assign("blockName", $form->_addBlockName); $form->assign("blockId", $additionalblockCount); $form->set($form->_addBlockName . "_Block_Count", $additionalblockCount); } $className = CRM_Utils_System::getClassName($form); if (in_array($className, array('CRM_Event_Form_ManageEvent_Location', 'CRM_Contact_Form_Domain'))) { $form->_blocks = array('Address' => ts('Address'), 'Email' => ts('Email'), 'Phone' => ts('Phone')); } $form->assign('blocks', $form->_blocks); $form->assign('className', $className); // get address sequence. if (!($addressSequence = $form->get('addressSequence'))) { require_once 'CRM/Core/BAO/Address.php'; $addressSequence = CRM_Core_BAO_Address::addressSequence(); $form->set('addressSequence', $addressSequence); } $form->assign('addressSequence', $addressSequence); }
/** * Function to create various elements of location block * * @param array $params (reference ) an assoc array of name/value pairs * @param boolean $fixAddress true if you need to fix (format) address values * before inserting in db * * @param null $entity * * @return array $location * @access public * @static */ static function create(&$params, $fixAddress = TRUE, $entity = NULL) { $location = array(); if (!self::dataExists($params)) { return $location; } // create location blocks. foreach (self::$blocks as $block) { if ($block != 'address') { $location[$block] = CRM_Core_BAO_Block::create($block, $params, $entity); } else { $location[$block] = CRM_Core_BAO_Address::create($params, $fixAddress, $entity); } } if ($entity) { // this is a special case for adding values in location block table $entityElements = array('entity_table' => $params['entity_table'], 'entity_id' => $params['entity_id']); $location['id'] = self::createLocBlock($location, $entityElements); } else { // when we come from a form which displays all the location elements (like the edit form or the inline block // elements, we can skip the below check. The below check adds quite a feq queries to an already overloaded // form if (!CRM_Utils_Array::value('updateBlankLocInfo', $params, FALSE)) { // make sure contact should have only one primary block, CRM-5051 self::checkPrimaryBlocks(CRM_Utils_Array::value('contact_id', $params)); } } return $location; }
/** * Run the page. * * This method is called after the page is created. */ public function run() { // get the emails for this contact $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, TRUE, NULL, $_REQUEST); $locBlockNo = CRM_Utils_Request::retrieve('locno', 'Positive', CRM_Core_DAO::$_nullObject, TRUE, NULL, $_REQUEST); $addressId = CRM_Utils_Request::retrieve('aid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE, NULL, $_REQUEST); $address = array(); if ($addressId > 0) { $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'display_name')); $entityBlock = array('id' => $addressId); $address = CRM_Core_BAO_Address::getValues($entityBlock, FALSE, 'id'); if (!empty($address)) { foreach ($address as $key => &$value) { $value['location_type'] = $locationTypes[$value['location_type_id']]; } } } // we just need current address block $currentAddressBlock['address'][$locBlockNo] = array_pop($address); if (!empty($currentAddressBlock['address'][$locBlockNo])) { // get contact name of shared contact names $sharedAddresses = array(); $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($currentAddressBlock['address']); foreach ($currentAddressBlock['address'] as $key => $addressValue) { if (!empty($addressValue['master_id']) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) { $sharedAddresses[$key]['shared_address_display'] = array('address' => $addressValue['display'], 'name' => $shareAddressContactNames[$addressValue['master_id']]['name']); } } $idValue = $currentAddressBlock['address'][$locBlockNo]['id']; if (!empty($currentAddressBlock['address'][$locBlockNo]['master_id'])) { $idValue = $currentAddressBlock['address'][$locBlockNo]['master_id']; } // add custom data of type address $groupTree = CRM_Core_BAO_CustomGroup::getTree('Address', $this, $idValue); // we setting the prefix to dnc_ below so that we don't overwrite smarty's grouptree var. $currentAddressBlock['address'][$locBlockNo]['custom'] = CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, "dnc_"); $this->assign("dnc_viewCustomData", NULL); $this->assign('add', $currentAddressBlock['address'][$locBlockNo]); $this->assign('sharedAddresses', $sharedAddresses); } $contact = new CRM_Contact_BAO_Contact(); $contact->id = $contactId; $contact->find(TRUE); $privacy = array(); foreach (CRM_Contact_BAO_Contact::$_commPrefs as $name) { if (isset($contact->{$name})) { $privacy[$name] = $contact->{$name}; } } $this->assign('contactId', $contactId); $this->assign('locationIndex', $locBlockNo); $this->assign('addressId', $addressId); $this->assign('privacy', $privacy); // check logged in user permission CRM_Contact_Page_View::checkUserPermission($this, $contactId); // finally call parent parent::run(); }
/** * takes an associative array and creates a contact object * * the function extract all the params it needs to initialize the create a * contact object. the params array could contain additional unused name/value * pairs * * @param array $params (reference ) an assoc array of name/value pairs * @param array $ids the array that holds all the db ids * @param array $locationId * * @return object CRM_Core_BAO_Address object * @access public * @static */ function add(&$params, &$ids, $locationId) { if (!CRM_Core_BAO_Address::dataExists($params, $locationId, $ids)) { return null; } $address =& new CRM_Core_BAO_Address(); $address->location_id = $params['location'][$locationId]['id']; $address->id = CRM_Utils_Array::value('address', $ids['location'][$locationId]); CRM_Core_BAO_Address::fixAddress($params['location'][$locationId]['address']); if ($address->copyValues($params['location'][$locationId]['address'])) { // we copied only null stuff, so we delete the object $address->delete(); return null; } return $address->save(); }
/** * Add an Address for a contact. * * FIXME: Should be using basic_create util * * @param array $params * Array per getfields metadata. * * @return array * API result array */ function civicrm_api3_address_create(&$params) { _civicrm_api3_check_edit_permissions('CRM_Core_BAO_Address', $params); /** * If street_parsing, street_address has to be parsed into * separate parts */ if (array_key_exists('street_parsing', $params)) { if ($params['street_parsing'] == 1) { if (array_key_exists('street_address', $params)) { if (!empty($params['street_address'])) { $parsedItems = CRM_Core_BAO_Address::parseStreetAddress($params['street_address']); if (array_key_exists('street_name', $parsedItems)) { $params['street_name'] = $parsedItems['street_name']; } if (array_key_exists('street_unit', $parsedItems)) { $params['street_unit'] = $parsedItems['street_unit']; } if (array_key_exists('street_number', $parsedItems)) { $params['street_number'] = $parsedItems['street_number']; } if (array_key_exists('street_number_suffix', $parsedItems)) { $params['street_number_suffix'] = $parsedItems['street_number_suffix']; } } } } } if (!isset($params['check_permissions'])) { $params['check_permissions'] = 0; } /** * Create array for BAO (expects address params in as an * element in array 'address' */ $addressBAO = CRM_Core_BAO_Address::add($params, TRUE); if (empty($addressBAO)) { return civicrm_api3_create_error("Address is not created or updated "); } else { $values = _civicrm_api3_dao_to_array($addressBAO, $params); return civicrm_api3_create_success($values, $params, 'Address', $addressBAO); } }
/** * Set variables up before form is built. * * @param CRM_Core_Form $form * * @return void */ public static function preProcess(&$form) { $form->_addBlockName = CRM_Utils_Request::retrieve('block', 'String', CRM_Core_DAO::$_nullObject); $additionalblockCount = CRM_Utils_Request::retrieve('count', 'Positive', CRM_Core_DAO::$_nullObject); $form->assign('addBlock', FALSE); if ($form->_addBlockName && $additionalblockCount) { $form->assign('addBlock', TRUE); $form->assign('blockName', $form->_addBlockName); $form->assign('blockId', $additionalblockCount); $form->set($form->_addBlockName . '_Block_Count', $additionalblockCount); } if (is_a($form, 'CRM_Event_Form_ManageEvent_Location') || is_a($form, 'CRM_Contact_Form_Domain')) { $form->_blocks = array('Address' => ts('Address'), 'Email' => ts('Email'), 'Phone' => ts('Phone')); } $form->assign('blocks', $form->_blocks); $form->assign('className', CRM_Utils_System::getClassName($form)); // get address sequence. if (!($addressSequence = $form->get('addressSequence'))) { $addressSequence = CRM_Core_BAO_Address::addressSequence(); $form->set('addressSequence', $addressSequence); } $form->assign('addressSequence', $addressSequence); }
/** * Function to create various elements of location block * * @param array $params (reference ) an assoc array of name/value pairs * @param boolean $fixAddress true if you need to fix (format) address values * before inserting in db * * @return array $location * @access public * @static */ static function create(&$params, $fixAddress = true, $entity = null) { $location = array(); if (!self::dataExists($params)) { return $location; } // create location blocks. foreach (self::$blocks as $block) { if ($block != 'address') { eval('$location[$block] = CRM_Core_BAO_Block::create( $block, $params, $entity );'); } else { $location[$block] = CRM_Core_BAO_Address::create($params, $fixAddress, $entity); } } if ($entity) { // this is a special case for adding values in location block table $entityElements = array('entity_table' => $params['entity_table'], 'entity_id' => $params['entity_id']); $location['id'] = self::createLocBlock($location, $entityElements); } else { // make sure contact should have only one primary block, CRM-5051 self::checkPrimaryBlocks(CRM_Utils_Array::value('contact_id', $params)); } return $location; }
/** * Function to add the custom fields * * @param $id * @param $name * @param bool $viewOnly * @param null $profileContactType * @param null $fieldTypes * * @return void * @access public */ function buildCustom($id, $name, $viewOnly = FALSE, $profileContactType = NULL, $fieldTypes = NULL) { if ($id) { $contactID = $this->getContactID(); // we don't allow conflicting fields to be // configured via profile - CRM 2100 $fieldsToIgnore = array('receive_date' => 1, 'trxn_id' => 1, 'invoice_id' => 1, 'net_amount' => 1, 'fee_amount' => 1, 'non_deductible_amount' => 1, 'total_amount' => 1, 'amount_level' => 1, 'contribution_status_id' => 1, 'payment_instrument' => 1, 'check_number' => 1, 'financial_type' => 1); $fields = NULL; if ($contactID && CRM_Core_BAO_UFGroup::filterUFGroups($id, $contactID)) { $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL); } else { $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL); } if ($fields) { // unset any email-* fields since we already collect it, CRM-2888 foreach (array_keys($fields) as $fieldName) { if (substr($fieldName, 0, 6) == 'email-' && $profileContactType != 'honor') { unset($fields[$fieldName]); } } if (array_intersect_key($fields, $fieldsToIgnore)) { $fields = array_diff_key($fields, $fieldsToIgnore); CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.'), ts('Warning'), 'alert'); } $fields = array_diff_assoc($fields, $this->_fields); CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID); $addCaptcha = FALSE; foreach ($fields as $key => $field) { if ($viewOnly && isset($field['data_type']) && $field['data_type'] == 'File' || $viewOnly && $field['name'] == 'image_URL') { // ignore file upload fields continue; } if ($profileContactType) { //Since we are showing honoree name separately so we are removing it from honoree profile just for display $honoreeNamefields = array('prefix_id', 'first_name', 'last_name', 'suffix_id', 'organization_name', 'household_name'); if ($profileContactType == 'honor' && in_array($field['name'], $honoreeNamefields)) { unset($fields[$field['name']]); continue; } if (!empty($fieldTypes) && in_array($field['field_type'], $fieldTypes)) { CRM_Core_BAO_UFGroup::buildProfile($this, $field, CRM_Profile_Form::MODE_CREATE, $contactID, TRUE, $profileContactType); $this->_fields[$profileContactType][$key] = $field; } else { unset($fields[$key]); } } else { CRM_Core_BAO_UFGroup::buildProfile($this, $field, CRM_Profile_Form::MODE_CREATE, $contactID, TRUE); $this->_fields[$key] = $field; } // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor if ($field['add_captcha'] && !$this->_userID) { $addCaptcha = TRUE; } } $this->assign($name, $fields); if ($addCaptcha && !$viewOnly) { $captcha = CRM_Utils_ReCAPTCHA::singleton(); $captcha->add($this); $this->assign('isCaptcha', TRUE); } } } }
/** * Function to actually build the form * * @return void * @access public */ public function buildQuickForm() { $this->assignToTemplate(); $productID = $this->get('productID'); $option = $this->get('option'); $membershipTypeID = $this->get('membershipTypeID'); $this->assign('receiptFromEmail', CRM_Utils_Array::value('receipt_from_email', $this->_values)); if ($productID) { CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE, $productID, $option); } if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_priceSetId, 'is_quick_config')) { $this->assign('lineItem', $this->_lineItem); } else { if (is_array($membershipTypeID)) { $membershipTypeID = current($membershipTypeID); } $this->assign('is_quick_config', 1); $this->_params['is_quick_config'] = 1; } $this->assign('priceSetID', $this->_priceSetId); $this->assign('useForMember', $this->get('useForMember')); $params = $this->_params; $honor_block_is_active = $this->get('honor_block_is_active'); if ($honor_block_is_active && (!empty($params["honor_first_name"]) && !empty($params["honor_last_name"]) || !empty($params["honor_email"]))) { $this->assign('honor_block_is_active', $honor_block_is_active); $this->assign('honor_block_title', CRM_Utils_Array::value('honor_block_title', $this->_values)); $prefix = CRM_Core_PseudoConstant::individualPrefix(); $honor = CRM_Core_PseudoConstant::honor(); $this->assign('honor_type', $honor[$params["honor_type_id"]]); $this->assign('honor_prefix', $params["honor_prefix_id"] ? $prefix[$params["honor_prefix_id"]] : ' '); $this->assign('honor_first_name', $params["honor_first_name"]); $this->assign('honor_last_name', $params["honor_last_name"]); $this->assign('honor_email', $params["honor_email"]); } $qParams = "reset=1&id={$this->_id}"; //pcp elements if ($this->_pcpId) { $qParams .= "&pcpId={$this->_pcpId}"; $this->assign('pcpBlock', TRUE); foreach (array('pcp_display_in_roll', 'pcp_is_anonymous', 'pcp_roll_nickname', 'pcp_personal_note') as $val) { if (CRM_Utils_Array::value($val, $this->_params)) { $this->assign($val, $this->_params[$val]); } } } $this->assign('qParams', $qParams); if ($membershipTypeID) { $transactionID = $this->get('membership_trx_id'); $membershipAmount = $this->get('membership_amount'); $renewalMode = $this->get('renewal_mode'); $this->assign('membership_trx_id', $transactionID); $this->assign('membership_amount', $membershipAmount); $this->assign('renewal_mode', $renewalMode); CRM_Member_BAO_Membership::buildMembershipBlock($this, $this->_id, FALSE, $membershipTypeID, TRUE, NULL, $this->_membershipContactID); } $this->_separateMembershipPayment = $this->get('separateMembershipPayment'); $this->assign("is_separate_payment", $this->_separateMembershipPayment); $this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE); $this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE); if (CRM_Utils_Array::value('hidden_onbehalf_profile', $params)) { $ufJoinParams = array('module' => 'onBehalf', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $this->_id); $OnBehalfProfile = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); $profileId = $OnBehalfProfile[0]; $fieldTypes = array('Contact', 'Organization'); $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization'); $fieldTypes = array_merge($fieldTypes, $contactSubType); if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) { $fieldTypes = array_merge($fieldTypes, array('Membership')); } else { $fieldTypes = array_merge($fieldTypes, array('Contribution')); } $this->buildCustom($profileId, 'onbehalfProfile', TRUE, TRUE, $fieldTypes); } $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $this->_params)); $this->assign('receive_date', CRM_Utils_Date::mysqlToIso(CRM_Utils_Array::value('receive_date', $this->_params))); $defaults = array(); $options = array(); $fields = array(); $removeCustomFieldTypes = array('Contribution'); foreach ($this->_fields as $name => $dontCare) { if ($name == 'onbehalf') { foreach ($dontCare as $key => $value) { $fields['onbehalf'][$key] = 1; } } else { $fields[$name] = 1; } } $fields['state_province'] = $fields['country'] = $fields['email'] = 1; $contact = $this->_params = $this->controller->exportValues('Main'); foreach ($fields as $name => $dontCare) { if ($name == 'onbehalf') { foreach ($dontCare as $key => $value) { //$defaults[$key] = $contact['onbehalf'][$key]; if (isset($contact['onbehalf'][$key])) { $defaults[$key] = $contact['onbehalf'][$key]; } if (isset($contact['onbehalf']["{$key}_id"])) { $defaults["{$key}_id"] = $contact['onbehalf']["{$key}_id"]; } } } elseif (isset($contact[$name])) { $defaults[$name] = $contact[$name]; if (substr($name, 0, 7) == 'custom_') { $timeField = "{$name}_time"; if (isset($contact[$timeField])) { $defaults[$timeField] = $contact[$timeField]; } } elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting')) && CRM_Utils_Array::value($name . '_custom', $contact)) { $defaults[$name . '_custom'] = $contact[$name . '_custom']; } } } // now fix all state country selectors CRM_Core_BAO_Address::fixAllStateSelects($this, $defaults); $this->_submitValues = array_merge($this->_submitValues, $defaults); $this->setDefaults($defaults); $values['entity_id'] = $this->_id; $values['entity_table'] = 'civicrm_contribution_page'; CRM_Friend_BAO_Friend::retrieve($values, $data); $tellAFriend = FALSE; if ($this->_pcpId) { if ($this->_pcpBlock['is_tellfriend_enabled']) { $this->assign('friendText', ts('Tell a Friend')); $subUrl = "eid={$this->_pcpId}&blockId={$this->_pcpBlock['id']}&pcomponent=pcp"; $tellAFriend = TRUE; } } elseif (CRM_Utils_Array::value('is_active', $data)) { $friendText = $data['title']; $this->assign('friendText', $friendText); $subUrl = "eid={$this->_id}&pcomponent=contribute"; $tellAFriend = TRUE; } if ($tellAFriend) { if ($this->_action & CRM_Core_Action::PREVIEW) { $url = CRM_Utils_System::url("civicrm/friend", "reset=1&action=preview&{$subUrl}"); } else { $url = CRM_Utils_System::url("civicrm/friend", "reset=1&{$subUrl}"); } $this->assign('friendURL', $url); } $this->freeze(); // can we blow away the session now to prevent hackery // CRM-9491 $this->controller->reset(); }
/** * Run the page. * * This method is called after the page is created. * * @return void * @access public * */ function run() { // get the emails for this contact $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, TRUE, NULL, $_REQUEST); $locBlockNo = CRM_Utils_Request::retrieve('locno', 'Positive', CRM_Core_DAO::$_nullObject, TRUE, NULL, $_REQUEST); $addressId = CRM_Utils_Request::retrieve('aid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE, NULL, $_REQUEST); $address = array(); if ($addressId > 0) { $locationTypes = CRM_Core_PseudoConstant::locationDisplayName(); $entityBlock = array('id' => $addressId); $address = CRM_Core_BAO_Address::getValues($entityBlock, FALSE, 'id'); if (!empty($address)) { foreach ($address as $key => &$value) { $value['location_type'] = $locationTypes[$value['location_type_id']]; } } } // we just need current address block $currentAddressBlock['address'][$locBlockNo] = array_pop($address); if (!empty($currentAddressBlock['address'][$locBlockNo])) { // get contact name of shared contact names $sharedAddresses = array(); $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($currentAddressBlock['address']); foreach ($currentAddressBlock['address'] as $key => $addressValue) { if (CRM_Utils_Array::value('master_id', $addressValue) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) { $sharedAddresses[$key]['shared_address_display'] = array('address' => $addressValue['display'], 'name' => $shareAddressContactNames[$addressValue['master_id']]['name']); } } // add custom data of type address $groupTree = CRM_Core_BAO_CustomGroup::getTree('Address', $this, $currentAddressBlock['address'][$locBlockNo]['id']); // we setting the prefix to dnc_ below so that we don't overwrite smarty's grouptree var. $currentAddressBlock['address'][$locBlockNo]['custom'] = CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, "dnc_"); $this->assign("dnc_viewCustomData", NULL); $this->assign('add', $currentAddressBlock['address'][$locBlockNo]); $this->assign('sharedAddresses', $sharedAddresses); } $this->assign('contactId', $contactId); $this->assign('locationIndex', $locBlockNo); $this->assign('addressId', $addressId); $appendBlockIndex = CRM_Core_BAO_Address::getAddressCount($contactId); // check if we are adding new address, then only append add link if ($appendBlockIndex == $locBlockNo) { if ($appendBlockIndex) { $appendBlockIndex++; } } else { $appendBlockIndex = 0; } $this->assign('appendBlockIndex', $appendBlockIndex); // check logged in user permission CRM_Contact_Page_View::checkUserPermission($this, $contactId); // finally call parent parent::run(); }
/** * build all the data structures needed to build the form * * @return void * @access public */ function preProcess() { $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE); $this->_searchKey = CRM_Utils_Request::retrieve('key', 'String', $this); // sort out whether it’s a delete-to-trash, delete-into-oblivion or restore (and let the template know) $values = $this->controller->exportValues(); $this->_skipUndelete = (CRM_Core_Permission::check('access deleted contacts') and (CRM_Utils_Request::retrieve('skip_undelete', 'Boolean', $this) or CRM_Utils_Array::value('task', $values) == CRM_Contact_Task::DELETE_PERMANENTLY)); $this->_restore = (CRM_Utils_Request::retrieve('restore', 'Boolean', $this) or CRM_Utils_Array::value('task', $values) == CRM_Contact_Task::RESTORE); if ($this->_restore && !CRM_Core_Permission::check('access deleted contacts')) { CRM_Core_Error::fatal(ts('You do not have permission to access this contact.')); } elseif (!CRM_Core_Permission::check('delete contacts')) { CRM_Core_Error::fatal(ts('You do not have permission to delete this contact.')); } $this->assign('trash', CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'contact_undelete', NULL) and !$this->_skipUndelete); $this->assign('restore', $this->_restore); if ($this->_restore) { CRM_Utils_System::setTitle(ts('Restore Contact')); } if ($cid) { if (!CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT)) { CRM_Core_Error::fatal(ts('You do not have permission to delete this contact. Note: you can delete contacts if you can edit them.')); } elseif (CRM_Contact_BAO_Contact::checkDomainContact($cid)) { CRM_Core_Error::fatal(ts('This contact is a special one for the contact information associated with the CiviCRM installation for this domain. No one is allowed to delete it because the information is used for special system purposes.')); } $this->_contactIds = array($cid); $this->_single = TRUE; $this->assign('totalSelectedContacts', 1); } else { parent::preProcess(); } $this->_sharedAddressMessage = $this->get('sharedAddressMessage'); if (!$this->_restore && !$this->_sharedAddressMessage) { // we check for each contact for shared contact address $sharedContactList = array(); $sharedAddressCount = 0; foreach ($this->_contactIds as $contactId) { // check if a contact that is being deleted has any shared addresses $sharedAddressMessage = CRM_Core_BAO_Address::setSharedAddressDeleteStatus(NULL, $contactId, TRUE); if ($sharedAddressMessage['count'] > 0) { $sharedAddressCount += $sharedAddressMessage['count']; $sharedContactList = array_merge($sharedContactList, $sharedAddressMessage['contactList']); } } $this->_sharedAddressMessage = array('count' => $sharedAddressCount, 'contactList' => $sharedContactList); if ($sharedAddressCount > 0) { if (count($this->_contactIds) > 1) { // more than one contact deleted $message = ts('One of the selected contacts has an address record that is shared with 1 other contact.', array('plural' => 'One or more selected contacts have address records which are shared with %count other contacts.', 'count' => $sharedAddressCount)); } else { // only one contact deleted $message = ts('This contact has an address record which is shared with 1 other contact.', array('plural' => 'This contact has an address record which is shared with %count other contacts.', 'count' => $sharedAddressCount)); } CRM_Core_Session::setStatus($message . ' ' . ts('Shared addresses will not be removed or altered but will no longer be shared.'), ts('Shared Addesses Owner')); } // set in form controller so that queries are not fired again $this->set('sharedAddressMessage', $this->_sharedAddressMessage); } }
/** * Parse all address blocks present in given params * and return parse result for all address blocks, * This function either parse street address in to child * elements or build street address from child elements. * * @param array $params * of key value consist of address blocks. * * @return array * as array of success/fails for each address block */ public function parseAddress(&$params) { $parseSuccess = $parsedFields = array(); if (!is_array($params['address']) || CRM_Utils_System::isNull($params['address'])) { return $parseSuccess; } foreach ($params['address'] as $instance => &$address) { $buildStreetAddress = FALSE; $parseFieldName = 'street_address'; foreach (array('street_number', 'street_name', 'street_unit') as $fld) { if (!empty($address[$fld])) { $parseFieldName = 'street_number'; $buildStreetAddress = TRUE; break; } } // main parse string. $parseString = CRM_Utils_Array::value($parseFieldName, $address); // parse address field. $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($parseString); if ($buildStreetAddress) { //hack to ignore spaces between number and suffix. //here user gives input as street_number so it has to //be street_number and street_number_suffix, but //due to spaces though preg detect string as street_name //consider it as 'street_number_suffix'. $suffix = $parsedFields['street_number_suffix']; if (!$suffix) { $suffix = $parsedFields['street_name']; } $address['street_number_suffix'] = $suffix; $address['street_number'] = $parsedFields['street_number']; $streetAddress = NULL; foreach (array('street_number', 'street_number_suffix', 'street_name', 'street_unit') as $fld) { if (in_array($fld, array('street_name', 'street_unit'))) { $streetAddress .= ' '; } $streetAddress .= CRM_Utils_Array::value($fld, $address); } $address['street_address'] = trim($streetAddress); $parseSuccess[$instance] = TRUE; } else { $success = TRUE; // consider address is automatically parseable, // when we should found street_number and street_name if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) { $success = FALSE; } // check for original street address string. if (empty($parseString)) { $success = TRUE; } $parseSuccess[$instance] = $success; // we do not reset element values, but keep what we've parsed // in case of partial matches: CRM-8378 // merge parse address in to main address block. $address = array_merge($address, $parsedFields); } } return $parseSuccess; }
/** * 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')); } }
/** * Set default values for address block. * * @param array $defaults * Defaults associated array. * @param CRM_Core_Form $form * Form object. */ public static function setDefaultValues(&$defaults, &$form) { $addressValues = array(); if (isset($defaults['address']) && is_array($defaults['address']) && !CRM_Utils_System::isNull($defaults['address'])) { // start of contact shared adddress defaults $sharedAddresses = array(); $masterAddress = array(); // get contact name of shared contact names $shareAddressContactNames = CRM_Contact_BAO_Contact_Utils::getAddressShareContactNames($defaults['address']); foreach ($defaults['address'] as $key => $addressValue) { if (!empty($addressValue['master_id']) && !$shareAddressContactNames[$addressValue['master_id']]['is_deleted']) { $master_cid = $shareAddressContactNames[$addressValue['master_id']]['contact_id']; $sharedAddresses[$key]['shared_address_display'] = array('address' => $addressValue['display'], 'name' => $shareAddressContactNames[$addressValue['master_id']]['name'], 'options' => CRM_Core_BAO_Address::getValues(array('entity_id' => $master_cid, 'contact_id' => $master_cid)), 'master_id' => $addressValue['master_id']); $defaults['address'][$key]['master_contact_id'] = $master_cid; } else { $defaults['address'][$key]['use_shared_address'] = 0; } //check if any address is shared by any other contacts $masterAddress[$key] = CRM_Core_BAO_Address::checkContactSharedAddress($addressValue['id']); } $form->assign('sharedAddresses', $sharedAddresses); $form->assign('masterAddress', $masterAddress); // end of shared address defaults // start of parse address functionality // build street address, CRM-5450. if ($form->_parseStreetAddress) { $parseFields = array('street_address', 'street_number', 'street_name', 'street_unit'); foreach ($defaults['address'] as $cnt => &$address) { $streetAddress = NULL; foreach (array('street_number', 'street_number_suffix', 'street_name', 'street_unit') as $fld) { if (in_array($fld, array('street_name', 'street_unit'))) { $streetAddress .= ' '; } $streetAddress .= CRM_Utils_Array::value($fld, $address); } $streetAddress = trim($streetAddress); if (!empty($streetAddress)) { $address['street_address'] = $streetAddress; } if (isset($address['street_number'])) { $address['street_number'] .= CRM_Utils_Array::value('street_number_suffix', $address); } // build array for set default. foreach ($parseFields as $field) { $addressValues["{$field}_{$cnt}"] = CRM_Utils_Array::value($field, $address); } // don't load fields, use js to populate. foreach (array('street_number', 'street_name', 'street_unit') as $f) { if (isset($address[$f])) { unset($address[$f]); } } } $form->assign('allAddressFieldValues', json_encode($addressValues)); //hack to handle show/hide address fields. $parsedAddress = array(); if ($form->_contactId && !empty($_POST['address']) && is_array($_POST['address'])) { foreach ($_POST['address'] as $cnt => $values) { $showField = 'streetAddress'; foreach (array('street_number', 'street_name', 'street_unit') as $fld) { if (!empty($values[$fld])) { $showField = 'addressElements'; break; } } $parsedAddress[$cnt] = $showField; } } $form->assign('showHideAddressFields', $parsedAddress); $form->assign('loadShowHideAddressFields', empty($parsedAddress) ? FALSE : TRUE); } // end of parse address functionality } }
/** * Function to add the custom fields * * @return None * @access public */ function buildCustom($id, $name, $viewOnly = FALSE, $onBehalf = FALSE, $fieldTypes = NULL) { $stateCountryMap = array(); if ($id) { $contactID = $this->getContactID(); // we don't allow conflicting fields to be // configured via profile - CRM 2100 $fieldsToIgnore = array('receive_date' => 1, 'trxn_id' => 1, 'invoice_id' => 1, 'net_amount' => 1, 'fee_amount' => 1, 'non_deductible_amount' => 1, 'total_amount' => 1, 'amount_level' => 1, 'contribution_status_id' => 1, 'payment_instrument' => 1, 'check_number' => 1, 'financial_type' => 1); $fields = NULL; if ($contactID && CRM_Core_BAO_UFGroup::filterUFGroups($id, $contactID)) { $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL); } else { $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL); } if ($fields) { // unset any email-* fields since we already collect it, CRM-2888 foreach (array_keys($fields) as $fieldName) { if (substr($fieldName, 0, 6) == 'email-') { unset($fields[$fieldName]); } } if (array_intersect_key($fields, $fieldsToIgnore)) { $fields = array_diff_key($fields, $fieldsToIgnore); CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.'), ts('Warning'), 'alert'); } $fields = array_diff_assoc($fields, $this->_fields); CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID); $addCaptcha = FALSE; foreach ($fields as $key => $field) { if ($viewOnly && isset($field['data_type']) && $field['data_type'] == 'File' || $viewOnly && $field['name'] == 'image_URL') { // ignore file upload fields continue; } list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2); if ($prefixName == 'state_province' || $prefixName == 'country' || $prefixName == 'county') { if (!array_key_exists($index, $stateCountryMap)) { $stateCountryMap[$index] = array(); } $stateCountryMap[$index][$prefixName] = $key; } if ($onBehalf) { if (!empty($fieldTypes) && in_array($field['field_type'], $fieldTypes)) { CRM_Core_BAO_UFGroup::buildProfile($this, $field, CRM_Profile_Form::MODE_CREATE, $contactID, TRUE); $this->_fields['onbehalf'][$key] = $field; } else { unset($fields[$key]); } } else { CRM_Core_BAO_UFGroup::buildProfile($this, $field, CRM_Profile_Form::MODE_CREATE, $contactID, TRUE); $this->_fields[$key] = $field; } // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor if ($field['add_captcha'] && !$this->_userID) { $addCaptcha = TRUE; } } $this->assign($name, $fields); CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap); if ($addCaptcha && !$viewOnly) { $captcha = CRM_Utils_ReCAPTCHA::singleton(); $captcha->add($this); $this->assign('isCaptcha', TRUE); } } } }
/** * Process the form. * * @return void */ public function postProcess() { $params = $this->exportValues(); // Process / save address $params['contact_id'] = $this->_contactId; $params['updateBlankLocInfo'] = TRUE; // process shared contact address. CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']); if ($this->_parseStreetAddress) { CRM_Contact_Form_Contact::parseAddress($params); } if ($this->_addressId > 0) { $params['address'][$this->_locBlockNo]['id'] = $this->_addressId; } // save address changes $address = CRM_Core_BAO_Address::create($params, TRUE); $this->log(); $this->ajaxResponse['addressId'] = $address[0]->id; $this->response(); }
/** * Gather values for contribution mail - this function has been created * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function * Values related to the contribution in question are gathered * * @param array $input * Input into function (probably from payment processor). * @param array $values * @param array $ids * The set of ids related to the input. * * @return array */ public function _gatherMessageValues($input, &$values, $ids = array()) { // set display address of contributor if ($this->address_id) { $addressParams = array('id' => $this->address_id); $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id'); $addressDetails = array_values($addressDetails); $values['address'] = $addressDetails[0]['display']; } if ($this->_component == 'contribute') { if (isset($this->contribution_page_id)) { CRM_Contribute_BAO_ContributionPage::setValues($this->contribution_page_id, $values); if ($this->contribution_page_id) { // CRM-8254 - override default currency if applicable $config = CRM_Core_Config::singleton(); $config->defaultCurrency = CRM_Utils_Array::value('currency', $values, $config->defaultCurrency); } } else { // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id) $values['is_email_receipt'] = 1; $values['title'] = 'Contribution'; } // set lineItem for contribution if ($this->id) { $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1); if (!empty($lineItem)) { $itemId = key($lineItem); foreach ($lineItem as &$eachItem) { if (is_array($this->_relatedObjects['membership']) && array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) { $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date); $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date); $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date); } } $values['lineItem'][0] = $lineItem; $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id'); } } $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds($this->id, $this->contact_id); // if this is onbehalf of contribution then set related contact if (!empty($relatedContact['individual_id'])) { $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id']; } } else { // event $eventParams = array('id' => $this->_relatedObjects['event']->id); $values['event'] = array(); CRM_Event_BAO_Event::retrieve($eventParams, $values['event']); // add custom fields for event $eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this->_relatedObjects['event'], $this->_relatedObjects['event']->id); $eventCustomGroup = array(); foreach ($eventGroupTree as $key => $group) { if ($key === 'info') { continue; } foreach ($group['fields'] as $k => $customField) { $groupLabel = $group['title']; if (!empty($customField['customValue'])) { foreach ($customField['customValue'] as $customFieldValues) { $eventCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues); } } } } $values['event']['customGroup'] = $eventCustomGroup; //get participant details $participantParams = array('id' => $this->_relatedObjects['participant']->id); $values['participant'] = array(); CRM_Event_BAO_Participant::getValues($participantParams, $values['participant'], $participantIds); // add custom fields for event $participantGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', $this->_relatedObjects['participant'], $this->_relatedObjects['participant']->id); $participantCustomGroup = array(); foreach ($participantGroupTree as $key => $group) { if ($key === 'info') { continue; } foreach ($group['fields'] as $k => $customField) { $groupLabel = $group['title']; if (!empty($customField['customValue'])) { foreach ($customField['customValue'] as $customFieldValues) { $participantCustomGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues); } } } } $values['participant']['customGroup'] = $participantCustomGroup; //get location details $locationParams = array('entity_id' => $this->_relatedObjects['event']->id, 'entity_table' => 'civicrm_event'); $values['location'] = CRM_Core_BAO_Location::getValues($locationParams); $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent'); list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); $values['custom_pre_id'] = $custom_pre_id; $values['custom_post_id'] = $custom_post_ids; // set lineItem for event contribution if ($this->id) { $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id); if (!empty($participantIds)) { foreach ($participantIds as $pIDs) { $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs); if (!CRM_Utils_System::isNull($lineItem)) { $values['lineItem'][] = $lineItem; } } } } } $groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', $this, $this->id); $customGroup = array(); foreach ($groupTree as $key => $group) { if ($key === 'info') { continue; } foreach ($group['fields'] as $k => $customField) { $groupLabel = $group['title']; if (!empty($customField['customValue'])) { foreach ($customField['customValue'] as $customFieldValues) { $customGroup[$groupLabel][$customField['label']] = CRM_Utils_Array::value('data', $customFieldValues); } } } } $values['customGroup'] = $customGroup; return $values; }
/** * process the form * * @return void * @access public */ public function postProcess() { $params = $this->exportValues(); // need to process / save address $params['contact_id'] = $this->_contactId; $params['updateBlankLocInfo'] = TRUE; // process shared contact address. CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']); if ($this->_parseStreetAddress) { CRM_Contact_Form_Contact::parseAddress($params); } if ($this->_addressId > 0) { $params['address'][$this->_locBlockNo]['id'] = $this->_addressId; } // save address changes $address = CRM_Core_BAO_Address::create($params, TRUE); // make entry in log table CRM_Core_BAO_Log::register($this->_contactId, 'civicrm_contact', $this->_contactId); $response = array('status' => 'save', 'addressId' => $address[0]->id); $this->postProcessHook(); echo json_encode($response); CRM_Utils_System::civiExit(); }
/** * Create the from clause. * * @param array $tables * Tables that need to be included in this from clause. * if null, return mimimal from clause (i.e. civicrm_contact) * @param array $inner * Tables that should be inner-joined. * @param array $right * Tables that should be right-joined. * * @param bool $primaryLocation * @param int $mode * * @return string * the from clause */ public static function fromClause(&$tables, $inner = NULL, $right = NULL, $primaryLocation = TRUE, $mode = 1) { $from = ' FROM civicrm_contact contact_a'; if (empty($tables)) { return $from; } if (!empty($tables['civicrm_worldregion'])) { $tables = array_merge(array('civicrm_country' => 1), $tables); } if ((!empty($tables['civicrm_state_province']) || !empty($tables['civicrm_country']) || CRM_Utils_Array::value('civicrm_county', $tables)) && empty($tables['civicrm_address'])) { $tables = array_merge(array('civicrm_address' => 1), $tables); } // add group_contact and group_contact_cache table if group table is present if (!empty($tables['civicrm_group'])) { if (empty($tables['civicrm_group_contact'])) { $tables['civicrm_group_contact'] = " LEFT JOIN civicrm_group_contact ON civicrm_group_contact.contact_id = contact_a.id AND civicrm_group_contact.status = 'Added' "; } if (empty($tables['civicrm_group_contact_cache'])) { $tables['civicrm_group_contact_cache'] = " LEFT JOIN civicrm_group_contact_cache ON civicrm_group_contact_cache.contact_id = contact_a.id "; } } // add group_contact and group table is subscription history is present if (!empty($tables['civicrm_subscription_history']) && empty($tables['civicrm_group'])) { $tables = array_merge(array('civicrm_group' => 1, 'civicrm_group_contact' => 1), $tables); } // to handle table dependencies of components CRM_Core_Component::tableNames($tables); // to handle table dependencies of hook injected tables CRM_Contact_BAO_Query_Hook::singleton()->setTableDependency($tables); //format the table list according to the weight $info = CRM_Core_TableHierarchy::info(); foreach ($tables as $key => $value) { $k = 99; if (strpos($key, '-') !== FALSE) { $keyArray = explode('-', $key); $k = CRM_Utils_Array::value('civicrm_' . $keyArray[1], $info, 99); } elseif (strpos($key, '_') !== FALSE) { $keyArray = explode('_', $key); if (is_numeric(array_pop($keyArray))) { $k = CRM_Utils_Array::value(implode('_', $keyArray), $info, 99); } else { $k = CRM_Utils_Array::value($key, $info, 99); } } else { $k = CRM_Utils_Array::value($key, $info, 99); } $tempTable[$k . ".{$key}"] = $key; } ksort($tempTable); $newTables = array(); foreach ($tempTable as $key) { $newTables[$key] = $tables[$key]; } $tables = $newTables; foreach ($tables as $name => $value) { if (!$value) { continue; } if (!empty($inner[$name])) { $side = 'INNER'; } elseif (!empty($right[$name])) { $side = 'RIGHT'; } else { $side = 'LEFT'; } if ($value != 1) { // if there is already a join statement in value, use value itself if (strpos($value, 'JOIN')) { $from .= " {$value} "; } else { $from .= " {$side} JOIN {$name} ON ( {$value} ) "; } continue; } switch ($name) { case 'civicrm_address': if ($primaryLocation) { $from .= " {$side} JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id AND civicrm_address.is_primary = 1 )"; } else { //CRM-14263 further handling of address joins further down... $from .= " {$side} JOIN civicrm_address ON ( contact_a.id = civicrm_address.contact_id ) "; } continue; case 'civicrm_phone': $from .= " {$side} JOIN civicrm_phone ON (contact_a.id = civicrm_phone.contact_id AND civicrm_phone.is_primary = 1) "; continue; case 'civicrm_email': $from .= " {$side} JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1) "; continue; case 'civicrm_im': $from .= " {$side} JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id AND civicrm_im.is_primary = 1) "; continue; case 'im_provider': $from .= " {$side} JOIN civicrm_im ON (contact_a.id = civicrm_im.contact_id) "; $from .= " {$side} JOIN civicrm_option_group option_group_imProvider ON option_group_imProvider.name = 'instant_messenger_service'"; $from .= " {$side} JOIN civicrm_option_value im_provider ON (civicrm_im.provider_id = im_provider.value AND option_group_imProvider.id = im_provider.option_group_id)"; continue; case 'civicrm_openid': $from .= " {$side} JOIN civicrm_openid ON ( civicrm_openid.contact_id = contact_a.id AND civicrm_openid.is_primary = 1 )"; continue; case 'civicrm_worldregion': $from .= " {$side} JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id "; $from .= " {$side} JOIN civicrm_worldregion ON civicrm_country.region_id = civicrm_worldregion.id "; continue; case 'civicrm_location_type': $from .= " {$side} JOIN civicrm_location_type ON civicrm_address.location_type_id = civicrm_location_type.id "; continue; case 'civicrm_group': $from .= " {$side} JOIN civicrm_group ON (civicrm_group.id = civicrm_group_contact.group_id OR civicrm_group.id = civicrm_group_contact_cache.group_id) "; continue; case 'civicrm_group_contact': $from .= " {$side} JOIN civicrm_group_contact ON contact_a.id = civicrm_group_contact.contact_id "; continue; case 'civicrm_group_contact_cache': $from .= " {$side} JOIN civicrm_group_contact_cache ON contact_a.id = civicrm_group_contact_cache.contact_id "; continue; case 'civicrm_activity': case 'civicrm_activity_tag': case 'activity_type': case 'activity_status': case 'parent_id': case 'civicrm_activity_contact': case 'source_contact': $from .= CRM_Activity_BAO_Query::from($name, $mode, $side); continue; case 'civicrm_entity_tag': $from .= " {$side} JOIN civicrm_entity_tag ON ( civicrm_entity_tag.entity_table = 'civicrm_contact' AND\n civicrm_entity_tag.entity_id = contact_a.id ) "; continue; case 'civicrm_note': $from .= " {$side} JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_contact' AND\n contact_a.id = civicrm_note.entity_id ) "; continue; case 'civicrm_subscription_history': $from .= " {$side} JOIN civicrm_subscription_history\n ON civicrm_group_contact.contact_id = civicrm_subscription_history.contact_id\n AND civicrm_group_contact.group_id = civicrm_subscription_history.group_id"; continue; case 'civicrm_relationship': if (self::$_relType == 'reciprocal') { if (self::$_relationshipTempTable) { // we have a temptable to join on $tbl = self::$_relationshipTempTable; $from .= " INNER JOIN {$tbl} civicrm_relationship ON civicrm_relationship.contact_id = contact_a.id"; } else { $from .= " {$side} JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id OR civicrm_relationship.contact_id_a = contact_a.id)"; $from .= " {$side} JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id OR civicrm_relationship.contact_id_b = contact_b.id)"; } } elseif (self::$_relType == 'b') { $from .= " {$side} JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = contact_a.id )"; $from .= " {$side} JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_a = contact_b.id )"; } else { $from .= " {$side} JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = contact_a.id )"; $from .= " {$side} JOIN civicrm_contact contact_b ON (civicrm_relationship.contact_id_b = contact_b.id )"; } continue; case 'civicrm_log': $from .= " INNER JOIN civicrm_log ON (civicrm_log.entity_id = contact_a.id AND civicrm_log.entity_table = 'civicrm_contact')"; $from .= " INNER JOIN civicrm_contact contact_b_log ON (civicrm_log.modified_id = contact_b_log.id)"; continue; case 'civicrm_tag': $from .= " {$side} JOIN civicrm_tag ON civicrm_entity_tag.tag_id = civicrm_tag.id "; continue; case 'civicrm_grant': $from .= CRM_Grant_BAO_Query::from($name, $mode, $side); continue; case 'civicrm_website': $from .= " {$side} JOIN civicrm_website ON contact_a.id = civicrm_website.contact_id "; continue; default: $locationTypeName = ''; if (strpos($name, '-address') != 0) { $locationTypeName = 'address'; } elseif (strpos($name, '-phone') != 0) { $locationTypeName = 'phone'; } elseif (strpos($name, '-email') != 0) { $locationTypeName = 'email'; } elseif (strpos($name, '-im') != 0) { $locationTypeName = 'im'; } elseif (strpos($name, '-openid') != 0) { $locationTypeName = 'openid'; } if ($locationTypeName) { //we have a join on an location table - possibly in conjunction with search builder - CRM-14263 $parts = explode('-', $name); $locationID = array_search($parts[0], CRM_Core_BAO_Address::buildOptions('location_type_id', 'get', array('name' => $parts[0]))); $from .= " {$side} JOIN civicrm_{$locationTypeName} `{$name}` ON ( contact_a.id = `{$name}`.contact_id ) and `{$name}`.location_type_id = {$locationID} "; } else { $from .= CRM_Core_Component::from($name, $mode, $side); } $from .= CRM_Contact_BAO_Query_Hook::singleton()->buildSearchfrom($name, $mode, $side); continue; } } return $from; }
/** * Process the PDf and email with activity and attachment. * on click of Print Invoices * * @param array $contribIDs * Contribution Id. * @param array $params * Associated array of submitted values. * @param array $contactIds * Contact Id. * @param CRM_Core_Form $form * Form object. */ public static function printPDF($contribIDs, &$params, $contactIds, &$form) { // get all the details needed to generate a invoice $messageInvoice = array(); $invoiceTemplate = CRM_Core_Smarty::singleton(); $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds); // gives the status id when contribution status is 'Refunded' $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID); // getting data from admin page $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings'); foreach ($invoiceElements['details'] as $contribID => $detail) { $input = $ids = $objects = array(); if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) { continue; } $input['component'] = $detail['component']; $ids['contact'] = $detail['contact']; $ids['contribution'] = $contribID; $ids['contributionRecur'] = NULL; $ids['contributionPage'] = NULL; $ids['membership'] = CRM_Utils_Array::value('membership', $detail); $ids['participant'] = CRM_Utils_Array::value('participant', $detail); $ids['event'] = CRM_Utils_Array::value('event', $detail); if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) { CRM_Core_Error::fatal(); } $contribution =& $objects['contribution']; $input['amount'] = $contribution->total_amount; $input['invoice_id'] = $contribution->invoice_id; $input['receive_date'] = $contribution->receive_date; $input['contribution_status_id'] = $contribution->contribution_status_id; $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name; $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date); $addressParams = array('contact_id' => $contribution->contact_id); $addressDetails = CRM_Core_BAO_Address::getValues($addressParams); // to get billing address if present $billingAddress = array(); foreach ($addressDetails as $key => $address) { if (isset($address['is_billing']) && $address['is_billing'] == 1 && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) { $billingAddress[$address['contact_id']] = $address; break; } elseif ($address['is_billing'] == 0 && $address['is_primary'] == 1 || isset($address['is_billing']) && $address['is_billing'] == 1 && $address['contact_id'] == $contribution->contact_id) { $billingAddress[$address['contact_id']] = $address; } } if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) { $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']); } else { $stateProvinceAbbreviation = ''; } if ($contribution->contribution_status_id == $refundedStatusId) { $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $contribution->id; } $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id; //to obtain due date for PDF invoice $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date']))); $invoiceDate = date("F j, Y"); $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period'])); if ($input['component'] == 'contribute') { $eid = $contribID; $etable = 'contribution'; $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, TRUE); } else { $eid = $contribution->_relatedObjects['participant']->id; $etable = 'participant'; $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable); } //TO DO: Need to do changes for partially paid to display amount due on PDF invoice $amountDue = $input['amount'] - $input['amount']; // retreiving the subtotal and sum of same tax_rate $dataArray = array(); $subTotal = 0; foreach ($lineItem as $entity_id => $taxRate) { if (isset($dataArray[(string) $taxRate['tax_rate']])) { $dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate); } else { $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate); } $subTotal += CRM_Utils_Array::value('subTotal', $taxRate); } // to email the invoice $mailDetails = array(); $values = array(); if ($contribution->_component == 'event') { $daoName = 'CRM_Event_DAO_Event'; $pageId = $contribution->_relatedObjects['event']->id; $mailElements = array('title', 'confirm_from_name', 'confirm_from_email', 'cc_confirm', 'bcc_confirm'); CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements); $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]); $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]); $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]); $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]); $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]); $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]); } elseif ($contribution->_component == 'contribute') { $daoName = 'CRM_Contribute_DAO_ContributionPage'; $pageId = $contribution->contribution_page_id; $mailElements = array('title', 'receipt_from_name', 'receipt_from_email', 'cc_receipt', 'bcc_receipt'); CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements); $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails)); $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails)); $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails)); $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails)); $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails)); $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails)); } $source = $contribution->source; $config = CRM_Core_Config::singleton(); if (!isset($params['forPage'])) { $config->doNotAttachPDFReceipt = 1; } // get organization address $domain = CRM_Core_BAO_Domain::getDomain(); $locParams = array('contact_id' => $domain->id); $locationDefaults = CRM_Core_BAO_Location::getValues($locParams); if (isset($locationDefaults['address'][1]['state_province_id'])) { $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']); } else { $stateProvinceAbbreviationDomain = ''; } if (isset($locationDefaults['address'][1]['country_id'])) { $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']); } else { $countryDomain = ''; } // parameters to be assign for template $tplParams = array('title' => $title, 'component' => $input['component'], 'id' => $contribution->id, 'source' => $source, 'invoice_id' => $invoiceId, 'resourceBase' => $config->userFrameworkResourceURL, 'defaultCurrency' => $config->defaultCurrency, 'amount' => $contribution->total_amount, 'amountDue' => $amountDue, 'invoice_date' => $invoiceDate, 'dueDate' => $dueDate, 'notes' => CRM_Utils_Array::value('notes', $prefixValue), 'display_name' => $contribution->_relatedObjects['contact']->display_name, 'lineItem' => $lineItem, 'dataArray' => $dataArray, 'refundedStatusId' => $refundedStatusId, 'contribution_status_id' => $contribution->contribution_status_id, 'subTotal' => $subTotal, 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'stateProvinceAbbreviation' => $stateProvinceAbbreviation, 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)), 'is_pay_later' => $contribution->is_pay_later, 'organization_name' => $contribution->_relatedObjects['contact']->organization_name, 'domain_organization' => $domain->name, 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])), 'domain_state' => $stateProvinceAbbreviationDomain, 'domain_country' => $countryDomain, 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])), 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone']))); if (isset($creditNoteId)) { $tplParams['creditnote_id'] = $creditNoteId; } $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_invoice_receipt', 'contactId' => $contribution->contact_id, 'tplParams' => $tplParams, 'PDFFilename' => 'Invoice.pdf'); $session = CRM_Core_Session::singleton(); $contactID = $session->get('userID'); //CRM-16319 - we dont store in userID in case the user is doing multiple //transactions etc if (empty($contactID)) { $contactID = $session->get('transaction.userID'); } $contactEmails = CRM_Core_BAO_Email::allEmails($contactID); $emails = array(); $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'display_name'); foreach ($contactEmails as $emailId => $item) { $email = $item['email']; if ($email) { $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> '; } } $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address')); // from email address if (isset($params['from_email_address'])) { $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail); } // condition to check for download PDF Invoice or email Invoice if ($invoiceElements['createPdf']) { list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); if (isset($params['forPage'])) { return $html; } else { $mail = array('subject' => $subject, 'body' => $message, 'html' => $html); if ($mail['html']) { $messageInvoice[] = $mail['html']; } else { $messageInvoice[] = nl2br($mail['body']); } } } elseif ($contribution->_component == 'contribute') { $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id); $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment'])); $sendTemplateParams['from'] = $fromEmailAddress; $sendTemplateParams['toEmail'] = $email; $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values); $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values); list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); // functions call for adding activity with attachment $fileName = self::putFile($html); self::addActivities($subject, $contribution->contact_id, $fileName, $params); } elseif ($contribution->_component == 'event') { $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id); $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment'])); $sendTemplateParams['from'] = $fromEmailAddress; $sendTemplateParams['toEmail'] = $email; $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values); $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values); list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); // functions call for adding activity with attachment $fileName = self::putFile($html); self::addActivities($subject, $contribution->contact_id, $fileName, $params); } CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId); if ($contribution->contribution_status_id == $refundedStatusId) { CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId); } $invoiceTemplate->clearTemplateVars(); } if ($invoiceElements['createPdf']) { if (isset($params['forPage'])) { return $html; } else { CRM_Utils_PDF_Utils::html2pdf($messageInvoice, 'Invoice.pdf', FALSE, array('margin_top' => 10, 'margin_left' => 65, 'metric' => 'px')); // functions call for adding activity with attachment $fileName = self::putFile($html); self::addActivities($subject, $contactIds, $fileName, $params); CRM_Utils_System::civiExit(); } } else { if ($invoiceElements['suppressedEmails']) { $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $invoiceElements['suppressedEmails'])); $msgTitle = ts('Email Error'); $msgType = 'error'; } else { $status = ts('Your mail has been sent.'); $msgTitle = ts('Sent'); $msgType = 'success'; } CRM_Core_Session::setStatus($status, $msgTitle, $msgType); } }
/** * Build the form * * @access public * * @return void */ function buildQuickForm($form, $proxSearch) { // is proximity search required (2) or optional (1)? $proxRequired = $proxSearch == 2 ? TRUE : FALSE; $form->assign('proximity_search', TRUE); $form->add('text', 'prox_street_address', ts('Street Address'), NULL, FALSE); $form->add('text', 'prox_city', ts('City'), NULL, FALSE); $form->add('text', 'prox_postal_code', ts('Postal Code'), NULL, FALSE); $defaults = self::setDefaultValues($form); if (CRM_Utils_Array::value('prox_country_id', $defaults)) { $stateProvince = array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvinceForCountry($defaults['prox_country_id']); } else { $stateProvince = array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvince(); } $form->add('select', 'prox_state_province_id', ts('State/Province'), $stateProvince, $proxRequired); $country = array('' => ts('- select -')) + CRM_Core_PseudoConstant::country(); $form->add('select', 'prox_country_id', ts('Country'), $country, $proxRequired); $form->add('text', 'prox_distance', ts('Distance'), NULL, $proxRequired); $proxUnits = array('km' => ts('km'), 'miles' => ts('miles')); $form->add('select', 'prox_distance_unit', ts('Units'), $proxUnits, $proxRequired); // prox_distance_unit // state country js, CRM-5233 $stateCountryMap = array(); $stateCountryMap[] = array('state_province' => 'prox_state_province_id', 'country' => 'prox_country_id'); CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap); CRM_Core_BAO_Address::fixAllStateSelects($this, $defaults); $form->addFormRule(array('CRM_Contact_Form_Task_ProximityCommon', 'formRule'), $form); }
/** * Function to actually build the form * * @return void * @access public */ public function buildQuickForm() { $this->assignToTemplate(); $params = $this->_params; $honor_block_is_active = $this->get('honor_block_is_active'); // make sure we have values for it if ($honor_block_is_active && !empty($params['soft_credit_type_id'])) { $honorName = null; $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE); $this->assign('honor_block_is_active', $honor_block_is_active); $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]); CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($this, $params['honor'], $params['honoree_profile_id']); $fieldTypes = array('Contact'); $fieldTypes[] = CRM_Core_BAO_UFGroup::getContactType($params['honoree_profile_id']); $this->buildCustom($params['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes); } $this->assign('receiptFromEmail', CRM_Utils_Array::value('receipt_from_email', $this->_values)); $amount_block_is_active = $this->get('amount_block_is_active'); $this->assign('amount_block_is_active', $amount_block_is_active); if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') { $option = CRM_Utils_Array::value('options_' . $params['selectProduct'], $params); $productID = $params['selectProduct']; CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE, $productID, $option); $this->set('productID', $productID); $this->set('option', $option); } $config = CRM_Core_Config::singleton(); if (in_array('CiviMember', $config->enableComponents)) { if (isset($params['selectMembership']) && $params['selectMembership'] != 'no_thanks') { CRM_Member_BAO_Membership::buildMembershipBlock($this, $this->_id, $this->_membershipContactID, FALSE, $params['selectMembership'], FALSE); } else { $this->assign('membershipBlock', FALSE); } } $this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE); $this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE); if (!empty($params['hidden_onbehalf_profile'])) { $ufJoinParams = array('module' => 'onBehalf', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $this->_id); $OnBehalfProfile = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams); $profileId = $OnBehalfProfile[0]; $fieldTypes = array('Contact', 'Organization'); $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization'); $fieldTypes = array_merge($fieldTypes, $contactSubType); if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) { $fieldTypes = array_merge($fieldTypes, array('Membership')); } else { $fieldTypes = array_merge($fieldTypes, array('Contribution')); } $this->buildCustom($profileId, 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes); } $this->_separateMembershipPayment = $this->get('separateMembershipPayment'); $this->assign('is_separate_payment', $this->_separateMembershipPayment); if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) { $this->assign('lineItem', $this->_lineItem); } else { $this->assign('is_quick_config', 1); $this->_params['is_quick_config'] = 1; } $this->assign('priceSetID', $this->_priceSetId); $paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(false, null, 'name'); if ($this->_paymentProcessor && $this->_paymentProcessor['payment_processor_type_id'] == CRM_Utils_Array::key('Google_Checkout', $paymentProcessorType) && !$this->_params['is_pay_later'] && !($this->_amount == 0)) { $this->_checkoutButtonName = $this->getButtonName('next', 'checkout'); $this->add('image', $this->_checkoutButtonName, $this->_paymentProcessor['url_button'], array('class' => 'form-submit')); $this->addButtons(array(array('type' => 'back', 'name' => ts('<< Go Back')))); } else { if ($this->_contributeMode == 'notify' || !$this->_values['is_monetary'] || $this->_amount <= 0.0 || $this->_params['is_pay_later'] || $this->_separateMembershipPayment && $this->_amount <= 0.0) { $contribButton = ts('Continue >>'); $this->assign('button', ts('Continue')); } else { $contribButton = ts('Make Contribution'); $this->assign('button', ts('Make Contribution')); } $this->addButtons(array(array('type' => 'next', 'name' => $contribButton, 'spacing' => ' ', 'isDefault' => TRUE, 'js' => array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');")), array('type' => 'back', 'name' => ts('Go Back')))); } $defaults = array(); $fields = array(); foreach ($this->_fields as $name => $dontCare) { if ($name != 'onbehalf' || $name != 'honor') { $fields[$name] = 1; } } $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1; $contact = $this->_params; foreach ($fields as $name => $dontCare) { if (isset($contact[$name])) { $defaults[$name] = $contact[$name]; if (substr($name, 0, 7) == 'custom_') { $timeField = "{$name}_time"; if (isset($contact[$timeField])) { $defaults[$timeField] = $contact[$timeField]; } if (isset($contact["{$name}_id"])) { $defaults["{$name}_id"] = $contact["{$name}_id"]; } } elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting')) && !empty($contact[$name . '_custom'])) { $defaults[$name . '_custom'] = $contact[$name . '_custom']; } } } $this->assign('useForMember', $this->get('useForMember')); // now fix all state country selectors CRM_Core_BAO_Address::fixAllStateSelects($this, $defaults); $this->setDefaults($defaults); $this->freeze(); }
/** * format common params data to proper format to store. * * @param array $params contain record values. * @param array $formatted array of formatted data. * @param array $contactFields contact DAO fields. * @static */ function formatCommonData($params, &$formatted, &$contactFields) { $csType = array(CRM_Utils_Array::value('contact_type', $formatted)); //CRM-5125 //add custom fields for contact sub type if (!empty($this->_contactSubType)) { $csType = $this->_contactSubType; } if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $formatted)) { $csType = $relCsType; } $customFields = CRM_Core_BAO_CustomField::getFields($formatted['contact_type'], false, false, $csType); //if a Custom Email Greeting, Custom Postal Greeting or Custom Addressee is mapped, and no "Greeting / Addressee Type ID" is provided, then automatically set the type = Customized, CRM-4575 $elements = array('email_greeting_custom' => 'email_greeting', 'postal_greeting_custom' => 'postal_greeting', 'addressee_custom' => 'addressee'); foreach ($elements as $k => $v) { if (array_key_exists($k, $params) && !array_key_exists($v, $params)) { $label = key(CRM_Core_OptionGroup::values($v, true, null, null, 'AND v.name = "Customized"')); $params[$v] = $label; } } //format date first $session =& CRM_Core_Session::singleton(); $dateType = $session->get("dateTypes"); foreach ($params as $key => $val) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { //we should not update Date to null, CRM-4062 if ($val && $customFields[$customFieldID]['data_type'] == 'Date') { self::formatCustomDate($params, $formatted, $dateType, $key); unset($params[$key]); } else { if ($customFields[$customFieldID]['data_type'] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } } if ($key == 'birth_date' && $val) { CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key); } else { if ($key == 'deceased_date' && $val) { CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key); } else { if ($key == 'is_deceased' && $val) { $params[$key] = CRM_Utils_String::strtoboolstr($val); } else { if ($key == 'gender') { //CRM-4360 $params[$key] = $this->checkGender($val); } } } } } //now format custom data. 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) { // check if $value does not contain IM provider or phoneType if (($name !== 'phone_type_id' || $name !== 'provider_id') && ($testForEmpty === '' || $testForEmpty == null)) { $break = true; break; } } } else { $break = true; } if (!$break) { _civicrm_add_formatted_param($value, $formatted); } } continue; } $formatValues = array($key => $field); if ($key !== 'preferred_communication_method' && array_key_exists($key, $contactFields)) { // due to merging of individual table and // contact table, we need to avoid // preferred_communication_method forcefully $formatValues['contact_type'] = $formatted['contact_type']; } if ($key == 'id' && isset($field)) { $formatted[$key] = $field; } _civicrm_add_formatted_param($formatValues, $formatted); //Handling Custom Data if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) && array_key_exists($customFieldID, $customFields)) { //get the html type. $type = $customFields[$customFieldID]['html_type']; switch ($type) { case 'CheckBox': case 'AdvMulti-Select': case 'Multi-Select': $mulValues = explode(',', $field); $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true); $formatted[$key] = array(); foreach ($mulValues as $v1) { foreach ($customOption as $v2) { if (strtolower($v2['label']) == strtolower(trim($v1)) || strtolower($v2['value']) == strtolower(trim($v1))) { if ($type == 'CheckBox') { $formatted[$key][$v2['value']] = 1; } else { $formatted[$key][] = $v2['value']; } } } } break; case 'Select': case 'Radio': $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true); foreach ($customOption as $v2) { if (strtolower($v2['label']) == strtolower(trim($field)) || strtolower($v2['value']) == strtolower(trim($field))) { $formatted[$key] = $v2['value']; } } break; case 'Multi-Select State/Province': $mulValues = explode(',', $field); $stateAbbr = CRM_Core_PseudoConstant::stateProvinceAbbreviation(); $stateName = CRM_Core_PseudoConstant::stateProvince(); $formatted[$key] = $stateValues = array(); foreach ($mulValues as $values) { if ($val = CRM_Utils_Array::key($values, $stateAbbr)) { $formatted[$key][] = $val; } else { if ($val = CRM_Utils_Array::key($values, $stateName)) { $formatted[$key][] = $val; } } } break; case 'Multi-Select Country': $config =& CRM_Core_Config::singleton(); $limitCodes = $config->countryLimit(); $mulValues = explode(',', $field); $formatted[$key] = array(); CRM_Core_PseudoConstant::populate($countryNames, 'CRM_Core_DAO_Country', true, 'name', 'is_active'); CRM_Core_PseudoConstant::populate($countryIsoCodes, 'CRM_Core_DAO_Country', true, 'iso_code'); foreach ($mulValues as $values) { if ($val = CRM_Utils_Array::key($values, $countryNames)) { $formatted[$key][] = $val; } else { if ($val = CRM_Utils_Array::key($values, $countryIsoCodes)) { $formatted[$key][] = $val; } else { if ($val = CRM_Utils_Array::key($values, $limitCodes)) { $formatted[$key][] = $val; } } } } break; } } } // check for primary location type, whether it is already present for the contact or not, CRM-4423 if (CRM_Utils_Array::value('id', $formatted) && isset($formatted['location'])) { $primaryLocationTypeId = CRM_Contact_BAO_Contact::getPrimaryLocationType($formatted['id'], true); if (isset($primaryLocationTypeId)) { foreach ($formatted['location'] as $loc => $details) { if ($primaryLocationTypeId == CRM_Utils_Array::value('location_type_id', $details)) { $formatted['location'][$loc]['is_primary'] = 1; break; } else { $formatted['location'][$loc]['is_primary'] = 0; } } } } // parse street address, CRM-5450 if ($this->_parseStreetAddress) { require_once 'CRM/Core/BAO/Address.php'; if (array_key_exists('address', $formatted) && is_array($formatted['address'])) { foreach ($formatted['address'] as $instance => &$address) { $streetAddress = CRM_Utils_Array::value('street_address', $address); if (empty($streetAddress)) { continue; } // parse address field. $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($streetAddress); //street address consider to be parsed properly, //If we get street_name and street_number. if (!CRM_Utils_Array::value('street_name', $parsedFields) || !CRM_Utils_Array::value('street_number', $parsedFields)) { $parsedFields = array_fill_keys(array_keys($parsedFields), ''); } // merge parse address w/ main address block. $address = array_merge($address, $parsedFields); } } } }
/** * This function sets the default values for the form. MobileProvider that in edit/view mode * the default values are retrieved from the database * * @access public * * @return None */ public function setDefaultValues() { if ($this->_cdType) { return CRM_Custom_Form_CustomData::setDefaultValues($this); } if ($this->_priceSetId) { return CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $defaults); } $defaults = parent::setDefaultValues(); //setting default join date and receive date list($now, $currentTime) = CRM_Utils_Date::setDateDefaults(); if ($this->_action == CRM_Core_Action::ADD) { $defaults['receive_date'] = $now; $defaults['receive_date_time'] = $currentTime; } if (is_numeric($this->_memType)) { $defaults['membership_type_id'] = array(); $defaults['membership_type_id'][0] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'member_of_contact_id', 'id'); $defaults['membership_type_id'][1] = $this->_memType; } else { $defaults['membership_type_id'] = $this->_memType; } $defaults['num_terms'] = 1; if (CRM_Utils_Array::value('id', $defaults)) { if ($this->_onlinePendingContributionId) { $defaults['record_contribution'] = $this->_onlinePendingContributionId; } else { $contributionId = CRM_Core_DAO::singleValueQuery("\n SELECT contribution_id\n FROM civicrm_membership_payment\n WHERE membership_id = {$this->_id}\n ORDER BY contribution_id\n DESC limit 1"); if ($contributionId) { $defaults['record_contribution'] = $contributionId; } } } if (CRM_Utils_Array::value('record_contribution', $defaults) && !$this->_mode) { $contributionParams = array('id' => $defaults['record_contribution']); $contributionIds = array(); //keep main object campaign in hand. $memberCampaignId = CRM_Utils_Array::value('campaign_id', $defaults); CRM_Contribute_BAO_Contribution::getValues($contributionParams, $defaults, $contributionIds); //get back original object campaign id. $defaults['campaign_id'] = $memberCampaignId; if (CRM_Utils_Array::value('receive_date', $defaults)) { list($defaults['receive_date']) = CRM_Utils_Date::setDateDefaults($defaults['receive_date']); } // Contribution::getValues() over-writes the membership record's source field value - so we need to restore it. if (CRM_Utils_Array::value('membership_source', $defaults)) { $defaults['source'] = $defaults['membership_source']; } } //CRM-13420 if (!CRM_Utils_Array::value('payment_instrument_id', $defaults)) { $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1')); } // User must explicitly choose to send a receipt in both add and update mode. $defaults['send_receipt'] = 0; if ($this->_action & CRM_Core_Action::UPDATE) { // in this mode by default uncheck this checkbox unset($defaults['record_contribution']); } if (CRM_Utils_Array::value('id', $defaults)) { $subscriptionCancelled = CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_id); } $alreadyAutoRenew = FALSE; if (CRM_Utils_Array::value('contribution_recur_id', $defaults) && !$subscriptionCancelled) { $defaults['auto_renew'] = 1; $alreadyAutoRenew = TRUE; } $this->assign('alreadyAutoRenew', $alreadyAutoRenew); $this->assign('member_is_test', CRM_Utils_Array::value('member_is_test', $defaults)); $this->assign('membership_status_id', CRM_Utils_Array::value('status_id', $defaults)); if (CRM_Utils_Array::value('is_pay_later', $defaults)) { $this->assign('is_pay_later', TRUE); } if ($this->_mode) { // set default country from config if no country set $config = CRM_Core_Config::singleton(); if (!CRM_Utils_Array::value("billing_country_id-{$this->_bltID}", $defaults)) { $defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry; } if (!CRM_Utils_Array::value("billing_state_province_id-{$this->_bltID}", $defaults)) { $defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince; } $billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID); $defaults = array_merge($defaults, $billingDefaults); // now fix all state country selectors, set correct state based on country CRM_Core_BAO_Address::fixAllStateSelects($this, $defaults); // // hack to simplify credit card entry for testing // $defaults['credit_card_type'] = 'Visa'; // $defaults['credit_card_number'] = '4807731747657838'; // $defaults['cvv2'] = '000'; // $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' ); } $dates = array('join_date', 'start_date', 'end_date'); foreach ($dates as $key) { if (CRM_Utils_Array::value($key, $defaults)) { list($defaults[$key]) = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value($key, $defaults)); } } //setting default join date if there is no join date if (!CRM_Utils_Array::value('join_date', $defaults)) { $defaults['join_date'] = $now; } if (CRM_Utils_Array::value('membership_end_date', $defaults)) { $this->assign('endDate', $defaults['membership_end_date']); } return $defaults; }
public static function getAddressDisplay() { $contactId = CRM_Utils_Request::retrieve('contact_id', 'Positive', CRM_Core_DAO::$_nullObject); if (!$contactId) { $addressVal["error_message"] = "no contact id found"; } else { $entityBlock = array('contact_id' => $contactId, 'entity_id' => $contactId); $addressVal = CRM_Core_BAO_Address::getValues($entityBlock); } CRM_Utils_JSON::output($addressVal); }
/** * Parse given street address string in to street_name, * street_unit, street_number and street_number_suffix * eg "54A Excelsior Ave. Apt 1C", or "917 1/2 Elm Street" * * NB: civic street formats for en_CA and fr_CA used by default if those locales are active * otherwise en_US format is default action * * @param string $streetAddress * Street address including number and apt. * @param string $locale * Locale used to parse address. * * @return array * parsed fields values. */ public static function parseStreetAddress($streetAddress, $locale = NULL) { $config = CRM_Core_Config::singleton(); /* locales supported include: * en_US - http://pe.usps.com/cpim/ftp/pubs/pub28/pub28.pdf * en_CA - http://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp * fr_CA - http://www.canadapost.ca/tools/pg/manual/PGaddress-f.asp * NB: common use of comma after street number also supported * default is en_US */ $supportedLocalesForParsing = array('en_US', 'en_CA', 'fr_CA'); if (!$locale) { $locale = $config->lcMessages; } // as different locale explicitly requested but is not available, display warning message and set $locale = 'en_US' if (!in_array($locale, $supportedLocalesForParsing)) { CRM_Core_Session::setStatus(ts('Unsupported locale specified to parseStreetAddress: %1. Proceeding with en_US locale.', array(1 => $locale)), ts('Unsupported Locale'), 'alert'); $locale = 'en_US'; } $emptyParseFields = $parseFields = array('street_name' => '', 'street_unit' => '', 'street_number' => '', 'street_number_suffix' => ''); if (empty($streetAddress)) { return $parseFields; } $streetAddress = trim($streetAddress); $matches = array(); if (in_array($locale, array('en_CA', 'fr_CA')) && preg_match('/^([A-Za-z0-9]+)[ ]*\\-[ ]*/', $streetAddress, $matches)) { $parseFields['street_unit'] = $matches[1]; // unset from rest of street address $streetAddress = preg_replace('/^([A-Za-z0-9]+)[ ]*\\-[ ]*/', '', $streetAddress); } // get street number and suffix. $matches = array(); //alter street number/suffix handling so that we accept -digit if (preg_match('/^[A-Za-z0-9]+([\\S]+)/', $streetAddress, $matches)) { // check that $matches[0] is numeric, else assume no street number if (preg_match('/^(\\d+)/', $matches[0])) { $streetNumAndSuffix = $matches[0]; // get street number. $matches = array(); if (preg_match('/^(\\d+)/', $streetNumAndSuffix, $matches)) { $parseFields['street_number'] = $matches[0]; $suffix = preg_replace('/^(\\d+)/', '', $streetNumAndSuffix); $parseFields['street_number_suffix'] = trim($suffix); } // unset from main street address. $streetAddress = preg_replace('/^[A-Za-z0-9]+([\\S]+)/', '', $streetAddress); $streetAddress = trim($streetAddress); } } elseif (preg_match('/^(\\d+)/', $streetAddress, $matches)) { $parseFields['street_number'] = $matches[0]; // unset from main street address. $streetAddress = preg_replace('/^(\\d+)/', '', $streetAddress); $streetAddress = trim($streetAddress); } // suffix might be like 1/2 $matches = array(); if (preg_match('/^\\d\\/\\d/', $streetAddress, $matches)) { $parseFields['street_number_suffix'] .= $matches[0]; // unset from main street address. $streetAddress = preg_replace('/^\\d+\\/\\d+/', '', $streetAddress); $streetAddress = trim($streetAddress); } // now get the street unit. // supportable street unit formats. $streetUnitFormats = array('APT', 'APARTMENT', 'BSMT', 'BASEMENT', 'BLDG', 'BUILDING', 'DEPT', 'DEPARTMENT', 'FL', 'FLOOR', 'FRNT', 'FRONT', 'HNGR', 'HANGER', 'LBBY', 'LOBBY', 'LOWR', 'LOWER', 'OFC', 'OFFICE', 'PH', 'PENTHOUSE', 'TRLR', 'TRAILER', 'UPPR', 'RM', 'ROOM', 'SIDE', 'SLIP', 'KEY', 'LOT', 'PIER', 'REAR', 'SPC', 'SPACE', 'STOP', 'STE', 'SUITE', 'UNIT', '#'); // overwriting $streetUnitFormats for 'en_CA' and 'fr_CA' locale if (in_array($locale, array('en_CA', 'fr_CA'))) { $streetUnitFormats = array('APT', 'APP', 'SUITE', 'BUREAU', 'UNIT'); } //@todo per CRM-14459 this regex picks up words with the string in them - e.g APT picks up //Captain - presuming fixing regex (& adding test) to ensure a-z does not preced string will fix $streetUnitPreg = '/(' . implode('|\\s', $streetUnitFormats) . ')(.+)?/i'; $matches = array(); if (preg_match($streetUnitPreg, $streetAddress, $matches)) { $parseFields['street_unit'] = trim($matches[0]); $streetAddress = str_replace($matches[0], '', $streetAddress); $streetAddress = trim($streetAddress); } // consider remaining string as street name. $parseFields['street_name'] = $streetAddress; //run parsed fields through stripSpaces to clean foreach ($parseFields as $parseField => $value) { $parseFields[$parseField] = CRM_Utils_String::stripSpaces($value); } //CRM-14459 if the field is too long we should assume it didn't get it right & skip rather than allow // the DB to fatal $fields = CRM_Core_BAO_Address::fields(); foreach ($fields as $fieldname => $field) { if (!empty($field['maxlength']) && strlen(CRM_Utils_Array::value($fieldname, $parseFields)) > $field['maxlength']) { return $emptyParseFields; } } return $parseFields; }
/** * Function to create address associated with contribution record. * @param array $params an associated array * @param int $billingID $billingLocationTypeID * * @return address id * @static */ static function createAddress(&$params, $billingLocationTypeID) { $billingFields = array("street_address", "city", "state_province_id", "postal_code", "country_id"); //build address array $addressParams = array(); $addressParams['location_type_id'] = $billingLocationTypeID; $addressParams['is_billing'] = 1; $addressParams['address_name'] = "{$params['billing_first_name']}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$params['billing_middle_name']}" . CRM_Core_DAO::VALUE_SEPARATOR . "{$params['billing_last_name']}"; foreach ($billingFields as $value) { $addressParams[$value] = $params["billing_{$value}-{$billingLocationTypeID}"]; } require_once "CRM/Core/BAO/Address.php"; $address = CRM_Core_BAO_Address::add($addressParams, false); return $address->id; }
/** * Function handles shared contact address processing. * In this function we just modify submitted values so that new address created for the user * has same address as shared contact address. We copy the address so that search etc will be * much efficient. * * @param array $address * This is associated array which contains submitted form values. */ public static function processSharedAddress(&$address) { if (!is_array($address)) { return; } // Sharing contact address during create mode is pretty straight forward. // In update mode we should check following: // - We should check if user has uncheck shared contact address // - If yes then unset the master_id or may be just delete the address that copied master // Normal update process will automatically create new address with submitted values // 1. loop through entire subnitted address array $masterAddress = array(); $skipFields = array('is_primary', 'location_type_id', 'is_billing', 'master_id'); foreach ($address as &$values) { // 2. check if master id exists, if not continue if (empty($values['master_id']) || empty($values['use_shared_address'])) { // we should unset master id when use uncheck share address for existing address $values['master_id'] = 'null'; continue; } // 3. get the address details for master_id $masterAddress = new CRM_Core_BAO_Address(); $masterAddress->id = CRM_Utils_Array::value('master_id', $values); $masterAddress->find(TRUE); // 4. modify submitted params and update it with shared contact address // make sure you preserve specific form values like location type, is_primary_ is_billing, master_id // CRM-10336: Also empty any fields from the existing address block if they don't exist in master (otherwise they will persist) foreach ($values as $field => $submittedValue) { if (!in_array($field, $skipFields)) { if (isset($masterAddress->{$field})) { $values[$field] = $masterAddress->{$field}; } else { $values[$field] = ''; } } } //5. modify the params to include county_id if it exist in master contact. // CRM-16152: This is a hack since QF does not submit disabled field. if (!empty($masterAddress->county_id) && empty($values['county_id'])) { $values['county_id'] = $masterAddress->county_id; } } }
/** * Add the custom fields. * * @param int $id * @param string $name * @param bool $viewOnly */ public function buildCustom($id, $name, $viewOnly = FALSE) { if ($id) { $button = substr($this->controller->getButtonName(), -4); $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this); $session = CRM_Core_Session::singleton(); $contactID = $session->get('userID'); // we don't allow conflicting fields to be // configured via profile $fieldsToIgnore = array('participant_fee_amount' => 1, 'participant_fee_level' => 1); if ($contactID) { //FIX CRM-9653 if (is_array($id)) { $fields = array(); foreach ($id as $profileID) { $field = CRM_Core_BAO_UFGroup::getFields($profileID, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, 'field_name', TRUE); $fields = array_merge($fields, $field); } } else { if (CRM_Core_BAO_UFGroup::filterUFGroups($id, $contactID)) { $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, 'field_name', TRUE); } } } else { $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, 'field_name', TRUE); } if (array_intersect_key($fields, $fieldsToIgnore)) { $fields = array_diff_key($fields, $fieldsToIgnore); CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.')); } $addCaptcha = FALSE; if (!empty($this->_fields)) { $fields = @array_diff_assoc($fields, $this->_fields); } if (empty($this->_params[0]['additional_participants']) && is_null($cid)) { CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID); } $this->assign($name, $fields); if (is_array($fields)) { foreach ($fields as $key => $field) { if ($viewOnly && isset($field['data_type']) && $field['data_type'] == 'File' || $viewOnly && $field['name'] == 'image_URL') { // ignore file upload fields continue; } //make the field optional if primary participant //have been skip the additional participant. if ($button == 'skip') { $field['is_required'] = FALSE; } elseif ($field['add_captcha'] && !$contactID) { // only add captcha for first page $addCaptcha = TRUE; } list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2); CRM_Core_BAO_UFGroup::buildProfile($this, $field, CRM_Profile_Form::MODE_CREATE, $contactID, TRUE); $this->_fields[$key] = $field; } } if ($addCaptcha && !$viewOnly) { $captcha = CRM_Utils_ReCAPTCHA::singleton(); $captcha->add($this); $this->assign('isCaptcha', TRUE); } } }
/** * Parse street address. * * @param array $contactValues * Contact values. * @param CRM_Core_Form $form * Form object. */ public static function parseStreetAddress(&$contactValues, &$form) { if (!is_array($contactValues) || !is_array($form->_fields)) { return; } static $parseAddress; $addressFldKey = 'street_address'; if (!isset($parseAddress)) { $parseAddress = FALSE; foreach ($form->_fields as $key => $fld) { if (strpos($key, $addressFldKey) !== FALSE) { $parseAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options'), FALSE); break; } } } if (!$parseAddress) { return; } $allParseValues = array(); foreach ($contactValues as $key => $value) { if (strpos($key, $addressFldKey) !== FALSE) { $locTypeId = substr($key, strlen($addressFldKey) + 1); // parse address field. $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($value); //street address consider to be parsed properly, //If we get street_name and street_number. if (empty($parsedFields['street_name']) || empty($parsedFields['street_number'])) { $parsedFields = array_fill_keys(array_keys($parsedFields), ''); } //merge parse values. foreach ($parsedFields as $fldKey => $parseVal) { if ($locTypeId) { $fldKey .= "-{$locTypeId}"; } $allParseValues[$fldKey] = $parseVal; } } } //finally merge all parse values if (!empty($allParseValues)) { $contactValues += $allParseValues; } }