示例#1
0
 /**
  * build the form elements for an IM object
  *
  * @param CRM_Core_Form $form       reference to the form object
  * @param array         $location   the location object to store all the form elements in
  * @param int           $locationId the locationId we are dealing with
  * @param int           $count      the number of blocks to create
  *
  * @return void
  * @access public
  * @static
  */
 function buildIMBlock(&$form, &$location, $locationId, $count)
 {
     for ($i = 1; $i <= $count; $i++) {
         $label = $i == 1 ? ts('Instant Messenger (preferred)') : ts('Instant Messenger');
         CRM_Core_ShowHideBlocks::linksForArray($form, $i, $count, "location[{$locationId}][im]", ts('another IM'), ts('hide this IM'));
         $location[$locationId]['im'][$i]['service_id'] = $form->addElement('select', "location[{$locationId}][im][{$i}][provider_id]", $label, array('' => ts('- select service -')) + CRM_Core_PseudoConstant::IMProvider());
         $location[$locationId]['im'][$i]['name'] = $form->addElement('text', "location[{$locationId}][im][{$i}][name]", null, CRM_Core_DAO::getAttribute('CRM_Core_DAO_IM', 'name'));
     }
 }
示例#2
0
 /**
  * build the form elements for an IM object
  *
  * @param CRM_Core_Form $form       reference to the form object
  * @param array         $location   the location object to store all the form elements in
  * @param int           $locationId the locationId we are dealing with
  * @param int           $count      the number of blocks to create
  *
  * @return void
  * @access public
  * @static
  */
 static function buildQuickForm(&$form)
 {
     $blockId = $form->get('IM_Block_Count') ? $form->get('IM_Block_Count') : 1;
     $form->applyFilter('__ALL__', 'trim');
     //IM provider select
     $form->addElement('select', "im[{$blockId}][provider_id]", '', CRM_Core_PseudoConstant::IMProvider());
     //Block type select
     $form->addElement('select', "im[{$blockId}][location_type_id]", '', CRM_Core_PseudoConstant::locationType());
     //IM box
     $form->addElement('text', "im[{$blockId}][name]", ts('Instant Messenger'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_IM', 'name'));
     //is_Primary radio
     $js = array('id' => "IM_" . $blockId . "_IsPrimary", 'onClick' => 'singleSelect( this.id );');
     $form->addElement('radio', "im[{$blockId}][is_primary]", '', '', '1', $js);
 }
 /**
  * Process the mapped fields and map it into the uploaded file
  * preview the file and extract some summary statistics
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues('MapField');
     //reload the mapfield if load mapping is pressed
     if (!empty($params['savedMapping'])) {
         $this->set('savedMapping', $params['savedMapping']);
         $this->controller->resetPage($this->_name);
         return;
     }
     $mapper = array();
     $mapperKeys = array();
     $mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
     $mapperKeysMain = array();
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     $websiteTypes = CRM_Core_PseudoConstant::websiteType();
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     //these mapper params need to set key as array and val as null.
     $mapperParams = array('related' => 'relatedVal', 'locations' => 'locationsVal', 'mapperLocType' => 'mapperLocTypeVal', 'mapperPhoneType' => 'mapperPhoneTypeVal', 'mapperImProvider' => 'mapperImProviderVal', 'mapperWebsiteType' => 'mapperWebsiteTypeVal', 'relatedContactType' => 'relatedContactTypeVal', 'relatedContactDetails' => 'relatedContactDetailsVal', 'relatedContactLocType' => 'relatedContactLocTypeVal', 'relatedContactPhoneType' => 'relatedContactPhoneTypeVal', 'relatedContactImProvider' => 'relatedContactImProviderVal', 'relatedContactWebsiteType' => 'relatedContactWebsiteTypeVal');
     //set respective mapper params to array.
     foreach (array_keys($mapperParams) as $mapperParam) {
         ${$mapperParam} = array();
     }
     for ($i = 0; $i < $this->_columnCount; $i++) {
         //set respective mapper value to null
         foreach (array_values($mapperParams) as $mapperParam) {
             ${$mapperParam} = NULL;
         }
         $fldName = CRM_Utils_Array::value(0, $mapperKeys[$i]);
         $selOne = CRM_Utils_Array::value(1, $mapperKeys[$i]);
         $selTwo = CRM_Utils_Array::value(2, $mapperKeys[$i]);
         $selThree = CRM_Utils_Array::value(3, $mapperKeys[$i]);
         $mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
         $mapperKeysMain[$i] = $fldName;
         //need to differentiate non location elements.
         if ($selOne && is_numeric($selOne)) {
             if ($fldName == 'url') {
                 $mapperWebsiteTypeVal = $websiteTypes[$selOne];
             } else {
                 $locationsVal = $locationTypes[$selOne];
                 $mapperLocTypeVal = $selOne;
                 if ($selTwo && is_numeric($selTwo)) {
                     if ($fldName == 'phone') {
                         $mapperPhoneTypeVal = $phoneTypes[$selTwo];
                     } elseif ($fldName == 'im') {
                         $mapperImProviderVal = $imProviders[$selTwo];
                     }
                 }
             }
         }
         //relationship contact mapper info.
         list($id, $first, $second) = CRM_Utils_System::explode('_', $fldName, 3);
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $relatedVal = $this->_mapperFields[$fldName];
             if ($selOne) {
                 if ($selOne == 'url') {
                     $relatedContactWebsiteTypeVal = $websiteTypes[$selTwo];
                 } else {
                     $relatedContactLocTypeVal = CRM_Utils_Array::value($selTwo, $locationTypes);
                     if ($selThree) {
                         if ($selOne == 'phone') {
                             $relatedContactPhoneTypeVal = $phoneTypes[$selThree];
                         } elseif ($selOne == 'im') {
                             $relatedContactImProviderVal = $imProviders[$selThree];
                         }
                     }
                 }
                 //get the related contact type.
                 $relationType = new CRM_Contact_DAO_RelationshipType();
                 $relationType->id = $id;
                 $relationType->find(TRUE);
                 $relatedContactTypeVal = $relationType->{"contact_type_{$second}"};
                 $relatedContactDetailsVal = $this->_formattedFieldNames[$relatedContactTypeVal][$selOne];
             }
         }
         //set the respective mapper param array values.
         foreach ($mapperParams as $mapperParamKey => $mapperParamVal) {
             ${$mapperParamKey}[$i] = ${$mapperParamVal};
         }
     }
     $this->set('columnNames', $this->_columnNames);
     //set main contact properties.
     $properties = array('ims' => 'mapperImProvider', 'mapper' => 'mapper', 'phones' => 'mapperPhoneType', 'websites' => 'mapperWebsiteType', 'locations' => 'locations');
     foreach ($properties as $propertyName => $propertyVal) {
         $this->set($propertyName, ${$propertyVal});
     }
     //set related contact propeties.
     $relProperties = array('related', 'relatedContactType', 'relatedContactDetails', 'relatedContactLocType', 'relatedContactPhoneType', 'relatedContactImProvider', 'relatedContactWebsiteType');
     foreach ($relProperties as $relProperty) {
         $this->set($relProperty, ${$relProperty});
     }
     // store mapping Id to display it in the preview page
     $this->set('loadMappingId', CRM_Utils_Array::value('mappingId', $params));
     //Updating Mapping Records
     if (CRM_Utils_Array::value('updateMapping', $params)) {
         $locationTypes = CRM_Core_PseudoConstant::locationType();
         $mappingFields = new CRM_Core_DAO_MappingField();
         $mappingFields->mapping_id = $params['mappingId'];
         $mappingFields->find();
         $mappingFieldsId = array();
         while ($mappingFields->fetch()) {
             if ($mappingFields->id) {
                 $mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
             }
         }
         for ($i = 0; $i < $this->_columnCount; $i++) {
             $updateMappingFields = new CRM_Core_DAO_MappingField();
             $updateMappingFields->id = $mappingFieldsId[$i];
             $updateMappingFields->mapping_id = $params['mappingId'];
             $updateMappingFields->column_number = $i;
             $mapperKeyParts = explode('_', $mapperKeys[$i][0], 3);
             $id = isset($mapperKeyParts[0]) ? $mapperKeyParts[0] : NULL;
             $first = isset($mapperKeyParts[1]) ? $mapperKeyParts[1] : NULL;
             $second = isset($mapperKeyParts[2]) ? $mapperKeyParts[2] : NULL;
             if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
                 $updateMappingFields->relationship_type_id = $id;
                 $updateMappingFields->relationship_direction = "{$first}_{$second}";
                 $updateMappingFields->name = ucwords(str_replace("_", " ", $mapperKeys[$i][1]));
                 // get phoneType id and provider id separately
                 // before updating mappingFields of phone and IM for related contact, CRM-3140
                 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'url') {
                     $updateMappingFields->website_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
                 } else {
                     if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') {
                         $updateMappingFields->phone_type_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL;
                     } elseif (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') {
                         $updateMappingFields->im_provider_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL;
                     }
                     $updateMappingFields->location_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
                 }
             } else {
                 $updateMappingFields->name = $mapper[$i];
                 $updateMappingFields->relationship_type_id = 'NULL';
                 $updateMappingFields->relationship_type_direction = 'NULL';
                 // to store phoneType id and provider id seperately
                 // before updating mappingFields for phone and IM, CRM-3140
                 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'url') {
                     $updateMappingFields->website_type_id = isset($mapperKeys[$i][1]) ? $mapperKeys[$i][1] : NULL;
                 } else {
                     if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'phone') {
                         $updateMappingFields->phone_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
                     } elseif (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'im') {
                         $updateMappingFields->im_provider_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
                     }
                     $location = array_keys($locationTypes, $locations[$i]);
                     $updateMappingFields->location_type_id = isset($location) ? $location[0] : NULL;
                 }
             }
             $updateMappingFields->save();
         }
     }
     //Saving Mapping Details and Records
     if (CRM_Utils_Array::value('saveMapping', $params)) {
         $mappingParams = array('name' => $params['saveMappingName'], 'description' => $params['saveMappingDesc'], 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type', 'Import Contact', 'name'));
         $saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
         $locationTypes = CRM_Core_PseudoConstant::locationType();
         $contactType = $this->get('contactType');
         switch ($contactType) {
             case CRM_Import_Parser::CONTACT_INDIVIDUAL:
                 $cType = 'Individual';
                 break;
             case CRM_Import_Parser::CONTACT_HOUSEHOLD:
                 $cType = 'Household';
                 break;
             case CRM_Import_Parser::CONTACT_ORGANIZATION:
                 $cType = 'Organization';
         }
         for ($i = 0; $i < $this->_columnCount; $i++) {
             $saveMappingFields = new CRM_Core_DAO_MappingField();
             $saveMappingFields->mapping_id = $saveMapping->id;
             $saveMappingFields->contact_type = $cType;
             $saveMappingFields->column_number = $i;
             $mapperKeyParts = explode('_', $mapperKeys[$i][0], 3);
             $id = isset($mapperKeyParts[0]) ? $mapperKeyParts[0] : NULL;
             $first = isset($mapperKeyParts[1]) ? $mapperKeyParts[1] : NULL;
             $second = isset($mapperKeyParts[2]) ? $mapperKeyParts[2] : NULL;
             if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
                 $saveMappingFields->name = ucwords(str_replace("_", " ", $mapperKeys[$i][1]));
                 $saveMappingFields->relationship_type_id = $id;
                 $saveMappingFields->relationship_direction = "{$first}_{$second}";
                 // to get phoneType id and provider id seperately
                 // before saving mappingFields of phone and IM for related contact, CRM-3140
                 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'url') {
                     $saveMappingFields->website_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
                 } else {
                     if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') {
                         $saveMappingFields->phone_type_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL;
                     } elseif (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') {
                         $saveMappingFields->im_provider_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : NULL;
                     }
                     $saveMappingFields->location_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
                 }
             } else {
                 $saveMappingFields->name = $mapper[$i];
                 $location_id = array_keys($locationTypes, $locations[$i]);
                 // to get phoneType id and provider id seperately
                 // before saving mappingFields of phone and IM, CRM-3140
                 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'url') {
                     $saveMappingFields->website_type_id = isset($mapperKeys[$i][1]) ? $mapperKeys[$i][1] : NULL;
                 } else {
                     if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'phone') {
                         $saveMappingFields->phone_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
                     } elseif (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'im') {
                         $saveMappingFields->im_provider_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : NULL;
                     }
                     $saveMappingFields->location_type_id = isset($location_id[0]) ? $location_id[0] : NULL;
                 }
                 $saveMappingFields->relationship_type_id = NULL;
             }
             $saveMappingFields->save();
         }
         $this->set('savedMapping', $saveMappingFields->mapping_id);
     }
     $parser = new CRM_Import_Parser_Contact($mapperKeysMain, $mapperLocType, $mapperPhoneType, $mapperImProvider, $related, $relatedContactType, $relatedContactDetails, $relatedContactLocType, $relatedContactPhoneType, $relatedContactImProvider, $mapperWebsiteType, $relatedContactWebsiteType);
     $primaryKeyName = $this->get('primaryKeyName');
     $statusFieldName = $this->get('statusFieldName');
     $parser->run($this->_importTableName, $mapper, CRM_Import_Parser::MODE_PREVIEW, $this->get('contactType'), $primaryKeyName, $statusFieldName, $this->_onDuplicate, NULL, NULL, FALSE, CRM_Import_Parser::DEFAULT_TIMEOUT, $this->get('contactSubType'), $this->get('dedupe'));
     // add all the necessary variables to the form
     $parser->set($this);
 }
示例#4
0
 /**
  * Function to build the mapping form
  *
  * @params object $form        form object
  * @params string $mappingType mapping type (Export/Import/Search Builder)
  * @params int    $mappingId   mapping id
  * @params mixed  $columnCount column count is int for and array for search builder
  * @params int    $blockCount  block count (no of blocks shown) 
  *
  * @return none
  * @access public
  * @static
  */
 static function buildMappingForm(&$form, $mappingType = 'Export', $mappingId = null, $columnNo, $blockCount = 3, $exportMode = null)
 {
     if ($mappingType == 'Export') {
         $name = "Map";
         $columnCount = array('1' => $columnNo);
     } else {
         if ($mappingType == 'Search Builder') {
             $name = "Builder";
             $columnCount = $columnNo;
         }
     }
     //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';
     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'));
     } else {
         if ($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;
     } else {
         if ($mappingType == 'Search Builder') {
             $required = false;
         }
     }
     $contactType = array('Individual', 'Household', 'Organization');
     foreach ($contactType as $value) {
         $relationfields[$value] = $fields[$value] =& CRM_Contact_BAO_Contact::exportableFields($value, false, $required);
         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();
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $fields['Student'] =& CRM_Quest_BAO_Student::exportableFields();
         $compArray['Student'] = 'Student';
     }
     //we need to unset groups, tags, notes for component export
     require_once 'CRM/Export/Form/Select.php';
     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' || $exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
         if (CRM_Core_Permission::access('CiviContribute')) {
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $fields['Contribution'] =& CRM_Contribute_BAO_Contribution::exportableFields();
             unset($fields['Contribution']['contribution_contact_id']);
             $compArray['Contribution'] = ts('Contribution');
         }
     }
     if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
         if (CRM_Core_Permission::access('CiviEvent')) {
             require_once 'CRM/Event/BAO/Participant.php';
             $fields['Participant'] =& CRM_Event_BAO_Participant::exportableFields();
             unset($fields['Participant']['participant_contact_id']);
             $compArray['Participant'] = ts('Participant');
         }
     }
     if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
         if (CRM_Core_Permission::access('CiviMember')) {
             require_once 'CRM/Member/BAO/Membership.php';
             $fields['Membership'] =& CRM_Member_BAO_Membership::getMembershipFields();
             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')) {
             require_once 'CRM/Pledge/BAO/Pledge.php';
             $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')) {
             require_once 'CRM/Case/BAO/Case.php';
             $fields['Case'] =& CRM_Case_BAO_Case::exportableFields();
             $compArray['Case'] = ts('Case');
             require_once 'CRM/Activity/BAO/Activity.php';
             $fields['Activity'] =& CRM_Activity_BAO_Activity::exportableFields();
             $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')) {
             require_once 'CRM/Grant/BAO/Grant.php';
             $fields['Grant'] =& CRM_Grant_BAO_Grant::exportableFields();
             unset($fields['Grant']['grant_contact_id']);
             $compArray['Grant'] = ts('Grant');
         }
     }
     //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();
         $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::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 = $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);
     $sel1 = array('' => ts('- select record type -')) + $contactTypes + $compArray;
     foreach ($sel1 as $key => $sel) {
         if ($key) {
             $sel2[$key] = $mapperFields[$key];
         }
     }
     $sel3[''] = null;
     $sel5[''] = null;
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     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);
                         $relationshipCustomFields = self::getRelationTypeCustomGroupData($id);
                         asort($relationshipCustomFields);
                         require_once 'CRM/Contact/BAO/RelationshipType.php';
                         $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();
                         $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');
     $relationFields = array();
     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++) {
             $colCnt = count($mappingName[$x]);
             if ($colCnt >= $columnCount[$x]) {
                 $columnCount[$x] = $colCnt;
             }
         }
     }
     $defaults = array();
     $noneArray = array();
     $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;
                             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, $mappingOperator[$x])) {
                             $defaults["operator[{$x}][{$i}]"] = CRM_Utils_Array::value($i, $mappingOperator[$x]);
                         }
                         if (CRM_Utils_Array::value($i, $mappingValue[$x])) {
                             $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)) {
                     if (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-'), '=' => '=', '!=' => '!=', '>' => '>', '<' => '<', '>=' => '>=', '<=' => '<=', 'IN' => 'IN', 'LIKE' => 'LIKE', 'IS NULL' => 'IS NULL', 'IS NOT NULL' => 'IS NOT NULL');
                 $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 .= "\nfor(var i=0;i<nullArray.length;i++) {\n  {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';\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 .= "\nfor(var i=0;i<noneArray.length;i++) {\n  {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';  \n}\n";
     }
     $js .= "</script>\n";
     $form->assign('initHideBoxes', $js);
     $form->assign('columnCount', $columnCount);
     $form->assign('blockCount', $blockCount);
     $form->setDefaults($defaults);
     $form->setDefaultAction('refresh');
 }
 public function runImport(&$form, $timeout = 55)
 {
     $mapper = $this->_mapper;
     $mapperFields = array();
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     $websiteTypes = CRM_Core_PseudoConstant::websiteType();
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     //initialize mapper perperty value.
     $mapperPeroperties = array('mapperRelated' => 'mapperRelatedVal', 'mapperLocTypes' => 'mapperLocTypesVal', 'mapperPhoneTypes' => 'mapperPhoneTypesVal', 'mapperImProviders' => 'mapperImProvidersVal', 'mapperWebsiteTypes' => 'mapperWebsiteTypesVal', 'mapperRelatedContactType' => 'mapperRelatedContactTypeVal', 'mapperRelatedContactDetails' => 'mapperRelatedContactDetailsVal', 'mapperRelatedContactLocType' => 'mapperRelatedContactLocTypeVal', 'mapperRelatedContactPhoneType' => 'mapperRelatedContactPhoneTypeVal', 'mapperRelatedContactImProvider' => 'mapperRelatedContactImProviderVal', 'mapperRelatedContactWebsiteType' => 'mapperRelatedContactWebsiteTypeVal');
     foreach ($mapper as $key => $value) {
         //set respective mapper value to null.
         foreach (array_values($mapperPeroperties) as $perpertyVal) {
             ${$perpertyVal} = NULL;
         }
         $header = array();
         $fldName = CRM_Utils_Array::value(0, $mapper[$key]);
         $selOne = CRM_Utils_Array::value(1, $mapper[$key]);
         $selTwo = CRM_Utils_Array::value(2, $mapper[$key]);
         $selThree = CRM_Utils_Array::value(3, $mapper[$key]);
         $this->_mapperKeys[$key] = $fldName;
         //need to differentiate non location elements.
         if ($selOne && is_numeric($selOne)) {
             if ($fldName == 'url') {
                 $header[] = $websiteTypes[$selOne];
                 $mapperWebsiteTypesVal = $selOne;
             } else {
                 $header[] = $locationTypes[$selOne];
                 $mapperLocTypesVal = $selOne;
                 if ($selTwo && is_numeric($selTwo)) {
                     if ($fldName == 'phone') {
                         $header[] = $phoneTypes[$selTwo];
                         $mapperPhoneTypesVal = $selTwo;
                     } elseif ($fldName == 'im') {
                         $header[] = $imProviders[$selTwo];
                         $mapperImProvidersVal = $selTwo;
                     }
                 }
             }
         }
         $fldNameParts = explode('_', $fldName, 3);
         $id = $fldNameParts[0];
         $first = isset($fldNameParts[1]) ? $fldNameParts[1] : NULL;
         $second = isset($fldNameParts[2]) ? $fldNameParts[2] : NULL;
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $header[] = ucwords(str_replace("_", " ", $selOne));
             $relationType = new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(TRUE);
             $mapperRelatedContactTypeVal = $relationType->{"contact_type_{$second}"};
             $mapperRelatedVal = $fldName;
             if ($selOne) {
                 $mapperRelatedContactDetailsVal = $selOne;
                 if ($selTwo) {
                     if ($selOne == 'url') {
                         $header[] = $websiteTypes[$selTwo];
                         $mapperRelatedContactWebsiteTypeVal = $selTwo;
                     } else {
                         $header[] = $locationTypes[$selTwo];
                         $mapperRelatedContactLocTypeVal = $selTwo;
                         if ($selThree) {
                             if ($selOne == 'phone') {
                                 $header[] = $phoneTypes[$selThree];
                                 $mapperRelatedContactPhoneTypeVal = $selThree;
                             } elseif ($selOne == 'im') {
                                 $header[] = $imProviders[$selThree];
                                 $mapperRelatedContactImProviderVal = $selThree;
                             }
                         }
                     }
                 }
             }
         }
         $mapperFields[] = implode(' - ', $header);
         //set the respective mapper param array values.
         foreach ($mapperPeroperties as $mapperProKey => $mapperProVal) {
             $this->{"_{$mapperProKey}"}[$key] = ${$mapperProVal};
         }
     }
     $this->_parser = new CRM_Import_Parser_Contact($this->_mapperKeys, $this->_mapperLocTypes, $this->_mapperPhoneTypes, $this->_mapperImProviders, $this->_mapperRelated, $this->_mapperRelatedContactType, $this->_mapperRelatedContactDetails, $this->_mapperRelatedContactLocType, $this->_mapperRelatedContactPhoneType, $this->_mapperRelatedContactImProvider, $this->_mapperWebsiteTypes, $this->_mapperRelatedContactWebsiteType);
     $this->_parser->run($this->_tableName, $mapperFields, CRM_Import_Parser::MODE_IMPORT, $this->_contactType, $this->_primaryKeyName, $this->_statusFieldName, $this->_onDuplicate, $this->_statusID, $this->_totalRowCount, $this->_doGeocodeAddress, CRM_Import_Parser::DEFAULT_TIMEOUT, $this->_contactSubType, $this->_dedupe);
     $contactIds = $this->_parser->getImportedContacts();
     //get the related contactIds. CRM-2926
     $relatedContactIds = $this->_parser->getRelatedImportedContacts();
     if ($relatedContactIds) {
         $contactIds = array_merge($contactIds, $relatedContactIds);
         if ($form) {
             $form->set('relatedCount', count($relatedContactIds));
         }
     }
     if ($this->_newGroupName || count($this->_groups)) {
         $groupAdditions = $this->_addImportedContactsToNewGroup($contactIds, $this->_newGroupName, $this->_newGroupDesc);
         if ($form) {
             $form->set('groupAdditions', $groupAdditions);
         }
     }
     if ($this->_newTagName || count($this->_tag)) {
         $tagAdditions = $this->_tagImportedContactsWithNewTag($contactIds, $this->_newTagName, $this->_newTagDesc);
         if ($form) {
             $form->set('tagAdditions', $tagAdditions);
         }
     }
 }
 function titlesAndValuesForTable($table)
 {
     // static caches for subsequent calls with the same $table
     static $titles = array();
     static $values = array();
     // FIXME: split off the table → DAO mapping to a GenCode-generated class
     static $daos = array('civicrm_address' => 'CRM_Core_DAO_Address', 'civicrm_contact' => 'CRM_Contact_DAO_Contact', 'civicrm_email' => 'CRM_Core_DAO_Email', 'civicrm_im' => 'CRM_Core_DAO_IM', 'civicrm_openid' => 'CRM_Core_DAO_OpenID', 'civicrm_phone' => 'CRM_Core_DAO_Phone', 'civicrm_website' => 'CRM_Core_DAO_Website', 'civicrm_contribution' => 'CRM_Contribute_DAO_Contribution', 'civicrm_note' => 'CRM_Core_DAO_Note', 'civicrm_relationship' => 'CRM_Contact_DAO_Relationship');
     if (!isset($titles[$table]) or !isset($values[$table])) {
         if (in_array($table, array_keys($daos))) {
             // FIXME: these should be populated with pseudo constants as they
             // were at the time of logging rather than their current values
             $values[$table] = array('contribution_page_id' => CRM_Contribute_PseudoConstant::contributionPage(), 'contribution_status_id' => CRM_Contribute_PseudoConstant::contributionStatus(), 'contribution_type_id' => CRM_Contribute_PseudoConstant::contributionType(), 'country_id' => CRM_Core_PseudoConstant::country(), 'gender_id' => CRM_Core_PseudoConstant::gender(), 'location_type_id' => CRM_Core_PseudoConstant::locationType(), 'payment_instrument_id' => CRM_Contribute_PseudoConstant::paymentInstrument(), 'phone_type_id' => CRM_Core_PseudoConstant::phoneType(), 'preferred_communication_method' => CRM_Core_PseudoConstant::pcm(), 'preferred_language' => CRM_Core_PseudoConstant::languages(), 'prefix_id' => CRM_Core_PseudoConstant::individualPrefix(), 'provider_id' => CRM_Core_PseudoConstant::IMProvider(), 'state_province_id' => CRM_Core_PseudoConstant::stateProvince(), 'suffix_id' => CRM_Core_PseudoConstant::individualSuffix(), 'website_type_id' => CRM_Core_PseudoConstant::websiteType());
             require_once str_replace('_', DIRECTORY_SEPARATOR, $daos[$table]) . '.php';
             eval("\$dao = new {$daos[$table]};");
             foreach ($dao->fields() as $field) {
                 $titles[$table][$field['name']] = CRM_Utils_Array::value('title', $field);
                 if ($field['type'] == CRM_Utils_Type::T_BOOLEAN) {
                     $values[$table][$field['name']] = array('0' => ts('false'), '1' => ts('true'));
                 }
             }
         } elseif (substr($table, 0, 14) == 'civicrm_value_') {
             list($titles[$table], $values[$table]) = $this->titlesAndValuesForCustomDataTable($table);
         }
     }
     return array($titles[$table], $values[$table]);
 }
示例#7
0
/**
 * function convert params to v3.0 format before add location.
 */
function _civicrm_format_params_v2_to_v3(&$params, $locationTypeId = null)
{
    // get the loc type id.
    if (!$locationTypeId) {
        // get location type.
        $locationTypeId = CRM_Utils_Array::value('location_type_id', $params);
        if (!$locationTypeId && array_key_exists('location_type', $params)) {
            require_once 'CRM/Core/PseudoConstant.php';
            $locTypes =& CRM_Core_PseudoConstant::locationType();
            $locType = $params['location_type'];
            if (is_array($params['location_type'])) {
                $locType = array_pop($params['location_type']);
            }
            $locationTypeId = CRM_Utils_Array::key($locType, $locTypes);
        }
    }
    // convert params into v3.0 format.
    $primary = $billing = array();
    $blocks = array('Email', 'Phone', 'IM', 'OpenID');
    // format params array.
    $firstBlockCount = null;
    foreach ($blocks as $block) {
        require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Core_DAO_" . $block) . ".php";
        eval('$fields =& CRM_Core_DAO_' . $block . '::fields( );');
        $name = strtolower($block);
        $blockCount = 0;
        if (CRM_Utils_Array::value($name, $params)) {
            if (is_array($params[$name])) {
                $values = $params[$name];
                $params[$name] = array();
                foreach ($values as $val) {
                    _civicrm_store_values($fields, $val, $params[$name][++$blockCount]);
                    // check for primary and billing.
                    if (CRM_Utils_Array::value('is_primary', $val)) {
                        $primary[$name][$blockCount] = true;
                    }
                    if (CRM_Utils_Array::value('is_billing', $val)) {
                        $primary[$name][$blockCount] = true;
                    }
                    if (!$firstBlockCount) {
                        $firstBlockCount = $blockCount;
                    }
                }
            } else {
                //need to get ids.
                if (in_array($name, array('im', 'phone'))) {
                    require_once 'CRM/Core/PseudoConstant.php';
                    if ($name == 'im') {
                        CRM_Utils_Array::lookupValue($params, 'provider', CRM_Core_PseudoConstant::IMProvider(), true);
                    } else {
                        CRM_Utils_Array::lookupValue($params, 'phone_type', CRM_Core_PseudoConstant::phoneType(), true);
                    }
                }
                $locValues[$name] = array();
                _civicrm_store_values($fields, $params, $locValues[$name][++$blockCount]);
                $params[$name] = $locValues[$name];
                $firstBlockCount = $blockCount;
                unset($locValues[$name]);
            }
            // make first block as default primary when is_primary
            // is not set in sub array and set in main params array.
            if (!CRM_Utils_Array::value($name, $primary) && CRM_Utils_Array::value('is_primary', $params)) {
                $primary[$name][$firstBlockCount] = true;
                $params[$name][$firstBlockCount]['is_primary'] = true;
            }
            if (!CRM_Utils_Array::value($name, $billing) && CRM_Utils_Array::value('is_billing', $params)) {
                $billing[$name][$firstBlockCount] = true;
                $params[$name][$firstBlockCount]['is_billing'] = true;
            }
        }
    }
    //get the address fields.
    $addressCount = 1;
    $ids = array('county', 'country_id', 'country', 'state_province_id', 'state_province', 'supplemental_address_1', 'supplemental_address_2', 'StateProvince.name', 'city', 'street_address');
    $addressTaken = false;
    foreach ($ids as $id) {
        if (array_key_exists($id, $params)) {
            if (!$addressTaken) {
                require_once 'CRM/Core/DAO/Address.php';
                $fields =& CRM_Core_DAO_Address::fields();
                _civicrm_store_values($fields, $params, $params['address'][$addressCount]);
                $addressTaken = true;
            }
            $params['address'][$addressCount][$id] = $params[$id];
            unset($params[$id]);
        }
    }
    // format state and country.
    foreach (array('state_province', 'country') as $field) {
        $fName = $field == 'state_province' ? 'stateProvinceAbbreviation' : 'countryIsoCode';
        if (CRM_Utils_Array::value('address', $params) && CRM_Utils_Array::value($field, $params['address'][$addressCount]) && is_numeric($params['address'][$addressCount][$field])) {
            $fValue =& $params['address'][$addressCount][$field];
            eval('$fValue = CRM_Core_PseudoConstant::' . $fName . '( $fValue );');
            //kill the reference.
            unset($fValue);
        }
    }
    // check for primary address.
    if (CRM_Utils_Array::value('is_primary', $params)) {
        if ($addressTaken) {
            $primary['address'][$addressCount] = true;
            $params['address'][$addressCount]['is_primary'] = true;
        }
        unset($params['is_primary']);
    }
    if (CRM_Utils_Array::value('is_billing', $params)) {
        if ($addressTaken) {
            $billing['address'][$addressCount] = true;
            $params['address'][$addressCount]['is_billing'] = true;
        }
        unset($params['is_billing']);
    }
    // handle primary and billing reset.
    foreach (array('email', 'phone', 'im', 'address', 'openid') as $name) {
        if (!array_key_exists($name, $params) || CRM_Utils_System::isNull($params[$name])) {
            continue;
        }
        $errorMsg = null;
        $primaryBlockIndex = $billingBlockIndex = 0;
        if (array_key_exists($name, $primary)) {
            if (count($primary[$name]) > 1) {
                $errorMsg .= ts("<br />Multiple Primary %1.", array(1 => $block));
            } else {
                $primaryBlockIndex = key($primary[$name]);
            }
        }
        if (array_key_exists($name, $billing)) {
            if (count($billing[$name]) > 1) {
                $errorMsg .= ts("<br />Multiple Billing %1.", array(1 => $block));
            } else {
                $billingBlockIndex = key($billing[$name]);
            }
        }
        if ($errorMsg) {
            return civicrm_create_error($errorMsg);
        }
        foreach ($params[$name] as $count => &$values) {
            if ($primaryBlockIndex && $count != $primaryBlockIndex) {
                $values['is_primary'] = false;
            }
            if ($billingBlockIndex && $count != $billingBlockIndex) {
                $values['is_billing'] = false;
            }
            // get location type if not present in sub array.
            if (!CRM_Utils_Array::value('location_type_id', $values)) {
                $values['location_type_id'] = $locationTypeId;
            }
            //kill the reference.
            unset($values);
        }
    }
    // finally unset location_type and location type id.
    foreach (array('location_type', 'location_type_id') as $f) {
        if (isset($params[$f])) {
            unset($params[$f]);
        }
    }
    return $params;
}
示例#8
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;
 }
