Merge pull request #4579 from colemanw/CRM_Utils_Array
[civicrm-core.git] / CRM / Core / BAO / Mapping.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 class CRM_Core_BAO_Mapping extends CRM_Core_DAO_Mapping {
36
37 /**
38 * class constructor
39 */
40 function __construct() {
41 parent::__construct();
42 }
43
44 /**
45 * Takes a bunch of params that are needed to match certain criteria and
46 * retrieves the relevant objects. Typically the valid params are only
47 * contact_id. We'll tweak this function to be more full featured over a period
48 * of time. This is the inverse function of create. It also stores all the retrieved
49 * values in the default array
50 *
51 * @param array $params (reference ) an assoc array of name/value pairs
52 * @param array $defaults (reference ) an assoc array to hold the flattened values
53 *
54 * @return object CRM_Core_DAO_Mapping object on success, otherwise null
55 * @access public
56 * @static
57 */
58 static function retrieve(&$params, &$defaults) {
59 $mapping = new CRM_Core_DAO_Mapping();
60 $mapping->copyValues($params);
61 if ($mapping->find(TRUE)) {
62 CRM_Core_DAO::storeValues($mapping, $defaults);
63 return $mapping;
64 }
65 return NULL;
66 }
67
68 /**
69 * Function to delete the mapping
70 *
71 * @param int $id mapping id
72 *
73 * @return boolean
74 * @access public
75 * @static
76 *
77 */
78 static function del($id) {
79 // delete from mapping_field table
80 $mappingField = new CRM_Core_DAO_MappingField();
81 $mappingField->mapping_id = $id;
82 $mappingField->find();
83 while ($mappingField->fetch()) {
84 $mappingField->delete();
85 }
86
87 // delete from mapping table
88 $mapping = new CRM_Core_DAO_Mapping();
89 $mapping->id = $id;
90 $mapping->delete();
91 CRM_Core_Session::setStatus(ts('Selected mapping has been deleted successfully.'), ts('Deleted'), 'success');
92
93 return TRUE;
94 }
95
96 /**
97 * takes an associative array and creates a contact object
98 *
99 * The function extract all the params it needs to initialize the create a
100 * contact object. the params array could contain additional unused name/value
101 * pairs
102 *
103 * @param array $params an array of name/value pairs
104 *
105 * @return object CRM_Core_DAO_Mapper object on success, otherwise null
106 * @access public
107 * @static
108 */
109 static function add($params) {
110 $mapping = new CRM_Core_DAO_Mapping();
111 $mapping->copyValues($params);
112 $mapping->save();
113
114 return $mapping;
115 }
116
117 /**
118 * function to get the list of mappings
119 *
120 * @params string $mappingTypeId mapping type id
121 *
122 * @param $mappingTypeId
123 *
124 * @return array $mapping array of mapping name
125 * @access public
126 * @static
127 */
128 static function getMappings($mappingTypeId) {
129 $mapping = array();
130 $mappingDAO = new CRM_Core_DAO_Mapping();
131 $mappingDAO->mapping_type_id = $mappingTypeId;
132 $mappingDAO->find();
133
134 while ($mappingDAO->fetch()) {
135 $mapping[$mappingDAO->id] = $mappingDAO->name;
136 }
137
138 return $mapping;
139 }
140
141 /**
142 * function to get the mapping fields
143 *
144 * @params int $mappingId mapping id
145 *
146 * @param $mappingId
147 *
148 * @return array $mappingFields array of mapping fields
149 * @access public
150 * @static
151 */
152 static function getMappingFields($mappingId) {
153 //mapping is to be loaded from database
154 $mapping = new CRM_Core_DAO_MappingField();
155 $mapping->mapping_id = $mappingId;
156 $mapping->orderBy('column_number');
157 $mapping->find();
158
159 $mappingName = $mappingLocation = $mappingContactType = $mappingPhoneType = array();
160 $mappingImProvider = $mappingRelation = $mappingOperator = $mappingValue = $mappingWebsiteType = array();
161 while ($mapping->fetch()) {
162 $mappingName[$mapping->grouping][$mapping->column_number] = $mapping->name;
163 $mappingContactType[$mapping->grouping][$mapping->column_number] = $mapping->contact_type;
164
165 if (!empty($mapping->location_type_id)) {
166 $mappingLocation[$mapping->grouping][$mapping->column_number] = $mapping->location_type_id;
167 }
168
169 if (!empty($mapping->phone_type_id)) {
170 $mappingPhoneType[$mapping->grouping][$mapping->column_number] = $mapping->phone_type_id;
171 }
172
173 // get IM service provider type id from mapping fields
174 if (!empty($mapping->im_provider_id)) {
175 $mappingImProvider[$mapping->grouping][$mapping->column_number] = $mapping->im_provider_id;
176 }
177
178 if (!empty($mapping->website_type_id)) {
179 $mappingWebsiteType[$mapping->grouping][$mapping->column_number] = $mapping->website_type_id;
180 }
181
182 if (!empty($mapping->relationship_type_id)) {
183 $mappingRelation[$mapping->grouping][$mapping->column_number] = "{$mapping->relationship_type_id}_{$mapping->relationship_direction}";
184 }
185
186 if (!empty($mapping->operator)) {
187 $mappingOperator[$mapping->grouping][$mapping->column_number] = $mapping->operator;
188 }
189
190 if (!empty($mapping->value)) {
191 $mappingValue[$mapping->grouping][$mapping->column_number] = $mapping->value;
192 }
193 }
194
195 return array(
196 $mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType,
197 $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue, $mappingWebsiteType,
198 );
199 }
200
201 /**
202 *function to check Duplicate Mapping Name
203 *
204 * @params $nameField string mapping Name
205 *
206 * @params $mapTypeId string mapping Type
207 *
208 * @param $nameField
209 * @param $mapTypeId
210 *
211 * @return boolean
212 */
213 static function checkMapping($nameField, $mapTypeId) {
214 $mapping = new CRM_Core_DAO_Mapping();
215 $mapping->name = $nameField;
216 $mapping->mapping_type_id = $mapTypeId;
217 if ($mapping->find(TRUE)) {
218 return TRUE;
219 }
220 else {
221 return FALSE;
222 }
223 }
224
225 /**
226 * Function returns associated array of elements, that will be passed for search
227 *
228 * @params int $smartGroupId smart group id
229 *
230 * @param $smartGroupId
231 *
232 * @return array $returnFields associated array of elements@static
233 * @public
234 */
235 static function getFormattedFields($smartGroupId) {
236 $returnFields = array();
237
238 //get the fields from mapping table
239 $dao = new CRM_Core_DAO_MappingField();
240 $dao->mapping_id = $smartGroupId;
241 $dao->find();
242 while ($dao->fetch()) {
243 $fldName = $dao->name;
244 if ($dao->location_type_id) {
245 $fldName .= "-{$dao->location_type_id}";
246 }
247 if ($dao->phone_type) {
248 $fldName .= "-{$dao->phone_type}";
249 }
250 $returnFields[$fldName]['value'] = $dao->value;
251 $returnFields[$fldName]['op'] = $dao->operator;
252 $returnFields[$fldName]['grouping'] = $dao->grouping;
253 }
254 return $returnFields;
255 }
256
257 /**
258 * Function to build the mapping form
259 *
260 * @params object $form form object
261 * @params string $mappingType mapping type (Export/Import/Search Builder)
262 * @params int $mappingId mapping id
263 * @params mixed $columnCount column count is int for and array for search builder
264 * @params int $blockCount block count (no of blocks shown)
265 *
266 * @param $form
267 * @param string $mappingType
268 * @param null $mappingId
269 * @param $columnNo
270 * @param int $blockCount
271 * @param null $exportMode
272 *
273 * @return void
274 * @access public
275 * @static
276 */
277 static function buildMappingForm(&$form, $mappingType = 'Export', $mappingId = NULL, $columnNo, $blockCount = 3, $exportMode = NULL) {
278 if ($mappingType == 'Export') {
279 $name = "Map";
280 $columnCount = array('1' => $columnNo);
281 }
282 elseif ($mappingType == 'Search Builder') {
283 $name = "Builder";
284 $columnCount = $columnNo;
285 }
286
287 //get the saved mapping details
288
289 if ($mappingType == 'Export') {
290 $form->applyFilter('saveMappingName', 'trim');
291
292 //to save the current mappings
293 if (!isset($mappingId)) {
294 $saveDetailsName = ts('Save this field mapping');
295 $form->add('text', 'saveMappingName', ts('Name'));
296 $form->add('text', 'saveMappingDesc', ts('Description'));
297 }
298 else {
299 $form->assign('loadedMapping', $mappingId);
300
301 $params = array('id' => $mappingId);
302 $temp = array();
303 $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
304
305 $form->assign('savedName', $mappingDetails->name);
306
307 $form->add('hidden', 'mappingId', $mappingId);
308
309 $form->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
310 $saveDetailsName = ts('Save as a new field mapping');
311 $form->add('text', 'saveMappingName', ts('Name'));
312 $form->add('text', 'saveMappingDesc', ts('Description'));
313 }
314
315 $form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
316 $form->addFormRule(array('CRM_Export_Form_Map', 'formRule'), $form->get('mappingTypeId'));
317 }
318 elseif ($mappingType == 'Search Builder') {
319 $form->addElement('submit', 'addBlock', ts('Also include contacts where'),
320 array('class' => 'submit-link')
321 );
322 }
323
324 $defaults = array();
325 $hasLocationTypes = array();
326 $hasRelationTypes = array();
327 $fields = array();
328
329 if ($mappingType == 'Export') {
330 $required = TRUE;
331 }
332 elseif ($mappingType == 'Search Builder') {
333 $required = FALSE;
334 }
335
336 $contactType = array('Individual', 'Household', 'Organization');
337 foreach ($contactType as $value) {
338 $contactFields = CRM_Contact_BAO_Contact::exportableFields($value, FALSE, $required);
339 $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook::singleton()->getFields());
340
341 // exclude the address options disabled in the Address Settings
342 $fields[$value] = CRM_Core_BAO_Address::validateAddressOptions($contactFields);
343 ksort($fields[$value]);
344 if ($mappingType == 'Export') {
345 $relationships = array();
346 $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $value);
347 asort($relationshipTypes);
348
349 foreach ($relationshipTypes as $key => $var) {
350 list($type) = explode('_', $key);
351
352 $relationships[$key]['title'] = $var;
353 $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
354 $relationships[$key]['export'] = TRUE;
355 $relationships[$key]['relationship_type_id'] = $type;
356 $relationships[$key]['related'] = TRUE;
357 $relationships[$key]['hasRelationType'] = 1;
358 }
359
360 if (!empty($relationships)) {
361 $fields[$value] = array_merge($fields[$value],
362 array('related' => array('title' => ts('- related contact info -'))),
363 $relationships
364 );
365 }
366 }
367 }
368
369 //get the current employer for mapping.
370 if ($required) {
371 $fields['Individual']['current_employer']['title'] = ts('Current Employer');
372 }
373
374 // add component fields
375 $compArray = array();
376
377 //we need to unset groups, tags, notes for component export
378 if ($exportMode != CRM_Export_Form_Select::CONTACT_EXPORT) {
379 foreach (array(
380 'groups', 'tags', 'notes') as $value) {
381 unset($fields['Individual'][$value]);
382 unset($fields['Household'][$value]);
383 unset($fields['Organization'][$value]);
384 }
385 }
386
387 if ($mappingType == 'Search Builder') {
388 //build the common contact fields array.
389 $fields['Contact'] = array();
390 foreach ($fields['Individual'] as $key => $value) {
391 if (!empty($fields['Household'][$key]) && !empty($fields['Organization'][$key])) {
392 $fields['Contact'][$key] = $value;
393 unset($fields['Organization'][$key],
394 $fields['Household'][$key],
395 $fields['Individual'][$key]);
396 }
397 }
398 if (array_key_exists('note', $fields['Contact'])) {
399 $noteTitle = $fields['Contact']['note']['title'];
400 $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
401 $fields['Contact']['note_body'] = array( 'title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body' );
402 $fields['Contact']['note_subject'] = array( 'title' => $noteTitle . ': ' . ts('Subject Only'), 'name' => 'note_subject' );
403 }
404 }
405
406 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT)) {
407 if (CRM_Core_Permission::access('CiviContribute')) {
408 $fields['Contribution'] = CRM_Contribute_BAO_Contribution::exportableFields();
409 unset($fields['Contribution']['contribution_contact_id']);
410 unset($fields['Contribution']['contribution_status_id']);
411 $compArray['Contribution'] = ts('Contribution');
412 }
413 }
414
415 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT)) {
416 if (CRM_Core_Permission::access('CiviEvent')) {
417 $fields['Participant'] = CRM_Event_BAO_Participant::exportableFields();
418 //get the component payment fields
419 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
420 require_once 'CRM/Export/BAO/Export.php';
421 $componentPaymentFields = array();
422 foreach (CRM_Export_BAO_Export::componentPaymentFields() as $payField => $payTitle) {
423 $componentPaymentFields[$payField] = array('title' => $payTitle);
424 }
425 $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
426 }
427
428 unset($fields['Participant']['participant_contact_id']);
429 $compArray['Participant'] = ts('Participant');
430 }
431 }
432
433 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT)) {
434 if (CRM_Core_Permission::access('CiviMember')) {
435 $fields['Membership'] = CRM_Member_BAO_Membership::getMembershipFields($exportMode);
436 unset($fields['Membership']['membership_contact_id']);
437 $compArray['Membership'] = ts('Membership');
438 }
439 }
440
441 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT)) {
442 if (CRM_Core_Permission::access('CiviPledge')) {
443 $fields['Pledge'] = CRM_Pledge_BAO_Pledge::exportableFields();
444 unset($fields['Pledge']['pledge_contact_id']);
445 $compArray['Pledge'] = ts('Pledge');
446 }
447 }
448
449 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CASE_EXPORT)) {
450 if (CRM_Core_Permission::access('CiviCase')) {
451 $fields['Case'] = CRM_Case_BAO_Case::exportableFields();
452 $compArray['Case'] = ts('Case');
453
454 $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Case');
455 $compArray['Activity'] = ts('Case Activity');
456
457 unset($fields['Case']['case_contact_id']);
458 }
459 }
460 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT)) {
461 if (CRM_Core_Permission::access('CiviGrant')) {
462 $fields['Grant'] = CRM_Grant_BAO_Grant::exportableFields();
463 unset($fields['Grant']['grant_contact_id']);
464 if ($mappingType == 'Search Builder') {
465 unset($fields['Grant']['grant_type_id']);
466 }
467 $compArray['Grant'] = ts('Grant');
468 }
469 }
470
471 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT)) {
472 $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Activity');
473 $compArray['Activity'] = ts('Activity');
474 }
475
476 //Contact Sub Type For export
477 $contactSubTypes = array();
478 $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
479
480 foreach ($subTypes as $subType => $val) {
481 //adding subtype specific relationships CRM-5256
482 $csRelationships = array();
483
484 if ($mappingType == 'Export') {
485 $subTypeRelationshipTypes =
486 CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'],
487 FALSE, 'label', TRUE, $subType);
488
489 foreach ($subTypeRelationshipTypes as $key => $var) {
490 if (!array_key_exists($key, $fields[$val['parent']])) {
491 list($type) = explode('_', $key);
492
493 $csRelationships[$key]['title'] = $var;
494 $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
495 $csRelationships[$key]['export'] = TRUE;
496 $csRelationships[$key]['relationship_type_id'] = $type;
497 $csRelationships[$key]['related'] = TRUE;
498 $csRelationships[$key]['hasRelationType'] = 1;
499 }
500 }
501 }
502
503 $fields[$subType] = $fields[$val['parent']] + $csRelationships;
504
505 //custom fields for sub type
506 $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($subType);
507 $fields[$subType] += $subTypeFields;
508
509 if (!empty($subTypeFields) || !empty($csRelationships)) {
510 $contactSubTypes[$subType] = $val['label'];
511 }
512 }
513
514 unset($subTypes);
515
516 foreach ($fields as $key => $value) {
517
518 foreach ($value as $key1 => $value1) {
519 //CRM-2676, replacing the conflict for same custom field name from different custom group.
520 $customGroupName = self::getCustomGroupName($key1);
521
522 if ($customGroupName) {
523 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
524 }
525 else {
526 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
527 }
528 if (isset($value1['hasLocationType'])) {
529 $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
530 }
531
532 if (isset($value1['hasRelationType'])) {
533 $hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
534 unset($relatedMapperFields[$key][$key1]);
535 }
536 }
537
538 if (array_key_exists('related', $relatedMapperFields[$key])) {
539 unset($relatedMapperFields[$key]['related']);
540 }
541 }
542
543 $mapperKeys = array_keys($mapperFields);
544
545 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
546
547 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
548
549 /* FIXME: dirty hack to make the default option show up first. This
550 * avoids a mozilla browser bug with defaults on dynamically constructed
551 * selector widgets. */
552
553
554 if ($defaultLocationType) {
555 $defaultLocation = $locationTypes[$defaultLocationType->id];
556 unset($locationTypes[$defaultLocationType->id]);
557 $locationTypes = array(
558 $defaultLocationType->id => $defaultLocation) + $locationTypes;
559 }
560
561 $locationTypes = array(
562 ' ' => ts('Primary')) + $locationTypes;
563
564 // since we need a hierarchical list to display contact types & subtypes,
565 // this is what we going to display in first selector
566 $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE);
567 if ($mappingType == 'Search Builder') {
568 $contactTypes = array('Contact' => ts('Contacts')) + $contactTypes;
569 }
570
571 $sel1 =
572 array('' => ts('- select record type -')) + $contactTypes + $compArray;
573
574 foreach ($sel1 as $key => $sel) {
575 if ($key) {
576 // sort everything BUT the contactType which is sorted seperately by
577 // an initial commit of CRM-13278 (check ksort above)
578 if (!in_array($key, $contactType)) {
579 asort($mapperFields[$key]);
580 }
581 $sel2[$key] = array('' => ts('- select field -')) + $mapperFields[$key];
582 }
583 }
584
585 $sel3[''] = NULL;
586 $sel5[''] = NULL;
587 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
588 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
589 asort($phoneTypes);
590
591 foreach ($sel1 as $k => $sel) {
592 if ($k) {
593 foreach ($locationTypes as $key => $value) {
594 if (trim($key) != '') {
595 $sel4[$k]['phone'][$key] = &$phoneTypes;
596 $sel4[$k]['im'][$key] = &$imProviders;
597 }
598 }
599 }
600 }
601
602 foreach ($sel1 as $k => $sel) {
603 if ($k) {
604 foreach ($mapperFields[$k] as $key => $value) {
605 if (isset($hasLocationTypes[$k][$key])) {
606 $sel3[$k][$key] = $locationTypes;
607 }
608 else {
609 $sel3[$key] = NULL;
610 }
611 }
612 }
613 }
614
615 //Array for core fields and relationship custom data
616
617 $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
618
619 if ($mappingType == 'Export') {
620 foreach ($sel1 as $k => $sel) {
621 if ($k) {
622 foreach ($mapperFields[$k] as $field => $dontCare) {
623 if (isset($hasRelationTypes[$k][$field])) {
624 list($id, $first, $second) = explode('_', $field);
625 // FIX ME: For now let's not expose custom data related to relationship
626 $relationshipCustomFields = array();
627 //$relationshipCustomFields = self::getRelationTypeCustomGroupData( $id );
628 //asort( $relationshipCustomFields ) ;
629
630 $relationshipType = new CRM_Contact_BAO_RelationshipType();
631 $relationshipType->id = $id;
632 if ($relationshipType->find(TRUE)) {
633 $direction = "contact_sub_type_$second";
634 if (isset($relationshipType->$direction)) {
635 $relatedFields = array_merge((array)$relatedMapperFields[$relationshipType->$direction], (array)$relationshipCustomFields);
636 }
637 else {
638 $target_type = 'contact_type_' . $second;
639 $relatedFields = array_merge((array)$relatedMapperFields[$relationshipType->$target_type], (array)$relationshipCustomFields);
640 }
641 }
642 $relationshipType->free();
643 asort($relatedFields);
644 $sel5[$k][$field] = $relatedFields;
645 }
646 }
647 }
648 }
649
650 //Location Type for relationship fields
651
652 foreach ($sel5 as $k => $v) {
653 if ($v) {
654 foreach ($v as $rel => $fields) {
655 foreach ($fields as $field => $fieldLabel) {
656 if (isset($hasLocationTypes[$k][$field])) {
657 $sel6[$k][$rel][$field] = $locationTypes;
658 }
659 }
660 }
661 }
662 }
663
664 //PhoneTypes for relationship fields
665 $sel7[''] = NULL;
666 foreach ($sel6 as $k => $rel) {
667 if ($k) {
668 foreach ($rel as $phonekey => $phonevalue) {
669 foreach ($locationTypes as $locType => $loc) {
670 if (trim($locType) != '') {
671 $sel7[$k][$phonekey]['phone'][$locType] = &$phoneTypes;
672 $sel7[$k][$phonekey]['im'][$locType] = &$imProviders;
673 }
674 }
675 }
676 }
677 }
678 }
679
680 //special fields that have location, hack for primary location
681 $specialFields = array(
682 'street_address', 'supplemental_address_1', 'supplemental_address_2',
683 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
684 'state_province', 'country', 'phone', 'email', 'im',
685 );
686
687 if (isset($mappingId)) {
688 $colCnt = 0;
689
690 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
691 $mappingRelation, $mappingOperator, $mappingValue
692 ) = CRM_Core_BAO_Mapping::getMappingFields($mappingId);
693
694 $blkCnt = count($mappingName);
695 if ($blkCnt >= $blockCount) {
696 $blockCount = $blkCnt + 1;
697 }
698 for ($x = 1; $x < $blockCount; $x++) {
699 if (isset($mappingName[$x])) {
700 $colCnt = count($mappingName[$x]);
701 if ($colCnt >= $columnCount[$x]) {
702 $columnCount[$x] = $colCnt;
703 }
704 }
705 }
706 }
707
708 $form->_blockCount = $blockCount;
709 $form->_columnCount = $columnCount;
710
711 $form->set('blockCount', $form->_blockCount);
712 $form->set('columnCount', $form->_columnCount);
713
714 $defaults = $noneArray = $nullArray = array();
715
716 //used to warn for mismatch column count or mismatch mapping
717 $warning = 0;
718 for ($x = 1; $x < $blockCount; $x++) {
719
720 for ($i = 0; $i < $columnCount[$x]; $i++) {
721
722 $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
723 $jsSet = FALSE;
724
725 if (isset($mappingId)) {
726 $locationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0;
727 if (isset($mappingName[$x][$i])) {
728 if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
729
730 if (isset($mappingRelation[$x][$i])) {
731
732 $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$x][$i]));
733 $relLocationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0;
734 if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
735 $relLocationId = " ";
736 }
737
738 $relPhoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
739
740 $defaults["mapper[$x][$i]"] = array(
741 $mappingContactType[$x][$i],
742 $mappingRelation[$x][$i],
743 $locationId,
744 $phoneType,
745 $mappingName[$x][$i],
746 $relLocationId,
747 $relPhoneType,
748 );
749
750 if (!$locationId) {
751 $noneArray[] = array($x, $i, 2);
752 }
753 if (!$phoneType && !$imProvider) {
754 $noneArray[] = array($x, $i, 3);
755 }
756 if (!$mappingName[$x][$i]) {
757 $noneArray[] = array($x, $i, 4);
758 }
759 if (!$relLocationId) {
760 $noneArray[] = array($x, $i, 5);
761 }
762 if (!$relPhoneType) {
763 $noneArray[] = array($x, $i, 6);
764 }
765 $noneArray[] = array($x, $i, 2);
766 }
767 else {
768 $phoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
769 $imProvider = isset($mappingImProvider[$x][$i]) ? $mappingImProvider[$x][$i] : NULL;
770 if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
771 $locationId = " ";
772 }
773
774 $defaults["mapper[$x][$i]"] = array(
775 $mappingContactType[$x][$i],
776 $mappingName[$x][$i],
777 $locationId,
778 $phoneType,
779 );
780 if (!$mappingName[$x][$i]) {
781 $noneArray[] = array($x, $i, 1);
782 }
783 if (!$locationId) {
784 $noneArray[] = array($x, $i, 2);
785 }
786 if (!$phoneType && !$imProvider) {
787 $noneArray[] = array($x, $i, 3);
788 }
789
790 $noneArray[] = array($x, $i, 4);
791 $noneArray[] = array($x, $i, 5);
792 $noneArray[] = array($x, $i, 6);
793 }
794
795 $jsSet = TRUE;
796
797 if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingOperator))) {
798 $defaults["operator[$x][$i]"] = CRM_Utils_Array::value($i, $mappingOperator[$x]);
799 }
800
801 if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingValue))) {
802 $defaults["value[$x][$i]"] = CRM_Utils_Array::value($i, $mappingValue[$x]);
803 }
804 }
805 }
806 }
807 //Fix for Search Builder
808 if ($mappingType == 'Export') {
809 $j = 7;
810 }
811 else {
812 $j = 4;
813 }
814
815 $formValues = $form->exportValues();
816 if (!$jsSet) {
817 if (empty($formValues)) {
818 // Incremented length for third select box(relationship type)
819 for ($k = 1; $k < $j; $k++) {
820 $noneArray[] = array($x, $i, $k);
821 }
822 }
823 else {
824 if (!empty($formValues['mapper'][$x])) {
825 foreach ($formValues['mapper'][$x] as $value) {
826 for ($k = 1; $k < $j; $k++) {
827 if (!isset($formValues['mapper'][$x][$i][$k]) ||
828 (!$formValues['mapper'][$x][$i][$k])
829 ) {
830 $noneArray[] = array($x, $i, $k);
831 }
832 else {
833 $nullArray[] = array($x, $i, $k);
834 }
835 }
836 }
837 }
838 else {
839 for ($k = 1; $k < $j; $k++) {
840 $noneArray[] = array($x, $i, $k);
841 }
842 }
843 }
844 }
845 //Fix for Search Builder
846 if ($mappingType == 'Export') {
847 if (!isset($mappingId) || $i >= count(reset($mappingName))) {
848 if (isset($formValues['mapper']) &&
849 isset($formValues['mapper'][$x][$i][1]) &&
850 array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)
851 ) {
852 $sel->setOptions(array($sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4));
853 }
854 else {
855 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
856 }
857 }
858 else {
859 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
860 }
861 }
862 else {
863 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
864 }
865
866 if ($mappingType == 'Search Builder') {
867 //CRM -2292, restricted array set
868 $operatorArray = array('' => ts('-operator-')) + CRM_Core_SelectValues::getSearchBuilderOperators();
869
870 $form->add('select', "operator[$x][$i]", '', $operatorArray);
871 $form->add('text', "value[$x][$i]", '');
872 }
873 }
874 //end of columnCnt for
875 if ($mappingType == 'Search Builder') {
876 $title = ts('Another search field');
877 }
878 else {
879 $title = ts('Select more fields');
880 }
881
882 $form->addElement('submit', "addMore[$x]", $title, array('class' => 'submit-link'));
883 }
884 //end of block for
885
886 $js = "<script type='text/javascript'>\n";
887 $formName = "document.{$name}";
888 if (!empty($nullArray)) {
889 $js .= "var nullArray = [";
890 $elements = array();
891 $seen = array();
892 foreach ($nullArray as $element) {
893 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
894 if (!isset($seen[$key])) {
895 $elements[] = "[$key]";
896 $seen[$key] = 1;
897 }
898 }
899 $js .= implode(', ', $elements);
900 $js .= "]";
901 $js .= "
902 for(var i=0;i<nullArray.length;i++) {
903 if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
904 {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
905 }
906 }
907 ";
908 }
909 if (!empty($noneArray)) {
910 $js .= "var noneArray = [";
911 $elements = array();
912 $seen = array();
913 foreach ($noneArray as $element) {
914 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
915 if (!isset($seen[$key])) {
916 $elements[] = "[$key]";
917 $seen[$key] = 1;
918 }
919 }
920 $js .= implode(', ', $elements);
921 $js .= "]";
922 $js .= "
923 for(var i=0;i<noneArray.length;i++) {
924 if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
925 {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
926 }
927 }
928 ";
929 }
930 $js .= "</script>\n";
931
932 $form->assign('initHideBoxes', $js);
933 $form->assign('columnCount', $columnCount);
934 $form->assign('blockCount', $blockCount);
935 $form->setDefaults($defaults);
936
937 $form->setDefaultAction('refresh');
938 }
939
940 /* Function returns all custom fields with group title and
941 * field label
942 * @relationshipTypeId related relationship type id
943 * @return $groupTitle all custom field titles
944 */
945 /**
946 * @param $relationshipTypeId
947 *
948 * @return array
949 */
950 function getRelationTypeCustomGroupData($relationshipTypeId) {
951
952 $customFields = CRM_Core_BAO_CustomField::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
953 $groupTitle = array();
954 foreach ($customFields as $krelation => $vrelation) {
955 $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
956 }
957 return $groupTitle;
958 }
959
960
961 /**
962 * Function returns all Custom group Names
963 *
964 * @param related $customfieldId
965 *
966 * @internal param \related $customfieldId custom field id
967 * @return null|string $customGroupName all custom group names@static
968 */
969 static function getCustomGroupName($customfieldId) {
970 if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($customfieldId)) {
971 $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
972 $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
973
974 if (strlen($customGroupName) > 13) {
975 $customGroupName = substr($customGroupName, 0, 10) . '...';
976 }
977
978 return $customGroupName;
979 }
980 }
981
982 /**
983 * Function returns associated array of elements, that will be passed for search
984 *
985 * @params array $params associated array of submitted values
986 * @params boolean $row row no of the fields
987 *
988 * @param $params
989 * @param bool $row
990 *
991 * @return array $returnFields formatted associated array of elements@static
992 * @public
993 */
994 static function formattedFields(&$params, $row = FALSE) {
995 $fields = array();
996
997 if (empty($params) || !isset($params['mapper'])) {
998 return $fields;
999 }
1000
1001 $types = array('Individual', 'Organization', 'Household');
1002 foreach ($params['mapper'] as $key => $value) {
1003 $contactType = NULL;
1004 foreach ($value as $k => $v) {
1005 if (in_array($v[0], $types)) {
1006 if ($contactType && $contactType != $v[0]) {
1007 CRM_Core_Error::fatal(ts("Cannot have two clauses with different types: %1, %2",
1008 array(1 => $contactType, 2 => $v[0])
1009 ));
1010 }
1011 $contactType = $v[0];
1012 }
1013 if (!empty($v['1'])) {
1014 $fldName = $v[1];
1015 $v2 = CRM_Utils_Array::value('2', $v);
1016 if ($v2 && trim($v2)) {
1017 $fldName .= "-{$v[2]}";
1018 }
1019
1020 $v3 = CRM_Utils_Array::value('3', $v);
1021 if ($v3 && trim($v3)) {
1022 $fldName .= "-{$v[3]}";
1023 }
1024
1025 $value = $params['value'][$key][$k];
1026 if ($fldName == 'group' || $fldName == 'tag') {
1027 $value = trim($value);
1028 $value = str_replace('(', '', $value);
1029 $value = str_replace(')', '', $value);
1030
1031 $v = explode(',', $value);
1032 $value = array();
1033 foreach ($v as $i) {
1034 $value[$i] = 1;
1035 }
1036 }
1037
1038 if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
1039 && substr($fldName, 0, 10) != 'financial_') {
1040 if (substr($fldName, 0, 13) != 'contribution_') {
1041 $fldName = 'contribution_' . $fldName;
1042 }
1043 }
1044
1045 // CRM-14563: we store checkbox, multi-select and adv-multi select custom field using separator, hence it
1046 // needs special handling.
1047 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($v[1])) {
1048 $isCustomField = TRUE;
1049 $customFieldType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'html_type');
1050 $specialHTMLType = array(
1051 'CheckBox',
1052 'Multi-Select',
1053 'AdvMulti-Select',
1054 'Multi-Select State/Province',
1055 'Multi-Select Country'
1056 );
1057
1058 // override the operator to handle separator ( note: this might have some performance issues )
1059 if (in_array($customFieldType, $specialHTMLType)) {
1060 // FIX ME: != and few other operators are not handled
1061 $specialOperators = array('=', 'IN', 'LIKE');
1062
1063 if (in_array($params['operator'][$key][$k], $specialOperators)) {
1064 $params['operator'][$key][$k] = 'RLIKE';
1065 }
1066 }
1067 }
1068
1069 // CRM-14983: verify if values are comma separated convert to array
1070 if (!is_array($value) && (strpos($value,',') !== false || strstr($value, '(')) && empty($isCustomField) && $params['operator'][$key][$k] == 'IN') {
1071 preg_match('#\((.*?)\)#', $value, $match);
1072 $tmpArray = explode(',', $match[1]);
1073 $value = array_combine(array_values($tmpArray),array_values($tmpArray));
1074 }
1075
1076 if ($row) {
1077 $fields[] = array(
1078 $fldName,
1079 $params['operator'][$key][$k],
1080 $value,
1081 $key,
1082 $k,
1083 );
1084 }
1085 else {
1086 $fields[] = array(
1087 $fldName,
1088 $params['operator'][$key][$k],
1089 $value,
1090 $key,
1091 0,
1092 );
1093 }
1094 }
1095 }
1096 if ($contactType) {
1097 $fields[] = array(
1098 'contact_type',
1099 '=',
1100 $contactType,
1101 $key,
1102 0,
1103 );
1104 }
1105 }
1106
1107 //add sortByCharacter values
1108 if (isset($params['sortByCharacter'])) {
1109 $fields[] = array(
1110 'sortByCharacter',
1111 '=',
1112 $params['sortByCharacter'],
1113 0,
1114 0,
1115 );
1116 }
1117
1118
1119 return $fields;
1120 }
1121
1122 /**
1123 * @param $params
1124 *
1125 * @return array
1126 */
1127 static function &returnProperties(&$params) {
1128 $fields = array(
1129 'contact_type' => 1,
1130 'contact_sub_type' => 1,
1131 'sort_name' => 1,
1132 );
1133
1134 if (empty($params) || empty($params['mapper'])) {
1135 return $fields;
1136 }
1137
1138 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
1139 foreach ($params['mapper'] as $key => $value) {
1140 foreach ($value as $k => $v) {
1141 if (isset($v[1])) {
1142 if ($v[1] == 'groups' || $v[1] == 'tags') {
1143 continue;
1144 }
1145
1146 if (isset($v[2]) && is_numeric($v[2])) {
1147 if (!array_key_exists('location', $fields)) {
1148 $fields['location'] = array();
1149 }
1150
1151 // make sure that we have a location fields and a location type for this
1152 $locationName = $locationTypes[$v[2]];
1153 if (!array_key_exists($locationName, $fields['location'])) {
1154 $fields['location'][$locationName] = array();
1155 $fields['location'][$locationName]['location_type'] = $v[2];
1156 }
1157
1158 if ($v[1] == 'phone' || $v[1] == 'email' || $v[1] == 'im') {
1159 // phone type handling
1160 if (isset($v[3])) {
1161 $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
1162 }
1163 else {
1164 $fields['location'][$locationName][$v[1]] = 1;
1165 }
1166 }
1167 else {
1168 $fields['location'][$locationName][$v[1]] = 1;
1169 }
1170 }
1171 else {
1172 $fields[$v[1]] = 1;
1173 }
1174 }
1175 }
1176 }
1177
1178 return $fields;
1179 }
1180
1181 /**
1182 * save the mapping field info for search builder / export given the formvalues
1183 *
1184 * @param array $params asscociated array of formvalues
1185 * @param int $mappingId mapping id
1186 *
1187 * @return null
1188 * @static
1189 * @access public
1190 */
1191 static function saveMappingFields(&$params, $mappingId) {
1192 //delete mapping fields records for exixting mapping
1193 $mappingFields = new CRM_Core_DAO_MappingField();
1194 $mappingFields->mapping_id = $mappingId;
1195 $mappingFields->delete();
1196
1197 if (empty($params['mapper'])) {
1198 return;
1199 }
1200
1201 //save record in mapping field table
1202 foreach ($params['mapper'] as $key => $value) {
1203 $colCnt = 0;
1204 foreach ($value as $k => $v) {
1205
1206 if (!empty($v['1'])) {
1207 $saveMappingFields = new CRM_Core_DAO_MappingField();
1208
1209 $saveMappingFields->mapping_id = $mappingId;
1210 $saveMappingFields->name = CRM_Utils_Array::value('1', $v);
1211 $saveMappingFields->contact_type = CRM_Utils_Array::value('0', $v);
1212 $locationId = CRM_Utils_Array::value('2', $v);
1213 $saveMappingFields->location_type_id = is_numeric($locationId) ? $locationId : NULL;
1214
1215 if ($v[1] == 'phone') {
1216 $saveMappingFields->phone_type_id = CRM_Utils_Array::value('3', $v);
1217 }
1218 elseif ($v[1] == 'im') {
1219 $saveMappingFields->im_provider_id = CRM_Utils_Array::value('3', $v);
1220 }
1221
1222 if (!empty($params['operator'])) {
1223 $saveMappingFields->operator = CRM_Utils_Array::value($k, $params['operator'][$key]);
1224 }
1225 if (!empty($params['value'])) {
1226 $saveMappingFields->value = CRM_Utils_Array::value($k, $params['value'][$key]);
1227 }
1228 // Handle mapping for 'related contact' fields
1229 if (count(explode('_', CRM_Utils_Array::value('1', $v))) > 2) {
1230 list($id, $first, $second) = explode('_', CRM_Utils_Array::value('1', $v));
1231 if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {
1232
1233 if (!empty($v['2'])) {
1234 $saveMappingFields->name = CRM_Utils_Array::value('2', $v);
1235 }
1236 elseif (!empty($v['4'])) {
1237 $saveMappingFields->name = CRM_Utils_Array::value('4', $v);
1238 }
1239
1240 if (is_numeric(CRM_Utils_Array::value('3', $v))) {
1241 $locationTypeid = CRM_Utils_Array::value('3', $v);
1242 }
1243 elseif (is_numeric(CRM_Utils_Array::value('5', $v))) {
1244 $locationTypeid = CRM_Utils_Array::value('5', $v);
1245 }
1246
1247 if (is_numeric(CRM_Utils_Array::value('4', $v))) {
1248 $phoneTypeid = CRM_Utils_Array::value('4', $v);
1249 }
1250 elseif (is_numeric(CRM_Utils_Array::value('6', $v))) {
1251 $phoneTypeid = CRM_Utils_Array::value('6', $v);
1252 }
1253
1254 $saveMappingFields->location_type_id = is_numeric($locationTypeid) ? $locationTypeid : NULL;
1255 $saveMappingFields->phone_type_id = is_numeric($phoneTypeid) ? $phoneTypeid : NULL;
1256 $saveMappingFields->relationship_type_id = $id;
1257 $saveMappingFields->relationship_direction = "{$first}_{$second}";
1258 }
1259 }
1260
1261 $saveMappingFields->grouping = $key;
1262 $saveMappingFields->column_number = $colCnt;
1263 $saveMappingFields->save();
1264 $colCnt++;
1265 $locationTypeid = $phoneTypeid = NULL;
1266 }
1267 }
1268 }
1269 }
1270 }
1271