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