Example #1
0
 /**
  * Function to actually build the form
  *
  * @return void
  * @access public
  */
 function buildQuickForm()
 {
     if ($this->_action & CRM_CORE_ACTION_DELETE) {
         $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete Profile Field'), 'spacing' => '         ', 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     if (isset($this->_id)) {
         $params = array('id' => $this->_id);
         CRM_Core_BAO_UFField::retrieve($params, $defaults);
         $defaults['field_name'] = array($defaults['field_type'], $defaults['field_name'], $defaults['location_type_id'], $defaults['phone_type']);
         $this->_gid = $defaults['uf_group_id'];
     } else {
         $defaults['is_active'] = 1;
     }
     if ($this->_action & CRM_CORE_ACTION_ADD) {
         $uf =& new CRM_Core_DAO();
         $sql = "SELECT weight FROM civicrm_uf_field  WHERE uf_group_id = " . $this->_gid . " ORDER BY weight  DESC LIMIT 0, 1";
         $uf->query($sql);
         while ($uf->fetch()) {
             $defaults['weight'] = $uf->weight + 1;
         }
         if (empty($defaults['weight'])) {
             $defaults['weight'] = 1;
         }
     }
     // lets trim all the whitespace
     $this->applyFilter('__ALL__', 'trim');
     //hidden field to catch the group id in profile
     $this->add('hidden', 'group_id', $this->_gid);
     //hidden field to catch the field id in profile
     $this->add('hidden', 'field_id', $this->_id);
     $fields = array();
     $fields['Individual'] =& CRM_Contact_BAO_Contact::exportableFields('Individual');
     $fields['Household'] =& CRM_Contact_BAO_Contact::exportableFields('Household');
     $fields['Organization'] =& CRM_Contact_BAO_Contact::exportableFields('Organization');
     $contribFields =& CRM_Contribute_BAO_Contribution::getContributionFields();
     if (!empty($contribFields)) {
         $fields['Contribution'] =& $contribFields;
     }
     foreach ($fields as $key => $value) {
         foreach ($value as $key1 => $value1) {
             $this->_mapperFields[$key][$key1] = $value1['title'];
             $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
         }
     }
     require_once 'CRM/Core/BAO/LocationType.php';
     $this->_location_types =& CRM_Core_PseudoConstant::locationType();
     $defaultLocationType =& CRM_Core_BAO_LocationType::getDefault();
     /* FIXME: dirty hack to make the default option show up first.  This
      * avoids a mozilla browser bug with defaults on dynamically constructed
      * selector widgets. */
     if ($defaultLocationType) {
         $defaultLocation = $this->_location_types[$defaultLocationType->id];
         unset($this->_location_types[$defaultLocationType->id]);
         $this->_location_types = array($defaultLocationType->id => $defaultLocation) + $this->_location_types;
     }
     $sel1 = array('' => '-select-') + CRM_Core_SelectValues::contactType();
     if (!empty($contribFields)) {
         $sel1['Contribution'] = 'Contributions';
     }
     foreach ($sel1 as $key => $sel) {
         if ($key) {
             $sel2[$key] = $this->_mapperFields[$key];
         }
     }
     $sel3[''] = null;
     $phoneTypes = CRM_Core_SelectValues::phoneType();
     foreach ($sel1 as $k => $sel) {
         if ($k) {
             foreach ($this->_location_types as $key => $value) {
                 $sel4[$k]['phone'][$key] =& $phoneTypes;
             }
         }
     }
     foreach ($sel1 as $k => $sel) {
         if ($k) {
             foreach ($this->_mapperFields[$k] as $key => $value) {
                 if ($hasLocationTypes[$k][$key]) {
                     $sel3[$k][$key] = $this->_location_types;
                 } else {
                     $sel3[$key] = null;
                 }
             }
         }
     }
     $this->_defaults = array();
     $js = "<script type='text/javascript'>\n";
     $formName = "document.{$this->_name}";
     $sel =& $this->addElement('hierselect', "field_name", ts('Field Name'), 'onclick="showLabel();"');
     $formValues = array();
     //$formValues = $this->controller->exportValues( $this->_name );
     $formValues = $_POST;
     // using $_POST since export values don't give values on first submit
     if (empty($formValues)) {
         for ($k = 1; $k < 4; $k++) {
             if (!$defaults['field_name'][$k]) {
                 $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n";
             }
         }
     } else {
         foreach ($formValues['field_name'] as $value) {
             for ($k = 1; $k < 4; $k++) {
                 if (!$formValues['field_name'][$k]) {
                     $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n";
                 }
             }
         }
     }
     $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
     $js .= "</script>\n";
     $this->assign('initHideBoxes', $js);
     $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::ufVisibility(), true);
     // should the field appear in selector?
     $this->add('checkbox', 'in_selector', ts('In Selector?'));
     // weight
     $this->add('text', 'weight', ts('Weight'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'weight'), true);
     $this->addRule('weight', ts(' is a numeric field'), 'numeric');
     $this->add('textarea', 'help_post', ts('Field Help'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'help_post'));
     // listings title
     $this->add('text', 'listings_title', ts('Listings Title'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'listings_title'));
     $this->addRule('listings_title', ts('Please enter a valid title for this field when displayed in user listings.'), 'title');
     $this->add('checkbox', 'is_required', ts('Required?'));
     $this->add('checkbox', 'is_active', ts('Active?'));
     $this->add('checkbox', 'is_searchable', ts('Searchable?'));
     $this->add('checkbox', 'is_view', ts('View Only?'));
     // $this->add( 'checkbox', 'is_registration', ts( 'Display in Registration Form?' ) );
     //$this->add( 'checkbox', 'is_match'       , ts( 'Key to Match Contacts?'        ) );
     $this->add('text', 'label', ts('Field Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'label'));
     // add buttons
     $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel'))));
     $this->addFormRule(array('CRM_UF_Form_Field', 'formRule'));
     // if view mode pls freeze it with the done button.
     if ($this->_action & CRM_CORE_ACTION_VIEW) {
         $this->freeze();
         $this->addElement('button', 'done', ts('Done'), array('onClick' => "location.href='civicrm/admin/uf/group/field?reset=1&action=browse&gid=" . $this->_gid . "'"));
     }
     $this->setDefaults($defaults);
 }
Example #2
0
 /**
  * Browse all CiviCRM Profile group fields.
  *
  * @return void
  * @access public
  * @static
  */
 function browse()
 {
     $ufField = array();
     $ufFieldBAO =& new CRM_Core_BAO_UFField();
     // fkey is gid
     $ufFieldBAO->uf_group_id = $this->_gid;
     $ufFieldBAO->orderBy('weight', 'field_name');
     $ufFieldBAO->find();
     $locationType = array();
     $locationType =& CRM_Core_PseudoConstant::locationType();
     require_once 'CRM/Contact/BAO/Contact.php';
     $fields =& CRM_Contact_BAO_Contact::exportableFields('All', false, true);
     $fields = array_merge(CRM_Contribute_BAO_Contribution::getContributionFields(), $fields);
     $select = array();
     foreach ($fields as $name => $field) {
         if ($name) {
             $select[$name] = $field['title'];
         }
     }
     $select['group'] = ts('Group(s)');
     $select['tag'] = ts('Tag(s)');
     while ($ufFieldBAO->fetch()) {
         $ufField[$ufFieldBAO->id] = array();
         $phoneType = $locType = '';
         CRM_Core_DAO::storeValues($ufFieldBAO, $ufField[$ufFieldBAO->id]);
         CRM_Core_DAO_UFField::addDisplayEnums($ufField[$ufFieldBAO->id]);
         // fix the field_name value
         $ufField[$ufFieldBAO->id]['field_name'] = $select[$ufField[$ufFieldBAO->id]['field_name']];
         if ($ufFieldBAO->location_type_id) {
             $locType = ' (' . $locationType[$ufFieldBAO->location_type_id] . ') ';
         }
         if ($ufFieldBAO->phone_type) {
             if ($ufFieldBAO->phone_type != 'Phone') {
                 // this hack is to prevent Phone Phone
                 $phoneType .= '-' . $ufFieldBAO->phone_type;
             }
         }
         $ufField[$ufFieldBAO->id]['field_name'] .= $phoneType . $locType;
         $action = array_sum(array_keys($this->actionLinks()));
         if ($ufFieldBAO->is_active) {
             $action -= CRM_CORE_ACTION_ENABLE;
         } else {
             $action -= CRM_CORE_ACTION_DISABLE;
         }
         $ufField[$ufFieldBAO->id]['action'] = CRM_Core_Action::formLink(CRM_UF_Page_Field::actionLinks(), $action, array('id' => $ufFieldBAO->id, 'gid' => $this->_gid));
     }
     $this->assign('ufField', $ufField);
 }
Example #3
0
 /**
  * Build the mapping form.
  *
  * @param CRM_Core_Form $form
  * @param string $mappingType
  *   (Export/Import/Search Builder).
  * @param int $mappingId
  * @param int $columnNo
  * @param int $blockCount
  *   (no of blocks shown).
  * @param NULL $exportMode
  *
  * @return void
  */
 public static function buildMappingForm(&$form, $mappingType = 'Export', $mappingId = NULL, $columnNo, $blockCount = 3, $exportMode = NULL)
 {
     if ($mappingType == 'Export') {
         $name = "Map";
         $columnCount = array('1' => $columnNo);
     } elseif ($mappingType == 'Search Builder') {
         $name = "Builder";
         $columnCount = $columnNo;
     }
     //get the saved mapping details
     if ($mappingType == 'Export') {
         $form->applyFilter('saveMappingName', 'trim');
         //to save the current mappings
         if (!isset($mappingId)) {
             $saveDetailsName = ts('Save this field mapping');
             $form->add('text', 'saveMappingName', ts('Name'));
             $form->add('text', 'saveMappingDesc', ts('Description'));
         } else {
             $form->assign('loadedMapping', $mappingId);
             $params = array('id' => $mappingId);
             $temp = array();
             $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
             $form->assign('savedName', $mappingDetails->name);
             $form->add('hidden', 'mappingId', $mappingId);
             $form->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
             $saveDetailsName = ts('Save as a new field mapping');
             $form->add('text', 'saveMappingName', ts('Name'));
             $form->add('text', 'saveMappingDesc', ts('Description'));
         }
         $form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
         $form->addFormRule(array('CRM_Export_Form_Map', 'formRule'), $form->get('mappingTypeId'));
     } elseif ($mappingType == 'Search Builder') {
         $form->addElement('submit', 'addBlock', ts('Also include contacts where'), array('class' => 'submit-link'));
     }
     $defaults = array();
     $hasLocationTypes = array();
     $hasRelationTypes = array();
     $fields = array();
     if ($mappingType == 'Export') {
         $required = TRUE;
     } elseif ($mappingType == 'Search Builder') {
         $required = FALSE;
     }
     $contactType = array('Individual', 'Household', 'Organization');
     foreach ($contactType as $value) {
         $contactFields = CRM_Contact_BAO_Contact::exportableFields($value, FALSE, $required);
         $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook::singleton()->getFields());
         // exclude the address options disabled in the Address Settings
         $fields[$value] = CRM_Core_BAO_Address::validateAddressOptions($contactFields);
         ksort($fields[$value]);
         if ($mappingType == 'Export') {
             $relationships = array();
             $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $value);
             asort($relationshipTypes);
             foreach ($relationshipTypes as $key => $var) {
                 list($type) = explode('_', $key);
                 $relationships[$key]['title'] = $var;
                 $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
                 $relationships[$key]['export'] = TRUE;
                 $relationships[$key]['relationship_type_id'] = $type;
                 $relationships[$key]['related'] = TRUE;
                 $relationships[$key]['hasRelationType'] = 1;
             }
             if (!empty($relationships)) {
                 $fields[$value] = array_merge($fields[$value], array('related' => array('title' => ts('- related contact info -'))), $relationships);
             }
         }
     }
     //get the current employer for mapping.
     if ($required) {
         $fields['Individual']['current_employer']['title'] = ts('Current Employer');
     }
     // add component fields
     $compArray = array();
     //we need to unset groups, tags, notes for component export
     if ($exportMode != CRM_Export_Form_Select::CONTACT_EXPORT) {
         foreach (array('groups', 'tags', 'notes') as $value) {
             unset($fields['Individual'][$value]);
             unset($fields['Household'][$value]);
             unset($fields['Organization'][$value]);
         }
     }
     if ($mappingType == 'Search Builder') {
         //build the common contact fields array.
         $fields['Contact'] = array();
         foreach ($fields['Individual'] as $key => $value) {
             if (!empty($fields['Household'][$key]) && !empty($fields['Organization'][$key])) {
                 $fields['Contact'][$key] = $value;
                 unset($fields['Organization'][$key], $fields['Household'][$key], $fields['Individual'][$key]);
             }
         }
         if (array_key_exists('note', $fields['Contact'])) {
             $noteTitle = $fields['Contact']['note']['title'];
             $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
             $fields['Contact']['note_body'] = array('title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body');
             $fields['Contact']['note_subject'] = array('title' => $noteTitle . ': ' . ts('Subject Only'), 'name' => 'note_subject');
         }
     }
     if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
         if (CRM_Core_Permission::access('CiviContribute')) {
             $fields['Contribution'] = CRM_Contribute_BAO_Contribution::exportableFields();
             foreach (array('contribution_contact_id', 'contribution_soft_credit_name', 'contribution_soft_credit_amount', 'contribution_soft_credit_type', 'contribution_soft_credit_contribution_id') as $element) {
                 unset($fields['Contribution'][$element]);
             }
             $compArray['Contribution'] = ts('Contribution');
         }
     }
     if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
         if (CRM_Core_Permission::access('CiviEvent')) {
             $fields['Participant'] = CRM_Event_BAO_Participant::exportableFields();
             //get the component payment fields
             if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
                 $componentPaymentFields = array();
                 foreach (CRM_Export_BAO_Export::componentPaymentFields() as $payField => $payTitle) {
                     $componentPaymentFields[$payField] = array('title' => $payTitle);
                 }
                 $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
             }
             $compArray['Participant'] = ts('Participant');
         }
     }
     if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
         if (CRM_Core_Permission::access('CiviMember')) {
             $fields['Membership'] = CRM_Member_BAO_Membership::getMembershipFields($exportMode);
             unset($fields['Membership']['membership_contact_id']);
             $compArray['Membership'] = ts('Membership');
         }
     }
     if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
         if (CRM_Core_Permission::access('CiviPledge')) {
             $fields['Pledge'] = CRM_Pledge_BAO_Pledge::exportableFields();
             unset($fields['Pledge']['pledge_contact_id']);
             $compArray['Pledge'] = ts('Pledge');
         }
     }
     if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
         if (CRM_Core_Permission::access('CiviCase')) {
             $fields['Case'] = CRM_Case_BAO_Case::exportableFields();
             $compArray['Case'] = ts('Case');
             $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Case');
             $compArray['Activity'] = ts('Case Activity');
             unset($fields['Case']['case_contact_id']);
         }
     }
     if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::GRANT_EXPORT) {
         if (CRM_Core_Permission::access('CiviGrant')) {
             $fields['Grant'] = CRM_Grant_BAO_Grant::exportableFields();
             unset($fields['Grant']['grant_contact_id']);
             if ($mappingType == 'Search Builder') {
                 unset($fields['Grant']['grant_type_id']);
             }
             $compArray['Grant'] = ts('Grant');
         }
     }
     if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
         $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Activity');
         $compArray['Activity'] = ts('Activity');
     }
     //Contact Sub Type For export
     $contactSubTypes = array();
     $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
     foreach ($subTypes as $subType => $val) {
         //adding subtype specific relationships CRM-5256
         $csRelationships = array();
         if ($mappingType == 'Export') {
             $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'], FALSE, 'label', TRUE, $subType);
             foreach ($subTypeRelationshipTypes as $key => $var) {
                 if (!array_key_exists($key, $fields[$val['parent']])) {
                     list($type) = explode('_', $key);
                     $csRelationships[$key]['title'] = $var;
                     $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
                     $csRelationships[$key]['export'] = TRUE;
                     $csRelationships[$key]['relationship_type_id'] = $type;
                     $csRelationships[$key]['related'] = TRUE;
                     $csRelationships[$key]['hasRelationType'] = 1;
                 }
             }
         }
         $fields[$subType] = $fields[$val['parent']] + $csRelationships;
         //custom fields for sub type
         $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($subType);
         $fields[$subType] += $subTypeFields;
         if (!empty($subTypeFields) || !empty($csRelationships)) {
             $contactSubTypes[$subType] = $val['label'];
         }
     }
     unset($subTypes);
     foreach ($fields as $key => $value) {
         foreach ($value as $key1 => $value1) {
             //CRM-2676, replacing the conflict for same custom field name from different custom group.
             $customGroupName = self::getCustomGroupName($key1);
             if ($customGroupName) {
                 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
             } else {
                 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
             }
             if (isset($value1['hasLocationType'])) {
                 $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
             }
             if (isset($value1['hasRelationType'])) {
                 $hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
                 unset($relatedMapperFields[$key][$key1]);
             }
         }
         if (array_key_exists('related', $relatedMapperFields[$key])) {
             unset($relatedMapperFields[$key]['related']);
         }
     }
     $mapperKeys = array_keys($mapperFields);
     $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
     // FIXME: dirty hack to make the default option show up first.  This
     // avoids a mozilla browser bug with defaults on dynamically constructed
     // selector widgets.
     if ($defaultLocationType) {
         $defaultLocation = $locationTypes[$defaultLocationType->id];
         unset($locationTypes[$defaultLocationType->id]);
         $locationTypes = array($defaultLocationType->id => $defaultLocation) + $locationTypes;
     }
     $locationTypes = array(' ' => ts('Primary')) + $locationTypes;
     // since we need a hierarchical list to display contact types & subtypes,
     // this is what we going to display in first selector
     $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE);
     if ($mappingType == 'Search Builder') {
         $contactTypes = array('Contact' => ts('Contacts')) + $contactTypes;
     }
     $sel1 = array('' => ts('- select record type -')) + $contactTypes + $compArray;
     foreach ($sel1 as $key => $sel) {
         if ($key) {
             // sort everything BUT the contactType which is sorted seperately by
             // an initial commit of CRM-13278 (check ksort above)
             if (!in_array($key, $contactType)) {
                 asort($mapperFields[$key]);
             }
             $sel2[$key] = array('' => ts('- select field -')) + $mapperFields[$key];
         }
     }
     $sel3[''] = NULL;
     $sel5[''] = NULL;
     $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
     $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
     asort($phoneTypes);
     foreach ($sel1 as $k => $sel) {
         if ($k) {
             foreach ($locationTypes as $key => $value) {
                 if (trim($key) != '') {
                     $sel4[$k]['phone'][$key] =& $phoneTypes;
                     $sel4[$k]['im'][$key] =& $imProviders;
                 }
             }
         }
     }
     foreach ($sel1 as $k => $sel) {
         if ($k) {
             foreach ($mapperFields[$k] as $key => $value) {
                 if (isset($hasLocationTypes[$k][$key])) {
                     $sel3[$k][$key] = $locationTypes;
                 } else {
                     $sel3[$key] = NULL;
                 }
             }
         }
     }
     // Array for core fields and relationship custom data
     $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
     if ($mappingType == 'Export') {
         foreach ($sel1 as $k => $sel) {
             if ($k) {
                 foreach ($mapperFields[$k] as $field => $dontCare) {
                     if (isset($hasRelationTypes[$k][$field])) {
                         list($id, $first, $second) = explode('_', $field);
                         // FIX ME: For now let's not expose custom data related to relationship
                         $relationshipCustomFields = array();
                         //$relationshipCustomFields    = self::getRelationTypeCustomGroupData( $id );
                         //asort($relationshipCustomFields);
                         $relationshipType = new CRM_Contact_BAO_RelationshipType();
                         $relationshipType->id = $id;
                         if ($relationshipType->find(TRUE)) {
                             $direction = "contact_sub_type_{$second}";
                             if (isset($relationshipType->{$direction})) {
                                 $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->{$direction}], (array) $relationshipCustomFields);
                             } else {
                                 $target_type = 'contact_type_' . $second;
                                 $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->{$target_type}], (array) $relationshipCustomFields);
                             }
                         }
                         $relationshipType->free();
                         asort($relatedFields);
                         $sel5[$k][$field] = $relatedFields;
                     }
                 }
             }
         }
         //Location Type for relationship fields
         foreach ($sel5 as $k => $v) {
             if ($v) {
                 foreach ($v as $rel => $fields) {
                     foreach ($fields as $field => $fieldLabel) {
                         if (isset($hasLocationTypes[$k][$field])) {
                             $sel6[$k][$rel][$field] = $locationTypes;
                         }
                     }
                 }
             }
         }
         //PhoneTypes for  relationship fields
         $sel7[''] = NULL;
         foreach ($sel6 as $k => $rel) {
             if ($k) {
                 foreach ($rel as $phonekey => $phonevalue) {
                     foreach ($locationTypes as $locType => $loc) {
                         if (trim($locType) != '') {
                             $sel7[$k][$phonekey]['phone'][$locType] =& $phoneTypes;
                             $sel7[$k][$phonekey]['im'][$locType] =& $imProviders;
                         }
                     }
                 }
             }
         }
     }
     //special fields that have location, hack for primary location
     $specialFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im');
     if (isset($mappingId)) {
         $colCnt = 0;
         list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue) = CRM_Core_BAO_Mapping::getMappingFields($mappingId);
         $blkCnt = count($mappingName);
         if ($blkCnt >= $blockCount) {
             $blockCount = $blkCnt + 1;
         }
         for ($x = 1; $x < $blockCount; $x++) {
             if (isset($mappingName[$x])) {
                 $colCnt = count($mappingName[$x]);
                 if ($colCnt >= $columnCount[$x]) {
                     $columnCount[$x] = $colCnt;
                 }
             }
         }
     }
     $form->_blockCount = $blockCount;
     $form->_columnCount = $columnCount;
     $form->set('blockCount', $form->_blockCount);
     $form->set('columnCount', $form->_columnCount);
     $defaults = $noneArray = $nullArray = array();
     //used to warn for mismatch column count or mismatch mapping
     $warning = 0;
     for ($x = 1; $x < $blockCount; $x++) {
         for ($i = 0; $i < $columnCount[$x]; $i++) {
             $sel =& $form->addElement('hierselect', "mapper[{$x}][{$i}]", ts('Mapper for Field %1', array(1 => $i)), NULL);
             $jsSet = FALSE;
             if (isset($mappingId)) {
                 $locationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0;
                 if (isset($mappingName[$x][$i])) {
                     if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
                         if (isset($mappingRelation[$x][$i])) {
                             $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$x][$i]));
                             $relLocationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0;
                             if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
                                 $relLocationId = " ";
                             }
                             $relPhoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
                             $defaults["mapper[{$x}][{$i}]"] = array($mappingContactType[$x][$i], $mappingRelation[$x][$i], $locationId, $phoneType, $mappingName[$x][$i], $relLocationId, $relPhoneType);
                             if (!$locationId) {
                                 $noneArray[] = array($x, $i, 2);
                             }
                             if (!$phoneType && !$imProvider) {
                                 $noneArray[] = array($x, $i, 3);
                             }
                             if (!$mappingName[$x][$i]) {
                                 $noneArray[] = array($x, $i, 4);
                             }
                             if (!$relLocationId) {
                                 $noneArray[] = array($x, $i, 5);
                             }
                             if (!$relPhoneType) {
                                 $noneArray[] = array($x, $i, 6);
                             }
                             $noneArray[] = array($x, $i, 2);
                         } else {
                             $phoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
                             $imProvider = isset($mappingImProvider[$x][$i]) ? $mappingImProvider[$x][$i] : NULL;
                             if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
                                 $locationId = " ";
                             }
                             $defaults["mapper[{$x}][{$i}]"] = array($mappingContactType[$x][$i], $mappingName[$x][$i], $locationId, $phoneType);
                             if (!$mappingName[$x][$i]) {
                                 $noneArray[] = array($x, $i, 1);
                             }
                             if (!$locationId) {
                                 $noneArray[] = array($x, $i, 2);
                             }
                             if (!$phoneType && !$imProvider) {
                                 $noneArray[] = array($x, $i, 3);
                             }
                             $noneArray[] = array($x, $i, 4);
                             $noneArray[] = array($x, $i, 5);
                             $noneArray[] = array($x, $i, 6);
                         }
                         $jsSet = TRUE;
                         if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingOperator))) {
                             $defaults["operator[{$x}][{$i}]"] = CRM_Utils_Array::value($i, $mappingOperator[$x]);
                         }
                         if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingValue))) {
                             $defaults["value[{$x}][{$i}]"] = CRM_Utils_Array::value($i, $mappingValue[$x]);
                         }
                     }
                 }
             }
             //Fix for Search Builder
             if ($mappingType == 'Export') {
                 $j = 7;
             } else {
                 $j = 4;
             }
             $formValues = $form->exportValues();
             if (!$jsSet) {
                 if (empty($formValues)) {
                     // Incremented length for third select box(relationship type)
                     for ($k = 1; $k < $j; $k++) {
                         $noneArray[] = array($x, $i, $k);
                     }
                 } else {
                     if (!empty($formValues['mapper'][$x])) {
                         foreach ($formValues['mapper'][$x] as $value) {
                             for ($k = 1; $k < $j; $k++) {
                                 if (!isset($formValues['mapper'][$x][$i][$k]) || !$formValues['mapper'][$x][$i][$k]) {
                                     $noneArray[] = array($x, $i, $k);
                                 } else {
                                     $nullArray[] = array($x, $i, $k);
                                 }
                             }
                         }
                     } else {
                         for ($k = 1; $k < $j; $k++) {
                             $noneArray[] = array($x, $i, $k);
                         }
                     }
                 }
             }
             //Fix for Search Builder
             if ($mappingType == 'Export') {
                 if (!isset($mappingId) || $i >= count(reset($mappingName))) {
                     if (isset($formValues['mapper']) && isset($formValues['mapper'][$x][$i][1]) && array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)) {
                         $sel->setOptions(array($sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4));
                     } else {
                         $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
                     }
                 } else {
                     $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
                 }
             } else {
                 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
             }
             if ($mappingType == 'Search Builder') {
                 //CRM -2292, restricted array set
                 $operatorArray = array('' => ts('-operator-')) + CRM_Core_SelectValues::getSearchBuilderOperators();
                 $form->add('select', "operator[{$x}][{$i}]", '', $operatorArray);
                 $form->add('text', "value[{$x}][{$i}]", '');
             }
         }
         //end of columnCnt for
         if ($mappingType == 'Search Builder') {
             $title = ts('Another search field');
         } else {
             $title = ts('Select more fields');
         }
         $form->addElement('submit', "addMore[{$x}]", $title, array('class' => 'submit-link'));
     }
     //end of block for
     $js = "<script type='text/javascript'>\n";
     $formName = "document.{$name}";
     if (!empty($nullArray)) {
         $js .= "var nullArray = [";
         $elements = array();
         $seen = array();
         foreach ($nullArray as $element) {
             $key = "{$element[0]}, {$element[1]}, {$element[2]}";
             if (!isset($seen[$key])) {
                 $elements[] = "[{$key}]";
                 $seen[$key] = 1;
             }
         }
         $js .= implode(', ', $elements);
         $js .= "]";
         $js .= "\n                for (var i=0;i<nullArray.length;i++) {\n                    if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {\n                        {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';\n                    }\n                }\n";
     }
     if (!empty($noneArray)) {
         $js .= "var noneArray = [";
         $elements = array();
         $seen = array();
         foreach ($noneArray as $element) {
             $key = "{$element[0]}, {$element[1]}, {$element[2]}";
             if (!isset($seen[$key])) {
                 $elements[] = "[{$key}]";
                 $seen[$key] = 1;
             }
         }
         $js .= implode(', ', $elements);
         $js .= "]";
         $js .= "\n                for (var i=0;i<noneArray.length;i++) {\n                    if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {\n  {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';\n                    }\n                }\n";
     }
     $js .= "</script>\n";
     $form->assign('initHideBoxes', $js);
     $form->assign('columnCount', $columnCount);
     $form->assign('blockCount', $blockCount);
     $form->setDefaults($defaults);
     $form->setDefaultAction('refresh');
 }
 /**
  * class constructor which also does all the work
  *
  * @param array   $params
  * @param array   $returnProperties
  * @param array   $fields
  * @param boolean $includeContactIds
  * @param boolean $strict
  * @param boolean $mode - mode the search is operating on
  *
  * @return Object
  * @access public
  */
 function __construct($params = NULL, $returnProperties = NULL, $fields = NULL, $includeContactIds = FALSE, $strict = FALSE, $mode = 1, $skipPermission = FALSE, $searchDescendentGroups = TRUE, $smartGroupCache = TRUE, $displayRelationshipType = NULL, $operator = 'AND')
 {
     // CRM_Core_Error::backtrace( );
     // CRM_Core_Error::debug( 'params', $params );
     // CRM_Core_Error::debug( 'post', $_POST );
     // CRM_Core_Error::debug( 'r', $returnProperties );
     $this->_params =& $params;
     if ($this->_params == NULL) {
         $this->_params = array();
     }
     if (empty($returnProperties)) {
         $this->_returnProperties = self::defaultReturnProperties($mode);
     } else {
         $this->_returnProperties =& $returnProperties;
     }
     $this->_includeContactIds = $includeContactIds;
     $this->_strict = $strict;
     $this->_mode = $mode;
     $this->_skipPermission = $skipPermission;
     $this->_smartGroupCache = $smartGroupCache;
     $this->_displayRelationshipType = $displayRelationshipType;
     $this->setOperator($operator);
     if ($fields) {
         $this->_fields =& $fields;
         $this->_search = FALSE;
         $this->_skipPermission = TRUE;
     } else {
         $this->_fields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE, TRUE);
         $fields = CRM_Core_Component::getQueryFields();
         unset($fields['note']);
         $this->_fields = array_merge($this->_fields, $fields);
         // add activity fields
         $fields = CRM_Activity_BAO_Activity::exportableFields();
         $this->_fields = array_merge($this->_fields, $fields);
     }
     // basically do all the work once, and then reuse it
     $this->initialize();
 }
