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