/**
  * Run the page.
  *
  * This method is called after the page is created.
  *
  * @return void
  * @access public
  *
  */
 function run()
 {
     // get the emails for this contact
     $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, TRUE, NULL, $_REQUEST);
     $locationTypes = CRM_Core_PseudoConstant::locationDisplayName();
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $entityBlock = array('contact_id' => $contactId);
     $phones = CRM_Core_BAO_Phone::getValues($entityBlock);
     if (!empty($phones)) {
         foreach ($phones as $key => &$value) {
             $value['location_type'] = $locationTypes[$value['location_type_id']];
             $value['phone_type'] = $phoneTypes[$value['phone_type_id']];
         }
     }
     $contact = new CRM_Contact_BAO_Contact();
     $contact->id = $contactId;
     $contact->find(true);
     $privacy = array();
     foreach (CRM_Contact_BAO_Contact::$_commPrefs as $name) {
         if (isset($contact->{$name})) {
             $privacy[$name] = $contact->{$name};
         }
     }
     $this->assign('contactId', $contactId);
     $this->assign('phone', $phones);
     $this->assign('privacy', $privacy);
     // check logged in user permission
     CRM_Contact_Page_View::checkUserPermission($this, $contactId);
     // finally call parent
     parent::run();
 }
 /**
  * build the form elements for a phone object
  *
  * @param CRM_Core_Form $form       reference to the form object
  * @param int           $addressBlockCount block number to build
  * @param boolean       $blockEdit         is it block edit
  *
  * @return void
  * @access public
  * @static
  */
 static function buildQuickForm(&$form, $addressBlockCount = NULL, $blockEdit = FALSE)
 {
     // passing this via the session is AWFUL. we need to fix this
     if (!$addressBlockCount) {
         $blockId = $form->get('Phone_Block_Count') ? $form->get('Phone_Block_Count') : 1;
     } else {
         $blockId = $addressBlockCount;
     }
     $form->applyFilter('__ALL__', 'trim');
     //phone type select
     $form->addElement('select', "phone[{$blockId}][phone_type_id]", ts('Phone'), CRM_Core_PseudoConstant::phoneType());
     //main phone number with crm_phone class
     $form->addElement('text', "phone[{$blockId}][phone]", ts('Phone'), array_merge(CRM_Core_DAO::getAttribute('CRM_Core_DAO_Phone', 'phone'), array('class' => 'crm_phone twelve')));
     // phone extension
     $form->addElement('text', "phone[{$blockId}][phone_ext]", ts('Extension'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Phone', 'phone_ext'));
     if (isset($form->_contactType) || $blockEdit) {
         //Block type select
         $form->addElement('select', "phone[{$blockId}][location_type_id]", '', CRM_Core_PseudoConstant::locationType());
         //is_Primary radio
         $js = array('id' => 'Phone_' . $blockId . '_IsPrimary', 'onClick' => 'singleSelect( this.id );');
         $form->addElement('radio', "phone[{$blockId}][is_primary]", '', '', '1', $js);
     }
     // TODO: set this up as a group, we need a valid phone_type_id if we have a  phone number
     // $form->addRule( "location[$locationId][phone][$locationId][phone]", ts('Phone number is not valid.'), 'phone' );
 }
Example #3
0
 /**
  * build the form elements for a phone 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('Phone_Block_Count') ? $form->get('Phone_Block_Count') : 1;
     $form->applyFilter('__ALL__', 'trim');
     //phone type select
     $form->addElement('select', "phone[{$blockId}][phone_type_id]", ts('Phone'), CRM_Core_PseudoConstant::phoneType());
     //phone box
     $form->addElement('text', "phone[{$blockId}][phone]", ts('Phone'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Phone', 'phone'));
     if (isset($form->_contactType)) {
         //Block type select
         $form->addElement('select', "phone[{$blockId}][location_type_id]", '', CRM_Core_PseudoConstant::locationType());
         //is_Primary radio
         $js = array('id' => "Phone_" . $blockId . "_IsPrimary", 'onClick' => 'singleSelect( this.id );');
         $form->addElement('radio', "phone[{$blockId}][is_primary]", '', '', '1', $js);
     }
     // TODO: set this up as a group, we need a valid phone_type_id if we have a  phone number
     // $form->addRule( "location[$locationId][phone][$locationId][phone]", ts('Phone number is not valid.'), 'phone' );
 }
 /**
  * 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);
 }
 /**
  * Get all phone type
  * The static array phoneType is returned
  * 
  * @access public
  * @static
  *
  * @param boolean $all - get All phone type - default is to get
  * only active ones.
  *
  * @return array - array reference of all phone types.
  *
  */
 public static function &phoneType()
 {
     if (!self::$phoneType) {
         require_once 'CRM/Core/OptionGroup.php';
         self::$phoneType = CRM_Core_OptionGroup::values('phone_type');
     }
     return self::$phoneType;
 }
Example #6
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);
         }
     }
 }
 /**
  *
  * 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);
         }
     }
 }
Example #9
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);
 }
Example #10
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 postProcessOld()
 {
     $doGeocodeAddress = $this->controller->exportValue('DataSource', 'doGeocodeAddress');
     $invalidRowCount = $this->get('invalidRowCount');
     $conflictRowCount = $this->get('conflictRowCount');
     $onDuplicate = $this->get('onDuplicate');
     $newGroupName = $this->controller->exportValue($this->_name, 'newGroupName');
     $newGroupDesc = $this->controller->exportValue($this->_name, 'newGroupDesc');
     $groups = $this->controller->exportValue($this->_name, 'groups');
     $allGroups = $this->get('groups');
     $newTagName = $this->controller->exportValue($this->_name, 'newTagName');
     $newTagDesc = $this->controller->exportValue($this->_name, 'newTagDesc');
     $tag = $this->controller->exportValue($this->_name, 'tag');
     $allTags = $this->get('tag');
     $mapper = $this->controller->exportValue('MapField', 'mapper');
     $mapperKeys = array();
     $mapperLocTypes = array();
     $mapperPhoneTypes = array();
     $mapperRelated = array();
     $mapperRelatedContactType = array();
     $mapperRelatedContactDetails = array();
     $mapperRelatedContactLocType = array();
     $mapperRelatedContactPhoneType = array();
     foreach ($mapper as $key => $value) {
         $mapperKeys[$key] = $mapper[$key][0];
         if (is_numeric($mapper[$key][1])) {
             $mapperLocTypes[$key] = $mapper[$key][1];
         } else {
             $mapperLocTypes[$key] = null;
         }
         if (CRM_Utils_Array::value($key, $mapperKeys) == 'phone') {
             $mapperPhoneTypes[$key] = $mapper[$key][2];
         } else {
             $mapperPhoneTypes[$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('$mapperRelatedContactType[$key] = $relationType->contact_type_' . $second . ';');
             $mapperRelated[$key] = $mapper[$key][0];
             $mapperRelatedContactDetails[$key] = $mapper[$key][1];
             $mapperRelatedContactLocType[$key] = $mapper[$key][2];
             $mapperRelatedContactPhoneType[$key] = $mapper[$key][3];
         } else {
             $mapperRelated[$key] = null;
             $mapperRelatedContactType[$key] = null;
             $mapperRelatedContactDetails[$key] = null;
             $mapperRelatedContactLocType[$key] = null;
             $mapperRelatedContactPhoneType[$key] = null;
         }
     }
     $parser =& new CRM_Import_Parser_Contact($mapperKeys, $mapperLocTypes, $mapperPhoneTypes, $mapperRelated, $mapperRelatedContactType, $mapperRelatedContactDetails, $mapperRelatedContactLocType, $mapperRelatedContactPhoneType);
     $mapFields = $this->get('fields');
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     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])) {
                 $header[] = $phoneTypes[$mapper[$key][3]];
             }
         } else {
             if (isset($mapFields[$mapper[$key][0]])) {
                 $header[] = $mapFields[$mapper[$key][0]];
                 if (isset($mapper[$key][1])) {
                     $header[] = $locationTypes[$mapper[$key][1]];
                 }
                 if (isset($mapper[$key][2])) {
                     $header[] = $phoneTypes[$mapper[$key][2]];
                 }
             }
         }
         $mapperFields[] = implode(' - ', $header);
     }
     $tableName = $this->get('importTableName');
     //print "Running parser on table: $tableName<br/>";
     $parser->run($tableName, $mapperFields, CRM_Import_Parser::MODE_IMPORT, $this->get('contactType'), $this->get('primaryKeyName'), $this->get('statusFieldName'), $onDuplicate, $this->get('statusID'), $this->get('totalRowCount'), $doGeocodeAddress, CRM_Import_Parser::DEFAULT_TIMEOUT, $this->get('contactSubType'));
     // add the new contacts to selected groups
     $contactIds =& $parser->getImportedContacts();
     // add the new related contacts to selected groups
     $relatedContactIds =& $parser->getRelatedImportedContacts();
     $this->set('relatedCount', count($relatedContactIds));
     $newGroupId = null;
     //changed below if-statement "if ($newGroup) {" to "if ($newGroupName) {"
     if ($newGroupName) {
         /* Create a new group */
         $gParams = array('name' => $newGroupName, 'title' => $newGroupName, 'description' => $newGroupDesc, 'is_active' => true);
         $group =& CRM_Contact_BAO_Group::create($gParams);
         $groups[] = $newGroupId = $group->id;
     }
     if (is_array($groups)) {
         $groupAdditions = array();
         foreach ($groups as $groupId) {
             $addCount =& CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
             if (!empty($relatedContactIds)) {
                 $addRelCount =& CRM_Contact_BAO_GroupContact::addContactsToGroup($relatedContactIds, $groupId);
             }
             $totalCount = $addCount[1] + $addRelCount[1];
             if ($groupId == $newGroupId) {
                 $name = $newGroupName;
                 $new = true;
             } else {
                 $name = $allGroups[$groupId];
                 $new = false;
             }
             $groupAdditions[] = array('url' => CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $groupId), 'name' => $name, 'added' => $totalCount, 'notAdded' => $addCount[2] + $addRelCount[2], 'new' => $new);
         }
         $this->set('groupAdditions', $groupAdditions);
     }
     $newTagId = null;
     if ($newTagName) {
         /* Create a new Tag */
         $tagParams = array('name' => $newTagName, 'title' => $newTagName, 'description' => $newTagDesc, 'is_active' => true);
         require_once 'CRM/Core/BAO/Tag.php';
         $id = array();
         $addedTag =& CRM_Core_BAO_Tag::add($tagParams, $id);
         $tag[$addedTag->id] = 1;
     }
     //add Tag to Import
     if (is_array($tag)) {
         $tagAdditions = array();
         require_once "CRM/Core/BAO/EntityTag.php";
         foreach ($tag as $tagId => $val) {
             $addTagCount =& CRM_Core_BAO_EntityTag::addContactsToTag($contactIds, $tagId);
             if (!empty($relatedContactIds)) {
                 $addRelTagCount =& CRM_Core_BAO_EntityTag::addContactsToTag($relatedContactIds, $tagId);
             }
             $totalTagCount = $addTagCount[1] + $addRelTagCount[1];
             if ($tagId == $addedTag->id) {
                 $tagName = $newTagName;
                 $new = true;
             } else {
                 $tagName = $allTags[$tagId];
                 $new = false;
             }
             $tagAdditions[] = array('url' => CRM_Utils_System::url('civicrm/contact/search', 'reset=1&force=1&context=smog&id=' . $tagId), 'name' => $tagName, 'added' => $totalTagCount, 'notAdded' => $addTagCount[2] + $addRelTagCount[2], 'new' => $new);
         }
         $this->set('tagAdditions', $tagAdditions);
     }
     // add all the necessary variables to the form
     $parser->set($this, CRM_Import_Parser::MODE_IMPORT);
     // check if there is any error occured
     $errorStack =& CRM_Core_Error::singleton();
     $errors = $errorStack->getErrors();
     $errorMessage = array();
     if (is_array($errors)) {
         foreach ($errors as $key => $value) {
             $errorMessage[] = $value['message'];
         }
         // there is no fileName since this is a sql import
         // so fudge it
         $config =& CRM_Core_Config::singleton();
         $errorFile = $config->uploadDir . "sqlImport.error.log";
         if ($fd = fopen($errorFile, 'w')) {
             fwrite($fd, implode('\\n', $errorMessage));
         }
         fclose($fd);
         $this->set('errorFile', $errorFile);
         $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', 'type=1'));
         $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', 'type=2'));
         $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', 'type=4'));
     }
 }