Example #5
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 #6
0
 public function testMergeHousehold()
 {
     $this->markTestSkipped('Skipping for now as it works fine locally.');
     $this->webtestLogin();
     // Create new  group
     $groupName = 'TestGroup_' . substr(sha1(rand()), 0, 7);
     $this->WebtestAddGroup($groupName);
     // Adding Parent group contact
     // We're using Quick Add block on the main page for this.
     $houseHold = 'H' . substr(sha1(rand()), 0, 5) . ' House';
     $this->openCiviPage("contact/add", "reset=1&ct=Household");
     $this->click('household_name');
     $this->type('household_name', $houseHold);
     //address section
     $this->click("addressBlock");
     $this->waitForElementPresent("address_1_street_address");
     // fill in address
     $this->click("//div[@id='addressBlockId']/div[1]");
     $this->type("address_1_street_address", "121A Sherman St. Apt. 12");
     $this->type("address_1_city", "Dumfries");
     $this->type("address_1_postal_code", "1234");
     $this->select("address_1_country_id", "United States");
     $this->select("address_1_state_province_id", "value=1019");
     $this->click('_qf_Contact_upload_view');
     $this->waitForPageToLoad($this->getTimeoutMsec());
     // Add contact to group
     // visit group tab.
     $this->click("css=li#tab_group a");
     $this->waitForElementPresent("group_id");
     // Add to group.
     $this->select("group_id", "label={$groupName}");
     $this->click("_qf_GroupContact_next");
     $this->waitForAjaxContent();
     $firstName1 = 'aa' . substr(sha1(rand()), 0, 5);
     $this->webtestAddContact($firstName1, "Smith", "{$firstName1}.smith@example.org");
     $sortName1 = "Smith, {$firstName1}";
     $displayName1 = "{$firstName1} Smith";
     // Add contact to parent  group
     // visit group tab.
     $this->click("css=li#tab_group a");
     $this->waitForElementPresent("group_id");
     // Add to group.
     $this->select("group_id", "label={$groupName}");
     $this->click("_qf_GroupContact_next");
     $this->waitForAjaxContent();
     $firstName2 = 'bb' . substr(sha1(rand()), 0, 5);
     $this->openCiviPage("contact/add", "reset=1&ct=Individual", "_qf_Contact_upload_view-bottom");
     $this->type('first_name', $firstName2);
     $this->type('last_name', "Smith");
     $this->type('email_1_email', "{$firstName2}.smith@example.org");
     //address section
     $this->click("addressBlock");
     $this->waitForElementPresent("address_1_street_address");
     $this->click("//div[@id='addressBlockId']/div[1]");
     $this->click("address[1][use_shared_address]");
     $this->waitForElementPresent("address_1_master_contact_id");
     $this->select2('address_1_master_contact_id', $houseHold);
     $this->waitForTextPresent("121A Sherman");
     $this->click('_qf_Contact_upload_view-bottom');
     $this->waitForPageToLoad($this->getTimeoutMsec());
     $sortName2 = "Smith, {$firstName2}";
     $displayName2 = "{$firstName2} Smith";
     // Add contact to parent  group
     // visit group tab.
     $this->click("css=li#tab_group a");
     $this->waitForElementPresent("group_id");
     // Add to group.
     $this->select("group_id", "label={$groupName}");
     $this->click("_qf_GroupContact_next");
     $this->waitForAjaxContent();
     $this->openCiviPage("contact/search", "reset=1", NULL);
     // Select group.
     $this->select("group", "label={$groupName}");
     // Click to search.
     $this->clickLink("_qf_Basic_refresh");
     // Is contact present in search result?
     $this->assertElementContainsText('css=div.crm-search-results', $sortName1, "Contact did not found in search result!");
     // Is contact present in search result?
     $this->assertElementContainsText('css=div.crm-search-results', $sortName2, "Contact did not found in search result!");
     // Is contact present in search result?
     $this->assertElementContainsText('css=div.crm-search-results', $houseHold, "Contact did not found in search result!");
     // select to export all the contasct from search result.
     $this->click("CIVICRM_QFID_ts_all_4");
     // Select the task action to export.
     $this->click("task");
     $this->select("task", "label=Export Contacts");
     $this->waitForPageToLoad($this->getTimeoutMsec());
     $this->click("CIVICRM_QFID_2_10");
     $csvFile = $this->downloadCSV("_qf_Select_next-bottom");
     // Build header row for assertion.
     require_once 'CRM/Contact/BAO/Contact.php';
     $expotableFields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE);
     $checkHeaders = array();
     foreach ($expotableFields as $key => $field) {
         // Exclude custom fields.
         if ($key && substr($key, 0, 6) == 'custom') {
             continue;
         }
         $checkHeaders[] = $field['title'];
     }
     // All other rows to be check.
     $checkRows = array(1 => array('Contact Type' => 'Household', 'Household Name' => $houseHold), 2 => array('Contact Type' => 'Individual', 'First Name' => $firstName1, 'Email' => "{$firstName1}.smith@example.org", 'Sort Name' => $sortName1, 'Display Name' => $displayName1));
     // Read CSV and fire assertions.
     $this->reviewCSV($csvFile, $checkHeaders, $checkRows, 2);
 }
 /**
  * different type of Contact Tokens
  *
  * @static
  * return array
  */
 static function &contactTokens()
 {
     static $tokens = null;
     if (!$tokens) {
         require_once 'CRM/Contact/BAO/Contact.php';
         require_once 'CRM/Core/BAO/CustomField.php';
         $additionalFields = array('checksum' => array('title' => ts('Checksum')), 'contact_id' => array('title' => ts('Internal Contact ID')));
         $exportFields = array_merge(CRM_Contact_BAO_Contact::exportableFields(), $additionalFields);
         $values = array_merge(array_keys($exportFields));
         unset($values[0]);
         //FIXME:skipping some tokens for time being.
         $skipTokens = array('is_bulkmail', 'group', 'tag', 'contact_sub_type', 'note', 'is_deceased', 'deceased_date', 'legal_identifier', 'contact_sub_type', 'user_unique_id');
         $customFields = array();
         $customFields = CRM_Core_BAO_CustomField::getFields('Individual');
         foreach ($values as $key => $val) {
             if (in_array($val, $skipTokens)) {
                 continue;
             }
             //keys for $tokens should be constant. $token Values are changed for Custom Fields. CRM-3734
             if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($val)) {
                 $tokens["{contact.{$val}}"] = $customFields[$customFieldId]['label'] . " :: " . $customFields[$customFieldId]['groupTitle'];
             } else {
                 $tokens["{contact.{$val}}"] = $exportFields[$val]['title'];
             }
         }
         // might as well get all the hook tokens to
         require_once 'CRM/Utils/Hook.php';
         $hookTokens = array();
         CRM_Utils_Hook::tokens($hookTokens);
         foreach ($hookTokens as $category => $tokenValues) {
             foreach ($tokenValues as $key => $value) {
                 if (is_numeric($key)) {
                     $key = $value;
                 }
                 if (!preg_match('/^\\{[^\\}]+\\}$/', $key)) {
                     $key = '{' . $key . '}';
                 }
                 if (preg_match('/^\\{([^\\}]+)\\}$/', $value, $matches)) {
                     $value = $matches[1];
                 }
                 $tokens[$key] = $value;
             }
         }
     }
     return $tokens;
 }
