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