public function testGetDisplayedValues()
 {
     $customGroup = Custom::createGroup(array(), 'Individual');
     $fields = array('label' => 'testCountryFld1', 'data_type' => 'Country', 'html_type' => 'Select Country', 'is_active' => 1, 'default_value' => 1228, 'custom_group_id' => $customGroup->id);
     $customField1 = CRM_Core_BAO_CustomField::create($fields);
     $customFieldID1 = $this->assertDBNotNull('CRM_Core_DAO_CustomField', $customGroup->id, 'id', 'custom_group_id', 'Database check for created CustomField.');
     $options = array();
     $options[$customFieldID1]['attributes'] = array('label' => 'testCountryFld1', 'data_type' => 'Country', 'html_type' => 'Select Country');
     $display = CRM_Core_BAO_CustomField::getDisplayValue($fields['default_value'], $customFieldID1, $options);
     $this->assertEquals('UNITED STATES', $display, 'Confirm Country display Name');
     Custom::deleteGroup($customGroup);
 }
Example #2
0
 /**
  * Function to 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  $associated array of fields
  * @param array  $moreReturnProperties additional return fields
  * @param int    $exportMode export mode
  * @param string $componentClause component clause
  *
  * @static
  * @access public
  */
 static function exportComponents($selectAll, $ids, $params, $order = null, $fields = null, $moreReturnProperties = null, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = null)
 {
     $headerRows = array();
     $primary = false;
     $returnProperties = array();
     $origFields = $fields;
     $queryMode = null;
     $paymentFields = false;
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true, 'label', false);
     $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
             break;
         case CRM_Export_Form_Select::PLEDGE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
             break;
         case CRM_Export_Form_Select::CASE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CASE;
             break;
     }
     require_once 'CRM/Core/BAO/CustomField.php';
     if ($fields) {
         //construct return properties
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $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 = null;
             $imProviderId = null;
             $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
             if (!$fieldName) {
                 continue;
             }
             // get phoneType id and IM service provider id seperately
             if ($fieldName == 'phone') {
                 $phoneTypeId = CRM_Utils_Array::value(3, $value);
             } else {
                 if ($fieldName == 'im') {
                     $imProviderId = CRM_Utils_Array::value(3, $value);
                 }
             }
             if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
                 if (CRM_Utils_Array::value(2, $value)) {
                     $relationField = CRM_Utils_Array::value(2, $value);
                     if (trim(CRM_Utils_Array::value(3, $value))) {
                         $relLocTypeId = CRM_Utils_Array::value(3, $value);
                     } else {
                         $relLocTypeId = 1;
                     }
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
                     } else {
                         if ($relationField == 'im') {
                             $relIMProviderId = CRM_Utils_Array::value(4, $value);
                         }
                     }
                 } else {
                     if (CRM_Utils_Array::value(4, $value)) {
                         $relationField = CRM_Utils_Array::value(4, $value);
                         $relLocTypeId = CRM_Utils_Array::value(5, $value);
                         if ($relationField == 'phone') {
                             $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
                         } else {
                             if ($relationField == 'im') {
                                 $relIMProviderId = CRM_Utils_Array::value(6, $value);
                             }
                         }
                     }
                 }
             }
             $contactType = CRM_Utils_Array::value(0, $value);
             $locTypeId = CRM_Utils_Array::value(2, $value);
             $phoneTypeId = CRM_Utils_Array::value(3, $value);
             if ($relationField) {
                 if (in_array($relationField, $locationTypeFields)) {
                     if ($relPhoneTypeId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
                     } else {
                         if ($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;
                 }
             } else {
                 if (is_numeric($locTypeId)) {
                     if ($phoneTypeId) {
                         $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
                     } else {
                         if (isset($imProviderId)) {
                             //build returnProperties for IM service provider
                             $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
                         } else {
                             $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
                         }
                     }
                 } else {
                     //hack to fix component fields
                     if ($fieldName == 'event_id') {
                         $returnProperties['event_title'] = 1;
                     } else {
                         $returnProperties[$fieldName] = 1;
                     }
                 }
             }
         }
         // hack to add default returnproperty based on export mode
         if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
             $returnProperties['contribution_id'] = 1;
         } else {
             if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
                 $returnProperties['participant_id'] = 1;
             } else {
                 if ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
                     $returnProperties['membership_id'] = 1;
                 } else {
                     if ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
                         $returnProperties['pledge_id'] = 1;
                     } else {
                         if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
                             $returnProperties['case_id'] = 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:
                 require_once 'CRM/Pledge/BAO/Query.php';
                 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
                 $paymentFields = true;
                 $paymentTableId = "pledge_payment_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_CASE:
                 require_once 'CRM/Case/BAO/Query.php';
                 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
                 break;
         }
         if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
             $componentReturnProperties =& CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
             $returnProperties = array_merge($returnProperties, $componentReturnProperties);
             if (!empty($extraReturnProperties)) {
                 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
             }
             // unset groups, tags, notes for components
             foreach (array('groups', 'tags', 'notes') as $value) {
                 unset($returnProperties[$value]);
             }
         }
     }
     if ($moreReturnProperties) {
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $query =& new CRM_Contact_BAO_Query(0, $returnProperties, null, false, false, $queryMode);
     list($select, $from, $where) = $query->query();
     // 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 (CRM_Utils_Array::value('groups', $returnProperties)) {
         $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 ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     $queryString = "{$select} {$from} {$where}";
     if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties) || CRM_Utils_Array::value('notes', $returnProperties) || $query->_useGroupBy) {
         $queryString .= " GROUP BY contact_a.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (CRM_Utils_Array::value($field, $returnProperties)) {
             $queryString .= " ORDER BY {$order}";
         }
     }
     //hack for student data
     require_once 'CRM/Core/OptionGroup.php';
     $multipleSelectFields = array('preferred_communication_method' => 1);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $studentFields = array();
         $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields;
         $multipleSelectFields = array_merge($multipleSelectFields, $studentFields);
     }
     $dao =& CRM_Core_DAO::executeQuery($queryString, CRM_Core_DAO::$_nullArray);
     $header = false;
     $addPaymentHeader = false;
     if ($paymentFields) {
         $addPaymentHeader = true;
         //special return properties for event and members
         $paymentHeaders = array(ts('Total Amount'), ts('Contribution Status'), ts('Received Date'), ts('Payment Instrument'), ts('Transaction ID'));
         // get payment related in for event and members
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
     }
     $componentDetails = $headerRows = array();
     $setHeader = true;
     while ($dao->fetch()) {
         $row = array();
         //first loop through returnproperties so that we return what is required, and in same order.
         $relationshipField = 0;
         foreach ($returnProperties as $field => $value) {
             //we should set header only once
             if ($setHeader) {
                 if (isset($query->_fields[$field]['title'])) {
                     $headerRows[] = $query->_fields[$field]['title'];
                 } else {
                     if ($field == 'phone_type_id') {
                         $headerRows[] = 'Phone Type';
                     } else {
                         if ($field == 'provider_id') {
                             $headerRows[] = 'Im Service Provider';
                         } else {
                             if (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 (CRM_Utils_Array::value(1, $type)) {
                                             if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                             } else {
                                                 if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                     $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                 }
                                             }
                                         }
                                         $headerRows[] = $hdr;
                                     }
                                 }
                             } else {
                                 if (substr($field, 0, 5) == 'case_') {
                                     if ($query->_fields['case'][$field]['title']) {
                                         $headerRows[] = $query->_fields['case'][$field]['title'];
                                     } else {
                                         if ($query->_fields['activity'][$field]['title']) {
                                             $headerRows[] = $query->_fields['activity'][$field]['title'];
                                         }
                                     }
                                 } else {
                                     if (array_key_exists($field, $contactRelationshipTypes)) {
                                         foreach ($value as $relationField => $relationValue) {
                                             if (is_array($relationValue)) {
                                                 foreach ($relationValue as $locType => $locValue) {
                                                     if ($relationField == 'location') {
                                                         foreach ($locValue as $locKey => $dont) {
                                                             list($serviceProvider, $serviceProviderID) = explode('-', $locKey);
                                                             if ($serviceProvider == 'phone') {
                                                                 $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $locType . ' - ' . $serviceProvider . ' - ' . CRM_Utils_Array::value($serviceProviderID, $phoneTypes, 'Primary');
                                                             } else {
                                                                 if ($serviceProvider == 'im') {
                                                                     $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $locType . ' - ' . $serviceProvider . ' - ' . CRM_Utils_Array::value($serviceProviderID, $imProviders, 'Primary');
                                                                 } else {
                                                                     $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $locType . ' - ' . $query->_fields[$locKey]['title'];
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             } else {
                                                 if ($query->_fields[$relationField]['title']) {
                                                     $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $query->_fields[$relationField]['title'];
                                                 } else {
                                                     $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $relationField;
                                                 }
                                             }
                                         }
                                     } else {
                                         $headerRows[] = $field;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             //build row values (data)
             if (property_exists($dao, $field)) {
                 $fieldValue = $dao->{$field};
                 // to get phone type from phone type id
                 if ($field == 'phone_type_id') {
                     $fieldValue = $phoneTypes[$fieldValue];
                 } else {
                     if ($field == 'provider_id') {
                         $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
                     }
                 }
             } else {
                 $fieldValue = '';
             }
             if ($field == 'id') {
                 $row[$field] = $dao->contact_id;
             } else {
                 if ($field == 'pledge_balance_amount') {
                     //special case for calculated field
                     $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid;
                 } else {
                     if ($field == 'pledge_next_pay_amount') {
                         //special case for calculated field
                         $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount;
                     } else {
                         if (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];
                                     if (CRM_Utils_Array::value(1, $type)) {
                                         $fldValue .= "-" . $type[1];
                                     }
                                     $row[$fldValue] = $dao->{$fldValue};
                                 }
                             }
                         } else {
                             if (array_key_exists($field, $contactRelationshipTypes)) {
                                 list($id, $direction) = explode('_', $field, 2);
                                 require_once 'api/v2/Relationship.php';
                                 require_once 'CRM/Contact/BAO/Contact.php';
                                 require_once 'CRM/Core/BAO/CustomValueTable.php';
                                 require_once 'CRM/Core/BAO/CustomQuery.php';
                                 $params['relationship_type_id'] = $contactRelationshipTypes[$field];
                                 $contact_id['contact_id'] = $dao->contact_id;
                                 //Get relationships
                                 $val = civicrm_contact_relationship_get($contact_id, null, $params);
                                 if (is_array($val['result'])) {
                                     asort($val['result']);
                                 }
                                 $is_valid = null;
                                 $data = null;
                                 if ($val['result']) {
                                     foreach ($val['result'] as $k => $v) {
                                         //consider only active relationships
                                         if ($v['is_active'] && $v['rtype'] == $direction) {
                                             $cID['contact_id'] = $v['cid'];
                                             if ($cID) {
                                                 //Get Contact Details
                                                 $data = CRM_Contact_BAO_Contact::retrieve($cID, $defaults);
                                             }
                                             $is_valid = true;
                                             break;
                                         }
                                     }
                                 }
                                 $relCustomIDs = array();
                                 foreach ($value as $relationkey => $relationvalue) {
                                     if ($val['result'] && ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationkey))) {
                                         foreach ($val['result'] as $k1 => $v1) {
                                             $contID = $v1['cid'];
                                             $param1 = array('entityID' => $contID, $relationkey => 1);
                                             $getcustomValue = CRM_Core_BAO_CustomValueTable::getValues($param1);
                                             $custom_ID = CRM_Core_BAO_CustomField::getKeyID($relationkey);
                                             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationkey)) {
                                                 if (empty($query->_options)) {
                                                     $relCustomIDs[$cfID] = array();
                                                     $relQuery = new CRM_Core_BAO_CustomQuery($relCustomIDs);
                                                     $relQuery->query();
                                                     $relOptions = $relQuery->_options;
                                                 } else {
                                                     $relOptions = $query->_options;
                                                 }
                                                 $custom_data = CRM_Core_BAO_CustomField::getDisplayValue($getcustomValue[$relationkey], $cfID, $relOptions);
                                             } else {
                                                 $custom_data = '';
                                             }
                                         }
                                     }
                                     //Get all relationships type custom fields
                                     list($id, $atype, $btype) = explode('_', $field);
                                     $relCustomData = CRM_Core_BAO_CustomField::getFields('Relationship', null, null, $id, null, null);
                                     $tmpArray = array_keys($relCustomData);
                                     $customIDs = array();
                                     foreach ($tmpArray as $customID) {
                                         $customIDs[$customID] = array();
                                     }
                                     require_once 'CRM/Core/BAO/CustomQuery.php';
                                     $customQuery = new CRM_Core_BAO_CustomQuery($customIDs);
                                     $customQuery->query();
                                     $options = $customQuery->_options;
                                     foreach ($relCustomData as $id => $customdatavalue) {
                                         if (in_array($relationkey, $customdatavalue)) {
                                             $customkey = "custom_{$id}";
                                             if ($val['result']) {
                                                 foreach ($val['result'] as $k => $v) {
                                                     $cid = $v['id'];
                                                     $param = array('entityID' => $cid, $customkey => 1);
                                                     //Get custom data values
                                                     $getCustomValueRel = CRM_Core_BAO_CustomValueTable::getValues($param);
                                                     if (!array_key_exists('error_message', $getCustomValueRel)) {
                                                         $customData = CRM_Core_BAO_CustomField::getDisplayValue($getCustomValueRel[$customkey], $id, $options);
                                                     } else {
                                                         $customData = '';
                                                     }
                                                     if ($customData) {
                                                         break;
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                     if (is_array($relationvalue)) {
                                         if (array_key_exists('location', $value)) {
                                             foreach ($value['location'] as $columnkey => $columnvalue) {
                                                 foreach ($columnvalue as $colkey => $colvalue) {
                                                     list($serviceProvider, $serviceProviderID) = explode('-', $colkey);
                                                     if (in_array($serviceProvider, array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'state_province', 'country'))) {
                                                         $serviceProvider = 'address';
                                                     }
                                                     $output = null;
                                                     foreach ((array) $data->{$serviceProvider} as $datakey => $datavalue) {
                                                         if ($columnkey == 'Primary') {
                                                             $columnkey = $locationTypes[$datavalue['location_type_id']];
                                                         }
                                                         if ($locationTypes[$datavalue['location_type_id']] == $columnkey) {
                                                             if (array_key_exists($colkey, $datavalue)) {
                                                                 $output = $datavalue[$colkey];
                                                             } else {
                                                                 if ($colkey == 'country') {
                                                                     $countryId = $datavalue['country_id'];
                                                                     if ($countryId) {
                                                                         require_once 'CRM/Core/PseudoConstant.php';
                                                                         $country =& CRM_Core_PseudoConstant::country($countryId);
                                                                     } else {
                                                                         $country = '';
                                                                     }
                                                                     $output = $country;
                                                                 } else {
                                                                     if ($colkey == 'state_province') {
                                                                         $stateProvinceId = $datavalue['state_province_id'];
                                                                         if ($stateProvinceId) {
                                                                             $stateProvince =& CRM_Core_PseudoConstant::stateProvince($stateProvinceId);
                                                                         } else {
                                                                             $stateProvince = '';
                                                                         }
                                                                         $output = $stateProvince;
                                                                     } else {
                                                                         if (is_numeric($serviceProviderID)) {
                                                                             if ($serviceProvider == 'phone') {
                                                                                 if (isset($datavalue['phone'])) {
                                                                                     $output = $datavalue['phone'];
                                                                                 } else {
                                                                                     $output = '';
                                                                                 }
                                                                             } else {
                                                                                 if ($serviceProvider == 'im') {
                                                                                     if (isset($datavalue['name'])) {
                                                                                         $output = $datavalue['name'];
                                                                                     } else {
                                                                                         $output = '';
                                                                                     }
                                                                                 }
                                                                             }
                                                                         } else {
                                                                             if ($datavalue['location_type_id']) {
                                                                                 if ($colkey == 'im') {
                                                                                     $output = $datavalue['name'];
                                                                                 } else {
                                                                                     $output = $datavalue[$colkey];
                                                                                 }
                                                                             } else {
                                                                                 $output = '';
                                                                             }
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                     if ($is_valid) {
                                                         $row[] = $output;
                                                     } else {
                                                         $row[] = '';
                                                     }
                                                 }
                                             }
                                         }
                                     } else {
                                         if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationkey) && $is_valid) {
                                             $row[] = $custom_data;
                                         } else {
                                             if ($query->_fields[$relationkey]['name'] && $is_valid) {
                                                 if ($query->_fields[$relationkey]['name'] == 'gender') {
                                                     $getGenders =& CRM_Core_PseudoConstant::gender();
                                                     $gender = array_search($data->gender_id, array_flip($getGenders));
                                                     $row[] = $gender;
                                                 } else {
                                                     if ($query->_fields[$relationkey]['name'] == 'greeting_type') {
                                                         $getgreeting =& CRM_Core_PseudoConstant::greeting();
                                                         $greeting = array_search($data->greeting_type_id, array_flip($getgreeting));
                                                         $row[] = $greeting;
                                                     } else {
                                                         $colValue = $query->_fields[$relationkey]['name'];
                                                         $row[] = $data->{$colValue};
                                                     }
                                                 }
                                             } else {
                                                 if ($customData && $is_valid) {
                                                     $row[] = $customData;
                                                 } else {
                                                     $row[] = '';
                                                 }
                                             }
                                         }
                                     }
                                 }
                             } else {
                                 if (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);
                                     } else {
                                         if (array_key_exists($field, $multipleSelectFields)) {
                                             //option group fixes
                                             $paramsNew = array($field => $fieldValue);
                                             if ($field == 'test_tutoring') {
                                                 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
                                             } else {
                                                 if (substr($field, 0, 4) == 'cmr_') {
                                                     //for  readers group
                                                     $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];
                                         } else {
                                             if (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                 //special case for greeting replacement
                                                 $fldValue = "{$field}_display";
                                                 $row[$field] = $dao->{$fldValue};
                                             } else {
                                                 //normal fields
                                                 $row[$field] = $fieldValue;
                                             }
                                         }
                                     }
                                 } else {
                                     // if field is empty or null
                                     $row[$field] = '';
                                 }
                             }
                         }
                     }
                 }
             }
         }
         //build header only once
         $setHeader = false;
         // add payment headers if required
         if ($addPaymentHeader && $paymentFields) {
             $headerRows = array_merge($headerRows, $paymentHeaders);
             $addPaymentHeader = false;
         }
         // add payment related information
         if ($paymentFields && isset($paymentDetails[$row[$paymentTableId]])) {
             $row = array_merge($row, $paymentDetails[$row[$paymentTableId]]);
         }
         //remove organization name for individuals if it is set for current employer
         if (CRM_Utils_Array::value('contact_type', $row) && $row['contact_type'] == 'Individual') {
             $row['organization_name'] = '';
         }
         // add component info
         $componentDetails[] = $row;
     }
     require_once 'CRM/Core/Report/Excel.php';
     CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName('csv', $exportMode), $headerRows, $componentDetails);
     exit;
 }
Example #3
0
 /**
  * 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;
 }
Example #4
0
 /**  
  * 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];
                                                                             }
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Example #5
0
 /**
  * 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;
         }
     }
 }
Example #6
0
 function getCustomData($clientID, $activityDAO, &$activityTypeInfo)
 {
     list($typeValues, $options, $sql) = $this->getActivityTypeCustomSQL($activityTypeInfo['id'], '%Y-%m-%d');
     $params = array(1 => array($activityDAO->id, 'Integer'));
     $customGroups = array();
     foreach ($sql as $tableName => $sqlClause) {
         $dao = CRM_Core_DAO::executeQuery($sqlClause, $params);
         if ($dao->fetch()) {
             $customGroup = array();
             foreach ($typeValues[$tableName] as $columnName => $typeValue) {
                 $value = CRM_Core_BAO_CustomField::getDisplayValue($dao->{$columnName}, $typeValue['fieldID'], $options);
                 if (CRM_Utils_Array::value('type', $typeValue) == 'Date') {
                     $value = $dao->{$columnName};
                 }
                 if ($value) {
                     // Note: this is already taken care in getDisplayValue above, but sometimes
                     // strings like '^A^A' creates problem. So to fix this special case -
                     if (strstr($value, CRM_Core_DAO::VALUE_SEPARATOR)) {
                         $value = trim($value, CRM_Core_DAO::VALUE_SEPARATOR);
                     }
                     if (CRM_Utils_Array::value('type', $typeValue) == 'String' || CRM_Utils_Array::value('type', $typeValue) == 'Memo') {
                         $value = $this->redact($value);
                     } elseif (CRM_Utils_Array::value('type', $typeValue) == 'File') {
                         $tableName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_EntityFile', $typeValue, 'entity_table');
                         $value = CRM_Core_BAO_File::attachmentInfo($tableName, $activityDAO->id);
                     } elseif (CRM_Utils_Array::value('type', $typeValue) == 'Link') {
                         $value = CRM_Utils_System::formatWikiURL($value);
                     }
                 }
                 //$typeValue
                 $customGroup[] = array('label' => $typeValue['label'], 'value' => $value, 'type' => $typeValue['type']);
             }
             $customGroups[$dao->groupTitle] = $customGroup;
         }
     }
     return empty($customGroups) ? NULL : $customGroups;
 }
 /**
  * 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)
 {
     $multipleFields = array('url');
     //$sort object processing for location fields
     if ($sort) {
         $vars = $sort->_vars;
         $varArray = array();
         foreach ($vars as $key => $field) {
             $field = $vars[$key];
             $fieldArray = explode('-', $field['name']);
             $fieldType = CRM_Utils_Array::value('2', $fieldArray);
             if (is_numeric(CRM_Utils_Array::value('1', $fieldArray))) {
                 if (!in_array($fieldType, $multipleFields)) {
                     $locationType = new CRM_Core_DAO_LocationType();
                     $locationType->id = $fieldArray[1];
                     $locationType->find(TRUE);
                     if ($fieldArray[0] == 'email' || $fieldArray[0] == 'im' || $fieldArray[0] == 'phone') {
                         $field['name'] = "`" . $locationType->name . "-" . $fieldArray[0] . "-1`";
                     } else {
                         $field['name'] = "`" . $locationType->name . "-" . $fieldArray[0] . "`";
                     }
                 } else {
                     $field['name'] = "`website-" . $fieldArray[1] . "-{$fieldType}`";
                 }
             }
             $varArray[$key] = $field;
         }
         $sort->_vars = $varArray;
     }
     $additionalWhereClause = 'contact_a.is_deleted = 0';
     $returnQuery = NULL;
     if ($this->_multiRecordTableName) {
         $returnQuery = TRUE;
     }
     $result = $this->_query->searchQuery($offset, $rowCount, $sort, NULL, NULL, NULL, NULL, $returnQuery, $additionalWhereClause);
     if ($returnQuery) {
         $resQuery = preg_replace('/GROUP BY contact_a.id[\\s]+ORDER BY/', ' ORDER BY', $result);
         $result = CRM_Core_DAO::executeQuery($resQuery);
     }
     // process the result of the query
     $rows = array();
     // check if edit is configured in profile settings
     if ($this->_gid) {
         $editLink = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'is_edit_link');
     }
     //FIXME : make sure to handle delete separately. CRM-4418
     $mask = CRM_Core_Action::mask(array(CRM_Core_Permission::getPermission()));
     if ($editLink && $mask & CRM_Core_Permission::EDIT) {
         // do not allow edit for anon users in joomla frontend, CRM-4668
         $config = CRM_Core_Config::singleton();
         if (!$config->userFrameworkFrontend) {
             $this->_editLink = TRUE;
         }
     }
     $links = self::links($this->_map, $this->_editLink, $this->_linkToUF, $this->_profileIds);
     $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) {
         // skip pseudo fields
         if (substr($key, 0, 9) == 'phone_ext') {
             continue;
         }
         if (!empty($field['in_selector']) && !in_array($key, $skipFields)) {
             if (strpos($key, '-') !== FALSE) {
                 $value = explode('-', $key);
                 $fieldName = CRM_Utils_Array::value(0, $value);
                 $id = CRM_Utils_Array::value(1, $value);
                 $type = CRM_Utils_Array::value(2, $value);
                 if (!in_array($fieldName, $multipleFields)) {
                     $locationTypeName = NULL;
                     if (is_numeric($id)) {
                         $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
                     } else {
                         if ($id == 'Primary') {
                             $locationTypeName = 1;
                         }
                     }
                     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[] = "website-{$id}-{$fieldName}";
                 }
             } elseif ($field['name'] == 'id') {
                 $names[] = 'contact_id';
             } else {
                 $names[] = $field['name'];
             }
         }
     }
     $multipleSelectFields = array('preferred_communication_method' => 1);
     $multiRecordTableId = NULL;
     if ($this->_multiRecordTableName) {
         $multiRecordTableId = "{$this->_multiRecordTableName}_id";
     }
     // we need to determine of overlay profile should be shown
     $showProfileOverlay = CRM_Core_BAO_UFGroup::showOverlayProfile();
     while ($result->fetch()) {
         $this->_query->convertToPseudoNames($result);
         if (isset($result->country)) {
             // the query returns the untranslated country name
             $i18n = CRM_Core_I18n::singleton();
             $result->country = $i18n->translate($result->country);
         }
         $row = array();
         $empty = TRUE;
         $row[] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id, $showProfileOverlay);
         if ($result->sort_name) {
             $row[] = $result->sort_name;
             $empty = FALSE;
         } else {
             continue;
         }
         foreach ($names as $name) {
             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                 $row[] = CRM_Core_BAO_CustomField::getDisplayValue($result->{$name}, $cfID, $this->_options, $result->contact_id);
             } elseif (substr($name, -4) == '-url' && !empty($result->{$name})) {
                 $url = CRM_Utils_System::fixURL($result->{$name});
                 $typeId = substr($name, 0, -4) . "-website_type_id";
                 $typeName = CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_Website', 'website_type_id', $result->{$typeId});
                 if ($typeName) {
                     $row[] = "<a href=\"{$url}\">{$result->{$name}} ({$typeName})</a>";
                 } else {
                     $row[] = "<a href=\"{$url}\">{$result->{$name}}</a>";
                 }
             } elseif ($name == 'preferred_language') {
                 $row[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $result->{$name});
             } elseif ($multipleSelectFields && array_key_exists($name, $multipleSelectFields)) {
                 $paramsNew = array($name => $result->{$name});
                 $name = array($name => array('newName' => $name, 'groupName' => $name));
                 CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
                 $row[] = $paramsNew[$key];
             } elseif (strpos($name, '-im')) {
                 if (!empty($result->{$name})) {
                     $providerId = $name . "-provider_id";
                     $providerName = CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_IM', 'provider_id', $result->{$providerId});
                     $row[] = $result->{$name} . " ({$providerName})";
                 } else {
                     $row[] = '';
                 }
             } elseif (strpos($name, '-phone-')) {
                 $phoneExtField = str_replace('phone', 'phone_ext', $name);
                 if (isset($result->{$phoneExtField})) {
                     $row[] = $result->{$name} . " (" . $result->{$phoneExtField} . ")";
                 } else {
                     $row[] = $result->{$name};
                 }
             } elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) {
                 $dname = $name . '_display';
                 $row[] = $result->{$dname};
             } elseif (in_array($name, array('birth_date', 'deceased_date'))) {
                 $row[] = CRM_Utils_Date::customFormat($result->{$name});
             } elseif (isset($result->{$name})) {
                 $row[] = $result->{$name};
             } else {
                 $row[] = '';
             }
             if (!empty($result->{$name})) {
                 $empty = FALSE;
             }
         }
         $newLinks = $links;
         $params = array('id' => $result->contact_id, 'gid' => implode(',', $this->_profileIds));
         // pass record id param to view url for multi record view
         if ($multiRecordTableId && $newLinks) {
             if ($result->{$multiRecordTableId}) {
                 if ($newLinks[CRM_Core_Action::VIEW]['url'] == 'civicrm/profile/view') {
                     $newLinks[CRM_Core_Action::VIEW]['qs'] .= "&multiRecord=view&recordId=%%recordId%%&allFields=1";
                     $params['recordId'] = $result->{$multiRecordTableId};
                 }
             }
         }
         if ($this->_linkToUF) {
             $ufID = CRM_Core_BAO_UFMatch::getUFId($result->contact_id);
             if (!$ufID) {
                 unset($newLinks[CRM_Core_Action::PROFILE]);
             } else {
                 $params['ufID'] = $ufID;
             }
         }
         $row[] = CRM_Core_Action::formLink($newLinks, $mask, $params, ts('more'), FALSE, 'profile.selector.row', 'Contact', $result->contact_id);
         if (!$empty) {
             $rows[] = $row;
         }
     }
     return $rows;
 }
Example #8
0
 /**
  * Build badges parameters before actually creating badges.
  *
  * @param array $params
  *   Associated array of submitted values.
  * @param CRM_Core_Form $form
  *
  * @return void
  */
 public static function buildBadges(&$params, &$form)
 {
     // get name badge layout info
     $layoutInfo = CRM_Badge_BAO_Layout::buildLayout($params);
     // split/get actual field names from token and individual contact image URLs
     $returnProperties = array();
     if (!empty($layoutInfo['data']['token'])) {
         foreach ($layoutInfo['data']['token'] as $index => $value) {
             $element = '';
             if ($value) {
                 $token = CRM_Utils_Token::getTokens($value);
                 if (key($token) == 'contact') {
                     $element = $token['contact'][0];
                 } elseif (key($token) == 'event') {
                     $element = $token['event'][0];
                     //FIX ME - we need to standardize event token names
                     if (substr($element, 0, 6) != 'event_') {
                         $element = 'event_' . $element;
                     }
                 } elseif (key($token) == 'participant') {
                     $element = $token['participant'][0];
                 }
                 // build returnproperties for query
                 $returnProperties[$element] = 1;
             }
             // add actual field name to row element
             $layoutInfo['data']['rowElements'][$index] = $element;
         }
     }
     // add additional required fields for query execution
     $additionalFields = array('participant_register_date', 'participant_id', 'event_id', 'contact_id', 'image_URL');
     foreach ($additionalFields as $field) {
         $returnProperties[$field] = 1;
     }
     if ($form->_single) {
         $queryParams = NULL;
     } else {
         $queryParams = $form->get('queryParams');
     }
     $query = new CRM_Contact_BAO_Query($queryParams, $returnProperties, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_EVENT);
     list($select, $from, $where, $having) = $query->query();
     if (empty($where)) {
         $where = "WHERE {$form->_componentClause}";
     } else {
         $where .= " AND {$form->_componentClause}";
     }
     $sortOrder = NULL;
     if ($form->get(CRM_Utils_Sort::SORT_ORDER)) {
         $sortOrder = $form->get(CRM_Utils_Sort::SORT_ORDER);
         if (!empty($sortOrder)) {
             $sortOrder = " ORDER BY {$sortOrder}";
         }
     }
     $queryString = "{$select} {$from} {$where} {$having} {$sortOrder}";
     $dao = CRM_Core_DAO::executeQuery($queryString);
     $rows = array();
     while ($dao->fetch()) {
         $query->convertToPseudoNames($dao);
         $rows[$dao->participant_id] = array();
         foreach ($returnProperties as $key => $dontCare) {
             $value = isset($dao->{$key}) ? $dao->{$key} : NULL;
             // Format custom fields
             if (strstr($key, 'custom_') && isset($value)) {
                 $value = CRM_Core_BAO_CustomField::getDisplayValue($value, substr($key, 7), $query->_options, $dao->contact_id);
             }
             $rows[$dao->participant_id][$key] = $value;
         }
     }
     $eventBadgeClass = new CRM_Badge_BAO_Badge();
     $eventBadgeClass->createLabels($rows, $layoutInfo);
 }
Example #9
0
 /**
  * Function to get the list the export fields
  *
  * @param int $exportContact type of export
  *
  * @access public
  */
 function exportContacts($selectAll, $ids, $formValues, $order = null, $fields = null)
 {
     $headerRows = array();
     $returnProperties = array();
     $primary = false;
     if ($fields) {
         $location = array();
         $locationType = array("Work" => array(), "Home" => array(), "Main" => array(), "Other" => array());
         $returnFields = $fields;
         foreach ($returnFields as $key => $field) {
             $flag = true;
             $phone_type = "";
             $phoneFlag = false;
             if ($field[3] && $field[1] == 'phone') {
                 if ($field[3] == 'Phone') {
                     $phone_type = $field[1] . "-" . "Phone";
                 } else {
                     if ($field[3] == 'Mobile') {
                         $phone_type = $field[1] . "-" . "Mobile";
                     } else {
                         if ($field[3] == 'Fax') {
                             $phone_type = $field[1] . "-" . "Fax";
                         } else {
                             if ($field[3] == 'Pager') {
                                 $phone_type = $field[1] . "-" . "Pager";
                             }
                         }
                     }
                 }
                 $phoneFlag = true;
             }
             if ($field[2]) {
                 if ($field[2] == 1) {
                     if ($phoneFlag) {
                         $locationType["Home"][$phone_type] = 1;
                     } else {
                         $locationType["Home"][$field[1]] = 1;
                     }
                 } else {
                     if ($field[2] == 2) {
                         if ($phoneFlag) {
                             $locationType["Work"][$phone_type] = 1;
                         } else {
                             $locationType["Work"][$field[1]] = 1;
                         }
                     } else {
                         if ($field[2] == 3) {
                             if ($phoneFlag) {
                                 $locationType["Main"][$phone_type] = 1;
                             } else {
                                 $locationType["Main"][$field[1]] = 1;
                             }
                         } else {
                             if ($field[2] == 4) {
                                 if ($phoneFlag) {
                                     $locationType["Other"][$phone_type] = 1;
                                 } else {
                                     $locationType["Other"][$field[1]] = 1;
                                 }
                             }
                         }
                     }
                 }
                 $flag = false;
             }
             if ($flag) {
                 $returnProperties[$field[1]] = 1;
             }
         }
         $returnProperties['location'] = $locationType;
     } else {
         $primary = true;
         $fields = CRM_Contact_BAO_Contact::exportableFields('All', true, true);
         foreach ($fields as $key => $var) {
             if ($key) {
                 $returnProperties[$key] = 1;
             }
         }
     }
     if ($primary) {
         $returnProperties['location_type'] = 1;
         $returnProperties['im_provider'] = 1;
         $returnProperties['phone_type'] = 1;
     }
     $session =& new CRM_Core_Session();
     if ($selectAll) {
         if ($primary) {
             $query =& new CRM_Contact_BAO_Query($formValues, $returnProperties, $fields);
         } else {
             $query =& new CRM_Contact_BAO_Query($formValues, $returnProperties);
         }
     } else {
         $params = array();
         foreach ($ids as $id) {
             $params[CRM_CORE_FORM_CB_PREFIX . $id] = 1;
         }
         if ($primary) {
             $query =& new CRM_Contact_BAO_Query($params, $returnProperties, $fields, true);
         } else {
             $query =& new CRM_Contact_BAO_Query($params, $returnProperties, null, true);
         }
     }
     list($select, $from, $where) = $query->query();
     $queryString = "{$select} {$from} {$where}";
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (CRM_Utils_Array::value($field, $returnProperties)) {
             $queryString .= " ORDER BY {$order}";
         }
     }
     if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties)) {
         $queryString .= " GROUP BY civicrm_contact.id";
     }
     $dao =& CRM_Core_DAO::executeQuery($queryString);
     $header = false;
     $contactDetails = array();
     while ($dao->fetch()) {
         $row = array();
         $validRow = false;
         foreach ($dao as $key => $varValue) {
             $flag = false;
             foreach ($returnProperties as $propKey => $props) {
                 if (is_array($props)) {
                     foreach ($props as $propKey1 => $prop) {
                         foreach ($prop as $propkey2 => $prop1) {
                             if ($propKey1 . "-" . $propkey2 == $key) {
                                 $flag = true;
                             }
                         }
                     }
                 }
             }
             if (array_key_exists($key, $returnProperties)) {
                 $flag = true;
             }
             if ($flag) {
                 if (isset($varValue) && $varValue != '') {
                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($key)) {
                         $row[$key] = CRM_Core_BAO_CustomField::getDisplayValue($varValue, $cfID, $query->_options);
                     } else {
                         $row[$key] = $varValue;
                     }
                     $validRow = true;
                 } else {
                     $row[$key] = '';
                 }
                 if (!$header) {
                     if (isset($query->_fields[$key]['title'])) {
                         $headerRows[] = $query->_fields[$key]['title'];
                     } else {
                         if ($key == 'phone_type') {
                             $headerRows[] = 'Phone Type';
                         } else {
                             $keyArray = explode('-', $key);
                             $hdr = $keyArray[0] . "-" . $query->_fields[$keyArray[1]]['title'];
                             if (CRM_Utils_Array::value(2, $keyArray)) {
                                 $hdr .= " " . $keyArray[2];
                             }
                             $headerRows[] = $hdr;
                         }
                     }
                 }
             }
         }
         if ($validRow) {
             $contactDetails[$dao->contact_id] = $row;
         }
         $header = true;
     }
     require_once 'CRM/Core/Report/Excel.php';
     CRM_Core_Report_Excel::writeCSVFile(CRM_Contact_BAO_Export::getExportFileName(), $headerRows, $contactDetails);
     exit;
 }
Example #10
0
 public function postProcess()
 {
     $formValues = $this->exportValues();
     // user can't choose to move cases without activities (CRM-3778)
     if ($formValues['move_rel_table_cases'] == '1' && array_key_exists('move_rel_table_activities', $formValues)) {
         $formValues['move_rel_table_activities'] = '1';
     }
     // reset all selected contact ids from session
     // when we came from search context, CRM-3526
     $session =& CRM_Core_Session::singleton();
     if ($session->get('selectedSearchContactIds')) {
         $session->resetScope('selectedSearchContactIds');
     }
     $relTables =& CRM_Dedupe_Merger::relTables();
     $moveTables = $locBlocks = array();
     foreach ($formValues as $key => $value) {
         if ($value == $this->_qfZeroBug) {
             $value = '0';
         }
         if ((in_array(substr($key, 5), CRM_Dedupe_Merger::$validFields) or substr($key, 0, 12) == 'move_custom_') and $value != null) {
             $submitted[substr($key, 5)] = $value;
         } elseif (substr($key, 0, 14) == 'move_location_' and $value != null) {
             $locField = explode('_', $key);
             $fieldName = $locField[2];
             $fieldCount = $locField[3];
             $operation = CRM_Utils_Array::value('operation', $formValues['location'][$fieldName][$fieldCount]);
             // default operation is overwrite.
             if (!$operation) {
                 $operation = 2;
             }
             $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
             $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $formValues['location'][$fieldName][$fieldCount]);
         } elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
             $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
         }
     }
     // process location blocks.
     if (!empty($locBlocks)) {
         $locComponent = array('email' => 'Email', 'phone' => 'Phone', 'im' => 'IM', 'openid' => 'OpenID', 'address' => 'Address');
         require_once 'CRM/Contact/BAO/Contact.php';
         $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($this->_cid, array('is_primary' => 1));
         $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($this->_cid, array('is_billing' => 1));
         foreach ($locBlocks as $name => $block) {
             if (!is_array($block) || CRM_Utils_System::isNull($block)) {
                 continue;
             }
             $daoName = $locComponent[$name];
             $primaryDAOId = array_key_exists($name, $primaryBlockIds) ? array_pop($primaryBlockIds[$name]) : null;
             $billingDAOId = array_key_exists($name, $billingBlockIds) ? array_pop($billingBlockIds[$name]) : null;
             foreach ($block as $blkCount => $values) {
                 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
                 $operation = CRM_Utils_Array::value('operation', $values, 2);
                 $updateBlockId = CRM_Utils_Array::value($blkCount, $this->_locBlockIds['other'][$name]);
                 // keep 1-1 mapping for address - loc type.
                 $idKey = $blkCount;
                 if ($name == 'address') {
                     $idKey = $locTypeId;
                 }
                 $deleteBlockId = CRM_Utils_Array::value($idKey, $this->_locBlockIds['main'][$name]);
                 if (!$updateBlockId) {
                     continue;
                 }
                 require_once "CRM/Core/DAO/{$daoName}.php";
                 eval("\$updateDAO =& new CRM_Core_DAO_{$daoName}();");
                 $updateDAO->id = $updateBlockId;
                 $updateDAO->contact_id = $this->_cid;
                 $updateDAO->location_type_id = $locTypeId;
                 // contact having primary block.
                 if ($primaryDAOId) {
                     $updateDAO->is_primary = 0;
                 }
                 if ($billingDAOId) {
                     $updateDAO->is_billing = 0;
                 }
                 // overwrite - need to delete block from main contact.
                 if ($deleteBlockId && $operation == 2) {
                     eval("\$deleteDAO =& new CRM_Core_DAO_{$daoName}();");
                     $deleteDAO->id = $deleteBlockId;
                     $deleteDAO->find(true);
                     // since we overwrite primary block.
                     if ($primaryDAOId && $primaryDAOId == $deleteDAO->id) {
                         $updateDAO->is_primary = 1;
                     }
                     if ($billingDAOId && $billingDAOId == $deleteDAO->id) {
                         $updateDAO->is_billing = 1;
                     }
                     $deleteDAO->delete();
                     $deleteDAO->free();
                 }
                 $updateDAO->update();
                 $updateDAO->free();
             }
         }
     }
     // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
     $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
     $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
     $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
     $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
     $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
     $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
     CRM_Core_OptionGroup::lookupValues($submitted, $names, true);
     // FIXME: fix custom fields so they're edible by createProfileContact()
     $cgTree =& CRM_Core_BAO_CustomGroup::getTree($this->_contactType, $this, null, -1);
     foreach ($cgTree as $key => $group) {
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             $cFields[$fid]['attributes'] = $field;
         }
     }
     if (!isset($submitted)) {
         $submitted = array();
     }
     foreach ($submitted as $key => $value) {
         if (substr($key, 0, 7) == 'custom_') {
             $fid = (int) substr($key, 7);
             $htmlType = $cFields[$fid]['attributes']['html_type'];
             switch ($htmlType) {
                 case 'File':
                     $customFiles[] = $fid;
                     unset($submitted["custom_{$fid}"]);
                     break;
                 case 'Select Country':
                 case 'Select State/Province':
                     $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
                     break;
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                 case 'Multi-Select Country':
                 case 'Multi-Select State/Province':
                     // Merge values from both contacts for multivalue fields, CRM-4385
                     // get the existing custom values from db.
                     require_once 'CRM/Core/BAO/CustomValueTable.php';
                     $customParams = array('entityID' => $this->_cid, $key => true);
                     $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
                     if (CRM_Utils_array::value($key, $customfieldValues)) {
                         $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
                         if (is_array($existingValue) && !empty($existingValue)) {
                             $mergeValue = $submmtedCustomValue = array();
                             if ($value) {
                                 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                             }
                             //hack to remove null and duplicate values from array.
                             foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
                                 if ($v != '' && !in_array($v, $mergeValue)) {
                                     $mergeValue[] = $v;
                                 }
                             }
                             //keep state and country as array format.
                             //for checkbox and m-select format w/ VALUE_SEPERATOR
                             if (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
                                 $submitted[$key] = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR . implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $mergeValue) . CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
                             } else {
                                 $submitted[$key] = $mergeValue;
                             }
                         }
                     } else {
                         if (in_array($htmlType, array('Multi-Select Country', 'Multi-Select State/Province'))) {
                             //we require submitted values should be in array format
                             if ($value) {
                                 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                                 //hack to remove null values from array.
                                 $mergeValue = array();
                                 foreach ($mergeValueArray as $k => $v) {
                                     if ($v != '') {
                                         $mergeValue[] = $v;
                                     }
                                 }
                                 $submitted[$key] = $mergeValue;
                             }
                         }
                     }
                     break;
                 default:
                     break;
             }
         }
     }
     // handle the related tables
     if (isset($moveTables)) {
         CRM_Dedupe_Merger::moveContactBelongings($this->_cid, $this->_oid, $moveTables);
     }
     // move file custom fields
     // FIXME: move this someplace else (one of the BAOs) after discussing
     // where to, and whether CRM_Core_BAO_File::delete() shouldn't actually,
     // like, delete a file...
     require_once 'CRM/Core/BAO/File.php';
     require_once 'CRM/Core/DAO/CustomField.php';
     require_once 'CRM/Core/DAO/CustomGroup.php';
     require_once 'CRM/Core/DAO/EntityFile.php';
     require_once 'CRM/Core/Config.php';
     if (!isset($customFiles)) {
         $customFiles = array();
     }
     foreach ($customFiles as $customId) {
         list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
         // get the contact_id -> file_id mapping
         $fileIds = array();
         $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$this->_cid}, {$this->_oid})";
         $dao =& CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         while ($dao->fetch()) {
             $fileIds[$dao->entity_id] = $dao->file_id;
         }
         $dao->free();
         // delete the main contact's file
         CRM_Core_BAO_File::delete($fileIds[$this->_cid], $this->_cid, $customId);
         // move the other contact's file to main contact
         $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$this->_oid]} WHERE entity_id = {$this->_cid}";
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         $sql = "UPDATE civicrm_entity_file SET entity_id = {$this->_cid} WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$this->_oid]}";
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
     }
     // move other's belongings and delete the other contact
     CRM_Dedupe_Merger::moveContactBelongings($this->_cid, $this->_oid);
     $otherParams = array('contact_id' => $this->_oid);
     if (CRM_Core_Permission::check('delete contacts')) {
         civicrm_contact_delete($otherParams);
     } else {
         CRM_Core_Session::setStatus(ts('Do not have sufficient permission to delete duplicate contact.'));
     }
     if (isset($submitted)) {
         $submitted['contact_id'] = $this->_cid;
         CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $this->_cid);
     }
     CRM_Core_Session::setStatus(ts('The contacts have been merged.'));
     $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_cid}");
     CRM_Utils_System::redirect($url);
 }
 /**
  * generate the where clause and also the english language
  * equivalent
  * 
  * @param NULL
  * 
  * @return void
  * 
  * @access public
  */
 function where()
 {
     //CRM_Core_Error::debug( 'fld', $this->_fields );
     //CRM_Core_Error::debug( 'ids', $this->_ids );
     foreach ($this->_ids as $id => $value) {
         // Fixed for Isuue CRM 607
         if ($value == null || CRM_Utils_Array::value($id, $this->_fields) === null) {
             continue;
         }
         // fix $value here to escape sql injection attacks
         $field = $this->_fields[$id];
         $qillValue = CRM_Core_BAO_CustomField::getDisplayValue($value, $id, $this->_options);
         if (!is_array($value)) {
             $value = addslashes(trim($value));
         }
         switch ($field['data_type']) {
             case 'String':
                 $sql = 'LOWER(' . CRM_CORE_BAO_CUSTOMQUERY_PREFIX . $field['id'] . '.char_data) LIKE ';
                 // if we are coming in from listings, for checkboxes the value is already in the right format and is NOT an array
                 if ($field['html_type'] == 'CheckBox' && is_array($value)) {
                     $this->_where[] = $sql . "'%" . implode('%', array_keys($value)) . "%'";
                     $this->_qill[] = ts('%1 like - %2', array(1 => $field['label'], 2 => $qillValue));
                 } else {
                     if ($field['is_search_range']) {
                         $this->searchRange($field['id'], $field['label'], 'char_data', $value);
                     } else {
                         $val = CRM_Utils_Type::escape(strtolower(trim($value)), 'String');
                         $this->_where[] = "{$sql} '%{$val}%'";
                         $this->_qill[] = ts('%1 like - %2', array(1 => $field['label'], 2 => $qillValue));
                     }
                 }
                 continue;
             case 'Int':
                 if ($field['is_search_range']) {
                     $this->searchRange($field['id'], $field['label'], 'int_data', $value);
                 } else {
                     $this->_where[] = CRM_CORE_BAO_CUSTOMQUERY_PREFIX . $field['id'] . '.int_data = ' . CRM_Utils_Type::escape($value, 'Integer');
                     $this->_qill[] = $field['label'] . " - {$value}";
                 }
                 continue;
             case 'Boolean':
                 $value = (int) $value;
                 $value = $value == 1 ? 1 : 0;
                 $this->_where[] = CRM_CORE_BAO_CUSTOMQUERY_PREFIX . $field['id'] . '.int_data = ' . CRM_Utils_Type::escape($value, 'Integer');
                 $value = $value ? ts('Yes') : ts('No');
                 $this->_qill[] = $field['label'] . " - {$value}";
                 continue;
             case 'Float':
                 if ($field['is_search_range']) {
                     $this->searchRange($field['id'], $field['label'], 'float_data', $value);
                 } else {
                     $this->_where[] = CRM_CORE_BAO_CUSTOMQUERY_PREFIX . $field['id'] . '.float_data = ' . CRM_Utils_Type::escape($value, 'Float');
                     $this->_qill[] = $field['label'] . " - {$value}";
                 }
                 continue;
             case 'Money':
                 if ($field['is_search_range']) {
                     $this->searchRange($field['id'], $field['label'], 'decimal_data', $value);
                 } else {
                     $this->_where[] = CRM_CORE_BAO_CUSTOMQUERY_PREFIX . $field['id'] . '.decimal_data = ' . CRM_Utils_Type::escape($value, 'Float');
                     $this->_qill[] = $field['label'] . " - {$value}";
                 }
                 continue;
             case 'Memo':
                 $val = CRM_Utils_Type::escape(strtolower(trim($value)), 'String');
                 $this->_where[] = CRM_CORE_BAO_CUSTOMQUERY_PREFIX . $field['id'] . ".memo_data LIKE '%{$val}%'";
                 $this->_qill[] = ts('%1 like - %2', array(1 => $field['label'], 2 => $value));
                 continue;
             case 'Date':
                 $fromValue = CRM_Utils_Array::value('from', $value);
                 $toValue = CRM_Utils_Array::value('to', $value);
                 if (!$fromValue && !$toValue) {
                     $date = CRM_Utils_Date::format($value);
                     if (!$date) {
                         continue;
                     }
                     $this->_where[] = CRM_CORE_BAO_CUSTOMQUERY_PREFIX . $field['id'] . ".date_data = {$date}";
                     $date = CRM_Utils_Date::format($value, '-');
                     $this->_qill[] = $field['label'] . ' = ' . CRM_Utils_Date::customFormat($date);
                 } else {
                     $fromDate = CRM_Utils_Date::format($fromValue);
                     $toDate = CRM_Utils_Date::format($toValue);
                     if (!$fromDate && !$toDate) {
                         continue;
                     }
                     if ($fromDate) {
                         $this->_where[] = CRM_CORE_BAO_CUSTOMQUERY_PREFIX . $field['id'] . ".date_data >= {$fromDate}";
                         $fromDate = CRM_Utils_Date::format($fromValue, '-');
                         $this->_qill[] = $field['label'] . ' >= ' . CRM_Utils_Date::customFormat($fromDate);
                     }
                     if ($toDate) {
                         $this->_where[] = CRM_CORE_BAO_CUSTOMQUERY_PREFIX . $field['id'] . ".date_data <= {$toDate}";
                         $toDate = CRM_Utils_Date::format($toValue, '-');
                         $this->_qill[] = $field['label'] . ' <= ' . CRM_Utils_Date::customFormat($toDate);
                     }
                 }
                 continue;
             case 'StateProvince':
                 $states =& CRM_Core_PseudoConstant::stateProvince();
                 if (!is_numeric($value)) {
                     $value = array_search($value, $states);
                 }
                 if ($value) {
                     $this->_where[] = CRM_CORE_BAO_CUSTOMQUERY_PREFIX . $field['id'] . '.int_data = ' . CRM_Utils_Type::escape($value, 'Int');
                     $this->_qill[] = $field['label'] . " - {$states[$value]}";
                 }
                 continue;
             case 'Country':
                 $countries =& CRM_Core_PseudoConstant::country();
                 if (!is_numeric($value)) {
                     $value = array_search($value, $countries);
                 }
                 if ($value) {
                     $this->_where[] = CRM_CORE_BAO_CUSTOMQUERY_PREFIX . $field['id'] . '.int_data = ' . CRM_Utils_Type::escape($value, 'Int');
                     $this->_qill[] = $field['label'] . " - {$countries[$value]}";
                 }
                 continue;
         }
     }
     // CRM_Core_Error::debug( 'w', $this->_where );
 }