Example #8
0
 /**
  * Browse all CiviCRM Profile group fields.
  *
  * @return void
  */
 public function browse()
 {
     $resourceManager = CRM_Core_Resources::singleton();
     if (!empty($_GET['new']) && $resourceManager->ajaxPopupsEnabled) {
         $resourceManager->addScriptFile('civicrm', 'js/crm.addNew.js', 999, 'html-header');
     }
     $ufField = array();
     $ufFieldBAO = new CRM_Core_BAO_UFField();
     // fkey is gid
     $ufFieldBAO->uf_group_id = $this->_gid;
     $ufFieldBAO->orderBy('weight', 'field_name');
     $ufFieldBAO->find();
     $otherModules = CRM_Core_BAO_UFGroup::getUFJoinRecord($this->_gid);
     $this->assign('otherModules', $otherModules);
     $isGroupReserved = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'is_reserved');
     $this->assign('isGroupReserved', $isGroupReserved);
     $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
     if ($profileType == 'Contribution' || $profileType == 'Membership' || $profileType == 'Activity' || $profileType == 'Participant') {
         $this->assign('skipCreate', TRUE);
     }
     $locationType = array();
     $locationType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $fields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE);
     $fields = array_merge(CRM_Contribute_BAO_Contribution::getContributionFields(), $fields);
     $select = array();
     foreach ($fields as $name => $field) {
         if ($name) {
             $select[$name] = $field['title'];
         }
     }
     $select['group'] = ts('Group(s)');
     $select['tag'] = ts('Tag(s)');
     $visibility = CRM_Core_SelectValues::ufVisibility();
     while ($ufFieldBAO->fetch()) {
         $ufField[$ufFieldBAO->id] = array();
         $phoneType = $locType = '';
         CRM_Core_DAO::storeValues($ufFieldBAO, $ufField[$ufFieldBAO->id]);
         $ufField[$ufFieldBAO->id]['visibility_display'] = $visibility[$ufFieldBAO->visibility];
         $ufField[$ufFieldBAO->id]['label'] = $ufFieldBAO->label;
         $action = array_sum(array_keys($this->actionLinks()));
         if ($ufFieldBAO->is_active) {
             $action -= CRM_Core_Action::ENABLE;
         } else {
             $action -= CRM_Core_Action::DISABLE;
         }
         if ($ufFieldBAO->is_reserved) {
             $action -= CRM_Core_Action::UPDATE;
             $action -= CRM_Core_Action::DISABLE;
             $action -= CRM_Core_Action::DELETE;
         }
         $ufField[$ufFieldBAO->id]['order'] = $ufField[$ufFieldBAO->id]['weight'];
         $ufField[$ufFieldBAO->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $ufFieldBAO->id, 'gid' => $this->_gid), ts('more'), FALSE, 'ufField.row.actions', 'UFField', $ufFieldBAO->id);
     }
     $returnURL = CRM_Utils_System::url('civicrm/admin/uf/group/field', "reset=1&action=browse&gid={$this->_gid}");
     $filter = "uf_group_id = {$this->_gid}";
     CRM_Utils_Weight::addOrder($ufField, 'CRM_Core_DAO_UFField', 'id', $returnURL, $filter);
     $this->assign('ufField', $ufField);
     // retrieve showBestResult from session
     $session = CRM_Core_Session::singleton();
     $showBestResult = $session->get('showBestResult');
     $this->assign('showBestResult', $showBestResult);
     $session->set('showBestResult', 0);
 }
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;
 }
 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 #11
