Merge pull request #9566 from totten/master-19690-layout
[civicrm-core.git] / CRM / Core / BAO / Mapping.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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, TRUE);
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 $relatedFields = array();
594 $relationshipType = new CRM_Contact_BAO_RelationshipType();
595 $relationshipType->id = $id;
596 if ($relationshipType->find(TRUE)) {
597 $direction = "contact_sub_type_$second";
598 $target_type = 'contact_type_' . $second;
599 if (isset($relationshipType->$direction)) {
600 $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->$direction], (array) $relationshipCustomFields);
601 }
602 elseif (isset($relationshipType->$target_type)) {
603 $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->$target_type], (array) $relationshipCustomFields);
604 }
605 }
606 $relationshipType->free();
607 asort($relatedFields);
608 $sel5[$k][$field] = $relatedFields;
609 }
610 }
611 }
612 }
613
614 //Location Type for relationship fields
615 foreach ($sel5 as $k => $v) {
616 if ($v) {
617 foreach ($v as $rel => $fields) {
618 foreach ($fields as $field => $fieldLabel) {
619 if (isset($hasLocationTypes[$k][$field])) {
620 $sel6[$k][$rel][$field] = $locationTypes;
621 }
622 }
623 }
624 }
625 }
626
627 //PhoneTypes for relationship fields
628 $sel7[''] = NULL;
629 foreach ($sel6 as $k => $rel) {
630 if ($k) {
631 foreach ($rel as $phonekey => $phonevalue) {
632 foreach ($locationTypes as $locType => $loc) {
633 if (trim($locType) != '') {
634 $sel7[$k][$phonekey]['phone'][$locType] = &$phoneTypes;
635 $sel7[$k][$phonekey]['im'][$locType] = &$imProviders;
636 }
637 }
638 }
639 }
640 }
641 }
642
643 //special fields that have location, hack for primary location
644 $specialFields = array(
645 'street_address',
646 'supplemental_address_1',
647 'supplemental_address_2',
648 'city',
649 'postal_code',
650 'postal_code_suffix',
651 'geo_code_1',
652 'geo_code_2',
653 'state_province',
654 'country',
655 'phone',
656 'email',
657 'im',
658 );
659
660 if (isset($mappingId)) {
661 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
662 $mappingRelation, $mappingOperator, $mappingValue
663 ) = CRM_Core_BAO_Mapping::getMappingFields($mappingId);
664
665 $blkCnt = count($mappingName);
666 if ($blkCnt >= $blockCount) {
667 $blockCount = $blkCnt + 1;
668 }
669 for ($x = 1; $x < $blockCount; $x++) {
670 if (isset($mappingName[$x])) {
671 $colCnt = count($mappingName[$x]);
672 if ($colCnt >= $columnCount[$x]) {
673 $columnCount[$x] = $colCnt;
674 }
675 }
676 }
677 }
678
679 $form->_blockCount = $blockCount;
680 $form->_columnCount = $columnCount;
681
682 $form->set('blockCount', $form->_blockCount);
683 $form->set('columnCount', $form->_columnCount);
684
685 $defaults = $noneArray = $nullArray = array();
686
687 for ($x = 1; $x < $blockCount; $x++) {
688
689 for ($i = 0; $i < $columnCount[$x]; $i++) {
690
691 $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
692 $jsSet = FALSE;
693
694 if (isset($mappingId)) {
695 $locationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0;
696 if (isset($mappingName[$x][$i])) {
697 if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
698
699 if (isset($mappingRelation[$x][$i])) {
700 $relLocationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0;
701 if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
702 $relLocationId = " ";
703 }
704
705 $relPhoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
706
707 $defaults["mapper[$x][$i]"] = array(
708 $mappingContactType[$x][$i],
709 $mappingRelation[$x][$i],
710 $locationId,
711 $phoneType,
712 $mappingName[$x][$i],
713 $relLocationId,
714 $relPhoneType,
715 );
716
717 if (!$locationId) {
718 $noneArray[] = array($x, $i, 2);
719 }
720 if (!$phoneType && !$imProvider) {
721 $noneArray[] = array($x, $i, 3);
722 }
723 if (!$mappingName[$x][$i]) {
724 $noneArray[] = array($x, $i, 4);
725 }
726 if (!$relLocationId) {
727 $noneArray[] = array($x, $i, 5);
728 }
729 if (!$relPhoneType) {
730 $noneArray[] = array($x, $i, 6);
731 }
732 $noneArray[] = array($x, $i, 2);
733 }
734 else {
735 $phoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
736 $imProvider = isset($mappingImProvider[$x][$i]) ? $mappingImProvider[$x][$i] : NULL;
737 if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
738 $locationId = " ";
739 }
740
741 $defaults["mapper[$x][$i]"] = array(
742 $mappingContactType[$x][$i],
743 $mappingName[$x][$i],
744 $locationId,
745 $phoneType,
746 );
747 if (!$mappingName[$x][$i]) {
748 $noneArray[] = array($x, $i, 1);
749 }
750 if (!$locationId) {
751 $noneArray[] = array($x, $i, 2);
752 }
753 if (!$phoneType && !$imProvider) {
754 $noneArray[] = array($x, $i, 3);
755 }
756
757 $noneArray[] = array($x, $i, 4);
758 $noneArray[] = array($x, $i, 5);
759 $noneArray[] = array($x, $i, 6);
760 }
761
762 $jsSet = TRUE;
763
764 if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingOperator))) {
765 $defaults["operator[$x][$i]"] = CRM_Utils_Array::value($i, $mappingOperator[$x]);
766 }
767
768 if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingValue))) {
769 $defaults["value[$x][$i]"] = CRM_Utils_Array::value($i, $mappingValue[$x]);
770 }
771 }
772 }
773 }
774 //Fix for Search Builder
775 if ($mappingType == 'Export') {
776 $j = 7;
777 }
778 else {
779 $j = 4;
780 }
781
782 $formValues = $form->exportValues();
783 if (!$jsSet) {
784 if (empty($formValues)) {
785 // Incremented length for third select box(relationship type)
786 for ($k = 1; $k < $j; $k++) {
787 $noneArray[] = array($x, $i, $k);
788 }
789 }
790 else {
791 if (!empty($formValues['mapper'][$x])) {
792 foreach ($formValues['mapper'][$x] as $value) {
793 for ($k = 1; $k < $j; $k++) {
794 if (!isset($formValues['mapper'][$x][$i][$k]) ||
795 (!$formValues['mapper'][$x][$i][$k])
796 ) {
797 $noneArray[] = array($x, $i, $k);
798 }
799 else {
800 $nullArray[] = array($x, $i, $k);
801 }
802 }
803 }
804 }
805 else {
806 for ($k = 1; $k < $j; $k++) {
807 $noneArray[] = array($x, $i, $k);
808 }
809 }
810 }
811 }
812 //Fix for Search Builder
813 if ($mappingType == 'Export') {
814 if (!isset($mappingId) || $i >= count(reset($mappingName))) {
815 if (isset($formValues['mapper']) &&
816 isset($formValues['mapper'][$x][$i][1]) &&
817 array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)
818 ) {
819 $sel->setOptions(array($sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4));
820 }
821 else {
822 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
823 }
824 }
825 else {
826 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
827 }
828 }
829 else {
830 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
831 }
832
833 if ($mappingType == 'Search Builder') {
834 //CRM -2292, restricted array set
835 $operatorArray = array('' => ts('-operator-')) + CRM_Core_SelectValues::getSearchBuilderOperators();
836
837 $form->add('select', "operator[$x][$i]", '', $operatorArray);
838 $form->add('text', "value[$x][$i]", '');
839 }
840 }
841 //end of columnCnt for
842 if ($mappingType == 'Search Builder') {
843 $title = ts('Another search field');
844 }
845 else {
846 $title = ts('Select more fields');
847 }
848
849 $form->addElement('submit', "addMore[$x]", $title, array('class' => 'submit-link'));
850 }
851 //end of block for
852
853 $js = "<script type='text/javascript'>\n";
854 $formName = "document." . (($mappingType == 'Export') ? 'Map' : 'Builder');
855 if (!empty($nullArray)) {
856 $js .= "var nullArray = [";
857 $elements = array();
858 $seen = array();
859 foreach ($nullArray as $element) {
860 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
861 if (!isset($seen[$key])) {
862 $elements[] = "[$key]";
863 $seen[$key] = 1;
864 }
865 }
866 $js .= implode(', ', $elements);
867 $js .= "]";
868 $js .= "
869 for (var i=0;i<nullArray.length;i++) {
870 if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
871 {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
872 }
873 }
874 ";
875 }
876 if (!empty($noneArray)) {
877 $js .= "var noneArray = [";
878 $elements = array();
879 $seen = array();
880 foreach ($noneArray as $element) {
881 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
882 if (!isset($seen[$key])) {
883 $elements[] = "[$key]";
884 $seen[$key] = 1;
885 }
886 }
887 $js .= implode(', ', $elements);
888 $js .= "]";
889 $js .= "
890 for (var i=0;i<noneArray.length;i++) {
891 if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
892 {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
893 }
894 }
895 ";
896 }
897 $js .= "</script>\n";
898
899 $form->assign('initHideBoxes', $js);
900 $form->assign('columnCount', $columnCount);
901 $form->assign('blockCount', $blockCount);
902 $form->setDefaults($defaults);
903
904 $form->setDefaultAction('refresh');
905 }
906
907 /**
908 * Function returns all custom fields with group title and
909 * field label
910 *
911 * @param int $relationshipTypeId
912 * Related relationship type id.
913 *
914 * @return array
915 * all custom field titles
916 */
917 public function getRelationTypeCustomGroupData($relationshipTypeId) {
918
919 $customFields = CRM_Core_BAO_CustomField::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
920 $groupTitle = array();
921 foreach ($customFields as $krelation => $vrelation) {
922 $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
923 }
924 return $groupTitle;
925 }
926
927
928 /**
929 * Function returns all Custom group Names.
930 *
931 * @param int $customfieldId
932 * Related file id.
933 *
934 * @return null|string
935 * $customGroupName all custom group names
936 */
937 public static function getCustomGroupName($customfieldId) {
938 if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($customfieldId)) {
939 $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
940 $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
941
942 if (strlen($customGroupName) > 13) {
943 $customGroupName = substr($customGroupName, 0, 10) . '...';
944 }
945
946 return $customGroupName;
947 }
948 }
949
950 /**
951 * Function returns associated array of elements, that will be passed for search
952 *
953 * @param array $params
954 * Associated array of submitted values.
955 * @param bool $row
956 * Row no of the fields.
957 *
958 *
959 * @return array
960 * formatted associated array of elements
961 */
962 public static function formattedFields(&$params, $row = FALSE) {
963 $fields = array();
964
965 if (empty($params) || !isset($params['mapper'])) {
966 return $fields;
967 }
968
969 $types = array('Individual', 'Organization', 'Household');
970 foreach ($params['mapper'] as $key => $value) {
971 $contactType = NULL;
972 foreach ($value as $k => $v) {
973 if (in_array($v[0], $types)) {
974 if ($contactType && $contactType != $v[0]) {
975 CRM_Core_Error::fatal(ts("Cannot have two clauses with different types: %1, %2",
976 array(1 => $contactType, 2 => $v[0])
977 ));
978 }
979 $contactType = $v[0];
980 }
981 if (!empty($v['1'])) {
982 $fldName = $v[1];
983 $v2 = CRM_Utils_Array::value('2', $v);
984 if ($v2 && trim($v2)) {
985 $fldName .= "-{$v[2]}";
986 }
987
988 $v3 = CRM_Utils_Array::value('3', $v);
989 if ($v3 && trim($v3)) {
990 $fldName .= "-{$v[3]}";
991 }
992
993 $value = $params['value'][$key][$k];
994
995 if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
996 && substr($fldName, 0, 10) != 'financial_'
997 && substr($fldName, 0, 8) != 'payment_') {
998 if (substr($fldName, 0, 13) != 'contribution_') {
999 $fldName = 'contribution_' . $fldName;
1000 }
1001 }
1002
1003 // CRM-14983: verify if values are comma separated convert to array
1004 if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
1005 $value = explode(',', $value);
1006 $value = array($params['operator'][$key][$k] => $value);
1007 }
1008 // CRM-19081 Fix legacy StateProvince Field Values.
1009 // These derive from smart groups created using search builder under older
1010 // CiviCRM versions.
1011 if (!is_numeric($value) && $fldName == 'state_province') {
1012 $value = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Address', 'state_province_id', $value);
1013 }
1014
1015 if ($row) {
1016 $fields[] = array(
1017 $fldName,
1018 $params['operator'][$key][$k],
1019 $value,
1020 $key,
1021 $k,
1022 );
1023 }
1024 else {
1025 $fields[] = array(
1026 $fldName,
1027 $params['operator'][$key][$k],
1028 $value,
1029 $key,
1030 0,
1031 );
1032 }
1033 }
1034 }
1035 if ($contactType) {
1036 $fields[] = array(
1037 'contact_type',
1038 '=',
1039 $contactType,
1040 $key,
1041 0,
1042 );
1043 }
1044 }
1045
1046 //add sortByCharacter values
1047 if (isset($params['sortByCharacter'])) {
1048 $fields[] = array(
1049 'sortByCharacter',
1050 '=',
1051 $params['sortByCharacter'],
1052 0,
1053 0,
1054 );
1055 }
1056 return $fields;
1057 }
1058
1059 /**
1060 * @param array $params
1061 *
1062 * @return array
1063 */
1064 public static function &returnProperties(&$params) {
1065 $fields = array(
1066 'contact_type' => 1,
1067 'contact_sub_type' => 1,
1068 'sort_name' => 1,
1069 );
1070
1071 if (empty($params) || empty($params['mapper'])) {
1072 return $fields;
1073 }
1074
1075 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
1076 foreach ($params['mapper'] as $key => $value) {
1077 foreach ($value as $k => $v) {
1078 if (isset($v[1])) {
1079 if ($v[1] == 'groups' || $v[1] == 'tags') {
1080 continue;
1081 }
1082
1083 if (isset($v[2]) && is_numeric($v[2])) {
1084 if (!array_key_exists('location', $fields)) {
1085 $fields['location'] = array();
1086 }
1087
1088 // make sure that we have a location fields and a location type for this
1089 $locationName = $locationTypes[$v[2]];
1090 if (!array_key_exists($locationName, $fields['location'])) {
1091 $fields['location'][$locationName] = array();
1092 $fields['location'][$locationName]['location_type'] = $v[2];
1093 }
1094
1095 if ($v[1] == 'phone' || $v[1] == 'email' || $v[1] == 'im') {
1096 // phone type handling
1097 if (isset($v[3])) {
1098 $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
1099 }
1100 else {
1101 $fields['location'][$locationName][$v[1]] = 1;
1102 }
1103 }
1104 else {
1105 $fields['location'][$locationName][$v[1]] = 1;
1106 }
1107 }
1108 else {
1109 $fields[$v[1]] = 1;
1110 }
1111 }
1112 }
1113 }
1114
1115 return $fields;
1116 }
1117
1118 /**
1119 * Save the mapping field info for search builder / export given the formvalues
1120 *
1121 * @param array $params
1122 * Asscociated array of formvalues.
1123 * @param int $mappingId
1124 * Mapping id.
1125 *
1126 * @return NULL
1127 */
1128 public static function saveMappingFields(&$params, $mappingId) {
1129 //delete mapping fields records for exixting mapping
1130 $mappingFields = new CRM_Core_DAO_MappingField();
1131 $mappingFields->mapping_id = $mappingId;
1132 $mappingFields->delete();
1133
1134 if (empty($params['mapper'])) {
1135 return NULL;
1136 }
1137
1138 //save record in mapping field table
1139 foreach ($params['mapper'] as $key => $value) {
1140 $colCnt = 0;
1141 foreach ($value as $k => $v) {
1142
1143 if (!empty($v['1'])) {
1144 $saveMappingFields = new CRM_Core_DAO_MappingField();
1145
1146 $saveMappingFields->mapping_id = $mappingId;
1147 $saveMappingFields->name = CRM_Utils_Array::value('1', $v);
1148 $saveMappingFields->contact_type = CRM_Utils_Array::value('0', $v);
1149 $locationId = CRM_Utils_Array::value('2', $v);
1150 $saveMappingFields->location_type_id = is_numeric($locationId) ? $locationId : NULL;
1151
1152 if ($v[1] == 'phone') {
1153 $saveMappingFields->phone_type_id = CRM_Utils_Array::value('3', $v);
1154 }
1155 elseif ($v[1] == 'im') {
1156 $saveMappingFields->im_provider_id = CRM_Utils_Array::value('3', $v);
1157 }
1158
1159 if (!empty($params['operator'])) {
1160 $saveMappingFields->operator = CRM_Utils_Array::value($k, $params['operator'][$key]);
1161 }
1162 if (!empty($params['value'])) {
1163 $saveMappingFields->value = CRM_Utils_Array::value($k, $params['value'][$key]);
1164 }
1165 // Handle mapping for 'related contact' fields
1166 if (count(explode('_', CRM_Utils_Array::value('1', $v))) > 2) {
1167 list($id, $first, $second) = explode('_', CRM_Utils_Array::value('1', $v));
1168 if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {
1169
1170 if (!empty($v['2'])) {
1171 $saveMappingFields->name = CRM_Utils_Array::value('2', $v);
1172 }
1173 elseif (!empty($v['4'])) {
1174 $saveMappingFields->name = CRM_Utils_Array::value('4', $v);
1175 }
1176
1177 if (is_numeric(CRM_Utils_Array::value('3', $v))) {
1178 $locationTypeid = CRM_Utils_Array::value('3', $v);
1179 }
1180 elseif (is_numeric(CRM_Utils_Array::value('5', $v))) {
1181 $locationTypeid = CRM_Utils_Array::value('5', $v);
1182 }
1183
1184 if (is_numeric(CRM_Utils_Array::value('4', $v))) {
1185 $phoneTypeid = CRM_Utils_Array::value('4', $v);
1186 }
1187 elseif (is_numeric(CRM_Utils_Array::value('6', $v))) {
1188 $phoneTypeid = CRM_Utils_Array::value('6', $v);
1189 }
1190
1191 $saveMappingFields->location_type_id = is_numeric($locationTypeid) ? $locationTypeid : NULL;
1192 $saveMappingFields->phone_type_id = is_numeric($phoneTypeid) ? $phoneTypeid : NULL;
1193 $saveMappingFields->relationship_type_id = $id;
1194 $saveMappingFields->relationship_direction = "{$first}_{$second}";
1195 }
1196 }
1197
1198 $saveMappingFields->grouping = $key;
1199 $saveMappingFields->column_number = $colCnt;
1200 $saveMappingFields->save();
1201 $colCnt++;
1202 $locationTypeid = $phoneTypeid = NULL;
1203 }
1204 }
1205 }
1206 }
1207
1208 }