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