0
 /**
  * class constructor which also does all the work
  *
  * @param array   $params
  * @param array   $returnProperties
  * @param array   $fields
  * @param boolean $includeContactIds
  * @param boolean $strict
  * @param boolean $mode - mode the search is operating on
  *
  * @return Object
  * @access public
  */
 function __construct($params = null, $returnProperties = null, $fields = null, $includeContactIds = false, $strict = false, $mode = 1, $skipPermission = false, $searchDescendentGroups = true, $smartGroupCache = true)
 {
     require_once 'CRM/Contact/BAO/Contact.php';
     // CRM_Core_Error::backtrace( );
     // CRM_Core_Error::debug_var( 'params', $params );
     // CRM_Core_Error::debug( 'post', $_POST );
     // CRM_Core_Error::debug( 'r', $returnProperties );
     $this->_params =& $params;
     if ($this->_params == null) {
         $this->_params = array();
     }
     if (empty($returnProperties)) {
         $this->_returnProperties =& self::defaultReturnProperties($mode);
     } else {
         $this->_returnProperties =& $returnProperties;
     }
     $this->_includeContactIds = $includeContactIds;
     $this->_strict = $strict;
     $this->_mode = $mode;
     $this->_skipPermission = $skipPermission;
     $this->_smartGroupCache = $smartGroupCache;
     if ($fields) {
         $this->_fields =& $fields;
         $this->_search = false;
         $this->_skipPermission = true;
     } else {
         require_once 'CRM/Contact/BAO/Contact.php';
         $this->_fields = CRM_Contact_BAO_Contact::exportableFields('All', false, true);
         require_once 'CRM/Core/Component.php';
         $fields =& CRM_Core_Component::getQueryFields();
         unset($fields['note']);
         $this->_fields = array_merge($this->_fields, $fields);
         // add activity fields
         require_once 'CRM/Activity/BAO/Activity.php';
         $fields = CRM_Activity_BAO_Activity::exportableFields();
         $this->_fields = array_merge($this->_fields, $fields);
     }
     // basically do all the work once, and then reuse it
     $this->initialize();
     // CRM_Core_Error::debug( $this );
 }
Example #12
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 #13
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;
 }