Example #12
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return void
  */
 public function postProcess()
 {
     $fv = $this->controller->exportValues($this->_name);
     $config =& CRM_Core_Config::singleton();
     $locName = null;
     //get the address format sequence from the config file
     require_once 'CRM/Core/BAO/Preferences.php';
     $sequence = CRM_Core_BAO_Preferences::value('mailing_sequence');
     foreach ($sequence as $v) {
         $address[$v] = 1;
     }
     if (array_key_exists('postal_code', $address)) {
         $address['postal_code_suffix'] = 1;
     }
     //build the returnproperties
     $returnProperties = array('display_name' => 1);
     $mailingFormat = CRM_Core_BAO_Preferences::value('mailing_format');
     $mailingFormatProperties = array();
     if ($mailingFormat) {
         $mailingFormatProperties = self::getReturnProperties($mailingFormat);
         $returnProperties = array_merge($returnProperties, $mailingFormatProperties);
     }
     $customFormatProperties = array();
     if (stristr($mailingFormat, 'custom_')) {
         foreach ($mailingFormatProperties as $token => $true) {
             if (substr($token, 0, 7) == 'custom_') {
                 if (!CRM_Utils_Array::value($token, $customFormatProperties)) {
                     $customFormatProperties[$token] = $mailingFormatProperties[$token];
                 }
             }
         }
     }
     if (!empty($customFormatProperties)) {
         $returnProperties = array_merge($returnProperties, $customFormatProperties);
     }
     //get the contacts information
     $params = array();
     if (CRM_Utils_Array::value('location_type_id', $fv)) {
         $locType = CRM_Core_PseudoConstant::locationType();
         $locName = $locType[$fv['location_type_id']];
         $location = array('location' => array("{$locName}" => $address));
         $returnProperties = array_merge($returnProperties, $location);
         $params[] = array('location_type', '=', array($fv['location_type_id'] => 1), 0, 0);
     } else {
         $returnProperties = array_merge($returnProperties, $address);
     }
     $rows = array();
     foreach ($this->_contactIds as $key => $contactID) {
         $params[] = array(CRM_Core_Form::CB_PREFIX . $contactID, '=', 1, 0, 0);
     }
     // fix for CRM-2651
     if (CRM_Utils_Array::value('do_not_mail', $fv)) {
         $params[] = array('do_not_mail', '=', 0, 0, 0);
     }
     // fix for CRM-2613
     $params[] = array('is_deceased', '=', 0, 0, 0);
     $custom = array();
     foreach ($returnProperties as $name => $dontCare) {
         $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
         if ($cfID) {
             $custom[] = $cfID;
         }
     }
     //get the total number of contacts to fetch from database.
     $numberofContacts = count($this->_contactIds);
     require_once 'CRM/Contact/BAO/Query.php';
     $query =& new CRM_Contact_BAO_Query($params, $returnProperties);
     $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
     // also get all token values
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::tokenValues($details[0], $this->_contactIds);
     $tokens = array();
     CRM_Utils_Hook::tokens($tokens);
     $tokenFields = array();
     foreach ($tokens as $category => $catTokens) {
         foreach ($catTokens as $token) {
             $tokenFields[] = $token;
         }
     }
     foreach ($this->_contactIds as $value) {
         foreach ($custom as $cfID) {
             if (isset($details[0][$value]["custom_{$cfID}"])) {
                 $details[0][$value]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($details[0][$value]["custom_{$cfID}"], $cfID, $details[1]);
             }
         }
         $contact = CRM_Utils_Array::value($value, $details['0']);
         if (is_a($contact, 'CRM_Core_Error')) {
             return null;
         }
         // we need to remove all the "_id"
         unset($contact['contact_id']);
         if ($locName && CRM_Utils_Array::value($locName, $contact)) {
             // If location type is not primary, $contact contains
             // one more array as "$contact[$locName] = array( values... )"
             $found = false;
             // we should replace all the tokens that are set in mailing label format
             foreach ($mailingFormatProperties as $key => $dontCare) {
                 if (CRM_Utils_Array::value($key, $contact)) {
                     $found = true;
                     break;
                 }
             }
             if (!$found) {
                 continue;
             }
             unset($contact[$locName]);
             if (CRM_Utils_Array::value('county_id', $contact)) {
                 unset($contact['county_id']);
             }
             foreach ($contact as $field => $fieldValue) {
                 $rows[$value][$field] = $fieldValue;
             }
             $valuesothers = array();
             $paramsothers = array('contact_id' => $value);
             require_once 'CRM/Core/BAO/Location.php';
             $valuesothers = CRM_Core_BAO_Location::getValues($paramsothers, $valuesothers);
             if (CRM_Utils_Array::value('location_type_id', $fv)) {
                 foreach ($valuesothers as $vals) {
                     if ($vals['location_type_id'] == CRM_Utils_Array::value('location_type_id', $fv)) {
                         foreach ($vals as $k => $v) {
                             if (in_array($k, array('email', 'phone', 'im', 'openid'))) {
                                 if ($k == 'im') {
                                     $rows[$value][$k] = $v['1']['name'];
                                 } else {
                                     $rows[$value][$k] = $v['1'][$k];
                                 }
                                 $rows[$value][$k . '_id'] = $v['1']['id'];
                             }
                         }
                     }
                 }
             }
         } else {
             $found = false;
             // we should replace all the tokens that are set in mailing label format
             foreach ($mailingFormatProperties as $key => $dontCare) {
                 if (CRM_Utils_Array::value($key, $contact)) {
                     $found = true;
                     break;
                 }
             }
             if (!$found) {
                 continue;
             }
             if (CRM_Utils_Array::value('addressee', $contact)) {
                 $contact['addressee'] = $contact['addressee_display'];
             }
             // now create the rows for generating mailing labels
             foreach ($contact as $field => $fieldValue) {
                 $rows[$value][$field] = $fieldValue;
             }
         }
     }
     $individualFormat = false;
     if (isset($fv['merge_same_address'])) {
         $this->mergeSameAddress($rows);
         $individualFormat = true;
     }
     // format the addresses according to CIVICRM_ADDRESS_FORMAT (CRM-1327)
     require_once 'CRM/Utils/Address.php';
     foreach ($rows as $id => $row) {
         if ($commMethods = CRM_Utils_Array::value('preferred_communication_method', $row)) {
             require_once 'CRM/Core/PseudoConstant.php';
             $val = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $commMethods));
             $comm = CRM_Core_PseudoConstant::pcm();
             $temp = array();
             foreach ($val as $vals) {
                 $temp[] = $comm[$vals];
             }
             $row['preferred_communication_method'] = implode(', ', $temp);
         }
         $row['id'] = $id;
         $formatted = CRM_Utils_Address::format($row, 'mailing_format', false, true, $individualFormat, $tokenFields);
         // CRM-2211: UFPDF doesn't have bidi support; use the PECL fribidi package to fix it.
         // On Ubuntu (possibly Debian?) be aware of http://pecl.php.net/bugs/bug.php?id=12366
         // Due to FriBidi peculiarities, this can't be called on
         // a multi-line string, hence the explode+implode approach.
         if (function_exists('fribidi_log2vis')) {
             $lines = explode("\n", $formatted);
             foreach ($lines as $i => $line) {
                 $lines[$i] = fribidi_log2vis($line, FRIBIDI_AUTO, FRIBIDI_CHARSET_UTF8);
             }
             $formatted = implode("\n", $lines);
         }
         $rows[$id] = array($formatted);
     }
     //call function to create labels
     self::createLabel($rows, $fv['label_id']);
     exit(1);
 }
