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