Example #14
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  $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
  *
  * @static
  * @access 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)
 {
     $headerRows = $returnProperties = array();
     $primary = $paymentFields = false;
     $origFields = $fields;
     $queryMode = null;
     $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;
         case CRM_Export_Form_Select::ACTIVITY_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_ACTIVITY;
             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 = $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 = 'Primary';
                     }
                     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) && is_numeric($relLocTypeId)) {
                     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;
                 if ($returnProperties['participant_role']) {
                     unset($returnProperties['participant_role']);
                     $returnProperties['participant_role_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 {
                                 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
                                     $returnProperties['activity_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 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) {
         $drop = false;
         //make sure the addressee fields are selected
         //while using merge same address feature
         $returnProperties['addressee'] = 1;
         $returnProperties['street_name'] = 1;
         if (!CRM_Utils_Array::value('last_name', $returnProperties)) {
             $returnProperties['last_name'] = 1;
             $drop = 'last_name';
         }
         $returnProperties['household_name'] = 1;
         $returnProperties['street_address'] = 1;
     }
     if ($moreReturnProperties) {
         // fix for CRM-7066
         if (CRM_Utils_Array::value('group', $moreReturnProperties)) {
             unset($moreReturnProperties['group']);
             $moreReturnProperties['groups'] = 1;
         }
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $query = new CRM_Contact_BAO_Query(0, $returnProperties, null, false, false, $queryMode);
     list($select, $from, $where) = $query->query();
     if ($mergeSameHousehold == 1) {
         if (!$returnProperties['id']) {
             $returnProperties['id'] = 1;
             $setId = true;
         } else {
             $setId = false;
         }
         $relationKey = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
         foreach ($returnProperties as $key => $value) {
             if (!array_key_exists($key, $contactRelationshipTypes)) {
                 $returnProperties[$relationKey][$key] = $value;
             }
         }
         unset($returnProperties[$relationKey]['location_type']);
         unset($returnProperties[$relationKey]['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(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';
             }
             if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
                 $relIDs = $ids;
             } else {
                 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
                     $query = "SELECT source_contact_id FROM civicrm_activity\n                              WHERE id IN ( " . implode(',', $ids) . ")";
                     $dao = CRM_Core_DAO::executeQuery($query);
                     while ($dao->fetch()) {
                         $relIDs[] = $dao->source_contact_id;
                     }
                 } else {
                     switch ($exportMode) {
                         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
                             $component = 'civicrm_contribution';
                             break;
                         case CRM_Export_Form_Select::EVENT_EXPORT:
                             $component = 'civicrm_participant';
                             break;
                         case CRM_Export_Form_Select::MEMBER_EXPORT:
                             $component = 'civicrm_membership';
                             break;
                         case CRM_Export_Form_Select::PLEDGE_EXPORT:
                             $component = 'civicrm_pledge';
                             break;
                         case CRM_Export_Form_Select::CASE_EXPORT:
                             $component = 'civicrm_case';
                             break;
                         case CRM_Export_Form_Select::GRANT_EXPORT:
                             $component = 'civicrm_grant';
                             break;
                     }
                     $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
                 }
             }
             $relationshipJoin = $relationshipClause = '';
             if ($componentTable) {
                 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
             } else {
                 $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} ";
             $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause}";
             $relationGroupBy = " GROUP BY crel.{$contactA}";
             $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
             $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere} {$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 (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 ($componentTable) {
         $from .= " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = contact_a.id ";
     } else {
         if ($componentClause) {
             if (empty($where)) {
                 $where = "WHERE {$componentClause}";
             } else {
                 $where .= " AND {$componentClause}";
             }
         }
     }
     $queryString = "{$select} {$from} {$where}";
     $groupBy = "";
     if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties) || CRM_Utils_Array::value('notes', $returnProperties) || $query->_useGroupBy) {
         $groupBy = " GROUP BY contact_a.id";
     }
     if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
         $groupBy = " GROUP BY civicrm_activity.id ";
     }
     $queryString .= $groupBy;
     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);
     }
     $header = $addPaymentHeader = false;
     if ($paymentFields) {
         //special return properties for event and members
         $paymentHeaders = array('total_amount' => ts('Total Amount'), 'contribution_status' => ts('Contribution Status'), 'received_date' => ts('Received Date'), 'payment_instrument' => ts('Payment Instrument'), 'transaction_id' => 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);
         if (!empty($paymentDetails)) {
             $addPaymentHeader = true;
         }
         $nullContributionDetails = array_fill_keys($paymentHeaders, null);
     }
     $componentDetails = $headerRows = $sqlColumns = array();
     $setHeader = true;
     $rowCount = self::EXPORT_ROW_COUNT;
     $offset = 0;
     $count = -1;
     // for CRM-3157 purposes
     require_once 'CRM/Core/I18n.php';
     $i18n =& CRM_Core_I18n::singleton();
     while (1) {
         $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
         $dao = CRM_Core_DAO::executeQuery($limitQuery);
         if ($dao->N <= 0) {
             break;
         }
         while ($dao->fetch()) {
             $count++;
             $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) {
                     $sqlDone = false;
                     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;
                                             self::sqlColumnDefn($query, $sqlColumns, $hdr);
                                         }
                                         $sqlDone = true;
                                     }
                                 } 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 = $field;
                                             foreach ($value as $relationField => $relationValue) {
                                                 // below block is same as primary block (duplicate)
                                                 if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
                                                     $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['title'];
                                                     $headerRows[] = $headerName;
                                                     self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                                 } else {
                                                     if ($relationField == 'phone_type_id') {
                                                         $headerName = $field . '-' . 'Phone Type';
                                                         $headerRows[] = $headerName;
                                                         self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                                     } else {
                                                         if ($relationField == 'provider_id') {
                                                             $headerName = $field . '-' . 'Im Service Provider';
                                                             $headerRows[] = $headerName;
                                                             self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                                         } 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);
                                                                                 }
                                                                             }
                                                                         }
                                                                         $headerName = $field . '-' . $hdr;
                                                                         $headerRows[] = $headerName;
                                                                         self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         } else {
                                             $headerRows[] = $field;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                     if (!$sqlDone) {
                         self::sqlColumnDefn($query, $sqlColumns, $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 {
                             if ($field == 'participant_role_id') {
                                 require_once 'CRM/Event/PseudoConstant.php';
                                 $participantRoles = CRM_Event_PseudoConstant::participantRole();
                                 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
                                 $viewRoles = array();
                                 foreach (explode($sep, $dao->{$field}) as $k => $v) {
                                     $viewRoles[] = $participantRoles[$v];
                                 }
                                 $fieldValue = implode(',', $viewRoles);
                             }
                         }
                     }
                 } else {
                     if ($field == 'master_address_belongs_to') {
                         $masterAddressId = null;
                         if (isset($dao->master_id)) {
                             $masterAddressId = $dao->master_id;
                         }
                         // get display name of contact that address is shared.
                         $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $dao->contact_id);
                     } 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];
                                         }
                                         // 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($dao->{$fldValue}, array('context' => 'country'));
                                                 break;
                                             case 'state_province':
                                                 $row[$fldValue] = $i18n->crm_translate($dao->{$fldValue}, array('context' => 'province'));
                                                 break;
                                             default:
                                                 $row[$fldValue] = $dao->{$fldValue};
                                                 break;
                                         }
                                     }
                                 }
                             } 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];
                                                         }
                                                         // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                                                         switch (true) {
                                                             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;
                                                         }
                                                     }
                                                 }
                                             } 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
                                                             // 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] = '';
                                                 }
                                             }
                                         }
                                     }
                                 } 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 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':
                                                             $row[$field] = $i18n->crm_translate($fieldValue);
                                                             break;
                                                         default:
                                                             $row[$field] = $fieldValue;
                                                             break;
                                                     }
                                                 }
                                             }
                                         }
                                     } else {
                                         // if field is empty or null
                                         $row[$field] = '';
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             // add payment headers if required
             if ($addPaymentHeader && $paymentFields) {
                 $headerRows = array_merge($headerRows, $paymentHeaders);
                 foreach ($paymentHeaders as $paymentHdr) {
                     self::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
                 }
                 $addPaymentHeader = false;
             }
             if ($setHeader) {
                 $exportTempTable = self::createTempTable($sqlColumns);
             }
             //build header only once
             $setHeader = false;
             // add payment related information
             if ($paymentFields && isset($paymentDetails[$row[$paymentTableId]])) {
                 $row = array_merge($row, $paymentDetails[$row[$paymentTableId]]);
             } else {
                 if ($paymentDetails) {
                     $row = array_merge($row, $nullContributionDetails);
                 }
             }
             //remove organization name for individuals if it is set for current employer
             if (CRM_Utils_Array::value('contact_type', $row) && $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 $rowCount rows
             if ($count % $rowCount == 0) {
                 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
                 $componentDetails = array();
             }
         }
         $dao->free();
         $offset += $rowCount;
     }
     self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
     // do merge same address and merge same household processing
     if ($mergeSameAddress) {
         self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $drop);
     }
     // merge the records if they have corresponding households
     if ($mergeSameHousehold) {
         self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKey);
     }
     // fix the headers for rows with relationship type
     if ($relName) {
         self::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
     }
     // call export hook
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
     // now write the CSV file
     self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
     CRM_Utils_System::civiExit();
 }
Example #15
0
 /**
  * Class constructor which also does all the work.
  *
  * @param array $params
  * @param array $returnProperties
  * @param array $fields
  * @param bool $includeContactIds
  * @param bool $strict
  * @param bool|int $mode - mode the search is operating on
  *
  * @param bool $skipPermission
  * @param bool $searchDescendentGroups
  * @param bool $smartGroupCache
  * @param null $displayRelationshipType
  * @param string $operator
  *
  * @return \CRM_Contact_BAO_Query
  */
 public function __construct($params = NULL, $returnProperties = NULL, $fields = NULL, $includeContactIds = FALSE, $strict = FALSE, $mode = 1, $skipPermission = FALSE, $searchDescendentGroups = TRUE, $smartGroupCache = TRUE, $displayRelationshipType = NULL, $operator = 'AND')
 {
     $this->_params =& $params;
     if ($this->_params == NULL) {
         $this->_params = array();
     }
     if (empty($returnProperties)) {
         $this->_returnProperties = self::defaultReturnProperties($mode);
     } else {
         $this->_returnProperties =& $returnProperties;
     }
     $this->_includeContactIds = $includeContactIds;
     $this->_strict = $strict;
     $this->_mode = $mode;
     $this->_skipPermission = $skipPermission;
     $this->_smartGroupCache = $smartGroupCache;
     $this->_displayRelationshipType = $displayRelationshipType;
     $this->setOperator($operator);
     if ($fields) {
         $this->_fields =& $fields;
         $this->_search = FALSE;
         $this->_skipPermission = TRUE;
     } else {
         $this->_fields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE, TRUE, FALSE, !$skipPermission);
         $fields = CRM_Core_Component::getQueryFields(!$this->_skipPermission);
         unset($fields['note']);
         $this->_fields = array_merge($this->_fields, $fields);
         // add activity fields
         $fields = CRM_Activity_BAO_Activity::exportableFields();
         $this->_fields = array_merge($this->_fields, $fields);
         // add any fields provided by hook implementers
         $extFields = CRM_Contact_BAO_Query_Hook::singleton()->getFields();
         $this->_fields = array_merge($this->_fields, $extFields);
     }
     // basically do all the work once, and then reuse it
     $this->initialize();
 }
Example #16
0
 public function getContactTokenReplacement($token, &$contact, $html = false, $returnBlankToken = false)
 {
     if (self::$_tokens['contact'] == null) {
         /* This should come from UF */
         self::$_tokens['contact'] = array_merge(array_keys(CRM_Contact_BAO_Contact::exportableFields('All')), array('checksum', 'contact_id'));
     }
     /* Construct value from $token and $contact */
     $value = null;
     // check if the token we were passed is valid
     // we have to do this because this function is
     // called only when we find a token in the string
     if (!in_array($token, self::$_tokens['contact'])) {
         $value = "{contact.{$token}}";
     } else {
         if ($token == 'checksum') {
             require_once 'CRM/Contact/BAO/Contact/Utils.php';
             $cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($contact['contact_id']);
             $value = "cs={$cs}";
         } else {
             $value = CRM_Utils_Array::retrieveValueRecursive($contact, $token);
         }
     }
     if (!$html) {
         $value = str_replace('&amp;', '&', $value);
     }
     // if null then return actual token
     if ($returnBlankToken && !$value) {
         $value = "{contact.{$token}}";
     }
     return $value;
 }