Example #13
0
 /**
  * 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
     $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);
     $mapMask = $mask & 4095;
     // mask value to hide map link if there are not lat/long
     $gc = CRM_Core_SelectValues::groupContactStatus();
     if ($this->_ufGroupID) {
         require_once 'CRM/Core/PseudoConstant.php';
         $locationTypes = CRM_Core_PseudoConstant::locationType();
         $names = array();
         static $skipFields = array('group', 'tag');
         foreach ($this->_fields as $key => $field) {
             if (CRM_Utils_Array::value('in_selector', $field) && !in_array($key, $skipFields)) {
                 if (strpos($key, '-') !== false) {
                     list($fieldName, $id, $type) = explode('-', $key);
                     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";
     } else {
         if (!empty($this->_returnProperties)) {
             $names =& self::makeProperties($this->_returnProperties);
         } else {
             $names = self::$_properties;
         }
     }
     //hack for student data (checkboxs)
     $multipleSelectFields = array('preferred_communication_method' => 1);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $multipleSelectFields = CRM_Quest_BAO_Student::$multipleSelectFields;
     }
     $searchType = null;
     if ($this->_action == CRM_Core_Action::BASIC) {
         $searchType = 'basic';
     } elseif ($this->_action == CRM_Core_Action::ADVANCED) {
         $searchType = 'advance';
     }
     require_once 'CRM/Core/OptionGroup.php';
     $links =& self::links($searchType, $this->_contextMenu);
     //check explicitly added contact to a Smart Group.
     $groupID = CRM_Utils_Array::key('1', $this->_formValues['group']);
     while ($result->fetch()) {
         $row = array();
         // 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);
             } else {
                 if ($multipleSelectFields && array_key_exists($property, $multipleSelectFields)) {
                     //fix to display student checkboxes
                     $key = $property;
                     $paramsNew = array($key => $result->{$property});
                     if ($key == 'test_tutoring') {
                         $name = array($key => array('newName' => $key, 'groupName' => 'test'));
                     } else {
                         if (substr($key, 0, 4) == 'cmr_') {
                             //for  readers group
                             $name = array($key => array('newName' => $key, 'groupName' => substr($key, 0, -3)));
                         } else {
                             $name = array($key => array('newName' => $key, 'groupName' => $key));
                         }
                     }
                     CRM_Core_OptionGroup::lookupValues($paramsNew, $name, false);
                     $row[$key] = $paramsNew[$key];
                 } else {
                     if (isset($tmfFields) && $tmfFields && array_key_exists($property, $tmfFields) || substr($property, 0, 12) == 'participant_') {
                         if (substr($property, -3) == '_id') {
                             $key = substr($property, 0, -3);
                             $paramsNew = array($key => $result->{$property});
                             $name = array($key => array('newName' => $key, 'groupName' => $key));
                             CRM_Core_OptionGroup::lookupValues($paramsNew, $name, false);
                             $row[$key] = $paramsNew[$key];
                         } else {
                             $row[$property] = $result->{$property};
                         }
                     } else {
                         if (strpos($property, '-im')) {
                             $row[$property] = $result->{$property};
                             if (!empty($result->{$property})) {
                                 $imProviders = CRM_Core_PseudoConstant::IMProvider();
                                 $providerId = $property . "-provider_id";
                                 $providerName = $imProviders[$result->{$providerId}];
                                 $row[$property] = $result->{$property} . " ({$providerName})";
                             }
                         } else {
                             if (in_array($property, array('addressee', 'email_greeting', 'postal_greeting'))) {
                                 $greeting = $property . '_display';
                                 $row[$property] = $result->{$greeting};
                             } else {
                                 $row[$property] = $result->{$property};
                             }
                         }
                     }
                 }
             }
             if (!empty($result->{$property})) {
                 $empty = false;
             }
         }
         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 (is_numeric(CRM_Utils_Array::value('geo_code_1', $row)) || $config->mapGeoCoding && CRM_Utils_Array::value('city', $row) && $row['state_province']) {
                 $row['action'] = CRM_Core_Action::formLink($links, $mask, array('id' => $result->contact_id));
             } else {
                 $row['action'] = CRM_Core_Action::formLink($links, $mapMask, array('id' => $result->contact_id));
             }
             // allow components to add more actions
             CRM_Core_Component::searchAction($row, $result->contact_id);
             require_once 'CRM/Contact/BAO/Contact/Utils.php';
             $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_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 (!$empty) {
             $duplicate = false;
             foreach ($rows as $checkRow) {
                 if ($checkRow['contact_id'] == $row['contact_id']) {
                     $duplicate = true;
                 }
             }
             if (!$duplicate) {
                 $rows[] = $row;
             }
         }
     }
     //CRM_Core_Error::debug( '$rows', $rows );
     return $rows;
 }
 /**
  * Browse the listing
  *
  * @return void
  * @access public
  */
 function browse()
 {
     if ($this->_profileId) {
         $fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, NULL, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::EDIT);
         $multiRecordFields = array();
         $fieldIDs = NULL;
         $result = NULL;
         $multiRecordFieldsWithSummaryListing = CRM_Core_BAO_UFGroup::shiftMultiRecordFields($fields, $multiRecordFields, TRUE);
         $multiFieldId = CRM_Core_BAO_CustomField::getKeyID(key($multiRecordFields));
         $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $multiFieldId, 'custom_group_id');
         $reached = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupId, $this->_contactId);
         if (!$reached) {
             $this->assign('contactId', $this->_contactId);
             $this->assign('gid', $this->_profileId);
         }
         $this->assign('reachedMax', $reached);
         if ($multiRecordFieldsWithSummaryListing && !empty($multiRecordFieldsWithSummaryListing)) {
             $fieldIDs = array_keys($multiRecordFieldsWithSummaryListing);
         }
     }
     if ($fieldIDs && !empty($fieldIDs) && $this->_contactId) {
         $options = array();
         $returnProperities = array('html_type', 'data_type', 'date_format', 'time_format');
         foreach ($fieldIDs as $key => $fieldID) {
             $fieldIDs[$key] = CRM_Core_BAO_CustomField::getKeyID($fieldID);
             $param = array('id' => $fieldIDs[$key]);
             $returnValues = array();
             CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $param, $returnValues, $returnProperities);
             $optionValuePairs = CRM_Core_BAO_CustomOption::getCustomOption($fieldIDs[$key]);
             if (!empty($optionValuePairs)) {
                 foreach ($optionValuePairs as $optionPairs) {
                     $options[$fieldIDs[$key]][$optionPairs['value']] = $optionPairs['label'];
                 }
             }
             $options[$fieldIDs[$key]]['attributes']['html_type'] = $returnValues['html_type'];
             $options[$fieldIDs[$key]]['attributes']['data_type'] = $returnValues['data_type'];
             $options[$fieldIDs[$key]]['attributes']['format'] = $options[$fieldIDs[$key]]['attributes']['date_format'] = CRM_Utils_Array::value('date_format', $returnValues);
             $options[$fieldIDs[$key]]['attributes']['time_format'] = CRM_Utils_Array::value('time_format', $returnValues);
         }
         $result = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_contactId, NULL, $fieldIDs, TRUE);
         if (!empty($fieldIDs)) {
             //get the group info of multi rec fields in listing view
             $fieldInput = $fieldIDs;
             $fieldIdInput = $fieldIDs[0];
         } else {
             //if no listing fields exist, take the group title for display
             $nonListingFieldIds = array_keys($multiRecordFields);
             $singleField = CRM_Core_BAO_CustomField::getKeyID($nonListingFieldIds[0]);
             $fieldIdInput = $singleField;
             $singleField = array($singleField);
             $fieldInput = $singleField;
         }
         $customGroupInfo = CRM_Core_BAO_CustomGroup::getGroupTitles($fieldInput);
         $this->_customGroupTitle = $customGroupInfo[$fieldIdInput]['groupTitle'];
         if ($result && !empty($result)) {
             $links = self::links();
             $pageCheckSum = $this->get('pageCheckSum');
             if ($pageCheckSum) {
                 foreach ($links as $key => $link) {
                     $links[$key] = $link['qs'] . "&cs=%%cs%%";
                 }
             }
             $linkAction = array_sum(array_keys($this->links()));
             foreach ($result as $recId => &$value) {
                 foreach ($value as $fieldId => &$val) {
                     if (is_numeric($fieldId)) {
                         $customValue =& $val;
                         $customValue = CRM_Core_BAO_CustomField::getDisplayValue($customValue, $fieldId, $options);
                         if (!$customValue) {
                             $customValue = "";
                         }
                         $actionParams = array('recordId' => $recId, 'gid' => $this->_profileId, 'id' => $this->_contactId, 'onPopupClose' => $this->_onPopupClose);
                         if ($pageCheckSum) {
                             $actionParams['cs'] = $pageCheckSum;
                         }
                         $value['action'] = CRM_Core_Action::formLink($links, $linkAction, $actionParams, ts('more'), FALSE, 'profile.multiValue.row', 'customValue', $fieldId);
                     }
                 }
             }
         }
     }
     $headers = array();
     if (!empty($fieldIDs)) {
         foreach ($fieldIDs as $fieldID) {
             $headers[$fieldID] = $customGroupInfo[$fieldID]['fieldLabel'];
         }
     }
     $this->assign('customGroupTitle', $this->_customGroupTitle);
     $this->assign('headers', $headers);
     $this->assign('records', $result);
 }
 public static function exportComponents($selectAll, $ids, $params, $order = NULL, $fields = NULL, $moreReturnProperties = NULL, $exportMode = CRM_Export_Form_Select_Relationship::RELATIONSHIP_EXPORT, $componentClause = NULL, $componentTable = NULL, $mergeSameAddress = FALSE, $mergeSameHousehold = FALSE, $exportParams = array(), $queryOperator = 'AND')
 {
     $headerRows = $returnProperties = array();
     $queryMode = CRM_Relationship_BAO_Query::MODE_RELATIONSHIPS;
     //Welke velden exporteren, gezet bij een mapping, indien niet gezet, primary fields.
     if ($fields) {
         foreach ($fields as $key => $value) {
             $fieldName = CRM_Utils_Array::value(0, $value);
             if (!$fieldName) {
                 continue;
             }
             $returnProperties[$fieldName] = 1;
         }
     } else {
         // Copied from CRM_Relationship_BAO_QUERY should be refactored to seperate
         // method.
         $fields = CRM_Contact_BAO_Relationship::fields();
         // Add display_name for both contacts
         $contact_fields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE, TRUE);
         $fields['contact_a'] = $contact_fields['display_name'];
         $fields['contact_a']['where'] = 'contact_a.display_name';
         $fields['contact_b'] = $contact_fields['display_name'];
         $fields['contact_b']['where'] = 'contact_b.display_name';
         // Add relationship type field
         $relationship_type_fields = CRM_Contact_BAO_RelationshipType::fields();
         $fields['relationship_type'] = $relationship_type_fields['label_a_b'];
         $fields['relationship_type']['where'] = 'relationship_type.label_a_b';
         // Add custom fields
         $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Relationship'));
         $returnProperties = CRM_Relationship_BAO_Query::defaultReturnProperties();
     }
     if ($moreReturnProperties) {
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $query = new CRM_Relationship_BAO_Query($params, $returnProperties, NULL, FALSE, FALSE, FALSE, TRUE, $queryOperator);
     //sort by state
     //CRM-15301
     $query->_sort = $order;
     list($select, $from, $where, $having) = $query->query();
     $allRelContactArray = $relationQuery = array();
     if (!$selectAll && $componentTable) {
         // TODO For not select all
         //$from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
     } elseif ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     $queryString = "{$select} {$from} {$where} {$having}";
     $groupBy = "";
     if ($queryMode & CRM_Relationship_BAO_Query::MODE_RELATIONSHIPS && $query->_useGroupBy) {
         $groupBy = " GROUP BY relationship.id";
     }
     $queryString .= $groupBy;
     // always add relationship.id to the ORDER clause
     // so the order is deterministic
     if (strpos('relationship.id', $order) === FALSE) {
         $order .= ", relationship.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (!empty($returnProperties[$field])) {
             //CRM-15301
             $queryString .= " ORDER BY {$order}";
         }
     }
     $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;
             //first loop through output columns so that we return what is required, and in same order.
             foreach ($outputColumns as $field => $value) {
                 //we should set header only once
                 if ($setHeader) {
                     $sqlDone = FALSE;
                     $headerRows[] = $query->_fields[$field]['title'];
                     if (!$sqlDone) {
                         self::sqlColumnDefn($query, $sqlColumns, $field);
                     }
                 }
                 //build row values (data)
                 $fieldValue = NULL;
                 if (property_exists($iterationDAO, $field)) {
                     $fieldValue = $iterationDAO->{$field};
                 }
                 if ($field == 'id') {
                     $row[$field] = $iterationDAO->relationship_id;
                 } 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);
                     } else {
                         //normal fields with a touch of CRM-3157
                         $row[$field] = $fieldValue;
                     }
                 } else {
                     // if field is empty or null
                     $row[$field] = '';
                 }
             }
             if ($setHeader) {
                 $exportTempTable = self::createTempTable($sqlColumns);
             }
             //build header only once
             $setHeader = FALSE;
             // 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);
         }
         // 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'));
     }
 }
