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