示例#9
0
 public function runImport(&$form, $timeout = 55)
 {
     $mapper = $this->_mapper;
     foreach ($mapper as $key => $value) {
         $this->_mapperKeys[$key] = $mapper[$key][0];
         if (is_numeric($mapper[$key][1])) {
             $this->_mapperLocTypes[$key] = $mapper[$key][1];
         } else {
             $this->_mapperLocTypes[$key] = null;
         }
         //to store phoneType id and provider id separately for contact
         if (is_numeric($mapper[$key][2])) {
             if (CRM_Utils_Array::value('0', $mapper[$key]) == 'phone') {
                 $this->_mapperPhoneTypes[$key] = $mapper[$key][2];
                 $this->_mapperImProviders[$key] = null;
             } else {
                 if (CRM_Utils_Array::value('0', $mapper[$key]) == 'im') {
                     $this->_mapperImProviders[$key] = $mapper[$key][2];
                     $this->_mapperPhoneTypes[$key] = null;
                 }
             }
         } else {
             $this->_mapperPhoneTypes[$key] = null;
             $this->_mapperImProviders[$key] = null;
         }
         list($id, $first, $second) = explode('_', $mapper[$key][0]);
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $relationType =& new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(true);
             eval('$this->_mapperRelatedContactType[$key] = $relationType->contact_type_' . $second . ';');
             $this->_mapperRelated[$key] = $mapper[$key][0];
             $this->_mapperRelatedContactDetails[$key] = $mapper[$key][1];
             $this->_mapperRelatedContactLocType[$key] = $mapper[$key][2];
             //to store phoneType id and provider id separately for related contact
             if (CRM_Utils_Array::value('1', $mapper[$key]) == 'phone') {
                 $this->_mapperRelatedContactPhoneType[$key] = $mapper[$key][3];
                 $this->_mapperRelatedContactImProvider[$key] = null;
             } else {
                 if (CRM_Utils_Array::value('1', $mapper[$key]) == 'im') {
                     $this->_mapperRelatedContactImProvider[$key] = $mapper[$key][3];
                     $this->_mapperRelatedContactPhoneType[$key] = null;
                 } else {
                     $this->_mapperRelatedContactPhoneType[$key] = null;
                     $this->_mapperRelatedContactImProvider[$key] = null;
                 }
             }
         } else {
             $this->_mapperRelated[$key] = null;
             $this->_mapperRelatedContactType[$key] = null;
             $this->_mapperRelatedContactDetails[$key] = null;
             $this->_mapperRelatedContactLocType[$key] = null;
             $this->_mapperRelatedContactPhoneType[$key] = null;
             $this->_mapperRelatedContactImProvider[$key] = null;
         }
     }
     require_once 'CRM/Import/Parser/Contact.php';
     $this->_parser = new CRM_Import_Parser_Contact($this->_mapperKeys, $this->_mapperLocTypes, $this->_mapperPhoneTypes, $this->_mapperImProviders, $this->_mapperRelated, $this->_mapperRelatedContactType, $this->_mapperRelatedContactDetails, $this->_mapperRelatedContactLocType, $this->_mapperRelatedContactPhoneType, $this->_mapperRelatedContactImProvider);
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     foreach ($mapper as $key => $value) {
         $header = array();
         list($id, $first, $second) = explode('_', $mapper[$key][0]);
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $relationType =& new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(true);
             $header[] = $relationType->name_a_b;
             $header[] = ucwords(str_replace("_", " ", $mapper[$key][1]));
             if (isset($mapper[$key][2])) {
                 $header[] = $locationTypes[$mapper[$key][2]];
             }
             if (isset($mapper[$key][3])) {
                 if (CRM_Utils_Array::value('1', $mapper[$key]) == 'phone') {
                     $header[] = $phoneTypes[$mapper[$key][3]];
                 } else {
                     if (CRM_Utils_Array::value('1', $mapper[$key]) == 'im') {
                         $header[] = $imProviders[$mapper[$key][3]];
                     }
                 }
             }
         } else {
             if (isset($this->_mapFields[$mapper[$key][0]])) {
                 $header[] = $this->_mapFields[$mapper[$key][0]];
                 if (isset($mapper[$key][1])) {
                     $header[] = $locationTypes[$mapper[$key][1]];
                 }
                 if (isset($mapper[$key][2])) {
                     if (CRM_Utils_Array::value('0', $mapper[$key]) == 'phone') {
                         $header[] = $phoneTypes[$mapper[$key][2]];
                     } else {
                         if (CRM_Utils_Array::value('0', $mapper[$key]) == 'im') {
                             $header[] = $imProviders[$mapper[$key][2]];
                         }
                     }
                 }
             }
         }
         $mapperFields[] = implode(' - ', $header);
     }
     $this->_parser->run($this->_tableName, $mapperFields, CRM_Import_Parser::MODE_IMPORT, $this->_contactType, $this->_primaryKeyName, $this->_statusFieldName, $this->_onDuplicate, $this->_statusID, $this->_totalRowCount, $this->_doGeocodeAddress, CRM_Import_Parser::DEFAULT_TIMEOUT, $this->_contactSubType);
     $contactIds = $this->_parser->getImportedContacts();
     //get the related contactIds. CRM-2926
     $relatedContactIds = $this->_parser->getRelatedImportedContacts();
     if ($relatedContactIds) {
         $contactIds = array_merge($contactIds, $relatedContactIds);
         if ($form) {
             $form->set('relatedCount', count($relatedContactIds));
         }
     }
     if ($this->_newGroupName || count($this->_groups)) {
         $groupAdditions = $this->_addImportedContactsToNewGroup($contactIds, $this->_newGroupName, $this->_newGroupDesc);
         if ($form) {
             $form->set('groupAdditions', $groupAdditions);
         }
     }
     if ($this->_newTagName || count($this->_tag)) {
         $tagAdditions = $this->_tagImportedContactsWithNewTag($contactIds, $this->_newTagName, $this->_newTagDesc);
         if ($form) {
             $form->set('tagAdditions', $tagAdditions);
         }
     }
 }