Example #16
0
 /**
  * Function to 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  $associated array of fields
  * @param array  $moreReturnProperties additional return fields
  * @param int    $exportMode export mode
  * @param string $componentClause component clause
  *
  * @static
  * @access public
  */
 static function exportComponents($selectAll, $ids, $params, $order = null, $fields = null, $moreReturnProperties = null, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = null)
 {
     $headerRows = array();
     $primary = false;
     $returnProperties = array();
     $origFields = $fields;
     $queryMode = null;
     $paymentFields = false;
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true, 'label', false);
     $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
             break;
         case CRM_Export_Form_Select::PLEDGE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
             break;
         case CRM_Export_Form_Select::CASE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CASE;
             break;
         case CRM_Export_Form_Select::GRANT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_GRANT;
             break;
     }
     require_once 'CRM/Core/BAO/CustomField.php';
     if ($fields) {
         //construct return properties
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $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 = null;
             $imProviderId = null;
             $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
             if (!$fieldName) {
                 continue;
             }
             // get phoneType id and IM service provider id seperately
             if ($fieldName == 'phone') {
                 $phoneTypeId = CRM_Utils_Array::value(3, $value);
             } else {
                 if ($fieldName == 'im') {
                     $imProviderId = CRM_Utils_Array::value(3, $value);
                 }
             }
             if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
                 if (CRM_Utils_Array::value(2, $value)) {
                     $relationField = CRM_Utils_Array::value(2, $value);
                     if (trim(CRM_Utils_Array::value(3, $value))) {
                         $relLocTypeId = CRM_Utils_Array::value(3, $value);
                     } else {
                         $relLocTypeId = 1;
                     }
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
                     } else {
                         if ($relationField == 'im') {
                             $relIMProviderId = CRM_Utils_Array::value(4, $value);
                         }
                     }
                 } else {
                     if (CRM_Utils_Array::value(4, $value)) {
                         $relationField = CRM_Utils_Array::value(4, $value);
                         $relLocTypeId = CRM_Utils_Array::value(5, $value);
                         if ($relationField == 'phone') {
                             $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
                         } else {
                             if ($relationField == 'im') {
                                 $relIMProviderId = CRM_Utils_Array::value(6, $value);
                             }
                         }
                     }
                 }
             }
             $contactType = CRM_Utils_Array::value(0, $value);
             $locTypeId = CRM_Utils_Array::value(2, $value);
             $phoneTypeId = CRM_Utils_Array::value(3, $value);
             if ($relationField) {
                 if (in_array($relationField, $locationTypeFields)) {
                     if ($relPhoneTypeId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
                     } else {
                         if ($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;
                 }
             } else {
                 if (is_numeric($locTypeId)) {
                     if ($phoneTypeId) {
                         $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
                     } else {
                         if (isset($imProviderId)) {
                             //build returnProperties for IM service provider
                             $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
                         } else {
                             $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
                         }
                     }
                 } else {
                     //hack to fix component fields
                     if ($fieldName == 'event_id') {
                         $returnProperties['event_title'] = 1;
                     } else {
                         $returnProperties[$fieldName] = 1;
                     }
                 }
             }
         }
         // hack to add default returnproperty based on export mode
         if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
             $returnProperties['contribution_id'] = 1;
         } else {
             if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
                 $returnProperties['participant_id'] = 1;
             } else {
                 if ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
                     $returnProperties['membership_id'] = 1;
                 } else {
                     if ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
                         $returnProperties['pledge_id'] = 1;
                     } else {
                         if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
                             $returnProperties['case_id'] = 1;
                         } else {
                             if ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) {
                                 $returnProperties['grant_id'] = 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:
                 require_once 'CRM/Pledge/BAO/Query.php';
                 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
                 $paymentFields = true;
                 $paymentTableId = "pledge_payment_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_CASE:
                 require_once 'CRM/Case/BAO/Query.php';
                 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
                 break;
         }
         if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
             $componentReturnProperties =& CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
             $returnProperties = array_merge($returnProperties, $componentReturnProperties);
             if (!empty($extraReturnProperties)) {
                 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
             }
             // unset groups, tags, notes for components
             foreach (array('groups', 'tags', 'notes') as $value) {
                 unset($returnProperties[$value]);
             }
         }
     }
     if ($moreReturnProperties) {
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $query =& new CRM_Contact_BAO_Query(0, $returnProperties, null, false, false, $queryMode);
     list($select, $from, $where) = $query->query();
     $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(0, $relationReturnProperties, null, false, false, $queryMode);
             list($relationSelect, $relationFrom, $relationWhere) = $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';
             }
             $relIDs = implode(',', $ids);
             $relSQL = "SELECT {$contactB} as relContact,{$contactA} as refContact  FROM civicrm_relationship \n                           WHERE  relationship_type_id = {$id} AND\n                                  {$contactA} IN ({$relIDs})\n                           GROUP BY {$contactA}";
             // Get the related contacts
             $relContactDAO = CRM_Core_DAO::executeQuery($relSQL);
             $relContactArray = array();
             while ($relContactDAO->fetch()) {
                 $relContactArray[$relContactDAO->refContact] = $relContactDAO->relContact;
             }
             $uniqueContacts = array_unique($relContactArray);
             if (!empty($uniqueContacts)) {
                 $relationWhere = " WHERE contact_a.id IN (" . implode(',', $uniqueContacts) . ") GROUP BY contact_id";
                 $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere}";
                 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
                 while ($allRelContactDAO->fetch()) {
                     foreach ($relContactArray as $k => $v) {
                         if ($allRelContactDAO->contact_id == $v) {
                             //$allRelContactArray[$rel][$k] = array();
                             // build the array of all related contacts
                             $allRelContactArray[$rel][$k] = clone $allRelContactDAO;
                         }
                     }
                 }
             }
         }
     }
     // 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 (CRM_Utils_Array::value('groups', $returnProperties)) {
         $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 ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     $queryString = "{$select} {$from} {$where}";
     if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties) || CRM_Utils_Array::value('notes', $returnProperties) || $query->_useGroupBy) {
         $queryString .= " GROUP BY contact_a.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (CRM_Utils_Array::value($field, $returnProperties)) {
             $queryString .= " ORDER BY {$order}";
         }
     }
     //hack for student data
     require_once 'CRM/Core/OptionGroup.php';
     $multipleSelectFields = array('preferred_communication_method' => 1);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $studentFields = array();
         $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields;
         $multipleSelectFields = array_merge($multipleSelectFields, $studentFields);
     }
     $dao =& CRM_Core_DAO::executeQuery($queryString, CRM_Core_DAO::$_nullArray);
     $header = false;
     $addPaymentHeader = false;
     if ($paymentFields) {
         $addPaymentHeader = true;
         //special return properties for event and members
         $paymentHeaders = array(ts('Total Amount'), ts('Contribution Status'), ts('Received Date'), ts('Payment Instrument'), ts('Transaction ID'));
         // get payment related in for event and members
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
     }
     $componentDetails = $headerRows = array();
     $setHeader = true;
     while ($dao->fetch()) {
         $row = array();
         //first loop through returnproperties so that we return what is required, and in same order.
         $relationshipField = 0;
         foreach ($returnProperties as $field => $value) {
             //we should set header only once
             if ($setHeader) {
                 if (isset($query->_fields[$field]['title'])) {
                     $headerRows[] = $query->_fields[$field]['title'];
                 } else {
                     if ($field == 'phone_type_id') {
                         $headerRows[] = 'Phone Type';
                     } else {
                         if ($field == 'provider_id') {
                             $headerRows[] = 'Im Service Provider';
                         } else {
                             if (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 (CRM_Utils_Array::value(1, $type)) {
                                             if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                             } else {
                                                 if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                     $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                 }
                                             }
                                         }
                                         $headerRows[] = $hdr;
                                     }
                                 }
                             } else {
                                 if (substr($field, 0, 5) == 'case_') {
                                     if ($query->_fields['case'][$field]['title']) {
                                         $headerRows[] = $query->_fields['case'][$field]['title'];
                                     } else {
                                         if ($query->_fields['activity'][$field]['title']) {
                                             $headerRows[] = $query->_fields['activity'][$field]['title'];
                                         }
                                     }
                                 } else {
                                     if (array_key_exists($field, $contactRelationshipTypes)) {
                                         $relName = CRM_Utils_Array::value($field, $contactRelationshipTypes);
                                         foreach ($value as $relationField => $relationValue) {
                                             // below block is same as primary block (duplicate)
                                             if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
                                                 $headerRows[] = $relName . '-' . $relationQuery[$field]->_fields[$relationField]['title'];
                                             } else {
                                                 if ($relationField == 'phone_type_id') {
                                                     $headerRows[] = $relName . '-' . 'Phone Type';
                                                 } else {
                                                     if ($relationField == 'provider_id') {
                                                         $headerRows[] = $relName . '-' . 'Im Service Provider';
                                                     } else {
                                                         if (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 (CRM_Utils_Array::value(1, $type)) {
                                                                         if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                                             $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                                                         } else {
                                                                             if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                                             }
                                                                         }
                                                                     }
                                                                     $headerRows[] = $relName . '-' . $hdr;
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     } else {
                                         $headerRows[] = $field;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             //build row values (data)
             if (property_exists($dao, $field)) {
                 $fieldValue = $dao->{$field};
                 // to get phone type from phone type id
                 if ($field == 'phone_type_id') {
                     $fieldValue = $phoneTypes[$fieldValue];
                 } else {
                     if ($field == 'provider_id') {
                         $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
                     }
                 }
             } else {
                 $fieldValue = '';
             }
             if ($field == 'id') {
                 $row[$field] = $dao->contact_id;
             } else {
                 if ($field == 'pledge_balance_amount') {
                     //special case for calculated field
                     $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid;
                 } else {
                     if ($field == 'pledge_next_pay_amount') {
                         //special case for calculated field
                         $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount;
                     } else {
                         if (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];
                                     if (CRM_Utils_Array::value(1, $type)) {
                                         $fldValue .= "-" . $type[1];
                                     }
                                     $row[$fldValue] = $dao->{$fldValue};
                                 }
                             }
                         } else {
                             if (array_key_exists($field, $contactRelationshipTypes)) {
                                 $relDAO = $allRelContactArray[$field][$dao->contact_id];
                                 foreach ($value as $relationField => $relationValue) {
                                     if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
                                         $fieldValue = $relDAO->{$relationField};
                                         if ($relationField == 'phone_type_id') {
                                             $fieldValue = $phoneTypes[$relationValue];
                                         } else {
                                             if ($relationField == 'provider_id') {
                                                 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
                                             }
                                         }
                                     } else {
                                         $fieldValue = '';
                                     }
                                     if ($relationField == 'id') {
                                         $row[$field . $relationField] = $relDAO->contact_id;
                                     } else {
                                         if (is_array($relationValue) && $relationField == 'location') {
                                             foreach ($relationValue as $ltype => $val) {
                                                 foreach (array_keys($val) as $fld) {
                                                     $type = explode('-', $fld);
                                                     $fldValue = "{$ltype}-" . $type[0];
                                                     if (CRM_Utils_Array::value(1, $type)) {
                                                         $fldValue .= "-" . $type[1];
                                                     }
                                                     $row[$field . $fldValue] = $relDAO->{$fldValue};
                                                 }
                                             }
                                         } else {
                                             if (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 {
                                                     if (in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                         //special case for greeting replacement
                                                         $fldValue = "{$relationField}_display";
                                                         $row[$field . $relationField] = $relDAO->{$fldValue};
                                                     } else {
                                                         //normal relationship fields
                                                         $row[$field . $relationField] = $fieldValue;
                                                     }
                                                 }
                                             } else {
                                                 // if relation field is empty or null
                                                 $row[$field . $relationField] = '';
                                             }
                                         }
                                     }
                                 }
                             } else {
                                 if (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);
                                     } else {
                                         if (array_key_exists($field, $multipleSelectFields)) {
                                             //option group fixes
                                             $paramsNew = array($field => $fieldValue);
                                             if ($field == 'test_tutoring') {
                                                 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
                                             } else {
                                                 if (substr($field, 0, 4) == 'cmr_') {
                                                     //for  readers group
                                                     $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];
                                         } else {
                                             if (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                 //special case for greeting replacement
                                                 $fldValue = "{$field}_display";
                                                 $row[$field] = $dao->{$fldValue};
                                             } else {
                                                 //normal fields
                                                 $row[$field] = $fieldValue;
                                             }
                                         }
                                     }
                                 } else {
                                     // if field is empty or null
                                     $row[$field] = '';
                                 }
                             }
                         }
                     }
                 }
             }
         }
         //build header only once
         $setHeader = false;
         // add payment headers if required
         if ($addPaymentHeader && $paymentFields) {
             $headerRows = array_merge($headerRows, $paymentHeaders);
             $addPaymentHeader = false;
         }
         // add payment related information
         if ($paymentFields && isset($paymentDetails[$row[$paymentTableId]])) {
             $row = array_merge($row, $paymentDetails[$row[$paymentTableId]]);
         }
         //remove organization name for individuals if it is set for current employer
         if (CRM_Utils_Array::value('contact_type', $row) && $row['contact_type'] == 'Individual') {
             $row['organization_name'] = '';
         }
         // CRM-3157: localise the output
         // FIXME: we should move this to multilingual stack some day
         require_once 'CRM/Core/I18n.php';
         $i18n =& CRM_Core_I18n::singleton();
         $translatable = array('preferred_communication_method', 'preferred_mail_format', 'gender', 'state_province', 'country', 'world_region');
         foreach ($translatable as $column) {
             if (isset($row[$column]) and $row[$column]) {
                 $row[$column] = $i18n->translate($row[$column]);
             }
         }
         // add component info
         $componentDetails[] = $row;
     }
     require_once 'CRM/Core/Report/Excel.php';
     CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName('csv', $exportMode), $headerRows, $componentDetails);
     exit;
 }
 /**
  * Generate the where clause and also the english language.
  * equivalent
  *
  * @return void
  */
 public function where()
 {
     foreach ($this->_ids as $id => $values) {
         // Fixed for Isuue CRM 607
         if (CRM_Utils_Array::value($id, $this->_fields) === NULL || !$values) {
             continue;
         }
         $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
         foreach ($values as $tuple) {
             list($name, $op, $value, $grouping, $wildcard) = $tuple;
             $field = $this->_fields[$id];
             $fieldName = "{$field['table_name']}.{$field['column_name']}";
             // Autocomplete comes back as a string not an array
             if ($field['data_type'] == 'String' && $field['html_type'] == 'Autocomplete-Select' && $op == '=') {
                 $value = explode(',', $value);
             }
             $isSerialized = CRM_Core_BAO_CustomField::isSerialized($field);
             // fix $value here to escape sql injection attacks
             $qillValue = NULL;
             if (!is_array($value)) {
                 $value = CRM_Core_DAO::escapeString(trim($value));
                 $qillValue = CRM_Core_BAO_CustomField::getDisplayValue($value, $id, $this->_options);
             } elseif (count($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
                 $op = key($value);
                 $qillValue = CRM_Core_BAO_CustomField::getDisplayValue($value[$op], $id, $this->_options);
             } else {
                 $op = 'IN';
                 $qillValue = CRM_Core_BAO_CustomField::getDisplayValue($value, $id, $this->_options);
             }
             $qillOp = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op);
             switch ($field['data_type']) {
                 case 'String':
                 case 'StateProvince':
                 case 'Country':
                     if ($field['is_search_range'] && is_array($value)) {
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         // fix $value here to escape sql injection attacks
                         if (!is_array($value)) {
                             if ($field['data_type'] == 'String') {
                                 $value = CRM_Utils_Type::escape($strtolower($value), 'String');
                             } else {
                                 $value = CRM_Utils_Type::escape($value, 'Integer');
                             }
                         } elseif ($isSerialized) {
                             if (in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
                                 $op = key($value);
                                 $value = $value[$op];
                             }
                             $value = implode(',', $value);
                         }
                         // CRM-14563,CRM-16575 : Special handling of multi-select custom fields
                         if ($isSerialized && !empty($value)) {
                             if (strstr($op, 'IN')) {
                                 $value = str_replace(",", "[[:cntrl:]]*|[[:cntrl:]]*", $value);
                                 $value = str_replace('(', '[[.left-parenthesis.]]', $value);
                                 $value = str_replace(')', '[[.right-parenthesis.]]', $value);
                             }
                             $op = strstr($op, '!') || strstr($op, 'NOT') ? 'NOT RLIKE' : 'RLIKE';
                             $value = "[[:cntrl:]]*" . $value . "[[:cntrl:]]*";
                             if (!$wildcard) {
                                 $value = str_replace("[[:cntrl:]]*|", '', $value);
                             }
                         }
                         //FIX for custom data query fired against no value(NULL/NOT NULL)
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
                         $this->_qill[$grouping][] = "{$field['label']} {$qillOp} {$qillValue}";
                     }
                     break;
                 case 'ContactReference':
                     $label = $value ? CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name') : '';
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
                     $this->_qill[$grouping][] = $field['label'] . " {$qillOp} {$label}";
                     break;
                 case 'Int':
                     if ($field['is_search_range'] && is_array($value)) {
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
                         $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
                     }
                     break;
                 case 'Boolean':
                     if (!is_array($value)) {
                         if (strtolower($value) == 'yes' || strtolower($value) == strtolower(ts('Yes'))) {
                             $value = 1;
                         } else {
                             $value = (int) $value;
                         }
                         $value = $value == 1 ? 1 : 0;
                         $qillValue = $value ? 'Yes' : 'No';
                     }
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
                     $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
                     break;
                 case 'Link':
                 case 'Memo':
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
                     $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
                     break;
                 case 'Money':
                     if (is_array($value)) {
                         $value = CRM_Utils_Array::value($op, $value, $value);
                         foreach ($value as $key => $val) {
                             $moneyFormat = CRM_Utils_Rule::cleanMoney($value[$key]);
                             $value[$key] = $moneyFormat;
                         }
                     } else {
                         $value = CRM_Utils_Rule::cleanMoney($value);
                     }
                 case 'Float':
                     if ($field['is_search_range']) {
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Float');
                         $this->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $field['label'], 2 => $qillOp, 3 => $qillValue));
                     }
                     break;
                 case 'Date':
                     $fromValue = CRM_Utils_Array::value('from', $value);
                     $toValue = CRM_Utils_Array::value('to', $value);
                     if (!$fromValue && !$toValue) {
                         if (!CRM_Utils_Date::processDate($value) && !in_array($op, array('IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY'))) {
                             continue;
                         }
                         // hack to handle yy format during search
                         if (is_numeric($value) && strlen($value) == 4) {
                             $value = "01-01-{$value}";
                         }
                         $date = CRM_Utils_Date::processDate($value);
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $date, 'String');
                         $this->_qill[$grouping][] = $field['label'] . " {$qillOp} " . CRM_Utils_Date::customFormat($date);
                     } else {
                         if (is_numeric($fromValue) && strlen($fromValue) == 4) {
                             $fromValue = "01-01-{$fromValue}";
                         }
                         if (is_numeric($toValue) && strlen($toValue) == 4) {
                             $toValue = "01-01-{$toValue}";
                         }
                         // TO DO: add / remove time based on date parts
                         $fromDate = CRM_Utils_Date::processDate($fromValue);
                         $toDate = CRM_Utils_Date::processDate($toValue);
                         if (!$fromDate && !$toDate) {
                             continue;
                         }
                         if ($fromDate) {
                             $this->_where[$grouping][] = "{$fieldName} >= {$fromDate}";
                             $this->_qill[$grouping][] = $field['label'] . ' >= ' . CRM_Utils_Date::customFormat($fromDate);
                         }
                         if ($toDate) {
                             $this->_where[$grouping][] = "{$fieldName} <= {$toDate}";
                             $this->_qill[$grouping][] = $field['label'] . ' <= ' . CRM_Utils_Date::customFormat($toDate);
                         }
                     }
                     break;
                 case 'File':
                     if ($op == 'IS NULL' || $op == 'IS NOT NULL' || $op == 'IS EMPTY' || $op == 'IS NOT EMPTY') {
                         switch ($op) {
                             case 'IS EMPTY':
                                 $op = 'IS NULL';
                                 break;
                             case 'IS NOT EMPTY':
                                 $op = 'IS NOT NULL';
                                 break;
                         }
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op);
                         $this->_qill[$grouping][] = $field['label'] . " {$qillOp} ";
                     }
                     break;
             }
         }
     }
 }
 /**
  * generate the where clause and also the english language
  * equivalent
  *
  * @param NULL
  *
  * @return void
  *
  * @access public
  */
 function where()
 {
     //CRM_Core_Error::debug( 'fld', $this->_fields );
     //CRM_Core_Error::debug( 'ids', $this->_ids );
     foreach ($this->_ids as $id => $values) {
         // Fixed for Isuue CRM 607
         if (CRM_Utils_Array::value($id, $this->_fields) === NULL || !$values) {
             continue;
         }
         $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
         foreach ($values as $tuple) {
             list($name, $op, $value, $grouping, $wildcard) = $tuple;
             // fix $value here to escape sql injection attacks
             $field = $this->_fields[$id];
             $qillValue = CRM_Core_BAO_CustomField::getDisplayValue($value, $id, $this->_options);
             if (!is_array($value)) {
                 $value = CRM_Core_DAO::escapeString(trim($value));
             }
             $fieldName = "{$field['table_name']}.{$field['column_name']}";
             switch ($field['data_type']) {
                 case 'String':
                     $sql = "{$fieldName}";
                     // if we are coming in from listings,
                     // for checkboxes the value is already in the right format and is NOT an array
                     if (is_array($value)) {
                         //ignoring $op value for checkbox and multi select
                         $sqlValue = array();
                         $sqlOP = ' AND ';
                         $sqlOPlabel = ts('match ALL');
                         if ($field['html_type'] == 'CheckBox') {
                             foreach ($value as $k => $v) {
                                 if ($v) {
                                     if ($k == 'CiviCRM_OP_OR') {
                                         $sqlOP = ' OR ';
                                         $sqlOPlabel = ts('match ANY');
                                         continue;
                                     }
                                     $sqlValue[] = "( {$sql} like '%" . CRM_Core_DAO::VALUE_SEPARATOR . $k . CRM_Core_DAO::VALUE_SEPARATOR . "%' ) ";
                                 }
                             }
                             //if user check only 'CiviCRM_OP_OR' check box
                             //of custom checkbox field, then ignore this field.
                             if (!empty($sqlValue)) {
                                 $this->_where[$grouping][] = ' ( ' . implode($sqlOP, $sqlValue) . ' ) ';
                                 $this->_qill[$grouping][] = "{$field['label']} {$op} {$qillValue} ( {$sqlOPlabel} )";
                             }
                             // for multi select
                         } else {
                             foreach ($value as $k => $v) {
                                 if ($v == 'CiviCRM_OP_OR') {
                                     $sqlOP = ' OR ';
                                     $sqlOPlabel = ts('match ANY');
                                     continue;
                                 }
                                 $v = CRM_Core_DAO::escapeString($v);
                                 $sqlValue[] = "( {$sql} like '%" . CRM_Core_DAO::VALUE_SEPARATOR . $v . CRM_Core_DAO::VALUE_SEPARATOR . "%' ) ";
                             }
                             //if user select only 'CiviCRM_OP_OR' value
                             //of custom multi select field, then ignore this field.
                             if (!empty($sqlValue)) {
                                 $this->_where[$grouping][] = ' ( ' . implode($sqlOP, $sqlValue) . ' ) ';
                                 $this->_qill[$grouping][] = "{$field['label']} {$op} {$qillValue} ( {$sqlOPlabel} )";
                             }
                         }
                     } else {
                         if ($field['is_search_range'] && is_array($value)) {
                             $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                         } else {
                             if ($field['html_type'] == 'Autocomplete-Select') {
                                 $wildcard = FALSE;
                                 $val = array_search($value, $this->_options[$field['id']]);
                             } elseif (in_array($field['html_type'], array('Select', 'Radio'))) {
                                 $wildcard = FALSE;
                                 $val = CRM_Utils_Type::escape($value, 'String');
                             } else {
                                 $val = CRM_Utils_Type::escape($strtolower(trim($value)), 'String');
                             }
                             if ($wildcard) {
                                 $val = $strtolower(CRM_Core_DAO::escapeString($val));
                                 $val = "%{$val}%";
                                 $op = 'LIKE';
                             }
                             //FIX for custom data query fired against no value(NULL/NOT NULL)
                             $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($sql, $op, $val, $field['data_type']);
                             $this->_qill[$grouping][] = "{$field['label']} {$op} {$qillValue}";
                         }
                     }
                     continue;
                 case 'ContactReference':
                     $label = $value ? CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name') : '';
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
                     $this->_qill[$grouping][] = $field['label'] . " {$op} {$label}";
                     continue;
                 case 'Int':
                     if ($field['is_search_range'] && is_array($value)) {
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
                         $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}";
                     }
                     continue;
                 case 'Boolean':
                     $value = (int) $value;
                     $value = $value == 1 ? 1 : 0;
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
                     $value = $value ? ts('Yes') : ts('No');
                     $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}";
                     continue;
                 case 'Link':
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
                     $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}";
                     continue;
                 case 'Float':
                     if ($field['is_search_range'] && is_array($value)) {
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Float');
                         $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}";
                     }
                     continue;
                 case 'Money':
                     if ($field['is_search_range'] && is_array($value)) {
                         foreach ($value as $key => $val) {
                             $moneyFormat = CRM_Utils_Rule::cleanMoney($value[$key]);
                             $value[$key] = $moneyFormat;
                         }
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         $moneyFormat = CRM_Utils_Rule::cleanMoney($value);
                         $value = $moneyFormat;
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Float');
                         $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}";
                     }
                     continue;
                 case 'Memo':
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
                     $this->_qill[$grouping][] = "{$field['label']} {$op} {$value}";
                     continue;
                 case 'Date':
                     $fromValue = CRM_Utils_Array::value('from', $value);
                     $toValue = CRM_Utils_Array::value('to', $value);
                     if (!$fromValue && !$toValue) {
                         if (!CRM_Utils_Date::processDate($value) && $op != 'IS NULL' && $op != 'IS NOT NULL') {
                             continue;
                         }
                         // hack to handle yy format during search
                         if (is_numeric($value) && strlen($value) == 4) {
                             $value = "01-01-{$value}";
                         }
                         $date = CRM_Utils_Date::processDate($value);
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $date, 'String');
                         $this->_qill[$grouping][] = $field['label'] . " {$op} " . CRM_Utils_Date::customFormat($date);
                     } else {
                         if (is_numeric($fromValue) && strlen($fromValue) == 4) {
                             $fromValue = "01-01-{$fromValue}";
                         }
                         if (is_numeric($toValue) && strlen($toValue) == 4) {
                             $toValue = "01-01-{$toValue}";
                         }
                         // TO DO: add / remove time based on date parts
                         $fromDate = CRM_Utils_Date::processDate($fromValue);
                         $toDate = CRM_Utils_Date::processDate($toValue);
                         if (!$fromDate && !$toDate) {
                             continue;
                         }
                         if ($fromDate) {
                             $this->_where[$grouping][] = "{$fieldName} >= {$fromDate}";
                             $this->_qill[$grouping][] = $field['label'] . ' >= ' . CRM_Utils_Date::customFormat($fromDate);
                         }
                         if ($toDate) {
                             $this->_where[$grouping][] = "{$fieldName} <= {$toDate}";
                             $this->_qill[$grouping][] = $field['label'] . ' <= ' . CRM_Utils_Date::customFormat($toDate);
                         }
                     }
                     continue;
                 case 'StateProvince':
                 case 'Country':
                     if (!is_array($value)) {
                         $this->_where[$grouping][] = "{$fieldName} {$op} " . CRM_Utils_Type::escape($value, 'Int');
                         $this->_qill[$grouping][] = $field['label'] . " {$op} {$qillValue}";
                     } else {
                         $sqlOP = ' AND ';
                         $sqlOPlabel = ts('match ALL');
                         foreach ($value as $k => $v) {
                             if ($v == 'CiviCRM_OP_OR') {
                                 $sqlOP = ' OR ';
                                 $sqlOPlabel = ts('match ANY');
                                 continue;
                             }
                             $sqlValue[] = "( {$fieldName} like '%" . CRM_Core_DAO::VALUE_SEPARATOR . $v . CRM_Core_DAO::VALUE_SEPARATOR . "%' ) ";
                         }
                         //if user select only 'CiviCRM_OP_OR' value
                         //of custom multi select field, then ignore this field.
                         if (!empty($sqlValue)) {
                             $this->_where[$grouping][] = " ( " . implode($sqlOP, $sqlValue) . " ) ";
                             $this->_qill[$grouping][] = "{$field['label']} {$op} {$qillValue} ( {$sqlOPlabel} )";
                         }
                     }
                     continue;
             }
         }
     }
 }
