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