Example #11
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);
         }
     }
 }
Example #12
0
 /**
  * Function to get the list the export fields
  *
  * @param int    $selectAll user preference while export
  * @param array  $ids  contact ids
  * @param array  $params associated array of fields
  * @param string $order order by clause
  * @param array  $associated array of fields
  * @param array  $moreReturnProperties additional return fields
  * @param int    $exportMode export mode
  * @param string $componentClause component clause
  *
  * @static
  * @access public
  */
 static function exportComponents($selectAll, $ids, $params, $order = null, $fields = null, $moreReturnProperties = null, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = null)
 {
     $headerRows = array();
     $primary = false;
     $returnProperties = array();
     $origFields = $fields;
     $queryMode = null;
     $paymentFields = false;
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true, 'label', false);
     $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
             break;
         case CRM_Export_Form_Select::PLEDGE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
             break;
         case CRM_Export_Form_Select::CASE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CASE;
             break;
     }
     require_once 'CRM/Core/BAO/CustomField.php';
     if ($fields) {
         //construct return properties
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im');
         foreach ($fields as $key => $value) {
             $phoneTypeId = null;
             $imProviderId = null;
             $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
             if (!$fieldName) {
                 continue;
             }
             // get phoneType id and IM service provider id seperately
             if ($fieldName == 'phone') {
                 $phoneTypeId = CRM_Utils_Array::value(3, $value);
             } else {
                 if ($fieldName == 'im') {
                     $imProviderId = CRM_Utils_Array::value(3, $value);
                 }
             }
             if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
                 if (CRM_Utils_Array::value(2, $value)) {
                     $relationField = CRM_Utils_Array::value(2, $value);
                     if (trim(CRM_Utils_Array::value(3, $value))) {
                         $relLocTypeId = CRM_Utils_Array::value(3, $value);
                     } else {
                         $relLocTypeId = 1;
                     }
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
                     } else {
                         if ($relationField == 'im') {
                             $relIMProviderId = CRM_Utils_Array::value(4, $value);
                         }
                     }
                 } else {
                     if (CRM_Utils_Array::value(4, $value)) {
                         $relationField = CRM_Utils_Array::value(4, $value);
                         $relLocTypeId = CRM_Utils_Array::value(5, $value);
                         if ($relationField == 'phone') {
                             $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
                         } else {
                             if ($relationField == 'im') {
                                 $relIMProviderId = CRM_Utils_Array::value(6, $value);
                             }
                         }
                     }
                 }
             }
             $contactType = CRM_Utils_Array::value(0, $value);
             $locTypeId = CRM_Utils_Array::value(2, $value);
             $phoneTypeId = CRM_Utils_Array::value(3, $value);
             if ($relationField) {
                 if (in_array($relationField, $locationTypeFields)) {
                     if ($relPhoneTypeId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
                     } else {
                         if ($relIMProviderId) {
                             $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
                         } else {
                             $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
                         }
                     }
                     $relPhoneTypeId = $relIMProviderId = null;
                 } else {
                     $returnProperties[$relationshipTypes][$relationField] = 1;
                 }
             } else {
                 if (is_numeric($locTypeId)) {
                     if ($phoneTypeId) {
                         $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
                     } else {
                         if (isset($imProviderId)) {
                             //build returnProperties for IM service provider
                             $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
                         } else {
                             $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
                         }
                     }
                 } else {
                     //hack to fix component fields
                     if ($fieldName == 'event_id') {
                         $returnProperties['event_title'] = 1;
                     } else {
                         $returnProperties[$fieldName] = 1;
                     }
                 }
             }
         }
         // hack to add default returnproperty based on export mode
         if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
             $returnProperties['contribution_id'] = 1;
         } else {
             if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
                 $returnProperties['participant_id'] = 1;
             } else {
                 if ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
                     $returnProperties['membership_id'] = 1;
                 } else {
                     if ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
                         $returnProperties['pledge_id'] = 1;
                     } else {
                         if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
                             $returnProperties['case_id'] = 1;
                         }
                     }
                 }
             }
         }
     } else {
         $primary = true;
         $fields = CRM_Contact_BAO_Contact::exportableFields('All', true, true);
         foreach ($fields as $key => $var) {
             if ($key && substr($key, 0, 6) != 'custom') {
                 //for CRM=952
                 $returnProperties[$key] = 1;
             }
         }
         if ($primary) {
             $returnProperties['location_type'] = 1;
             $returnProperties['im_provider'] = 1;
             $returnProperties['phone_type_id'] = 1;
             $returnProperties['provider_id'] = 1;
             $returnProperties['current_employer'] = 1;
         }
         $extraReturnProperties = array();
         $paymentFields = false;
         switch ($queryMode) {
             case CRM_Contact_BAO_Query::MODE_EVENT:
                 $paymentFields = true;
                 $paymentTableId = "participant_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_MEMBER:
                 $paymentFields = true;
                 $paymentTableId = "membership_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_PLEDGE:
                 require_once 'CRM/Pledge/BAO/Query.php';
                 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
                 $paymentFields = true;
                 $paymentTableId = "pledge_payment_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_CASE:
                 require_once 'CRM/Case/BAO/Query.php';
                 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
                 break;
         }
         if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
             $componentReturnProperties =& CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
             $returnProperties = array_merge($returnProperties, $componentReturnProperties);
             if (!empty($extraReturnProperties)) {
                 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
             }
             // unset groups, tags, notes for components
             foreach (array('groups', 'tags', 'notes') as $value) {
                 unset($returnProperties[$value]);
             }
         }
     }
     if ($moreReturnProperties) {
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $query =& new CRM_Contact_BAO_Query(0, $returnProperties, null, false, false, $queryMode);
     list($select, $from, $where) = $query->query();
     // make sure the groups stuff is included only if specifically specified
     // by the fields param (CRM-1969), else we limit the contacts outputted to only
     // ones that are part of a group
     if (CRM_Utils_Array::value('groups', $returnProperties)) {
         $oldClause = "contact_a.id = civicrm_group_contact.contact_id";
         $newClause = " ( {$oldClause} AND civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) ";
         // total hack for export, CRM-3618
         $from = str_replace($oldClause, $newClause, $from);
     }
     if ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     $queryString = "{$select} {$from} {$where}";
     if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties) || CRM_Utils_Array::value('notes', $returnProperties) || $query->_useGroupBy) {
         $queryString .= " GROUP BY contact_a.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (CRM_Utils_Array::value($field, $returnProperties)) {
             $queryString .= " ORDER BY {$order}";
         }
     }
     //hack for student data
     require_once 'CRM/Core/OptionGroup.php';
     $multipleSelectFields = array('preferred_communication_method' => 1);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $studentFields = array();
         $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields;
         $multipleSelectFields = array_merge($multipleSelectFields, $studentFields);
     }
     $dao =& CRM_Core_DAO::executeQuery($queryString, CRM_Core_DAO::$_nullArray);
     $header = false;
     $addPaymentHeader = false;
     if ($paymentFields) {
         $addPaymentHeader = true;
         //special return properties for event and members
         $paymentHeaders = array(ts('Total Amount'), ts('Contribution Status'), ts('Received Date'), ts('Payment Instrument'), ts('Transaction ID'));
         // get payment related in for event and members
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
     }
     $componentDetails = $headerRows = array();
     $setHeader = true;
     while ($dao->fetch()) {
         $row = array();
         //first loop through returnproperties so that we return what is required, and in same order.
         $relationshipField = 0;
         foreach ($returnProperties as $field => $value) {
             //we should set header only once
             if ($setHeader) {
                 if (isset($query->_fields[$field]['title'])) {
                     $headerRows[] = $query->_fields[$field]['title'];
                 } else {
                     if ($field == 'phone_type_id') {
                         $headerRows[] = 'Phone Type';
                     } else {
                         if ($field == 'provider_id') {
                             $headerRows[] = 'Im Service Provider';
                         } else {
                             if (is_array($value) && $field == 'location') {
                                 // fix header for location type case
                                 foreach ($value as $ltype => $val) {
                                     foreach (array_keys($val) as $fld) {
                                         $type = explode('-', $fld);
                                         $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
                                         if (CRM_Utils_Array::value(1, $type)) {
                                             if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                             } else {
                                                 if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                     $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                 }
                                             }
                                         }
                                         $headerRows[] = $hdr;
                                     }
                                 }
                             } else {
                                 if (substr($field, 0, 5) == 'case_') {
                                     if ($query->_fields['case'][$field]['title']) {
                                         $headerRows[] = $query->_fields['case'][$field]['title'];
                                     } else {
                                         if ($query->_fields['activity'][$field]['title']) {
                                             $headerRows[] = $query->_fields['activity'][$field]['title'];
                                         }
                                     }
                                 } else {
                                     if (array_key_exists($field, $contactRelationshipTypes)) {
                                         foreach ($value as $relationField => $relationValue) {
                                             if (is_array($relationValue)) {
                                                 foreach ($relationValue as $locType => $locValue) {
                                                     if ($relationField == 'location') {
                                                         foreach ($locValue as $locKey => $dont) {
                                                             list($serviceProvider, $serviceProviderID) = explode('-', $locKey);
                                                             if ($serviceProvider == 'phone') {
                                                                 $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $locType . ' - ' . $serviceProvider . ' - ' . CRM_Utils_Array::value($serviceProviderID, $phoneTypes, 'Primary');
                                                             } else {
                                                                 if ($serviceProvider == 'im') {
                                                                     $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $locType . ' - ' . $serviceProvider . ' - ' . CRM_Utils_Array::value($serviceProviderID, $imProviders, 'Primary');
                                                                 } else {
                                                                     $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $locType . ' - ' . $query->_fields[$locKey]['title'];
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             } else {
                                                 if ($query->_fields[$relationField]['title']) {
                                                     $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $query->_fields[$relationField]['title'];
                                                 } else {
                                                     $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $relationField;
                                                 }
                                             }
                                         }
                                     } else {
                                         $headerRows[] = $field;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             //build row values (data)
             if (property_exists($dao, $field)) {
                 $fieldValue = $dao->{$field};
                 // to get phone type from phone type id
                 if ($field == 'phone_type_id') {
                     $fieldValue = $phoneTypes[$fieldValue];
                 } else {
                     if ($field == 'provider_id') {
                         $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
                     }
                 }
             } else {
                 $fieldValue = '';
             }
             if ($field == 'id') {
                 $row[$field] = $dao->contact_id;
             } else {
                 if ($field == 'pledge_balance_amount') {
                     //special case for calculated field
                     $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid;
                 } else {
                     if ($field == 'pledge_next_pay_amount') {
                         //special case for calculated field
                         $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount;
                     } else {
                         if (is_array($value) && $field == 'location') {
                             // fix header for location type case
                             foreach ($value as $ltype => $val) {
                                 foreach (array_keys($val) as $fld) {
                                     $type = explode('-', $fld);
                                     $fldValue = "{$ltype}-" . $type[0];
                                     if (CRM_Utils_Array::value(1, $type)) {
                                         $fldValue .= "-" . $type[1];
                                     }
                                     $row[$fldValue] = $dao->{$fldValue};
                                 }
                             }
                         } else {
                             if (array_key_exists($field, $contactRelationshipTypes)) {
                                 list($id, $direction) = explode('_', $field, 2);
                                 require_once 'api/v2/Relationship.php';
                                 require_once 'CRM/Contact/BAO/Contact.php';
                                 require_once 'CRM/Core/BAO/CustomValueTable.php';
                                 require_once 'CRM/Core/BAO/CustomQuery.php';
                                 $params['relationship_type_id'] = $contactRelationshipTypes[$field];
                                 $contact_id['contact_id'] = $dao->contact_id;
                                 //Get relationships
                                 $val = civicrm_contact_relationship_get($contact_id, null, $params);
                                 if (is_array($val['result'])) {
                                     asort($val['result']);
                                 }
                                 $is_valid = null;
                                 $data = null;
                                 if ($val['result']) {
                                     foreach ($val['result'] as $k => $v) {
                                         //consider only active relationships
                                         if ($v['is_active'] && $v['rtype'] == $direction) {
                                             $cID['contact_id'] = $v['cid'];
                                             if ($cID) {
                                                 //Get Contact Details
                                                 $data = CRM_Contact_BAO_Contact::retrieve($cID, $defaults);
                                             }
                                             $is_valid = true;
                                             break;
                                         }
                                     }
                                 }
                                 $relCustomIDs = array();
                                 foreach ($value as $relationkey => $relationvalue) {
                                     if ($val['result'] && ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationkey))) {
                                         foreach ($val['result'] as $k1 => $v1) {
                                             $contID = $v1['cid'];
                                             $param1 = array('entityID' => $contID, $relationkey => 1);
                                             $getcustomValue = CRM_Core_BAO_CustomValueTable::getValues($param1);
                                             $custom_ID = CRM_Core_BAO_CustomField::getKeyID($relationkey);
                                             if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationkey)) {
                                                 if (empty($query->_options)) {
                                                     $relCustomIDs[$cfID] = array();
                                                     $relQuery = new CRM_Core_BAO_CustomQuery($relCustomIDs);
                                                     $relQuery->query();
                                                     $relOptions = $relQuery->_options;
                                                 } else {
                                                     $relOptions = $query->_options;
                                                 }
                                                 $custom_data = CRM_Core_BAO_CustomField::getDisplayValue($getcustomValue[$relationkey], $cfID, $relOptions);
                                             } else {
                                                 $custom_data = '';
                                             }
                                         }
                                     }
                                     //Get all relationships type custom fields
                                     list($id, $atype, $btype) = explode('_', $field);
                                     $relCustomData = CRM_Core_BAO_CustomField::getFields('Relationship', null, null, $id, null, null);
                                     $tmpArray = array_keys($relCustomData);
                                     $customIDs = array();
                                     foreach ($tmpArray as $customID) {
                                         $customIDs[$customID] = array();
                                     }
                                     require_once 'CRM/Core/BAO/CustomQuery.php';
                                     $customQuery = new CRM_Core_BAO_CustomQuery($customIDs);
                                     $customQuery->query();
                                     $options = $customQuery->_options;
                                     foreach ($relCustomData as $id => $customdatavalue) {
                                         if (in_array($relationkey, $customdatavalue)) {
                                             $customkey = "custom_{$id}";
                                             if ($val['result']) {
                                                 foreach ($val['result'] as $k => $v) {
                                                     $cid = $v['id'];
                                                     $param = array('entityID' => $cid, $customkey => 1);
                                                     //Get custom data values
                                                     $getCustomValueRel = CRM_Core_BAO_CustomValueTable::getValues($param);
                                                     if (!array_key_exists('error_message', $getCustomValueRel)) {
                                                         $customData = CRM_Core_BAO_CustomField::getDisplayValue($getCustomValueRel[$customkey], $id, $options);
                                                     } else {
                                                         $customData = '';
                                                     }
                                                     if ($customData) {
                                                         break;
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                     if (is_array($relationvalue)) {
                                         if (array_key_exists('location', $value)) {
                                             foreach ($value['location'] as $columnkey => $columnvalue) {
                                                 foreach ($columnvalue as $colkey => $colvalue) {
                                                     list($serviceProvider, $serviceProviderID) = explode('-', $colkey);
                                                     if (in_array($serviceProvider, array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'state_province', 'country'))) {
                                                         $serviceProvider = 'address';
                                                     }
                                                     $output = null;
                                                     foreach ((array) $data->{$serviceProvider} as $datakey => $datavalue) {
                                                         if ($columnkey == 'Primary') {
                                                             $columnkey = $locationTypes[$datavalue['location_type_id']];
                                                         }
                                                         if ($locationTypes[$datavalue['location_type_id']] == $columnkey) {
                                                             if (array_key_exists($colkey, $datavalue)) {
                                                                 $output = $datavalue[$colkey];
                                                             } else {
                                                                 if ($colkey == 'country') {
                                                                     $countryId = $datavalue['country_id'];
                                                                     if ($countryId) {
                                                                         require_once 'CRM/Core/PseudoConstant.php';
                                                                         $country =& CRM_Core_PseudoConstant::country($countryId);
                                                                     } else {
                                                                         $country = '';
                                                                     }
                                                                     $output = $country;
                                                                 } else {
                                                                     if ($colkey == 'state_province') {
                                                                         $stateProvinceId = $datavalue['state_province_id'];
                                                                         if ($stateProvinceId) {
                                                                             $stateProvince =& CRM_Core_PseudoConstant::stateProvince($stateProvinceId);
                                                                         } else {
                                                                             $stateProvince = '';
                                                                         }
                                                                         $output = $stateProvince;
                                                                     } else {
                                                                         if (is_numeric($serviceProviderID)) {
                                                                             if ($serviceProvider == 'phone') {
                                                                                 if (isset($datavalue['phone'])) {
                                                                                     $output = $datavalue['phone'];
                                                                                 } else {
                                                                                     $output = '';
                                                                                 }
                                                                             } else {
                                                                                 if ($serviceProvider == 'im') {
                                                                                     if (isset($datavalue['name'])) {
                                                                                         $output = $datavalue['name'];
                                                                                     } else {
                                                                                         $output = '';
                                                                                     }
                                                                                 }
                                                                             }
                                                                         } else {
                                                                             if ($datavalue['location_type_id']) {
                                                                                 if ($colkey == 'im') {
                                                                                     $output = $datavalue['name'];
                                                                                 } else {
                                                                                     $output = $datavalue[$colkey];
                                                                                 }
                                                                             } else {
                                                                                 $output = '';
                                                                             }
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                     if ($is_valid) {
                                                         $row[] = $output;
                                                     } else {
                                                         $row[] = '';
                                                     }
                                                 }
                                             }
                                         }
                                     } else {
                                         if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationkey) && $is_valid) {
                                             $row[] = $custom_data;
                                         } else {
                                             if ($query->_fields[$relationkey]['name'] && $is_valid) {
                                                 if ($query->_fields[$relationkey]['name'] == 'gender') {
                                                     $getGenders =& CRM_Core_PseudoConstant::gender();
                                                     $gender = array_search($data->gender_id, array_flip($getGenders));
                                                     $row[] = $gender;
                                                 } else {
                                                     if ($query->_fields[$relationkey]['name'] == 'greeting_type') {
                                                         $getgreeting =& CRM_Core_PseudoConstant::greeting();
                                                         $greeting = array_search($data->greeting_type_id, array_flip($getgreeting));
                                                         $row[] = $greeting;
                                                     } else {
                                                         $colValue = $query->_fields[$relationkey]['name'];
                                                         $row[] = $data->{$colValue};
                                                     }
                                                 }
                                             } else {
                                                 if ($customData && $is_valid) {
                                                     $row[] = $customData;
                                                 } else {
                                                     $row[] = '';
                                                 }
                                             }
                                         }
                                     }
                                 }
                             } else {
                                 if (isset($fieldValue) && $fieldValue != '') {
                                     //check for custom data
                                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
                                         $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
                                     } else {
                                         if (array_key_exists($field, $multipleSelectFields)) {
                                             //option group fixes
                                             $paramsNew = array($field => $fieldValue);
                                             if ($field == 'test_tutoring') {
                                                 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
                                             } else {
                                                 if (substr($field, 0, 4) == 'cmr_') {
                                                     //for  readers group
                                                     $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
                                                 } else {
                                                     $name = array($field => array('newName' => $field, 'groupName' => $field));
                                                 }
                                             }
                                             CRM_Core_OptionGroup::lookupValues($paramsNew, $name, false);
                                             $row[$field] = $paramsNew[$field];
                                         } else {
                                             if (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                 //special case for greeting replacement
                                                 $fldValue = "{$field}_display";
                                                 $row[$field] = $dao->{$fldValue};
                                             } else {
                                                 //normal fields
                                                 $row[$field] = $fieldValue;
                                             }
                                         }
                                     }
                                 } else {
                                     // if field is empty or null
                                     $row[$field] = '';
                                 }
                             }
                         }
                     }
                 }
             }
         }
         //build header only once
         $setHeader = false;
         // add payment headers if required
         if ($addPaymentHeader && $paymentFields) {
             $headerRows = array_merge($headerRows, $paymentHeaders);
             $addPaymentHeader = false;
         }
         // add payment related information
         if ($paymentFields && isset($paymentDetails[$row[$paymentTableId]])) {
             $row = array_merge($row, $paymentDetails[$row[$paymentTableId]]);
         }
         //remove organization name for individuals if it is set for current employer
         if (CRM_Utils_Array::value('contact_type', $row) && $row['contact_type'] == 'Individual') {
             $row['organization_name'] = '';
         }
         // add component info
         $componentDetails[] = $row;
     }
     require_once 'CRM/Core/Report/Excel.php';
     CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName('csv', $exportMode), $headerRows, $componentDetails);
     exit;
 }
Example #13
0
 /**
  *
  * 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);
         }
     }
 }
Example #14
0
 /**
  * Function to get the list the export fields
  *
  * @param int    $selectAll user preference while export
  * @param array  $ids  contact ids
  * @param array  $params associated array of fields
  * @param string $order order by clause
  * @param array  $fields associated array of fields
  * @param array  $moreReturnProperties additional return fields
  * @param int    $exportMode export mode
  * @param string $componentClause component clause
  * @param string $componentTable component table 
  * @param bool   $mergeSameAddress merge records if they have same address 
  * @param bool   $mergeSameHousehold merge records if they belong to the same household
  *
  * @static
  * @access public
  */
 static function exportComponents($selectAll, $ids, $params, $order = null, $fields = null, $moreReturnProperties = null, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = null, $componentTable = null, $mergeSameAddress = false, $mergeSameHousehold = false)
 {
     $headerRows = $returnProperties = array();
     $primary = $paymentFields = false;
     $origFields = $fields;
     $queryMode = null;
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true, 'label', false);
     $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
             break;
         case CRM_Export_Form_Select::PLEDGE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
             break;
         case CRM_Export_Form_Select::CASE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CASE;
             break;
         case CRM_Export_Form_Select::GRANT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_GRANT;
             break;
         case CRM_Export_Form_Select::ACTIVITY_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_ACTIVITY;
             break;
     }
     require_once 'CRM/Core/BAO/CustomField.php';
     if ($fields) {
         //construct return properties
         $locationTypes = CRM_Core_PseudoConstant::locationType();
         $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im');
         foreach ($fields as $key => $value) {
             $phoneTypeId = $imProviderId = null;
             $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
             if (!$fieldName) {
                 continue;
             }
             // get phoneType id and IM service provider id seperately
             if ($fieldName == 'phone') {
                 $phoneTypeId = CRM_Utils_Array::value(3, $value);
             } else {
                 if ($fieldName == 'im') {
                     $imProviderId = CRM_Utils_Array::value(3, $value);
                 }
             }
             if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
                 if (CRM_Utils_Array::value(2, $value)) {
                     $relationField = CRM_Utils_Array::value(2, $value);
                     if (trim(CRM_Utils_Array::value(3, $value))) {
                         $relLocTypeId = CRM_Utils_Array::value(3, $value);
                     } else {
                         $relLocTypeId = 'Primary';
                     }
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
                     } else {
                         if ($relationField == 'im') {
                             $relIMProviderId = CRM_Utils_Array::value(4, $value);
                         }
                     }
                 } else {
                     if (CRM_Utils_Array::value(4, $value)) {
                         $relationField = CRM_Utils_Array::value(4, $value);
                         $relLocTypeId = CRM_Utils_Array::value(5, $value);
                         if ($relationField == 'phone') {
                             $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
                         } else {
                             if ($relationField == 'im') {
                                 $relIMProviderId = CRM_Utils_Array::value(6, $value);
                             }
                         }
                     }
                 }
             }
             $contactType = CRM_Utils_Array::value(0, $value);
             $locTypeId = CRM_Utils_Array::value(2, $value);
             $phoneTypeId = CRM_Utils_Array::value(3, $value);
             if ($relationField) {
                 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
                     if ($relPhoneTypeId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
                     } else {
                         if ($relIMProviderId) {
                             $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
                         } else {
                             $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
                         }
                     }
                     $relPhoneTypeId = $relIMProviderId = null;
                 } else {
                     $returnProperties[$relationshipTypes][$relationField] = 1;
                 }
             } else {
                 if (is_numeric($locTypeId)) {
                     if ($phoneTypeId) {
                         $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
                     } else {
                         if (isset($imProviderId)) {
                             //build returnProperties for IM service provider
                             $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
                         } else {
                             $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
                         }
                     }
                 } else {
                     //hack to fix component fields
                     if ($fieldName == 'event_id') {
                         $returnProperties['event_title'] = 1;
                     } else {
                         $returnProperties[$fieldName] = 1;
                     }
                 }
             }
         }
         // hack to add default returnproperty based on export mode
         if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
             $returnProperties['contribution_id'] = 1;
         } else {
             if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
                 $returnProperties['participant_id'] = 1;
                 if ($returnProperties['participant_role']) {
                     unset($returnProperties['participant_role']);
                     $returnProperties['participant_role_id'] = 1;
                 }
             } else {
                 if ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
                     $returnProperties['membership_id'] = 1;
                 } else {
                     if ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
                         $returnProperties['pledge_id'] = 1;
                     } else {
                         if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
                             $returnProperties['case_id'] = 1;
                         } else {
                             if ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) {
                                 $returnProperties['grant_id'] = 1;
                             } else {
                                 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
                                     $returnProperties['activity_id'] = 1;
                                 }
                             }
                         }
                     }
                 }
             }
         }
     } else {
         $primary = true;
         $fields = CRM_Contact_BAO_Contact::exportableFields('All', true, true);
         foreach ($fields as $key => $var) {
             if ($key && substr($key, 0, 6) != 'custom') {
                 //for CRM=952
                 $returnProperties[$key] = 1;
             }
         }
         if ($primary) {
             $returnProperties['location_type'] = 1;
             $returnProperties['im_provider'] = 1;
             $returnProperties['phone_type_id'] = 1;
             $returnProperties['provider_id'] = 1;
             $returnProperties['current_employer'] = 1;
         }
         $extraReturnProperties = array();
         $paymentFields = false;
         switch ($queryMode) {
             case CRM_Contact_BAO_Query::MODE_EVENT:
                 $paymentFields = true;
                 $paymentTableId = "participant_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_MEMBER:
                 $paymentFields = true;
                 $paymentTableId = "membership_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_PLEDGE:
                 require_once 'CRM/Pledge/BAO/Query.php';
                 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
                 $paymentFields = true;
                 $paymentTableId = "pledge_payment_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_CASE:
                 require_once 'CRM/Case/BAO/Query.php';
                 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
                 break;
         }
         if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
             $componentReturnProperties = CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
             $returnProperties = array_merge($returnProperties, $componentReturnProperties);
             if (!empty($extraReturnProperties)) {
                 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
             }
             // unset non exportable fields for components
             $nonExpoFields = array('groups', 'tags', 'notes', 'contribution_status_id', 'pledge_status_id', 'pledge_payment_status_id');
             foreach ($nonExpoFields as $value) {
                 unset($returnProperties[$value]);
             }
         }
     }
     if ($mergeSameAddress) {
         $drop = false;
         //make sure the addressee fields are selected
         //while using merge same address feature
         $returnProperties['addressee'] = 1;
         $returnProperties['street_name'] = 1;
         if (!CRM_Utils_Array::value('last_name', $returnProperties)) {
             $returnProperties['last_name'] = 1;
             $drop = 'last_name';
         }
         $returnProperties['household_name'] = 1;
         $returnProperties['street_address'] = 1;
     }
     if ($moreReturnProperties) {
         // fix for CRM-7066
         if (CRM_Utils_Array::value('group', $moreReturnProperties)) {
             unset($moreReturnProperties['group']);
             $moreReturnProperties['groups'] = 1;
         }
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $query = new CRM_Contact_BAO_Query(0, $returnProperties, null, false, false, $queryMode);
     list($select, $from, $where) = $query->query();
     if ($mergeSameHousehold == 1) {
         if (!$returnProperties['id']) {
             $returnProperties['id'] = 1;
             $setId = true;
         } else {
             $setId = false;
         }
         $relationKey = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
         foreach ($returnProperties as $key => $value) {
             if (!array_key_exists($key, $contactRelationshipTypes)) {
                 $returnProperties[$relationKey][$key] = $value;
             }
         }
         unset($returnProperties[$relationKey]['location_type']);
         unset($returnProperties[$relationKey]['im_provider']);
     }
     $allRelContactArray = $relationQuery = array();
     foreach ($contactRelationshipTypes as $rel => $dnt) {
         if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) {
             $allRelContactArray[$rel] = array();
             // build Query for each relationship
             $relationQuery[$rel] = new CRM_Contact_BAO_Query(0, $relationReturnProperties, null, false, false, $queryMode);
             list($relationSelect, $relationFrom, $relationWhere) = $relationQuery[$rel]->query();
             list($id, $direction) = explode('_', $rel, 2);
             // identify the relationship direction
             $contactA = 'contact_id_a';
             $contactB = 'contact_id_b';
             if ($direction == 'b_a') {
                 $contactA = 'contact_id_b';
                 $contactB = 'contact_id_a';
             }
             if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
                 $relIDs = $ids;
             } else {
                 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
                     $query = "SELECT source_contact_id FROM civicrm_activity\n                              WHERE id IN ( " . implode(',', $ids) . ")";
                     $dao = CRM_Core_DAO::executeQuery($query);
                     while ($dao->fetch()) {
                         $relIDs[] = $dao->source_contact_id;
                     }
                 } else {
                     switch ($exportMode) {
                         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
                             $component = 'civicrm_contribution';
                             break;
                         case CRM_Export_Form_Select::EVENT_EXPORT:
                             $component = 'civicrm_participant';
                             break;
                         case CRM_Export_Form_Select::MEMBER_EXPORT:
                             $component = 'civicrm_membership';
                             break;
                         case CRM_Export_Form_Select::PLEDGE_EXPORT:
                             $component = 'civicrm_pledge';
                             break;
                         case CRM_Export_Form_Select::CASE_EXPORT:
                             $component = 'civicrm_case';
                             break;
                         case CRM_Export_Form_Select::GRANT_EXPORT:
                             $component = 'civicrm_grant';
                             break;
                     }
                     $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
                 }
             }
             $relationshipJoin = $relationshipClause = '';
             if ($componentTable) {
                 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
             } else {
                 $relID = implode(',', $relIDs);
                 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
             }
             $relationFrom = " {$relationFrom}\n                INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id} \n                {$relationshipJoin} ";
             $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause}";
             $relationGroupBy = " GROUP BY crel.{$contactA}";
             $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
             $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere} {$relationGroupBy}";
             $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
             while ($allRelContactDAO->fetch()) {
                 //FIX Me: Migrate this to table rather than array
                 // build the array of all related contacts
                 $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone $allRelContactDAO;
             }
             $allRelContactDAO->free();
         }
     }
     // make sure the groups stuff is included only if specifically specified
     // by the fields param (CRM-1969), else we limit the contacts outputted to only
     // ones that are part of a group
     if (CRM_Utils_Array::value('groups', $returnProperties)) {
         $oldClause = "contact_a.id = civicrm_group_contact.contact_id";
         $newClause = " ( {$oldClause} AND civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) ";
         // total hack for export, CRM-3618
         $from = str_replace($oldClause, $newClause, $from);
     }
     if ($componentTable) {
         $from .= " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = contact_a.id ";
     } else {
         if ($componentClause) {
             if (empty($where)) {
                 $where = "WHERE {$componentClause}";
             } else {
                 $where .= " AND {$componentClause}";
             }
         }
     }
     $queryString = "{$select} {$from} {$where}";
     $groupBy = "";
     if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties) || CRM_Utils_Array::value('notes', $returnProperties) || $query->_useGroupBy) {
         $groupBy = " GROUP BY contact_a.id";
     }
     if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
         $groupBy = " GROUP BY civicrm_activity.id ";
     }
     $queryString .= $groupBy;
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (CRM_Utils_Array::value($field, $returnProperties)) {
             // $queryString .= " ORDER BY $order";
         }
     }
     //hack for student data
     require_once 'CRM/Core/OptionGroup.php';
     $multipleSelectFields = array('preferred_communication_method' => 1);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $studentFields = array();
         $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields;
         $multipleSelectFields = array_merge($multipleSelectFields, $studentFields);
     }
     $header = $addPaymentHeader = false;
     if ($paymentFields) {
         //special return properties for event and members
         $paymentHeaders = array('total_amount' => ts('Total Amount'), 'contribution_status' => ts('Contribution Status'), 'received_date' => ts('Received Date'), 'payment_instrument' => ts('Payment Instrument'), 'transaction_id' => ts('Transaction ID'));
         // get payment related in for event and members
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
         if (!empty($paymentDetails)) {
             $addPaymentHeader = true;
         }
         $nullContributionDetails = array_fill_keys($paymentHeaders, null);
     }
     $componentDetails = $headerRows = $sqlColumns = array();
     $setHeader = true;
     $rowCount = self::EXPORT_ROW_COUNT;
     $offset = 0;
     $count = -1;
     // for CRM-3157 purposes
     require_once 'CRM/Core/I18n.php';
     $i18n =& CRM_Core_I18n::singleton();
     while (1) {
         $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
         $dao = CRM_Core_DAO::executeQuery($limitQuery);
         if ($dao->N <= 0) {
             break;
         }
         while ($dao->fetch()) {
             $count++;
             $row = array();
             //first loop through returnproperties so that we return what is required, and in same order.
             $relationshipField = 0;
             foreach ($returnProperties as $field => $value) {
                 //we should set header only once
                 if ($setHeader) {
                     $sqlDone = false;
                     if (isset($query->_fields[$field]['title'])) {
                         $headerRows[] = $query->_fields[$field]['title'];
                     } else {
                         if ($field == 'phone_type_id') {
                             $headerRows[] = 'Phone Type';
                         } else {
                             if ($field == 'provider_id') {
                                 $headerRows[] = 'Im Service Provider';
                             } else {
                                 if (is_array($value) && $field == 'location') {
                                     // fix header for location type case
                                     foreach ($value as $ltype => $val) {
                                         foreach (array_keys($val) as $fld) {
                                             $type = explode('-', $fld);
                                             $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
                                             if (CRM_Utils_Array::value(1, $type)) {
                                                 if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                     $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                                 } else {
                                                     if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                         $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                     }
                                                 }
                                             }
                                             $headerRows[] = $hdr;
                                             self::sqlColumnDefn($query, $sqlColumns, $hdr);
                                         }
                                         $sqlDone = true;
                                     }
                                 } else {
                                     if (substr($field, 0, 5) == 'case_') {
                                         if ($query->_fields['case'][$field]['title']) {
                                             $headerRows[] = $query->_fields['case'][$field]['title'];
                                         } else {
                                             if ($query->_fields['activity'][$field]['title']) {
                                                 $headerRows[] = $query->_fields['activity'][$field]['title'];
                                             }
                                         }
                                     } else {
                                         if (array_key_exists($field, $contactRelationshipTypes)) {
                                             $relName = $field;
                                             foreach ($value as $relationField => $relationValue) {
                                                 // below block is same as primary block (duplicate)
                                                 if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
                                                     $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['title'];
                                                     $headerRows[] = $headerName;
                                                     self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                                 } else {
                                                     if ($relationField == 'phone_type_id') {
                                                         $headerName = $field . '-' . 'Phone Type';
                                                         $headerRows[] = $headerName;
                                                         self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                                     } else {
                                                         if ($relationField == 'provider_id') {
                                                             $headerName = $field . '-' . 'Im Service Provider';
                                                             $headerRows[] = $headerName;
                                                             self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                                         } else {
                                                             if (is_array($relationValue) && $relationField == 'location') {
                                                                 // fix header for location type case
                                                                 foreach ($relationValue as $ltype => $val) {
                                                                     foreach (array_keys($val) as $fld) {
                                                                         $type = explode('-', $fld);
                                                                         $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
                                                                         if (CRM_Utils_Array::value(1, $type)) {
                                                                             if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                                                             } else {
                                                                                 if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                                                     $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                                                 }
                                                                             }
                                                                         }
                                                                         $headerName = $field . '-' . $hdr;
                                                                         $headerRows[] = $headerName;
                                                                         self::sqlColumnDefn($query, $sqlColumns, $headerName);
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         } else {
                                             $headerRows[] = $field;
                                         }
                                     }
                                 }
                             }
                         }
                     }
                     if (!$sqlDone) {
                         self::sqlColumnDefn($query, $sqlColumns, $field);
                     }
                 }
                 //build row values (data)
                 if (property_exists($dao, $field)) {
                     $fieldValue = $dao->{$field};
                     // to get phone type from phone type id
                     if ($field == 'phone_type_id') {
                         $fieldValue = $phoneTypes[$fieldValue];
                     } else {
                         if ($field == 'provider_id') {
                             $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
                         } else {
                             if ($field == 'participant_role_id') {
                                 require_once 'CRM/Event/PseudoConstant.php';
                                 $participantRoles = CRM_Event_PseudoConstant::participantRole();
                                 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
                                 $viewRoles = array();
                                 foreach (explode($sep, $dao->{$field}) as $k => $v) {
                                     $viewRoles[] = $participantRoles[$v];
                                 }
                                 $fieldValue = implode(',', $viewRoles);
                             }
                         }
                     }
                 } else {
                     if ($field == 'master_address_belongs_to') {
                         $masterAddressId = null;
                         if (isset($dao->master_id)) {
                             $masterAddressId = $dao->master_id;
                         }
                         // get display name of contact that address is shared.
                         $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $dao->contact_id);
                     } else {
                         $fieldValue = '';
                     }
                 }
                 if ($field == 'id') {
                     $row[$field] = $dao->contact_id;
                 } else {
                     if ($field == 'pledge_balance_amount') {
                         //special case for calculated field
                         $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid;
                     } else {
                         if ($field == 'pledge_next_pay_amount') {
                             //special case for calculated field
                             $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount;
                         } else {
                             if (is_array($value) && $field == 'location') {
                                 // fix header for location type case
                                 foreach ($value as $ltype => $val) {
                                     foreach (array_keys($val) as $fld) {
                                         $type = explode('-', $fld);
                                         $fldValue = "{$ltype}-" . $type[0];
                                         if (CRM_Utils_Array::value(1, $type)) {
                                             $fldValue .= "-" . $type[1];
                                         }
                                         // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                                         switch ($fld) {
                                             case 'country':
                                             case 'world_region':
                                                 $row[$fldValue] = $i18n->crm_translate($dao->{$fldValue}, array('context' => 'country'));
                                                 break;
                                             case 'state_province':
                                                 $row[$fldValue] = $i18n->crm_translate($dao->{$fldValue}, array('context' => 'province'));
                                                 break;
                                             default:
                                                 $row[$fldValue] = $dao->{$fldValue};
                                                 break;
                                         }
                                     }
                                 }
                             } else {
                                 if (array_key_exists($field, $contactRelationshipTypes)) {
                                     $relDAO = $allRelContactArray[$field][$dao->contact_id];
                                     foreach ($value as $relationField => $relationValue) {
                                         if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
                                             $fieldValue = $relDAO->{$relationField};
                                             if ($relationField == 'phone_type_id') {
                                                 $fieldValue = $phoneTypes[$relationValue];
                                             } else {
                                                 if ($relationField == 'provider_id') {
                                                     $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
                                                 }
                                             }
                                         } else {
                                             $fieldValue = '';
                                         }
                                         if ($relationField == 'id') {
                                             $row[$field . $relationField] = $relDAO->contact_id;
                                         } else {
                                             if (is_array($relationValue) && $relationField == 'location') {
                                                 foreach ($relationValue as $ltype => $val) {
                                                     foreach (array_keys($val) as $fld) {
                                                         $type = explode('-', $fld);
                                                         $fldValue = "{$ltype}-" . $type[0];
                                                         if (CRM_Utils_Array::value(1, $type)) {
                                                             $fldValue .= "-" . $type[1];
                                                         }
                                                         // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                                                         switch (true) {
                                                             case in_array('country', $type):
                                                             case in_array('world_region', $type):
                                                                 $row[$field . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'country'));
                                                                 break;
                                                             case in_array('state_province', $type):
                                                                 $row[$field . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'province'));
                                                                 break;
                                                             default:
                                                                 $row[$field . $fldValue] = $relDAO->{$fldValue};
                                                                 break;
                                                         }
                                                     }
                                                 }
                                             } else {
                                                 if (isset($fieldValue) && $fieldValue != '') {
                                                     //check for custom data
                                                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
                                                         $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $relationQuery[$field]->_options);
                                                     } else {
                                                         if (in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                             //special case for greeting replacement
                                                             $fldValue = "{$relationField}_display";
                                                             $row[$field . $relationField] = $relDAO->{$fldValue};
                                                         } else {
                                                             //normal relationship fields
                                                             // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
                                                             switch ($relationField) {
                                                                 case 'country':
                                                                 case 'world_region':
                                                                     $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
                                                                     break;
                                                                 case 'state_province':
                                                                     $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
                                                                     break;
                                                                 default:
                                                                     $row[$field . $relationField] = $fieldValue;
                                                                     break;
                                                             }
                                                         }
                                                     }
                                                 } else {
                                                     // if relation field is empty or null
                                                     $row[$field . $relationField] = '';
                                                 }
                                             }
                                         }
                                     }
                                 } else {
                                     if (isset($fieldValue) && $fieldValue != '') {
                                         //check for custom data
                                         if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
                                             $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
                                         } else {
                                             if (array_key_exists($field, $multipleSelectFields)) {
                                                 //option group fixes
                                                 $paramsNew = array($field => $fieldValue);
                                                 if ($field == 'test_tutoring') {
                                                     $name = array($field => array('newName' => $field, 'groupName' => 'test'));
                                                 } else {
                                                     if (substr($field, 0, 4) == 'cmr_') {
                                                         //for  readers group
                                                         $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
                                                     } else {
                                                         $name = array($field => array('newName' => $field, 'groupName' => $field));
                                                     }
                                                 }
                                                 CRM_Core_OptionGroup::lookupValues($paramsNew, $name, false);
                                                 $row[$field] = $paramsNew[$field];
                                             } else {
                                                 if (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                     //special case for greeting replacement
                                                     $fldValue = "{$field}_display";
                                                     $row[$field] = $dao->{$fldValue};
                                                 } else {
                                                     //normal fields with a touch of CRM-3157
                                                     switch ($field) {
                                                         case 'country':
                                                         case 'world_region':
                                                             $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
                                                             break;
                                                         case 'state_province':
                                                             $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
                                                             break;
                                                         case 'gender':
                                                         case 'preferred_communication_method':
                                                         case 'preferred_mail_format':
                                                             $row[$field] = $i18n->crm_translate($fieldValue);
                                                             break;
                                                         default:
                                                             $row[$field] = $fieldValue;
                                                             break;
                                                     }
                                                 }
                                             }
                                         }
                                     } else {
                                         // if field is empty or null
                                         $row[$field] = '';
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             // add payment headers if required
             if ($addPaymentHeader && $paymentFields) {
                 $headerRows = array_merge($headerRows, $paymentHeaders);
                 foreach ($paymentHeaders as $paymentHdr) {
                     self::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
                 }
                 $addPaymentHeader = false;
             }
             if ($setHeader) {
                 $exportTempTable = self::createTempTable($sqlColumns);
             }
             //build header only once
             $setHeader = false;
             // add payment related information
             if ($paymentFields && isset($paymentDetails[$row[$paymentTableId]])) {
                 $row = array_merge($row, $paymentDetails[$row[$paymentTableId]]);
             } else {
                 if ($paymentDetails) {
                     $row = array_merge($row, $nullContributionDetails);
                 }
             }
             //remove organization name for individuals if it is set for current employer
             if (CRM_Utils_Array::value('contact_type', $row) && $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)) {
                 $row['organization_name'] = '';
             }
             // add component info
             // write the row to a file
             $componentDetails[] = $row;
             // output every $rowCount rows
             if ($count % $rowCount == 0) {
                 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
                 $componentDetails = array();
             }
         }
         $dao->free();
         $offset += $rowCount;
     }
     self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
     // do merge same address and merge same household processing
     if ($mergeSameAddress) {
         self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $drop);
     }
     // merge the records if they have corresponding households
     if ($mergeSameHousehold) {
         self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKey);
     }
     // fix the headers for rows with relationship type
     if ($relName) {
         self::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
     }
     // call export hook
     require_once 'CRM/Utils/Hook.php';
     CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
     // now write the CSV file
     self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
     CRM_Utils_System::civiExit();
 }
 /**
  * Get all phone type
  * The static array phoneType is returned
  *
  * @access public
  * @static
  *
  * @param boolean $all - get All phone type - default is to get
  * only active ones.
  *
  * @return array - array reference of all phone types.
  *
  */
 public static function &phoneType()
 {
     if (!self::$phoneType) {
         self::$phoneType = CRM_Core_OptionGroup::values('phone_type');
     }
     return self::$phoneType;
 }