Example #19
0
 function getCustomData($clientID, $activityDAO, &$activityTypeInfo)
 {
     list($typeValues, $options, $sql) = $this->getActivityTypeCustomSQL($activityTypeInfo['id'], '%Y-%m-%d');
     $params = array(1 => array($activityDAO->id, 'Integer'));
     require_once "CRM/Core/BAO/CustomField.php";
     $customGroups = array();
     foreach ($sql as $tableName => $sqlClause) {
         $dao = CRM_Core_DAO::executeQuery($sqlClause, $params);
         if ($dao->fetch()) {
             $customGroup = array();
             foreach ($typeValues[$tableName] as $columnName => $typeValue) {
                 $value = CRM_Core_BAO_CustomField::getDisplayValue($dao->{$columnName}, $typeValue['fieldID'], $options);
                 // Note: this is already taken care in getDisplayValue above, but sometimes
                 // strings like '^A^A' creates problem. So to fix this special case -
                 if (strstr($value, CRM_Core_BAO_CustomOption::VALUE_SEPERATOR)) {
                     $value = trim($value, CRM_Core_BAO_CustomOption::VALUE_SEPERATOR);
                 }
                 if (CRM_Utils_Array::value('type', $typeValue) == 'String' || CRM_Utils_Array::value('type', $typeValue) == 'Memo') {
                     $value = $this->redact($value);
                 }
                 //$typeValue
                 $customGroup[] = array('label' => $typeValue['label'], 'value' => $value, 'type' => $typeValue['type']);
             }
             $customGroups[$dao->groupTitle] = $customGroup;
         }
     }
     return empty($customGroups) ? null : $customGroups;
 }