示例#10
0
文件: Export.php 项目: ksecor/civicrm
 /**
  * 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;
 }
 /**
  * returns all the rows in the given offset and rowCount
  *
  * @param enum   $action   the action being performed
  * @param int    $offset   the row number to start from
  * @param int    $rowCount the number of rows to return
  * @param string $sort     the sql string that describes the sort order
  * @param enum   $output   what should the result set include (web/email/csv)
  *
  * @return int   the total number of rows for this action
  */
 function &getRows($action, $offset, $rowCount, $sort, $output = NULL)
 {
     $multipleFields = array('url');
     //$sort object processing for location fields
     if ($sort) {
         $vars = $sort->_vars;
         $varArray = array();
         foreach ($vars as $key => $field) {
             $field = $vars[$key];
             $fieldArray = explode('-', $field['name']);
             $fieldType = CRM_Utils_Array::value('2', $fieldArray);
             if (is_numeric(CRM_Utils_Array::value('1', $fieldArray))) {
                 if (!in_array($fieldType, $multipleFields)) {
                     $locationType = new CRM_Core_DAO_LocationType();
                     $locationType->id = $fieldArray[1];
                     $locationType->find(TRUE);
                     if ($fieldArray[0] == 'email' || $fieldArray[0] == 'im' || $fieldArray[0] == 'phone') {
                         $field['name'] = "`" . $locationType->name . "-" . $fieldArray[0] . "-1`";
                     } else {
                         $field['name'] = "`" . $locationType->name . "-" . $fieldArray[0] . "`";
                     }
                 } else {
                     $field['name'] = "`website-" . $fieldArray[1] . "-{$fieldType}`";
                 }
             }
             $varArray[$key] = $field;
         }
     }
     $sort->_vars = $varArray;
     $additionalWhereClause = 'contact_a.is_deleted = 0';
     $result = $this->_query->searchQuery($offset, $rowCount, $sort, NULL, NULL, NULL, NULL, NULL, $additionalWhereClause);
     // process the result of the query
     $rows = array();
     // check if edit is configured in profile settings
     if ($this->_gid) {
         $editLink = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'is_edit_link');
     }
     //FIXME : make sure to handle delete separately. CRM-4418
     $mask = CRM_Core_Action::mask(array(CRM_Core_Permission::getPermission()));
     if ($editLink && $mask & CRM_Core_Permission::EDIT) {
         // do not allow edit for anon users in joomla frontend, CRM-4668
         $config = CRM_Core_Config::singleton();
         if (!$config->userFrameworkFrontend) {
             $this->_editLink = TRUE;
         }
     }
     $links = self::links($this->_map, $this->_editLink, $this->_linkToUF, $this->_profileIds);
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     $names = array();
     static $skipFields = array('group', 'tag');
     foreach ($this->_fields as $key => $field) {
         if (CRM_Utils_Array::value('in_selector', $field) && !in_array($key, $skipFields)) {
             if (strpos($key, '-') !== FALSE) {
                 $value = explode('-', $key);
                 $fieldName = CRM_Utils_Array::value(0, $value);
                 $id = CRM_Utils_Array::value(1, $value);
                 $type = CRM_Utils_Array::value(2, $value);
                 if (!in_array($fieldName, $multipleFields)) {
                     $locationTypeName = NULL;
                     if (is_numeric($id)) {
                         $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
                     } else {
                         if ($id == 'Primary') {
                             $locationTypeName = 1;
                         }
                     }
                     if (!$locationTypeName) {
                         continue;
                     }
                     $locationTypeName = str_replace(' ', '_', $locationTypeName);
                     if (in_array($fieldName, array('phone', 'im', 'email'))) {
                         if ($type) {
                             $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
                         } else {
                             $names[] = "{$locationTypeName}-{$fieldName}";
                         }
                     } else {
                         $names[] = "{$locationTypeName}-{$fieldName}";
                     }
                 } else {
                     $names[] = "website-{$id}-{$fieldName}";
                 }
             } elseif ($field['name'] == 'id') {
                 $names[] = 'contact_id';
             } else {
                 $names[] = $field['name'];
             }
         }
     }
     $multipleSelectFields = array('preferred_communication_method' => 1);
     if (CRM_Core_Permission::access('Quest')) {
         $multipleSelectFields = CRM_Quest_BAO_Student::$multipleSelectFields;
     }
     // we need to determine of overlay profile should be shown
     $showProfileOverlay = CRM_Core_BAO_UFGroup::showOverlayProfile();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     $websiteTypes = CRM_Core_PseudoConstant::websiteType();
     $languages = CRM_Core_PseudoConstant::languages();
     while ($result->fetch()) {
         if (isset($result->country)) {
             // the query returns the untranslated country name
             $i18n = CRM_Core_I18n::singleton();
             $result->country = $i18n->translate($result->country);
         }
         $row = array();
         $empty = TRUE;
         $row[] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id, $showProfileOverlay);
         if ($result->sort_name) {
             $row['sort_name'] = $result->sort_name;
             $empty = FALSE;
         } else {
             continue;
         }
         foreach ($names as $name) {
             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                 $row[] = CRM_Core_BAO_CustomField::getDisplayValue($result->{$name}, $cfID, $this->_options, $result->contact_id);
             } elseif (substr($name, -4) == '-url' && !empty($result->{$name})) {
                 $url = CRM_Utils_System::fixURL($result->{$name});
                 $typeId = substr($name, 0, -4) . "-website_type_id";
                 $typeName = $websiteTypes[$result->{$typeId}];
                 if ($typeName) {
                     $row[] = "<a href=\"{$url}\">{$result->{$name}} ({$typeName})</a>";
                 } else {
                     $row[] = "<a href=\"{$url}\">{$result->{$name}}</a>";
                 }
             } elseif ($name == 'preferred_language') {
                 $row[] = $languages[$result->{$name}];
             } elseif ($multipleSelectFields && array_key_exists($name, $multipleSelectFields)) {
                 //fix to display student checkboxes
                 $key = $name;
                 $paramsNew = array($key => $result->{$name});
                 if ($key == 'test_tutoring') {
                     $name = array($key => array('newName' => $key, 'groupName' => 'test'));
                     // for  readers group
                 } elseif (substr($key, 0, 4) == 'cmr_') {
                     $name = array($key => array('newName' => $key, 'groupName' => substr($key, 0, -3)));
                 } else {
                     $name = array($key => array('newName' => $key, 'groupName' => $key));
                 }
                 CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
                 $row[] = $paramsNew[$key];
             } elseif (strpos($name, '-im')) {
                 if (!empty($result->{$name})) {
                     $providerId = $name . "-provider_id";
                     $providerName = $imProviders[$result->{$providerId}];
                     $row[] = $result->{$name} . " ({$providerName})";
                 } else {
                     $row[] = '';
                 }
             } elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) {
                 $dname = $name . '_display';
                 $row[] = $result->{$dname};
             } elseif (in_array($name, array('birth_date', 'deceased_date'))) {
                 $row[] = CRM_Utils_Date::customFormat($result->{$name});
             } elseif (isset($result->{$name})) {
                 $row[] = $result->{$name};
             } else {
                 $row[] = '';
             }
             if (!empty($result->{$name})) {
                 $empty = FALSE;
             }
         }
         $newLinks = $links;
         $params = array('id' => $result->contact_id, 'gid' => implode(',', $this->_profileIds));
         if ($this->_linkToUF) {
             $ufID = CRM_Core_BAO_UFMatch::getUFId($result->contact_id);
             if (!$ufID) {
                 unset($newLinks[CRM_Core_Action::PROFILE]);
             } else {
                 $params['ufID'] = $ufID;
             }
         }
         $row[] = CRM_Core_Action::formLink($newLinks, $mask, $params);
         if (!$empty) {
             $rows[] = $row;
         }
     }
     return $rows;
 }
