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