Example #16
0
 /**
  * Function to actually build the form
  *
  * @return void
  * @access public
  */
 public function buildQuickForm()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete Profile Field'), 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel'))));
         return;
     }
     if (isset($this->_id)) {
         $params = array('id' => $this->_id);
         CRM_Core_BAO_UFField::retrieve($params, $defaults);
         // set it to null if so (avoids crappy E_NOTICE errors below
         $defaults['location_type_id'] = CRM_Utils_Array::value('location_type_id', $defaults);
         $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', 'county', 'phone', 'email', 'im', 'address_name');
         if (!$defaults['location_type_id'] && in_array($defaults['field_name'], $specialFields)) {
             $defaults['location_type_id'] = 0;
         }
         $defaults['field_name'] = array($defaults['field_type'], $defaults['field_name'], $defaults['location_type_id'], CRM_Utils_Array::value('phone_type_id', $defaults));
         $this->_gid = $defaults['uf_group_id'];
     } else {
         $defaults['is_active'] = 1;
     }
     if ($this->_action & CRM_Core_Action::ADD) {
         $fieldValues = array('uf_group_id' => $this->_gid);
         $defaults['weight'] = CRM_Utils_Weight::getDefaultWeight('CRM_Core_DAO_UFField', $fieldValues);
     }
     // lets trim all the whitespace
     $this->applyFilter('__ALL__', 'trim');
     //hidden field to catch the group id in profile
     $this->add('hidden', 'group_id', $this->_gid);
     //hidden field to catch the field id in profile
     $this->add('hidden', 'field_id', $this->_id);
     $fields = array();
     $fields['Individual'] =& CRM_Contact_BAO_Contact::importableFields('Individual', false, false, true);
     $fields['Household'] =& CRM_Contact_BAO_Contact::importableFields('Household', false, false, true);
     $fields['Organization'] =& CRM_Contact_BAO_Contact::importableFields('Organization', false, false, true);
     // add current employer for individuals
     $fields['Individual']['current_employer'] = array('name' => 'organization_name', 'title' => ts('Current Employer'));
     // unset unwanted fields
     $unsetFieldArray = array('note', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom', 'id');
     foreach ($unsetFieldArray as $value) {
         unset($fields['Individual'][$value]);
         unset($fields['Household'][$value]);
         unset($fields['Organization'][$value]);
     }
     require_once 'CRM/Core/BAO/Preferences.php';
     $addressOptions = CRM_Core_BAO_Preferences::valueOptions('address_options', true, null, true);
     if (!$addressOptions['county']) {
         unset($fields['Individual']['county']);
         unset($fields['Household']['county']);
         unset($fields['Organization']['county']);
     }
     //build the common contact fields array CRM-3037.
     foreach ($fields['Individual'] as $key => $value) {
         if (CRM_Utils_Array::value($key, $fields['Household']) && CRM_Utils_Array::value($key, $fields['Organization'])) {
             $fields['Contact'][$key] = $value;
             //as we move common fields to contacts. There fore these fields
             //are unset from resoective array's.
             unset($fields['Individual'][$key]);
             unset($fields['Household'][$key]);
             unset($fields['Organization'][$key]);
         }
     }
     // add current employer for individuals
     $fields['Contact']['id'] = array('name' => 'id', 'title' => ts('Internal Contact ID'));
     unset($fields['Contact']['contact_type']);
     // 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);
     unset($contactTypes['']);
     // include Subtypes For Profile
     $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
     foreach ($subTypes as $name => $val) {
         //custom fields for sub type
         $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($name);
         if (array_key_exists($val['parent'], $fields)) {
             $fields[$name] = $fields[$val['parent']] + $subTypeFields;
         } else {
             $fields[$name] = $subTypeFields;
         }
     }
     unset($subTypes);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $fields['Student'] =& CRM_Quest_BAO_Student::exportableFields();
     }
     if (CRM_Core_Permission::access('CiviContribute')) {
         $contribFields =& CRM_Contribute_BAO_Contribution::getContributionFields();
         if (!empty($contribFields)) {
             unset($contribFields['is_test']);
             unset($contribFields['is_pay_later']);
             unset($contribFields['contribution_id']);
             $fields['Contribution'] =& $contribFields;
         }
     }
     if (CRM_Core_Permission::access('CiviEvent')) {
         require_once 'CRM/Event/BAO/Query.php';
         $participantFields =& CRM_Event_BAO_Query::getParticipantFields(true);
         if (!empty($participantFields)) {
             unset($participantFields['external_identifier']);
             unset($participantFields['event_id']);
             unset($participantFields['participant_contact_id']);
             unset($participantFields['participant_is_test']);
             unset($participantFields['participant_fee_level']);
             unset($participantFields['participant_id']);
             unset($participantFields['participant_is_pay_later']);
             $fields['Participant'] =& $participantFields;
         }
     }
     if (CRM_Core_Permission::access('CiviMember')) {
         require_once 'CRM/Member/BAO/Membership.php';
         $membershipFields =& CRM_Member_BAO_Membership::getMembershipFields();
         unset($membershipFields['membership_id']);
         unset($membershipFields['join_date']);
         unset($membershipFields['membership_start_date']);
         unset($membershipFields['membership_type_id']);
         unset($membershipFields['membership_end_date']);
         unset($membershipFields['member_is_test']);
         unset($membershipFields['is_override']);
         unset($membershipFields['status_id']);
         unset($membershipFields['member_is_pay_later']);
         $fields['Membership'] =& $membershipFields;
     }
     $noSearchable = array();
     foreach ($fields as $key => $value) {
         foreach ($value as $key1 => $value1) {
             //CRM-2676, replacing the conflict for same custom field name from different custom group.
             require_once 'CRM/Core/BAO/CustomField.php';
             if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key1)) {
                 $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
                 $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
                 $this->_mapperFields[$key][$key1] = $value1['title'] . ' :: ' . $customGroupName;
             } else {
                 $this->_mapperFields[$key][$key1] = $value1['title'];
             }
             $hasLocationTypes[$key][$key1] = CRM_Utils_Array::value('hasLocationType', $value1);
             // hide the 'is searchable' field for 'File' custom data
             if (isset($value1['data_type']) && isset($value1['html_type']) && ($value1['data_type'] == 'File' && $value1['html_type'] == 'File' || $value1['data_type'] == 'Link' && $value1['html_type'] == 'Link')) {
                 if (!in_array($value1['title'], $noSearchable)) {
                     $noSearchable[] = $value1['title'];
                 }
             }
         }
     }
     $this->assign('noSearchable', $noSearchable);
     require_once 'CRM/Core/BAO/LocationType.php';
     $this->_location_types =& CRM_Core_PseudoConstant::locationType();
     $defaultLocationType =& CRM_Core_BAO_LocationType::getDefault();
     /* FIXME: dirty hack to make the default option show up first.  This
      * avoids a mozilla browser bug with defaults on dynamically constructed
      * selector widgets. */
     if ($defaultLocationType) {
         $defaultLocation = $this->_location_types[$defaultLocationType->id];
         unset($this->_location_types[$defaultLocationType->id]);
         $this->_location_types = array($defaultLocationType->id => $defaultLocation) + $this->_location_types;
     }
     $this->_location_types = array('Primary') + $this->_location_types;
     $contactTypes = !empty($contactTypes) ? array('Contact' => 'Contacts') + $contactTypes : array();
     $sel1 = array('' => '- select -') + $contactTypes;
     if (CRM_Core_Permission::access('Quest')) {
         $sel1['Student'] = 'Students';
     }
     if (CRM_Core_Permission::access('CiviEvent')) {
         $sel1['Participant'] = 'Participants';
     }
     if (!empty($contribFields)) {
         $sel1['Contribution'] = 'Contributions';
     }
     if (!empty($membershipFields)) {
         $sel1['Membership'] = 'Membership';
     }
     foreach ($sel1 as $key => $sel) {
         if ($key) {
             $sel2[$key] = $this->_mapperFields[$key];
         }
     }
     $sel3[''] = null;
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     ksort($phoneTypes);
     foreach ($sel1 as $k => $sel) {
         if ($k) {
             foreach ($this->_location_types as $key => $value) {
                 $sel4[$k]['phone'][$key] =& $phoneTypes;
             }
         }
     }
     foreach ($sel1 as $k => $sel) {
         if ($k) {
             if (is_array($this->_mapperFields[$k])) {
                 foreach ($this->_mapperFields[$k] as $key => $value) {
                     if ($hasLocationTypes[$k][$key]) {
                         $sel3[$k][$key] = $this->_location_types;
                     } else {
                         $sel3[$key] = null;
                     }
                 }
             }
         }
     }
     $this->_defaults = array();
     $js = "<script type='text/javascript'>\n";
     $formName = "document.{$this->_name}";
     $alreadyMixProfile = false;
     if (CRM_Core_BAO_UFField::checkProfileType($this->_gid)) {
         $alreadyMixProfile = true;
     }
     $this->assign('alreadyMixProfile', $alreadyMixProfile);
     $attributes = array('onclick' => "showLabel();mixProfile();", 'onblur' => 'showLabel();mixProfile();');
     $sel =& $this->addElement('hierselect', "field_name", ts('Field Name'), $attributes);
     $formValues = array();
     $formValues = $this->exportValues();
     if (empty($formValues)) {
         for ($k = 1; $k < 4; $k++) {
             if (!$defaults['field_name'][$k]) {
                 $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n";
             }
         }
     } else {
         if (!empty($formValues['field_name'])) {
             foreach ($formValues['field_name'] as $value) {
                 for ($k = 1; $k < 4; $k++) {
                     if (!isset($formValues['field_name'][$k]) || !$formValues['field_name'][$k]) {
                         $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n";
                     } else {
                         $js .= "{$formName}['field_name[{$k}]'].style.display = '';\n";
                     }
                 }
             }
         } else {
             for ($k = 1; $k < 4; $k++) {
                 if (!isset($defaults['field_name'][$k])) {
                     $js .= "{$formName}['field_name[{$k}]'].style.display = 'none';\n";
                 }
             }
         }
     }
     foreach ($sel2 as $k => $v) {
         if (is_array($sel2[$k])) {
             asort($sel2[$k]);
         }
     }
     $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
     $js .= "</script>\n";
     $this->assign('initHideBoxes', $js);
     $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::ufVisibility(), true, array("onChange" => "showHideSeletorSearch(this.value);"));
     //CRM-4363
     $js = array('onclick' => "mixProfile();");
     // should the field appear in selectors (as a column)?
     $this->add('checkbox', 'in_selector', ts('Results Column?'), null, null, $js);
     $this->add('checkbox', 'is_searchable', ts('Searchable?'), null, null, $js);
     // weight
     $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'weight'), true);
     $this->addRule('weight', ts('is a numeric field'), 'numeric');
     $this->add('textarea', 'help_post', ts('Field Help'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'help_post'));
     // listings title
     $this->add('text', 'listings_title', ts('Listings Title'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'listings_title'));
     $this->addRule('listings_title', ts('Please enter a valid title for this field when displayed in user listings.'), 'title');
     $this->add('checkbox', 'is_required', ts('Required?'));
     $this->add('checkbox', 'is_active', ts('Active?'));
     $this->add('checkbox', 'is_view', ts('View Only?'));
     // $this->add( 'checkbox', 'is_registration', ts( 'Display in Registration Form?' ) );
     //$this->add( 'checkbox', 'is_match'       , ts( 'Key to Match Contacts?'        ) );
     $this->add('text', 'label', ts('Field Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_UFField', 'label'));
     $js = null;
     if ($this->_hasSearchableORInSelector) {
         $js = array('onclick' => "return verify( );");
     }
     // add buttons
     $this->addButtons(array(array('type' => 'next', 'name' => ts('Save'), 'isDefault' => true, 'js' => $js), array('type' => 'next', 'name' => ts('Save and New'), 'subName' => 'new', 'js' => $js), array('type' => 'cancel', 'name' => ts('Cancel'))));
     $this->addFormRule(array('CRM_UF_Form_Field', 'formRule'), $this);
     // if view mode pls freeze it with the done button.
     if ($this->_action & CRM_Core_Action::VIEW) {
         $this->freeze();
         $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/uf/group/field?reset=1&action=browse&gid=" . $this->_gid . "'"));
     }
     $this->setDefaults($defaults);
 }
