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