/** * @inheritDoc */ protected function buildWhereClause() { foreach ($this->where as $key => $value) { $table_name = NULL; $column_name = NULL; $field = $this->getField($key); if (in_array($key, $this->entityFieldNames)) { $table_name = self::MAIN_TABLE_ALIAS; $column_name = $key; } elseif (($cf_id = \CRM_Core_BAO_CustomField::getKeyID($key)) != FALSE) { //list($table_name, $column_name) = $this->addCustomField($this->apiFieldSpec['custom_' . $cf_id], 'INNER'); } elseif (strpos($key, '.')) { $fkInfo = $this->addFkField($key, 'INNER'); if ($fkInfo) { list($table_name, $column_name) = $fkInfo; $this->validateNestedInput($key, $value); } } if (!$table_name || !$column_name || is_null($value)) { throw new \API_Exception("Invalid field '{$key}' in where clause."); } if (!is_array($value)) { $this->query->where(array("`{$table_name}`.`{$column_name}` = @value"), array("@value" => $value)); } elseif (count($value) !== 1) { throw new \API_Exception("Invalid value in where clause for field '{$key}'"); } else { $clause = \CRM_Core_DAO::createSQLFilter("`{$table_name}`.`{$column_name}`", $value); if ($clause === NULL) { throw new \API_Exception("Invalid value in where clause for field '{$key}'"); } $this->query->where($clause); } } }
/** * Set the default form values * * @access protected * * @return array the default array reference */ function setDefaultValues() { $defaults = array(); $stateCountryMap = array(); foreach ($this->_fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($field['name'])) { CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $defaults, NULL, CRM_Profile_Form::MODE_REGISTER); } //CRM-5403 if (substr($name, 0, 14) === 'state_province' || substr($name, 0, 7) === 'country' || substr($name, 0, 6) === 'county') { list($fieldName, $index) = CRM_Utils_System::explode('-', $name, 2); if (!array_key_exists($index, $stateCountryMap)) { $stateCountryMap[$index] = array(); } $stateCountryMap[$index][$fieldName] = $name; } } // also take care of state country widget if (!empty($stateCountryMap)) { CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap, $defaults); } //set default for country. CRM_Core_BAO_UFGroup::setRegisterDefaults($this->_fields, $defaults); // now fix all state country selectors CRM_Core_BAO_Address::fixAllStateSelects($this, $defaults); return $defaults; }
/** * Set the default form values. * * * @return array * the default array reference */ public function setDefaultValues() { $defaults = array(); foreach ($this->_fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($field['name'])) { CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $defaults, NULL, CRM_Profile_Form::MODE_REGISTER); } } //set default for country. CRM_Core_BAO_UFGroup::setRegisterDefaults($this->_fields, $defaults); return $defaults; }
function setDefaultValues() { $defaults = array(); $profileFields = CRM_Core_BAO_UFGroup::getFields($this->_profileID); $contactID = $this->_contactID; $entityCaseID = NULL; $cases = CRM_Case_BAO_Case::retrieveCaseIdsByContactId($contactID, FALSE, 'Application'); $entityCaseID = end($cases); if ($contactID) { $options = array(); $fields = array(); foreach ($profileFields as $name => $field) { if (substr($name, 0, 7) == 'custom_') { $id = substr($name, 7); if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) { if ($entityCaseID) { CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $defaults, $entityCaseID, CRM_Profile_Form::MODE_REGISTER); } if (!isset($defaults[$name])) { CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $defaults, $contactID, CRM_Profile_Form::MODE_REGISTER); } $htmlType = $field['html_type']; if ($htmlType == 'File') { $this->assign('customname', $name); $entityId = $entityCaseID; $url = CRM_Core_BAO_CustomField::getFileURL($entityId, $customFieldID); if ($url) { $customFiles[$field['name']]['displayURL'] = ts("Attached File") . ": {$url['file_url']}"; $deleteExtra = ts("Are you sure you want to delete attached file?"); $fileId = $url['file_id']; $session = CRM_Core_Session::singleton(); $session->pushUserContext(CRM_Utils_System::url('civicrm/vacancy/apply', "reset=1&id={$this->_id}&cid={$contactID}")); $deleteURL = CRM_Utils_System::url('civicrm/file', "reset=1&id={$fileId}&eid={$entityId}&fid={$customFieldID}&action=delete"); $text = ts("Delete Attached File"); $customFiles[$field['name']]['deleteURL'] = "<a href=\"{$deleteURL}\" onclick = \"if (confirm( ' {$deleteExtra} ' )) this.href+='&confirmed=1'; else return false;\">{$text}</a>"; $this->assign('customFiles', $customFiles); } } } } else { $fields[$name] = 1; } } CRM_Core_BAO_UFGroup::setProfileDefaults($contactID, $fields, $defaults); } return $defaults; }
/** * Build the form object. */ public function buildQuickForm() { $ufGroupId = $this->get('ufGroupId'); if (!$ufGroupId) { CRM_Core_Error::fatal('ufGroupId is missing'); } $this->_title = ts('Update multiple contacts') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId); CRM_Utils_System::setTitle($this->_title); $this->addDefaultButtons(ts('Save')); $this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW); // remove file type field and then limit fields $suppressFields = FALSE; $removehtmlTypes = array('File', 'Autocomplete-Select'); foreach ($this->_fields as $name => $field) { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && in_array($this->_fields[$name]['html_type'], $removehtmlTypes)) { $suppressFields = TRUE; unset($this->_fields[$name]); } } //FIX ME: phone ext field is added at the end and it gets removed because of below code //$this->_fields = array_slice($this->_fields, 0, $this->_maxFields); $this->addButtons(array(array('type' => 'submit', 'name' => ts('Update Contact(s)'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel')))); $this->assign('profileTitle', $this->_title); $this->assign('componentIds', $this->_contactIds); // if below fields are missing we should not reset sort name / display name // CRM-6794 $preserveDefaultsArray = array('first_name', 'last_name', 'middle_name', 'organization_name', 'prefix_id', 'suffix_id', 'household_name'); foreach ($this->_contactIds as $contactId) { $profileFields = $this->_fields; CRM_Core_BAO_Address::checkContactSharedAddressFields($profileFields, $contactId); foreach ($profileFields as $name => $field) { CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $contactId); if (in_array($field['name'], $preserveDefaultsArray)) { $this->_preserveDefault = FALSE; } } } $this->assign('fields', $this->_fields); // don't set the status message when form is submitted. $buttonName = $this->controller->getButtonName('submit'); if ($suppressFields && $buttonName != '_qf_BatchUpdateProfile_next') { CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple contacts."), ts('Some Fields Excluded'), 'info'); } $this->addDefaultButtons(ts('Update Contacts')); $this->addFormRule(array('CRM_Contact_Form_Task_Batch', 'formRule')); }
function setDefaultValues() { if (!$this->_donorID) { return; } foreach ($this->_fields as $name => $dontcare) { $fields[$name] = 1; } require_once "CRM/Core/BAO/UFGroup.php"; CRM_Core_BAO_UFGroup::setProfileDefaults($this->_donorID, $fields, $this->_defaults); //set custom field defaults require_once "CRM/Core/BAO/CustomField.php"; foreach ($this->_fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) { if (!isset($this->_defaults[$name])) { CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $this->_defaults, NULL, CRM_Profile_Form::MODE_REGISTER); } } } return $this->_defaults; }
/** * Set the default values. */ public function setDefaultValues() { // check if the user is registered and we have a contact ID $contactID = $this->getContactID(); if (!empty($contactID)) { $fields = array(); $removeCustomFieldTypes = array('Contribution', 'Membership'); $contribFields = CRM_Contribute_BAO_Contribution::getContributionFields(); // remove component related fields foreach ($this->_fields as $name => $dontCare) { //don't set custom data Used for Contribution (CRM-1344) if (substr($name, 0, 7) == 'custom_') { $id = substr($name, 7); if (!CRM_Core_BAO_CustomGroup::checkCustomField($id, $removeCustomFieldTypes)) { continue; } // ignore component fields } elseif (array_key_exists($name, $contribFields) || substr($name, 0, 11) == 'membership_' || substr($name, 0, 13) == 'contribution_') { continue; } $fields[$name] = 1; } if (!empty($fields)) { CRM_Core_BAO_UFGroup::setProfileDefaults($contactID, $fields, $this->_defaults); } $billingDefaults = $this->getProfileDefaults('Billing', $contactID); $this->_defaults = array_merge($this->_defaults, $billingDefaults); } if (!empty($this->_ccid) && !empty($this->_pendingAmount)) { $this->_defaults['total_amount'] = CRM_Utils_Money::format($this->_pendingAmount, NULL, '%a'); } /* * hack to simplify credit card entry for testing * * $this->_defaults['credit_card_type'] = 'Visa'; * $this->_defaults['amount'] = 168; * $this->_defaults['credit_card_number'] = '4111111111111111'; * $this->_defaults['cvv2'] = '000'; * $this->_defaults['credit_card_exp_date'] = array('Y' => date('Y')+1, 'M' => '05'); * // hack to simplify direct debit entry for testing * $this->_defaults['account_holder'] = 'Max Müller'; * $this->_defaults['bank_account_number'] = '12345678'; * $this->_defaults['bank_identification_number'] = '12030000'; * $this->_defaults['bank_name'] = 'Bankname'; */ //build set default for pledge overdue payment. if (!empty($this->_values['pledge_id'])) { //used to record completed pledge payment ids used later for honor default $completedContributionIds = array(); $pledgePayments = CRM_Pledge_BAO_PledgePayment::getPledgePayments($this->_values['pledge_id']); $paymentAmount = 0; $duePayment = FALSE; foreach ($pledgePayments as $payId => $value) { if ($value['status'] == 'Overdue') { $this->_defaults['pledge_amount'][$payId] = 1; $paymentAmount += $value['scheduled_amount']; } elseif (!$duePayment && $value['status'] == 'Pending') { $this->_defaults['pledge_amount'][$payId] = 1; $paymentAmount += $value['scheduled_amount']; $duePayment = TRUE; } elseif ($value['status'] == 'Completed' && $value['contribution_id']) { $completedContributionIds[] = $value['contribution_id']; } } $this->_defaults['price_' . $this->_priceSetId] = $paymentAmount; if (count($completedContributionIds)) { $softCredit = array(); foreach ($completedContributionIds as $id) { $softCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id); } if (isset($softCredit['soft_credit'])) { $this->_defaults['soft_credit_type_id'] = $softCredit['soft_credit'][1]['soft_credit_type']; //since honoree profile fieldname of fields are prefixed with 'honor' //we need to reformat the fieldname to append prefix during setting default values CRM_Core_BAO_UFGroup::setProfileDefaults($softCredit['soft_credit'][1]['contact_id'], CRM_Core_BAO_UFGroup::getFields($this->_honoreeProfileId), $defaults); foreach ($defaults as $fieldName => $value) { $this->_defaults['honor[' . $fieldName . ']'] = $value; } } } } elseif (!empty($this->_values['pledge_block_id'])) { //set default to one time contribution. $this->_defaults['is_pledge'] = 0; } // to process Custom data that are appended to URL $getDefaults = CRM_Core_BAO_CustomGroup::extractGetParams($this, "'Contact', 'Individual', 'Contribution'"); $this->_defaults = array_merge($this->_defaults, $getDefaults); $config = CRM_Core_Config::singleton(); // set default country from config if no country set if (empty($this->_defaults["billing_country_id-{$this->_bltID}"])) { $this->_defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry; } // set default state/province from config if no state/province set if (empty($this->_defaults["billing_state_province_id-{$this->_bltID}"])) { $this->_defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince; } $entityId = $memtypeID = NULL; if ($this->_priceSetId) { if ($this->_useForMember && !empty($this->_currentMemberships) || $this->_defaultMemTypeId) { $selectedCurrentMemTypes = array(); foreach ($this->_priceSet['fields'] as $key => $val) { foreach ($val['options'] as $keys => $values) { $opMemTypeId = CRM_Utils_Array::value('membership_type_id', $values); $priceFieldName = 'price_' . $values['price_field_id']; $priceFieldValue = CRM_Price_BAO_PriceSet::getPriceFieldValueFromURL($this, $priceFieldName); if (!empty($priceFieldValue)) { CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $this->_defaults); // break here to prevent overwriting of default due to 'is_default' // option configuration or setting of current membership or // membership for related organization. // The value sent via URL get's higher priority. break; } elseif ($opMemTypeId && in_array($opMemTypeId, $this->_currentMemberships) && !in_array($opMemTypeId, $selectedCurrentMemTypes)) { CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults); $memtypeID = $selectedCurrentMemTypes[] = $values['membership_type_id']; } elseif (!empty($values['is_default']) && !$opMemTypeId && (!isset($this->_defaults[$priceFieldName]) || $val['html_type'] == 'CheckBox' && !isset($this->_defaults[$priceFieldName][$keys]))) { CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults); $memtypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_defaults[$priceFieldName], 'membership_type_id'); } } } $entityId = CRM_Utils_Array::value('id', CRM_Member_BAO_Membership::getContactMembership($contactID, $memtypeID, NULL)); } else { CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $this->_defaults); } } //set custom field defaults set by admin if value is not set if (!empty($this->_fields)) { //load default campaign from page. if (array_key_exists('contribution_campaign_id', $this->_fields)) { $this->_defaults['contribution_campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values); } //set custom field defaults foreach ($this->_fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) { if (!isset($this->_defaults[$name])) { CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $this->_defaults, $entityId, CRM_Profile_Form::MODE_REGISTER); } } } } if (!empty($this->_paymentProcessors)) { foreach ($this->_paymentProcessors as $pid => $value) { if (!empty($value['is_default'])) { $this->_defaults['payment_processor_id'] = $pid; } } } return $this->_defaults; }
/** * Build the form * * @access public * * @return void */ function buildQuickForm() { $ufGroupId = $this->get('ufGroupId'); if (!$ufGroupId) { CRM_Core_Error::fatal('ufGroupId is missing'); } $this->_title = ts('Batch Update for Events') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId); CRM_Utils_System::setTitle($this->_title); $this->addDefaultButtons(ts('Save')); $this->_fields = array(); $this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW); // remove file type field and then limit fields $suppressFields = FALSE; $removehtmlTypes = array('File', 'Autocomplete-Select'); foreach ($this->_fields as $name => $field) { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && in_array($this->_fields[$name]['html_type'], $removehtmlTypes)) { $suppressFields = TRUE; unset($this->_fields[$name]); } //fix to reduce size as we are using this field in grid if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) { //shrink class to "form-text-medium" $this->_fields[$name]['attributes']['size'] = 19; } } $this->_fields = array_slice($this->_fields, 0, $this->_maxFields); $this->addButtons(array(array('type' => 'submit', 'name' => ts('Update Participant(s)'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel')))); $this->assign('profileTitle', $this->_title); $this->assign('componentIds', $this->_participantIds); $fileFieldExists = FALSE; //load all campaigns. if (array_key_exists('participant_campaign_id', $this->_fields)) { $this->_componentCampaigns = array(); CRM_Core_PseudoConstant::populate($this->_componentCampaigns, 'CRM_Event_DAO_Participant', TRUE, 'campaign_id', 'id', ' id IN (' . implode(' , ', array_values($this->_participantIds)) . ' ) '); } //fix for CRM-2752 // get the option value for custom data type $this->_roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name'); $this->_eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name'); // build custom data getFields array $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_roleCustomDataTypeID); $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_eventNameCustomDataTypeID); $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)); $this->_customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields); foreach ($this->_participantIds as $participantId) { $roleId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participantId, 'role_id'); $eventId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participantId, 'event_id'); foreach ($this->_fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) { $customValue = CRM_Utils_Array::value($customFieldID, $this->_customFields); $entityColumnValue = array(); if (CRM_Utils_Array::value('extends_entity_column_value', $customValue)) { $entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customValue['extends_entity_column_value']); } $entityColumnValueRole = CRM_Utils_Array::value($roleId, $entityColumnValue); if ($this->_roleCustomDataTypeID == $customValue['extends_entity_column_id'] && $entityColumnValueRole) { CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId); } elseif ($this->_eventNameCustomDataTypeID == $customValue['extends_entity_column_id'] && $eventId == $entityColumnValueRole) { CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId); } elseif (CRM_Utils_System::isNull($entityColumnValueRole)) { CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId); } } else { if ($field['name'] == 'participant_role_id') { $field['is_multiple'] = TRUE; } // handle non custom fields CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId); } } } $this->assign('fields', $this->_fields); // don't set the status message when form is submitted. $buttonName = $this->controller->getButtonName('submit'); if ($suppressFields && $buttonName != '_qf_Batch_next') { CRM_Core_Session::setStatus("FILE or Autocomplete Select type field(s) in the selected profile are not supported for Batch Update and have been excluded."); } $this->addDefaultButtons(ts('Update Participant(s)')); }
/** * Handle the values in import mode. * * @param int $onDuplicate * The code for what action to take on duplicates. * @param array $values * The array of values belonging to this line. * * @return bool * the result of this processing */ public function import($onDuplicate, &$values) { // first make sure this is a valid line $response = $this->summary($values); if ($response != CRM_Import_Parser::VALID) { return $response; } $params =& $this->getActiveFieldParams(); $formatted = array('version' => 3); // don't add to recent items, CRM-4399 $formatted['skipRecentView'] = TRUE; //for date-Formats $session = CRM_Core_Session::singleton(); $dateType = $session->get('dateTypes'); $customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Contribution'; $customFields = CRM_Core_BAO_CustomField::getFields($customDataType); //CRM-10994 if (isset($params['total_amount']) && $params['total_amount'] == 0) { $params['total_amount'] = '0.00'; } foreach ($params as $key => $val) { if ($val) { switch ($key) { case 'receive_date': case 'cancel_date': case 'receipt_date': case 'thankyou_date': $params[$key] = CRM_Utils_Date::formatDate($params[$key], $dateType); break; case 'pledge_payment': $params[$key] = CRM_Utils_String::strtobool($val); break; } if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($customFields[$customFieldID]['data_type'] == 'Date') { CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key); unset($params[$key]); } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } } } //date-Format part ends static $indieFields = NULL; if ($indieFields == NULL) { $tempIndieFields = CRM_Contribute_DAO_Contribution::import(); $indieFields = $tempIndieFields; } $paramValues = array(); foreach ($params as $key => $field) { if ($field == NULL || $field === '') { continue; } $paramValues[$key] = $field; } //import contribution record according to select contact type if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP && (!empty($paramValues['contribution_contact_id']) || !empty($paramValues['external_identifier']))) { $paramValues['contact_type'] = $this->_contactType; } elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE && (!empty($paramValues['contribution_id']) || !empty($values['trxn_id']) || !empty($paramValues['invoice_id']))) { $paramValues['contact_type'] = $this->_contactType; } elseif (!empty($params['soft_credit'])) { $paramValues['contact_type'] = $this->_contactType; } elseif (!empty($paramValues['pledge_payment'])) { $paramValues['contact_type'] = $this->_contactType; } //need to pass $onDuplicate to check import mode. if (!empty($paramValues['pledge_payment'])) { $paramValues['onDuplicate'] = $onDuplicate; } require_once 'CRM/Utils/DeprecatedUtils.php'; $formatError = _civicrm_api3_deprecated_formatted_param($paramValues, $formatted, TRUE, $onDuplicate); if ($formatError) { array_unshift($values, $formatError['error_message']); if (CRM_Utils_Array::value('error_data', $formatError) == 'soft_credit') { return CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR; } elseif (CRM_Utils_Array::value('error_data', $formatError) == 'pledge_payment') { return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR; } return CRM_Import_Parser::ERROR; } if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) { $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Contribution'); } else { //fix for CRM-2219 - Update Contribution // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE if (!empty($paramValues['invoice_id']) || !empty($paramValues['trxn_id']) || !empty($paramValues['contribution_id'])) { $dupeIds = array('id' => CRM_Utils_Array::value('contribution_id', $paramValues), 'trxn_id' => CRM_Utils_Array::value('trxn_id', $paramValues), 'invoice_id' => CRM_Utils_Array::value('invoice_id', $paramValues)); $ids['contribution'] = CRM_Contribute_BAO_Contribution::checkDuplicateIds($dupeIds); if ($ids['contribution']) { $formatted['id'] = $ids['contribution']; $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatted['id'], 'Contribution'); //process note if (!empty($paramValues['note'])) { $noteID = array(); $contactID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id'); $daoNote = new CRM_Core_BAO_Note(); $daoNote->entity_table = 'civicrm_contribution'; $daoNote->entity_id = $ids['contribution']; if ($daoNote->find(TRUE)) { $noteID['id'] = $daoNote->id; } $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $paramValues['note'], 'entity_id' => $ids['contribution'], 'contact_id' => $contactID); CRM_Core_BAO_Note::add($noteParams, $noteID); unset($formatted['note']); } //need to check existing soft credit contribution, CRM-3968 if (!empty($formatted['soft_credit'])) { $dupeSoftCredit = array('contact_id' => $formatted['soft_credit'], 'contribution_id' => $ids['contribution']); //Delete all existing soft Contribution from contribution_soft table for pcp_id is_null $existingSoftCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dupeSoftCredit['contribution_id']); if (isset($existingSoftCredit['soft_credit']) && !empty($existingSoftCredit['soft_credit'])) { foreach ($existingSoftCredit['soft_credit'] as $key => $existingSoftCreditValues) { if (!empty($existingSoftCreditValues['soft_credit_id'])) { $deleteParams = array('id' => $existingSoftCreditValues['soft_credit_id'], 'pcp_id' => NULL); CRM_Contribute_BAO_ContributionSoft::del($deleteParams); } } } } $newContribution = CRM_Contribute_BAO_Contribution::create($formatted, $ids); $this->_newContributions[] = $newContribution->id; //return soft valid since we need to show how soft credits were added if (!empty($formatted['soft_credit'])) { return CRM_Contribute_Import_Parser::SOFT_CREDIT; } // process pledge payment assoc w/ the contribution return self::processPledgePayments($formatted); return CRM_Import_Parser::VALID; } else { $labels = array('id' => 'Contribution ID', 'trxn_id' => 'Transaction ID', 'invoice_id' => 'Invoice ID'); foreach ($dupeIds as $k => $v) { if ($v) { $errorMsg[] = "{$labels[$k]} {$v}"; } } $errorMsg = implode(' AND ', $errorMsg); array_unshift($values, 'Matching Contribution record not found for ' . $errorMsg . '. Row was skipped.'); return CRM_Import_Parser::ERROR; } } } if ($this->_contactIdIndex < 0) { // set the contact type if its not set if (!isset($paramValues['contact_type'])) { $paramValues['contact_type'] = $this->_contactType; } $paramValues['version'] = 3; //retrieve contact id using contact dedupe rule require_once 'CRM/Utils/DeprecatedUtils.php'; $error = _civicrm_api3_deprecated_check_contact_dedupe($paramValues); if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) > 1) { array_unshift($values, 'Multiple matching contact records detected for this row. The contribution was not imported'); return CRM_Import_Parser::ERROR; } else { $cid = $matchedIDs[0]; $formatted['contact_id'] = $cid; $newContribution = civicrm_api('contribution', 'create', $formatted); if (civicrm_error($newContribution)) { if (is_array($newContribution['error_message'])) { array_unshift($values, $newContribution['error_message']['message']); if ($newContribution['error_message']['params'][0]) { return CRM_Import_Parser::DUPLICATE; } } else { array_unshift($values, $newContribution['error_message']); return CRM_Import_Parser::ERROR; } } $this->_newContributions[] = $newContribution['id']; $formatted['contribution_id'] = $newContribution['id']; //return soft valid since we need to show how soft credits were added if (!empty($formatted['soft_credit'])) { return CRM_Contribute_Import_Parser::SOFT_CREDIT; } // process pledge payment assoc w/ the contribution return self::processPledgePayments($formatted); return CRM_Import_Parser::VALID; } } else { // Using new Dedupe rule. $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised'); $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); $disp = NULL; foreach ($fieldsArray as $value) { if (array_key_exists(trim($value), $params)) { $paramValue = $params[trim($value)]; if (is_array($paramValue)) { $disp .= $params[trim($value)][0][trim($value)] . " "; } else { $disp .= $params[trim($value)] . " "; } } } if (!empty($params['external_identifier'])) { if ($disp) { $disp .= "AND {$params['external_identifier']}"; } else { $disp = $params['external_identifier']; } } array_unshift($values, 'No matching Contact found for (' . $disp . ')'); return CRM_Import_Parser::ERROR; } } else { if (!empty($paramValues['external_identifier'])) { $checkCid = new CRM_Contact_DAO_Contact(); $checkCid->external_identifier = $paramValues['external_identifier']; $checkCid->find(TRUE); if ($checkCid->id != $formatted['contact_id']) { array_unshift($values, 'Mismatch of External ID:' . $paramValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']); return CRM_Import_Parser::ERROR; } } $newContribution = civicrm_api('contribution', 'create', $formatted); if (civicrm_error($newContribution)) { if (is_array($newContribution['error_message'])) { array_unshift($values, $newContribution['error_message']['message']); if ($newContribution['error_message']['params'][0]) { return CRM_Import_Parser::DUPLICATE; } } else { array_unshift($values, $newContribution['error_message']); return CRM_Import_Parser::ERROR; } } $this->_newContributions[] = $newContribution['id']; $formatted['contribution_id'] = $newContribution['id']; //return soft valid since we need to show how soft credits were added if (!empty($formatted['soft_credit'])) { return CRM_Contribute_Import_Parser::SOFT_CREDIT; } // process pledge payment assoc w/ the contribution return self::processPledgePayments($formatted); return CRM_Import_Parser::VALID; } }
/** * @param string $fileName * @param string $seperator * @param $mapper * @param bool $skipColumnHeader * @param int $mode * @param int $contactType * @param int $onDuplicate * * @return mixed * @throws Exception */ public function run($fileName, $seperator = ',', &$mapper, $skipColumnHeader = FALSE, $mode = self::MODE_PREVIEW, $contactType = self::CONTACT_INDIVIDUAL, $onDuplicate = self::DUPLICATE_SKIP) { if (!is_array($fileName)) { CRM_Core_Error::fatal(); } $fileName = $fileName['name']; switch ($contactType) { case self::CONTACT_INDIVIDUAL: $this->_contactType = 'Individual'; break; case self::CONTACT_HOUSEHOLD: $this->_contactType = 'Household'; break; case self::CONTACT_ORGANIZATION: $this->_contactType = 'Organization'; } $this->init(); $this->_haveColumnHeader = $skipColumnHeader; $this->_seperator = $seperator; $fd = fopen($fileName, "r"); if (!$fd) { return FALSE; } $this->_lineCount = $this->_warningCount = 0; $this->_invalidRowCount = $this->_validCount = 0; $this->_totalCount = $this->_conflictCount = 0; $this->_errors = array(); $this->_warnings = array(); $this->_conflicts = array(); $this->_fileSize = number_format(filesize($fileName) / 1024.0, 2); if ($mode == self::MODE_MAPFIELD) { $this->_rows = array(); } else { $this->_activeFieldCount = count($this->_activeFields); } while (!feof($fd)) { $this->_lineCount++; $values = fgetcsv($fd, 8192, $seperator); if (!$values) { continue; } self::encloseScrub($values); // skip column header if we're not in mapfield mode if ($mode != self::MODE_MAPFIELD && $skipColumnHeader) { $skipColumnHeader = FALSE; continue; } /* trim whitespace around the values */ $empty = TRUE; foreach ($values as $k => $v) { $values[$k] = trim($v, " \t\r\n"); } if (CRM_Utils_System::isNull($values)) { continue; } $this->_totalCount++; if ($mode == self::MODE_MAPFIELD) { $returnCode = $this->mapField($values); } elseif ($mode == self::MODE_PREVIEW) { $returnCode = $this->preview($values); } elseif ($mode == self::MODE_SUMMARY) { $returnCode = $this->summary($values); } elseif ($mode == self::MODE_IMPORT) { $returnCode = $this->import($onDuplicate, $values); } else { $returnCode = self::ERROR; } // note that a line could be valid but still produce a warning if ($returnCode & self::VALID) { $this->_validCount++; if ($mode == self::MODE_MAPFIELD) { $this->_rows[] = $values; $this->_activeFieldCount = max($this->_activeFieldCount, count($values)); } } if ($returnCode & self::WARNING) { $this->_warningCount++; if ($this->_warningCount < $this->_maxWarningCount) { $this->_warningCount[] = $line; } } if ($returnCode & self::ERROR) { $this->_invalidRowCount++; if ($this->_invalidRowCount < $this->_maxErrorCount) { $recordNumber = $this->_lineCount; array_unshift($values, $recordNumber); $this->_errors[] = $values; } } if ($returnCode & self::CONFLICT) { $this->_conflictCount++; $recordNumber = $this->_lineCount; array_unshift($values, $recordNumber); $this->_conflicts[] = $values; } if ($returnCode & self::DUPLICATE) { if ($returnCode & self::MULTIPLE_DUPE) { /* TODO: multi-dupes should be counted apart from singles * on non-skip action */ } $this->_duplicateCount++; $recordNumber = $this->_lineCount; array_unshift($values, $recordNumber); $this->_duplicates[] = $values; if ($onDuplicate != self::DUPLICATE_SKIP) { $this->_validCount++; } } // we give the derived class a way of aborting the process // note that the return code could be multiple code or'ed together if ($returnCode & self::STOP) { break; } // if we are done processing the maxNumber of lines, break if ($this->_maxLinesToProcess > 0 && $this->_validCount >= $this->_maxLinesToProcess) { break; } } fclose($fd); if ($mode == self::MODE_PREVIEW || $mode == self::MODE_IMPORT) { $customHeaders = $mapper; $customfields = CRM_Core_BAO_CustomField::getFields('Membership'); foreach ($customHeaders as $key => $value) { if ($id = CRM_Core_BAO_CustomField::getKeyID($value)) { $customHeaders[$key] = $customfields[$id][0]; } } if ($this->_invalidRowCount) { // removed view url for invlaid contacts $headers = array_merge(array(ts('Line Number'), ts('Reason')), $customHeaders); $this->_errorFileName = self::errorFileName(self::ERROR); self::exportCSV($this->_errorFileName, $headers, $this->_errors); } if ($this->_conflictCount) { $headers = array_merge(array(ts('Line Number'), ts('Reason')), $customHeaders); $this->_conflictFileName = self::errorFileName(self::CONFLICT); self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts); } if ($this->_duplicateCount) { $headers = array_merge(array(ts('Line Number'), ts('View Membership URL')), $customHeaders); $this->_duplicateFileName = self::errorFileName(self::DUPLICATE); self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates); } } return $this->fini(); }
/** * Build the form * * @access public * * @return void */ function buildQuickForm() { $ufGroupId = $this->get('ufGroupId'); if (!$ufGroupId) { CRM_Core_Error::fatal('ufGroupId is missing'); } $this->_title = ts('Batch Update for Activities') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId); CRM_Utils_System::setTitle($this->_title); $this->addDefaultButtons(ts('Save')); $this->_fields = array(); $this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW); // remove file type field and then limit fields $suppressFields = FALSE; $removehtmlTypes = array('File', 'Autocomplete-Select'); foreach ($this->_fields as $name => $field) { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && in_array($this->_fields[$name]['html_type'], $removehtmlTypes)) { $suppressFields = TRUE; unset($this->_fields[$name]); } //fix to reduce size as we are using this field in grid if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) { //shrink class to "form-text-medium" $this->_fields[$name]['attributes']['size'] = 19; } } $this->_fields = array_slice($this->_fields, 0, $this->_maxFields); $this->addButtons(array(array('type' => 'submit', 'name' => ts('Update Activities'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel')))); $this->assign('profileTitle', $this->_title); $this->assign('componentIds', $this->_activityHolderIds); $fileFieldExists = FALSE; //load all campaigns. if (array_key_exists('activity_campaign_id', $this->_fields)) { $this->_componentCampaigns = array(); CRM_Core_PseudoConstant::populate($this->_componentCampaigns, 'CRM_Activity_DAO_Activity', TRUE, 'campaign_id', 'id', ' id IN (' . implode(' , ', array_values($this->_activityHolderIds)) . ' ) '); } $customFields = CRM_Core_BAO_CustomField::getFields('Activity'); foreach ($this->_activityHolderIds as $activityId) { $typeId = CRM_Core_DAO::getFieldValue("CRM_Activity_DAO_Activity", $activityId, 'activity_type_id'); foreach ($this->_fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) { $customValue = CRM_Utils_Array::value($customFieldID, $customFields); if (!empty($customValue['extends_entity_column_value'])) { $entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customValue['extends_entity_column_value']); } if (!empty($entityColumnValue[$typeId]) || CRM_Utils_System::isNull($entityColumnValue[$typeId])) { CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $activityId); } } else { // handle non custom fields CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $activityId); } } } $this->assign('fields', $this->_fields); // don't set the status message when form is submitted. // $buttonName = $this->controller->getButtonName('submit'); if ($suppressFields) { CRM_Core_Session::setStatus(ts("FILE or Autocomplete Select type field(s) in the selected profile are not supported for Batch Update."), ts("Some fields have been excluded"), "info"); } $this->addDefaultButtons(ts('Update Activities')); }
/** * @return bool */ public function validate() { if (CRM_Utils_System::isNull($this->_value)) { return TRUE; } switch ($this->_name) { case 'contact_id': // note: we validate extistence of the contact in API, upon // insert (it would be too costlty to do a db call here) return CRM_Utils_Rule::integer($this->_value); case 'register_date': return CRM_Utils_Rule::date($this->_value); /* @codingStandardsIgnoreStart case 'event_id': static $events = null; if (!$events) { $events = CRM_Event_PseudoConstant::event(); } if (in_array($this->_value, $events)) { return true; } else { return false; } break; @codingStandardsIgnoreEnd */ /* @codingStandardsIgnoreStart case 'event_id': static $events = null; if (!$events) { $events = CRM_Event_PseudoConstant::event(); } if (in_array($this->_value, $events)) { return true; } else { return false; } break; @codingStandardsIgnoreEnd */ default: break; } // check whether that's a valid custom field id // and if so, check the contents' validity if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($this->_name)) { static $customFields = NULL; if (!$customFields) { $customFields = CRM_Core_BAO_CustomField::getFields('Participant'); } if (!array_key_exists($customFieldID, $customFields)) { return FALSE; } return CRM_Core_BAO_CustomValue::typecheck($customFields[$customFieldID]['data_type'], $this->_value); } return TRUE; }
/** * Gives required details of contacts in an indexed array format so we * can iterate in a nice loop and do token evaluation * * @param $contactIDs * @param array $returnProperties * Of required properties. * @param bool $skipOnHold Don't return on_hold contact info also. * Don't return on_hold contact info also. * @param bool $skipDeceased Don't return deceased contact info. * Don't return deceased contact info. * @param array $extraParams * Extra params. * @param array $tokens * The list of tokens we've extracted from the content. * @param null $className * @param int $jobID * The mailing list jobID - this is a legacy param. * * @return array */ public static function getTokenDetails($contactIDs, $returnProperties = NULL, $skipOnHold = TRUE, $skipDeceased = TRUE, $extraParams = NULL, $tokens = array(), $className = NULL, $jobID = NULL) { if (empty($contactIDs)) { // putting a fatal here so we can track if/when this happens CRM_Core_Error::fatal(); } // @todo this functions needs unit tests. $params = array(); foreach ($contactIDs as $key => $contactID) { $params[] = array(CRM_Core_Form::CB_PREFIX . $contactID, '=', 1, 0, 0); } // fix for CRM-2613 if ($skipDeceased) { $params[] = array('is_deceased', '=', 0, 0, 0); } //fix for CRM-3798 if ($skipOnHold) { $params[] = array('on_hold', '=', 0, 0, 0); } if ($extraParams) { $params = array_merge($params, $extraParams); } // if return properties are not passed then get all return properties if (empty($returnProperties)) { $fields = array_merge(array_keys(CRM_Contact_BAO_Contact::exportableFields()), array('display_name', 'checksum', 'contact_id')); foreach ($fields as $key => $val) { // The unavailable fields are not available as tokens, do not have a one-2-one relationship // with contacts and are expensive to resolve. // @todo see CRM-17253 - there are some other fields (e.g note) that should be excluded // and upstream calls to this should populate return properties. $unavailableFields = array('group', 'tag'); if (!in_array($val, $unavailableFields)) { $returnProperties[$val] = 1; } } } $custom = array(); foreach ($returnProperties as $name => $dontCare) { $cfID = CRM_Core_BAO_CustomField::getKeyID($name); if ($cfID) { $custom[] = $cfID; } } //get the total number of contacts to fetch from database. $numberofContacts = count($contactIDs); $query = new CRM_Contact_BAO_Query($params, $returnProperties); $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts); $contactDetails =& $details[0]; foreach ($contactIDs as $key => $contactID) { if (array_key_exists($contactID, $contactDetails)) { if (CRM_Utils_Array::value('preferred_communication_method', $returnProperties) == 1 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])) { $pcm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method'); // communication Preference $contactPcm = explode(CRM_Core_DAO::VALUE_SEPARATOR, $contactDetails[$contactID]['preferred_communication_method']); $result = array(); foreach ($contactPcm as $key => $val) { if ($val) { $result[$val] = $pcm[$val]; } } $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result); } foreach ($custom as $cfID) { if (isset($contactDetails[$contactID]["custom_{$cfID}"])) { $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"], $cfID, $details[1]); } } // special case for greeting replacement foreach (array('email_greeting', 'postal_greeting', 'addressee') as $val) { if (!empty($contactDetails[$contactID][$val])) { $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"]; } } } } // also call a hook and get token details CRM_Utils_Hook::tokenValues($details[0], $contactIDs, $jobID, $tokens, $className); return $details; }
/** * process the form after the input has been submitted and validated * * @access public * * @return void */ public function postProcess() { $fv = $this->controller->exportValues($this->_name); $config = CRM_Core_Config::singleton(); $locName = NULL; //get the address format sequence from the config file $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'mailing_format'); $sequence = CRM_Utils_Address::sequence($mailingFormat); foreach ($sequence as $v) { $address[$v] = 1; } if (array_key_exists('postal_code', $address)) { $address['postal_code_suffix'] = 1; } //build the returnproperties $returnProperties = array('display_name' => 1, 'contact_type' => 1); $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'mailing_format'); $mailingFormatProperties = array(); if ($mailingFormat) { $mailingFormatProperties = self::getReturnProperties($mailingFormat); $returnProperties = array_merge($returnProperties, $mailingFormatProperties); } //we should not consider addressee for data exists, CRM-6025 if (array_key_exists('addressee', $mailingFormatProperties)) { unset($mailingFormatProperties['addressee']); } $customFormatProperties = array(); if (stristr($mailingFormat, 'custom_')) { foreach ($mailingFormatProperties as $token => $true) { if (substr($token, 0, 7) == 'custom_') { if (empty($customFormatProperties[$token])) { $customFormatProperties[$token] = $mailingFormatProperties[$token]; } } } } if (!empty($customFormatProperties)) { $returnProperties = array_merge($returnProperties, $customFormatProperties); } if (isset($fv['merge_same_address'])) { // we need first name/last name for summarising to avoid spillage $returnProperties['first_name'] = 1; $returnProperties['last_name'] = 1; } $individualFormat = FALSE; /* * CRM-8338: replace ids of household members with the id of their household * so we can merge labels by household. */ if (isset($fv['merge_same_household'])) { $this->mergeContactIdsByHousehold(); $individualFormat = TRUE; } //get the contacts information $params = array(); if (!empty($fv['location_type_id'])) { $locType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $locName = $locType[$fv['location_type_id']]; $location = array('location' => array("{$locName}" => $address)); $returnProperties = array_merge($returnProperties, $location); $params[] = array('location_type', '=', array($fv['location_type_id'] => 1), 0, 0); } else { $returnProperties = array_merge($returnProperties, $address); } $rows = array(); foreach ($this->_contactIds as $key => $contactID) { $params[] = array(CRM_Core_Form::CB_PREFIX . $contactID, '=', 1, 0, 0); } // fix for CRM-2651 if (!empty($fv['do_not_mail'])) { $params[] = array('do_not_mail', '=', 0, 0, 0); } // fix for CRM-2613 $params[] = array('is_deceased', '=', 0, 0, 0); $custom = array(); foreach ($returnProperties as $name => $dontCare) { $cfID = CRM_Core_BAO_CustomField::getKeyID($name); if ($cfID) { $custom[] = $cfID; } } //get the total number of contacts to fetch from database. $numberofContacts = count($this->_contactIds); $query = new CRM_Contact_BAO_Query($params, $returnProperties); $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts); $messageToken = CRM_Utils_Token::getTokens($mailingFormat); // also get all token values CRM_Utils_Hook::tokenValues($details[0], $this->_contactIds, NULL, $messageToken, 'CRM_Contact_Form_Task_Label'); $tokens = array(); CRM_Utils_Hook::tokens($tokens); $tokenFields = array(); foreach ($tokens as $category => $catTokens) { foreach ($catTokens as $token => $tokenName) { $tokenFields[] = $token; } } foreach ($this->_contactIds as $value) { foreach ($custom as $cfID) { if (isset($details[0][$value]["custom_{$cfID}"])) { $details[0][$value]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($details[0][$value]["custom_{$cfID}"], $cfID, $details[1]); } } $contact = CRM_Utils_Array::value($value, $details['0']); if (is_a($contact, 'CRM_Core_Error')) { return NULL; } // we need to remove all the "_id" unset($contact['contact_id']); if ($locName && !empty($contact[$locName])) { // If location type is not primary, $contact contains // one more array as "$contact[$locName] = array( values... )" if (!$this->tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) { continue; } unset($contact[$locName]); if (!empty($contact['county_id'])) { unset($contact['county_id']); } foreach ($contact as $field => $fieldValue) { $rows[$value][$field] = $fieldValue; } $valuesothers = array(); $paramsothers = array('contact_id' => $value); $valuesothers = CRM_Core_BAO_Location::getValues($paramsothers, $valuesothers); if (!empty($fv['location_type_id'])) { foreach ($valuesothers as $vals) { if (CRM_Utils_Array::value('location_type_id', $vals) == CRM_Utils_Array::value('location_type_id', $fv)) { foreach ($vals as $k => $v) { if (in_array($k, array('email', 'phone', 'im', 'openid'))) { if ($k == 'im') { $rows[$value][$k] = $v['1']['name']; } else { $rows[$value][$k] = $v['1'][$k]; } $rows[$value][$k . '_id'] = $v['1']['id']; } } } } } } else { if (!$this->tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) { continue; } if (!empty($contact['addressee_display'])) { $contact['addressee_display'] = trim($contact['addressee_display']); } if (!empty($contact['addressee'])) { $contact['addressee'] = $contact['addressee_display']; } // now create the rows for generating mailing labels foreach ($contact as $field => $fieldValue) { $rows[$value][$field] = $fieldValue; } } } if (isset($fv['merge_same_address'])) { $this->mergeSameAddress($rows); $individualFormat = TRUE; } // format the addresses according to CIVICRM_ADDRESS_FORMAT (CRM-1327) foreach ($rows as $id => $row) { if ($commMethods = CRM_Utils_Array::value('preferred_communication_method', $row)) { $val = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $commMethods)); $comm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method'); $temp = array(); foreach ($val as $vals) { $temp[] = $comm[$vals]; } $row['preferred_communication_method'] = implode(', ', $temp); } $row['id'] = $id; $formatted = CRM_Utils_Address::format($row, 'mailing_format', FALSE, TRUE, $individualFormat, $tokenFields); // CRM-2211: UFPDF doesn't have bidi support; use the PECL fribidi package to fix it. // On Ubuntu (possibly Debian?) be aware of http://pecl.php.net/bugs/bug.php?id=12366 // Due to FriBidi peculiarities, this can't be called on // a multi-line string, hence the explode+implode approach. if (function_exists('fribidi_log2vis')) { $lines = explode("\n", $formatted); foreach ($lines as $i => $line) { $lines[$i] = fribidi_log2vis($line, FRIBIDI_AUTO, FRIBIDI_CHARSET_UTF8); } $formatted = implode("\n", $lines); } $rows[$id] = array($formatted); } //call function to create labels self::createLabel($rows, $fv['label_name']); CRM_Utils_System::civiExit(1); }
/** * Format custom field name. * * Combine group and field name to avoid conflict. * * @param array $fields * * @return array */ public function formatCustomFieldName(&$fields) { //CRM-2676, replacing the conflict for same custom field name from different custom group. $fieldIds = $formattedFieldNames = array(); foreach ($fields as $key => $value) { if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key)) { $fieldIds[] = $customFieldId; } } if (!empty($fieldIds) && is_array($fieldIds)) { $groupTitles = CRM_Core_BAO_CustomGroup::getGroupTitles($fieldIds); if (!empty($groupTitles)) { foreach ($groupTitles as $fId => $values) { $key = "custom_{$fId}"; $groupTitle = $values['groupTitle']; $formattedFieldNames[$key] = $fields[$key] . ' :: ' . $groupTitle; } } } return $formattedFieldNames; }
/** * Handle the values in import mode. * * @param int $onDuplicate * The code for what action to take on duplicates. * @param array $values * The array of values belonging to this line. * * @return bool * the result of this processing */ public function import($onDuplicate, &$values) { // first make sure this is a valid line $response = $this->summary($values); if ($response != CRM_Import_Parser::VALID) { return $response; } $params =& $this->getActiveFieldParams(); $session = CRM_Core_Session::singleton(); $dateType = $session->get('dateTypes'); $formatted = array('version' => 3); $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params)); // don't add to recent items, CRM-4399 $formatted['skipRecentView'] = TRUE; foreach ($params as $key => $val) { if ($val) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($customFields[$customFieldID]['data_type'] == 'Date') { CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key); unset($params[$key]); } elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } if ($key == 'participant_register_date') { CRM_Utils_Date::convertToDefaultDate($params, $dateType, 'participant_register_date'); $formatted['participant_register_date'] = CRM_Utils_Date::processDate($params['participant_register_date']); } } } if (!(!empty($params['participant_role_id']) || !empty($params['participant_role']))) { if (!empty($params['event_id'])) { $params['participant_role_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id'); } else { $eventTitle = $params['event_title']; $qParams = array(); $dao = new CRM_Core_DAO(); $params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '{$eventTitle}' ", $qParams); } } //date-Format part ends static $indieFields = NULL; if ($indieFields == NULL) { $indieFields = CRM_Event_BAO_Participant::import(); } $formatValues = array(); foreach ($params as $key => $field) { if ($field == NULL || $field === '') { continue; } $formatValues[$key] = $field; } $formatError = _civicrm_api3_deprecated_participant_formatted_param($formatValues, $formatted, TRUE); if ($formatError) { array_unshift($values, $formatError['error_message']); return CRM_Import_Parser::ERROR; } if (!CRM_Utils_Rule::integer($formatted['event_id'])) { array_unshift($values, ts('Invalid value for Event ID')); return CRM_Import_Parser::ERROR; } if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) { $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, NULL, 'Participant'); } else { if ($formatValues['participant_id']) { $dao = new CRM_Event_BAO_Participant(); $dao->id = $formatValues['participant_id']; $formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted, $formatValues['participant_id'], 'Participant'); if ($dao->find(TRUE)) { $ids = array('participant' => $formatValues['participant_id'], 'userId' => $session->get('userID')); $participantValues = array(); //@todo calling api functions directly is not supported $newParticipant = _civicrm_api3_deprecated_participant_check_params($formatted, $participantValues, FALSE); if ($newParticipant['error_message']) { array_unshift($values, $newParticipant['error_message']); return CRM_Import_Parser::ERROR; } $newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids); if (!empty($formatted['fee_level'])) { $otherParams = array('fee_label' => $formatted['fee_level'], 'event_id' => $newParticipant->event_id); CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams); } $this->_newParticipant[] = $newParticipant->id; return CRM_Import_Parser::VALID; } else { array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.'); return CRM_Import_Parser::ERROR; } } } if ($this->_contactIdIndex < 0) { //retrieve contact id using contact dedupe rule $formatValues['contact_type'] = $this->_contactType; $formatValues['version'] = 3; $error = _civicrm_api3_deprecated_check_contact_dedupe($formatValues); if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) >= 1) { foreach ($matchedIDs as $contactId) { $formatted['contact_id'] = $contactId; $formatted['version'] = 3; $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate); } } } else { // Using new Dedupe rule. $ruleParams = array('contact_type' => $this->_contactType, 'used' => 'Unsupervised'); $fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams); $disp = ''; foreach ($fieldsArray as $value) { if (array_key_exists(trim($value), $params)) { $paramValue = $params[trim($value)]; if (is_array($paramValue)) { $disp .= $params[trim($value)][0][trim($value)] . " "; } else { $disp .= $params[trim($value)] . " "; } } } if (!empty($params['external_identifier'])) { if ($disp) { $disp .= "AND {$params['external_identifier']}"; } else { $disp = $params['external_identifier']; } } array_unshift($values, 'No matching Contact found for (' . $disp . ')'); return CRM_Import_Parser::ERROR; } } else { if (!empty($formatValues['external_identifier'])) { $checkCid = new CRM_Contact_DAO_Contact(); $checkCid->external_identifier = $formatValues['external_identifier']; $checkCid->find(TRUE); if ($checkCid->id != $formatted['contact_id']) { array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']); return CRM_Import_Parser::ERROR; } } $newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate); } if (is_array($newParticipant) && civicrm_error($newParticipant)) { if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) { $contactID = CRM_Utils_Array::value('contactID', $newParticipant); $participantID = CRM_Utils_Array::value('participantID', $newParticipant); $url = CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE); if (is_array($newParticipant['error_message']) && $participantID == $newParticipant['error_message']['params'][0]) { array_unshift($values, $url); return CRM_Import_Parser::DUPLICATE; } elseif ($newParticipant['error_message']) { array_unshift($values, $newParticipant['error_message']); return CRM_Import_Parser::ERROR; } return CRM_Import_Parser::ERROR; } } if (!(is_array($newParticipant) && civicrm_error($newParticipant))) { $this->_newParticipants[] = CRM_Utils_Array::value('id', $newParticipant); } return CRM_Import_Parser::VALID; }
/** * Function to build the array for display the profile fields * * @param array $params key value. * @param int $gid profile Id * @param array $groupTitle Profile Group Title. * @param array $values formatted array of key value * * @param array $profileFields * * @return void * @access public * @static */ static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array()) { if ($gid) { $config = CRM_Core_Config::singleton(); $session = CRM_Core_Session::singleton(); $contactID = $session->get('userID'); if ($contactID) { if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) { $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW); } } else { $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::ADD); } foreach ($fields as $v) { if (!empty($v['groupTitle'])) { $groupTitle['groupTitle'] = $v['groupTitle']; break; } } $customVal = ''; $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); //start of code to set the default values foreach ($fields as $name => $field) { $skip = FALSE; // skip fields that should not be displayed separately if ($field['skipDisplay']) { continue; } $index = $field['title']; if ($name === 'organization_name') { $values[$index] = $params[$name]; } if ('state_province' == substr($name, 0, 14)) { if ($params[$name]) { $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]); } else { $values[$index] = ''; } } elseif ('date' == substr($name, -4)) { $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name]), $config->dateformatFull); } elseif ('country' == substr($name, 0, 7)) { if ($params[$name]) { $values[$index] = CRM_Core_PseudoConstant::country($params[$name]); } else { $values[$index] = ''; } } elseif ('county' == substr($name, 0, 6)) { if ($params[$name]) { $values[$index] = CRM_Core_PseudoConstant::county($params[$name]); } else { $values[$index] = ''; } } elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) { $values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]); } elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) { $filterCondition = array('greeting_type' => $name); $greeting = CRM_Core_PseudoConstant::greeting($filterCondition); $values[$index] = $greeting[$params[$name]]; } elseif ($name === 'preferred_communication_method') { $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method'); $compref = array(); $pref = $params[$name]; if (is_array($pref)) { foreach ($pref as $k => $v) { if ($v) { $compref[] = $communicationFields[$k]; } } } $values[$index] = implode(',', $compref); } elseif ($name == 'contact_sub_type') { $values[$index] = implode(', ', $params[$name]); } elseif ($name == 'group') { $groups = CRM_Contact_BAO_GroupContact::getGroupList(); $title = array(); foreach ($params[$name] as $gId => $dontCare) { if ($dontCare) { $title[] = $groups[$gId]; } } $values[$index] = implode(', ', $title); } elseif ($name == 'tag') { $entityTags = $params[$name]; $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE)); $title = array(); if (is_array($entityTags)) { foreach ($entityTags as $tagId => $dontCare) { $title[] = $allTags[$tagId]; } } $values[$index] = implode(', ', $title); } elseif ('participant_role_id' == $name or 'participant_role' == $name) { $roles = CRM_Event_PseudoConstant::participantRole(); $values[$index] = $roles[$params[$name]]; } elseif ('participant_status_id' == $name or 'participant_status' == $name) { $status = CRM_Event_PseudoConstant::participantStatus(); $values[$index] = $status[$params[$name]]; } elseif (substr($name, -11) == 'campaign_id') { $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($params[$name]); $values[$index] = CRM_Utils_Array::value($params[$name], $campaigns); } elseif (strpos($name, '-') !== FALSE) { list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2); $detailName = str_replace(' ', '_', $name); if (in_array($fieldName, array('state_province', 'country', 'county'))) { $values[$index] = $params[$detailName]; $idx = $detailName . '_id'; $values[$index] = $params[$idx]; } elseif ($fieldName == 'im') { $providerName = NULL; if ($providerId = $detailName . '-provider_id') { $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders); } if ($providerName) { $values[$index] = $params[$detailName] . " (" . $providerName . ")"; } else { $values[$index] = $params[$detailName]; } } elseif ($fieldName == 'phone') { $phoneExtField = str_replace('phone', 'phone_ext', $detailName); if (isset($params[$phoneExtField])) { $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")"; } else { $values[$index] = $params[$detailName]; } } else { $values[$index] = $params[$detailName]; } } else { if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') { if ($params[$name]) { $values[$index] = '[ x ]'; } } else { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) { $query = "\nSELECT html_type, data_type\nFROM civicrm_custom_field\nWHERE id = {$cfID}\n"; $dao = CRM_Core_DAO::executeQuery($query); $dao->fetch(); $htmlType = $dao->html_type; if ($htmlType == 'File') { $values[$index] = $params[$index]; } else { if ($dao->data_type == 'Int' || $dao->data_type == 'Boolean') { $v = $params[$name]; if (!CRM_Utils_System::isNull($v)) { $customVal = (int) $v; } } elseif ($dao->data_type == 'Float') { $customVal = (double) $params[$name]; } elseif ($dao->data_type == 'Date') { //@todo note the currently we are using default date time formatting. Since you can select/set // different date and time format specific to custom field we should consider fixing this // sometime in the future $customVal = $displayValue = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name]), $config->dateformatFull); if (!empty($params[$name . '_time'])) { $customVal = $displayValue = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name], $params[$name . '_time']), $config->dateformatDatetime); } $skip = TRUE; } else { $customVal = $params[$name]; } //take the custom field options $returnProperties = array($name => 1); $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields); $options =& $query->_options; if (!$skip) { $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options); } //Hack since we dont have function to check empty. //FIXME in 2.3 using crmIsEmptyArray() $customValue = TRUE; if (is_array($customVal) && is_array($displayValue)) { $customValue = array_diff($customVal, $displayValue); } //use difference of arrays if (empty($customValue) || !$customValue) { $values[$index] = ''; } else { $values[$index] = $displayValue; } } } elseif ($name == 'home_URL' && !empty($params[$name])) { $url = CRM_Utils_System::fixURL($params[$name]); $values[$index] = "<a href=\"{$url}\">{$params[$name]}</a>"; } elseif (in_array($name, array('birth_date', 'deceased_date', 'participant_register_date'))) { $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name])); } else { $values[$index] = $params[$name]; } } } $profileFields[$name] = $field; } } }
/** * Check if the field is selected. * * @param string $prop * * @return bool */ public function isFieldSelected($prop) { if (empty($prop)) { return FALSE; } if (!empty($this->_params['fields'])) { foreach (array_keys($prop['fields']) as $fieldAlias) { $customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias); if ($customFieldId) { if (array_key_exists($fieldAlias, $this->_params['fields'])) { return TRUE; } //might be survey response field. if (!empty($this->_params['fields']['survey_response']) && !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])) { return TRUE; } } } } if (!empty($this->_params['group_bys']) && $this->_customGroupGroupBy) { foreach (array_keys($prop['group_bys']) as $fieldAlias) { if (array_key_exists($fieldAlias, $this->_params['group_bys']) && CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) { return TRUE; } } } if (!empty($this->_params['order_bys'])) { foreach (array_keys($prop['fields']) as $fieldAlias) { foreach ($this->_params['order_bys'] as $orderBy) { if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) { return TRUE; } } } } return $this->isFieldFiltered($prop); }
function postProcess(&$params, &$customFields, $entityID, $customFieldExtends, $inline = false) { $customData = array(); foreach ($params as $key => $value) { if ($customFieldInfo = CRM_Core_BAO_CustomField::getKeyID($key, true)) { // for autocomplete transfer hidden value instead of label if ($params[$key] && isset($params[$key . '_id'])) { $value = $params[$key . '_id']; } // we need to append time with date if ($params[$key] && isset($params[$key . '_time'])) { $value .= ' ' . $params[$key . '_time']; } CRM_Core_BAO_CustomField::formatCustomField($customFieldInfo[0], $customData, $value, $customFieldExtends, $customFieldInfo[1], $entityID, $inline); } } return $customData; }
/** * 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); } } } }
/** * Build the form * * @access public * @return void */ function buildQuickForm() { $ufGroupId = $this->get('ufGroupId'); if (!$ufGroupId) { CRM_Core_Error::fatal('ufGroupId is missing'); } require_once "CRM/Core/BAO/UFGroup.php"; require_once "CRM/Core/BAO/CustomGroup.php"; $this->_title = ts('Batch Update for Contributions') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId); CRM_Utils_System::setTitle($this->_title); $this->addDefaultButtons(ts('Save')); $this->_fields = array(); $this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, false, CRM_Core_Action::VIEW); // remove file type field and then limit fields $suppressFields = false; $removehtmlTypes = array('File', 'Autocomplete-Select'); foreach ($this->_fields as $name => $field) { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && in_array($this->_fields[$name]['html_type'], $removehtmlTypes)) { $suppressFields = true; unset($this->_fields[$name]); } //fix to reduce size as we are using this field in grid if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) { //shrink class to "form-text-medium" $this->_fields[$name]['attributes']['size'] = 19; } } $this->_fields = array_slice($this->_fields, 0, $this->_maxFields); $this->addButtons(array(array('type' => 'submit', 'name' => ts('Update Contribution(s)'), 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel')))); $this->assign('profileTitle', $this->_title); $this->assign('componentIds', $this->_contributionIds); $fileFieldExists = false; //fix for CRM-2752 require_once "CRM/Core/BAO/CustomField.php"; $customFields = CRM_Core_BAO_CustomField::getFields('Contribution'); foreach ($this->_contributionIds as $contributionId) { $typeId = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $contributionId, 'contribution_type_id'); foreach ($this->_fields as $name => $field) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) { $customValue = CRM_Utils_Array::value($customFieldID, $customFields); if ($typeId == $customValue['extends_entity_column_value'] || CRM_Utils_System::isNull($customValue['extends_entity_column_value'])) { CRM_Core_BAO_UFGroup::buildProfile($this, $field, null, $contributionId); } } else { // handle non custom fields CRM_Core_BAO_UFGroup::buildProfile($this, $field, null, $contributionId); } } } $this->assign('fields', $this->_fields); // don't set the status message when form is submitted. $buttonName = $this->controller->getButtonName('submit'); if ($suppressFields && $buttonName != '_qf_Batch_next') { CRM_Core_Session::setStatus("FILE or Autocomplete Select type field(s) in the selected profile are not supported for Batch Update and have been excluded."); } $this->addDefaultButtons(ts('Update Contributions')); }
/** * Run the page. * * This method is called after the page is created. It checks for the * type of action and executes that action. * * @return void */ public function run() { $template = CRM_Core_Smarty::singleton(); if ($this->_id && $this->_gid) { // first check that id is part of the limit group id, CRM-4822 $limitListingsGroupsID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'limit_listings_group_id'); $config = CRM_Core_Config::singleton(); if ($limitListingsGroupsID) { if (!CRM_Contact_BAO_GroupContact::isContactInGroup($this->_id, $limitListingsGroupsID)) { CRM_Utils_System::setTitle(ts('Profile View - Permission Denied')); return CRM_Core_Session::setStatus(ts('You do not have permission to view this contact record. Contact the site administrator if you need assistance.'), ts('Permission Denied'), 'error'); } } $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); $this->_isPermissionedChecksum = $allowPermission = FALSE; $permissionType = CRM_Core_Permission::VIEW; if (CRM_Core_Permission::check('administer users') || CRM_Core_Permission::check('view all contacts') || CRM_Contact_BAO_Contact_Permission::allow($this->_id)) { $allowPermission = TRUE; } if ($this->_id != $userID) { // do not allow edit for anon users in joomla frontend, CRM-4668, unless u have checksum CRM-5228 if ($config->userFrameworkFrontend) { $this->_isPermissionedChecksum = CRM_Contact_BAO_Contact_Permission::validateOnlyChecksum($this->_id, $this, FALSE); if (!$this->_isPermissionedChecksum) { $this->_isPermissionedChecksum = $allowPermission; } } else { $this->_isPermissionedChecksum = CRM_Contact_BAO_Contact_Permission::validateChecksumContact($this->_id, $this, FALSE); } } // CRM-10853 // Users with create or edit permission should be allowed to view their own profile if ($this->_id == $userID || $this->_isPermissionedChecksum) { if (!CRM_Core_Permission::check('profile view')) { if (CRM_Core_Permission::check('profile create') || CRM_Core_Permission::check('profile edit')) { $this->_skipPermission = TRUE; } } } // make sure we dont expose all fields based on permission $admin = FALSE; if (!$config->userFrameworkFrontend && $allowPermission || $this->_id == $userID || $this->_isPermissionedChecksum) { $admin = TRUE; } $values = array(); $fields = CRM_Core_BAO_UFGroup::getFields($this->_profileIds, FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, $this->_restrict, $this->_skipPermission, NULL, $permissionType); if ($this->_multiRecord & CRM_Core_Action::VIEW && $this->_recordId && !$this->_allFields) { CRM_Core_BAO_UFGroup::shiftMultiRecordFields($fields, $multiRecordFields); $fields = $multiRecordFields; } if ($this->_isContactActivityProfile && $this->_gid) { $errors = CRM_Profile_Form::validateContactActivityProfile($this->_activityId, $this->_id, $this->_gid); if (!empty($errors)) { CRM_Core_Error::fatal(array_pop($errors)); } } //reformat fields array foreach ($fields as $name => $field) { // also eliminate all formatting fields if (CRM_Utils_Array::value('field_type', $field) == 'Formatting') { unset($fields[$name]); } // make sure that there is enough permission to expose this field if (!$admin && $field['visibility'] == 'User and User Admin Only') { unset($fields[$name]); } } if ($this->_isContactActivityProfile) { $contactFields = $activityFields = array(); foreach ($fields as $fieldName => $field) { if (CRM_Utils_Array::value('field_type', $field) == 'Activity') { $activityFields[$fieldName] = $field; } else { $contactFields[$fieldName] = $field; } } CRM_Core_BAO_UFGroup::getValues($this->_id, $contactFields, $values); if ($this->_activityId) { CRM_Core_BAO_UFGroup::getValues(NULL, $activityFields, $values, TRUE, array(array('activity_id', '=', $this->_activityId, 0, 0))); } } else { $customWhereClause = NULL; if ($this->_multiRecord & CRM_Core_Action::VIEW && $this->_recordId) { if ($this->_allFields) { $copyFields = $fields; CRM_Core_BAO_UFGroup::shiftMultiRecordFields($copyFields, $multiRecordFields); $fieldKey = key($multiRecordFields); } else { $fieldKey = key($fields); } if ($fieldID = CRM_Core_BAO_CustomField::getKeyID($fieldKey)) { $tableColumnGroup = CRM_Core_BAO_CustomField::getTableColumnGroup($fieldID); $columnName = "{$tableColumnGroup[0]}.id"; $customWhereClause = $columnName . ' = ' . $this->_recordId; } } CRM_Core_BAO_UFGroup::getValues($this->_id, $fields, $values, TRUE, NULL, FALSE, $customWhereClause); } // $profileFields array can be used for customized display of field labels and values in Profile/View.tpl $profileFields = array(); $labels = array(); foreach ($fields as $name => $field) { //CRM-14338 // Create a unique, non-empty index for each field. $index = $field['title']; if ($index === '') { $index = ' '; } while (array_key_exists($index, $labels)) { $index .= ' '; } $labels[$index] = preg_replace('/\\s+|\\W+/', '_', $name); } foreach ($values as $title => $value) { $profileFields[$labels[$title]] = array('label' => $title, 'value' => $value); } $template->assign_by_ref('row', $values); $template->assign_by_ref('profileFields', $profileFields); } $name = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'name'); $this->assign('ufGroupName', $name); CRM_Utils_Hook::viewProfile($name); if (strtolower($name) == 'summary_overlay') { $template->assign('overlayProfile', TRUE); } if ($this->_multiRecord & CRM_Core_Action::VIEW && $this->_recordId && !$this->_allFields) { $fieldDetail = reset($fields); $fieldId = CRM_Core_BAO_CustomField::getKeyID($fieldDetail['name']); $customGroupDetails = CRM_Core_BAO_CustomGroup::getGroupTitles(array($fieldId)); $multiRecTitle = $customGroupDetails[$fieldId]['groupTitle']; } else { $title = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'title'); } //CRM-4131. $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_id, 'display_name'); if ($displayName) { $session = CRM_Core_Session::singleton(); $config = CRM_Core_Config::singleton(); if ($session->get('userID') && CRM_Core_Permission::check('access CiviCRM') && CRM_Contact_BAO_Contact_Permission::allow($session->get('userID'), CRM_Core_Permission::VIEW) && !$config->userFrameworkFrontend) { $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "action=view&reset=1&cid={$this->_id}", TRUE); $this->assign('displayName', $displayName); $displayName = "<a href=\"{$contactViewUrl}\">{$displayName}</a>"; } $title .= ' - ' . $displayName; } $title = isset($multiRecTitle) ? ts('View %1 Record', array(1 => $multiRecTitle)) : $title; CRM_Utils_System::setTitle($title); // invoke the pagRun hook, CRM-3906 CRM_Utils_Hook::pageRun($this); return trim($template->fetch($this->getHookedTemplateFileName())); }
/** * @deprecated - this function formats params according to v2 standards but * need to be sure about the impact of not calling it so retaining on the import class * take the input parameter list as specified in the data model and * convert it into the same format that we use in QF and BAO object * * @param array $params Associative array of property name/value * pairs to insert in new contact. * @param array $values The reformatted properties that we can use internally * * @param array $create Is the formatted Values array going to * be used for CRM_Member_BAO_Membership:create() * * @return array|error * @access public */ function membership_format_params($params, &$values, $create = FALSE) { require_once 'api/v3/utils.php'; $fields = CRM_Member_DAO_Membership::fields(); _civicrm_api3_store_values($fields, $params, $values); $customFields = CRM_Core_BAO_CustomField::getFields('Membership'); foreach ($params as $key => $value) { // ignore empty values or empty arrays etc if (CRM_Utils_System::isNull($value)) { continue; } //Handling Custom Data if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { $values[$key] = $value; $type = $customFields[$customFieldID]['html_type']; if ($type == 'CheckBox' || $type == 'Multi-Select' || $type == 'AdvMulti-Select') { $mulValues = explode(',', $value); $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true); $values[$key] = array(); foreach ($mulValues as $v1) { foreach ($customOption as $customValueID => $customLabel) { $customValue = $customLabel['value']; if (strtolower($customLabel['label']) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) { if ($type == 'CheckBox') { $values[$key][$customValue] = 1; } else { $values[$key][] = $customValue; } } } } } } switch ($key) { case 'membership_contact_id': if (!CRM_Utils_Rule::integer($value)) { throw new Exception("contact_id not valid: {$value}"); } $dao = new CRM_Core_DAO(); $qParams = array(); $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}", $qParams); if (!$svq) { throw new Exception("Invalid Contact ID: There is no contact record with contact_id = {$value}."); } $values['contact_id'] = $values['membership_contact_id']; unset($values['membership_contact_id']); break; case 'membership_type_id': if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipType())) { throw new Exception('Invalid Membership Type Id'); } $values[$key] = $value; break; case 'membership_type': $membershipTypeId = CRM_Utils_Array::key(ucfirst($value), CRM_Member_PseudoConstant::membershipType()); if ($membershipTypeId) { if (CRM_Utils_Array::value('membership_type_id', $values) && $membershipTypeId != $values['membership_type_id']) { throw new Exception('Mismatched membership Type and Membership Type Id'); } } else { throw new Exception('Invalid Membership Type'); } $values['membership_type_id'] = $membershipTypeId; break; case 'status_id': if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipStatus())) { throw new Exception('Invalid Membership Status Id'); } $values[$key] = $value; break; case 'membership_status': $membershipStatusId = CRM_Utils_Array::key(ucfirst($value), CRM_Member_PseudoConstant::membershipStatus()); if ($membershipStatusId) { if (CRM_Utils_Array::value('status_id', $values) && $membershipStatusId != $values['status_id']) { throw new Exception('Mismatched membership Status and Membership Status Id'); } } else { throw new Exception('Invalid Membership Status'); } $values['status_id'] = $membershipStatusId; break; default: break; } } _civicrm_api3_custom_format_params($params, $values, 'Membership'); if ($create) { // CRM_Member_BAO_Membership::create() handles membership_start_date, // membership_end_date and membership_source. So, if $values contains // membership_start_date, membership_end_date or membership_source, // convert it to start_date, end_date or source $changes = array('membership_start_date' => 'start_date', 'membership_end_date' => 'end_date', 'membership_source' => 'source'); foreach ($changes as $orgVal => $changeVal) { if (isset($values[$orgVal])) { $values[$changeVal] = $values[$orgVal]; unset($values[$orgVal]); } } } return NULL; }
function whereClauseSingle(&$values) { // do not process custom fields or prefixed contact ids or component params if (CRM_Core_BAO_CustomField::getKeyID($values[0]) || substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX || substr($values[0], 0, 13) == 'contribution_' || substr($values[0], 0, 6) == 'event_' || substr($values[0], 0, 12) == 'participant_' || substr($values[0], 0, 7) == 'member_' || substr($values[0], 0, 6) == 'quest_' || substr($values[0], 0, 8) == 'kabissa_' || substr($values[0], 0, 4) == 'tmf_' || substr($values[0], 0, 6) == 'grant_' || substr($values[0], 0, 7) == 'pledge_' || substr($values[0], 0, 5) == 'case_') { return; } switch ($values[0]) { case 'deleted_contacts': $this->deletedContacts($values); return; case 'contact_type': $this->contactType($values); return; case 'contact_sub_type': $this->contactSubType($values); return; case 'group': list($name, $op, $value, $grouping, $wildcard) = $values; $this->group($values); return; // case tag comes from find contacts // case tag comes from find contacts case 'tag_search': $this->tagSearch($values); return; case 'tag': case 'contact_tags': $this->tag($values); return; case 'note': $this->notes($values); return; case 'uf_user': $this->ufUser($values); return; case 'sort_name': case 'display_name': $this->sortName($values); //force civicrm_activity_target, CRM-7812 self::$_withContactActivitiesOnly = TRUE; return; case 'email': $this->email($values); return; case 'street_address': $this->street_address($values); return; case 'street_number': $this->street_number($values); return; case 'sortByCharacter': $this->sortByCharacter($values); return; case 'location_type': $this->locationType($values); return; case 'county': $this->county($values); return; case 'state_province': $this->stateProvince($values); return; case 'country': $this->country($values, FALSE); return; case 'postal_code': case 'postal_code_low': case 'postal_code_high': $this->postalCode($values); return; case 'activity_date': case 'activity_date_low': case 'activity_date_high': case 'activity_role': case 'activity_status': case 'activity_subject': case 'test_activities': case 'activity_type_id': case 'activity_survey_id': case 'activity_tags': case 'activity_taglist': case 'activity_test': case 'activity_contact_name': case 'activity_campaign_id': case 'activity_engagement_level': case 'activity_id': CRM_Activity_BAO_Query::whereClauseSingle($values, $this); return; case 'birth_date_low': case 'birth_date_high': case 'deceased_date_low': case 'deceased_date_high': $this->demographics($values); return; case 'log_date_low': case 'log_date_high': $this->modifiedDates($values); return; case 'changed_by': $this->changeLog($values); return; case 'do_not_phone': case 'do_not_email': case 'do_not_mail': case 'do_not_sms': case 'do_not_trade': case 'is_opt_out': $this->privacy($values); return; case 'privacy_options': $this->privacyOptions($values); return; case 'privacy_operator': case 'privacy_toggle': // these are handled by privacy options return; case 'preferred_communication_method': $this->preferredCommunication($values); return; case 'relation_type_id': $this->relationship($values); return; case 'relation_target_name': // since this case is handled with the above return; case 'relation_status': // since this case is handled with the above return; case 'task_status_id': $this->task($values); return; case 'task_id': // since this case is handled with the above return; case 'prox_distance': CRM_Contact_BAO_ProximityQuery::process($this, $values); return; case 'prox_street_address': case 'prox_city': case 'prox_postal_code': case 'prox_state_province_id': case 'prox_country_id': // handled by the proximity_distance clause return; default: $this->restWhere($values); return; } }
/** * Build the form * * @access public * * @return void */ function buildQuickForm() { if (!$this->_profileId) { CRM_Core_Error::fatal(ts('Profile for bulk data entry is missing.')); } $this->addElement('hidden', 'batch_id', $this->_batchId); // get the profile information if ($this->_batchInfo['type_id'] == 1) { CRM_Utils_System::setTitle(ts('Batch Data Entry for Contributions')); $customFields = CRM_Core_BAO_CustomField::getFields('Contribution'); } else { CRM_Utils_System::setTitle(ts('Batch Data Entry for Memberships')); $customFields = CRM_Core_BAO_CustomField::getFields('Membership'); } $this->_fields = array(); $this->_fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, CRM_Core_Action::VIEW); // remove file type field and then limit fields $suppressFields = FALSE; $removehtmlTypes = array('File', 'Autocomplete-Select'); foreach ($this->_fields as $name => $field) { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && in_array($this->_fields[$name]['html_type'], $removehtmlTypes)) { $suppressFields = TRUE; unset($this->_fields[$name]); } //fix to reduce size as we are using this field in grid if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) { //shrink class to "form-text-medium" $this->_fields[$name]['attributes']['size'] = 19; } } $this->addFormRule(array('CRM_Batch_Form_Entry', 'formRule'), $this); // add the force save button $forceSave = $this->getButtonName('upload', 'force'); $this->addElement('submit', $forceSave, ts('Ignore Mismatch & Process the Batch?')); $this->addButtons(array(array('type' => 'upload', 'name' => ts('Validate & Process the Batch'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Save & Continue Later')))); $this->assign('rowCount', $this->_batchInfo['item_count'] + 1); $fileFieldExists = FALSE; $preserveDefaultsArray = array('first_name', 'last_name', 'middle_name', 'organization_name', 'household_name'); $contactTypes = array('Contact', 'Individual', 'Household', 'Organization'); $contactReturnProperties = array(); for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) { $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', array('create' => TRUE, 'placeholder' => ts('- select -'))); // special field specific to membership batch udpate if ($this->_batchInfo['type_id'] == 2) { $options = array(1 => ts('Add Membership'), 2 => ts('Renew Membership')); $this->add('select', "member_option[{$rowNumber}]", '', $options); } foreach ($this->_fields as $name => $field) { if (in_array($field['field_type'], $contactTypes)) { $fld = explode('-', $field['name']); $contactReturnProperties[$field['name']] = $fld[0]; } CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber); if (in_array($field['name'], $preserveDefaultsArray)) { $this->_preserveDefault = FALSE; } } } $this->assign('fields', $this->_fields); CRM_Core_Resources::singleton()->addSetting(array('contact' => array('return' => implode(',', $contactReturnProperties), 'fieldmap' => array_flip($contactReturnProperties)))); // don't set the status message when form is submitted. $buttonName = $this->controller->getButtonName('submit'); if ($suppressFields && $buttonName != '_qf_Entry_next') { CRM_Core_Session::setStatus(ts("FILE or Autocomplete Select type field(s) in the selected profile are not supported for Batch Update."), ts("Some fields have been excluded."), "info"); } }
/** * Function to build the array for display the profile fields * * @param array $params key value. * @param int $gid profile Id * @param array $groupTitle Profile Group Title. * @param array $values formatted array of key value * * @return None * @access public */ function displayProfile(&$params, $gid, &$groupTitle, &$values) { if ($gid) { require_once 'CRM/Core/BAO/UFGroup.php'; require_once 'CRM/Profile/Form.php'; require_once 'CRM/Event/PseudoConstant.php'; $session = CRM_Core_Session::singleton(); $contactID = $session->get('userID'); if ($contactID) { if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) { $fields = CRM_Core_BAO_UFGroup::getFields($gid, false, CRM_Core_Action::VIEW); } } else { $fields = CRM_Core_BAO_UFGroup::getFields($gid, false, CRM_Core_Action::ADD); } if (is_array($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]); } } } foreach ($fields as $v) { if (CRM_Utils_Array::value('groupTitle', $v)) { $groupTitle['groupTitle'] = $v["groupTitle"]; break; } } $config = CRM_Core_Config::singleton(); require_once 'CRM/Core/PseudoConstant.php'; $locationTypes = $imProviders = array(); $locationTypes = CRM_Core_PseudoConstant::locationType(); $imProviders = CRM_Core_PseudoConstant::IMProvider(); //start of code to set the default values foreach ($fields as $name => $field) { $index = $field['title']; $customFieldName = null; if ($name === 'organization_name') { $values[$index] = $params[$name]; } if ('state_province' == substr($name, 0, 14)) { if ($params[$name]) { $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]); } else { $values[$index] = ''; } } else { if ('country' == substr($name, 0, 7)) { if ($params[$name]) { $values[$index] = CRM_Core_PseudoConstant::country($params[$name]); } else { $values[$index] = ''; } } else { if ('county' == substr($name, 0, 6)) { if ($params[$name]) { $values[$index] = CRM_Core_PseudoConstant::county($params[$name]); } else { $values[$index] = ''; } } else { if ('gender' == substr($name, 0, 6)) { $gender = CRM_Core_PseudoConstant::gender(); $values[$index] = $gender[$params[$name]]; } else { if ('individual_prefix' == substr($name, 0, 17)) { $prefix = CRM_Core_PseudoConstant::individualPrefix(); $values[$index] = $prefix[$params[$name]]; } else { if ('individual_suffix' == substr($name, 0, 17)) { $suffix = CRM_Core_PseudoConstant::individualSuffix(); $values[$index] = $suffix[$params[$name]]; } else { if (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) { $filterCondition = array('greeting_type' => $name); $greeting =& CRM_Core_PseudoConstant::greeting($filterCondition); $values[$index] = $greeting[$params[$name]]; } else { if ($name === 'preferred_communication_method') { $communicationFields = CRM_Core_PseudoConstant::pcm(); $pref = array(); $compref = array(); $pref = $params[$name]; if (is_array($pref)) { foreach ($pref as $k => $v) { if ($v) { $compref[] = $communicationFields[$k]; } } } $values[$index] = implode(",", $compref); } else { if ($name == 'group') { require_once 'CRM/Contact/BAO/GroupContact.php'; $groups = CRM_Contact_BAO_GroupContact::getGroupList(); $title = array(); foreach ($params[$name] as $gId => $dontCare) { if ($dontCare) { $title[] = $groups[$gId]; } } $values[$index] = implode(', ', $title); } else { if ($name == 'tag') { require_once 'CRM/Core/BAO/EntityTag.php'; $entityTags = $params[$name]; $allTags =& CRM_Core_PseudoConstant::tag(); $title = array(); if (is_array($entityTags)) { foreach ($entityTags as $tagId => $dontCare) { $title[] = $allTags[$tagId]; } } $values[$index] = implode(', ', $title); } else { if ('participant_role_id' == $name) { $roles = CRM_Event_PseudoConstant::participantRole(); $values[$index] = $roles[$params[$name]]; } else { if ('participant_status_id' == $name) { $status = CRM_Event_PseudoConstant::participantStatus(); $values[$index] = $status[$params[$name]]; } else { if (strpos($name, '-') !== false) { list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2); $detailName = str_replace(' ', '_', $name); if (in_array($fieldName, array('state_province', 'country', 'county'))) { $values[$index] = $params[$detailName]; $idx = $detailName . '_id'; $values[$index] = $params[$idx]; } else { if ($fieldName == 'im') { $providerName = null; if ($providerId = $detailName . '-provider_id') { $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders); } if ($providerName) { $values[$index] = $params[$detailName] . " (" . $providerName . ")"; } else { $values[$index] = $params[$detailName]; } } else { $values[$index] = $params[$detailName]; } } } else { if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') { if ($params[$name]) { $values[$index] = '[ x ]'; } } else { require_once 'CRM/Core/BAO/CustomField.php'; if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) { $query = "\nSELECT html_type, data_type\nFROM civicrm_custom_field\nWHERE id = {$cfID}\n"; $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); $dao->fetch(); $htmlType = $dao->html_type; $dataType = $dao->data_type; if ($htmlType == 'File') { //$fileURL = CRM_Core_BAO_CustomField::getFileURL( $contactID, $cfID ); //$params[$index] = $values[$index] = $fileURL['file_url']; $values[$index] = $params[$index]; } else { if ($dao->data_type == 'Int' || $dao->data_type == 'Boolean') { $customVal = (int) $params[$name]; } else { if ($dao->data_type == 'Float') { $customVal = (double) $params[$name]; } else { if ($dao->data_type == 'Date') { $date = CRM_Utils_Date::format($params[$name], null, 'invalidDate'); if ($date != 'invalidDate') { $customVal = $date; } } else { $customVal = $params[$name]; } } } //take the custom field options $returnProperties = array($name => 1); require_once 'CRM/Contact/BAO/Query.php'; $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields); $options =& $query->_options; $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options); //Hack since we dont have function to check empty. //FIXME in 2.3 using crmIsEmptyArray() $customValue = true; if (is_array($customVal) && is_array($displayValue)) { $customValue = array_diff($customVal, $displayValue); } //use difference of arrays if (empty($customValue) || !$customValue) { $values[$index] = ''; } else { $values[$index] = $displayValue; } if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) { $customFieldName = "{$name}_from"; } } } else { if ($name == 'home_URL' && !empty($params[$name])) { $url = CRM_Utils_System::fixURL($params[$name]); $values[$index] = "<a href=\"{$url}\">{$params[$name]}</a>"; } else { if (in_array($name, array('birth_date', 'deceased_date', 'participant_register_date'))) { require_once 'CRM/Utils/Date.php'; $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name])); } else { $values[$index] = $params[$name]; } } } } } } } } } } } } } } } } } } } }
/** * returns all the rows in the given offset and rowCount * * @param enum $action the action being performed * @param int $offset the row number to start from * @param int $rowCount the number of rows to return * @param string $sort the sql string that describes the sort order * @param enum $output what should the result set include (web/email/csv) * * @return int the total number of rows for this action */ function &getRows($action, $offset, $rowCount, $sort, $output = NULL) { $config = CRM_Core_Config::singleton(); if (($output == CRM_Core_Selector_Controller::EXPORT || $output == CRM_Core_Selector_Controller::SCREEN) && $this->_formValues['radio_ts'] == 'ts_sel') { $includeContactIds = TRUE; } else { $includeContactIds = FALSE; } // note the formvalues were given by CRM_Contact_Form_Search to us // and contain the search criteria (parameters) // note that the default action is basic if ($rowCount) { $cacheKey = $this->buildPrevNextCache($sort); $result = $this->_query->getCachedContacts($cacheKey, $offset, $rowCount, $includeContactIds); } else { $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds); } // process the result of the query $rows = array(); $permissions = array(CRM_Core_Permission::getPermission()); if (CRM_Core_Permission::check('delete contacts')) { $permissions[] = CRM_Core_Permission::DELETE; } $mask = CRM_Core_Action::mask($permissions); // mask value to hide map link if there are not lat/long $mapMask = $mask & 4095; if ($this->_searchContext == 'smog') { $gc = CRM_Core_SelectValues::groupContactStatus(); } if ($this->_ufGroupID) { $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $names = array(); static $skipFields = array('group', 'tag'); foreach ($this->_fields as $key => $field) { if (!empty($field['in_selector']) && !in_array($key, $skipFields)) { if (strpos($key, '-') !== FALSE) { list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $key, 3); if ($id == 'Primary') { $locationTypeName = 1; } else { $locationTypeName = CRM_Utils_Array::value($id, $locationTypes); if (!$locationTypeName) { continue; } } $locationTypeName = str_replace(' ', '_', $locationTypeName); if (in_array($fieldName, array('phone', 'im', 'email'))) { if ($type) { $names[] = "{$locationTypeName}-{$fieldName}-{$type}"; } else { $names[] = "{$locationTypeName}-{$fieldName}"; } } else { $names[] = "{$locationTypeName}-{$fieldName}"; } } else { $names[] = $field['name']; } } } $names[] = "status"; } elseif (!empty($this->_returnProperties)) { $names = self::makeProperties($this->_returnProperties); } else { $names = self::$_properties; } $multipleSelectFields = array('preferred_communication_method' => 1); $links = self::links($this->_context, $this->_contextMenu, $this->_key); //check explicitly added contact to a Smart Group. $groupID = CRM_Utils_Array::key('1', $this->_formValues['group']); $pseudoconstants = array(); // for CRM-3157 purposes if (in_array('world_region', $names)) { $pseudoconstants['world_region'] = array('dbName' => 'world_region_id', 'values' => CRM_Core_PseudoConstant::worldRegion()); } $seenIDs = array(); while ($result->fetch()) { $row = array(); $this->_query->convertToPseudoNames($result); // the columns we are interested in foreach ($names as $property) { if ($property == 'status') { continue; } if ($cfID = CRM_Core_BAO_CustomField::getKeyID($property)) { $row[$property] = CRM_Core_BAO_CustomField::getDisplayValue($result->{$property}, $cfID, $this->_options, $result->contact_id); } elseif ($multipleSelectFields && array_key_exists($property, $multipleSelectFields)) { $key = $property; $paramsNew = array($key => $result->{$property}); $name = array($key => array('newName' => $key, 'groupName' => $key)); CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE); $row[$key] = $paramsNew[$key]; } elseif (strpos($property, '-im')) { $row[$property] = $result->{$property}; if (!empty($result->{$property})) { $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); $providerId = $property . "-provider_id"; $providerName = $imProviders[$result->{$providerId}]; $row[$property] = $result->{$property} . " ({$providerName})"; } } elseif (in_array($property, array('addressee', 'email_greeting', 'postal_greeting'))) { $greeting = $property . '_display'; $row[$property] = $result->{$greeting}; } elseif (isset($pseudoconstants[$property])) { $row[$property] = CRM_Utils_Array::value($result->{$pseudoconstants[$property]['dbName']}, $pseudoconstants[$property]['values']); } elseif (strpos($property, '-url') !== FALSE) { $websiteUrl = ''; $websiteKey = 'website-1'; $propertyArray = explode('-', $property); $websiteFld = $websiteKey . '-' . array_pop($propertyArray); if (!empty($result->{$websiteFld})) { $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'); $websiteType = $websiteTypes[$result->{"{$websiteKey}-website_type_id"}]; $websiteValue = $result->{$websiteFld}; $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue} ({$websiteType})</a>"; } $row[$property] = $websiteUrl; } else { $row[$property] = isset($result->{$property}) ? $result->{$property} : NULL; } } if (!empty($result->postal_code_suffix)) { $row['postal_code'] .= "-" . $result->postal_code_suffix; } if ($output != CRM_Core_Selector_Controller::EXPORT && $this->_searchContext == 'smog') { if (empty($result->status) && $groupID) { $contactID = $result->contact_id; if ($contactID) { $gcParams = array('contact_id' => $contactID, 'group_id' => $groupID); $gcDefaults = array(); CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults); if (empty($gcDefaults)) { $row['status'] = ts('Smart'); } else { $row['status'] = $gc[$gcDefaults['status']]; } } else { $row['status'] = NULL; } } else { $row['status'] = $gc[$result->status]; } } if ($output != CRM_Core_Selector_Controller::EXPORT) { $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contact_id; if (!empty($this->_formValues['deleted_contacts']) && CRM_Core_Permission::check('access deleted contacts')) { $links = array(array('name' => ts('View'), 'url' => 'civicrm/contact/view', 'qs' => 'reset=1&cid=%%id%%', 'class' => 'no-popup', 'title' => ts('View Contact Details')), array('name' => ts('Restore'), 'url' => 'civicrm/contact/view/delete', 'qs' => 'reset=1&cid=%%id%%&restore=1', 'title' => ts('Restore Contact'))); if (CRM_Core_Permission::check('delete contacts')) { $links[] = array('name' => ts('Delete Permanently'), 'url' => 'civicrm/contact/view/delete', 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1', 'title' => ts('Permanently Delete Contact')); } $row['action'] = CRM_Core_Action::formLink($links, NULL, array('id' => $result->contact_id), ts('more'), FALSE, 'contact.selector.row', 'Contact', $result->contact_id); } elseif (is_numeric(CRM_Utils_Array::value('geo_code_1', $row)) || $config->mapGeoCoding && !empty($row['city']) && CRM_Utils_Array::value('state_province', $row)) { $row['action'] = CRM_Core_Action::formLink($links, $mask, array('id' => $result->contact_id), ts('more'), FALSE, 'contact.selector.row', 'Contact', $result->contact_id); } else { $row['action'] = CRM_Core_Action::formLink($links, $mapMask, array('id' => $result->contact_id), ts('more'), FALSE, 'contact.selector.row', 'Contact', $result->contact_id); } // allow components to add more actions CRM_Core_Component::searchAction($row, $result->contact_id); $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id); $row['contact_type_orig'] = $result->contact_sub_type ? $result->contact_sub_type : $result->contact_type; $row['contact_sub_type'] = $result->contact_sub_type ? CRM_Contact_BAO_ContactType::contactTypePairs(FALSE, $result->contact_sub_type, ', ') : $result->contact_sub_type; $row['contact_id'] = $result->contact_id; $row['sort_name'] = $result->sort_name; if (array_key_exists('id', $row)) { $row['id'] = $result->contact_id; } } // Dedupe contacts if (in_array($row['contact_id'], $seenIDs) === FALSE) { $seenIDs[] = $row['contact_id']; $rows[] = $row; } } return $rows; }
function validate() { if (CRM_Utils_System::isNull($this->_value)) { return true; } switch ($this->_name) { case 'contact_id': // note: we validate extistence of the contact in API, upon // insert (it would be too costlty to do a db call here) return CRM_Utils_Rule::integer($this->_value); break; case 'receive_date': case 'cancel_date': case 'receipt_date': case 'thankyou_date': return CRM_Utils_Rule::date($this->_value); break; case 'non_deductible_amount': case 'total_amount': case 'fee_amount': case 'net_amount': return CRM_Utils_Rule::money($this->_value); break; case 'trxn_id': static $seenTrxnIds = array(); if (in_array($this->_value, $seenTrxnIds)) { return false; } elseif ($this->_value) { $seenTrxnIds[] = $this->_value; return true; } else { $this->_value = null; return true; } break; case 'currency': return CRM_Utils_Rule::currencyCode($this->_value); break; case 'contribution_type': static $contributionTypes = null; if (!$contributionTypes) { $contributionTypes =& CRM_Contribute_PseudoConstant::contributionType(); } if (in_array($this->_value, $contributionTypes)) { return true; } else { return false; } break; case 'payment_instrument': static $paymentInstruments = null; if (!$paymentInstruments) { $paymentInstruments =& CRM_Contribute_PseudoConstant::paymentInstrument(); } if (in_array($this->_value, $paymentInstruments)) { return true; } else { return false; } break; default: break; } // check whether that's a valid custom field id // and if so, check the contents' validity if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($this->_name)) { static $customFields = null; if (!$customFields) { $customFields =& CRM_Core_BAO_CustomField::getFields('Contribution'); } if (!array_key_exists($customFieldID, $customFields)) { return false; } return CRM_Core_BAO_CustomValue::typecheck($customFields[$customFieldID]['data_type'], $this->_value); } return true; }
/** * Get the list the export fields. * * @param int $selectAll * User preference while export. * @param array $ids * Contact ids. * @param array $params * Associated array of fields. * @param string $order * Order by clause. * @param array $fields * Associated array of fields. * @param array $moreReturnProperties * Additional return fields. * @param int $exportMode * Export mode. * @param string $componentClause * Component clause. * @param string $componentTable * Component table. * @param bool $mergeSameAddress * Merge records if they have same address. * @param bool $mergeSameHousehold * Merge records if they belong to the same household. * * @param array $exportParams * @param string $queryOperator * */ public static function exportComponents($selectAll, $ids, $params, $order = NULL, $fields = NULL, $moreReturnProperties = NULL, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = NULL, $componentTable = NULL, $mergeSameAddress = FALSE, $mergeSameHousehold = FALSE, $exportParams = array(), $queryOperator = 'AND') { $headerRows = $returnProperties = array(); $primary = $paymentFields = $selectedPaymentFields = FALSE; $origFields = $fields; $relationField = NULL; $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE, 'name', FALSE); $queryMode = self::getQueryMode($exportMode); if ($fields) { //construct return properties $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im'); foreach ($fields as $key => $value) { $phoneTypeId = $imProviderId = NULL; $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value); if (!$fieldName) { continue; } // get phoneType id and IM service provider id separately if ($fieldName == 'phone') { $phoneTypeId = CRM_Utils_Array::value(3, $value); } elseif ($fieldName == 'im') { $imProviderId = CRM_Utils_Array::value(3, $value); } if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) { if (!empty($value[2])) { $relationField = CRM_Utils_Array::value(2, $value); if (trim(CRM_Utils_Array::value(3, $value))) { $relLocTypeId = CRM_Utils_Array::value(3, $value); } else { $relLocTypeId = 'Primary'; } if ($relationField == 'phone') { $relPhoneTypeId = CRM_Utils_Array::value(4, $value); } elseif ($relationField == 'im') { $relIMProviderId = CRM_Utils_Array::value(4, $value); } } elseif (!empty($value[4])) { $relationField = CRM_Utils_Array::value(4, $value); $relLocTypeId = CRM_Utils_Array::value(5, $value); if ($relationField == 'phone') { $relPhoneTypeId = CRM_Utils_Array::value(6, $value); } elseif ($relationField == 'im') { $relIMProviderId = CRM_Utils_Array::value(6, $value); } } } $contactType = CRM_Utils_Array::value(0, $value); $locTypeId = CRM_Utils_Array::value(2, $value); if ($relationField) { if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) { if ($relPhoneTypeId) { $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1; } elseif ($relIMProviderId) { $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1; } else { $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1; } $relPhoneTypeId = $relIMProviderId = NULL; } else { $returnProperties[$relationshipTypes][$relationField] = 1; } } elseif (is_numeric($locTypeId)) { if ($phoneTypeId) { $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1; } elseif ($imProviderId) { $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1; } else { $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1; } } else { //hack to fix component fields //revert mix of event_id and title if ($fieldName == 'event_id') { $returnProperties['event_id'] = 1; } elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT && array_key_exists($fieldName, self::componentPaymentFields())) { $selectedPaymentFields = TRUE; $paymentTableId = 'participant_id'; $returnProperties[$fieldName] = 1; } else { $returnProperties[$fieldName] = 1; } } } $returnProperties[self::defaultReturnProperty($exportMode)] = 1; } else { $primary = TRUE; $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE); foreach ($fields as $key => $var) { if ($key && substr($key, 0, 6) != 'custom') { //for CRM=952 $returnProperties[$key] = 1; } } if ($primary) { $returnProperties['location_type'] = 1; $returnProperties['im_provider'] = 1; $returnProperties['phone_type_id'] = 1; $returnProperties['provider_id'] = 1; $returnProperties['current_employer'] = 1; } $extraReturnProperties = array(); $paymentFields = FALSE; switch ($queryMode) { case CRM_Contact_BAO_Query::MODE_EVENT: $paymentFields = TRUE; $paymentTableId = 'participant_id'; break; case CRM_Contact_BAO_Query::MODE_MEMBER: $paymentFields = TRUE; $paymentTableId = 'membership_id'; break; case CRM_Contact_BAO_Query::MODE_PLEDGE: $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode); $paymentFields = TRUE; $paymentTableId = 'pledge_payment_id'; break; case CRM_Contact_BAO_Query::MODE_CASE: $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode); break; } if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) { $componentReturnProperties = CRM_Contact_BAO_Query::defaultReturnProperties($queryMode); if ($queryMode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) { // soft credit columns are not automatically populated, because contribution search doesn't require them by default $componentReturnProperties = array_merge($componentReturnProperties, CRM_Contribute_BAO_Query::softCreditReturnProperties(TRUE)); } $returnProperties = array_merge($returnProperties, $componentReturnProperties); if (!empty($extraReturnProperties)) { $returnProperties = array_merge($returnProperties, $extraReturnProperties); } // unset non exportable fields for components $nonExpoFields = array('groups', 'tags', 'notes', 'contribution_status_id', 'pledge_status_id', 'pledge_payment_status_id'); foreach ($nonExpoFields as $value) { unset($returnProperties[$value]); } } } if ($mergeSameAddress) { //make sure the addressee fields are selected //while using merge same address feature $returnProperties['addressee'] = 1; $returnProperties['postal_greeting'] = 1; $returnProperties['email_greeting'] = 1; $returnProperties['street_name'] = 1; $returnProperties['household_name'] = 1; $returnProperties['street_address'] = 1; $returnProperties['city'] = 1; $returnProperties['state_province'] = 1; // some columns are required for assistance incase they are not already present $exportParams['merge_same_address']['temp_columns'] = array(); $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id'); foreach ($tempColumns as $column) { if (!array_key_exists($column, $returnProperties)) { $returnProperties[$column] = 1; $column = $column == 'id' ? 'civicrm_primary_id' : $column; $exportParams['merge_same_address']['temp_columns'][$column] = 1; } } } if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) { // If an Additional Group is selected, then all contacts in that group are // added to the export set (filtering out duplicates). $query = "\nINSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_contact gc WHERE gc.group_id = {$exportParams['additional_group']} ON DUPLICATE KEY UPDATE {$componentTable}.contact_id = gc.contact_id"; CRM_Core_DAO::executeQuery($query); } if ($moreReturnProperties) { // fix for CRM-7066 if (!empty($moreReturnProperties['group'])) { unset($moreReturnProperties['group']); $moreReturnProperties['groups'] = 1; } $returnProperties = array_merge($returnProperties, $moreReturnProperties); } $exportParams['postal_mailing_export']['temp_columns'] = array(); if ($exportParams['exportOption'] == 2 && isset($exportParams['postal_mailing_export']) && CRM_Utils_Array::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1) { $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'); foreach ($postalColumns as $column) { if (!array_key_exists($column, $returnProperties)) { $returnProperties[$column] = 1; $exportParams['postal_mailing_export']['temp_columns'][$column] = 1; } } } // rectify params to what proximity search expects if there is a value for prox_distance // CRM-7021 if (!empty($params)) { CRM_Contact_BAO_ProximityQuery::fixInputParams($params); } $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL, FALSE, FALSE, $queryMode, FALSE, TRUE, TRUE, NULL, $queryOperator); //sort by state //CRM-15301 $query->_sort = $order; list($select, $from, $where, $having) = $query->query(); if ($mergeSameHousehold == 1) { if (!$returnProperties['id']) { $returnProperties['id'] = 1; } //also merge Head of Household $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes); $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes); foreach ($returnProperties as $key => $value) { if (!array_key_exists($key, $contactRelationshipTypes)) { $returnProperties[$relationKeyMOH][$key] = $value; $returnProperties[$relationKeyHOH][$key] = $value; } } unset($returnProperties[$relationKeyMOH]['location_type']); unset($returnProperties[$relationKeyMOH]['im_provider']); unset($returnProperties[$relationKeyHOH]['location_type']); unset($returnProperties[$relationKeyHOH]['im_provider']); } $allRelContactArray = $relationQuery = array(); foreach ($contactRelationshipTypes as $rel => $dnt) { if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) { $allRelContactArray[$rel] = array(); // build Query for each relationship $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties, NULL, FALSE, FALSE, $queryMode); list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query(); list($id, $direction) = explode('_', $rel, 2); // identify the relationship direction $contactA = 'contact_id_a'; $contactB = 'contact_id_b'; if ($direction == 'b_a') { $contactA = 'contact_id_b'; $contactB = 'contact_id_a'; } if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) { $relIDs = $ids; } elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) { $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source'); $query = "SELECT contact_id FROM civicrm_activity_contact\n WHERE activity_id IN ( " . implode(',', $ids) . ") AND\n record_type_id = {$sourceID}"; $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $relIDs[] = $dao->contact_id; } } else { $component = self::exportComponent($exportMode); if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) { $relIDs = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids); } else { $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component); } } $relationshipJoin = $relationshipClause = ''; if (!$selectAll && $componentTable) { $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}"; } elseif (!empty($relIDs)) { $relID = implode(',', $relIDs); $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )"; } $relationFrom = " {$relationFrom}\n INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}\n {$relationshipJoin} "; //check for active relationship status only $today = date('Ymd'); $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )"; $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}"; $relationGroupBy = " GROUP BY crel.{$contactA}"; $relationSelect = "{$relationSelect}, {$contactA} as refContact "; $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere} {$relationHaving} {$relationGroupBy}"; $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString); while ($allRelContactDAO->fetch()) { //FIX Me: Migrate this to table rather than array // build the array of all related contacts $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone $allRelContactDAO; } $allRelContactDAO->free(); } } // make sure the groups stuff is included only if specifically specified // by the fields param (CRM-1969), else we limit the contacts outputted to only // ones that are part of a group if (!empty($returnProperties['groups'])) { $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )"; $newClause = " ( {$oldClause} AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )"; // total hack for export, CRM-3618 $from = str_replace($oldClause, $newClause, $from); } if (!$selectAll && $componentTable) { $from .= " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = contact_a.id "; } elseif ($componentClause) { if (empty($where)) { $where = "WHERE {$componentClause}"; } else { $where .= " AND {$componentClause}"; } } // CRM-13982 - check if is deleted $excludeTrashed = TRUE; foreach ($params as $value) { if ($value[0] == 'contact_is_deleted') { $excludeTrashed = FALSE; } } $trashClause = $excludeTrashed ? "contact_a.is_deleted != 1" : "( 1 )"; if (empty($where)) { $where = "WHERE {$trashClause}"; } else { $where .= " AND {$trashClause}"; } $queryString = "{$select} {$from} {$where} {$having}"; $groupBy = ""; if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) || CRM_Utils_Array::value('notes', $returnProperties) || $queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy) { $groupBy = " GROUP BY contact_a.id"; } switch ($exportMode) { case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: $groupBy = 'GROUP BY civicrm_contribution.id'; if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) { // especial group by when soft credit columns are included $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id'; } break; case CRM_Export_Form_Select::EVENT_EXPORT: $groupBy = 'GROUP BY civicrm_participant.id'; break; case CRM_Export_Form_Select::MEMBER_EXPORT: $groupBy = " GROUP BY civicrm_membership.id"; break; } if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) { $groupBy = " GROUP BY civicrm_activity.id "; } $queryString .= $groupBy; // always add contact_a.id to the ORDER clause // so the order is deterministic //CRM-15301 if (strpos('contact_a.id', $order) === FALSE) { $order .= ", contact_a.id"; } if ($order) { list($field, $dir) = explode(' ', $order, 2); $field = trim($field); if (!empty($returnProperties[$field])) { //CRM-15301 $queryString .= " ORDER BY {$order}"; } } $multipleSelectFields = array('preferred_communication_method' => 1); $addPaymentHeader = FALSE; $paymentDetails = array(); if ($paymentFields || $selectedPaymentFields) { // get payment related in for event and members $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids); //get all payment headers. // If we haven't selected specific payment fields, load in all the // payment headers. if (!$selectedPaymentFields) { $paymentHeaders = self::componentPaymentFields(); if (!empty($paymentDetails)) { $addPaymentHeader = TRUE; } } else { $paymentHeaders = array(); } $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL); } $componentDetails = $headerRows = $sqlColumns = array(); $setHeader = TRUE; $rowCount = self::EXPORT_ROW_COUNT; $offset = 0; // we write to temp table often to avoid using too much memory $tempRowCount = 100; $count = -1; // for CRM-3157 purposes $i18n = CRM_Core_I18n::singleton(); $outputColumns = array(); //@todo - it would be clearer to start defining output columns earlier in this function rather than stick with return properties until this point // as the array is not actually 'returnProperties' after the sql query is formed - making the alterations to it confusing foreach ($returnProperties as $key => $value) { $outputColumns[$key] = $value; } while (1) { $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}"; $dao = CRM_Core_DAO::executeQuery($limitQuery); if ($dao->N <= 0) { break; } while ($dao->fetch()) { $count++; $row = array(); //convert the pseudo constants // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned // temporary iterationDAO object to get around it. // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object // these additional properties are NOT reset when the $dao cycles through the while loop // nor are they overwritten as they are not in the loop // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the // relevant property is set. // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the // export class before tackling a better architectural fix $iterationDAO = clone $dao; $query->convertToPseudoNames($iterationDAO); //first loop through output columns so that we return what is required, and in same order. $relationshipField = 0; foreach ($outputColumns as $field => $value) { //we should set header only once if ($setHeader) { $sqlDone = FALSE; // Split campaign into 2 fields for id and title if (substr($field, -14) == 'campaign_title') { $headerRows[] = ts('Campaign Title'); } elseif (substr($field, -11) == 'campaign_id') { $headerRows[] = ts('Campaign ID'); } elseif (isset($query->_fields[$field]['title'])) { $headerRows[] = $query->_fields[$field]['title']; } elseif ($field == 'phone_type_id') { $headerRows[] = ts('Phone Type'); } elseif ($field == 'provider_id') { $headerRows[] = ts('IM Service Provider'); } elseif (is_array($value) && $field == 'location') { // fix header for location type case foreach ($value as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title']; if (!empty($type[1])) { if (CRM_Utils_Array::value(0, $type) == 'phone') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes); } elseif (CRM_Utils_Array::value(0, $type) == 'im') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders); } } $headerRows[] = $hdr; self::sqlColumnDefn($query, $sqlColumns, $hdr); } $sqlDone = TRUE; } } elseif (substr($field, 0, 5) == 'case_') { if ($query->_fields['case'][$field]['title']) { $headerRows[] = $query->_fields['case'][$field]['title']; } elseif ($query->_fields['activity'][$field]['title']) { $headerRows[] = $query->_fields['activity'][$field]['title']; } } elseif (array_key_exists($field, $contactRelationshipTypes)) { $relName = $field; foreach ($value as $relationField => $relationValue) { // below block is same as primary block (duplicate) if (isset($relationQuery[$field]->_fields[$relationField]['title'])) { if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') { $headerName = $field . '-' . $relationField; } else { if ($relationField == 'current_employer') { $headerName = $field . '-' . 'current_employer'; } else { $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name']; } } $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } elseif ($relationField == 'phone_type_id') { $headerName = $field . '-' . 'Phone Type'; $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } elseif ($relationField == 'provider_id') { $headerName = $field . '-' . 'Im Service Provider'; $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } elseif ($relationField == 'state_province_id') { $headerName = $field . '-' . 'state_province_id'; $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } elseif (is_array($relationValue) && $relationField == 'location') { // fix header for location type case foreach ($relationValue as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title']; if (!empty($type[1])) { if (CRM_Utils_Array::value(0, $type) == 'phone') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes); } elseif (CRM_Utils_Array::value(0, $type) == 'im') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders); } } $headerName = $field . '-' . $hdr; $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } } } } } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) { $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields()); } else { $headerRows[] = $field; } if (!$sqlDone) { self::sqlColumnDefn($query, $sqlColumns, $field); } } // add im_provider to $dao object if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) { $iterationDAO->im_provider = $iterationDAO->provider_id; } //build row values (data) $fieldValue = NULL; if (property_exists($iterationDAO, $field)) { $fieldValue = $iterationDAO->{$field}; // to get phone type from phone type id if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) { $fieldValue = $phoneTypes[$fieldValue]; } elseif ($field == 'provider_id' || $field == 'im_provider') { $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders); } elseif ($field == 'master_id') { $masterAddressId = NULL; if (isset($iterationDAO->master_id)) { $masterAddressId = $iterationDAO->master_id; } // get display name of contact that address is shared. $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id); } } if ($field == 'id') { $row[$field] = $iterationDAO->contact_id; // special case for calculated field } elseif ($field == 'source_contact_id') { $row[$field] = $iterationDAO->contact_id; } elseif ($field == 'pledge_balance_amount') { $row[$field] = $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid; // special case for calculated field } elseif ($field == 'pledge_next_pay_amount') { $row[$field] = $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount; } elseif (is_array($value) && $field == 'location') { // fix header for location type case foreach ($value as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $fldValue = "{$ltype}-" . $type[0]; // CRM-14076 - fix label to work as the query object expects // FIXME: We should not be using labels as keys! $daoField = CRM_Utils_String::munge($ltype) . '-' . $type[0]; if (!empty($type[1])) { $fldValue .= "-" . $type[1]; $daoField .= "-" . $type[1]; } // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context) switch ($fld) { case 'country': case 'world_region': $row[$fldValue] = $i18n->crm_translate($iterationDAO->{$daoField}, array('context' => 'country')); break; case 'state_province': $row[$fldValue] = $i18n->crm_translate($iterationDAO->{$daoField}, array('context' => 'province')); break; case 'im_provider': $imFieldvalue = $daoField . "-provider_id"; $row[$fldValue] = CRM_Utils_Array::value($iterationDAO->{$imFieldvalue}, $imProviders); break; default: $row[$fldValue] = $iterationDAO->{$daoField}; break; } } } } elseif (array_key_exists($field, $contactRelationshipTypes)) { $relDAO = CRM_Utils_Array::value($iterationDAO->contact_id, $allRelContactArray[$field]); $relationQuery[$field]->convertToPseudoNames($relDAO); foreach ($value as $relationField => $relationValue) { if (is_object($relDAO) && property_exists($relDAO, $relationField)) { $fieldValue = $relDAO->{$relationField}; if ($relationField == 'phone_type_id') { $fieldValue = $phoneTypes[$relationValue]; } elseif ($relationField == 'provider_id') { $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders); } elseif (is_object($relDAO) && in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) { //special case for greeting replacement $fldValue = "{$relationField}_display"; $fieldValue = $relDAO->{$fldValue}; } } elseif (is_object($relDAO) && $relationField == 'state_province') { $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id); } elseif (is_object($relDAO) && $relationField == 'country') { $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id); } else { $fieldValue = ''; } $field = $field . '_'; if (array_key_exists($relationField, $multipleSelectFields)) { $param = array($relationField => $fieldValue); $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField)); CRM_Core_OptionGroup::lookupValues($param, $names, FALSE); $fieldValue = $param[$relationField]; } if (is_object($relDAO) && $relationField == 'id') { $row[$field . $relationField] = $relDAO->contact_id; } elseif (is_array($relationValue) && $relationField == 'location') { foreach ($relationValue as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $fldValue = "{$ltype}-" . $type[0]; if (!empty($type[1])) { $fldValue .= "-" . $type[1]; } // CRM-3157: localise country, region (both have ‘country’ context) // and state_province (‘province’ context) switch (TRUE) { case !is_object($relDAO): $row[$field . '_' . $fldValue] = ''; break; case in_array('country', $type): case in_array('world_region', $type): $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'country')); break; case in_array('state_province', $type): $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'province')); break; default: $row[$field . '_' . $fldValue] = $relDAO->{$fldValue}; break; } } } } elseif (isset($fieldValue) && $fieldValue != '') { //check for custom data if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) { $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $relationQuery[$field]->_options); } else { //normal relationship fields // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context) switch ($relationField) { case 'country': case 'world_region': $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country')); break; case 'state_province': $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province')); break; default: $row[$field . $relationField] = $fieldValue; break; } } } else { // if relation field is empty or null $row[$field . $relationField] = ''; } } } elseif (isset($fieldValue) && $fieldValue != '') { //check for custom data if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) { $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options); } elseif (array_key_exists($field, $multipleSelectFields)) { //option group fixes $paramsNew = array($field => $fieldValue); if ($field == 'test_tutoring') { $name = array($field => array('newName' => $field, 'groupName' => 'test')); // for readers group } elseif (substr($field, 0, 4) == 'cmr_') { $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3))); } else { $name = array($field => array('newName' => $field, 'groupName' => $field)); } CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE); $row[$field] = $paramsNew[$field]; } elseif (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) { //special case for greeting replacement $fldValue = "{$field}_display"; $row[$field] = $iterationDAO->{$fldValue}; } else { //normal fields with a touch of CRM-3157 switch ($field) { case 'country': case 'world_region': $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country')); break; case 'state_province': $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province')); break; case 'gender': case 'preferred_communication_method': case 'preferred_mail_format': case 'communication_style': $row[$field] = $i18n->crm_translate($fieldValue); break; default: $row[$field] = $fieldValue; break; } } } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) { $paymentData = CRM_Utils_Array::value($iterationDAO->{$paymentTableId}, $paymentDetails); $payFieldMapper = array('componentPaymentField_total_amount' => 'total_amount', 'componentPaymentField_contribution_status' => 'contribution_status', 'componentPaymentField_payment_instrument' => 'pay_instru', 'componentPaymentField_transaction_id' => 'trxn_id', 'componentPaymentField_received_date' => 'receive_date'); $row[$field] = CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, ''); } else { // if field is empty or null $row[$field] = ''; } } // add payment headers if required if ($addPaymentHeader && $paymentFields) { $headerRows = array_merge($headerRows, $paymentHeaders); foreach (array_keys($paymentHeaders) as $paymentHdr) { self::sqlColumnDefn($query, $sqlColumns, $paymentHdr); } } if ($setHeader) { $exportTempTable = self::createTempTable($sqlColumns); } //build header only once $setHeader = FALSE; // If specific payment fields have been selected for export, payment // data will already be in $row. Otherwise, add payment related // information, if appropriate. if ($addPaymentHeader) { if (!$selectedPaymentFields) { if ($paymentFields) { $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails); if (!is_array($paymentData) || empty($paymentData)) { $paymentData = $nullContributionDetails; } $row = array_merge($row, $paymentData); } elseif (!empty($paymentDetails)) { $row = array_merge($row, $nullContributionDetails); } } } //remove organization name for individuals if it is set for current employer if (!empty($row['contact_type']) && $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)) { $row['organization_name'] = ''; } // add component info // write the row to a file $componentDetails[] = $row; // output every $tempRowCount rows if ($count % $tempRowCount == 0) { self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns); $componentDetails = array(); } } $dao->free(); $offset += $rowCount; } if ($exportTempTable) { self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns); // do merge same address and merge same household processing if ($mergeSameAddress) { self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams); } // merge the records if they have corresponding households if ($mergeSameHousehold) { self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH); self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH); } // fix the headers for rows with relationship type if (!empty($relName)) { self::manipulateHeaderRows($headerRows, $contactRelationshipTypes); } // if postalMailing option is checked, exclude contacts who are deceased, have // "Do not mail" privacy setting, or have no street address if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) && $exportParams['postal_mailing_export']['postal_mailing_export'] == 1) { self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode); } // call export hook CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode); // now write the CSV file self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode); // delete the export temp table and component table $sql = "DROP TABLE IF EXISTS {$exportTempTable}"; CRM_Core_DAO::executeQuery($sql); CRM_Utils_System::civiExit(); } else { CRM_Core_Error::fatal(ts('No records to export')); } }
/** * Get the where clause for a single field. * * @param array $values */ public function whereClauseSingle(&$values) { // do not process custom fields or prefixed contact ids or component params if (CRM_Core_BAO_CustomField::getKeyID($values[0]) || substr($values[0], 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX || substr($values[0], 0, 13) == 'contribution_' || substr($values[0], 0, 6) == 'event_' || substr($values[0], 0, 12) == 'participant_' || substr($values[0], 0, 7) == 'member_' || substr($values[0], 0, 6) == 'grant_' || substr($values[0], 0, 7) == 'pledge_' || substr($values[0], 0, 5) == 'case_' || substr($values[0], 0, 10) == 'financial_' || substr($values[0], 0, 8) == 'payment_' || substr($values[0], 0, 11) == 'membership_') { return; } // skip for hook injected fields / params $extFields = CRM_Contact_BAO_Query_Hook::singleton()->getFields(); if (array_key_exists($values[0], $extFields)) { return; } switch ($values[0]) { case 'deleted_contacts': $this->deletedContacts($values); return; case 'contact_type': $this->contactType($values); return; case 'contact_sub_type': $this->contactSubType($values); return; case 'group': $this->group($values); return; case 'group_type': // so we resolve this into a list of groups & proceed as if they had been // handed in list($name, $op, $value, $grouping, $wildcard) = $values; $values[0] = 'group'; $values[1] = 'IN'; $this->_paramLookup['group'][0][0] = 'group'; $this->_paramLookup['group'][0][1] = 'IN'; $this->_paramLookup['group'][0][2] = $values[2] = $this->getGroupsFromTypeCriteria($value); $this->group($values); return; // case tag comes from find contacts // case tag comes from find contacts case 'tag_search': $this->tagSearch($values); return; case 'tag': case 'contact_tags': $this->tag($values); return; case 'note': case 'note_body': case 'note_subject': $this->notes($values); return; case 'uf_user': $this->ufUser($values); return; case 'sort_name': case 'display_name': $this->sortName($values); return; case 'addressee': case 'postal_greeting': case 'email_greeting': $this->greetings($values); return; case 'email': $this->email($values); return; case 'phone_numeric': $this->phone_numeric($values); return; case 'phone_phone_type_id': case 'phone_location_type_id': $this->phone_option_group($values); return; case 'street_address': $this->street_address($values); return; case 'street_number': $this->street_number($values); return; case 'sortByCharacter': $this->sortByCharacter($values); return; case 'location_type': $this->locationType($values); return; case 'county': $this->county($values); return; case 'state_province': $this->stateProvince($values); return; case 'country': $this->country($values, FALSE); return; case 'postal_code': case 'postal_code_low': case 'postal_code_high': $this->postalCode($values); return; case 'activity_date': case 'activity_date_low': case 'activity_date_high': case 'activity_role': case 'activity_status_id': case 'activity_status': case 'followup_parent_id': case 'parent_id': case 'source_contact_id': case 'activity_subject': case 'test_activities': case 'activity_type_id': case 'activity_type': case 'activity_survey_id': case 'activity_tags': case 'activity_taglist': case 'activity_test': case 'activity_campaign_id': case 'activity_engagement_level': case 'activity_id': case 'activity_result': case 'source_contact': CRM_Activity_BAO_Query::whereClauseSingle($values, $this); return; case 'age_low': case 'age_high': case 'birth_date_low': case 'birth_date_high': case 'deceased_date_low': case 'deceased_date_high': $this->demographics($values); return; case 'age_asof_date': // handled by demographics return; case 'log_date_low': case 'log_date_high': $this->modifiedDates($values); return; case 'changed_by': $this->changeLog($values); return; case 'do_not_phone': case 'do_not_email': case 'do_not_mail': case 'do_not_sms': case 'do_not_trade': case 'is_opt_out': $this->privacy($values); return; case 'privacy_options': $this->privacyOptions($values); return; case 'privacy_operator': case 'privacy_toggle': // these are handled by privacy options return; case 'preferred_communication_method': $this->preferredCommunication($values); return; case 'relation_type_id': case 'relation_start_date_high': case 'relation_start_date_low': case 'relation_end_date_high': case 'relation_end_date_low': case 'relation_target_name': case 'relation_status': case 'relation_date_low': case 'relation_date_high': $this->relationship($values); $this->_relationshipValuesAdded = TRUE; return; case 'task_status_id': $this->task($values); return; case 'task_id': // since this case is handled with the above return; case 'prox_distance': CRM_Contact_BAO_ProximityQuery::process($this, $values); return; case 'prox_street_address': case 'prox_city': case 'prox_postal_code': case 'prox_state_province_id': case 'prox_country_id': // handled by the proximity_distance clause return; default: $this->restWhere($values); return; } }