Merge pull request #2352 from colemanw/4.4
[civicrm-core.git] / CRM / Core / BAO / Mapping.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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 */
35 class 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);
327 $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook::singleton()->getFields());
328
329 // exclude the address options disabled in the Address Settings
330 $fields[$value] = CRM_Core_BAO_Address::validateAddressOptions($contactFields);
331 ksort($fields[$value]);
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();
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
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') {
472 $subTypeRelationshipTypes =
473 CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'],
474 FALSE, 'label', TRUE, $subType);
475
476 foreach ($subTypeRelationshipTypes as $key => $var) {
477 if (!array_key_exists($key, $fields[$val['parent']])) {
478 list($type) = explode('_', $key);
479
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
532 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
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) {
563 // sort everything BUT the contactType which is sorted seperately by
564 // an initial commit of CRM-13278 (check ksort above)
565 if (!in_array($key, $contactType)) {
566 asort($mapperFields[$key]);
567 }
568 $sel2[$key] = array('' => ts('- select field -')) + $mapperFields[$key];
569 }
570 }
571
572 $sel3[''] = NULL;
573 $sel5[''] = NULL;
574 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
575 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
576 asort($phoneTypes);
577
578 foreach ($sel1 as $k => $sel) {
579 if ($k) {
580 foreach ($locationTypes as $key => $value) {
581 if (trim($key) != '') {
582 $sel4[$k]['phone'][$key] = &$phoneTypes;
583 $sel4[$k]['im'][$key] = &$imProviders;
584 }
585 }
586 }
587 }
588
589 foreach ($sel1 as $k => $sel) {
590 if ($k) {
591 foreach ($mapperFields[$k] as $key => $value) {
592 if (isset($hasLocationTypes[$k][$key])) {
593 $sel3[$k][$key] = $locationTypes;
594 }
595 else {
596 $sel3[$key] = NULL;
597 }
598 }
599 }
600 }
601
602 //Array for core fields and relationship custom data
603
604 $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
605
606 if ($mappingType == 'Export') {
607 foreach ($sel1 as $k => $sel) {
608 if ($k) {
609 foreach ($mapperFields[$k] as $field => $dontCare) {
610 if (isset($hasRelationTypes[$k][$field])) {
611 list($id, $first, $second) = explode('_', $field);
612 // FIX ME: For now let's not expose custom data related to relationship
613 $relationshipCustomFields = array();
614 //$relationshipCustomFields = self::getRelationTypeCustomGroupData( $id );
615 //asort( $relationshipCustomFields ) ;
616
617 $relationshipType = new CRM_Contact_BAO_RelationshipType();
618 $relationshipType->id = $id;
619 if ($relationshipType->find(TRUE)) {
620 $direction = "contact_sub_type_$second";
621 if (isset($relationshipType->$direction)) {
622 $relatedFields = array_merge((array)$relatedMapperFields[$relationshipType->$direction], (array)$relationshipCustomFields);
623 }
624 else {
625 $target_type = 'contact_type_' . $second;
626 $relatedFields = array_merge((array)$relatedMapperFields[$relationshipType->$target_type], (array)$relationshipCustomFields);
627 }
628 }
629 $relationshipType->free();
630 asort($relatedFields);
631 $sel5[$k][$field] = $relatedFields;
632 }
633 }
634 }
635 }
636
637 //Location Type for relationship fields
638
639 foreach ($sel5 as $k => $v) {
640 if ($v) {
641 foreach ($v as $rel => $fields) {
642 foreach ($fields as $field => $fieldLabel) {
643 if (isset($hasLocationTypes[$k][$field])) {
644 $sel6[$k][$rel][$field] = $locationTypes;
645 }
646 }
647 }
648 }
649 }
650
651 //PhoneTypes for relationship fields
652 $sel7[''] = NULL;
653 foreach ($sel6 as $k => $rel) {
654 if ($k) {
655 foreach ($rel as $phonekey => $phonevalue) {
656 foreach ($locationTypes as $locType => $loc) {
657 if (trim($locType) != '') {
658 $sel7[$k][$phonekey]['phone'][$locType] = &$phoneTypes;
659 $sel7[$k][$phonekey]['im'][$locType] = &$imProviders;
660 }
661 }
662 }
663 }
664 }
665 }
666
667 //special fields that have location, hack for primary location
668 $specialFields = array(
669 'street_address', 'supplemental_address_1', 'supplemental_address_2',
670 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2',
671 'state_province', 'country', 'phone', 'email', 'im',
672 );
673
674 if (isset($mappingId)) {
675 $colCnt = 0;
676
677 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
678 $mappingRelation, $mappingOperator, $mappingValue
679 ) = CRM_Core_BAO_Mapping::getMappingFields($mappingId);
680
681 $blkCnt = count($mappingName);
682 if ($blkCnt >= $blockCount) {
683 $blockCount = $blkCnt + 1;
684 }
685 for ($x = 1; $x < $blockCount; $x++) {
686 if (isset($mappingName[$x])) {
687 $colCnt = count($mappingName[$x]);
688 if ($colCnt >= $columnCount[$x]) {
689 $columnCount[$x] = $colCnt;
690 }
691 }
692 }
693 }
694
695 $form->_blockCount = $blockCount;
696 $form->_columnCount = $columnCount;
697
698 $form->set('blockCount', $form->_blockCount);
699 $form->set('columnCount', $form->_columnCount);
700
701 $defaults = $noneArray = $nullArray = array();
702
703 //used to warn for mismatch column count or mismatch mapping
704 $warning = 0;
705 for ($x = 1; $x < $blockCount; $x++) {
706
707 for ($i = 0; $i < $columnCount[$x]; $i++) {
708
709 $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
710 $jsSet = FALSE;
711
712 if (isset($mappingId)) {
713 $locationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0;
714 if (isset($mappingName[$x][$i])) {
715 if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
716
717 if (isset($mappingRelation[$x][$i])) {
718
719 $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$x][$i]));
720 $relLocationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0;
721 if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
722 $relLocationId = " ";
723 }
724
725 $relPhoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
726
727 $defaults["mapper[$x][$i]"] = array(
728 $mappingContactType[$x][$i],
729 $mappingRelation[$x][$i],
730 $locationId,
731 $phoneType,
732 $mappingName[$x][$i],
733 $relLocationId,
734 $relPhoneType,
735 );
736
737 if (!$locationId) {
738 $noneArray[] = array($x, $i, 2);
739 }
740 if (!$phoneType && !$imProvider) {
741 $noneArray[] = array($x, $i, 3);
742 }
743 if (!$mappingName[$x][$i]) {
744 $noneArray[] = array($x, $i, 4);
745 }
746 if (!$relLocationId) {
747 $noneArray[] = array($x, $i, 5);
748 }
749 if (!$relPhoneType) {
750 $noneArray[] = array($x, $i, 6);
751 }
752 $noneArray[] = array($x, $i, 2);
753 }
754 else {
755 $phoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL;
756 $imProvider = isset($mappingImProvider[$x][$i]) ? $mappingImProvider[$x][$i] : NULL;
757 if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
758 $locationId = " ";
759 }
760
761 $defaults["mapper[$x][$i]"] = array(
762 $mappingContactType[$x][$i],
763 $mappingName[$x][$i],
764 $locationId,
765 $phoneType,
766 );
767 if (!$mappingName[$x][$i]) {
768 $noneArray[] = array($x, $i, 1);
769 }
770 if (!$locationId) {
771 $noneArray[] = array($x, $i, 2);
772 }
773 if (!$phoneType && !$imProvider) {
774 $noneArray[] = array($x, $i, 3);
775 }
776
777 $noneArray[] = array($x, $i, 4);
778 $noneArray[] = array($x, $i, 5);
779 $noneArray[] = array($x, $i, 6);
780 }
781
782 $jsSet = TRUE;
783
784 if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingOperator))) {
785 $defaults["operator[$x][$i]"] = CRM_Utils_Array::value($i, $mappingOperator[$x]);
786 }
787
788 if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingValue))) {
789 $defaults["value[$x][$i]"] = CRM_Utils_Array::value($i, $mappingValue[$x]);
790 }
791 }
792 }
793 }
794 //Fix for Search Builder
795 if ($mappingType == 'Export') {
796 $j = 7;
797 }
798 else {
799 $j = 4;
800 }
801
802 $formValues = $form->exportValues();
803 if (!$jsSet) {
804 if (empty($formValues)) {
805 // Incremented length for third select box(relationship type)
806 for ($k = 1; $k < $j; $k++) {
807 $noneArray[] = array($x, $i, $k);
808 }
809 }
810 else {
811 if (!empty($formValues['mapper'][$x])) {
812 foreach ($formValues['mapper'][$x] as $value) {
813 for ($k = 1; $k < $j; $k++) {
814 if (!isset($formValues['mapper'][$x][$i][$k]) ||
815 (!$formValues['mapper'][$x][$i][$k])
816 ) {
817 $noneArray[] = array($x, $i, $k);
818 }
819 else {
820 $nullArray[] = array($x, $i, $k);
821 }
822 }
823 }
824 }
825 else {
826 for ($k = 1; $k < $j; $k++) {
827 $noneArray[] = array($x, $i, $k);
828 }
829 }
830 }
831 }
832 //Fix for Search Builder
833 if ($mappingType == 'Export') {
834 if (!isset($mappingId)) {
835 if (isset($formValues['mapper']) &&
836 isset($formValues['mapper'][$x][$i][1]) &&
837 array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)
838 ) {
839 $sel->setOptions(array($sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4));
840 }
841 else {
842 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
843 }
844 }
845 else {
846 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7));
847 }
848 }
849 else {
850 $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
851 }
852
853 if ($mappingType == 'Search Builder') {
854 //CRM -2292, restricted array set
855 $operatorArray = array(
856 '' => ts('-operator-'),
857 '=' => '=',
858 '!=' => '≠',
859 '>' => '>',
860 '<' => '<',
861 '>=' => '≥',
862 '<=' => '≤',
863 'IN' => ts('In'),
864 'LIKE' => ts('Like'),
865 'RLIKE' => ts('Regex'),
866 'IS EMPTY' => ts('Is Empty'),
867 'IS NOT EMPTY' => ts('Not Empty'),
868 'IS NULL' => ts('Is Null'),
869 'IS NOT NULL' => ts('Not Null'),
870 );
871
872 $form->add('select', "operator[$x][$i]", '', $operatorArray);
873 $form->add('text', "value[$x][$i]", '');
874 }
875 }
876 //end of columnCnt for
877 if ($mappingType == 'Search Builder') {
878 $title = ts('Another search field');
879 }
880 else {
881 $title = ts('Select more fields');
882 }
883
884 $form->addElement('submit', "addMore[$x]", $title, array('class' => 'submit-link'));
885 }
886 //end of block for
887
888 $js = "<script type='text/javascript'>\n";
889 $formName = "document.{$name}";
890 if (!empty($nullArray)) {
891 $js .= "var nullArray = [";
892 $elements = array();
893 $seen = array();
894 foreach ($nullArray as $element) {
895 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
896 if (!isset($seen[$key])) {
897 $elements[] = "[$key]";
898 $seen[$key] = 1;
899 }
900 }
901 $js .= implode(', ', $elements);
902 $js .= "]";
903 $js .= "
904 for(var i=0;i<nullArray.length;i++) {
905 if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
906 {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
907 }
908 }
909 ";
910 }
911 if (!empty($noneArray)) {
912 $js .= "var noneArray = [";
913 $elements = array();
914 $seen = array();
915 foreach ($noneArray as $element) {
916 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
917 if (!isset($seen[$key])) {
918 $elements[] = "[$key]";
919 $seen[$key] = 1;
920 }
921 }
922 $js .= implode(', ', $elements);
923 $js .= "]";
924 $js .= "
925 for(var i=0;i<noneArray.length;i++) {
926 if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
927 {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
928 }
929 }
930 ";
931 }
932 $js .= "</script>\n";
933
934 $form->assign('initHideBoxes', $js);
935 $form->assign('columnCount', $columnCount);
936 $form->assign('blockCount', $blockCount);
937 $form->setDefaults($defaults);
938
939 $form->setDefaultAction('refresh');
940 }
941
942 /* Function returns all custom fields with group title and
943 * field label
944 * @relationshipTypeId related relationship type id
945 * @return $groupTitle all custom field titles
946 */
947 function getRelationTypeCustomGroupData($relationshipTypeId) {
948
949 $customFields = CRM_Core_BAO_CustomField::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
950 $groupTitle = array();
951 foreach ($customFields as $krelation => $vrelation) {
952 $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
953 }
954 return $groupTitle;
955 }
956
957
958 /**
959 * Function returns all Custom group Names
960 *
961 * @param customfieldId related custom field id
962 * @return $customGroupName all custom group names
963 * @static
964 */
965 static function getCustomGroupName($customfieldId) {
966 if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($customfieldId)) {
967 $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
968 $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
969
970 if (strlen($customGroupName) > 13) {
971 $customGroupName = substr($customGroupName, 0, 10) . '...';
972 }
973
974 return $customGroupName;
975 }
976 }
977
978 /**
979 * Function returns associated array of elements, that will be passed for search
980 *
981 * @params array $params associated array of submitted values
982 * @params boolean $row row no of the fields
983 *
984 * @return $returnFields formatted associated array of elements
985 *
986 * @static
987 * @public
988 */
989 static function &formattedFields(&$params, $row = FALSE) {
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",
1003 array(1 => $contactType, 2 => $v[0])
1004 ));
1005 }
1006 $contactType = $v[0];
1007 }
1008 if (CRM_Utils_Array::value('1', $v)) {
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];
1021 if ($fldName == 'group' || $fldName == 'tag') {
1022 $value = trim($value);
1023 $value = str_replace('(', '', $value);
1024 $value = str_replace(')', '', $value);
1025
1026 $v = explode(',', $value);
1027 $value = array();
1028 foreach ($v as $i) {
1029 $value[$i] = 1;
1030 }
1031 }
1032
1033 if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
1034 && substr($fldName, 0, 10) != 'financial_') {
1035 if (substr($fldName, 0, 13) != 'contribution_') {
1036 $fldName = 'contribution_' . $fldName;
1037 }
1038 }
1039
1040 if ($row) {
1041 $fields[] = array(
1042 $fldName,
1043 $params['operator'][$key][$k],
1044 $value,
1045 $key,
1046 $k,
1047 );
1048 }
1049 else {
1050 $fields[] = array(
1051 $fldName,
1052 $params['operator'][$key][$k],
1053 $value,
1054 $key,
1055 0,
1056 );
1057 }
1058 }
1059 }
1060 if ($contactType) {
1061 $fields[] = array(
1062 'contact_type',
1063 '=',
1064 $contactType,
1065 $key,
1066 0,
1067 );
1068 }
1069 }
1070
1071 //add sortByCharacter values
1072 if (isset($params['sortByCharacter'])) {
1073 $fields[] = array(
1074 'sortByCharacter',
1075 '=',
1076 $params['sortByCharacter'],
1077 0,
1078 0,
1079 );
1080 }
1081
1082
1083 return $fields;
1084 }
1085
1086 static function &returnProperties(&$params) {
1087 $fields = array(
1088 'contact_type' => 1,
1089 'contact_sub_type' => 1,
1090 'sort_name' => 1,
1091 );
1092
1093 if (empty($params) || empty($params['mapper'])) {
1094 return $fields;
1095 }
1096
1097 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
1098 foreach ($params['mapper'] as $key => $value) {
1099 foreach ($value as $k => $v) {
1100 if (isset($v[1])) {
1101 if ($v[1] == 'groups' || $v[1] == 'tags') {
1102 continue;
1103 }
1104
1105 if (isset($v[2]) && is_numeric($v[2])) {
1106 if (!array_key_exists('location', $fields)) {
1107 $fields['location'] = array();
1108 }
1109
1110 // make sure that we have a location fields and a location type for this
1111 $locationName = $locationTypes[$v[2]];
1112 if (!array_key_exists($locationName, $fields['location'])) {
1113 $fields['location'][$locationName] = array();
1114 $fields['location'][$locationName]['location_type'] = $v[2];
1115 }
1116
1117 if ($v[1] == 'phone' || $v[1] == 'email' || $v[1] == 'im') {
1118 // phone type handling
1119 if (isset($v[3])) {
1120 $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
1121 }
1122 else {
1123 $fields['location'][$locationName][$v[1]] = 1;
1124 }
1125 }
1126 else {
1127 $fields['location'][$locationName][$v[1]] = 1;
1128 }
1129 }
1130 else {
1131 $fields[$v[1]] = 1;
1132 }
1133 }
1134 }
1135 }
1136
1137 return $fields;
1138 }
1139
1140 /**
1141 * save the mapping field info for search builder / export given the formvalues
1142 *
1143 * @param array $params asscociated array of formvalues
1144 * @param int $mappingId mapping id
1145 *
1146 * @return null
1147 * @static
1148 * @access public
1149 */
1150 static function saveMappingFields(&$params, $mappingId) {
1151 //delete mapping fields records for exixting mapping
1152 $mappingFields = new CRM_Core_DAO_MappingField();
1153 $mappingFields->mapping_id = $mappingId;
1154 $mappingFields->delete();
1155
1156 if (empty($params['mapper'])) {
1157 return;
1158 }
1159
1160 //save record in mapping field table
1161 foreach ($params['mapper'] as $key => $value) {
1162 $colCnt = 0;
1163 foreach ($value as $k => $v) {
1164
1165 if (CRM_Utils_Array::value('1', $v)) {
1166 $saveMappingFields = new CRM_Core_DAO_MappingField();
1167
1168 $saveMappingFields->mapping_id = $mappingId;
1169 $saveMappingFields->name = CRM_Utils_Array::value('1', $v);
1170 $saveMappingFields->contact_type = CRM_Utils_Array::value('0', $v);
1171 $locationId = CRM_Utils_Array::value('2', $v);
1172 $saveMappingFields->location_type_id = is_numeric($locationId) ? $locationId : NULL;
1173
1174 if ($v[1] == 'phone') {
1175 $saveMappingFields->phone_type_id = CRM_Utils_Array::value('3', $v);
1176 }
1177 elseif ($v[1] == 'im') {
1178 $saveMappingFields->im_provider_id = CRM_Utils_Array::value('3', $v);
1179 }
1180
1181 if (CRM_Utils_Array::value('operator', $params)) {
1182 $saveMappingFields->operator = CRM_Utils_Array::value($k, $params['operator'][$key]);
1183 }
1184 if (CRM_Utils_Array::value('value', $params)) {
1185 $saveMappingFields->value = CRM_Utils_Array::value($k, $params['value'][$key]);
1186 }
1187 // Handle mapping for 'related contact' fields
1188 if (count(explode('_', CRM_Utils_Array::value('1', $v))) > 2) {
1189 list($id, $first, $second) = explode('_', CRM_Utils_Array::value('1', $v));
1190 if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {
1191
1192 if (CRM_Utils_Array::value('2', $v)) {
1193 $saveMappingFields->name = CRM_Utils_Array::value('2', $v);
1194 }
1195 elseif (CRM_Utils_Array::value('4', $v)) {
1196 $saveMappingFields->name = CRM_Utils_Array::value('4', $v);
1197 }
1198
1199 if (is_numeric(CRM_Utils_Array::value('3', $v))) {
1200 $locationTypeid = CRM_Utils_Array::value('3', $v);
1201 }
1202 elseif (is_numeric(CRM_Utils_Array::value('5', $v))) {
1203 $locationTypeid = CRM_Utils_Array::value('5', $v);
1204 }
1205
1206 if (is_numeric(CRM_Utils_Array::value('4', $v))) {
1207 $phoneTypeid = CRM_Utils_Array::value('4', $v);
1208 }
1209 elseif (is_numeric(CRM_Utils_Array::value('6', $v))) {
1210 $phoneTypeid = CRM_Utils_Array::value('6', $v);
1211 }
1212
1213 $saveMappingFields->location_type_id = is_numeric($locationTypeid) ? $locationTypeid : NULL;
1214 $saveMappingFields->phone_type_id = is_numeric($phoneTypeid) ? $phoneTypeid : NULL;
1215 $saveMappingFields->relationship_type_id = $id;
1216 $saveMappingFields->relationship_direction = "{$first}_{$second}";
1217 }
1218 }
1219
1220 $saveMappingFields->grouping = $key;
1221 $saveMappingFields->column_number = $colCnt;
1222 $saveMappingFields->save();
1223 $colCnt++;
1224 $locationTypeid = $phoneTypeid = NULL;
1225 }
1226 }
1227 }
1228 }
1229 }
1230