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