示例#12
0
 /**
  *
  * Get the values for pseudoconstants for name->value and reverse.
  *
  * @param array   $defaults (reference) the default values, some of which need to be resolved.
  * @param boolean $reverse  true if we want to resolve the values in the reverse direction (value -> name)
  *
  * @return none
  * @access public
  * @static
  */
 static function resolveDefaults(&$defaults, $reverse = false)
 {
     // hack for birth_date
     if (CRM_Utils_Array::value('birth_date', $defaults)) {
         if (is_array($defaults['birth_date'])) {
             $defaults['birth_date'] = CRM_Utils_Date::format($defaults['birth_date'], '-');
         }
     }
     CRM_Utils_Array::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant::individualPrefix(), $reverse);
     CRM_Utils_Array::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant::individualSuffix(), $reverse);
     CRM_Utils_Array::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant::gender(), $reverse);
     //lookup value of email/postal greeting, addressee, CRM-4575
     $filterCondition = array('contact_type' => CRM_Utils_Array::value('contact_type', $defaults), 'greeting_type' => 'email_greeting');
     CRM_Utils_Array::lookupValue($defaults, 'email_greeting', CRM_Core_PseudoConstant::greeting($filterCondition), $reverse);
     $filterCondition = array('contact_type' => CRM_Utils_Array::value('contact_type', $defaults), 'greeting_type' => 'postal_greeting');
     CRM_Utils_Array::lookupValue($defaults, 'postal_greeting', CRM_Core_PseudoConstant::greeting($filterCondition), $reverse);
     $filterCondition = array('contact_type' => CRM_Utils_Array::value('contact_type', $defaults), 'greeting_type' => 'addressee');
     CRM_Utils_Array::lookupValue($defaults, 'addressee', CRM_Core_PseudoConstant::greeting($filterCondition), $reverse);
     $blocks = array('address', 'im', 'phone');
     foreach ($blocks as $name) {
         if (!array_key_exists($name, $defaults) || !is_array($defaults[$name])) {
             continue;
         }
         foreach ($defaults[$name] as $count => &$values) {
             //get location type id.
             CRM_Utils_Array::lookupValue($values, 'location_type', CRM_Core_PseudoConstant::locationType(), $reverse);
             if ($name == 'address') {
                 // FIXME: lookupValue doesn't work for vcard_name
                 if (CRM_Utils_Array::value('location_type_id', $values)) {
                     $vcardNames =& CRM_Core_PseudoConstant::locationVcardName();
                     $values['vcard_name'] = $vcardNames[$values['location_type_id']];
                 }
                 if (!CRM_Utils_Array::lookupValue($values, 'state_province', CRM_Core_PseudoConstant::stateProvince(), $reverse) && $reverse) {
                     CRM_Utils_Array::lookupValue($values, 'state_province', CRM_Core_PseudoConstant::stateProvinceAbbreviation(), $reverse);
                 }
                 if (!CRM_Utils_Array::lookupValue($values, 'country', CRM_Core_PseudoConstant::country(), $reverse) && $reverse) {
                     CRM_Utils_Array::lookupValue($values, 'country', CRM_Core_PseudoConstant::countryIsoCode(), $reverse);
                 }
                 CRM_Utils_Array::lookupValue($values, 'county', CRM_Core_PseudoConstant::county(), $reverse);
             }
             if ($name == 'im') {
                 CRM_Utils_Array::lookupValue($values, 'provider', CRM_Core_PseudoConstant::IMProvider(), $reverse);
             }
             if ($name == 'phone') {
                 CRM_Utils_Array::lookupValue($values, 'phone_type', CRM_Core_PseudoConstant::phoneType(), $reverse);
             }
             //kill the reference.
             unset($values);
         }
     }
 }
示例#13
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();
 }
 /**
  *
  * Get the values for pseudoconstants for name->value and reverse.
  *
  * @param array   $defaults (reference) the default values, some of which need to be resolved.
  * @param boolean $reverse  true if we want to resolve the values in the reverse direction (value -> name)
  *
  * @return none
  * @access public
  * @static
  */
 static function resolveDefaults(&$defaults, $reverse = FALSE)
 {
     // hack for birth_date
     if (CRM_Utils_Array::value('birth_date', $defaults)) {
         if (is_array($defaults['birth_date'])) {
             $defaults['birth_date'] = CRM_Utils_Date::format($defaults['birth_date'], '-');
         }
     }
     CRM_Utils_Array::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant::individualPrefix(), $reverse);
     CRM_Utils_Array::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant::individualSuffix(), $reverse);
     CRM_Utils_Array::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant::gender(), $reverse);
     //lookup value of email/postal greeting, addressee, CRM-4575
     foreach (self::$_greetingTypes as $greeting) {
         $filterCondition = array('contact_type' => CRM_Utils_Array::value('contact_type', $defaults), 'greeting_type' => $greeting);
         CRM_Utils_Array::lookupValue($defaults, $greeting, CRM_Core_PseudoConstant::greeting($filterCondition), $reverse);
     }
     $blocks = array('address', 'im', 'phone');
     foreach ($blocks as $name) {
         if (!array_key_exists($name, $defaults) || !is_array($defaults[$name])) {
             continue;
         }
         foreach ($defaults[$name] as $count => &$values) {
             //get location type id.
             CRM_Utils_Array::lookupValue($values, 'location_type', CRM_Core_PseudoConstant::locationType(), $reverse);
             if ($name == 'address') {
                 // FIXME: lookupValue doesn't work for vcard_name
                 if (CRM_Utils_Array::value('location_type_id', $values)) {
                     $vcardNames = CRM_Core_PseudoConstant::locationVcardName();
                     $values['vcard_name'] = $vcardNames[$values['location_type_id']];
                 }
                 if (!CRM_Utils_Array::lookupValue($values, 'country', CRM_Core_PseudoConstant::country(), $reverse) && $reverse) {
                     CRM_Utils_Array::lookupValue($values, 'country', CRM_Core_PseudoConstant::countryIsoCode(), $reverse);
                 }
                 // CRM-7597
                 // if we find a country id above, we need to restrict it to that country
                 // rather than the list of all countries
                 if (!empty($values['country_id'])) {
                     $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($values['country_id']);
                 } else {
                     $stateProvinceList = CRM_Core_PseudoConstant::stateProvince();
                 }
                 if (!CRM_Utils_Array::lookupValue($values, 'state_province', $stateProvinceList, $reverse) && $reverse) {
                     if (!empty($values['country_id'])) {
                         $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($values['country_id'], 'abbreviation');
                     } else {
                         $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviation();
                     }
                     CRM_Utils_Array::lookupValue($values, 'state_province', $stateProvinceList, $reverse);
                 }
                 if (!empty($values['state_province_id'])) {
                     $countyList = CRM_Core_PseudoConstant::countyForState($values['state_province_id']);
                 } else {
                     $countyList = CRM_Core_PseudoConstant::county();
                 }
                 CRM_Utils_Array::lookupValue($values, 'county', $countyList, $reverse);
             }
             if ($name == 'im') {
                 CRM_Utils_Array::lookupValue($values, 'provider', CRM_Core_PseudoConstant::IMProvider(), $reverse);
             }
             if ($name == 'phone') {
                 CRM_Utils_Array::lookupValue($values, 'phone_type', CRM_Core_PseudoConstant::phoneType(), $reverse);
             }
             //kill the reference.
             unset($values);
         }
     }
 }
 /**
  * returns all the rows in the given offset and rowCount
  *
  * @param enum   $action   the action being performed
  * @param int    $offset   the row number to start from
  * @param int    $rowCount the number of rows to return
  * @param string $sort     the sql string that describes the sort order
  * @param enum   $output   what should the result set include (web/email/csv)
  *
  * @return int   the total number of rows for this action
  */
 function &getRows($action, $offset, $rowCount, $sort, $output = NULL)
 {
     $config = CRM_Core_Config::singleton();
     if (($output == CRM_Core_Selector_Controller::EXPORT || $output == CRM_Core_Selector_Controller::SCREEN) && $this->_formValues['radio_ts'] == 'ts_sel') {
         $includeContactIds = TRUE;
     } else {
         $includeContactIds = FALSE;
     }
     // note the formvalues were given by CRM_Contact_Form_Search to us
     // and contain the search criteria (parameters)
     // note that the default action is basic
     $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, $includeContactIds);
     // process the result of the query
     $rows = array();
     $permissions = array(CRM_Core_Permission::getPermission());
     if (CRM_Core_Permission::check('delete contacts')) {
         $permissions[] = CRM_Core_Permission::DELETE;
     }
     $mask = CRM_Core_Action::mask($permissions);
     // mask value to hide map link if there are not lat/long
     $mapMask = $mask & 4095;
     if ($this->_searchContext == 'smog') {
         $gc = CRM_Core_SelectValues::groupContactStatus();
     }
     if ($this->_ufGroupID) {
         $locationTypes = CRM_Core_PseudoConstant::locationType();
         $names = array();
         static $skipFields = array('group', 'tag');
         foreach ($this->_fields as $key => $field) {
             if (CRM_Utils_Array::value('in_selector', $field) && !in_array($key, $skipFields)) {
                 if (strpos($key, '-') !== FALSE) {
                     list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $key, 3);
                     if ($id == 'Primary') {
                         $locationTypeName = 1;
                     } else {
                         $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
                         if (!$locationTypeName) {
                             continue;
                         }
                     }
                     $locationTypeName = str_replace(' ', '_', $locationTypeName);
                     if (in_array($fieldName, array('phone', 'im', 'email'))) {
                         if ($type) {
                             $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
                         } else {
                             $names[] = "{$locationTypeName}-{$fieldName}";
                         }
                     } else {
                         $names[] = "{$locationTypeName}-{$fieldName}";
                     }
                 } else {
                     $names[] = $field['name'];
                 }
             }
         }
         $names[] = "status";
     } elseif (!empty($this->_returnProperties)) {
         $names = self::makeProperties($this->_returnProperties);
     } else {
         $names = self::$_properties;
     }
     //hack for student data (checkboxs)
     $multipleSelectFields = array('preferred_communication_method' => 1);
     if (CRM_Core_Permission::access('Quest')) {
         $multipleSelectFields = CRM_Quest_BAO_Student::$multipleSelectFields;
     }
     $links = self::links($this->_context, $this->_contextMenu, $this->_key);
     //check explicitly added contact to a Smart Group.
     $groupID = CRM_Utils_Array::key('1', $this->_formValues['group']);
     // for CRM-3157 purposes
     if (in_array('country', $names)) {
         $countries = CRM_Core_PseudoConstant::country();
     }
     if (in_array('state_province', $names)) {
         $provinces = CRM_Core_PseudoConstant::stateProvince();
     }
     if (in_array('world_region', $names)) {
         $regions = CRM_Core_PseudoConstant::worldRegion();
     }
     $seenIDs = array();
     while ($result->fetch()) {
         $row = array();
         // the columns we are interested in
         foreach ($names as $property) {
             if ($property == 'status') {
                 continue;
             }
             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($property)) {
                 $row[$property] = CRM_Core_BAO_CustomField::getDisplayValue($result->{$property}, $cfID, $this->_options, $result->contact_id);
             } elseif ($multipleSelectFields && array_key_exists($property, $multipleSelectFields)) {
                 //fix to display student checkboxes
                 $key = $property;
                 $paramsNew = array($key => $result->{$property});
                 if ($key == 'test_tutoring') {
                     $name = array($key => array('newName' => $key, 'groupName' => 'test'));
                     // for  readers group
                 } elseif (substr($key, 0, 4) == 'cmr_') {
                     $name = array($key => array('newName' => $key, 'groupName' => substr($key, 0, -3)));
                 } else {
                     $name = array($key => array('newName' => $key, 'groupName' => $key));
                 }
                 CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
                 $row[$key] = $paramsNew[$key];
             } elseif (isset($tmfFields) && $tmfFields && array_key_exists($property, $tmfFields) || substr($property, 0, 12) == 'participant_') {
                 if (substr($property, -3) == '_id') {
                     $key = substr($property, 0, -3);
                     $paramsNew = array($key => $result->{$property});
                     $name = array($key => array('newName' => $key, 'groupName' => $key));
                     CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
                     $row[$key] = $paramsNew[$key];
                 } else {
                     $row[$property] = $result->{$property};
                 }
             } elseif (strpos($property, '-im')) {
                 $row[$property] = $result->{$property};
                 if (!empty($result->{$property})) {
                     $imProviders = CRM_Core_PseudoConstant::IMProvider();
                     $providerId = $property . "-provider_id";
                     $providerName = $imProviders[$result->{$providerId}];
                     $row[$property] = $result->{$property} . " ({$providerName})";
                 }
             } elseif (in_array($property, array('addressee', 'email_greeting', 'postal_greeting'))) {
                 $greeting = $property . '_display';
                 $row[$property] = $result->{$greeting};
             } elseif ($property == 'country') {
                 $row[$property] = CRM_Utils_Array::value($result->country_id, $countries);
             } elseif ($property == 'state_province') {
                 $row[$property] = CRM_Utils_Array::value($result->state_province_id, $provinces);
             } elseif ($property == 'world_region') {
                 $row[$property] = $regions[$result->world_region_id];
             } elseif (strpos($property, '-url') !== FALSE) {
                 $websiteUrl = '';
                 $websiteKey = 'website-1';
                 $websiteFld = $websiteKey . '-' . array_pop(explode('-', $property));
                 if (!empty($result->{$websiteFld})) {
                     $websiteTypes = CRM_Core_PseudoConstant::websiteType();
                     $websiteType = $websiteTypes[$result->{"{$websiteKey}-website_type_id"}];
                     $websiteValue = $result->{$websiteFld};
                     $websiteUrl = "<a href=\"{$websiteValue}\">{$websiteValue}  ({$websiteType})</a>";
                 }
                 $row[$property] = $websiteUrl;
             } else {
                 $row[$property] = isset($result->{$property}) ? $result->{$property} : NULL;
             }
         }
         if (!empty($result->postal_code_suffix)) {
             $row['postal_code'] .= "-" . $result->postal_code_suffix;
         }
         if ($output != CRM_Core_Selector_Controller::EXPORT && $this->_searchContext == 'smog') {
             if (empty($result->status) && $groupID) {
                 $contactID = $result->contact_id;
                 if ($contactID) {
                     $gcParams = array('contact_id' => $contactID, 'group_id' => $groupID);
                     $gcDefaults = array();
                     CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
                     if (empty($gcDefaults)) {
                         $row['status'] = ts('Smart');
                     } else {
                         $row['status'] = $gc[$gcDefaults['status']];
                     }
                 } else {
                     $row['status'] = NULL;
                 }
             } else {
                 $row['status'] = $gc[$result->status];
             }
         }
         if ($output != CRM_Core_Selector_Controller::EXPORT) {
             $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contact_id;
             if (CRM_Utils_Array::value('deleted_contacts', $this->_formValues) && CRM_Core_Permission::check('access deleted contacts')) {
                 $links = array(array('name' => ts('View'), 'url' => 'civicrm/contact/view', 'qs' => 'reset=1&cid=%%id%%', 'title' => ts('View Contact Details')), array('name' => ts('Restore'), 'url' => 'civicrm/contact/view/delete', 'qs' => 'reset=1&cid=%%id%%&restore=1', 'title' => ts('Restore Contact')));
                 if (CRM_Core_Permission::check('delete contacts')) {
                     $links[] = array('name' => ts('Delete Permanently'), 'url' => 'civicrm/contact/view/delete', 'qs' => 'reset=1&cid=%%id%%&skip_undelete=1', 'title' => ts('Permanently Delete Contact'));
                 }
                 $row['action'] = CRM_Core_Action::formLink($links, NULL, array('id' => $result->contact_id));
             } elseif (is_numeric(CRM_Utils_Array::value('geo_code_1', $row)) || $config->mapGeoCoding && CRM_Utils_Array::value('city', $row) && CRM_Utils_Array::value('state_province', $row)) {
                 $row['action'] = CRM_Core_Action::formLink($links, $mask, array('id' => $result->contact_id));
             } else {
                 $row['action'] = CRM_Core_Action::formLink($links, $mapMask, array('id' => $result->contact_id));
             }
             // allow components to add more actions
             CRM_Core_Component::searchAction($row, $result->contact_id);
             $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id);
             $row['contact_type_orig'] = $result->contact_type;
             $row['contact_sub_type'] = $result->contact_sub_type;
             $row['contact_id'] = $result->contact_id;
             $row['sort_name'] = $result->sort_name;
             if (array_key_exists('id', $row)) {
                 $row['id'] = $result->contact_id;
             }
         }
         // Dedupe contacts
         if (in_array($row['contact_id'], $seenIDs) === FALSE) {
             $seenIDs[] = $row['contact_id'];
             $rows[] = $row;
         }
     }
     $this->buildPrevNextCache($sort);
     return $rows;
 }