Example #17
0
 /**
  * class constructor which also does all the work
  *
  * @param array   $params
  * @param array   $returnProperties
  * @param array   $fields
  * @param boolean $includeContactIds
  * @param boolean $strict
  * @param boolean $mode - mode the search is operating on
  *
  * @return Object
  * @access public
  */
 function CRM_Contact_BAO_Query($params = null, $returnProperties = null, $fields = null, $includeContactIds = false, $strict = false, $mode = 1)
 {
     require_once 'CRM/Contact/BAO/Contact.php';
     //CRM_Core_Error::debug( 'params', $params );
     //CRM_Core_Error::debug( 'post', $_POST );
     $this->_params =& $params;
     if (empty($returnProperties)) {
         $this->_returnProperties =& CRM_Contact_BAO_Query::defaultReturnProperties($mode);
     } else {
         $this->_returnProperties =& $returnProperties;
     }
     $this->_includeContactIds = $includeContactIds;
     $this->_strict = $strict;
     $this->_mode = $mode;
     if ($fields) {
         $this->_fields =& $fields;
         $this->_search = false;
     } else {
         require_once 'CRM/Contact/BAO/Contact.php';
         $this->_fields = CRM_Contact_BAO_Contact::exportableFields('All', false, true);
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $fields = CRM_Contribute_BAO_Contribution::exportableFields();
         unset($fields['contact_id']);
         unset($fields['note']);
         $this->_fields = array_merge($this->_fields, $fields);
     }
     // basically do all the work once, and then reuse it
     $this->initialize();
     // CRM_Core_Error::debug( 'q', $this );
 }
 /**
  * Class constructor which also does all the work.
  *
  * @param array $params
  * @param array $returnProperties
  * @param array $fields
  * @param bool $includeRelationshipIds
  * @param bool $strict
  *
  * @param bool $skipPermission
  * @param string $operator
  *
  * @return \CRM_Relationship_BAO_Query
  */
 public function __construct($params = NULL, $returnProperties = NULL, $fields = NULL, $includeRelationshipIds = FALSE, $strict = FALSE, $mode = 1, $skipPermission = FALSE, $operator = 'AND')
 {
     $this->_params =& $params;
     if ($this->_params == NULL) {
         $this->_params = array();
     }
     if (empty($returnProperties)) {
         $this->_returnProperties = self::defaultReturnProperties($mode);
     } else {
         $this->_returnProperties =& $returnProperties;
     }
     $this->_includeRelationshipIds = $includeRelationshipIds;
     $this->_strict = $strict;
     $this->_mode = $mode;
     $this->_skipPermission = $skipPermission;
     //$this->setOperator($operator);
     if ($fields) {
         $this->_fields =& $fields;
         $this->_search = FALSE;
         $this->_skipPermission = TRUE;
     } else {
         $this->_fields = CRM_Contact_BAO_Relationship::fields();
         foreach ($this->_fields as $defaultFieldKey => $defaultField) {
             $this->_fields[$defaultFieldKey]['where'] = 'relationship.' . $defaultFieldKey;
         }
         // Add display_name for both contacts
         $contact_fields = CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE, TRUE);
         $this->_fields['contact_a'] = $contact_fields['display_name'];
         $this->_fields['contact_a']['where'] = 'contact_a.display_name';
         $this->_fields['contact_b'] = $contact_fields['display_name'];
         $this->_fields['contact_b']['where'] = 'contact_b.display_name';
         // Add relationship type field
         $relationship_type_fields = CRM_Contact_BAO_RelationshipType::fields();
         $this->_fields['relationship_type'] = $relationship_type_fields['label_a_b'];
         $this->_fields['relationship_type']['where'] = 'relationship_type.label_a_b';
         // Add custom fields
         $this->_fields = array_merge($this->_fields, CRM_Core_BAO_CustomField::getFieldsForImport('Relationship'));
     }
     // basically do all the work once, and then reuse it
     $this->initialize();
 }
Example #19
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;
 }
Example #20
0
 /**
  * Browse all CiviCRM Profile group fields.
  *
  * @return void
  * @access public
  * @static
  */
 function browse()
 {
     $ufField = array();
     $ufFieldBAO = new CRM_Core_BAO_UFField();
     // fkey is gid
     $ufFieldBAO->uf_group_id = $this->_gid;
     $ufFieldBAO->orderBy('weight', 'field_name');
     $ufFieldBAO->find();
     require_once "CRM/Core/BAO/UFField.php";
     $profileType = CRM_Core_BAO_UFField::getProfileType($this->_gid);
     if ($profileType == 'Contribution' || $profileType == 'Membership' || $profileType == 'Activity' || $profileType == 'Participant') {
         $this->assign('skipCreate', true);
     }
     $locationType = array();
     $locationType =& CRM_Core_PseudoConstant::locationType();
     require_once 'CRM/Contact/BAO/Contact.php';
     $fields =& CRM_Contact_BAO_Contact::exportableFields('All', false, true);
     require_once "CRM/Contribute/BAO/Contribution.php";
     $fields = array_merge(CRM_Contribute_BAO_Contribution::getContributionFields(), $fields);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $fields = array_merge(CRM_Quest_BAO_Student::exportableFields(), $fields);
     }
     $select = array();
     foreach ($fields as $name => $field) {
         if ($name) {
             $select[$name] = $field['title'];
         }
     }
     $select['group'] = ts('Group(s)');
     $select['tag'] = ts('Tag(s)');
     while ($ufFieldBAO->fetch()) {
         $ufField[$ufFieldBAO->id] = array();
         $phoneType = $locType = '';
         CRM_Core_DAO::storeValues($ufFieldBAO, $ufField[$ufFieldBAO->id]);
         CRM_Core_DAO_UFField::addDisplayEnums($ufField[$ufFieldBAO->id]);
         $ufField[$ufFieldBAO->id]['label'] = $ufFieldBAO->label;
         $action = array_sum(array_keys($this->actionLinks()));
         if ($ufFieldBAO->is_active) {
             $action -= CRM_Core_Action::ENABLE;
         } else {
             $action -= CRM_Core_Action::DISABLE;
         }
         if ($ufFieldBAO->is_reserved) {
             $action -= CRM_Core_Action::UPDATE;
             $action -= CRM_Core_Action::DISABLE;
             $action -= CRM_Core_Action::DELETE;
         }
         $ufField[$ufFieldBAO->id]['order'] = $ufField[$ufFieldBAO->id]['weight'];
         $ufField[$ufFieldBAO->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $ufFieldBAO->id, 'gid' => $this->_gid));
     }
     $returnURL = CRM_Utils_System::url('civicrm/admin/uf/group/field', "reset=1&action=browse&gid={$this->_gid}");
     $filter = "uf_group_id = {$this->_gid}";
     require_once 'CRM/Utils/Weight.php';
     CRM_Utils_Weight::addOrder($ufField, 'CRM_Core_DAO_UFField', 'id', $returnURL, $filter);
     $this->assign('ufField', $ufField);
     // retrieve showBestResult from session
     $session = CRM_Core_Session::singleton();
     $showBestResult = $session->get('showBestResult');
     $this->assign('showBestResult', $showBestResult);
     $session->set('showBestResult', 0);
 }
Example #21
0
 static function fields()
 {
     $fields = array_merge(CRM_Contact_BAO_Contact::exportableFields('All', FALSE, TRUE), CRM_Core_Component::getQueryFields(), CRM_Contact_BAO_Query_Hook::singleton()->getFields(), CRM_Activity_BAO_Activity::exportableFields());
     return $fields;
 }