Example #20
0
 /**
  * function to get the rows for the labels
  *
  * @param array $contactIds Contact IDS to do labels for
  * @param integer $locationTypeID
  * @param boolean $respectDoNotMail
  * @return array of rows for labels
  * @access  public
  */
 static function getRows($contactIDs, $locationTypeID, $respectDoNotMail, $mergeSameAddress, $mergeSameHousehold)
 {
     $locName = NULL;
     //get the address format sequence from the config file
     $addressReturnProperties = CRM_Contact_Form_Task_LabelCommon::getAddressReturnProperties();
     //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 = CRM_Contact_Form_Task_LabelCommon::regexReturnProperties($mailingFormat);
         $returnProperties = array_merge($returnProperties, $mailingFormatProperties);
     }
     $customFormatProperties = array();
     if (stristr($mailingFormat, 'custom_')) {
         foreach ($mailingFormatProperties as $token => $true) {
             if (substr($token, 0, 7) == 'custom_') {
                 if (!CRM_Utils_Array::value($token, $customFormatProperties)) {
                     $customFormatProperties[$token] = $mailingFormatProperties[$token];
                 }
             }
         }
     }
     $returnProperties = array_merge($returnProperties, $customFormatProperties);
     if ($mergeSameAddress) {
         // we need first name/last name for summarising to avoid spillage
         $returnProperties['first_name'] = 1;
         $returnProperties['last_name'] = 1;
     }
     //get the contacts information
     $params = $custom = array();
     foreach ($contactIDs as $key => $contactID) {
         $params[] = array(CRM_Core_Form::CB_PREFIX . $contactID, '=', 1, 0, 0);
     }
     // fix for CRM-2651
     if (CRM_Utils_Array::value('do_not_mail', $respectDoNotMail)) {
         $params[] = array('do_not_mail', '=', 0, 0, 0);
     }
     // fix for CRM-2613
     $params[] = array('is_deceased', '=', 0, 0, 0);
     if ($locationTypeID) {
         $locType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
         $locName = $locType[$locationTypeID];
         $location = array('location' => array("{$locName}" => $addressReturnProperties));
         $returnProperties = array_merge($returnProperties, $location);
         $params[] = array('location_type', '=', array($locationTypeID => 1), 0, 0);
     } else {
         $returnProperties = array_merge($returnProperties, $addressReturnProperties);
     }
     foreach ($returnProperties as $name) {
         $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
         if ($cfID) {
             $custom[] = $cfID;
         }
     }
     //get the total number of contacts to fetch from database.
     $numberofContacts = count($contactIDs);
     //this does the same as calling civicrm_api3('contact, get, array('id' => array('IN' => $this->_contactIds)
     // except it also handles multiple locations
     $query = new CRM_Contact_BAO_Query($params, $returnProperties);
     $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
     $messageToken = CRM_Utils_Token::getTokens($mailingFormat);
     $details = $details[0];
     $tokenFields = CRM_Contact_Form_Task_LabelCommon::getTokenData($details);
     foreach ($contactIDs as $value) {
         foreach ($custom as $cfID) {
             if (isset($details[$value]["custom_{$cfID}"])) {
                 $details[$value]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($details[$value]["custom_{$cfID}"], $cfID, $details[1]);
             }
         }
         $contact = CRM_Utils_Array::value($value, $details);
         if (is_a($contact, 'CRM_Core_Error')) {
             return NULL;
         }
         // we need to remove all the "_id"
         unset($contact['contact_id']);
         if ($locName && CRM_Utils_Array::value($locName, $contact)) {
             // If location type is not primary, $contact contains
             // one more array as "$contact[$locName] = array( values... )"
             if (!CRM_Contact_Form_Task_LabelCommon::tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) {
                 continue;
             }
             unset($contact[$locName]);
             if (CRM_Utils_Array::value('county_id', $contact)) {
                 unset($contact['county_id']);
             }
             foreach ($contact as $field => $fieldValue) {
                 $rows[$value][$field] = $fieldValue;
             }
             $valuesothers = array();
             $paramsothers = array('contact_id' => $value);
             $valuesothers = CRM_Core_BAO_Location::getValues($paramsothers, $valuesothers);
             if ($locationTypeID) {
                 foreach ($valuesothers as $vals) {
                     if (CRM_Utils_Array::value('location_type_id', $vals) == $locationTypeID) {
                         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 (!CRM_Contact_Form_Task_LabelCommon::tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) {
                 continue;
             }
             if (CRM_Utils_Array::value('addressee_display', $contact)) {
                 $contact['addressee_display'] = trim($contact['addressee_display']);
             }
             if (CRM_Utils_Array::value('addressee', $contact)) {
                 $contact['addressee'] = $contact['addressee_display'];
             }
             // now create the rows for generating mailing labels
             foreach ($contact as $field => $fieldValue) {
                 $rows[$value][$field] = $fieldValue;
             }
         }
     }
     // sigh couldn't extract out tokenfields yet
     return array($rows, $tokenFields);
 }
Example #21
0
 /**
  * Given a contact id and a field set, return the values from the db
  * for this contact
  *
  * @param int $cid
  * @param array $fields
  *   The profile fields of interest.
  * @param array $values
  *   The values for the above fields.
  * @param bool $searchable
  *   Searchable or not.
  * @param array $componentWhere
  *   Component condition.
  * @param bool $absolute
  *   Return urls in absolute form (useful when sending an email).
  * @param null $additionalWhereClause
  */
 public static function getValues($cid, &$fields, &$values, $searchable = TRUE, $componentWhere = NULL, $absolute = FALSE, $additionalWhereClause = NULL)
 {
     if (empty($cid) && empty($componentWhere)) {
         return NULL;
     }
     // get the contact details (hier)
     $returnProperties = CRM_Contact_BAO_Contact::makeHierReturnProperties($fields);
     $params = $cid ? array(array('contact_id', '=', $cid, 0, 0)) : array();
     // add conditions specified by components. eg partcipant_id etc
     if (!empty($componentWhere)) {
         $params = array_merge($params, $componentWhere);
     }
     $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
     $options =& $query->_options;
     $details = $query->searchQuery(0, 0, NULL, FALSE, FALSE, FALSE, FALSE, FALSE, $additionalWhereClause);
     if (!$details->fetch()) {
         return;
     }
     $query->convertToPseudoNames($details);
     $config = CRM_Core_Config::singleton();
     $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
     $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
     $multipleFields = array('url');
     //start of code to set the default values
     foreach ($fields as $name => $field) {
         // fix for CRM-3962
         if ($name == 'id') {
             $name = 'contact_id';
         }
         // skip fields that should not be displayed separately
         if (!empty($field['skipDisplay'])) {
             continue;
         }
         // Create a unique, non-empty index for each field.
         $index = $field['title'];
         if ($index === '') {
             $index = ' ';
         }
         while (array_key_exists($index, $values)) {
             $index .= ' ';
         }
         $params[$index] = $values[$index] = '';
         $customFieldName = NULL;
         // hack for CRM-665
         if (isset($details->{$name}) || $name == 'group' || $name == 'tag') {
             // to handle gender / suffix / prefix
             if (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix'))) {
                 $params[$index] = $details->{$name};
                 $values[$index] = $details->{$name};
             } elseif (in_array($name, CRM_Contact_BAO_Contact::$_greetingTypes)) {
                 $dname = $name . '_display';
                 $values[$index] = $details->{$dname};
                 $name = $name . '_id';
                 $params[$index] = $details->{$name};
             } elseif (in_array($name, array('state_province', 'country', 'county'))) {
                 $values[$index] = $details->{$name};
                 $idx = $name . '_id';
                 $params[$index] = $details->{$idx};
             } elseif ($name === 'preferred_communication_method') {
                 $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
                 $compref = array();
                 $pref = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name});
                 foreach ($pref as $k) {
                     if ($k) {
                         $compref[] = $communicationFields[$k];
                     }
                 }
                 $params[$index] = $details->{$name};
                 $values[$index] = implode(',', $compref);
             } elseif ($name === 'preferred_language') {
                 $params[$index] = $details->{$name};
                 $values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $details->{$name});
             } elseif ($name == 'group') {
                 $groups = CRM_Contact_BAO_GroupContact::getContactGroup($cid, 'Added', NULL, FALSE, TRUE);
                 $title = $ids = array();
                 foreach ($groups as $g) {
                     // CRM-8362: User and User Admin visibility groups should be included in display if user has
                     // VIEW permission on that group
                     $groupPerm = CRM_Contact_BAO_Group::checkPermission($g['group_id'], $g['title']);
                     if ($g['visibility'] != 'User and User Admin Only' || CRM_Utils_Array::key(CRM_Core_Permission::VIEW, $groupPerm)) {
                         $title[] = $g['title'];
                         if ($g['visibility'] == 'Public Pages') {
                             $ids[] = $g['group_id'];
                         }
                     }
                 }
                 $values[$index] = implode(', ', $title);
                 $params[$index] = implode(',', $ids);
             } elseif ($name == 'tag') {
                 $entityTags = CRM_Core_BAO_EntityTag::getTag($cid);
                 $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
                 $title = array();
                 foreach ($entityTags as $tagId) {
                     $title[] = $allTags[$tagId];
                 }
                 $values[$index] = implode(', ', $title);
                 $params[$index] = implode(',', $entityTags);
             } elseif ($name == 'activity_status_id') {
                 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
                 $values[$index] = $activityStatus[$details->{$name}];
                 $params[$index] = $details->{$name};
             } elseif ($name == 'activity_date_time') {
                 $values[$index] = CRM_Utils_Date::customFormat($details->{$name});
                 $params[$index] = $details->{$name};
             } elseif ($name == 'contact_sub_type') {
                 $contactSubTypeNames = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name});
                 if (!empty($contactSubTypeNames)) {
                     $contactSubTypeLabels = array();
                     // get all contact subtypes
                     $allContactSubTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
                     // build contact subtype labels array
                     foreach ($contactSubTypeNames as $cstName) {
                         if ($cstName) {
                             $contactSubTypeLabels[] = $allContactSubTypes[$cstName]['label'];
                         }
                     }
                     $values[$index] = implode(',', $contactSubTypeLabels);
                 }
                 $params[$index] = $details->{$name};
             } else {
                 if (substr($name, 0, 7) === 'do_not_' || substr($name, 0, 3) === 'is_') {
                     if ($details->{$name}) {
                         $values[$index] = '[ x ]';
                     }
                 } else {
                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                         $htmlType = $field['html_type'];
                         // field_type is only set when we are retrieving profile values
                         // when sending email, we call the same function to get custom field
                         // values etc, i.e. emulating a profile
                         $fieldType = CRM_Utils_Array::value('field_type', $field);
                         if ($htmlType == 'File') {
                             $entityId = $cid;
                             if (!$cid && $fieldType == 'Activity' && !empty($componentWhere[0][2])) {
                                 $entityId = $componentWhere[0][2];
                             }
                             $fileURL = CRM_Core_BAO_CustomField::getFileURL($entityId, $cfID, NULL, $absolute, $additionalWhereClause);
                             $params[$index] = $values[$index] = $fileURL['file_url'];
                         } else {
                             $customVal = NULL;
                             if (isset($dao) && property_exists($dao, 'data_type') && ($dao->data_type == 'Int' || $dao->data_type == 'Boolean')) {
                                 $customVal = (int) $details->{$name};
                             } elseif (isset($dao) && property_exists($dao, 'data_type') && $dao->data_type == 'Float') {
                                 $customVal = (double) $details->{$name};
                             } elseif (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name}))) {
                                 $customVal = $details->{$name};
                             }
                             //CRM-4582
                             if (CRM_Utils_System::isNull($customVal)) {
                                 continue;
                             }
                             $params[$index] = $customVal;
                             $values[$index] = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
                             if ($field['data_type'] == 'ContactReference') {
                                 $params[$index] = $values[$index];
                             }
                             if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) {
                                 $customFieldName = "{$name}_from";
                             }
                         }
                     } elseif ($name == 'image_URL') {
                         list($width, $height) = getimagesize(CRM_Utils_String::unstupifyUrl($details->{$name}));
                         list($thumbWidth, $thumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($width, $height);
                         $image_URL = '<img src="' . $details->{$name} . '" height= ' . $thumbHeight . ' width= ' . $thumbWidth . '  />';
                         $values[$index] = "<a href='#' onclick='contactImagePopUp(\"{$details->{$name}}\", {$width}, {$height});'>{$image_URL}</a>";
                     } elseif (in_array($name, array('birth_date', 'deceased_date', 'membership_start_date', 'membership_end_date', 'join_date'))) {
                         $values[$index] = CRM_Utils_Date::customFormat($details->{$name});
                         $params[$index] = CRM_Utils_Date::isoToMysql($details->{$name});
                     } else {
                         $dao = '';
                         if ($index == 'Campaign') {
                             $dao = 'CRM_Campaign_DAO_Campaign';
                         } elseif ($index == 'Contribution Page') {
                             $dao = 'CRM_Contribute_DAO_ContributionPage';
                         }
                         if ($dao) {
                             $value = CRM_Core_DAO::getFieldValue($dao, $details->{$name}, 'title');
                         } else {
                             $value = $details->{$name};
                         }
                         $values[$index] = $value;
                     }
                 }
             }
         } elseif (strpos($name, '-') !== FALSE) {
             list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $name, 3);
             if (!in_array($fieldName, $multipleFields)) {
                 if ($id == 'Primary') {
                     // fix for CRM-1543
                     // not sure why we'd every use Primary location type id
                     // we need to fix the source if we are using it
                     // $locationTypeName = CRM_Contact_BAO_Contact::getPrimaryLocationType( $cid );
                     $locationTypeName = 1;
                 } else {
                     $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
                 }
                 if (!$locationTypeName) {
                     continue;
                 }
                 $detailName = "{$locationTypeName}-{$fieldName}";
                 $detailName = str_replace(' ', '_', $detailName);
                 if (in_array($fieldName, array('phone', 'im', 'email', 'openid'))) {
                     if ($type) {
                         $detailName .= "-{$type}";
                     }
                 }
                 if (in_array($fieldName, array('state_province', 'country', 'county'))) {
                     $values[$index] = $details->{$detailName};
                     $idx = $detailName . '_id';
                     $params[$index] = $details->{$idx};
                 } elseif ($fieldName == 'im') {
                     $providerId = $detailName . '-provider_id';
                     if (isset($imProviders[$details->{$providerId}])) {
                         $values[$index] = $details->{$detailName} . " (" . $imProviders[$details->{$providerId}] . ")";
                     } else {
                         $values[$index] = $details->{$detailName};
                     }
                     $params[$index] = $details->{$detailName};
                 } elseif ($fieldName == 'phone') {
                     $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
                     if (isset($details->{$phoneExtField})) {
                         $values[$index] = $details->{$detailName} . " (" . $details->{$phoneExtField} . ")";
                     } else {
                         $values[$index] = $details->{$detailName};
                     }
                     $params[$index] = $details->{$detailName};
                 } else {
                     $values[$index] = $params[$index] = $details->{$detailName};
                 }
             } else {
                 $detailName = "website-{$id}-{$fieldName}";
                 $url = CRM_Utils_System::fixURL($details->{$detailName});
                 if ($details->{$detailName}) {
                     $websiteTypeId = "website-{$id}-website_type_id";
                     $websiteType = $websiteTypes[$details->{$websiteTypeId}];
                     $values[$index] = "<a href=\"{$url}\">{$details->{$detailName}} ( {$websiteType} )</a>";
                 } else {
                     $values[$index] = '';
                 }
             }
         }
         if (CRM_Utils_Array::value('visibility', $field) == 'Public Pages and Listings' && CRM_Core_Permission::check('profile listings and forms')) {
             if (CRM_Utils_System::isNull($params[$index])) {
                 $params[$index] = $values[$index];
             }
             if (!isset($params[$index])) {
                 continue;
             }
             if (!$customFieldName) {
                 $fieldName = $field['name'];
             } else {
                 $fieldName = $customFieldName;
             }
             $url = NULL;
             if (CRM_Core_BAO_CustomField::getKeyID($field['name'])) {
                 $htmlType = $field['html_type'];
                 if ($htmlType == 'Link') {
                     $url = $params[$index];
                 } elseif (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Multi-Select State/Province', 'Multi-Select Country'))) {
                     $valSeperator = CRM_Core_DAO::VALUE_SEPARATOR;
                     $selectedOptions = explode($valSeperator, $params[$index]);
                     foreach ($selectedOptions as $key => $multiOption) {
                         if ($multiOption) {
                             $url[] = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($multiOption));
                         }
                     }
                 } else {
                     $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index]));
                 }
             } else {
                 $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index]));
             }
             if ($url && !empty($values[$index]) && $searchable) {
                 if (is_array($url) && !empty($url)) {
                     $links = array();
                     $eachMultiValue = explode(', ', $values[$index]);
                     foreach ($eachMultiValue as $key => $valueLabel) {
                         $links[] = '<a href="' . $url[$key] . '">' . $valueLabel . '</a>';
                     }
                     $values[$index] = implode(', ', $links);
                 } else {
                     $values[$index] = '<a href="' . $url . '">' . $values[$index] . '</a>';
                 }
             }
         }
     }
 }
 /**
  * Browse the listing.
  *
  * @return void
  */
 public function browse()
 {
     $dateFields = NULL;
     $cgcount = 0;
     $attributes = array();
     $dateFieldsVals = NULL;
     if ($this->_pageViewType == 'profileDataView' && $this->_profileId) {
         $fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, NULL, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::EDIT);
         $multiRecordFields = array();
         $fieldIDs = NULL;
         $result = NULL;
         $multiRecordFieldsWithSummaryListing = CRM_Core_BAO_UFGroup::shiftMultiRecordFields($fields, $multiRecordFields, TRUE);
         $multiFieldId = CRM_Core_BAO_CustomField::getKeyID(key($multiRecordFields));
         $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $multiFieldId, 'custom_group_id');
         $reached = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupId, $this->_contactId);
         if (!$reached) {
             $this->assign('contactId', $this->_contactId);
             $this->assign('gid', $this->_profileId);
         }
         $this->assign('reachedMax', $reached);
         if ($multiRecordFieldsWithSummaryListing && !empty($multiRecordFieldsWithSummaryListing)) {
             $fieldIDs = array_keys($multiRecordFieldsWithSummaryListing);
         }
     } elseif ($this->_pageViewType == 'customDataView') {
         // require custom group id for _pageViewType of customDataView
         $customGroupId = $this->_customGroupId;
         $reached = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupId, $this->_contactId);
         if (!$reached) {
             $this->assign('contactId', $this->_contactId);
             $this->assign('customGroupId', $customGroupId);
             $this->assign('ctype', $this->_contactType);
         }
         $this->assign('reachedMax', $reached);
         // custom group info : this consists of the field title of group fields
         $groupDetail = CRM_Core_BAO_CustomGroup::getGroupDetail($customGroupId, NULL, CRM_Core_DAO::$_nullObject, TRUE);
         // field ids of fields in_selector for the custom group id provided
         $fieldIDs = array_keys($groupDetail[$customGroupId]['fields']);
         // field labels for headers
         $fieldLabels = $groupDetail[$customGroupId]['fields'];
         // from the above customGroupInfo we can get $this->_customGroupTitle
         $this->_customGroupTitle = $groupDetail[$customGroupId]['title'];
     }
     if ($fieldIDs && !empty($fieldIDs) && $this->_contactId) {
         $options = array();
         $returnProperities = array('html_type', 'data_type', 'date_format', 'time_format', 'default_value', 'is_required');
         foreach ($fieldIDs as $key => $fieldID) {
             $fieldIDs[$key] = !is_numeric($fieldID) ? CRM_Core_BAO_CustomField::getKeyID($fieldID) : $fieldID;
             $param = array('id' => $fieldIDs[$key]);
             $returnValues = array();
             CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $param, $returnValues, $returnProperities);
             if ($returnValues['data_type'] == 'Date') {
                 $dateFields[$fieldIDs[$key]] = 1;
                 $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats();
                 $dateFormat = (array) CRM_Utils_Array::value($returnValues['date_format'], $actualPHPFormats);
                 $timeFormat = CRM_Utils_Array::value('time_format', $returnValues);
             }
             $optionValuePairs = CRM_Core_BAO_CustomOption::getCustomOption($fieldIDs[$key]);
             if (!empty($optionValuePairs)) {
                 foreach ($optionValuePairs as $optionPairs) {
                     $options[$fieldIDs[$key]][$optionPairs['value']] = $optionPairs['label'];
                 }
             }
             $options[$fieldIDs[$key]]['attributes']['html_type'] = $returnValues['html_type'];
             $options[$fieldIDs[$key]]['attributes']['data_type'] = $returnValues['data_type'];
             $options[$fieldIDs[$key]]['attributes']['is_required'] = !empty($returnValues['is_required']);
             $options[$fieldIDs[$key]]['attributes']['default_value'] = CRM_Utils_Array::value('default_value', $returnValues);
             $options[$fieldIDs[$key]]['attributes']['format'] = $options[$fieldIDs[$key]]['attributes']['date_format'] = CRM_Utils_Array::value('date_format', $returnValues);
             $options[$fieldIDs[$key]]['attributes']['time_format'] = CRM_Utils_Array::value('time_format', $returnValues);
         }
         // commonly used for both views i.e profile listing view (profileDataView) and custom data listing view (customDataView)
         $result = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_contactId, NULL, $fieldIDs, TRUE);
         if ($this->_pageViewType == 'profileDataView') {
             if (!empty($fieldIDs)) {
                 //get the group info of multi rec fields in listing view
                 $fieldInput = $fieldIDs;
                 $fieldIdInput = $fieldIDs[0];
             } else {
                 //if no listing fields exist, take the group title for display
                 $nonListingFieldIds = array_keys($multiRecordFields);
                 $singleField = CRM_Core_BAO_CustomField::getKeyID($nonListingFieldIds[0]);
                 $fieldIdInput = $singleField;
                 $singleField = array($singleField);
                 $fieldInput = $singleField;
             }
             $customGroupInfo = CRM_Core_BAO_CustomGroup::getGroupTitles($fieldInput);
             $this->_customGroupTitle = $customGroupInfo[$fieldIdInput]['groupTitle'];
         }
         // $cgcount is defined before 'if' condition as enitiy may have no record
         // and $cgcount is used to build new record url
         $cgcount = 1;
         if ($result && !empty($result)) {
             $links = self::links();
             if ($this->_pageViewType == 'profileDataView') {
                 $pageCheckSum = $this->get('pageCheckSum');
                 if ($pageCheckSum) {
                     foreach ($links as $key => $link) {
                         $links[$key] = $link['qs'] . "&cs=%%cs%%";
                     }
                 }
             }
             $linkAction = array_sum(array_keys($this->links()));
             if ($reached) {
                 unset($links[CRM_Core_Action::COPY]);
             }
             $newCgCount = !$reached ? count($result) + 1 : NULL;
             foreach ($result as $recId => &$value) {
                 foreach ($value as $fieldId => &$val) {
                     if (is_numeric($fieldId)) {
                         $customValue =& $val;
                         if (!empty($dateFields) && array_key_exists($fieldId, $dateFields)) {
                             // formated date capture value capture
                             $dateFieldsVals[$fieldId][$recId] = CRM_Core_BAO_CustomField::getDisplayValue($customValue, $fieldId, $options);
                             //set date and time format
                             switch ($timeFormat) {
                                 case 1:
                                     $dateFormat[1] = 'g:iA';
                                     break;
                                 case 2:
                                     $dateFormat[1] = 'G:i';
                                     break;
                                 default:
                                     // if time is not selected remove time from value
                                     $result[$recId][$fieldId] = substr($result[$recId][$fieldId], 0, 10);
                             }
                             $result[$recId][$fieldId] = CRM_Utils_Date::processDate($result[$recId][$fieldId], NULL, FALSE, implode(" ", $dateFormat));
                         } else {
                             // assign to $result
                             $customValue = CRM_Core_BAO_CustomField::getDisplayValue($customValue, $fieldId, $options);
                         }
                         // FIXME: getDisplayValue should always return a string so why is this necessary?
                         if (!$customValue && $customValue !== '0') {
                             $customValue = "";
                         }
                         // Set field attributes to support crmEditable
                         // Note that $fieldAttributes[data-type] actually refers to the html type not the sql data type
                         // TODO: Not all widget types and validation rules are supported by crmEditable so some fields will not be in-place editable
                         $fieldAttributes = array('class' => "crmf-custom_{$fieldId}_{$recId}");
                         $editable = FALSE;
                         if ($linkAction & CRM_Core_Action::UPDATE) {
                             $spec = $options[$fieldId]['attributes'];
                             switch ($spec['html_type']) {
                                 case 'Text':
                                     // Other data types like money would require some extra validation
                                     // FIXME: crmEditable currently does not support any validation rules :(
                                     $supportedDataTypes = array('Float', 'String', 'Int');
                                     $editable = in_array($spec['data_type'], $supportedDataTypes);
                                     break;
                                 case 'TextArea':
                                     $editable = TRUE;
                                     $fieldAttributes['data-type'] = 'textarea';
                                     break;
                                 case 'Radio':
                                 case 'Select':
                                 case 'Select Country':
                                 case 'Select State/Province':
                                     $editable = TRUE;
                                     $fieldAttributes['data-type'] = $spec['data_type'] == 'Boolean' ? 'boolean' : 'select';
                                     if (!$spec['is_required']) {
                                         $fieldAttributes['data-empty-option'] = ts('- none -');
                                     }
                                     break;
                             }
                         }
                         if ($editable) {
                             $fieldAttributes['class'] .= ' crm-editable';
                         }
                         $attributes[$fieldId][$recId] = $fieldAttributes;
                         $op = NULL;
                         if ($this->_pageViewType == 'profileDataView') {
                             $actionParams = array('recordId' => $recId, 'gid' => $this->_profileId, 'id' => $this->_contactId);
                             $op = 'profile.multiValue.row';
                         } else {
                             // different set of url params
                             $actionParams['gid'] = $actionParams['groupID'] = $this->_customGroupId;
                             $actionParams['cid'] = $actionParams['entityID'] = $this->_contactId;
                             $actionParams['recId'] = $recId;
                             $actionParams['type'] = $this->_contactType;
                             $actionParams['cgcount'] = $cgcount;
                             $actionParams['newCgCount'] = $newCgCount;
                             // DELETE action links
                             $deleteData = array('valueID' => $recId, 'groupID' => $this->_customGroupId, 'contactId' => $this->_contactId, 'key' => CRM_Core_Key::get('civicrm/ajax/customvalue'));
                             $links[CRM_Core_Action::DELETE]['url'] = '#';
                             $links[CRM_Core_Action::DELETE]['extra'] = ' data-delete_params="' . htmlspecialchars(json_encode($deleteData)) . '"';
                             $links[CRM_Core_Action::DELETE]['class'] = 'delete-custom-row';
                         }
                         if (!empty($pageCheckSum)) {
                             $actionParams['cs'] = $pageCheckSum;
                         }
                         $value['action'] = CRM_Core_Action::formLink($links, $linkAction, $actionParams, ts('more'), FALSE, $op, 'customValue', $fieldId);
                     }
                 }
                 $cgcount++;
             }
         }
     }
     $headers = array();
     if (!empty($fieldIDs)) {
         foreach ($fieldIDs as $fieldID) {
             $headers[$fieldID] = $this->_pageViewType == 'profileDataView' ? $customGroupInfo[$fieldID]['fieldLabel'] : $fieldLabels[$fieldID]['label'];
         }
     }
     $this->assign('dateFields', $dateFields);
     $this->assign('dateFieldsVals', $dateFieldsVals);
     $this->assign('cgcount', $cgcount);
     $this->assign('customGroupTitle', $this->_customGroupTitle);
     $this->assign('headers', $headers);
     $this->assign('records', $result);
     $this->assign('attributes', $attributes);
 }
 /**
  * generate the where clause and also the english language
  * equivalent
  *
  * @param NULL
  *
  * @return void
  *
  * @access public
  */
 function where()
 {
     foreach ($this->_ids as $id => $values) {
         // Fixed for Isuue CRM 607
         if (CRM_Utils_Array::value($id, $this->_fields) === NULL || !$values) {
             continue;
         }
         $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
         foreach ($values as $tuple) {
             list($name, $op, $value, $grouping, $wildcard) = $tuple;
             $field = $this->_fields[$id];
             $fieldName = "{$field['table_name']}.{$field['column_name']}";
             // Autocomplete comes back as a string not an array
             if ($field['data_type'] == 'String' && $field['html_type'] == 'Autocomplete-Select' && $op == '=') {
                 $value = explode(',', $value);
             }
             // Handle multi-select search for any data type
             if (is_array($value) && !$field['is_search_range']) {
                 $isSerialized = CRM_Core_BAO_CustomField::isSerialized($field);
                 $wildcard = $isSerialized ? $wildcard : TRUE;
                 $options = CRM_Utils_Array::value('values', civicrm_api3('contact', 'getoptions', array('field' => $name, 'context' => 'search'), array()));
                 $qillValue = '';
                 $sqlOP = $wildcard ? ' OR ' : ' AND ';
                 $sqlValue = array();
                 foreach ($value as $num => &$v) {
                     $sep = count($value) > 1 + $num ? ', ' : ' ' . ($wildcard ? ts('OR') : ts('AND')) . ' ';
                     $qillValue .= ($num ? $sep : '') . $options[$v];
                     $v = CRM_Core_DAO::escapeString($v);
                     if ($isSerialized) {
                         $sqlValue[] = "( {$fieldName} like '%" . CRM_Core_DAO::VALUE_SEPARATOR . $v . CRM_Core_DAO::VALUE_SEPARATOR . "%' ) ";
                     } else {
                         $v = "'{$v}'";
                     }
                 }
                 if (!$isSerialized) {
                     $sqlValue = array("{$fieldName} IN (" . implode(',', $value) . ")");
                 }
                 $this->_where[$grouping][] = ' ( ' . implode($sqlOP, $sqlValue) . ' ) ';
                 $this->_qill[$grouping][] = "{$field['label']} {$op} {$qillValue}";
                 continue;
             }
             // fix $value here to escape sql injection attacks
             if (!is_array($value)) {
                 $value = CRM_Core_DAO::escapeString(trim($value));
             }
             $qillValue = CRM_Core_BAO_CustomField::getDisplayValue($value, $id, $this->_options);
             switch ($field['data_type']) {
                 case 'String':
                     $sql = "{$fieldName}";
                     if ($field['is_search_range'] && is_array($value)) {
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         $val = CRM_Utils_Type::escape($strtolower(trim($value)), 'String');
                         if ($wildcard) {
                             $val = $strtolower(CRM_Core_DAO::escapeString($val));
                             $val = "%{$val}%";
                             $op = 'LIKE';
                         }
                         //FIX for custom data query fired against no value(NULL/NOT NULL)
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($sql, $op, $val, $field['data_type']);
                         $this->_qill[$grouping][] = "{$field['label']} {$op} {$qillValue}";
                     }
                     break;
                 case 'ContactReference':
                     $label = $value ? CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $value, 'sort_name') : '';
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
                     $this->_qill[$grouping][] = $field['label'] . " {$op} {$label}";
                     break;
                 case 'Int':
                     if ($field['is_search_range'] && is_array($value)) {
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
                         $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}";
                     }
                     break;
                 case 'Boolean':
                     if (strtolower($value) == 'yes' || strtolower($value) == strtolower(ts('Yes'))) {
                         $value = 1;
                     } else {
                         $value = (int) $value;
                     }
                     $value = $value == 1 ? 1 : 0;
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Integer');
                     $value = $value ? ts('Yes') : ts('No');
                     $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}";
                     break;
                 case 'Link':
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
                     $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}";
                     break;
                 case 'Float':
                     if ($field['is_search_range'] && is_array($value)) {
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Float');
                         $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}";
                     }
                     break;
                 case 'Money':
                     if ($field['is_search_range'] && is_array($value)) {
                         foreach ($value as $key => $val) {
                             $moneyFormat = CRM_Utils_Rule::cleanMoney($value[$key]);
                             $value[$key] = $moneyFormat;
                         }
                         $this->searchRange($field['id'], $field['label'], $field['data_type'], $fieldName, $value, $grouping);
                     } else {
                         $moneyFormat = CRM_Utils_Rule::cleanMoney($value);
                         $value = $moneyFormat;
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'Float');
                         $this->_qill[$grouping][] = $field['label'] . " {$op} {$value}";
                     }
                     break;
                 case 'Memo':
                     $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $value, 'String');
                     $this->_qill[$grouping][] = "{$field['label']} {$op} {$value}";
                     break;
                 case 'Date':
                     $fromValue = CRM_Utils_Array::value('from', $value);
                     $toValue = CRM_Utils_Array::value('to', $value);
                     if (!$fromValue && !$toValue) {
                         if (!CRM_Utils_Date::processDate($value) && $op != 'IS NULL' && $op != 'IS NOT NULL') {
                             continue;
                         }
                         // hack to handle yy format during search
                         if (is_numeric($value) && strlen($value) == 4) {
                             $value = "01-01-{$value}";
                         }
                         $date = CRM_Utils_Date::processDate($value);
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op, $date, 'String');
                         $this->_qill[$grouping][] = $field['label'] . " {$op} " . CRM_Utils_Date::customFormat($date);
                     } else {
                         if (is_numeric($fromValue) && strlen($fromValue) == 4) {
                             $fromValue = "01-01-{$fromValue}";
                         }
                         if (is_numeric($toValue) && strlen($toValue) == 4) {
                             $toValue = "01-01-{$toValue}";
                         }
                         // TO DO: add / remove time based on date parts
                         $fromDate = CRM_Utils_Date::processDate($fromValue);
                         $toDate = CRM_Utils_Date::processDate($toValue);
                         if (!$fromDate && !$toDate) {
                             continue;
                         }
                         if ($fromDate) {
                             $this->_where[$grouping][] = "{$fieldName} >= {$fromDate}";
                             $this->_qill[$grouping][] = $field['label'] . ' >= ' . CRM_Utils_Date::customFormat($fromDate);
                         }
                         if ($toDate) {
                             $this->_where[$grouping][] = "{$fieldName} <= {$toDate}";
                             $this->_qill[$grouping][] = $field['label'] . ' <= ' . CRM_Utils_Date::customFormat($toDate);
                         }
                     }
                     break;
                 case 'StateProvince':
                 case 'Country':
                     $this->_where[$grouping][] = "{$fieldName} {$op} " . CRM_Utils_Type::escape($value, 'Int');
                     $this->_qill[$grouping][] = $field['label'] . " {$op} {$qillValue}";
                     break;
                 case 'File':
                     if ($op == 'IS NULL' || $op == 'IS NOT NULL' || $op == 'IS EMPTY' || $op == 'IS NOT EMPTY') {
                         switch ($op) {
                             case 'IS EMPTY':
                                 $op = 'IS NULL';
                                 break;
                             case 'IS NOT EMPTY':
                                 $op = 'IS NOT NULL';
                                 break;
                         }
                         $this->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause($fieldName, $op);
                         $this->_qill[$grouping][] = $field['label'] . " {$op} ";
                     }
                     break;
             }
         }
     }
 }
