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