Example #22
0
 /**
  * global validation rules for the form
  *
  * @param array $fields posted values of the form
  *
  * @return array list of errors to be posted back to the form
  * @static
  * @access public
  */
 static function formRule(&$values)
 {
     //CRM_Core_Error::debug('s', $values);
     if (CRM_Utils_Array::value('addMore', $values) || CRM_Utils_Array::value('addBlock', $values)) {
         return true;
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     $fields = array();
     $fields = CRM_Contact_BAO_Contact::exportableFields('All', false, true);
     require_once 'CRM/Core/Component.php';
     $compomentFields =& CRM_Core_Component::getQueryFields();
     $fields = array_merge($fields, $compomentFields);
     $fld = array();
     $fld = CRM_Core_BAO_Mapping::formattedFields($values, true);
     require_once 'CRM/Utils/Type.php';
     $errorMsg = array();
     foreach ($fld as $k => $v) {
         if (!$v[1]) {
             $errorMsg["operator[{$v['3']}][{$v['4']}]"] = ts("Please enter the operator.");
         } else {
             if (in_array($v[1], array('IS NULL', 'IS NOT NULL')) && $v[2]) {
                 $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts('Please clear your value if you want to use %1 operator.', array(1 => $v[1]));
             } else {
                 if ($v[0] == 'group' || $v[0] == 'tag') {
                     $grpId = array_keys($v[2]);
                     if (!key($v[2])) {
                         $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the value.");
                     }
                     if (count($grpId) > 1) {
                         if ($v[1] != 'IN' && $v[1] != 'NOT IN') {
                             $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the valid value.");
                         }
                         foreach ($grpId as $val) {
                             $error = CRM_Utils_Type::validate($val, 'Integer', false);
                             if ($error != $val) {
                                 $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter valid value.");
                                 break;
                             }
                         }
                     } else {
                         $error = CRM_Utils_Type::validate($grpId[0], 'Integer', false);
                         if ($error != $grpId[0]) {
                             $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts('Please enter valid %1 id.', array(1 => $v[0]));
                         }
                     }
                 } else {
                     if (substr($v[0], 0, 7) === 'do_not_' or substr($v[0], 0, 3) === 'is_') {
                         if ($v[2]) {
                             $v2 = array($v[2]);
                             if (!isset($v[2])) {
                                 $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the value.");
                             }
                             $error = CRM_Utils_Type::validate($v2[0], 'Integer', false);
                             if ($error != $v2[0]) {
                                 $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter valid value.");
                             }
                         } else {
                             $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the value.");
                         }
                     } else {
                         if ($v[0] === 'sort_name' || $v[0] === 'display_name') {
                             $v2 = trim($v[2]);
                             if (empty($v2)) {
                                 $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the value.");
                             }
                         } else {
                             if (substr($v[0], 0, 7) == 'custom_') {
                                 $type = $fields[$v[0]]['data_type'];
                                 // hack to handle custom data of type state and country
                                 if (in_array($type, array('Country', 'StateProvince'))) {
                                     $type = "Integer";
                                 }
                             } else {
                                 $fldName = $v[0];
                                 // FIXME: no idea at this point what to do with this,
                                 // FIXME: but definitely needs fixing.
                                 if (substr($v[0], 0, 13) == 'contribution_') {
                                     $fldName = substr($v[0], 13);
                                 }
                                 $fldType = CRM_Utils_Array::value('type', $fields[$fldName]);
                                 $type = CRM_Utils_Type::typeToString($fldType);
                                 // Check Empty values for Integer Or Boolean Or Date type For operators other than IS NULL and IS NOT NULL.
                                 if (!in_array($v[1], array('IS NULL', 'IS NOT NULL'))) {
                                     if (($type == 'Int' || $type == 'Boolean') && !trim($v[2]) && $v[2] != '0') {
                                         $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the value.");
                                     } else {
                                         if ($type == 'Date' && !trim($v[2])) {
                                             $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the value.");
                                         }
                                     }
                                 }
                             }
                             if ($type && empty($errorMsg)) {
                                 // check for valid format while using IN Operator
                                 if ($v[1] == 'IN') {
                                     $inVal = trim($v[2]);
                                     //checking for format to avoid db errors
                                     if (!preg_match('/^[(]([A-Za-z0-9\'\\,]+)[)]$/', $inVal)) {
                                         $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter correct Data ( in valid format ).");
                                     }
                                     // Validate each value in parenthesis to avoid db errors
                                     if (empty($errorMsg)) {
                                         $parenValues = array();
                                         $parenValues = explode(',', trim($inVal, "(..)"));
                                         foreach ($parenValues as $val) {
                                             if (!$val && $val != '0') {
                                                 $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter the values correctly.");
                                             }
                                             if (empty($errorMsg)) {
                                                 $error = CRM_Utils_Type::validate($val, $type, false);
                                                 if ($error != $val) {
                                                     $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter valid value.");
                                                 }
                                             }
                                         }
                                     }
                                 } else {
                                     if (trim($v[2])) {
                                         //else check value for rest of the Operators
                                         $error = CRM_Utils_Type::validate($v[2], $type, false);
                                         if ($error != $v[2]) {
                                             $errorMsg["value[{$v['3']}][{$v['4']}]"] = ts("Please enter valid value.");
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if (!empty($errorMsg)) {
         return $errorMsg;
     }
     return true;
 }
Example #23
0
 /**
  * Test case for createProfileContact.
  */
 public function testCreateProfileContact()
 {
     $fields = CRM_Contact_BAO_Contact::exportableFields('Individual');
     //current employer field for individual
     $fields['organization_name'] = array('name' => 'organization_name', 'where' => 'civicrm_organization.organization_name', 'title' => 'Current Employer');
     //get the common params
     $contactParams = $this->contactParams();
     $unsetParams = array('location', 'privacy');
     foreach ($unsetParams as $param) {
         unset($contactParams[$param]);
     }
     $profileParams = array('organization_name' => 'Yahoo', 'gender_id' => '2', 'prefix_id' => '3', 'suffix_id' => '2', 'city-Primary' => 'Newark', 'contact_type' => 'Individual', 'country-Primary' => '1228', 'do_not_email' => '1', 'do_not_mail' => '1', 'do_not_phone' => '1', 'do_not_trade' => '1', 'do_not_sms' => '1', 'email-Primary' => '*****@*****.**', 'geo_code_1-Primary' => '18.219023', 'geo_code_2-Primary' => '-105.00973', 'im-Primary-provider_id' => '1', 'im-Primary' => 'john.smith', 'on_hold' => '1', 'openid' => '*****@*****.**', 'phone-Primary-1' => '303443689', 'phone-Primary-2' => '9833910234', 'postal_code-Primary' => '01903', 'postal_code_suffix-Primary' => '12345', 'state_province-Primary' => '1029', 'street_address-Primary' => 'Saint Helier St', 'supplemental_address_1-Primary' => 'Hallmark Ct', 'supplemental_address_2-Primary' => 'Jersey Village', 'user_unique_id' => '123456789', 'is_bulkmail' => '1', 'world_region' => 'India', 'tag' => array('3' => '1', '4' => '1', '1' => '1'));
     $createParams = array_merge($contactParams, $profileParams);
     //create the contact using create profile contact.
     $contactId = CRM_Contact_BAO_Contact::createProfileContact($createParams, $fields, NULL, NULL, NULL, NULL, TRUE);
     //get the parameters to compare.
     $params = $this->contactParams();
     //check the values in DB.
     foreach ($params as $key => $val) {
         if (!is_array($params[$key])) {
             if ($key == 'contact_source') {
                 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'source', 'id', $params[$key], "Check for {$key} creation.");
             } else {
                 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $params[$key], "Check for {$key} creation.");
             }
         }
     }
     //check privacy options.
     foreach ($params['privacy'] as $key => $value) {
         $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $params['privacy'][$key], 'Check for do_not_email creation.');
     }
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'contact_type', 'id', $profileParams['contact_type'], 'Check for contact type creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'user_unique_id', 'id', $profileParams['user_unique_id'], 'Check for user_unique_id creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'birth_date', 'id', $params['birth_date'], 'Check for birth_date creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'deceased_date', 'id', $params['deceased_date'], 'Check for deceased_date creation.');
     $dbPrefComm = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'preferred_communication_method', 'id', TRUE));
     $checkPrefComm = array();
     foreach ($dbPrefComm as $key => $value) {
         if ($value) {
             $checkPrefComm[$value] = 1;
         }
     }
     $this->assertAttributesEquals($checkPrefComm, $params['preferred_communication_method']);
     //Now check DB for Address
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1);
     $compareParams = array('street_address' => CRM_Utils_Array::value('street_address-Primary', $profileParams), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1-Primary', $profileParams), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2-Primary', $profileParams), 'city' => CRM_Utils_Array::value('city-Primary', $profileParams), 'postal_code' => CRM_Utils_Array::value('postal_code-Primary', $profileParams), 'country_id' => CRM_Utils_Array::value('country-Primary', $profileParams), 'state_province_id' => CRM_Utils_Array::value('state_province-Primary', $profileParams), 'geo_code_1' => CRM_Utils_Array::value('geo_code_1-Primary', $profileParams), 'geo_code_2' => CRM_Utils_Array::value('geo_code_2-Primary', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Address', $searchParams, $compareParams);
     //Now check DB for Email
     $compareParams = array('email' => CRM_Utils_Array::value('email-Primary', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Email', $searchParams, $compareParams);
     //Now check DB for IM
     $compareParams = array('name' => CRM_Utils_Array::value('im-Primary', $profileParams), 'provider_id' => CRM_Utils_Array::value('im-Primary-provider_id', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_IM', $searchParams, $compareParams);
     //Now check DB for Phone
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1);
     $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-1', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams);
     //Now check DB for Mobile
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'phone_type_id' => CRM_Utils_Array::value('phone_type_id', $params['phone'][2]));
     $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-2', $profileParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams);
     //get the value of relationship
     $values = array();
     $searchParams = array('contact_id' => $contactId);
     $relationship = CRM_Contact_BAO_Relationship::getValues($searchParams, $values);
     //Now check values of Relationship Count.
     $this->assertEquals(0, $values['relationship']['totalCount'], 'Check for total relationship count');
     foreach ($values['relationship']['data'] as $key => $val) {
         //Now check values of Relationship organization.
         $this->assertEquals($profileParams['organization_name'], $val['name'], 'Check for organization');
         //Now check values of Relationship type.
         $this->assertEquals('Employee of', $val['relation'], 'Check for relationship type');
         //delete the organization.
         $this->contactDelete(CRM_Utils_Array::value('cid', $val));
     }
     //Now check values of tag ids.
     $tags = CRM_Core_BAO_EntityTag::getTag($contactId);
     foreach ($tags as $key => $val) {
         $tagIds[$key] = 1;
     }
     $this->assertAttributesEquals($profileParams['tag'], $tagIds);
     //update Contact mode
     $updateCParams = array('first_name' => 'john', 'last_name' => 'doe', 'contact_type' => 'Individual', 'middle_name' => 'abc', 'prefix_id' => 2, 'suffix_id' => 3, 'nick_name' => 'Nick Name Updated', 'job_title' => 'software Developer', 'gender_id' => 1, 'is_deceased' => 1, 'website' => array(1 => array('website_type_id' => 1, 'url' => 'http://civicrmUpdate.org')), 'contact_source' => 'test contact', 'external_identifier' => 111222333, 'preferred_mail_format' => 'Both', 'is_opt_out' => 0, 'legal_identifier' => '123123123123', 'image_URL' => 'http://imageupdate.com', 'deceased_date' => '1981-10-10', 'birth_date' => '1951-11-11', 'privacy' => array('do_not_phone' => 1, 'do_not_email' => 1), 'preferred_communication_method' => array('1' => 0, '2' => 1, '3' => 0, '4' => 1, '5' => 0));
     $updatePfParams = array('organization_name' => 'Google', 'city-Primary' => 'Mumbai', 'contact_type' => 'Individual', 'country-Primary' => '1228', 'do_not_email' => '1', 'do_not_mail' => '1', 'do_not_phone' => '1', 'do_not_trade' => '1', 'do_not_sms' => '1', 'email-Primary' => '*****@*****.**', 'geo_code_1-Primary' => '31.694842', 'geo_code_2-Primary' => '-106.29998', 'im-Primary-provider_id' => '1', 'im-Primary' => 'john.doe', 'on_hold' => '1', 'openid' => '*****@*****.**', 'phone-Primary-1' => '02115245336', 'phone-Primary-2' => '9766323895', 'postal_code-Primary' => '12345', 'postal_code_suffix-Primary' => '123', 'state_province-Primary' => '1004', 'street_address-Primary' => 'Oberoi Garden', 'supplemental_address_1-Primary' => 'A-wing:3037', 'supplemental_address_2-Primary' => 'Andhery', 'user_unique_id' => '1122334455', 'is_bulkmail' => '1', 'world_region' => 'India', 'tag' => array('2' => '1', '5' => '1'));
     $createParams = array_merge($updateCParams, $updatePfParams);
     //create the contact using create profile contact.
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($createParams, $fields, $contactId, NULL, NULL, NULL, TRUE);
     //check the contact ids
     $this->assertEquals($contactId, $contactID, 'check for Contact ids');
     //check the values in DB.
     foreach ($updateCParams as $key => $val) {
         if (!is_array($updateCParams[$key])) {
             if ($key == 'contact_source') {
                 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'source', 'id', $updateCParams[$key], "Check for {$key} creation.");
             } else {
                 $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $updateCParams[$key], "Check for {$key} creation.");
             }
         }
     }
     //check privacy options.
     foreach ($updateCParams['privacy'] as $key => $value) {
         $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, $key, 'id', $updateCParams['privacy'][$key], 'Check for do_not_email creation.');
     }
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'contact_type', 'id', $updatePfParams['contact_type'], 'Check for contact type creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'user_unique_id', 'id', $updatePfParams['user_unique_id'], 'Check for user_unique_id creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'birth_date', 'id', $updateCParams['birth_date'], 'Check for birth_date creation.');
     $this->assertDBCompareValue('CRM_Contact_DAO_Contact', $contactId, 'deceased_date', 'id', $updateCParams['deceased_date'], 'Check for deceased_date creation.');
     $dbPrefComm = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'preferred_communication_method', 'id', TRUE));
     $checkPrefComm = array();
     foreach ($dbPrefComm as $key => $value) {
         if ($value) {
             $checkPrefComm[$value] = 1;
         }
     }
     $this->assertAttributesEquals($checkPrefComm, $updateCParams['preferred_communication_method']);
     //Now check DB for Address
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1);
     $compareParams = array('street_address' => CRM_Utils_Array::value('street_address-Primary', $updatePfParams), 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1-Primary', $updatePfParams), 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2-Primary', $updatePfParams), 'city' => CRM_Utils_Array::value('city-Primary', $updatePfParams), 'postal_code' => CRM_Utils_Array::value('postal_code-Primary', $updatePfParams), 'country_id' => CRM_Utils_Array::value('country-Primary', $updatePfParams), 'state_province_id' => CRM_Utils_Array::value('state_province-Primary', $updatePfParams), 'geo_code_1' => CRM_Utils_Array::value('geo_code_1-Primary', $updatePfParams), 'geo_code_2' => CRM_Utils_Array::value('geo_code_2-Primary', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Address', $searchParams, $compareParams);
     //Now check DB for Email
     $compareParams = array('email' => CRM_Utils_Array::value('email-Primary', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Email', $searchParams, $compareParams);
     //Now check DB for IM
     $compareParams = array('name' => CRM_Utils_Array::value('im-Primary', $updatePfParams), 'provider_id' => CRM_Utils_Array::value('im-Primary-provider_id', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_IM', $searchParams, $compareParams);
     //Now check DB for Phone
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'is_primary' => 1);
     $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-1', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams);
     //Now check DB for Mobile
     $searchParams = array('contact_id' => $contactId, 'location_type_id' => 1, 'phone_type_id' => CRM_Utils_Array::value('phone_type_id', $params['phone'][2]));
     $compareParams = array('phone' => CRM_Utils_Array::value('phone-Primary-2', $updatePfParams));
     $this->assertDBCompareValues('CRM_Core_DAO_Phone', $searchParams, $compareParams);
     //get the value of relationship
     $values = array();
     $searchParams = array('contact_id' => $contactId);
     $relationship = CRM_Contact_BAO_Relationship::getValues($searchParams, $values);
     //Now check values of Relationship Count.
     $this->assertEquals(0, $values['relationship']['totalCount'], 'Check for total relationship count');
     foreach ($values['relationship']['data'] as $key => $val) {
         //Now check values of Relationship organization.
         $this->assertEquals($updatePfParams['organization_name'], $val['name'], 'Check for organization');
         //Now check values of Relationship type.
         $this->assertEquals('Employee of', $val['relation'], 'Check for relationship type');
         //delete the organization.
         $this->contactDelete(CRM_Utils_Array::value('cid', $val));
     }
     //Now check values of tag ids.
     $tags = CRM_Core_BAO_EntityTag::getTag($contactId);
     foreach ($tags as $key => $val) {
         $tagIds[$key] = 1;
     }
     $this->assertAttributesEquals($updatePfParams['tag'], $tagIds);
     //cleanup DB by deleting the contact
     $this->contactDelete($contactId);
 }
Example #24
0
 /**
  * Different type of Contact Tokens.
  *
  * @return array
  */
 public static function contactTokens()
 {
     static $tokens = NULL;
     if (!$tokens) {
         $additionalFields = array('checksum' => array('title' => ts('Checksum')), 'contact_id' => array('title' => ts('Internal Contact ID')));
         $exportFields = array_merge(CRM_Contact_BAO_Contact::exportableFields(), $additionalFields);
         $values = array_merge(array_keys($exportFields));
         unset($values[0]);
         //FIXME:skipping some tokens for time being.
         $skipTokens = array('is_bulkmail', 'group', 'tag', 'contact_sub_type', 'note', 'is_deceased', 'deceased_date', 'legal_identifier', 'contact_sub_type', 'user_unique_id');
         $customFields = CRM_Core_BAO_CustomField::getFields(array('Individual', 'Address'));
         $legacyTokenNames = array_flip(CRM_Utils_Token::legacyContactTokens());
         foreach ($values as $val) {
             if (in_array($val, $skipTokens)) {
                 continue;
             }
             //keys for $tokens should be constant. $token Values are changed for Custom Fields. CRM-3734
             $customFieldId = CRM_Core_BAO_CustomField::getKeyID($val);
             if ($customFieldId) {
                 // CRM-15191 - if key is not in $customFields then the field is disabled and should be ignored
                 if (!empty($customFields[$customFieldId])) {
                     $tokens["{contact.{$val}}"] = $customFields[$customFieldId]['label'] . " :: " . $customFields[$customFieldId]['groupTitle'];
                 }
             } else {
                 // Support legacy token names
                 $tokenName = CRM_Utils_Array::value($val, $legacyTokenNames, $val);
                 $tokens["{contact.{$tokenName}}"] = $exportFields[$val]['title'];
             }
         }
         // Get all the hook tokens too
         $hookTokens = array();
         CRM_Utils_Hook::tokens($hookTokens);
         foreach ($hookTokens as $tokenValues) {
             foreach ($tokenValues as $key => $value) {
                 if (is_numeric($key)) {
                     $key = $value;
                 }
                 if (!preg_match('/^\\{[^\\}]+\\}$/', $key)) {
                     $key = '{' . $key . '}';
                 }
                 if (preg_match('/^\\{([^\\}]+)\\}$/', $value, $matches)) {
                     $value = $matches[1];
                 }
                 $tokens[$key] = $value;
             }
         }
     }
     return $tokens;
 }
Example #25
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 #26
0
 function buildQuickForm()
 {
     //get the saved mapping details
     require_once 'CRM/Core/DAO/Mapping.php';
     require_once 'CRM/Contact/BAO/Contact.php';
     require_once 'CRM/Core/BAO/LocationType.php';
     $mappingDAO =& new CRM_Core_DAO_Mapping();
     $mappingDAO->domain_id = CRM_Core_Config::domainID();
     $mappingDAO->mapping_type = 'Export';
     $mappingDAO->find();
     $mappingArray = array();
     while ($mappingDAO->fetch()) {
         $mappingArray[$mappingDAO->id] = $mappingDAO->name;
     }
     if (!empty($mappingArray)) {
         $this->assign('savedMapping', $mappingArray);
         $this->add('select', 'savedMapping', ts('Mapping Option'), array('' => '-select-') + $mappingArray);
         //if ( !isset($this->_loadedMappingId) ) {
         //$this->addRule('savedMapping',ts('Please select saved mappings.'), 'required');
         //}
         $this->addElement('submit', 'loadMapping', ts('Load Mapping'), array('class' => 'form-submit'));
     }
     //to save the current mappings
     if (!isset($this->_loadedMappingId)) {
         $saveDetailsName = ts('Save this field mapping');
         $this->add('text', 'saveMappingName', ts('Name'));
         $this->add('text', 'saveMappingDesc', ts('Description'));
     } else {
         //mapping is to be loaded from database
         $mapping =& new CRM_Core_DAO_MappingField();
         $mapping->mapping_id = $this->_loadedMappingId;
         $mapping->orderBy('column_number');
         $mapping->find();
         $mappingName = array();
         $mappingLocation = array();
         $mappingContactType = array();
         $mappingPhoneType = array();
         while ($mapping->fetch()) {
             if ($mapping->name) {
                 $mappingName[] = $mapping->name;
             }
             if ($mapping->contact_type) {
                 $mappingContactType[] = $mapping->contact_type;
             }
             if (!empty($mapping->location_type_id)) {
                 $mappingLocation[$mapping->column_number] = $mapping->location_type_id;
             }
             if (!empty($mapping->phone_type)) {
                 $mappingPhoneType[$mapping->column_number] = $mapping->phone_type;
             }
         }
         $this->assign('loadedMapping', $this->_loadedMappingId);
         $getMappingName =& new CRM_Core_DAO_Mapping();
         $getMappingName->id = $savedMapping;
         $getMappingName->mapping_type = 'Export';
         $getMappingName->find();
         while ($getMappingName->fetch()) {
             $mapperName = $getMappingName->name;
         }
         $this->assign('savedName', $mapperName);
         $this->add('hidden', 'mappingId', $this->_loadedMappingId);
         $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), null);
         $saveDetailsName = ts('Save as a new field mapping');
         $this->add('text', 'saveMappingName', ts('Name'));
         $this->add('text', 'saveMappingDesc', ts('Description'));
     }
     $this->addElement('checkbox', 'saveMapping', $saveDetailsName, null, array('onclick' => "showSaveDetails(this)"));
     $this->addFormRule(array('CRM_Contact_Form_Task_Export_Map', 'formRule'));
     //-------- end of saved mapping stuff ---------
     $this->_defaults = array();
     $hasLocationTypes = array();
     $contactId = array();
     $fields = array();
     $fields['Individual'] =& CRM_Contact_BAO_Contact::exportableFields('Individual', false, true);
     $fields['Household'] =& CRM_Contact_BAO_Contact::exportableFields('Household', false, true);
     $fields['Organization'] =& CRM_Contact_BAO_Contact::exportableFields('Organization', false, true);
     foreach ($fields as $key => $value) {
         foreach ($value as $key1 => $value1) {
             $this->_mapperFields[$key][$key1] = $value1['title'];
             $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
         }
     }
     $mapperKeys = array_keys($this->_mapperFields);
     $this->_location_types =& CRM_Core_PseudoConstant::locationType();
     $defaultLocationType =& CRM_Core_BAO_LocationType::getDefault();
     /* FIXME: dirty hack to make the default option show up first.  This
      * avoids a mozilla browser bug with defaults on dynamically constructed
      * selector widgets. */
     if ($defaultLocationType) {
         $defaultLocation = $this->_location_types[$defaultLocationType->id];
         unset($this->_location_types[$defaultLocationType->id]);
         $this->_location_types = array($defaultLocationType->id => $defaultLocation) + $this->_location_types;
     }
     $sel1 = array('' => '-select-') + CRM_Core_SelectValues::contactType();
     foreach ($sel1 as $key => $sel) {
         if ($key) {
             $sel2[$key] = $this->_mapperFields[$key];
         }
     }
     $sel3[''] = null;
     $phoneTypes = CRM_Core_SelectValues::phoneType();
     foreach ($sel1 as $k => $sel) {
         if ($k) {
             foreach ($this->_location_types as $key => $value) {
                 $sel4[$k]['phone'][$key] =& $phoneTypes;
             }
         }
     }
     foreach ($sel1 as $k => $sel) {
         if ($k) {
             foreach ($this->_mapperFields[$k] as $key => $value) {
                 if ($hasLocationTypes[$k][$key]) {
                     $sel3[$k][$key] = $this->_location_types;
                 } else {
                     $sel3[$key] = null;
                 }
             }
         }
     }
     // print_r($sel3);
     $this->_defaults = array();
     $js = "<script type='text/javascript'>\n";
     $formName = "document.{$this->_name}";
     //used to warn for mismatch column count or mismatch mapping
     $warning = 0;
     for ($i = 0; $i < $this->_columnCount; $i++) {
         $sel =& $this->addElement('hierselect', "mapper[{$i}]", ts('Mapper for Field %1', array(1 => $i)), null);
         $jsSet = false;
         if (isset($this->_loadedMappingId)) {
             $locationId = isset($mappingLocation[$i]) ? $mappingLocation[$i] : 0;
             if (isset($mappingName[$i])) {
                 if (is_array($this->_mapperFields[$mappingContactType[$i]])) {
                     $phoneType = isset($mappingPhoneType[$i]) ? $mappingPhoneType[$i] : null;
                     $mappingHeader = array_keys($this->_mapperFields[$mappingContactType[$i]], $mappingName[$i]);
                     $defaults["mapper[{$i}]"] = array($mappingContactType[$i], $mappingHeader[0], $locationId, $phoneType);
                     if (!$mappingHeader[0]) {
                         $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n";
                     }
                     if (!$locationId) {
                         $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n";
                     }
                     if (!$phoneType) {
                         $js .= "{$formName}['mapper[{$i}][3]'].style.display = 'none';\n";
                     }
                     $jsSet = true;
                 }
             }
         }
         //$formValues = $this->controller->exportValues( $this->_name );
         $formValues = $_POST;
         // using $_POST since export values don't give values on first submit
         /*             
          if ( ! $jsSet && empty( $formValues ) ) {
              for ( $k = 1; $k < 4; $k++ ) {
                  $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n"; 
              }
          }
         */
         if (!$jsSet) {
             if (empty($formValues)) {
                 for ($k = 1; $k < 4; $k++) {
                     $js .= "{$formName}['mapper[{$i}][{$k}]'].style.display = 'none';\n";
                 }
             } else {
                 foreach ($formValues['mapper'] as $value) {
                     for ($k = 1; $k < 4; $k++) {
                         if (!$formValues['mapper'][$i][$k]) {
                             $js .= "{$formName}['mapper[{$i}][{$k}]'].style.display = 'none';\n";
                         }
                     }
                 }
             }
         }
         $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
         //set the defaults on load mapping
     }
     $js .= "</script>\n";
     $this->assign('initHideBoxes', $js);
     $this->assign('columnCount', $this->_columnCount);
     $this->setDefaults($defaults);
     $this->addElement('submit', 'addMore', ts('Select more fields'), array('class' => 'form-submit'));
     $this->setDefaultAction('refresh');
     $this->addButtons(array(array('type' => 'back', 'name' => ts('<< Previous')), array('type' => 'next', 'name' => ts('Export >>'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'), array('type' => 'cancel', 'name' => ts('Done'))));
 }