Example #24
0
 /**
  * Given a contact id and a field set, return the values from the db
  * for this contact
  *
  * @param int     $id       the contact id
  * @param array   $fields   the profile fields of interest
  * @param array   $values   the values for the above fields
  * @return void
  * @access public
  * @static
  */
 function getValues($cid, &$fields, &$values)
 {
     $options = array();
     // get the contact details (hier)
     $returnProperties =& CRM_Contact_BAO_Contact::makeHierReturnProperties($fields);
     $params = array('id' => $cid);
     $query =& new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
     $options =& $query->_options;
     $details = $query->searchQuery();
     if (!$details->fetch()) {
         return;
     }
     require_once 'CRM/Core/PseudoConstant.php';
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     //start of code to set the default values
     foreach ($fields as $name => $field) {
         $index = $field['title'];
         $params[$index] = $values[$index] = '';
         if ($details->{$name} || $name == 'group' || $name == 'tag') {
             //hack for CRM-665
             //to handle custom data (checkbox) to be written
             // to handle gender / suffix / prefix
             if (in_array($name, array('gender', 'individual_prefix', 'individual_suffix'))) {
                 $values[$index] = $details->{$name};
                 $name = $name . '_id';
                 $params[$index] = $details->{$name};
             } else {
                 if (in_array($name, array('state_province', 'country'))) {
                     $values[$index] = $details->{$name};
                     $idx = $name . '_id';
                     $params[$index] = $details->{$idx};
                 } else {
                     if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
                         if ($details->{$name}) {
                             $values[$index] = '[ x ]';
                         }
                     } else {
                         if ($name == 'group') {
                             $groups = CRM_Contact_BAO_GroupContact::getContactGroup($cid, 'Added', null, false, true);
                             $title = array();
                             $ids = array();
                             foreach ($groups as $g) {
                                 if ($g['visibility'] != 'User and User Admin Only') {
                                     $title[] = $g['title'];
                                     if ($g['visibility'] == 'Public User Pages and Listings') {
                                         $ids[] = $g['group_id'];
                                     }
                                 }
                             }
                             $values[$index] = implode(', ', $title);
                             $params[$index] = implode(',', $ids);
                         } else {
                             if ($name == 'tag') {
                                 require_once 'CRM/Core/BAO/EntityTag.php';
                                 $entityTags =& CRM_Core_BAO_EntityTag::getTag('civicrm_contact', $cid);
                                 $allTags =& CRM_Core_PseudoConstant::tag();
                                 $title = array();
                                 foreach ($entityTags as $tagId) {
                                     $title[] = $allTags[$tagId];
                                 }
                                 $values[$index] = implode(', ', $title);
                                 $params[$index] = implode(',', $entityTags);
                             } else {
                                 require_once 'CRM/Core/BAO/CustomField.php';
                                 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                                     $params[$index] = $details->{$name};
                                     $values[$index] = CRM_Core_BAO_CustomField::getDisplayValue($details->{$name}, $cfID, $options);
                                 } else {
                                     $values[$index] = $details->{$name};
                                 }
                             }
                         }
                     }
                 }
             }
         } else {
             if (strpos($name, '-') !== false) {
                 list($fieldName, $id, $type) = explode('-', $name);
                 $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
                 if (!$locationTypeName) {
                     continue;
                 }
                 $detailName = "{$locationTypeName}-{$fieldName}";
                 if (in_array($fieldName, array('phone', 'im', 'email'))) {
                     if ($type) {
                         $detailName .= "-{$type}";
                     } else {
                         $detailName .= '-1';
                     }
                 }
                 if (in_array($fieldName, array('state_province', 'country'))) {
                     $values[$index] = $details->{$detailName};
                     $idx = $detailName . '_id';
                     $params[$index] = $details->{$idx};
                 } else {
                     $values[$index] = $params[$index] = $details->{$detailName};
                 }
             }
         }
         if ($field['visibility'] == "Public User Pages and Listings" && CRM_Utils_System::checkPermission('profile listings and forms')) {
             if (CRM_Utils_System::isNull($params[$index])) {
                 $params[$index] = $values[$index];
             }
             if (empty($params[$index])) {
                 continue;
             }
             $fieldName = $field['name'];
             $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index]));
             if (!empty($values[$index])) {
                 $values[$index] = '<a href="' . $url . '">' . $values[$index] . '</a>';
             }
         }
     }
 }
Example #25
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     $fv = $this->controller->exportValues($this->_name);
     $config = CRM_Core_Config::singleton();
     $locName = NULL;
     //get the address format sequence from the config file
     $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);
 }
