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