示例#16
0
 /**
  * Function to build profile form
  *
  * @params object  $form       form object
  * @params array   $field      array field properties
  * @params int     $mode       profile mode
  * @params int     $contactID  contact id
  *
  * @return null
  * @static
  * @access public
  */
 static function buildProfile(&$form, &$field, $mode, $contactId = null, $online = false)
 {
     require_once "CRM/Profile/Form.php";
     require_once "CRM/Core/OptionGroup.php";
     require_once 'CRM/Core/BAO/UFField.php';
     require_once 'CRM/Contact/BAO/ContactType.php';
     $defaultValues = array();
     $fieldName = $field['name'];
     $title = $field['title'];
     $attributes = $field['attributes'];
     $rule = $field['rule'];
     $view = $field['is_view'];
     $required = $mode == CRM_Profile_Form::MODE_SEARCH ? false : $field['is_required'];
     $search = $mode == CRM_Profile_Form::MODE_SEARCH ? true : false;
     // do not display view fields in drupal registration form
     // CRM-4632
     if ($view && $mode == CRM_Profile_Form::MODE_REGISTER) {
         return;
     }
     if ($contactId && !$online) {
         $name = "field[{$contactId}][{$fieldName}]";
     } else {
         $name = $fieldName;
     }
     require_once 'CRM/Core/BAO/Preferences.php';
     $addressOptions = CRM_Core_BAO_Preferences::valueOptions('address_options', true, null, true);
     if (substr($fieldName, 0, 14) === 'state_province') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvince(), $required);
     } else {
         if (substr($fieldName, 0, 7) === 'country') {
             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::country(), $required);
             $config =& CRM_Core_Config::singleton();
             if (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)) && $config->defaultContactCountry) {
                 $defaultValues[$name] = $config->defaultContactCountry;
                 $form->setDefaults($defaultValues);
             }
         } else {
             if (substr($fieldName, 0, 6) === 'county') {
                 if ($addressOptions['county']) {
                     $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::county(), $required);
                 }
             } else {
                 if (substr($fieldName, 0, 2) === 'im') {
                     if (!$contactId) {
                         $form->add('select', $name . '-provider_id', $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::IMProvider(), $required);
                         if ($view && $mode != CRM_Profile_Form::MODE_SEARCH) {
                             $form->freeze($name . "-provider_id");
                         }
                     }
                     $form->add('text', $name, $title, $attributes, $required);
                 } else {
                     if ($fieldName === 'birth_date' || $fieldName === 'deceased_date') {
                         $form->addDate($name, $title, $required, array('formatType' => 'birth'));
                     } else {
                         if (in_array($fieldName, array("membership_start_date", "membership_end_date", "join_date"))) {
                             $form->addDate($name, $title, $required, array('formatType' => 'custom'));
                         } else {
                             if ($field['name'] == 'membership_type_id') {
                                 require_once 'CRM/Member/PseudoConstant.php';
                                 $form->add('select', 'membership_type_id', $title, array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipType(), $required);
                             } else {
                                 if ($field['name'] == 'status_id') {
                                     require_once 'CRM/Member/PseudoConstant.php';
                                     $form->add('select', 'status_id', $title, array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(), $required);
                                 } else {
                                     if ($fieldName === 'gender') {
                                         $genderOptions = array();
                                         $gender = CRM_Core_PseudoConstant::gender();
                                         foreach ($gender as $key => $var) {
                                             $genderOptions[$key] = HTML_QuickForm::createElement('radio', null, ts('Gender'), $var, $key);
                                         }
                                         $form->addGroup($genderOptions, $name, $title);
                                         if ($required) {
                                             $form->addRule($name, ts('%1 is a required field.', array(1 => $title)), 'required');
                                         }
                                     } else {
                                         if ($fieldName === 'individual_prefix') {
                                             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::individualPrefix(), $required);
                                         } else {
                                             if ($fieldName === 'individual_suffix') {
                                                 $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::individualSuffix(), $required);
                                             } else {
                                                 if ($fieldName === 'contact_sub_type') {
                                                     $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $form->_fields[$fieldName]);
                                                     $profileType = $gId ? CRM_Core_BAO_UFField::getProfileType($gId) : null;
                                                     $setSubtype = false;
                                                     if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
                                                         $setSubtype = $profileType;
                                                         $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
                                                     }
                                                     $subtypes = $profileType ? CRM_Contact_BAO_ContactType::subTypePairs($profileType) : array();
                                                     if ($setSubtype) {
                                                         $subtypeList = array();
                                                         $subtypeList[$setSubtype] = $subtypes[$setSubtype];
                                                     } else {
                                                         $subtypeList = array('' => ts('- select -')) + $subtypes;
                                                     }
                                                     $form->add('select', $name, $title, $subtypeList, $required);
                                                 } else {
                                                     if (in_array($fieldName, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                         //add email greeting, postal greeting, addressee, CRM-4575
                                                         $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $field);
                                                         $profileType = CRM_Core_BAO_UFField::getProfileType($gId, true, false, true);
                                                         if (empty($profileType) || in_array($profileType, array('Contact', 'Contribution', 'Participant', 'Membership'))) {
                                                             $profileType = 'Individual';
                                                         }
                                                         if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
                                                             $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
                                                         }
                                                         if ($fieldName == 'email_greeting') {
                                                             $emailGreeting = array('contact_type' => $profileType, 'greeting_type' => 'email_greeting');
                                                             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::greeting($emailGreeting), $required);
                                                             // adding custom email greeting element alongwith email greeting
                                                             $form->add('text', 'email_greeting_custom', ts('Custom Email Greeting'), null, false);
                                                         } else {
                                                             if ($fieldName === 'postal_greeting') {
                                                                 $postalGreeting = array('contact_type' => $profileType, 'greeting_type' => 'postal_greeting');
                                                                 $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::greeting($postalGreeting), $required);
                                                                 // adding custom postal greeting element alongwith postal greeting
                                                                 $form->add('text', 'postal_greeting_custom', ts('Custom Postal Greeting'), null, false);
                                                             } else {
                                                                 if ($fieldName === 'addressee') {
                                                                     $addressee = array('contact_type' => $profileType, 'greeting_type' => 'addressee');
                                                                     $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::greeting($addressee), $required);
                                                                     // adding custom addressee  element alongwith addressee type
                                                                     $form->add('text', 'addressee_custom', ts('Custom Addressee'), null, false);
                                                                 }
                                                             }
                                                         }
                                                     } else {
                                                         if ($fieldName === 'preferred_communication_method') {
                                                             $communicationFields = CRM_Core_PseudoConstant::pcm();
                                                             foreach ($communicationFields as $key => $var) {
                                                                 if ($key == '') {
                                                                     continue;
                                                                 }
                                                                 $communicationOptions[] =& HTML_QuickForm::createElement('checkbox', $key, null, $var);
                                                             }
                                                             $form->addGroup($communicationOptions, $name, $title, '<br/>');
                                                         } else {
                                                             if ($fieldName === 'preferred_mail_format') {
                                                                 $form->add('select', $name, $title, CRM_Core_SelectValues::pmf());
                                                             } else {
                                                                 if ($fieldName == 'external_identifier') {
                                                                     $form->add('text', $name, $title, $attributes, $required);
                                                                     $contID = $contactId;
                                                                     if (!$contID) {
                                                                         $contID = $form->get('id');
                                                                     }
                                                                     $form->addRule($name, ts('External ID already exists in Database.'), 'objectExists', array('CRM_Contact_DAO_Contact', $contID, 'external_identifier'));
                                                                 } else {
                                                                     if ($fieldName === 'group') {
                                                                         require_once 'CRM/Contact/Form/Edit/TagsAndGroups.php';
                                                                         CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($form, $contactId, CRM_Contact_Form_Edit_TagsAndGroups::GROUP, true, $required, $title, null, $name);
                                                                     } else {
                                                                         if ($fieldName === 'tag') {
                                                                             require_once 'CRM/Contact/Form/Edit/TagsAndGroups.php';
                                                                             CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($form, $contactId, CRM_Contact_Form_Edit_TagsAndGroups::TAG, false, $required, null, $title, $name);
                                                                         } else {
                                                                             if ($fieldName === 'home_URL') {
                                                                                 $form->addElement('text', $name, $title, array_merge(CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'home_URL'), array('onfocus' => "if (!this.value) this.value='http://'; else return false", 'onblur' => "if ( this.value == 'http://') this.value=''; else return false")));
                                                                                 $form->addRule($name, ts('Enter a valid Website.'), 'url');
                                                                             } else {
                                                                                 if (substr($fieldName, 0, 6) === 'custom') {
                                                                                     $customFieldID = CRM_Core_BAO_CustomField::getKeyID($fieldName);
                                                                                     if ($customFieldID) {
                                                                                         CRM_Core_BAO_CustomField::addQuickFormElement($form, $name, $customFieldID, false, $required, $search, $title);
                                                                                     }
                                                                                 } else {
                                                                                     if (in_array($fieldName, array('receive_date', 'receipt_date', 'thankyou_date', 'cancel_date'))) {
                                                                                         $form->addDate($name, $title, $required, array('formatType' => 'custom'));
                                                                                     } else {
                                                                                         if ($fieldName == 'payment_instrument') {
                                                                                             require_once "CRM/Contribute/PseudoConstant.php";
                                                                                             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), $required);
                                                                                         } else {
                                                                                             if ($fieldName == 'contribution_type') {
                                                                                                 require_once "CRM/Contribute/PseudoConstant.php";
                                                                                                 $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType(), $required);
                                                                                             } else {
                                                                                                 if ($fieldName == 'contribution_status_id') {
                                                                                                     require_once "CRM/Contribute/PseudoConstant.php";
                                                                                                     $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionStatus(), $required);
                                                                                                 } else {
                                                                                                     if ($fieldName == 'participant_register_date') {
                                                                                                         $form->addDateTime($name, $title, $required, array('formatType' => 'activityDateTime'));
                                                                                                     } else {
                                                                                                         if ($fieldName == 'participant_status_id') {
                                                                                                             require_once "CRM/Event/PseudoConstant.php";
                                                                                                             $cond = null;
                                                                                                             if ($online == true) {
                                                                                                                 $cond = "visibility_id = 1";
                                                                                                             }
                                                                                                             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Event_PseudoConstant::participantStatus(null, $cond), $required);
                                                                                                         } else {
                                                                                                             if ($fieldName == 'participant_role_id') {
                                                                                                                 require_once "CRM/Event/PseudoConstant.php";
                                                                                                                 $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Event_PseudoConstant::participantRole(), $required);
                                                                                                             } else {
                                                                                                                 if ($fieldName == 'scholarship_type_id') {
                                                                                                                     $form->add('select', $name, $title, array("" => "-- Select -- ") + array_flip(CRM_Core_OptionGroup::values('scholarship_type', true)));
                                                                                                                 } else {
                                                                                                                     if ($fieldName == 'applicant_status_id') {
                                                                                                                         $form->add('select', $name, $title, array("" => "-- Select -- ") + array_flip(CRM_Core_OptionGroup::values('applicant_status', true)));
                                                                                                                     } else {
                                                                                                                         if ($fieldName == 'highschool_gpa_id') {
                                                                                                                             $form->add('select', $name, $title, array("" => "-- Select -- ") + CRM_Core_OptionGroup::values('highschool_gpa'));
                                                                                                                         } else {
                                                                                                                             if ($fieldName == 'world_region') {
                                                                                                                                 require_once "CRM/Core/PseudoConstant.php";
                                                                                                                                 $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::worldRegion(), $required);
                                                                                                                             } else {
                                                                                                                                 $processed = false;
                                                                                                                                 if (CRM_Core_Permission::access('Quest', false)) {
                                                                                                                                     require_once 'CRM/Quest/BAO/Student.php';
                                                                                                                                     $processed = CRM_Quest_BAO_Student::buildStudentForm($form, $fieldName, $title, $contactId);
                                                                                                                                 }
                                                                                                                                 if (!$processed) {
                                                                                                                                     if (substr($fieldName, 0, 3) === 'is_' or substr($fieldName, 0, 7) === 'do_not_') {
                                                                                                                                         $form->add('checkbox', $name, $title, $attributes, $required);
                                                                                                                                     } else {
                                                                                                                                         $form->add('text', $name, $title, $attributes, $required);
                                                                                                                                     }
                                                                                                                                 }
                                                                                                                             }
                                                                                                                         }
                                                                                                                     }
                                                                                                                 }
                                                                                                             }
                                                                                                         }
                                                                                                     }
                                                                                                 }
                                                                                             }
                                                                                         }
                                                                                     }
                                                                                 }
                                                                             }
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     static $hiddenSubtype = false;
     if (!$hiddenSubtype && CRM_Contact_BAO_ContactType::isaSubType($field['field_type'])) {
         // In registration mode params are submitted via POST and we don't have any clue
         // about profile-id or the profile-type (which could be a subtype)
         // To generalize the  behavior and simplify the process,
         // lets always add the hidden
         //subtype value if there is any, and we won't have to
         // compute it while processing.
         $form->addElement('hidden', 'contact_sub_type_hidden', $field['field_type']);
         $hiddenSubtype = true;
     }
     if ($view && $mode != CRM_Profile_Form::MODE_SEARCH) {
         $form->freeze($name);
     }
     //add the rules
     if (in_array($fieldName, array('non_deductible_amount', 'total_amount', 'fee_amount', 'net_amount'))) {
         $form->addRule($name, ts('Please enter a valid amount.'), 'money');
     }
     if ($rule) {
         if (!($rule == 'email' && $mode == CRM_Profile_Form::MODE_SEARCH)) {
             $form->addRule($name, ts('Please enter a valid %1', array(1 => $title)), $rule);
         }
     }
 }
 /**
  * Function to build profile form
  *
  * @params object  $form       form object
  * @params array   $field      array field properties
  * @params int     $mode       profile mode
  * @params int     $contactID  contact id
  *
  * @return null
  * @static
  * @access public
  */
 static function buildProfile(&$form, &$field, $mode, $contactId = NULL, $online = FALSE, $onBehalf = FALSE, $rowNumber = NULL, $prefix = '')
 {
     $defaultValues = array();
     $fieldName = $field['name'];
     $title = $field['title'];
     $attributes = $field['attributes'];
     $rule = $field['rule'];
     $view = $field['is_view'];
     $required = $mode == CRM_Profile_Form::MODE_SEARCH ? FALSE : $field['is_required'];
     $search = $mode == CRM_Profile_Form::MODE_SEARCH ? TRUE : FALSE;
     $isShared = CRM_Utils_Array::value('is_shared', $field, 0);
     // do not display view fields in drupal registration form
     // CRM-4632
     if ($view && $mode == CRM_Profile_Form::MODE_REGISTER) {
         return;
     }
     if ($onBehalf) {
         $name = "onbehalf[{$fieldName}]";
     } elseif ($contactId && !$online) {
         $name = "field[{$contactId}][{$fieldName}]";
     } elseif ($rowNumber) {
         $name = "field[{$rowNumber}][{$fieldName}]";
     } elseif (!empty($prefix)) {
         $name = $prefix . "[{$fieldName}]";
     } else {
         $name = $fieldName;
     }
     if ($fieldName == 'image_URL' && $mode == CRM_Profile_Form::MODE_EDIT) {
         $deleteExtra = ts('Are you sure you want to delete contact image.');
         $deleteURL = array(CRM_Core_Action::DELETE => array('name' => ts('Delete Contact Image'), 'url' => 'civicrm/contact/image', 'qs' => 'reset=1&id=%%id%%&gid=%%gid%%&action=delete', 'extra' => 'onclick = "if (confirm( \'' . $deleteExtra . '\' ) ) this.href+=\'&amp;confirmed=1\'; else return false;"'));
         $deleteURL = CRM_Core_Action::formLink($deleteURL, CRM_Core_Action::DELETE, array('id' => $form->get('id'), 'gid' => $form->get('gid')));
         $form->assign('deleteURL', $deleteURL);
     }
     $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options', TRUE, NULL, TRUE);
     if (substr($fieldName, 0, 14) === 'state_province') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvince(), $required);
     } elseif (substr($fieldName, 0, 7) === 'country') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::country(), $required);
         $config = CRM_Core_Config::singleton();
         if (!in_array($mode, array(CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH)) && $config->defaultContactCountry) {
             $defaultValues[$name] = $config->defaultContactCountry;
             $form->setDefaults($defaultValues);
         }
     } elseif (substr($fieldName, 0, 6) === 'county') {
         if ($addressOptions['county']) {
             $form->add('select', $name, $title, array('' => ts('- select state -')), $required);
         }
     } elseif (substr($fieldName, 0, 9) === 'image_URL') {
         $form->add('file', $name, $title, $attributes, $required);
         $form->addUploadElement($name);
     } elseif (substr($fieldName, 0, 2) === 'im') {
         $form->add('text', $name, $title, $attributes, $required);
         if (!$contactId) {
             if ($onBehalf) {
                 if (substr($name, -1) == ']') {
                     $providerName = substr($name, 0, -1) . '-provider_id]';
                 }
                 $form->add('select', $providerName, NULL, array('' => ts('- select -')) + CRM_Core_PseudoConstant::IMProvider(), $required);
             } else {
                 $form->add('select', $name . '-provider_id', $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::IMProvider(), $required);
             }
             if ($view && $mode != CRM_Profile_Form::MODE_SEARCH) {
                 $form->freeze($name . '-provider_id');
             }
         }
     } elseif ($fieldName === 'birth_date' || $fieldName === 'deceased_date') {
         $form->addDate($name, $title, $required, array('formatType' => 'birth'));
     } elseif (in_array($fieldName, array('membership_start_date', 'membership_end_date', 'join_date'))) {
         $form->addDate($name, $title, $required, array('formatType' => 'custom'));
     } elseif ($field['name'] == 'membership_type') {
         list($orgInfo, $types) = CRM_Member_BAO_MembershipType::getMembershipTypeInfo();
         $sel =& $form->addElement('hierselect', $name, $title);
         $select = array('' => ts('- select -'));
         $sel->setOptions(array($select + $orgInfo, $types));
     } elseif ($field['name'] == 'membership_status') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'), $required);
     } elseif ($fieldName === 'gender') {
         $genderOptions = array();
         $gender = CRM_Core_PseudoConstant::gender();
         foreach ($gender as $key => $var) {
             $genderOptions[$key] = $form->createElement('radio', NULL, ts('Gender'), $var, $key);
         }
         $form->addGroup($genderOptions, $name, $title);
         if ($required) {
             $form->addRule($name, ts('%1 is a required field.', array(1 => $title)), 'required');
         }
     } elseif ($fieldName === 'individual_prefix') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::individualPrefix(), $required);
     } elseif ($fieldName === 'individual_suffix') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::individualSuffix(), $required);
     } elseif ($fieldName === 'contact_sub_type') {
         $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $form->_fields[$fieldName]);
         if ($onBehalf) {
             $profileType = 'Organization';
         } else {
             $profileType = $gId ? CRM_Core_BAO_UFField::getProfileType($gId) : NULL;
         }
         $setSubtype = FALSE;
         if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
             $setSubtype = $profileType;
             $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
         }
         $subtypes = $profileType ? CRM_Contact_BAO_ContactType::subTypePairs($profileType) : array();
         if ($setSubtype) {
             $subtypeList = array();
             $subtypeList[$setSubtype] = $subtypes[$setSubtype];
         } else {
             $subtypeList = $subtypes;
         }
         $sel = $form->add('select', $name, $title, $subtypeList, $required);
         $sel->setMultiple(TRUE);
     } elseif (in_array($fieldName, CRM_Contact_BAO_Contact::$_greetingTypes)) {
         //add email greeting, postal greeting, addressee, CRM-4575
         $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $field);
         $profileType = CRM_Core_BAO_UFField::getProfileType($gId, TRUE, FALSE, TRUE);
         if (empty($profileType) || in_array($profileType, array('Contact', 'Contribution', 'Participant', 'Membership'))) {
             $profileType = 'Individual';
         }
         if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) {
             $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType);
         }
         $greeting = array('contact_type' => $profileType, 'greeting_type' => $fieldName);
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::greeting($greeting), $required);
         // add custom greeting element
         $form->add('text', $fieldName . '_custom', ts('Custom %1', array(1 => ucwords(str_replace('_', ' ', $fieldName)))), NULL, FALSE);
     } elseif ($fieldName === 'preferred_communication_method') {
         $communicationFields = CRM_Core_PseudoConstant::pcm();
         foreach ($communicationFields as $key => $var) {
             if ($key == '') {
                 continue;
             }
             $communicationOptions[] = $form->createElement('checkbox', $key, NULL, $var);
         }
         $form->addGroup($communicationOptions, $name, $title, '<br/>');
     } elseif ($fieldName === 'preferred_mail_format') {
         $form->add('select', $name, $title, CRM_Core_SelectValues::pmf());
     } elseif ($fieldName === 'preferred_language') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::languages());
     } elseif ($fieldName == 'external_identifier') {
         $form->add('text', $name, $title, $attributes, $required);
         $contID = $contactId;
         if (!$contID) {
             $contID = $form->get('id');
         }
         $form->addRule($name, ts('External ID already exists in Database.'), 'objectExists', array('CRM_Contact_DAO_Contact', $contID, 'external_identifier'));
     } elseif ($fieldName === 'group') {
         CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($form, $contactId, CRM_Contact_Form_Edit_TagsAndGroups::GROUP, TRUE, $required, $title, NULL, $name);
     } elseif ($fieldName === 'tag') {
         CRM_Contact_Form_Edit_TagsAndGroups::buildQuickForm($form, $contactId, CRM_Contact_Form_Edit_TagsAndGroups::TAG, FALSE, $required, NULL, $title, $name);
     } elseif (substr($fieldName, 0, 4) === 'url-') {
         $form->addElement('text', $name, $title, array_merge(CRM_Core_DAO::getAttribute('CRM_Core_DAO_Website', 'url'), array('onfocus' => "if (!this.value) {  this.value='http://';} else return false", 'onblur' => "if ( this.value == 'http://') {  this.value='';} else return false")));
         $form->addRule($name, ts('Enter a valid Website.'), 'url');
         //Website type select
         if ($onBehalf) {
             if (substr($name, -1) == ']') {
                 $websiteTypeName = substr($name, 0, -1) . '-website_type_id]';
             }
             $form->addElement('select', $websiteTypeName, NULL, CRM_Core_PseudoConstant::websiteType());
         } else {
             $form->addElement('select', $name . '-website_type_id', NULL, CRM_Core_PseudoConstant::websiteType());
         }
         // added because note appeared as a standard text input
     } elseif ($fieldName == 'note') {
         $form->add('textarea', $name, $title, $attributes, $required);
     } elseif (substr($fieldName, 0, 6) === 'custom') {
         $customFieldID = CRM_Core_BAO_CustomField::getKeyID($fieldName);
         if ($customFieldID) {
             CRM_Core_BAO_CustomField::addQuickFormElement($form, $name, $customFieldID, FALSE, $required, $search, $title);
         }
     } elseif (substr($fieldName, 0, 14) === 'address_custom') {
         list($fName, $locTypeId) = CRM_Utils_System::explode('-', $fieldName, 2);
         $customFieldID = CRM_Core_BAO_CustomField::getKeyID(substr($fName, 8));
         if ($customFieldID) {
             CRM_Core_BAO_CustomField::addQuickFormElement($form, $name, $customFieldID, FALSE, $required, $search, $title);
         }
     } elseif (in_array($fieldName, array('receive_date', 'receipt_date', 'thankyou_date', 'cancel_date'))) {
         $form->addDateTime($name, $title, $required, array('formatType' => 'activityDateTime'));
     } elseif ($fieldName == 'send_receipt') {
         $form->addElement('checkbox', $name, $title);
     } elseif ($fieldName == 'soft_credit') {
         CRM_Contact_Form_NewContact::buildQuickForm($form, $rowNumber, NULL, FALSE, 'soft_credit_');
     } elseif ($fieldName == 'product_name') {
         list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
         $sel =& $form->addElement('hierselect', $name, $title);
         $products = array('0' => ts('- select -')) + $products;
         $sel->setOptions(array($products, $options));
     } elseif ($fieldName == 'payment_instrument') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), $required);
     } elseif ($fieldName == 'contribution_type') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType(), $required);
     } elseif ($fieldName == 'contribution_status_id') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionStatus(), $required);
     } elseif ($fieldName == 'currency') {
         $form->addCurrency($name, $title, $required);
     } elseif ($fieldName == 'contribution_page_id') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionPage(), $required, 'class="big"');
     } elseif ($fieldName == 'participant_register_date') {
         $form->addDateTime($name, $title, $required, array('formatType' => 'activityDateTime'));
     } elseif ($fieldName == 'activity_status_id') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::activityStatus(), $required);
     } elseif ($fieldName == 'activity_engagement_level') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Campaign_PseudoConstant::engagementLevel(), $required);
     } elseif ($fieldName == 'activity_date_time') {
         $form->addDateTime($name, $title, $required, array('formatType' => 'activityDateTime'));
     } elseif ($fieldName == 'participant_status') {
         $cond = NULL;
         if ($online == TRUE) {
             $cond = 'visibility_id = 1';
         }
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Event_PseudoConstant::participantStatus(NULL, $cond, 'label'), $required);
     } elseif ($fieldName == 'participant_role') {
         if (CRM_Utils_Array::value('is_multiple', $field)) {
             $form->addCheckBox($name, $title, CRM_Event_PseudoConstant::participantRole(), NULL, NULL, NULL, NULL, '&nbsp', TRUE);
         } else {
             $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Event_PseudoConstant::participantRole(), $required);
         }
     } elseif ($fieldName == 'scholarship_type_id') {
         $form->add('select', $name, $title, array('' => '-- Select -- ') + array_flip(CRM_Core_OptionGroup::values('scholarship_type', TRUE)));
     } elseif ($fieldName == 'applicant_status_id') {
         $form->add('select', $name, $title, array('' => '-- Select -- ') + array_flip(CRM_Core_OptionGroup::values('applicant_status', TRUE)));
     } elseif ($fieldName == 'highschool_gpa_id') {
         $form->add('select', $name, $title, array('' => '-- Select -- ') + CRM_Core_OptionGroup::values('highschool_gpa'));
     } elseif ($fieldName == 'world_region') {
         $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::worldRegion(), $required);
     } elseif ($fieldName == 'signature_html') {
         $form->addWysiwyg($name, $title, CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', $fieldName));
     } elseif ($fieldName == 'signature_text') {
         $form->add('textarea', $name, $title, CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', $fieldName));
     } elseif (substr($fieldName, -11) == 'campaign_id') {
         if (CRM_Campaign_BAO_Campaign::isCampaignEnable()) {
             $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns(CRM_Utils_Array::value($contactId, $form->_componentCampaigns));
             $campaign =& $form->add('select', $name, $title, array('' => ts('- select -')) + $campaigns, $required, 'class="big"');
         }
     } elseif ($fieldName == 'activity_details') {
         $form->addWysiwyg($fieldName, $title, array('rows' => 4, 'cols' => 60), $required);
     } elseif ($fieldName == 'activity_duration') {
         $form->add('text', $fieldName, $title, $attributes, $required);
         $form->addRule($name, ts('Please enter the duration as number of minutes (integers only).'), 'positiveInteger');
     } else {
         $processed = FALSE;
         if (CRM_Core_Permission::access('Quest', FALSE)) {
             $processed = CRM_Quest_BAO_Student::buildStudentForm($form, $fieldName, $title, $contactId);
         }
         if (!$processed) {
             if (substr($fieldName, 0, 3) === 'is_' or substr($fieldName, 0, 7) === 'do_not_') {
                 $form->add('advcheckbox', $name, $title, $attributes, $required);
             } else {
                 $form->add('text', $name, $title, $attributes, $required);
             }
         }
     }
     static $hiddenSubtype = FALSE;
     if (!$hiddenSubtype && CRM_Contact_BAO_ContactType::isaSubType($field['field_type'])) {
         // In registration mode params are submitted via POST and we don't have any clue
         // about profile-id or the profile-type (which could be a subtype)
         // To generalize the  behavior and simplify the process,
         // lets always add the hidden
         //subtype value if there is any, and we won't have to
         // compute it while processing.
         if ($onBehalf) {
             $form->addElement('hidden', 'onbehalf[contact_sub_type]', $field['field_type']);
         } else {
             $form->addElement('hidden', 'contact_sub_type_hidden', $field['field_type']);
         }
         $hiddenSubtype = TRUE;
     }
     if ($view && $mode != CRM_Profile_Form::MODE_SEARCH || $isShared) {
         $form->freeze($name);
     }
     //add the rules
     if (in_array($fieldName, array('non_deductible_amount', 'total_amount', 'fee_amount', 'net_amount'))) {
         $form->addRule($name, ts('Please enter a valid amount.'), 'money');
     }
     if ($rule) {
         if (!($rule == 'email' && $mode == CRM_Profile_Form::MODE_SEARCH)) {
             $form->addRule($name, ts('Please enter a valid %1', array(1 => $title)), $rule);
         }
     }
 }
示例#18
0
 /**
  * Process the mapped fields and map it into the uploaded file
  * preview the file and extract some summary statistics
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     $params = $this->controller->exportValues('MapField');
     //reload the mapfield if load mapping is pressed
     if (!empty($params['savedMapping'])) {
         $this->set('savedMapping', $params['savedMapping']);
         $this->controller->resetPage($this->_name);
         return;
     }
     $mapperKeys = array();
     $mapper = array();
     $mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
     $mapperKeysMain = array();
     $mapperLocType = array();
     $mapperPhoneType = array();
     $mapperImProvider = array();
     $locations = array();
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     for ($i = 0; $i < $this->_columnCount; $i++) {
         $mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
         $mapperKeysMain[$i] = $mapperKeys[$i][0];
         if (isset($mapperKeys[$i][1]) && is_numeric($mapperKeys[$i][1])) {
             $mapperLocType[$i] = $mapperKeys[$i][1];
         } else {
             $mapperLocType[$i] = null;
         }
         $locations[$i] = isset($mapperLocType[$i]) ? $this->_location_types[$mapperLocType[$i]] : null;
         // to store phone_type id and provider id seperately, CRM-3140
         if (CRM_Utils_Array::value($i, $mapperKeysMain) == 'phone') {
             $mapperPhoneType[$i] = $phoneTypes[$mapperKeys[$i][2]];
             $mapperImProvider[$i] = null;
         } else {
             if (CRM_Utils_Array::value($i, $mapperKeysMain) == 'im') {
                 $mapperImProvider[$i] = $imProviders[$mapperKeys[$i][2]];
                 $mapperPhoneType[$i] = null;
             } else {
                 $mapperPhoneType[$i] = null;
                 $mapperImProvider[$i] = null;
             }
         }
         //relationship info
         if (isset($mapperKeys[$i]) && isset($mapperKeys[$i][0])) {
             list($id, $first, $second) = CRM_Utils_System::explode('_', $mapperKeys[$i][0], 3);
         } else {
             list($id, $first, $second) = array(null, null, null);
         }
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $related[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
             $relatedContactLocType[$i] = isset($mapperKeys[$i][1]) ? $this->_location_types[$mapperKeys[$i][2]] : null;
             //$relatedContactPhoneType[$i] = !is_numeric($mapperKeys[$i][2]) ? $mapperKeys[$i][3] : null;
             // to store phoneType id and provider id seperately for ralated contact, CRM-3140
             if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') {
                 $relatedContactPhoneType[$i] = isset($mapperKeys[$i][3]) ? $phoneTypes[$mapperKeys[$i][3]] : null;
                 $relatedContactImProvider[$i] = null;
             } else {
                 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') {
                     $relatedContactImProvider[$i] = isset($mapperKeys[$i][3]) ? $imProviders[$mapperKeys[$i][3]] : null;
                     $relatedContactPhoneType[$i] = null;
                 }
             }
             $relationType =& new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(true);
             eval('$relatedContactType[$i] = $relationType->contact_type_' . $second . ';');
             $relatedContactDetails[$i] = $this->_formattedFieldNames[$relatedContactType[$i]][$mapperKeys[$i][1]];
         } else {
             $related[$i] = null;
             $relatedContactType[$i] = null;
             $relatedContactDetails[$i] = null;
             $relatedContactLocType[$i] = null;
             $relatedContactPhoneType[$i] = null;
             $relatedContactImProvider[$i] = null;
         }
     }
     $this->set('mapper', $mapper);
     $this->set('locations', $locations);
     $this->set('phones', $mapperPhoneType);
     $this->set('ims', $mapperImProvider);
     $this->set('columnNames', $this->_columnNames);
     //relationship info
     $this->set('related', $related);
     $this->set('relatedContactType', $relatedContactType);
     $this->set('relatedContactDetails', $relatedContactDetails);
     $this->set('relatedContactLocType', $relatedContactLocType);
     $this->set('relatedContactPhoneType', $relatedContactPhoneType);
     $this->set('relatedContactImProvider', $relatedContactImProvider);
     // store mapping Id to display it in the preview page
     $this->set('loadMappingId', CRM_Utils_Array::value('mappingId', $params));
     //Updating Mapping Records
     if (CRM_Utils_Array::value('updateMapping', $params)) {
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $mappingFields =& new CRM_Core_DAO_MappingField();
         $mappingFields->mapping_id = $params['mappingId'];
         $mappingFields->find();
         $mappingFieldsId = array();
         while ($mappingFields->fetch()) {
             if ($mappingFields->id) {
                 $mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
             }
         }
         for ($i = 0; $i < $this->_columnCount; $i++) {
             $updateMappingFields =& new CRM_Core_DAO_MappingField();
             $updateMappingFields->id = $mappingFieldsId[$i];
             $updateMappingFields->mapping_id = $params['mappingId'];
             $updateMappingFields->column_number = $i;
             list($id, $first, $second) = explode('_', $mapperKeys[$i][0]);
             if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
                 $updateMappingFields->relationship_type_id = $id;
                 $updateMappingFields->relationship_direction = "{$first}_{$second}";
                 $updateMappingFields->name = ucwords(str_replace("_", " ", $mapperKeys[$i][1]));
                 $updateMappingFields->location_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : null;
                 // get phoneType id and provider id separately
                 // before updating mappingFields of phone and IM for related contact, CRM-3140
                 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') {
                     $updateMappingFields->phone_type_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : null;
                 } else {
                     if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') {
                         $updateMappingFields->im_provider_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : null;
                     }
                 }
             } else {
                 $updateMappingFields->name = $mapper[$i];
                 $updateMappingFields->relationship_type_id = null;
                 $location = array_keys($locationTypes, $locations[$i]);
                 $updateMappingFields->location_type_id = isset($location) ? $location[0] : null;
                 // to store phoneType id and provider id seperately
                 // before updating mappingFields for phone and IM, CRM-3140
                 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'phone') {
                     $updateMappingFields->phone_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : null;
                 } else {
                     if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'im') {
                         $updateMappingFields->im_provider_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : null;
                     }
                 }
             }
             $updateMappingFields->save();
         }
     }
     //Saving Mapping Details and Records
     if (CRM_Utils_Array::value('saveMapping', $params)) {
         $mappingParams = array('name' => $params['saveMappingName'], 'description' => $params['saveMappingDesc'], 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type', 'Import Contact', 'name'));
         $saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $contactType = $this->get('contactType');
         switch ($contactType) {
             case CRM_Import_Parser::CONTACT_INDIVIDUAL:
                 $cType = 'Individual';
                 break;
             case CRM_Import_Parser::CONTACT_HOUSEHOLD:
                 $cType = 'Household';
                 break;
             case CRM_Import_Parser::CONTACT_ORGANIZATION:
                 $cType = 'Organization';
         }
         for ($i = 0; $i < $this->_columnCount; $i++) {
             $saveMappingFields =& new CRM_Core_DAO_MappingField();
             $saveMappingFields->mapping_id = $saveMapping->id;
             $saveMappingFields->contact_type = $cType;
             $saveMappingFields->column_number = $i;
             list($id, $first, $second) = explode('_', $mapperKeys[$i][0]);
             if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
                 $saveMappingFields->name = ucwords(str_replace("_", " ", $mapperKeys[$i][1]));
                 $saveMappingFields->relationship_type_id = $id;
                 $saveMappingFields->relationship_direction = "{$first}_{$second}";
                 // to get phoneType id and provider id seperately
                 // before saving mappingFields of phone and IM for related contact, CRM-3140
                 if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'phone') {
                     $saveMappingFields->phone_type_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : null;
                 } else {
                     if (CRM_Utils_Array::value('1', $mapperKeys[$i]) == 'im') {
                         $saveMappingFields->im_provider_id = isset($mapperKeys[$i][3]) ? $mapperKeys[$i][3] : null;
                     }
                 }
                 $saveMappingFields->location_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : null;
             } else {
                 $saveMappingFields->name = $mapper[$i];
                 $location_id = array_keys($locationTypes, $locations[$i]);
                 $saveMappingFields->location_type_id = isset($location_id[0]) ? $location_id[0] : null;
                 // to get phoneType id and provider id seperately
                 // before saving mappingFields of phone and IM, CRM-3140
                 if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'phone') {
                     $saveMappingFields->phone_type_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : null;
                 } else {
                     if (CRM_Utils_Array::value('0', $mapperKeys[$i]) == 'im') {
                         $saveMappingFields->im_provider_id = isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : null;
                     }
                 }
                 $saveMappingFields->relationship_type_id = null;
             }
             $saveMappingFields->save();
         }
         $this->set('savedMapping', $saveMappingFields->mapping_id);
     }
     $parser =& new CRM_Import_Parser_Contact($mapperKeysMain, $mapperLocType, $mapperPhoneType, $mapperImProvider, $related, $relatedContactType, $relatedContactDetails, $relatedContactLocType, $relatedContactPhoneType, $relatedContactImProvider);
     $primaryKeyName = $this->get('primaryKeyName');
     $statusFieldName = $this->get('statusFieldName');
     $parser->run($this->_importTableName, $mapper, CRM_Import_Parser::MODE_PREVIEW, $this->get('contactType'), $primaryKeyName, $statusFieldName, $this->_onDuplicate, null, null, false, CRM_Import_Parser::DEFAULT_TIMEOUT, $this->get('contactSubType'));
     // add all the necessary variables to the form
     $parser->set($this);
 }
示例#19
0
 /**
  * returns all the rows in the given offset and rowCount
  *
  * @param enum   $action   the action being performed
  * @param int    $offset   the row number to start from
  * @param int    $rowCount the number of rows to return
  * @param string $sort     the sql string that describes the sort order
  * @param enum   $output   what should the result set include (web/email/csv)
  *
  * @return int   the total number of rows for this action
  */
 function &getRows($action, $offset, $rowCount, $sort, $output = null)
 {
     $config =& CRM_Core_Config::singleton();
     if (($output == CRM_Core_Selector_Controller::EXPORT || $output == CRM_Core_Selector_Controller::SCREEN) && $this->_formValues['radio_ts'] == 'ts_sel') {
         $includeContactIds = true;
     } else {
         $includeContactIds = false;
     }
     // note the formvalues were given by CRM_Contact_Form_Search to us
     // and contain the search criteria (parameters)
     // note that the default action is basic
     $result = $this->_query->searchQuery($offset, $rowCount, $sort, false, $includeContactIds);
     // process the result of the query
     $rows = array();
     $permissions = array(CRM_Core_Permission::getPermission());
     if (CRM_Core_Permission::check('delete contacts')) {
         $permissions[] = CRM_Core_Permission::DELETE;
     }
     $mask = CRM_Core_Action::mask($permissions);
     $mapMask = $mask & 4095;
     // mask value to hide map link if there are not lat/long
     $gc = CRM_Core_SelectValues::groupContactStatus();
     if ($this->_ufGroupID) {
         require_once 'CRM/Core/PseudoConstant.php';
         $locationTypes = CRM_Core_PseudoConstant::locationType();
         $names = array();
         static $skipFields = array('group', 'tag');
         foreach ($this->_fields as $key => $field) {
             if (CRM_Utils_Array::value('in_selector', $field) && !in_array($key, $skipFields)) {
                 if (strpos($key, '-') !== false) {
                     list($fieldName, $id, $type) = explode('-', $key);
                     if ($id == 'Primary') {
                         $locationTypeName = 1;
                     } else {
                         $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
                         if (!$locationTypeName) {
                             continue;
                         }
                     }
                     $locationTypeName = str_replace(' ', '_', $locationTypeName);
                     if (in_array($fieldName, array('phone', 'im', 'email'))) {
                         if ($type) {
                             $names[] = "{$locationTypeName}-{$fieldName}-{$type}";
                         } else {
                             $names[] = "{$locationTypeName}-{$fieldName}";
                         }
                     } else {
                         $names[] = "{$locationTypeName}-{$fieldName}";
                     }
                 } else {
                     $names[] = $field['name'];
                 }
             }
         }
         $names[] = "status";
     } else {
         if (!empty($this->_returnProperties)) {
             $names =& self::makeProperties($this->_returnProperties);
         } else {
             $names = self::$_properties;
         }
     }
     //hack for student data (checkboxs)
     $multipleSelectFields = array('preferred_communication_method' => 1);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $multipleSelectFields = CRM_Quest_BAO_Student::$multipleSelectFields;
     }
     $searchType = null;
     if ($this->_action == CRM_Core_Action::BASIC) {
         $searchType = 'basic';
     } elseif ($this->_action == CRM_Core_Action::ADVANCED) {
         $searchType = 'advance';
     }
     require_once 'CRM/Core/OptionGroup.php';
     $links =& self::links($searchType, $this->_contextMenu);
     //check explicitly added contact to a Smart Group.
     $groupID = CRM_Utils_Array::key('1', $this->_formValues['group']);
     while ($result->fetch()) {
         $row = array();
         // the columns we are interested in
         foreach ($names as $property) {
             if ($property == 'status') {
                 continue;
             }
             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($property)) {
                 $row[$property] = CRM_Core_BAO_CustomField::getDisplayValue($result->{$property}, $cfID, $this->_options, $result->contact_id);
             } else {
                 if ($multipleSelectFields && array_key_exists($property, $multipleSelectFields)) {
                     //fix to display student checkboxes
                     $key = $property;
                     $paramsNew = array($key => $result->{$property});
                     if ($key == 'test_tutoring') {
                         $name = array($key => array('newName' => $key, 'groupName' => 'test'));
                     } else {
                         if (substr($key, 0, 4) == 'cmr_') {
                             //for  readers group
                             $name = array($key => array('newName' => $key, 'groupName' => substr($key, 0, -3)));
                         } else {
                             $name = array($key => array('newName' => $key, 'groupName' => $key));
                         }
                     }
                     CRM_Core_OptionGroup::lookupValues($paramsNew, $name, false);
                     $row[$key] = $paramsNew[$key];
                 } else {
                     if (isset($tmfFields) && $tmfFields && array_key_exists($property, $tmfFields) || substr($property, 0, 12) == 'participant_') {
                         if (substr($property, -3) == '_id') {
                             $key = substr($property, 0, -3);
                             $paramsNew = array($key => $result->{$property});
                             $name = array($key => array('newName' => $key, 'groupName' => $key));
                             CRM_Core_OptionGroup::lookupValues($paramsNew, $name, false);
                             $row[$key] = $paramsNew[$key];
                         } else {
                             $row[$property] = $result->{$property};
                         }
                     } else {
                         if (strpos($property, '-im')) {
                             $row[$property] = $result->{$property};
                             if (!empty($result->{$property})) {
                                 $imProviders = CRM_Core_PseudoConstant::IMProvider();
                                 $providerId = $property . "-provider_id";
                                 $providerName = $imProviders[$result->{$providerId}];
                                 $row[$property] = $result->{$property} . " ({$providerName})";
                             }
                         } else {
                             if (in_array($property, array('addressee', 'email_greeting', 'postal_greeting'))) {
                                 $greeting = $property . '_display';
                                 $row[$property] = $result->{$greeting};
                             } else {
                                 $row[$property] = $result->{$property};
                             }
                         }
                     }
                 }
             }
             if (!empty($result->{$property})) {
                 $empty = false;
             }
         }
         if (!empty($result->postal_code_suffix)) {
             $row['postal_code'] .= "-" . $result->postal_code_suffix;
         }
         if ($output != CRM_Core_Selector_Controller::EXPORT && $this->_searchContext == 'smog') {
             if (empty($result->status) && $groupID) {
                 $contactID = $result->contact_id;
                 if ($contactID) {
                     $gcParams = array('contact_id' => $contactID, 'group_id' => $groupID);
                     $gcDefaults = array();
                     CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_GroupContact', $gcParams, $gcDefaults);
                     if (empty($gcDefaults)) {
                         $row['status'] = ts('Smart');
                     } else {
                         $row['status'] = $gc[$gcDefaults['status']];
                     }
                 } else {
                     $row['status'] = null;
                 }
             } else {
                 $row['status'] = $gc[$result->status];
             }
         }
         if ($output != CRM_Core_Selector_Controller::EXPORT) {
             $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contact_id;
             if (is_numeric(CRM_Utils_Array::value('geo_code_1', $row)) || $config->mapGeoCoding && CRM_Utils_Array::value('city', $row) && $row['state_province']) {
                 $row['action'] = CRM_Core_Action::formLink($links, $mask, array('id' => $result->contact_id));
             } else {
                 $row['action'] = CRM_Core_Action::formLink($links, $mapMask, array('id' => $result->contact_id));
             }
             // allow components to add more actions
             CRM_Core_Component::searchAction($row, $result->contact_id);
             require_once 'CRM/Contact/BAO/Contact/Utils.php';
             $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type);
             $row['contact_id'] = $result->contact_id;
             $row['sort_name'] = $result->sort_name;
             if (array_key_exists('id', $row)) {
                 $row['id'] = $result->contact_id;
             }
         }
         // Dedupe contacts
         if (!$empty) {
             $duplicate = false;
             foreach ($rows as $checkRow) {
                 if ($checkRow['contact_id'] == $row['contact_id']) {
                     $duplicate = true;
                 }
             }
             if (!$duplicate) {
                 $rows[] = $row;
             }
         }
     }
     //CRM_Core_Error::debug( '$rows', $rows );
     return $rows;
 }