Example #17
0
 /**
  * Function to get the list the export fields
  *
  * @param int    $selectAll user preference while export
  * @param array  $ids  contact ids
  * @param array  $params associated array of fields
  * @param string $order order by clause
  * @param array  $associated array of fields
  * @param array  $moreReturnProperties additional return fields
  * @param int    $exportMode export mode
  * @param string $componentClause component clause
  *
  * @static
  * @access public
  */
 static function exportComponents($selectAll, $ids, $params, $order = null, $fields = null, $moreReturnProperties = null, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = null)
 {
     $headerRows = array();
     $primary = false;
     $returnProperties = array();
     $origFields = $fields;
     $queryMode = null;
     $paymentFields = false;
     $phoneTypes = CRM_Core_PseudoConstant::phoneType();
     $imProviders = CRM_Core_PseudoConstant::IMProvider();
     $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true, 'label', false);
     $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
     switch ($exportMode) {
         case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
             break;
         case CRM_Export_Form_Select::EVENT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
             break;
         case CRM_Export_Form_Select::MEMBER_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
             break;
         case CRM_Export_Form_Select::PLEDGE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
             break;
         case CRM_Export_Form_Select::CASE_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_CASE;
             break;
         case CRM_Export_Form_Select::GRANT_EXPORT:
             $queryMode = CRM_Contact_BAO_Query::MODE_GRANT;
             break;
     }
     require_once 'CRM/Core/BAO/CustomField.php';
     if ($fields) {
         //construct return properties
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im');
         foreach ($fields as $key => $value) {
             $phoneTypeId = null;
             $imProviderId = null;
             $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
             if (!$fieldName) {
                 continue;
             }
             // get phoneType id and IM service provider id seperately
             if ($fieldName == 'phone') {
                 $phoneTypeId = CRM_Utils_Array::value(3, $value);
             } else {
                 if ($fieldName == 'im') {
                     $imProviderId = CRM_Utils_Array::value(3, $value);
                 }
             }
             if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
                 if (CRM_Utils_Array::value(2, $value)) {
                     $relationField = CRM_Utils_Array::value(2, $value);
                     if (trim(CRM_Utils_Array::value(3, $value))) {
                         $relLocTypeId = CRM_Utils_Array::value(3, $value);
                     } else {
                         $relLocTypeId = 1;
                     }
                     if ($relationField == 'phone') {
                         $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
                     } else {
                         if ($relationField == 'im') {
                             $relIMProviderId = CRM_Utils_Array::value(4, $value);
                         }
                     }
                 } else {
                     if (CRM_Utils_Array::value(4, $value)) {
                         $relationField = CRM_Utils_Array::value(4, $value);
                         $relLocTypeId = CRM_Utils_Array::value(5, $value);
                         if ($relationField == 'phone') {
                             $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
                         } else {
                             if ($relationField == 'im') {
                                 $relIMProviderId = CRM_Utils_Array::value(6, $value);
                             }
                         }
                     }
                 }
             }
             $contactType = CRM_Utils_Array::value(0, $value);
             $locTypeId = CRM_Utils_Array::value(2, $value);
             $phoneTypeId = CRM_Utils_Array::value(3, $value);
             if ($relationField) {
                 if (in_array($relationField, $locationTypeFields)) {
                     if ($relPhoneTypeId) {
                         $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
                     } else {
                         if ($relIMProviderId) {
                             $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
                         } else {
                             $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
                         }
                     }
                     $relPhoneTypeId = $relIMProviderId = null;
                 } else {
                     $returnProperties[$relationshipTypes][$relationField] = 1;
                 }
             } else {
                 if (is_numeric($locTypeId)) {
                     if ($phoneTypeId) {
                         $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
                     } else {
                         if (isset($imProviderId)) {
                             //build returnProperties for IM service provider
                             $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
                         } else {
                             $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
                         }
                     }
                 } else {
                     //hack to fix component fields
                     if ($fieldName == 'event_id') {
                         $returnProperties['event_title'] = 1;
                     } else {
                         $returnProperties[$fieldName] = 1;
                     }
                 }
             }
         }
         // hack to add default returnproperty based on export mode
         if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
             $returnProperties['contribution_id'] = 1;
         } else {
             if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
                 $returnProperties['participant_id'] = 1;
             } else {
                 if ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
                     $returnProperties['membership_id'] = 1;
                 } else {
                     if ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
                         $returnProperties['pledge_id'] = 1;
                     } else {
                         if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
                             $returnProperties['case_id'] = 1;
                         } else {
                             if ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) {
                                 $returnProperties['grant_id'] = 1;
                             }
                         }
                     }
                 }
             }
         }
     } else {
         $primary = true;
         $fields = CRM_Contact_BAO_Contact::exportableFields('All', true, true);
         foreach ($fields as $key => $var) {
             if ($key && substr($key, 0, 6) != 'custom') {
                 //for CRM=952
                 $returnProperties[$key] = 1;
             }
         }
         if ($primary) {
             $returnProperties['location_type'] = 1;
             $returnProperties['im_provider'] = 1;
             $returnProperties['phone_type_id'] = 1;
             $returnProperties['provider_id'] = 1;
             $returnProperties['current_employer'] = 1;
         }
         $extraReturnProperties = array();
         $paymentFields = false;
         switch ($queryMode) {
             case CRM_Contact_BAO_Query::MODE_EVENT:
                 $paymentFields = true;
                 $paymentTableId = "participant_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_MEMBER:
                 $paymentFields = true;
                 $paymentTableId = "membership_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_PLEDGE:
                 require_once 'CRM/Pledge/BAO/Query.php';
                 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
                 $paymentFields = true;
                 $paymentTableId = "pledge_payment_id";
                 break;
             case CRM_Contact_BAO_Query::MODE_CASE:
                 require_once 'CRM/Case/BAO/Query.php';
                 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
                 break;
         }
         if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
             $componentReturnProperties =& CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
             $returnProperties = array_merge($returnProperties, $componentReturnProperties);
             if (!empty($extraReturnProperties)) {
                 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
             }
             // unset groups, tags, notes for components
             foreach (array('groups', 'tags', 'notes') as $value) {
                 unset($returnProperties[$value]);
             }
         }
     }
     if ($moreReturnProperties) {
         $returnProperties = array_merge($returnProperties, $moreReturnProperties);
     }
     $query =& new CRM_Contact_BAO_Query(0, $returnProperties, null, false, false, $queryMode);
     list($select, $from, $where) = $query->query();
     $allRelContactArray = $relationQuery = array();
     foreach ($contactRelationshipTypes as $rel => $dnt) {
         if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) {
             $allRelContactArray[$rel] = array();
             // build Query for each relationship
             $relationQuery[$rel] =& new CRM_Contact_BAO_Query(0, $relationReturnProperties, null, false, false, $queryMode);
             list($relationSelect, $relationFrom, $relationWhere) = $relationQuery[$rel]->query();
             list($id, $direction) = explode('_', $rel, 2);
             // identify the relationship direction
             $contactA = 'contact_id_a';
             $contactB = 'contact_id_b';
             if ($direction == 'b_a') {
                 $contactA = 'contact_id_b';
                 $contactB = 'contact_id_a';
             }
             $relIDs = implode(',', $ids);
             $relSQL = "SELECT {$contactB} as relContact,{$contactA} as refContact  FROM civicrm_relationship \n                           WHERE  relationship_type_id = {$id} AND\n                                  {$contactA} IN ({$relIDs})\n                           GROUP BY {$contactA}";
             // Get the related contacts
             $relContactDAO = CRM_Core_DAO::executeQuery($relSQL);
             $relContactArray = array();
             while ($relContactDAO->fetch()) {
                 $relContactArray[$relContactDAO->refContact] = $relContactDAO->relContact;
             }
             $uniqueContacts = array_unique($relContactArray);
             if (!empty($uniqueContacts)) {
                 $relationWhere = " WHERE contact_a.id IN (" . implode(',', $uniqueContacts) . ") GROUP BY contact_id";
                 $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere}";
                 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
                 while ($allRelContactDAO->fetch()) {
                     foreach ($relContactArray as $k => $v) {
                         if ($allRelContactDAO->contact_id == $v) {
                             //$allRelContactArray[$rel][$k] = array();
                             // build the array of all related contacts
                             $allRelContactArray[$rel][$k] = clone $allRelContactDAO;
                         }
                     }
                 }
             }
         }
     }
     // make sure the groups stuff is included only if specifically specified
     // by the fields param (CRM-1969), else we limit the contacts outputted to only
     // ones that are part of a group
     if (CRM_Utils_Array::value('groups', $returnProperties)) {
         $oldClause = "contact_a.id = civicrm_group_contact.contact_id";
         $newClause = " ( {$oldClause} AND civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) ";
         // total hack for export, CRM-3618
         $from = str_replace($oldClause, $newClause, $from);
     }
     if ($componentClause) {
         if (empty($where)) {
             $where = "WHERE {$componentClause}";
         } else {
             $where .= " AND {$componentClause}";
         }
     }
     $queryString = "{$select} {$from} {$where}";
     if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties) || CRM_Utils_Array::value('notes', $returnProperties) || $query->_useGroupBy) {
         $queryString .= " GROUP BY contact_a.id";
     }
     if ($order) {
         list($field, $dir) = explode(' ', $order, 2);
         $field = trim($field);
         if (CRM_Utils_Array::value($field, $returnProperties)) {
             $queryString .= " ORDER BY {$order}";
         }
     }
     //hack for student data
     require_once 'CRM/Core/OptionGroup.php';
     $multipleSelectFields = array('preferred_communication_method' => 1);
     if (CRM_Core_Permission::access('Quest')) {
         require_once 'CRM/Quest/BAO/Student.php';
         $studentFields = array();
         $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields;
         $multipleSelectFields = array_merge($multipleSelectFields, $studentFields);
     }
     $dao =& CRM_Core_DAO::executeQuery($queryString, CRM_Core_DAO::$_nullArray);
     $header = false;
     $addPaymentHeader = false;
     if ($paymentFields) {
         $addPaymentHeader = true;
         //special return properties for event and members
         $paymentHeaders = array(ts('Total Amount'), ts('Contribution Status'), ts('Received Date'), ts('Payment Instrument'), ts('Transaction ID'));
         // get payment related in for event and members
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
     }
     $componentDetails = $headerRows = array();
     $setHeader = true;
     while ($dao->fetch()) {
         $row = array();
         //first loop through returnproperties so that we return what is required, and in same order.
         $relationshipField = 0;
         foreach ($returnProperties as $field => $value) {
             //we should set header only once
             if ($setHeader) {
                 if (isset($query->_fields[$field]['title'])) {
                     $headerRows[] = $query->_fields[$field]['title'];
                 } else {
                     if ($field == 'phone_type_id') {
                         $headerRows[] = 'Phone Type';
                     } else {
                         if ($field == 'provider_id') {
                             $headerRows[] = 'Im Service Provider';
                         } else {
                             if (is_array($value) && $field == 'location') {
                                 // fix header for location type case
                                 foreach ($value as $ltype => $val) {
                                     foreach (array_keys($val) as $fld) {
                                         $type = explode('-', $fld);
                                         $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
                                         if (CRM_Utils_Array::value(1, $type)) {
                                             if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                             } else {
                                                 if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                     $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                 }
                                             }
                                         }
                                         $headerRows[] = $hdr;
                                     }
                                 }
                             } else {
                                 if (substr($field, 0, 5) == 'case_') {
                                     if ($query->_fields['case'][$field]['title']) {
                                         $headerRows[] = $query->_fields['case'][$field]['title'];
                                     } else {
                                         if ($query->_fields['activity'][$field]['title']) {
                                             $headerRows[] = $query->_fields['activity'][$field]['title'];
                                         }
                                     }
                                 } else {
                                     if (array_key_exists($field, $contactRelationshipTypes)) {
                                         $relName = CRM_Utils_Array::value($field, $contactRelationshipTypes);
                                         foreach ($value as $relationField => $relationValue) {
                                             // below block is same as primary block (duplicate)
                                             if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
                                                 $headerRows[] = $relName . '-' . $relationQuery[$field]->_fields[$relationField]['title'];
                                             } else {
                                                 if ($relationField == 'phone_type_id') {
                                                     $headerRows[] = $relName . '-' . 'Phone Type';
                                                 } else {
                                                     if ($relationField == 'provider_id') {
                                                         $headerRows[] = $relName . '-' . 'Im Service Provider';
                                                     } else {
                                                         if (is_array($relationValue) && $relationField == 'location') {
                                                             // fix header for location type case
                                                             foreach ($relationValue as $ltype => $val) {
                                                                 foreach (array_keys($val) as $fld) {
                                                                     $type = explode('-', $fld);
                                                                     $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
                                                                     if (CRM_Utils_Array::value(1, $type)) {
                                                                         if (CRM_Utils_Array::value(0, $type) == 'phone') {
                                                                             $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
                                                                         } else {
                                                                             if (CRM_Utils_Array::value(0, $type) == 'im') {
                                                                                 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
                                                                             }
                                                                         }
                                                                     }
                                                                     $headerRows[] = $relName . '-' . $hdr;
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     } else {
                                         $headerRows[] = $field;
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             //build row values (data)
             if (property_exists($dao, $field)) {
                 $fieldValue = $dao->{$field};
                 // to get phone type from phone type id
                 if ($field == 'phone_type_id') {
                     $fieldValue = $phoneTypes[$fieldValue];
                 } else {
                     if ($field == 'provider_id') {
                         $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
                     }
                 }
             } else {
                 $fieldValue = '';
             }
             if ($field == 'id') {
                 $row[$field] = $dao->contact_id;
             } else {
                 if ($field == 'pledge_balance_amount') {
                     //special case for calculated field
                     $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid;
                 } else {
                     if ($field == 'pledge_next_pay_amount') {
                         //special case for calculated field
                         $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount;
                     } else {
                         if (is_array($value) && $field == 'location') {
                             // fix header for location type case
                             foreach ($value as $ltype => $val) {
                                 foreach (array_keys($val) as $fld) {
                                     $type = explode('-', $fld);
                                     $fldValue = "{$ltype}-" . $type[0];
                                     if (CRM_Utils_Array::value(1, $type)) {
                                         $fldValue .= "-" . $type[1];
                                     }
                                     $row[$fldValue] = $dao->{$fldValue};
                                 }
                             }
                         } else {
                             if (array_key_exists($field, $contactRelationshipTypes)) {
                                 $relDAO = $allRelContactArray[$field][$dao->contact_id];
                                 foreach ($value as $relationField => $relationValue) {
                                     if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
                                         $fieldValue = $relDAO->{$relationField};
                                         if ($relationField == 'phone_type_id') {
                                             $fieldValue = $phoneTypes[$relationValue];
                                         } else {
                                             if ($relationField == 'provider_id') {
                                                 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
                                             }
                                         }
                                     } else {
                                         $fieldValue = '';
                                     }
                                     if ($relationField == 'id') {
                                         $row[$field . $relationField] = $relDAO->contact_id;
                                     } else {
                                         if (is_array($relationValue) && $relationField == 'location') {
                                             foreach ($relationValue as $ltype => $val) {
                                                 foreach (array_keys($val) as $fld) {
                                                     $type = explode('-', $fld);
                                                     $fldValue = "{$ltype}-" . $type[0];
                                                     if (CRM_Utils_Array::value(1, $type)) {
                                                         $fldValue .= "-" . $type[1];
                                                     }
                                                     $row[$field . $fldValue] = $relDAO->{$fldValue};
                                                 }
                                             }
                                         } else {
                                             if (isset($fieldValue) && $fieldValue != '') {
                                                 //check for custom data
                                                 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
                                                     $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $relationQuery[$field]->_options);
                                                 } else {
                                                     if (in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                         //special case for greeting replacement
                                                         $fldValue = "{$relationField}_display";
                                                         $row[$field . $relationField] = $relDAO->{$fldValue};
                                                     } else {
                                                         //normal relationship fields
                                                         $row[$field . $relationField] = $fieldValue;
                                                     }
                                                 }
                                             } else {
                                                 // if relation field is empty or null
                                                 $row[$field . $relationField] = '';
                                             }
                                         }
                                     }
                                 }
                             } else {
                                 if (isset($fieldValue) && $fieldValue != '') {
                                     //check for custom data
                                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
                                         $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
                                     } else {
                                         if (array_key_exists($field, $multipleSelectFields)) {
                                             //option group fixes
                                             $paramsNew = array($field => $fieldValue);
                                             if ($field == 'test_tutoring') {
                                                 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
                                             } else {
                                                 if (substr($field, 0, 4) == 'cmr_') {
                                                     //for  readers group
                                                     $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
                                                 } else {
                                                     $name = array($field => array('newName' => $field, 'groupName' => $field));
                                                 }
                                             }
                                             CRM_Core_OptionGroup::lookupValues($paramsNew, $name, false);
                                             $row[$field] = $paramsNew[$field];
                                         } else {
                                             if (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) {
                                                 //special case for greeting replacement
                                                 $fldValue = "{$field}_display";
                                                 $row[$field] = $dao->{$fldValue};
                                             } else {
                                                 //normal fields
                                                 $row[$field] = $fieldValue;
                                             }
                                         }
                                     }
                                 } else {
                                     // if field is empty or null
                                     $row[$field] = '';
                                 }
                             }
                         }
                     }
                 }
             }
         }
         //build header only once
         $setHeader = false;
         // add payment headers if required
         if ($addPaymentHeader && $paymentFields) {
             $headerRows = array_merge($headerRows, $paymentHeaders);
             $addPaymentHeader = false;
         }
         // add payment related information
         if ($paymentFields && isset($paymentDetails[$row[$paymentTableId]])) {
             $row = array_merge($row, $paymentDetails[$row[$paymentTableId]]);
         }
         //remove organization name for individuals if it is set for current employer
         if (CRM_Utils_Array::value('contact_type', $row) && $row['contact_type'] == 'Individual') {
             $row['organization_name'] = '';
         }
         // CRM-3157: localise the output
         // FIXME: we should move this to multilingual stack some day
         require_once 'CRM/Core/I18n.php';
         $i18n =& CRM_Core_I18n::singleton();
         $translatable = array('preferred_communication_method', 'preferred_mail_format', 'gender', 'state_province', 'country', 'world_region');
         foreach ($translatable as $column) {
             if (isset($row[$column]) and $row[$column]) {
                 $row[$column] = $i18n->translate($row[$column]);
             }
         }
         // add component info
         $componentDetails[] = $row;
     }
     require_once 'CRM/Core/Report/Excel.php';
     CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName('csv', $exportMode), $headerRows, $componentDetails);
     exit;
 }
Example #18
0
 /**
  * Get all the phone numbers for a specified location_block id, with the primary phone being first
  *
  * @param array $entityElements the array containing entity_id and
  * entity_table name
  *
  * @return array  the array of phone ids which are potential numbers
  * @access public
  * @static
  */
 static function allEntityPhones($entityElements, $type = null)
 {
     if (empty($entityElements)) {
         return null;
     }
     $cond = null;
     if ($type) {
         require_once 'CRM/Core/PseudoConstant.php';
         $phoneTypeId = array_search($type, CRM_Core_PseudoConstant::phoneType());
         if ($phoneTypeId) {
             $cond = " AND civicrm_phone.phone_type_id = {$phoneTypeId}";
         }
     }
     $entityId = $entityElements['entity_id'];
     $entityTable = $entityElements['entity_table'];
     $sql = " SELECT phone, ltype.name as locationType, ph.is_primary as is_primary,\n     ph.id as phone_id, ph.location_type_id as locationTypeId\nFROM civicrm_loc_block loc, civicrm_phone ph, civicrm_location_type ltype, {$entityTable} ev\nWHERE ev.id = %1\nAND   loc.id = ev.loc_block_id\nAND   ph.id IN (loc.phone_id, loc.phone_2_id)\nAND   ltype.id = ph.location_type_id\nORDER BY ph.is_primary DESC, phone_id ASC ";
     $params = array(1 => array($entityId, 'Integer'));
     $numbers = array();
     $dao =& CRM_Core_DAO::executeQuery($sql, $params);
     while ($dao->fetch()) {
         $numbers[$dao->phone_id] = array('locationType' => $dao->locationType, 'is_primary' => $dao->is_primary, 'id' => $dao->phone_id, 'phone' => $dao->phone, 'locationTypeId' => $dao->locationTypeId);
     }
     return $numbers;
 }
Example #19
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;
}
 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]);
 }