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