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