Merge pull request #2319 from lcdservices/CRM-13252
[civicrm-core.git] / CRM / Core / BAO / Mapping.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 *
122 * @return array $mapping array of mapping name
123 * @access public
124 * @static
125 */
126 static function getMappings($mappingTypeId) {
127 $mapping = array();
128 $mappingDAO = new CRM_Core_DAO_Mapping();
129 $mappingDAO->mapping_type_id = $mappingTypeId;
130 $mappingDAO->find();
131
132 while ($mappingDAO->fetch()) {
133 $mapping[$mappingDAO->id] = $mappingDAO->name;
134 }
135
136 return $mapping;
137 }
138
139 /**
140 * function to get the mapping fields
141 *
142 * @params int $mappingId mapping id
143 *
144 * @return array $mappingFields array of mapping fields
145 * @access public
146 * @static
147 *
148 */
149 static function getMappingFields($mappingId) {
150 //mapping is to be loaded from database
151 $mapping = new CRM_Core_DAO_MappingField();
152 $mapping->mapping_id = $mappingId;
153 $mapping->orderBy('column_number');
154 $mapping->find();
155
156 $mappingName = $mappingLocation = $mappingContactType = $mappingPhoneType = array();
157 $mappingImProvider = $mappingRelation = $mappingOperator = $mappingValue = $mappingWebsiteType = array();
158 while ($mapping->fetch()) {
159 $mappingName[$mapping->grouping][$mapping->column_number] = $mapping->name;
160 $mappingContactType[$mapping->grouping][$mapping->column_number] = $mapping->contact_type;
161
162 if (!empty($mapping->location_type_id)) {
163 $mappingLocation[$mapping->grouping][$mapping->column_number] = $mapping->location_type_id;
164 }
165
166 if (!empty($mapping->phone_type_id)) {
167 $mappingPhoneType[$mapping->grouping][$mapping->column_number] = $mapping->phone_type_id;
168 }
169
170 // get IM service provider type id from mapping fields
171 if (!empty($mapping->im_provider_id)) {
172 $mappingImProvider[$mapping->grouping][$mapping->column_number] = $mapping->im_provider_id;
173 }
174
175 if (!empty($mapping->website_type_id)) {
176 $mappingWebsiteType[$mapping->grouping][$mapping->column_number] = $mapping->website_type_id;
177 }
178
179 if (!empty($mapping->relationship_type_id)) {
180 $mappingRelation[$mapping->grouping][$mapping->column_number] = "{$mapping->relationship_type_id}_{$mapping->relationship_direction}";
181 }
182
183 if (!empty($mapping->operator)) {
184 $mappingOperator[$mapping->grouping][$mapping->column_number] = $mapping->operator;
185 }
186
187 if (!empty($mapping->value)) {
188 $mappingValue[$mapping->grouping][$mapping->column_number] = $mapping->value;
189 }
190 }
191
192 return array(
193 $mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType,
194 $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue, $mappingWebsiteType,
195 );
196 }
197
198 /**
199 *function to check Duplicate Mapping Name
200 *
201 * @params $nameField string mapping Name
202 *
203 * @params $mapTypeId string mapping Type
204 *
205 * @return boolean
206 *
207 */
208 static function checkMapping($nameField, $mapTypeId) {
209 $mapping = new CRM_Core_DAO_Mapping();
210 $mapping->name = $nameField;
211 $mapping->mapping_type_id = $mapTypeId;
212 if ($mapping->find(TRUE)) {
213 return TRUE;
214 }
215 else {
216 return FALSE;
217 }
218 }
219
220 /**
221 * Function returns associated array of elements, that will be passed for search
222 *
223 * @params int $smartGroupId smart group id
224 *
225 * @return $returnFields associated array of elements
226 *
227 * @static
228 * @public
229 */
230 static function getFormattedFields($smartGroupId) {
231 $returnFields = array();
232
233 //get the fields from mapping table
234 $dao = new CRM_Core_DAO_MappingField();
235 $dao->mapping_id = $smartGroupId;
236 $dao->find();
237 while ($dao->fetch()) {
238 $fldName = $dao->name;
239 if ($dao->location_type_id) {
240 $fldName .= "-{$dao->location_type_id}";
241 }
242 if ($dao->phone_type) {
243 $fldName .= "-{$dao->phone_type}";
244 }
245 $returnFields[$fldName]['value'] = $dao->value;
246 $returnFields[$fldName]['op'] = $dao->operator;
247 $returnFields[$fldName]['grouping'] = $dao->grouping;
248 }
249 return $returnFields;
250 }
251
252 /**
253 * Function to build the mapping form
254 *
255 * @params object $form form object
256 * @params string $mappingType mapping type (Export/Import/Search Builder)
257 * @params int $mappingId mapping id
258 * @params mixed $columnCount column count is int for and array for search builder
259 * @params int $blockCount block count (no of blocks shown)
260 *
261 * @return none
262 * @access public
263 * @static
264 */
265 static function buildMappingForm(&$form, $mappingType = 'Export', $mappingId = NULL, $columnNo, $blockCount = 3, $exportMode = NULL) {
266 if ($mappingType == 'Export') {
267 $name = "Map";
268 $columnCount = array('1' => $columnNo);
269 }
270 elseif ($mappingType == 'Search Builder') {
271 $name = "Builder";
272 $columnCount = $columnNo;
273 }
274
275 //get the saved mapping details
276
277 if ($mappingType == 'Export') {
278 $form->applyFilter('saveMappingName', 'trim');
279
280 //to save the current mappings
281 if (!isset($mappingId)) {
282 $saveDetailsName = ts('Save this field mapping');
283 $form->add('text', 'saveMappingName', ts('Name'));
284 $form->add('text', 'saveMappingDesc', ts('Description'));
285 }
286 else {
287 $form->assign('loadedMapping', $mappingId);
288
289 $params = array('id' => $mappingId);
290 $temp = array();
291 $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
292
293 $form->assign('savedName', $mappingDetails->name);
294
295 $form->add('hidden', 'mappingId', $mappingId);
296
297 $form->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
298 $saveDetailsName = ts('Save as a new field mapping');
299 $form->add('text', 'saveMappingName', ts('Name'));
300 $form->add('text', 'saveMappingDesc', ts('Description'));
301 }
302
303 $form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
304 $form->addFormRule(array('CRM_Export_Form_Map', 'formRule'), $form->get('mappingTypeId'));
305 }
306 elseif ($mappingType == 'Search Builder') {
307 $form->addElement('submit', 'addBlock', ts('Also include contacts where'),
308 array('class' => 'submit-link')
309 );
310 }
311
312 $defaults = array();
313 $hasLocationTypes = array();
314 $hasRelationTypes = array();
315 $fields = array();
316
317 if ($mappingType == 'Export') {
318 $required = TRUE;
319 }
320 elseif ($mappingType == 'Search Builder') {
321 $required = FALSE;
322 }
323
324 $contactType = array('Individual', 'Household', 'Organization');
325 foreach ($contactType as $value) {
326 $contactFields = CRM_Contact_BAO_Contact::exportableFields($value, FALSE, $required);
eb1e3589
DS
327 $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook::singleton()->getFields());
328
6a488035
TO
329 // exclude the address options disabled in the Address Settings
330 $fields[$value] = CRM_Core_BAO_Address::validateAddressOptions($contactFields);
c49a1c1a 331 ksort($fields[$value]);
6a488035
TO
332 if ($mappingType == 'Export') {
333 $relationships = array();
334 $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $value);
335 asort($relationshipTypes);
336
337 foreach ($relationshipTypes as $key => $var) {
338 list($type) = explode('_', $key);
339
340 $relationships[$key]['title'] = $var;
341 $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
342 $relationships[$key]['export'] = TRUE;
343 $relationships[$key]['relationship_type_id'] = $type;
344 $relationships[$key]['related'] = TRUE;
345 $relationships[$key]['hasRelationType'] = 1;
346 }
347
348 if (!empty($relationships)) {
349 $fields[$value] = array_merge($fields[$value],
350 array('related' => array('title' => ts('- related contact info -'))),
351 $relationships
352 );
353 }
354 }
355 }
356
357 //get the current employer for mapping.
358 if ($required) {
359 $fields['Individual']['current_employer']['title'] = ts('Current Employer');
360 }
361
362 // add component fields
363 $compArray = array();
364
365 //we need to unset groups, tags, notes for component export
366 if ($exportMode != CRM_Export_Form_Select::CONTACT_EXPORT) {
367 foreach (array(
368 'groups', 'tags', 'notes') as $value) {
369 unset($fields['Individual'][$value]);
370 unset($fields['Household'][$value]);
371 unset($fields['Organization'][$value]);
372 }
373 }
374
375 if ($mappingType == 'Search Builder') {
376 //build the common contact fields array.
377 $fields['Contact'] = array();
378 foreach ($fields['Individual'] as $key => $value) {
379 if (CRM_Utils_Array::value($key, $fields['Household']) &&
380 CRM_Utils_Array::value($key, $fields['Organization'])
381 ) {
382 $fields['Contact'][$key] = $value;
383 unset($fields['Organization'][$key],
384 $fields['Household'][$key],
385 $fields['Individual'][$key]);
386 }
387 }
388 if (array_key_exists('note', $fields['Contact'])) {
389 $noteTitle = $fields['Contact']['note']['title'];
390 $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
391 $fields['Contact']['note_body'] = array( 'title' => $noteTitle . ': ' . ts('Body only'), 'name' => 'note_body' );
392 $fields['Contact']['note_subject'] = array( 'title' => $noteTitle . ': ' . ts('Subject only'), 'name' => 'note_subject' );
393 }
394 }
395
396 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT)) {
397 if (CRM_Core_Permission::access('CiviContribute')) {
398 $fields['Contribution'] = CRM_Contribute_BAO_Contribution::exportableFields();
399 unset($fields['Contribution']['contribution_contact_id']);
400 unset($fields['Contribution']['contribution_status_id']);
401 $compArray['Contribution'] = ts('Contribution');
402 }
403 }
404
405 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT)) {
406 if (CRM_Core_Permission::access('CiviEvent')) {
407 $fields['Participant'] = CRM_Event_BAO_Participant::exportableFields();
d77aba4b
AS
408 //get the component payment fields
409 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
410 require_once 'CRM/Export/BAO/Export.php';
411 $componentPaymentFields = array();
412 foreach (CRM_Export_BAO_Export::componentPaymentFields() as $payField => $payTitle) {
413 $componentPaymentFields[$payField] = array('title' => $payTitle);
414 }
415 $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
416 }
417
6a488035
TO
418 unset($fields['Participant']['participant_contact_id']);
419 $compArray['Participant'] = ts('Participant');
420 }
421 }
422
423 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT)) {
424 if (CRM_Core_Permission::access('CiviMember')) {
425 $fields['Membership'] = CRM_Member_BAO_Membership::getMembershipFields($exportMode);
426 unset($fields['Membership']['membership_contact_id']);
427 $compArray['Membership'] = ts('Membership');
428 }
429 }
430
431 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT)) {
432 if (CRM_Core_Permission::access('CiviPledge')) {
433 $fields['Pledge'] = CRM_Pledge_BAO_Pledge::exportableFields();
434 unset($fields['Pledge']['pledge_contact_id']);
435 $compArray['Pledge'] = ts('Pledge');
436 }
437 }
438
439 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CASE_EXPORT)) {
440 if (CRM_Core_Permission::access('CiviCase')) {
441 $fields['Case'] = CRM_Case_BAO_Case::exportableFields();
442 $compArray['Case'] = ts('Case');
443
444 $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Case');
445 $compArray['Activity'] = ts('Case Activity');
446
447 unset($fields['Case']['case_contact_id']);
448 }
449 }
450 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT)) {
451 if (CRM_Core_Permission::access('CiviGrant')) {
452 $fields['Grant'] = CRM_Grant_BAO_Grant::exportableFields();
453 unset($fields['Grant']['grant_contact_id']);
454 $compArray['Grant'] = ts('Grant');
455 }
456 }
457
458 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT)) {
459 $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Activity');
460 $compArray['Activity'] = ts('Activity');
461 }
462
463 //Contact Sub Type For export
464 $contactSubTypes = array();
465 $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
466
467 foreach ($subTypes as $subType => $val) {
468 //adding subtype specific relationships CRM-5256
469 $csRelationships = array();
470
471 if ($mappingType == 'Export') {
8ef12e64 472 $subTypeRelationshipTypes =
6a488035
TO
473 CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'],
474 FALSE, 'label', TRUE, $subType);
8ef12e64 475
6a488035
TO
476 foreach ($subTypeRelationshipTypes as $key => $var) {
477 if (!array_key_exists($key, $fields[$val['parent']])) {
478 list($type) = explode('_', $key);
8ef12e64 479
6a488035
TO
480 $csRelationships[$key]['title'] = $var;
481 $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
482 $csRelationships[$key]['export'] = TRUE;
483 $csRelationships[$key]['relationship_type_id'] = $type;
484 $csRelationships[$key]['related'] = TRUE;
485 $csRelationships[$key]['hasRelationType'] = 1;
486 }
487 }
488 }
489
490 $fields[$subType] = $fields[$val['parent']] + $csRelationships;
491
492 //custom fields for sub type
493 $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($subType);
494 $fields[$subType] += $subTypeFields;
495
496 if (!empty($subTypeFields) || !empty($csRelationships)) {
497 $contactSubTypes[$subType] = $val['label'];
498 }
499 }
500
501 unset($subTypes);
502
503 foreach ($fields as $key => $value) {
504
505 foreach ($value as $key1 => $value1) {
506 //CRM-2676, replacing the conflict for same custom field name from different custom group.
507 $customGroupName = self::getCustomGroupName($key1);
508
509 if ($customGroupName) {
510 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
511 }
512 else {
513 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
514 }
515 if (isset($value1['hasLocationType'])) {
516 $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
517 }
518
519 if (isset($value1['hasRelationType'])) {
520 $hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
521 unset($relatedMapperFields[$key][$key1]);
522 }
523 }
524
525 if (array_key_exists('related', $relatedMapperFields[$key])) {
526 unset($relatedMapperFields[$key]['related']);
527 }
528 }
529
530 $mapperKeys = array_keys($mapperFields);
531
b2b0530a 532 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
533
534 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
535
536 /* FIXME: dirty hack to make the default option show up first. This
537 * avoids a mozilla browser bug with defaults on dynamically constructed
538 * selector widgets. */
539
540
541 if ($defaultLocationType) {
542 $defaultLocation = $locationTypes[$defaultLocationType->id];
543 unset($locationTypes[$defaultLocationType->id]);
544 $locationTypes = array(
545 $defaultLocationType->id => $defaultLocation) + $locationTypes;
546 }
547
548 $locationTypes = array(
549 ' ' => ts('Primary')) + $locationTypes;
550
551 // since we need a hierarchical list to display contact types & subtypes,
552 // this is what we going to display in first selector
553 $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE);
554 if ($mappingType == 'Search Builder') {
555 $contactTypes = array('Contact' => ts('Contacts')) + $contactTypes;
556 }
557
558 $sel1 =
559 array('' => ts('- select record type -')) + $contactTypes + $compArray;
560
561 foreach ($sel1 as $key => $sel) {
562 if ($key) {
6a488035
TO
563 $sel2[$key] = array('' => ts('- select field -')) + $mapperFields[$key];
564 }
565 }
566
567 $sel3[''] = NULL;
568 $sel5[''] = NULL;
b4f964d9 569 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
e7e657f0 570 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
6a488035
TO
571 asort($phoneTypes);
572
573 foreach ($sel1 as $k => $sel) {
574 if ($k) {
575 foreach ($locationTypes as $key => $value) {
576 if (trim($key) != '') {
577 $sel4[$k]['phone'][$key] = &$phoneTypes;
578 $sel4[$k]['im'][$key] = &$imProviders;
579 }
580 }
581 }
582 }
583
584 foreach ($sel1 as $k => $sel) {
585 if ($k) {
586 foreach ($mapperFields[$k] as $key => $value) {
587 if (isset($hasLocationTypes[$k][$key])) {
588 $sel3[$k][$key] = $locationTypes;
589 }
590 else {
591 $sel3[$key] = NULL;
592 }
593 }
594 }
595 }
596
597 //Array for core fields and relationship custom data
598
599 $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
600
601 if ($mappingType == 'Export') {
602 foreach ($sel1 as $k => $sel) {
603 if ($k) {
604 foreach ($mapperFields[$k] as $field => $dontCare) {
605 if (isset($hasRelationTypes[$k][$field])) {
606 list($id, $first, $second) = explode('_', $field);
607 // FIX ME: For now let's not expose custom data related to relationship
608 $relationshipCustomFields = array();
609 //$relationshipCustomFields = self::getRelationTypeCustomGroupData( $id );
610 //asort( $relationshipCustomFields ) ;
611
612 $relationshipType = new CRM_Contact_BAO_RelationshipType();
613 $relationshipType->id = $id;
614 if ($relationshipType->find(TRUE)) {
615 $direction = "contact_sub_type_$second";
616 if (isset($relationshipType->$direction)) {
617 $relatedFields = array_merge((array)$relatedMapperFields[$relationshipType->$direction], (array)$relationshipCustomFields);
618 }
619 else {
620 $target_type = 'contact_type_' . $second;
621 $relatedFields = array_merge((array)$relatedMapperFields[$relationshipType->$target_type], (array)$relationshipCustomFields);
622 }
623 }
624 $relationshipType->free();
625 asort($relatedFields);
626 $sel5[$k][$field] = $relatedFields;
627 }
628 }
629 }
630 }
631
632 //Location Type for relationship fields
633
634 foreach ($sel5 as $k => $v) {
635 if ($v) {
636 foreach ($v as $rel => $fields) {
637 foreach ($fields as $field => $fieldLabel) {
638 if (isset($hasLocationTypes[$k][$field])) {
639 $sel6[$k][$rel][$field] = $locationTypes;
640 }
641 }
642 }
643 }
644 }
645
646 //PhoneTypes for relationship fields
647 $sel7[''] = NULL;
648 foreach ($sel6 as $k => $rel) {
649 if ($k) {
650 foreach ($rel as $phonekey => $phonevalue) {
651 foreach ($locationTypes as $locType => $loc) {
652 if (trim($locType) != '') {
653 $sel7[$k][$phonekey]['phone'][$locType] = &$phoneTypes;
654 $sel7[$k][$phonekey]['im'][$locType] = &$imProviders;
655 }
656 }
657 }
658 }
659 }
660 }
661
662 //special fields that have location, hack for primary location
663 $specialFields = array(
664 'street_address', 'supplemental_address_1', 'supplemental_address_2',
665 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
666 'state_province', 'country', 'phone', 'email', 'im',
667 );
668
669 if (isset($mappingId)) {
670 $colCnt = 0;
671
672 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
673 $mappingRelation, $mappingOperator, $mappingValue
674 ) = CRM_Core_BAO_Mapping::getMappingFields($mappingId);
675
676 $blkCnt = count($mappingName);
677 if ($blkCnt >= $blockCount) {
678 $blockCount = $blkCnt + 1;
679 }
680 for ($x = 1; $x < $blockCount; $x++) {
681 if (isset($mappingName[$x])) {
682 $colCnt = count($mappingName[$x]);
683 if ($colCnt >= $columnCount[$x]) {
684 $columnCount[$x] = $colCnt;
685 }
686 }
687 }
688 }
689
690 $form->_blockCount = $blockCount;
691 $form->_columnCount = $columnCount;
692
693 $form->set('blockCount', $form->_blockCount);
694 $form->set('columnCount', $form->_columnCount);
695
696 $defaults = $noneArray = $nullArray = array();
697
698 //used to warn for mismatch column count or mismatch mapping
699 $warning = 0;
700 for ($x = 1; $x < $blockCount; $x++) {
701
702 for ($i = 0; $i < $columnCount[$x]; $i++) {
703
704 $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
705 $jsSet = FALSE;
706
707 if (isset($mappingId)) {
708 $locationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0;
709 if (isset($mappingName[$x][$i])) {
710 if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
711
712 if (isset($mappingRelation[$x][$i])) {
713
714 $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$x][$i]));
715 $relLocationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0;
716 if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
717 $relLocationId = " ";
718 }
719
720 $relPhoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
721
722 $defaults["mapper[$x][$i]"] = array(
723 $mappingContactType[$x][$i],
724 $mappingRelation[$x][$i],
725 $locationId,
726 $phoneType,
727 $mappingName[$x][$i],
728 $relLocationId,
729 $relPhoneType,
730 );
731
732 if (!$locationId) {
733 $noneArray[] = array($x, $i, 2);
734 }
735 if (!$phoneType && !$imProvider) {
736 $noneArray[] = array($x, $i, 3);
737 }
738 if (!$mappingName[$x][$i]) {
739 $noneArray[] = array($x, $i, 4);
740 }
741 if (!$relLocationId) {
742 $noneArray[] = array($x, $i, 5);
743 }
744 if (!$relPhoneType) {
745 $noneArray[] = array($x, $i, 6);
746 }
747 $noneArray[] = array($x, $i, 2);
748 }
749 else {
750 $phoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
751 $imProvider = isset($mappingImProvider[$x][$i]) ? $mappingImProvider[$x][$i] : NULL;
752 if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
753 $locationId = " ";
754 }
755
756 $defaults["mapper[$x][$i]"] = array(
757 $mappingContactType[$x][$i],
758 $mappingName[$x][$i],
759 $locationId,
760 $phoneType,
761 );
762 if (!$mappingName[$x][$i]) {
763 $noneArray[] = array($x, $i, 1);
764 }
765 if (!$locationId) {
766 $noneArray[] = array($x, $i, 2);
767 }
768 if (!$phoneType && !$imProvider) {
769 $noneArray[] = array($x, $i, 3);
770 }
771
772 $noneArray[] = array($x, $i, 4);
773 $noneArray[] = array($x, $i, 5);
774 $noneArray[] = array($x, $i, 6);
775 }
776
777 $jsSet = TRUE;
778
779 if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingOperator))) {
780 $defaults["operator[$x][$i]"] = CRM_Utils_Array::value($i, $mappingOperator[$x]);
781 }
782
783 if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingValue))) {
784 $defaults["value[$x][$i]"] = CRM_Utils_Array::value($i, $mappingValue[$x]);
785 }
786 }
787 }
788 }
789 //Fix for Search Builder
790 if ($mappingType == 'Export') {
791 $j = 7;
792 }
793 else {
794 $j = 4;
795 }
796
797 $formValues = $form->exportValues();
798 if (!$jsSet) {
799 if (empty($formValues)) {
800 // Incremented length for third select box(relationship type)
801 for ($k = 1; $k < $j; $k++) {
802 $noneArray[] = array($x, $i, $k);
803 }
804 }
805 else {
806 if (!empty($formValues['mapper'][$x])) {
807 foreach ($formValues['mapper'][$x] as $value) {
808 for ($k = 1; $k < $j; $k++) {
809 if (!isset($formValues['mapper'][$x][$i][$k]) ||
810 (!$formValues['mapper'][$x][$i][$k])
811 ) {
812 $noneArray[] = array($x, $i, $k);
813 }
814 else {
815 $nullArray[] = array($x, $i, $k);
816 }
817 }
818 }
819 }
820 else {
821 for ($k = 1; $k < $j; $k++) {
822 $noneArray[] = array($x, $i, $k);
823 }
824 }
825 }
826 }
827 //Fix for Search Builder
828 if ($mappingType == 'Export') {
829 if (!isset($mappingId)) {
830 if (isset($formValues['mapper']) &&
831 isset($formValues['mapper'][$x][$i][1]) &&
832 array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)
833 ) {
834 $sel->setOptions(array($sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4));
835 }
836 else {
837 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
838 }
839 }
840 else {
841 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
842 }
843 }
844 else {
845 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
846 }
847
848 if ($mappingType == 'Search Builder') {
849 //CRM -2292, restricted array set
850 $operatorArray = array(
d073fff9
CW
851 '' => ts('-operator-'),
852 '=' => '=',
853 '!=' => '≠',
854 '>' => '>',
855 '<' => '<',
856 '>=' => '≥',
857 '<=' => '≤',
858 'IN' => ts('In'),
859 'LIKE' => ts('Like'),
860 'RLIKE' => ts('Regex'),
861 'IS EMPTY' => ts('Is Empty'),
862 'IS NOT EMPTY' => ts('Not Empty'),
863 'IS NULL' => ts('Is Null'),
864 'IS NOT NULL' => ts('Not Null'),
6a488035
TO
865 );
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 */
942 function getRelationTypeCustomGroupData($relationshipTypeId) {
943
944 $customFields = CRM_Core_BAO_CustomField::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
945 $groupTitle = array();
946 foreach ($customFields as $krelation => $vrelation) {
947 $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
948 }
949 return $groupTitle;
950 }
951
952
953 /**
954 * Function returns all Custom group Names
955 *
956 * @param customfieldId related custom field id
957 * @return $customGroupName all custom group names
958 * @static
959 */
960 static function getCustomGroupName($customfieldId) {
961 if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($customfieldId)) {
962 $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
963 $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
964
965 if (strlen($customGroupName) > 13) {
966 $customGroupName = substr($customGroupName, 0, 10) . '...';
967 }
968
969 return $customGroupName;
970 }
971 }
972
973 /**
974 * Function returns associated array of elements, that will be passed for search
975 *
976 * @params array $params associated array of submitted values
977 * @params boolean $row row no of the fields
978 *
979 * @return $returnFields formatted associated array of elements
980 *
981 * @static
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 }
1003 if (CRM_Utils_Array::value('1', $v)) {
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
1035 if ($row) {
1036 $fields[] = array(
1037 $fldName,
1038 $params['operator'][$key][$k],
1039 $value,
1040 $key,
1041 $k,
1042 );
1043 }
1044 else {
1045 $fields[] = array(
1046 $fldName,
1047 $params['operator'][$key][$k],
1048 $value,
1049 $key,
1050 0,
1051 );
1052 }
1053 }
1054 }
1055 if ($contactType) {
1056 $fields[] = array(
1057 'contact_type',
1058 '=',
1059 $contactType,
1060 $key,
1061 0,
1062 );
1063 }
1064 }
1065
1066 //add sortByCharacter values
1067 if (isset($params['sortByCharacter'])) {
1068 $fields[] = array(
1069 'sortByCharacter',
1070 '=',
1071 $params['sortByCharacter'],
1072 0,
1073 0,
1074 );
1075 }
1076
1077
1078 return $fields;
1079 }
1080
1081 static function &returnProperties(&$params) {
1082 $fields = array(
1083 'contact_type' => 1,
1084 'contact_sub_type' => 1,
1085 'sort_name' => 1,
1086 );
1087
1088 if (empty($params) || empty($params['mapper'])) {
1089 return $fields;
1090 }
1091
b2b0530a 1092 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
1093 foreach ($params['mapper'] as $key => $value) {
1094 foreach ($value as $k => $v) {
1095 if (isset($v[1])) {
1096 if ($v[1] == 'groups' || $v[1] == 'tags') {
1097 continue;
1098 }
1099
1100 if (isset($v[2]) && is_numeric($v[2])) {
1101 if (!array_key_exists('location', $fields)) {
1102 $fields['location'] = array();
1103 }
1104
1105 // make sure that we have a location fields and a location type for this
1106 $locationName = $locationTypes[$v[2]];
1107 if (!array_key_exists($locationName, $fields['location'])) {
1108 $fields['location'][$locationName] = array();
1109 $fields['location'][$locationName]['location_type'] = $v[2];
1110 }
1111
1112 if ($v[1] == 'phone' || $v[1] == 'email' || $v[1] == 'im') {
1113 // phone type handling
1114 if (isset($v[3])) {
1115 $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
1116 }
1117 else {
1118 $fields['location'][$locationName][$v[1]] = 1;
1119 }
1120 }
1121 else {
1122 $fields['location'][$locationName][$v[1]] = 1;
1123 }
1124 }
1125 else {
1126 $fields[$v[1]] = 1;
1127 }
1128 }
1129 }
1130 }
1131
1132 return $fields;
1133 }
1134
1135 /**
1136 * save the mapping field info for search builder / export given the formvalues
1137 *
1138 * @param array $params asscociated array of formvalues
1139 * @param int $mappingId mapping id
1140 *
1141 * @return null
1142 * @static
1143 * @access public
1144 */
1145 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 (CRM_Utils_Array::value('1', $v)) {
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 (CRM_Utils_Array::value('operator', $params)) {
8ef12e64 1177 $saveMappingFields->operator = CRM_Utils_Array::value($k, $params['operator'][$key]);
6a488035
TO
1178 }
1179 if (CRM_Utils_Array::value('value', $params)) {
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 (CRM_Utils_Array::value('2', $v)) {
1188 $saveMappingFields->name = CRM_Utils_Array::value('2', $v);
1189 }
1190 elseif (CRM_Utils_Array::value('4', $v)) {
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}
1225