Example #26
0
 /**
  * Given a contact id and a field set, return the values from the db
  * for this contact
  *
  * @param int     $id             the contact id
  * @param array   $fields         the profile fields of interest
  * @param array   $values         the values for the above fields
  * @param boolean $searchable     searchable or not
  * @param array   $componentWhere component condition
  *
  * @return void
  * @access public
  * @static
  */
 public static function getValues($cid, &$fields, &$values, $searchable = true, $componentWhere = null)
 {
     if (empty($cid)) {
         return null;
     }
     $options = array();
     $studentFields = array();
     if (CRM_Core_Permission::access('Quest', false)) {
         //student fields ( check box )
         require_once 'CRM/Quest/BAO/Student.php';
         $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields;
     }
     // get the contact details (hier)
     $returnProperties =& CRM_Contact_BAO_Contact::makeHierReturnProperties($fields);
     $params = array(array('contact_id', '=', $cid, 0, 0));
     // add conditions specified by components. eg partcipant_id etc
     if (!empty($componentWhere)) {
         $params = array_merge($params, $componentWhere);
     }
     $query =& new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
     $options =& $query->_options;
     $details = $query->searchQuery();
     if (!$details->fetch()) {
         return;
     }
     $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) {
         // fix for CRM-3962
         if ($name == 'id') {
             $name = 'contact_id';
         }
         $index = $field['title'];
         $params[$index] = $values[$index] = '';
         $customFieldName = null;
         $elements = array('email_greeting_custom' => 'email_greeting', 'postal_greeting_custom' => 'postal_greeting', 'addressee_custom' => 'addressee');
         if (isset($details->{$name}) || $name == 'group' || $name == 'tag') {
             //hack for CRM-665
             // to handle gender / suffix / prefix
             if (in_array($name, array('gender', 'individual_prefix', 'individual_suffix'))) {
                 $values[$index] = $details->{$name};
                 $name = $name . '_id';
                 $params[$index] = $details->{$name};
             } else {
                 if (in_array($name, array('email_greeting', 'postal_greeting', 'addressee'))) {
                     $dname = $name . '_display';
                     $values[$index] = $details->{$dname};
                     $name = $name . '_id';
                     $params[$index] = $details->{$name};
                 } else {
                     if (in_array($name, array('state_province', 'country', 'county'))) {
                         $values[$index] = $details->{$name};
                         $idx = $name . '_id';
                         $params[$index] = $details->{$idx};
                     } else {
                         if ($name === 'preferred_communication_method') {
                             $communicationFields = CRM_Core_PseudoConstant::pcm();
                             $pref = array();
                             $compref = array();
                             $pref = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $details->{$name});
                             foreach ($pref as $k) {
                                 if ($k) {
                                     $compref[] = $communicationFields[$k];
                                 }
                             }
                             $params[$index] = $details->{$name};
                             $values[$index] = implode(",", $compref);
                         } else {
                             if ($name == 'group') {
                                 $groups = CRM_Contact_BAO_GroupContact::getContactGroup($cid, 'Added', null, false, true);
                                 $title = array();
                                 $ids = array();
                                 foreach ($groups as $g) {
                                     if ($g['visibility'] != 'User and User Admin Only') {
                                         $title[] = $g['title'];
                                         if ($g['visibility'] == 'Public Pages') {
                                             $ids[] = $g['group_id'];
                                         }
                                     }
                                 }
                                 $values[$index] = implode(', ', $title);
                                 $params[$index] = implode(',', $ids);
                             } else {
                                 if ($name == 'tag') {
                                     require_once 'CRM/Core/BAO/EntityTag.php';
                                     $entityTags =& CRM_Core_BAO_EntityTag::getTag($cid);
                                     $allTags =& CRM_Core_PseudoConstant::tag();
                                     $title = array();
                                     foreach ($entityTags as $tagId) {
                                         $title[] = $allTags[$tagId];
                                     }
                                     $values[$index] = implode(', ', $title);
                                     $params[$index] = implode(',', $entityTags);
                                 } else {
                                     if (array_key_exists($name, $studentFields)) {
                                         require_once 'CRM/Core/OptionGroup.php';
                                         $paramsNew = array($name => $details->{$name});
                                         if ($name == 'test_tutoring') {
                                             $names = array($name => array('newName' => $index, 'groupName' => 'test'));
                                         } else {
                                             if (substr($name, 0, 4) == 'cmr_') {
                                                 //for  readers group
                                                 $names = array($name => array('newName' => $index, 'groupName' => substr($name, 0, -3)));
                                             } else {
                                                 $names = array($name => array('newName' => $index, 'groupName' => $name));
                                             }
                                         }
                                         CRM_Core_OptionGroup::lookupValues($paramsNew, $names, false);
                                         $values[$index] = $paramsNew[$index];
                                         $params[$index] = $paramsNew[$name];
                                     } else {
                                         $processed = false;
                                         if (CRM_Core_Permission::access('Quest', false)) {
                                             require_once 'CRM/Quest/BAO/Student.php';
                                             $processed = CRM_Quest_BAO_Student::buildStudentForm($this, $field);
                                         }
                                         if (!$processed) {
                                             if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
                                                 if ($details->{$name}) {
                                                     $values[$index] = '[ x ]';
                                                 }
                                             } else {
                                                 require_once 'CRM/Core/BAO/CustomField.php';
                                                 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                                                     $htmlType = $field['html_type'];
                                                     $dataType = $field['data_type'];
                                                     if ($htmlType == 'File') {
                                                         $fileURL = CRM_Core_BAO_CustomField::getFileURL($cid, $cfID);
                                                         $params[$index] = $values[$index] = $fileURL['file_url'];
                                                     } else {
                                                         $customVal = null;
                                                         if (isset($dao) && ($dao->data_type == 'Int' || $dao->data_type == 'Boolean')) {
                                                             $customVal = (int) $details->{$name};
                                                         } else {
                                                             if (isset($dao) && $dao->data_type == 'Float') {
                                                                 $customVal = (double) $details->{$name};
                                                             } else {
                                                                 if (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name}))) {
                                                                     $customVal = $details->{$name};
                                                                 }
                                                             }
                                                         }
                                                         //CRM-4582
                                                         if (CRM_Utils_System::isNull($customVal)) {
                                                             continue;
                                                         }
                                                         $params[$index] = $customVal;
                                                         $values[$index] = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
                                                         if ($htmlType == 'Autocomplete-Select') {
                                                             $params[$index] = $values[$index];
                                                         }
                                                         if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) {
                                                             $customFieldName = "{$name}_from";
                                                         }
                                                     }
                                                 } else {
                                                     if ($name == 'home_URL' && !empty($details->{$name})) {
                                                         $url = CRM_Utils_System::fixURL($details->{$name});
                                                         $values[$index] = "<a href=\"{$url}\">{$details->{$name}}</a>";
                                                     } else {
                                                         if (in_array($name, array('birth_date', 'deceased_date', 'membership_start_date', 'membership_end_date', 'join_date'))) {
                                                             require_once 'CRM/Utils/Date.php';
                                                             $values[$index] = CRM_Utils_Date::customFormat($details->{$name});
                                                             $params[$index] = CRM_Utils_Date::isoToMysql($details->{$name});
                                                         } else {
                                                             $values[$index] = $details->{$name};
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         } else {
             if (strpos($name, '-') !== false) {
                 list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $name, 3);
                 if ($id == 'Primary') {
                     // fix for CRM-1543
                     // not sure why we'd every use Primary location type id
                     // we need to fix the source if we are using it
                     // $locationTypeName = CRM_Contact_BAO_Contact::getPrimaryLocationType( $cid );
                     $locationTypeName = 1;
                 } else {
                     $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
                 }
                 if (!$locationTypeName) {
                     continue;
                 }
                 $detailName = "{$locationTypeName}-{$fieldName}";
                 $detailName = str_replace(' ', '_', $detailName);
                 if (in_array($fieldName, array('phone', 'im', 'email', 'openid'))) {
                     if ($type) {
                         $detailName .= "-{$type}";
                     }
                 }
                 if (in_array($fieldName, array('state_province', 'country', 'county'))) {
                     $values[$index] = $details->{$detailName};
                     $idx = $detailName . '_id';
                     $params[$index] = $details->{$idx};
                 } else {
                     if ($fieldName == 'im') {
                         $providerId = $detailName . '-provider_id';
                         $providerName = $imProviders[$details->{$providerId}];
                         if ($providerName) {
                             $values[$index] = $details->{$detailName} . " (" . $providerName . ")";
                         } else {
                             $values[$index] = $details->{$detailName};
                         }
                         $params[$index] = $details->{$detailName};
                     } else {
                         $values[$index] = $params[$index] = $details->{$detailName};
                     }
                 }
             }
         }
         if ($field['visibility'] == "Public Pages and Listings" && CRM_Core_Permission::check('profile listings and forms')) {
             if (CRM_Utils_System::isNull($params[$index])) {
                 $params[$index] = $values[$index];
             }
             if (!isset($params[$index])) {
                 continue;
             }
             $customFieldID = CRM_Core_BAO_CustomField::getKeyID($field['name']);
             if (!$customFieldName) {
                 $fieldName = $field['name'];
             } else {
                 $fieldName = $customFieldName;
             }
             $url = null;
             if (CRM_Core_BAO_CustomField::getKeyID($field['name'])) {
                 $htmlType = $field['html_type'];
                 if ($htmlType == 'Link') {
                     $url = $params[$index];
                 } else {
                     if (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Multi-Select State/Province', 'Multi-Select Country'))) {
                         $valSeperator = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR;
                         $selectedOptions = explode($valSeperator, $params[$index]);
                         foreach ($selectedOptions as $key => $multiOption) {
                             if ($multiOption) {
                                 $eachOption = $valSeperator . $multiOption . $valSeperator;
                                 $url[] = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($eachOption));
                             }
                         }
                     } else {
                         $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index]));
                     }
                 }
             } else {
                 $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index]));
             }
             if ($url && !empty($values[$index]) && $searchable) {
                 if (is_array($url) && !empty($url)) {
                     $links = array();
                     $eachMultiValue = explode(', ', $values[$index]);
                     foreach ($eachMultiValue as $key => $valueLabel) {
                         $links[] = '<a href="' . $url[$key] . '">' . $valueLabel . '</a>';
                     }
                     $values[$index] = implode(', ', $links);
                 } else {
                     $values[$index] = '<a href="' . $url . '">' . $values[$index] . '</a>';
                 }
             }
         }
     }
 }
Example #27
0
 /**
  * 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;
 }
Example #28
0
 /**
  * Based on the provided two contact_ids and a set of tables, move the belongings of the
  * other contact to the main one - be it Location / CustomFields or Contact .. related info.
  * A superset of moveContactBelongings() function.
  *
  * @param int $mainId
  *   Main contact with whom merge has to happen.
  * @param int $otherId
  *   Duplicate contact which would be deleted after merge operation.
  *
  * @param $migrationInfo
  *
  * @return bool
  */
 public static function moveAllBelongings($mainId, $otherId, $migrationInfo)
 {
     if (empty($migrationInfo)) {
         return FALSE;
     }
     $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
     $relTables = CRM_Dedupe_Merger::relTables();
     $moveTables = $locBlocks = $tableOperations = array();
     foreach ($migrationInfo as $key => $value) {
         if ($value == $qfZeroBug) {
             $value = '0';
         }
         if ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) || substr($key, 0, 12) == 'move_custom_') && $value != NULL) {
             $submitted[substr($key, 5)] = $value;
         } elseif (substr($key, 0, 14) == 'move_location_' and $value != NULL) {
             $locField = explode('_', $key);
             $fieldName = $locField[2];
             $fieldCount = $locField[3];
             $operation = CRM_Utils_Array::value('operation', $migrationInfo['location'][$fieldName][$fieldCount]);
             // default operation is overwrite.
             if (!$operation) {
                 $operation = 2;
             }
             $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
             $locBlocks[$fieldName][$fieldCount]['locTypeId'] = CRM_Utils_Array::value('locTypeId', $migrationInfo['location'][$fieldName][$fieldCount]);
         } elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
             $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
             if (array_key_exists('operation', $migrationInfo)) {
                 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
                     if (array_key_exists($key, $migrationInfo['operation'])) {
                         $tableOperations[$table] = $migrationInfo['operation'][$key];
                     }
                 }
             }
         }
     }
     // **** Do location related migration:
     if (!empty($locBlocks)) {
         $locComponent = array('email' => 'Email', 'phone' => 'Phone', 'im' => 'IM', 'openid' => 'OpenID', 'address' => 'Address');
         $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_primary' => 1));
         $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, array('is_billing' => 1));
         foreach ($locBlocks as $name => $block) {
             if (!is_array($block) || CRM_Utils_System::isNull($block)) {
                 continue;
             }
             $daoName = 'CRM_Core_DAO_' . $locComponent[$name];
             $primaryDAOId = array_key_exists($name, $primaryBlockIds) ? array_pop($primaryBlockIds[$name]) : NULL;
             $billingDAOId = array_key_exists($name, $billingBlockIds) ? array_pop($billingBlockIds[$name]) : NULL;
             foreach ($block as $blkCount => $values) {
                 $locTypeId = CRM_Utils_Array::value('locTypeId', $values, 1);
                 $operation = CRM_Utils_Array::value('operation', $values, 2);
                 $otherBlockId = CRM_Utils_Array::value($blkCount, $migrationInfo['other_details']['loc_block_ids'][$name]);
                 // keep 1-1 mapping for address - loc type.
                 $idKey = $blkCount;
                 if (array_key_exists($name, $locComponent)) {
                     $idKey = $locTypeId;
                 }
                 if (isset($migrationInfo['main_details']['loc_block_ids'][$name])) {
                     $mainBlockId = CRM_Utils_Array::value($idKey, $migrationInfo['main_details']['loc_block_ids'][$name]);
                 }
                 if (!$otherBlockId) {
                     continue;
                 }
                 // for the block which belongs to other-contact, link the contact to main-contact
                 $otherBlockDAO = new $daoName();
                 $otherBlockDAO->id = $otherBlockId;
                 $otherBlockDAO->contact_id = $mainId;
                 $otherBlockDAO->location_type_id = $locTypeId;
                 // if main contact already has primary & billing, set the flags to 0.
                 if ($primaryDAOId) {
                     $otherBlockDAO->is_primary = 0;
                 }
                 if ($billingDAOId) {
                     $otherBlockDAO->is_billing = 0;
                 }
                 // overwrite - need to delete block which belongs to main-contact.
                 if (isset($mainBlockId) && $mainBlockId && $operation == 2) {
                     $deleteDAO = new $daoName();
                     $deleteDAO->id = $mainBlockId;
                     $deleteDAO->find(TRUE);
                     // if we about to delete a primary / billing block, set the flags for new block
                     // that we going to assign to main-contact
                     if ($primaryDAOId && $primaryDAOId == $deleteDAO->id) {
                         $otherBlockDAO->is_primary = 1;
                     }
                     if ($billingDAOId && $billingDAOId == $deleteDAO->id) {
                         $otherBlockDAO->is_billing = 1;
                     }
                     $deleteDAO->delete();
                     $deleteDAO->free();
                 }
                 $otherBlockDAO->update();
                 $otherBlockDAO->free();
             }
         }
     }
     // **** Do tables related migrations
     if (!empty($moveTables)) {
         CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations);
         unset($moveTables, $tableOperations);
     }
     // **** Do contact related migrations
     CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId);
     // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
     $names['gender'] = array('newName' => 'gender_id', 'groupName' => 'gender');
     $names['individual_prefix'] = array('newName' => 'prefix_id', 'groupName' => 'individual_prefix');
     $names['individual_suffix'] = array('newName' => 'suffix_id', 'groupName' => 'individual_suffix');
     $names['communication_style'] = array('newName' => 'communication_style_id', 'groupName' => 'communication_style');
     $names['addressee'] = array('newName' => 'addressee_id', 'groupName' => 'addressee');
     $names['email_greeting'] = array('newName' => 'email_greeting_id', 'groupName' => 'email_greeting');
     $names['postal_greeting'] = array('newName' => 'postal_greeting_id', 'groupName' => 'postal_greeting');
     CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
     // fix custom fields so they're edible by createProfileContact()
     static $treeCache = array();
     if (!array_key_exists($migrationInfo['main_details']['contact_type'], $treeCache)) {
         $treeCache[$migrationInfo['main_details']['contact_type']] = CRM_Core_BAO_CustomGroup::getTree($migrationInfo['main_details']['contact_type'], CRM_Core_DAO::$_nullObject, NULL, -1);
     }
     $cgTree =& $treeCache[$migrationInfo['main_details']['contact_type']];
     $cFields = array();
     foreach ($cgTree as $key => $group) {
         if (!isset($group['fields'])) {
             continue;
         }
         foreach ($group['fields'] as $fid => $field) {
             $cFields[$fid]['attributes'] = $field;
         }
     }
     if (!isset($submitted)) {
         $submitted = array();
     }
     foreach ($submitted as $key => $value) {
         if (substr($key, 0, 7) == 'custom_') {
             $fid = (int) substr($key, 7);
             if (empty($cFields[$fid])) {
                 continue;
             }
             $htmlType = $cFields[$fid]['attributes']['html_type'];
             switch ($htmlType) {
                 case 'File':
                     $customFiles[] = $fid;
                     unset($submitted["custom_{$fid}"]);
                     break;
                 case 'Select Country':
                 case 'Select State/Province':
                     $submitted[$key] = CRM_Core_BAO_CustomField::getDisplayValue($value, $fid, $cFields);
                     break;
                 case 'CheckBox':
                 case 'AdvMulti-Select':
                 case 'Multi-Select':
                 case 'Multi-Select Country':
                 case 'Multi-Select State/Province':
                     // Merge values from both contacts for multivalue fields, CRM-4385
                     // get the existing custom values from db.
                     $customParams = array('entityID' => $mainId, $key => TRUE);
                     $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
                     if (!empty($customfieldValues[$key])) {
                         $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
                         if (is_array($existingValue) && !empty($existingValue)) {
                             $mergeValue = $submmtedCustomValue = array();
                             if ($value) {
                                 $submmtedCustomValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                             }
                             //hack to remove null and duplicate values from array.
                             foreach (array_merge($submmtedCustomValue, $existingValue) as $k => $v) {
                                 if ($v != '' && !in_array($v, $mergeValue)) {
                                     $mergeValue[] = $v;
                                 }
                             }
                             //keep state and country as array format.
                             //for checkbox and m-select format w/ VALUE_SEPARATOR
                             if (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select'))) {
                                 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $mergeValue) . CRM_Core_DAO::VALUE_SEPARATOR;
                             } else {
                                 $submitted[$key] = $mergeValue;
                             }
                         }
                     } elseif (in_array($htmlType, array('Multi-Select Country', 'Multi-Select State/Province'))) {
                         //we require submitted values should be in array format
                         if ($value) {
                             $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
                             //hack to remove null values from array.
                             $mergeValue = array();
                             foreach ($mergeValueArray as $k => $v) {
                                 if ($v != '') {
                                     $mergeValue[] = $v;
                                 }
                             }
                             $submitted[$key] = $mergeValue;
                         }
                     }
                     break;
                 default:
                     break;
             }
         }
     }
     // **** Do file custom fields related migrations
     // FIXME: move this someplace else (one of the BAOs) after discussing
     // where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
     // like, delete a file...
     if (!isset($customFiles)) {
         $customFiles = array();
     }
     foreach ($customFiles as $customId) {
         list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField::getTableColumnGroup($customId);
         // get the contact_id -> file_id mapping
         $fileIds = array();
         $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
         $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         while ($dao->fetch()) {
             $fileIds[$dao->entity_id] = $dao->file_id;
         }
         $dao->free();
         // delete the main contact's file
         if (!empty($fileIds[$mainId])) {
             CRM_Core_BAO_File::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
         }
         // move the other contact's file to main contact
         //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
         if (CRM_Core_DAO::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
             $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
         } else {
             $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
         }
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         if (CRM_Core_DAO::singleValueQuery("\n        SELECT id\n        FROM civicrm_entity_file\n        WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")) {
             $sql = "\n          UPDATE civicrm_entity_file\n          SET entity_id = {$mainId}\n          WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
         } else {
             $sql = "\n          INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )\n          VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
         }
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
     }
     // move view only custom fields CRM-5362
     $viewOnlyCustomFields = array();
     foreach ($submitted as $key => $value) {
         $fid = (int) substr($key, 7);
         if (array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])) {
             $viewOnlyCustomFields[$key] = $value;
         }
     }
     // special case to set values for view only, CRM-5362
     if (!empty($viewOnlyCustomFields)) {
         $viewOnlyCustomFields['entityID'] = $mainId;
         CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
     }
     // **** Delete other contact & update prev-next caching
     $otherParams = array('contact_id' => $otherId, 'id' => $otherId, 'version' => 3);
     if (CRM_Core_Permission::check('merge duplicate contacts') && CRM_Core_Permission::check('delete contacts')) {
         // if ext id is submitted then set it null for contact to be deleted
         if (!empty($submitted['external_identifier'])) {
             $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
             CRM_Core_DAO::executeQuery($query);
         }
         civicrm_api('contact', 'delete', $otherParams);
         CRM_Core_BAO_PrevNextCache::deleteItem($otherId);
     }
     // FIXME: else part
     /*         else { */
     /*             CRM_Core_Session::setStatus( ts('Do not have sufficient permission to delete duplicate contact.') ); */
     /*         } */
     // CRM-15681 merge sub_types
     if ($other_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['other_details'])) {
         if ($main_sub_types = CRM_Utils_array::value('contact_sub_type', $migrationInfo['main_details'])) {
             $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
         } else {
             $submitted['contact_sub_type'] = $other_sub_types;
         }
     }
     // **** Update contact related info for the main contact
     if (!empty($submitted)) {
         $submitted['contact_id'] = $mainId;
         //update current employer field
         if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
             if (!CRM_Utils_System::isNull($currentEmloyerId)) {
                 $submitted['current_employer'] = $submitted['current_employer_id'];
             } else {
                 $submitted['current_employer'] = '';
             }
             unset($submitted['current_employer_id']);
         }
         //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
         if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
             $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
         }
         if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
             $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
         }
         CRM_Contact_BAO_Contact::createProfileContact($submitted, CRM_Core_DAO::$_nullArray, $mainId);
         unset($submitted);
     }
     CRM_Utils_Hook::post('merge', 'Contact', $mainId, CRM_Core_DAO::$_nullObject);
     return TRUE;
 }
Example #29
0
 /**
  * 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'));
     }
 }
Example #30
0
 /**
  * gives required details of contacts 
  *
  * @param  array   $contactIds       of conatcts
  * @param  array   $returnProperties of required properties
  * @param  boolean $skipOnHold       don't return on_hold contact info also.
  * @param  boolean $skipDeceased     don't return deceased contact info.
  * @param  array   $extraParams      extra params
  *
  * @return array
  * @access public
  */
 function getDetails($contactIDs, $returnProperties = null, $skipOnHold = true, $skipDeceased = true, $extraParams = null)
 {
     $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)) {
         require_once 'CRM/Contact/BAO/Contact.php';
         $fields = array_merge(array_keys(CRM_Contact_BAO_Contact::exportableFields()), array('display_name', 'checksum', 'contact_id'));
         foreach ($fields as $key => $val) {
             $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);
     require_once 'CRM/Contact/BAO/Query.php';
     $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])) {
                 require_once 'CRM/Core/PseudoConstant.php';
                 $pcm = CRM_Core_PseudoConstant::pcm();
                 // communication Prefferance
                 require_once 'CRM/Core/BAO/CustomOption.php';
                 $contactPcm = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $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 (CRM_Utils_Array::value($val, $contactDetails[$contactID])) {
                     $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
                 }
             }
         }
     }
     // also call a hook and get token details
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::tokenValues($details[0], $contactIDs);
     return $details;
 }