示例#20
0
 /**  
  * Function to build the array for display the profile fields
  *  
  * @param array $params key value. 
  * @param int $gid profile Id
  * @param array $groupTitle Profile Group Title.
  * @param array $values formatted array of key value
  *
  * @return None  
  * @access public  
  */
 function displayProfile(&$params, $gid, &$groupTitle, &$values)
 {
     if ($gid) {
         require_once 'CRM/Core/BAO/UFGroup.php';
         require_once 'CRM/Profile/Form.php';
         require_once 'CRM/Event/PseudoConstant.php';
         $session = CRM_Core_Session::singleton();
         $contactID = $session->get('userID');
         if ($contactID) {
             if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) {
                 $fields = CRM_Core_BAO_UFGroup::getFields($gid, false, CRM_Core_Action::VIEW);
             }
         } else {
             $fields = CRM_Core_BAO_UFGroup::getFields($gid, false, CRM_Core_Action::ADD);
         }
         if (is_array($fields)) {
             // unset any email-* fields since we already collect it, CRM-2888
             foreach (array_keys($fields) as $fieldName) {
                 if (substr($fieldName, 0, 6) == 'email-') {
                     unset($fields[$fieldName]);
                 }
             }
         }
         foreach ($fields as $v) {
             if (CRM_Utils_Array::value('groupTitle', $v)) {
                 $groupTitle['groupTitle'] = $v["groupTitle"];
                 break;
             }
         }
         $config = CRM_Core_Config::singleton();
         require_once 'CRM/Core/PseudoConstant.php';
         $locationTypes = $imProviders = array();
         $locationTypes = CRM_Core_PseudoConstant::locationType();
         $imProviders = CRM_Core_PseudoConstant::IMProvider();
         //start of code to set the default values
         foreach ($fields as $name => $field) {
             $index = $field['title'];
             $customFieldName = null;
             if ($name === 'organization_name') {
                 $values[$index] = $params[$name];
             }
             if ('state_province' == substr($name, 0, 14)) {
                 if ($params[$name]) {
                     $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]);
                 } else {
                     $values[$index] = '';
                 }
             } else {
                 if ('country' == substr($name, 0, 7)) {
                     if ($params[$name]) {
                         $values[$index] = CRM_Core_PseudoConstant::country($params[$name]);
                     } else {
                         $values[$index] = '';
                     }
                 } else {
                     if ('county' == substr($name, 0, 6)) {
                         if ($params[$name]) {
                             $values[$index] = CRM_Core_PseudoConstant::county($params[$name]);
                         } else {
                             $values[$index] = '';
                         }
                     } else {
                         if ('gender' == substr($name, 0, 6)) {
                             $gender = CRM_Core_PseudoConstant::gender();
                             $values[$index] = $gender[$params[$name]];
                         } else {
                             if ('individual_prefix' == substr($name, 0, 17)) {
                                 $prefix = CRM_Core_PseudoConstant::individualPrefix();
                                 $values[$index] = $prefix[$params[$name]];
                             } else {
                                 if ('individual_suffix' == substr($name, 0, 17)) {
                                     $suffix = CRM_Core_PseudoConstant::individualSuffix();
                                     $values[$index] = $suffix[$params[$name]];
                                 } else {
                                     if (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) {
                                         $filterCondition = array('greeting_type' => $name);
                                         $greeting =& CRM_Core_PseudoConstant::greeting($filterCondition);
                                         $values[$index] = $greeting[$params[$name]];
                                     } else {
                                         if ($name === 'preferred_communication_method') {
                                             $communicationFields = CRM_Core_PseudoConstant::pcm();
                                             $pref = array();
                                             $compref = array();
                                             $pref = $params[$name];
                                             if (is_array($pref)) {
                                                 foreach ($pref as $k => $v) {
                                                     if ($v) {
                                                         $compref[] = $communicationFields[$k];
                                                     }
                                                 }
                                             }
                                             $values[$index] = implode(",", $compref);
                                         } else {
                                             if ($name == 'group') {
                                                 require_once 'CRM/Contact/BAO/GroupContact.php';
                                                 $groups = CRM_Contact_BAO_GroupContact::getGroupList();
                                                 $title = array();
                                                 foreach ($params[$name] as $gId => $dontCare) {
                                                     if ($dontCare) {
                                                         $title[] = $groups[$gId];
                                                     }
                                                 }
                                                 $values[$index] = implode(', ', $title);
                                             } else {
                                                 if ($name == 'tag') {
                                                     require_once 'CRM/Core/BAO/EntityTag.php';
                                                     $entityTags = $params[$name];
                                                     $allTags =& CRM_Core_PseudoConstant::tag();
                                                     $title = array();
                                                     if (is_array($entityTags)) {
                                                         foreach ($entityTags as $tagId => $dontCare) {
                                                             $title[] = $allTags[$tagId];
                                                         }
                                                     }
                                                     $values[$index] = implode(', ', $title);
                                                 } else {
                                                     if ('participant_role_id' == $name) {
                                                         $roles = CRM_Event_PseudoConstant::participantRole();
                                                         $values[$index] = $roles[$params[$name]];
                                                     } else {
                                                         if ('participant_status_id' == $name) {
                                                             $status = CRM_Event_PseudoConstant::participantStatus();
                                                             $values[$index] = $status[$params[$name]];
                                                         } else {
                                                             if (strpos($name, '-') !== false) {
                                                                 list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2);
                                                                 $detailName = str_replace(' ', '_', $name);
                                                                 if (in_array($fieldName, array('state_province', 'country', 'county'))) {
                                                                     $values[$index] = $params[$detailName];
                                                                     $idx = $detailName . '_id';
                                                                     $values[$index] = $params[$idx];
                                                                 } else {
                                                                     if ($fieldName == 'im') {
                                                                         $providerName = null;
                                                                         if ($providerId = $detailName . '-provider_id') {
                                                                             $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders);
                                                                         }
                                                                         if ($providerName) {
                                                                             $values[$index] = $params[$detailName] . " (" . $providerName . ")";
                                                                         } else {
                                                                             $values[$index] = $params[$detailName];
                                                                         }
                                                                     } else {
                                                                         $values[$index] = $params[$detailName];
                                                                     }
                                                                 }
                                                             } else {
                                                                 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
                                                                     if ($params[$name]) {
                                                                         $values[$index] = '[ x ]';
                                                                     }
                                                                 } else {
                                                                     require_once 'CRM/Core/BAO/CustomField.php';
                                                                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                                                                         $query = "\nSELECT html_type, data_type\nFROM   civicrm_custom_field\nWHERE  id = {$cfID}\n";
                                                                         $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
                                                                         $dao->fetch();
                                                                         $htmlType = $dao->html_type;
                                                                         $dataType = $dao->data_type;
                                                                         if ($htmlType == 'File') {
                                                                             //$fileURL = CRM_Core_BAO_CustomField::getFileURL( $contactID, $cfID );
                                                                             //$params[$index] = $values[$index] = $fileURL['file_url'];
                                                                             $values[$index] = $params[$index];
                                                                         } else {
                                                                             if ($dao->data_type == 'Int' || $dao->data_type == 'Boolean') {
                                                                                 $customVal = (int) $params[$name];
                                                                             } else {
                                                                                 if ($dao->data_type == 'Float') {
                                                                                     $customVal = (double) $params[$name];
                                                                                 } else {
                                                                                     if ($dao->data_type == 'Date') {
                                                                                         $date = CRM_Utils_Date::format($params[$name], null, 'invalidDate');
                                                                                         if ($date != 'invalidDate') {
                                                                                             $customVal = $date;
                                                                                         }
                                                                                     } else {
                                                                                         $customVal = $params[$name];
                                                                                     }
                                                                                 }
                                                                             }
                                                                             //take the custom field options
                                                                             $returnProperties = array($name => 1);
                                                                             require_once 'CRM/Contact/BAO/Query.php';
                                                                             $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
                                                                             $options =& $query->_options;
                                                                             $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
                                                                             //Hack since we dont have function to check empty.
                                                                             //FIXME in 2.3 using crmIsEmptyArray()
                                                                             $customValue = true;
                                                                             if (is_array($customVal) && is_array($displayValue)) {
                                                                                 $customValue = array_diff($customVal, $displayValue);
                                                                             }
                                                                             //use difference of arrays
                                                                             if (empty($customValue) || !$customValue) {
                                                                                 $values[$index] = '';
                                                                             } else {
                                                                                 $values[$index] = $displayValue;
                                                                             }
                                                                             if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) {
                                                                                 $customFieldName = "{$name}_from";
                                                                             }
                                                                         }
                                                                     } else {
                                                                         if ($name == 'home_URL' && !empty($params[$name])) {
                                                                             $url = CRM_Utils_System::fixURL($params[$name]);
                                                                             $values[$index] = "<a href=\"{$url}\">{$params[$name]}</a>";
                                                                         } else {
                                                                             if (in_array($name, array('birth_date', 'deceased_date', 'participant_register_date'))) {
                                                                                 require_once 'CRM/Utils/Date.php';
                                                                                 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name]));
                                                                             } else {
                                                                                 $values[$index] = $params[$name];
                                                                             }
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
示例#21
0
 /**
  *
  * Get the values for pseudoconstants for name->value and reverse.
  *
  * @param array   $defaults (reference) the default values, some of which need to be resolved.
  * @param boolean $reverse  true if we want to resolve the values in the reverse direction (value -> name)
  *
  * @return none
  * @access public
  * @static
  */
 function resolveDefaults(&$defaults, $reverse = false)
 {
     // hack for birth_date
     if (CRM_Utils_Array::value('birth_date', $defaults)) {
         if (is_array($defaults['birth_date'])) {
             $defaults['birth_date'] = CRM_Utils_Date::format($defaults['birth_date'], '-');
         }
     }
     if (CRM_Utils_Array::value('prefix', $defaults)) {
         CRM_Contact_BAO_Contact::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant::individualPrefix(), $reverse);
     }
     if (CRM_Utils_Array::value('suffix', $defaults)) {
         CRM_Contact_BAO_Contact::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant::individualSuffix(), $reverse);
     }
     if (CRM_Utils_Array::value('gender', $defaults)) {
         CRM_Contact_BAO_Contact::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant::gender(), $reverse);
     }
     if (array_key_exists('location', $defaults)) {
         $locations =& $defaults['location'];
         foreach ($locations as $index => $location) {
             $location =& $locations[$index];
             CRM_Contact_BAO_Contact::lookupValue($location, 'location_type', CRM_Core_PseudoConstant::locationType(), $reverse);
             // FIXME: lookupValue doesn't work for vcard_name
             $vcardNames =& CRM_Core_PseudoConstant::locationVcardName();
             $location['vcard_name'] = $vcardNames[$location['location_type_id']];
             if (array_key_exists('address', $location)) {
                 if (!CRM_Contact_BAO_Contact::lookupValue($location['address'], 'state_province', CRM_Core_PseudoConstant::stateProvince(), $reverse) && $reverse) {
                     CRM_Contact_BAO_Contact::lookupValue($location['address'], 'state_province', CRM_Core_PseudoConstant::stateProvinceAbbreviation(), $reverse);
                 }
                 if (!CRM_Contact_BAO_Contact::lookupValue($location['address'], 'country', CRM_Core_PseudoConstant::country(), $reverse) && $reverse) {
                     CRM_Contact_BAO_Contact::lookupValue($location['address'], 'country', CRM_Core_PseudoConstant::countryIsoCode(), $reverse);
                 }
                 CRM_Contact_BAO_Contact::lookupValue($location['address'], 'county', CRM_Core_SelectValues::county(), $reverse);
             }
             if (array_key_exists('im', $location)) {
                 $ims =& $location['im'];
                 foreach ($ims as $innerIndex => $im) {
                     $im =& $ims[$innerIndex];
                     CRM_Contact_BAO_Contact::lookupValue($im, 'provider', CRM_Core_PseudoConstant::IMProvider(), $reverse);
                     unset($im);
                 }
             }
             unset($location);
         }
     }
 }