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