Merge pull request #353 from eileenmcnaughton/trunk-kill-eval
[civicrm-core.git] / api / v2 / utils.v2.php
CommitLineData
6a488035
TO
1<?php
2// $Id$
3
4/*
5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.3 |
7 +--------------------------------------------------------------------+
8 | Copyright CiviCRM LLC (c) 2004-2013 |
9 +--------------------------------------------------------------------+
10 | This file is a part of CiviCRM. |
11 | |
12 | CiviCRM is free software; you can copy, modify, and distribute it |
13 | under the terms of the GNU Affero General Public License |
14 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | |
16 | CiviCRM is distributed in the hope that it will be useful, but |
17 | WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
19 | See the GNU Affero General Public License for more details. |
20 | |
21 | You should have received a copy of the GNU Affero General Public |
22 | License and the CiviCRM Licensing Exception along |
23 | with this program; if not, contact CiviCRM LLC |
24 | at info[AT]civicrm[DOT]org. If you have questions about the |
25 | GNU Affero General Public License or the licensing of CiviCRM, |
26 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
27 +--------------------------------------------------------------------+
28*/
29
30/**
31 * File for CiviCRM APIv2 utilitity functions
32 *
33 * @package CiviCRM_APIv2
34 * @subpackage API_utils
35 *
36 * @copyright CiviCRM LLC (c) 2004-2013
37 * @version $Id: utils.php 31877 2011-01-19 04:23:54Z shot $
38 *
39 */
40require_once 'api/api.php';
41
42/**
43 * @todo Write documentation
44 *
45 */
46function _civicrm_initialize() {
47 require_once 'CRM/Core/Config.php';
48 $config = CRM_Core_Config::singleton();
49 }
50
51function civicrm_verify_mandatory(&$params, $daoName = NULL, $keys = array(
52 )) {
53 if (!is_array($params)) {
54 throw new Exception('Input parameters is not an array');
55 }
56
57 if ($daoName != NULL) {
58 _civicrm_check_required_fields($params, $daoName, TRUE);
59 }
60
61 foreach ($keys as $key) {
62 if (!array_key_exists($key, $params)) {
63 throw new Exception("Mandatory param missing: " . $key);
64 }
65 }
66}
67
68/**
69 *
70 * @param <type> $msg
71 * @param <type> $data
72 *
73 * @return <type>
74 */
75function &civicrm_create_error($msg, $data = NULL) {
76 return CRM_Core_Error::createAPIError($msg, $data);
77}
78
79/**
80 *
81 * @param <type> $result
82 *
83 * @return <type>
84 */
85function civicrm_create_success($result = 1) {
86
87 $values = array();
88
89 $values['is_error'] = 0;
90 $values['result'] = $result;
91
92 return $values;
93}
94
95/**
96 * function to check if an error is actually a duplicate contact error
97 *
98 * @param array $error (array of) valid Error values
99 *
100 * @return true if error is duplicate contact error, false otherwise
101 *
102 * @access public
103 */
104function civicrm_duplicate($error) {
105 if (is_array($error) && civicrm_error($error)) {
106 $code = $error['error_message']['code'];
107 if ($code == CRM_Core_Error::DUPLICATE_CONTACT) {
108 return TRUE;
109 }
110 }
111 return FALSE;
112}
113
114/**
115 *
116 * @param <type> $fields
117 * @param <type> $params
118 * @param <type> $values
119 *
120 * @return <type>
121 */
122function _civicrm_store_values(&$fields, &$params, &$values) {
123 $valueFound = FALSE;
124
125 $keys = array_intersect_key($params, $fields);
126 foreach ($fields as $name => $field) {
127 // ignore all ids for now
128 if ($name === 'id' || substr($name, -1, 3) === '_id') {
129 continue;
130 }
131 if (CRM_Utils_Array::value($name, $params)) {
132 $values[$name] = $params[$name];
133 $valueFound = TRUE;
134 }
135 }
136 return $valueFound;
137}
138
139/**
140 * Converts an object to an array
141 *
142 * @param object $dao (reference )object to convert
143 * @param array $dao (reference )array
144 *
145 * @return array
146 * @static void
147 * @access public
148 */
149function _civicrm_object_to_array(&$dao, &$values) {
150 $tmpFields = $dao->fields();
151 $fields = array();
152 //rebuild $fields array to fix unique name of the fields
153 foreach ($tmpFields as $key => $val) {
154 $fields[$val["name"]] = $val;
155 }
156
157 foreach ($fields as $key => $value) {
158 if (array_key_exists($key, $dao)) {
159 $values[$key] = $dao->$key;
160 }
161 }
162}
163
164/**
165 * This function adds the contact variable in $values to the
166 * parameter list $params. For most cases, $values should have length 1. If
167 * the variable being added is a child of Location, a location_type_id must
168 * also be included. If it is a child of phone, a phone_type must be included.
169 *
170 * @param array $values The variable(s) to be added
171 * @param array $params The structured parameter list
172 *
173 * @return bool|CRM_Utils_Error
174 * @access public
175 */
176function _civicrm_add_formatted_param(&$values, &$params) {
177 /* Crawl through the possible classes:
178 * Contact
179 * Individual
180 * Household
181 * Organization
182 * Location
183 * Address
184 * Email
185 * Phone
186 * IM
187 * Note
188 * Custom
189 */
190
191
192
193 /* Cache the various object fields */
194
195
196 static $fields = NULL;
197
198 if ($fields == NULL) {
199 $fields = array();
200 }
201
202 //first add core contact values since for other Civi modules they are not added
203 require_once 'CRM/Contact/BAO/Contact.php';
204 $contactFields = CRM_Contact_DAO_Contact::fields();
205 _civicrm_store_values($contactFields, $values, $params);
206
207 if (isset($values['contact_type'])) {
208 /* we're an individual/household/org property */
209
210
211
212 $fields[$values['contact_type']] = CRM_Contact_DAO_Contact::fields();
213
214 _civicrm_store_values($fields[$values['contact_type']], $values, $params);
215 return TRUE;
216 }
217
218 if (isset($values['individual_prefix'])) {
219 if (CRM_Utils_Array::value('prefix_id', $params)) {
220 $prefixes = array();
221 $prefixes = CRM_Core_PseudoConstant::individualPrefix();
222 $params['prefix'] = $prefixes[$params['prefix_id']];
223 }
224 else {
225 $params['prefix'] = $values['individual_prefix'];
226 }
227 return TRUE;
228 }
229
230 if (isset($values['individual_suffix'])) {
231 if (CRM_Utils_Array::value('suffix_id', $params)) {
232 $suffixes = array();
233 $suffixes = CRM_Core_PseudoConstant::individualSuffix();
234 $params['suffix'] = $suffixes[$params['suffix_id']];
235 }
236 else {
237 $params['suffix'] = $values['individual_suffix'];
238 }
239 return TRUE;
240 }
241
242 //CRM-4575
243 if (isset($values['email_greeting'])) {
244 if (CRM_Utils_Array::value('email_greeting_id', $params)) {
245 $emailGreetings = array();
246 $emailGreetingFilter = array('contact_type' => CRM_Utils_Array::value('contact_type', $params),
247 'greeting_type' => 'email_greeting',
248 );
249 $emailGreetings = CRM_Core_PseudoConstant::greeting($emailGreetingFilter);
250 $params['email_greeting'] = $emailGreetings[$params['email_greeting_id']];
251 }
252 else {
253 $params['email_greeting'] = $values['email_greeting'];
254 }
255
256 return TRUE;
257 }
258
259 if (isset($values['postal_greeting'])) {
260 if (CRM_Utils_Array::value('postal_greeting_id', $params)) {
261 $postalGreetings = array();
262 $postalGreetingFilter = array('contact_type' => CRM_Utils_Array::value('contact_type', $params),
263 'greeting_type' => 'postal_greeting',
264 );
265 $postalGreetings = CRM_Core_PseudoConstant::greeting($postalGreetingFilter);
266 $params['postal_greeting'] = $postalGreetings[$params['postal_greeting_id']];
267 }
268 else {
269 $params['postal_greeting'] = $values['postal_greeting'];
270 }
271 return TRUE;
272 }
273
274 if (isset($values['addressee'])) {
275 if (CRM_Utils_Array::value('addressee_id', $params)) {
276 $addressee = array();
277 $addresseeFilter = array('contact_type' => CRM_Utils_Array::value('contact_type', $params),
278 'greeting_type' => 'addressee',
279 );
280 $addressee = CRM_Core_PseudoConstant::addressee($addresseeFilter);
281 $params['addressee'] = $addressee[$params['addressee_id']];
282 }
283 else {
284 $params['addressee'] = $values['addressee'];
285 }
286 return TRUE;
287 }
288
289 if (isset($values['gender'])) {
290 if (CRM_Utils_Array::value('gender_id', $params)) {
291 $genders = array();
292 $genders = CRM_Core_PseudoConstant::gender();
293 $params['gender'] = $genders[$params['gender_id']];
294 }
295 else {
296 $params['gender'] = $values['gender'];
297 }
298 return TRUE;
299 }
300
301 if (isset($values['preferred_communication_method'])) {
302 $comm = array();
303 $preffComm = array();
304 $pcm = array();
305 $pcm = array_change_key_case(array_flip(CRM_Core_PseudoConstant::pcm()), CASE_LOWER);
306
307 $preffComm = explode(',', $values['preferred_communication_method']);
308 foreach ($preffComm as $v) {
309 $v = strtolower(trim($v));
310 if (array_key_exists($v, $pcm)) {
311 $comm[$pcm[$v]] = 1;
312 }
313 }
314
315 $params['preferred_communication_method'] = $comm;
316 return TRUE;
317 }
318
319 //format the website params.
320 if (CRM_Utils_Array::value('url', $values)) {
321 static $websiteFields;
322 if (!is_array($websiteFields)) {
323 require_once 'CRM/Core/DAO/Website.php';
324 $websiteFields = CRM_Core_DAO_Website::fields();
325 }
326 if (!array_key_exists('website', $params) ||
327 !is_array($params['website'])
328 ) {
329 $params['website'] = array();
330 }
331
332 $websiteCount = count($params['website']);
333 _civicrm_store_values($websiteFields, $values,
334 $params['website'][++$websiteCount]
335 );
336
337 return TRUE;
338 }
339
340 // get the formatted location blocks into params - w/ 3.0 format, CRM-4605
341 if (CRM_Utils_Array::value('location_type_id', $values)) {
342 _civicrm_add_formatted_location_blocks($values, $params);
343 return TRUE;
344 }
345
346 if (isset($values['note'])) {
347 /* add a note field */
348
349
350 if (!isset($params['note'])) {
351 $params['note'] = array();
352 }
353 $noteBlock = count($params['note']) + 1;
354
355 $params['note'][$noteBlock] = array();
356 if (!isset($fields['Note'])) {
357 $fields['Note'] = CRM_Core_DAO_Note::fields();
358 }
359
360 // get the current logged in civicrm user
361 $session = CRM_Core_Session::singleton();
362 $userID = $session->get('userID');
363
364 if ($userID) {
365 $values['contact_id'] = $userID;
366 }
367
368 _civicrm_store_values($fields['Note'], $values, $params['note'][$noteBlock]);
369
370 return TRUE;
371 }
372
373 /* Check for custom field values */
374
375
376 if (!CRM_Utils_Array::value('custom', $fields)) {
377 $fields['custom'] = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $values));
378 }
379
380 foreach ($values as $key => $value) {
381 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
382 /* check if it's a valid custom field id */
383
384
385 if (!array_key_exists($customFieldID, $fields['custom'])) {
386 return civicrm_create_error('Invalid custom field ID');
387 }
388 else {
389 $params[$key] = $value;
390 }
391 }
392 }
393}
394
395/**
396 * This function format location blocks w/ v3.0 format.
397 *
398 * @param array $values The variable(s) to be added
399 * @param array $params The structured parameter list
400 *
401 * @return bool
402 * @access public
403 */
404function _civicrm_add_formatted_location_blocks(&$values, &$params) {
405 static $fields = NULL;
406 if ($fields == NULL) {
407 $fields = array();
408 }
409
410 foreach (array(
411 'Phone', 'Email', 'IM', 'OpenID') as $block) {
412 $name = strtolower($block);
413 if (!array_key_exists($name, $values)) {
414 continue;
415 }
416
417 // block present in value array.
418 if (!array_key_exists($name, $params) || !is_array($params[$name])) {
419 $params[$name] = array();
420 }
421
422 if (!array_key_exists($block, $fields)) {
423 require_once (str_replace('_', DIRECTORY_SEPARATOR, "CRM_Core_DAO_" . $block) . ".php");
424 eval('$fields[$block] =& CRM_Core_DAO_' . $block . '::fields( );');
425 }
426
427 $blockCnt = count($params[$name]);
428
429 // copy value to dao field name.
430 if ($name == 'im') {
431 $values['name'] = $values[$name];
432 }
433
434 _civicrm_store_values($fields[$block], $values,
435 $params[$name][++$blockCnt]
436 );
437
438 if (!CRM_Utils_Array::value('id', $params) && ($blockCnt == 1)) {
439 $params[$name][$blockCnt]['is_primary'] = TRUE;
440 }
441
442 // we only process single block at a time.
443 return TRUE;
444 }
445
446 // handle address fields.
447 if (!array_key_exists('address', $params) || !is_array($params['address'])) {
448 $params['address'] = array();
449 }
450
451 $addressCnt = 1;
452 foreach ($params['address'] as $cnt => $addressBlock) {
453 if (CRM_Utils_Array::value('location_type_id', $values) ==
454 CRM_Utils_Array::value('location_type_id', $addressBlock)
455 ) {
456 $addressCnt = $cnt;
457 break;
458 }
459 $addressCnt++;
460 }
461
462 if (!array_key_exists('Address', $fields)) {
463 require_once 'CRM/Core/DAO/Address.php';
464 $fields['Address'] = CRM_Core_DAO_Address::fields();
465 }
466 _civicrm_store_values($fields['Address'], $values, $params['address'][$addressCnt]);
467
468 $addressFields = array(
469 'county', 'country', 'state_province',
470 'supplemental_address_1', 'supplemental_address_2',
471 'StateProvince.name',
472 );
473
474 foreach ($addressFields as $field) {
475 if (array_key_exists($field, $values)) {
476 if (!array_key_exists('address', $params)) {
477 $params['address'] = array();
478 }
479 $params['address'][$addressCnt][$field] = $values[$field];
480 }
481 }
482 //Handle Address Custom data
483 $fields['address_custom'] = CRM_Core_BAO_CustomField::getFields('Address');
484 foreach ($values as $key => $value) {
485 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
486 /* check if it's a valid custom field id */
487
488
489 if (array_key_exists($customFieldID, $fields['address_custom'])) {
490 $type = $fields['address_custom'][$customFieldID]['html_type'];
491 _civicrm_add_custom_formatted_param($customFieldID, $key, $value, $params['address'][$addressCnt], $type);
492 }
493 else {
494 return civicrm_create_error('Invalid custom field ID');
495 }
496 }
497 }
498
499 if ($addressCnt == 1) {
500
501 $params['address'][$addressCnt]['is_primary'] = TRUE;
502 }
503
504 return TRUE;
505}
506
507/**
508 * Check a formatted parameter list for required fields. Note that this
509 * function does no validation or dupe checking.
510 *
511 * @param array $params Structured parameter list (as in crm_format_params)
512 *
513 * @return bool|CRM_core_Error Parameter list has all required fields
514 * @access public
515 */
516function _civicrm_required_formatted_contact(&$params) {
517
518 if (!isset($params['contact_type'])) {
519 return civicrm_create_error('No contact type specified');
520 }
521
522 switch ($params['contact_type']) {
523 case 'Individual':
524 if (isset($params['first_name']) && isset($params['last_name'])) {
525 return civicrm_create_success(TRUE);
526 }
527
528 if (array_key_exists('email', $params) &&
529 is_array($params['email']) &&
530 !CRM_Utils_System::isNull($params['email'])
531 ) {
532 return civicrm_create_success(TRUE);
533 }
534 break;
535
536 case 'Household':
537 if (isset($params['household_name'])) {
538 return civicrm_create_success(TRUE);
539 }
540 break;
541
542 case 'Organization':
543 if (isset($params['organization_name'])) {
544 return civicrm_create_success(TRUE);
545 }
546 break;
547
548 default:
549 return civicrm_create_error('Invalid Contact Type: ' . $params['contact_type']);
550 }
551
552 return civicrm_create_error('Missing required fields');
553}
554
555/**
556 *
557 * @param array $params
558 * @param int $dedupeRuleGroupID - the dedupe rule ID to use if present
559 *
560 */
561function _civicrm_duplicate_formatted_contact(&$params,
562 $dedupeRuleGroupID = NULL
563) {
564 $id = CRM_Utils_Array::value('id', $params);
565 $externalId = CRM_Utils_Array::value('external_identifier', $params);
566 if ($id || $externalId) {
567 $contact = new CRM_Contact_DAO_Contact();
568
569 $contact->id = $id;
570 $contact->external_identifier = $externalId;
571
572 if ($contact->find(TRUE)) {
573 if ($params['contact_type'] != $contact->contact_type) {
574 return civicrm_create_error("Mismatched contact IDs OR Mismatched contact Types");
575 }
576
577 $error = CRM_Core_Error::createError("Found matching contacts: $contact->id",
578 CRM_Core_Error::DUPLICATE_CONTACT,
579 'Fatal', $contact->id
580 );
581 return civicrm_create_error($error->pop());
582 }
583 }
584 else {
585 require_once 'CRM/Dedupe/Finder.php';
586 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
587 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams,
588 $params['contact_type'],
589 'Strict',
590 array(),
591 $dedupeRuleGroupID
592 );
593
594 if (!empty($ids)) {
595 $ids = implode(',', $ids);
596 $error = CRM_Core_Error::createError("Found matching contacts: $ids",
597 CRM_Core_Error::DUPLICATE_CONTACT,
598 'Fatal', $ids
599 );
600 return civicrm_create_error($error->pop());
601 }
602 }
603 return civicrm_create_success(TRUE);
604}
605
606/**
607 * Validate a formatted contact parameter list.
608 *
609 * @param array $params Structured parameter list (as in crm_format_params)
610 *
611 * @return bool|CRM_Core_Error
612 * @access public
613 */
614function _civicrm_validate_formatted_contact(&$params) {
615 /* Look for offending email addresses */
616
617
618 if (array_key_exists('email', $params)) {
619 foreach ($params['email'] as $count => $values) {
620 if (!is_array($values)) {
621 continue;
622 }
623 if ($email = CRM_Utils_Array::value('email', $values)) {
624 //validate each email
625 if (!CRM_Utils_Rule::email($email)) {
626 return civicrm_create_error('No valid email address');
627 }
628
629 //check for loc type id.
630 if (!CRM_Utils_Array::value('location_type_id', $values)) {
631 return civicrm_create_error('Location Type Id missing.');
632 }
633 }
634 }
635 }
636
637 /* Validate custom data fields */
638
639
640 if (array_key_exists('custom', $params) && is_array($params['custom'])) {
641 foreach ($params['custom'] as $key => $custom) {
642 if (is_array($custom)) {
643 $valid = CRM_Core_BAO_CustomValue::typecheck(
644 $custom['type'], $custom['value']
645 );
646 if (!$valid) {
647 return civicrm_create_error('Invalid value for custom field \'' .
648 $custom['name'] . '\''
649 );
650 }
651 if ($custom['type'] == 'Date') {
652 $params['custom'][$key]['value'] = str_replace('-', '', $params['custom'][$key]['value']);
653 }
654 }
655 }
656 }
657
658 return civicrm_create_success(TRUE);
659}
660
661/**
662 *
663 * @param array $params
664 * @param array $values
665 * @param string $extends entity that this custom field extends (e.g. contribution, event, contact)
666 * @param string $entityId ID of entity per $extends
667 */
668function _civicrm_custom_format_params(&$params, &$values, $extends, $entityId = NULL) {
669 $values['custom'] = array();
670
671 require_once 'CRM/Core/BAO/CustomField.php';
672 foreach ($params as $key => $value) {
673 list($customFieldID, $customValueID) = CRM_Core_BAO_CustomField::getKeyID($key, TRUE);
674 if ($customFieldID) {
675 CRM_Core_BAO_CustomField::formatCustomField($customFieldID, $values['custom'],
676 $value, $extends, $customValueID, $entityId
677 );
678 }
679 }
680}
681
682/**
683 * This function ensures that we have the right input parameters
684 *
685 * We also need to make sure we run all the form rules on the params list
686 * to ensure that the params are valid
687 *
688 * @param array $params Associative array of property name/value
689 * pairs to insert in new history.
690 *
691 *
692 * @return bool true if success false otherwise
693 * @access public
694 */
695function _civicrm_check_required_fields(&$params, $daoName, $throwException = FALSE) {
696 if (isset($params['extends'])) {
697 if (($params['extends'] == 'Activity' ||
698 $params['extends'] == 'Phonecall' ||
699 $params['extends'] == 'Meeting' ||
700 $params['extends'] == 'Group' ||
701 $params['extends'] == 'Contribution'
702 ) &&
703 ($params['style'] == 'Tab')
704 ) {
705 return civicrm_create_error(ts("Can not create Custom Group in Tab for " . $params['extends']));
706 }
707 }
708
709 require_once (str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php");
710
711 $dao = new $daoName();
712 $fields = $dao->fields();
713
714 $missing = array();
715 foreach ($fields as $k => $v) {
716 if ($k == 'id') {
717 continue;
718 }
719
720 if (isset($v['required'])) {
721 if ($v['required'] && !(isset($params[$k]))) {
722 $missing[] = $k;
723 }
724 }
725 }
726
727 if (!empty($missing)) {
728 if ($throwException) {
729 throw new Exception("Required fields " . implode(',', $missing) . " for $daoName are not found");
730 }
731 return civicrm_create_error(ts("Required fields " . implode(',', $missing) . " for $daoName are not found"));
732 }
733
734 return TRUE;
735}
736
737/**
738 * take the input parameter list as specified in the data model and
739 * convert it into the same format that we use in QF and BAO object
740 *
741 * @param array $params Associative array of property name/value
742 * pairs to insert in new contact.
743 * @param array $values The reformatted properties that we can use internally
744 *
745 * @param array $create Is the formatted Values array going to
746 * be used for CRM_Event_BAO_Participant:create()
747 *
748 * @return array|CRM_Error
749 * @access public
750 */
751function _civicrm_participant_formatted_param(&$params, &$values, $create = FALSE) {
752 $fields = CRM_Event_DAO_Participant::fields();
753 _civicrm_store_values($fields, $params, $values);
754
755 require_once 'CRM/Core/OptionGroup.php';
756 $customFields = CRM_Core_BAO_CustomField::getFields('Participant');
757
758 foreach ($params as $key => $value) {
759 // ignore empty values or empty arrays etc
760 if (CRM_Utils_System::isNull($value)) {
761 continue;
762 }
763
764 //Handling Custom Data
765 _civicrm_generic_handle_custom_data($key, $value, $values, $customFields);
766
767 switch ($key) {
768 case 'participant_contact_id':
769 if (!CRM_Utils_Rule::integer($value)) {
770 return civicrm_create_error("contact_id not valid: $value");
771 }
772 $dao = new CRM_Core_DAO();
773 $qParams = array();
774 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value",
775 $qParams
776 );
777 if (!$svq) {
778 return civicrm_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
779 }
780 $values['contact_id'] = $values['participant_contact_id'];
781 unset($values['participant_contact_id']);
782 break;
783
784 case 'participant_register_date':
785 if (!CRM_Utils_Rule::date($value)) {
786 return civicrm_create_error("$key not a valid date: $value");
787 }
788 break;
789
790 case 'event_title':
791 $id = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $value, 'id', 'title');
792 $values['event_id'] = $id;
793 break;
794
795 case 'event_id':
796 if (!CRM_Utils_Rule::integer($value)) {
797 return civicrm_create_error("Event ID is not valid: $value");
798 }
799 $dao = new CRM_Core_DAO();
800 $qParams = array();
801 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_event WHERE id = $value",
802 $qParams
803 );
804 if (!$svq) {
805 return civicrm_create_error("Invalid Event ID: There is no event record with event_id = $value.");
806 }
807 break;
808
809 case 'participant_status':
810 $values['status_id'] = $values['participant_status_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantStatusType', $value, 'id', 'label');
811 break;
812
813 case 'participant_status_id':
814 if ((int) $value) {
815 $values['status_id'] = $values[$key] = $value;
816 }
817 else {
818 $id = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantStatusType', $value, 'id', 'label');
819 $values['status_id'] = $values[$key] = $id;
820 }
821 break;
822
823 case 'participant_role_id':
824 case 'participant_role':
825 $role = CRM_Event_PseudoConstant::participantRole();
826 $participantRoles = explode(",", $value);
827 foreach ($participantRoles as $k => $v) {
828 $v = trim($v);
829 if ($key == 'participant_role') {
830 $participantRoles[$k] = CRM_Utils_Array::key($v, $role);
831 }
832 else {
833 $participantRoles[$k] = $v;
834 }
835 }
836 require_once 'CRM/Core/DAO.php';
837 $values['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $participantRoles);
838 unset($values[$key]);
839 break;
840
841 default:
842 break;
843 }
844 }
845
846 if (array_key_exists('participant_note', $params)) {
847 $values['participant_note'] = $params['participant_note'];
848 }
849
850 if ($create) {
851 // CRM_Event_BAO_Participant::create() handles register_date,
852 // status_id and source. So, if $values contains
853 // participant_register_date, participant_status_id or participant_source,
854 // convert it to register_date, status_id or source
855 $changes = array(
856 'participant_register_date' => 'register_date',
857 'participant_source' => 'source',
858 'participant_status_id' => 'status_id',
859 'participant_role_id' => 'role_id',
860 'participant_fee_level' => 'fee_level',
861 'participant_fee_amount' => 'fee_amount',
862 'participant_id' => 'id',
863 );
864
865 foreach ($changes as $orgVal => $changeVal) {
866 if (isset($values[$orgVal])) {
867 $values[$changeVal] = $values[$orgVal];
868 unset($values[$orgVal]);
869 }
870 }
871 }
872
873 return NULL;
874}
875
876/**
877 * take the input parameter list as specified in the data model and
878 * convert it into the same format that we use in QF and BAO object
879 *
880 * @param array $params Associative array of property name/value
881 * pairs to insert in new contact.
882 * @param array $values The reformatted properties that we can use internally
883 * '
884 *
885 * @return array|CRM_Error
886 * @access public
887 */
888function _civicrm_contribute_formatted_param(&$params, &$values, $create = FALSE) {
889 // copy all the contribution fields as is
890
891 $fields = CRM_Contribute_DAO_Contribution::fields();
892
893 _civicrm_store_values($fields, $params, $values);
894
895 require_once 'CRM/Core/OptionGroup.php';
896 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
897
898 foreach ($params as $key => $value) {
899 // ignore empty values or empty arrays etc
900 if (CRM_Utils_System::isNull($value)) {
901 continue;
902 }
903
904 //Handling Custom Data
905 _civicrm_generic_handle_custom_data($key, $value, $values, $customFields);
906
907 switch ($key) {
908 case 'contribution_contact_id':
909 if (!CRM_Utils_Rule::integer($value)) {
910 return civicrm_create_error("contact_id not valid: $value");
911 }
912 $dao = new CRM_Core_DAO();
913 $qParams = array();
914 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value",
915 $qParams
916 );
917 if (!$svq) {
918 return civicrm_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
919 }
920
921 $values['contact_id'] = $values['contribution_contact_id'];
922 unset($values['contribution_contact_id']);
923 break;
924
925 case 'contact_type':
926 //import contribution record according to select contact type
927 require_once 'CRM/Contact/DAO/Contact.php';
928 $contactType = new CRM_Contact_DAO_Contact();
929 //when insert mode check contact id or external identifire
930 if ($params['contribution_contact_id'] || $params['external_identifier']) {
931 if ($params['contribution_contact_id']) {
932 $contactType->id = $params['contribution_contact_id'];
933 }
934 elseif ($params['external_identifier']) {
935 $contactType->external_identifier = $params['external_identifier'];
936 }
937 if ($contactType->find(TRUE)) {
938 if ($params['contact_type'] != $contactType->contact_type) {
939 return civicrm_create_error("Contact Type is wrong: $contactType->contact_type");
940 }
941 }
942 }
943 elseif ($params['contribution_id'] || $params['trxn_id'] || $params['invoice_id']) {
944 //when update mode check contribution id or trxn id or
945 //invoice id
946 $contactId = new CRM_Contribute_DAO_Contribution();
947 if ($params['contribution_id']) {
948 $contactId->id = $params['contribution_id'];
949 }
950 elseif ($params['trxn_id']) {
951 $contactId->trxn_id = $params['trxn_id'];
952 }
953 elseif ($params['invoice_id']) {
954 $contactId->invoice_id = $params['invoice_id'];
955 }
956 if ($contactId->find(TRUE)) {
957 $contactType->id = $contactId->contact_id;
958 if ($contactType->find(TRUE)) {
959 if ($params['contact_type'] != $contactType->contact_type) {
960 return civicrm_create_error("Contact Type is wrong: $contactType->contact_type");
961 }
962 }
963 }
964 }
965 break;
966
967 case 'receive_date':
968 case 'cancel_date':
969 case 'receipt_date':
970 case 'thankyou_date':
971 if (!CRM_Utils_Rule::date($value)) {
972 return civicrm_create_error("$key not a valid date: $value");
973 }
974 break;
975
976 case 'non_deductible_amount':
977 case 'total_amount':
978 case 'fee_amount':
979 case 'net_amount':
980 if (!CRM_Utils_Rule::money($value)) {
981 return civicrm_create_error("$key not a valid amount: $value");
982 }
983 break;
984
985 case 'currency':
986 if (!CRM_Utils_Rule::currencyCode($value)) {
987 return civicrm_create_error("currency not a valid code: $value");
988 }
989 break;
990
991 case 'financial_type':
992 require_once 'CRM/Contribute/PseudoConstant.php';
993 $contriTypes = CRM_Contribute_PseudoConstant::financialType( );
994 foreach ($contriTypes as $val => $type) {
995 if (strtolower($value) == strtolower($type)) {
996 $values['financial_type_id'] = $val;
997 break;
998 }
999 }
1000 if (!CRM_Utils_Array::value('financial_type_id', $values)) {
1001 return civicrm_create_error("Financial Type is not valid: $value");
1002 }
1003 break;
1004
1005 case 'payment_instrument':
1006 require_once 'CRM/Core/OptionGroup.php';
1007 $values['payment_instrument_id'] = CRM_Core_OptionGroup::getValue('payment_instrument', $value);
1008 if (!CRM_Utils_Array::value('payment_instrument_id', $values)) {
1009 return civicrm_create_error("Payment Instrument is not valid: $value");
1010 }
1011 break;
1012
1013 case 'contribution_status_id':
1014 require_once 'CRM/Core/OptionGroup.php';
1015 if (!$values['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', $value)) {
1016 return civicrm_create_error("Contribution Status is not valid: $value");
1017 }
1018 break;
1019
1020 case 'honor_type_id':
1021 require_once 'CRM/Core/OptionGroup.php';
1022 $values['honor_type_id'] = CRM_Core_OptionGroup::getValue('honor_type', $value);
1023 if (!CRM_Utils_Array::value('honor_type_id', $values)) {
1024 return civicrm_create_error("Honor Type is not valid: $value");
1025 }
1026 break;
1027
1028 case 'soft_credit':
1029 //import contribution record according to select contact type
1030
1031 // validate contact id and external identifier.
1032 $contactId = CRM_Utils_Array::value('contact_id', $params['soft_credit']);
1033 $externalId = CRM_Utils_Array::value('external_identifier', $params['soft_credit']);
1034 if ($contactId || $externalId) {
1035 require_once 'CRM/Contact/DAO/Contact.php';
1036 $contact = new CRM_Contact_DAO_Contact();
1037 $contact->id = $contactId;
1038 $contact->external_identifier = $externalId;
1039
1040 $errorMsg = NULL;
1041 if (!$contact->find(TRUE)) {
1042 $errorMsg = ts("No match found for specified Soft Credit contact data. Row was skipped.");
1043 }
1044 elseif ($params['contact_type'] != $contact->contact_type) {
1045 $errorMsg = ts("Soft Credit Contact Type is wrong: %1", array(1 => $contact->contact_type));
1046 }
1047
1048 if ($errorMsg) {
1049 return civicrm_create_error($errorMsg, 'soft_credit');
1050 }
1051
1052 // finally get soft credit contact id.
1053 $values['soft_credit_to'] = $contact->id;
1054 }
1055 else {
1056 // get the contact id from dupicate contact rule, if more than one contact is returned
1057 // we should return error, since current interface allows only one-one mapping
1058
1059 $softParams = $params['soft_credit'];
1060 $softParams['contact_type'] = $params['contact_type'];
1061
1062 $error = _civicrm_duplicate_formatted_contact($softParams);
1063
1064 if (isset($error['error_message']['params'][0])) {
1065 $matchedIDs = explode(',', $error['error_message']['params'][0]);
1066
1067 // check if only one contact is found
1068 if (count($matchedIDs) > 1) {
1069 return civicrm_create_error($error['error_message']['message'], 'soft_credit');
1070 }
1071 else {
1072 $values['soft_credit_to'] = $matchedIDs[0];
1073 }
1074 }
1075 else {
1076 return civicrm_create_error('No match found for specified Soft Credit contact data. Row was skipped.', 'soft_credit');
1077 }
1078 }
1079 break;
1080
1081 case 'pledge_payment':
1082 case 'pledge_id':
1083
1084 //giving respect to pledge_payment flag.
1085 if (!CRM_Utils_Array::value('pledge_payment', $params)) {
1086 continue;
1087 }
1088
1089 //get total amount of from import fields
1090 $totalAmount = CRM_Utils_Array::value('total_amount', $params);
1091
1092 $onDuplicate = CRM_Utils_Array::value('onDuplicate', $params);
1093
1094 //we need to get contact id $contributionContactID to
1095 //retrieve pledge details as well as to validate pledge ID
1096
1097 //first need to check for update mode
1098 if ($onDuplicate == CRM_Contribute_Import_Parser::DUPLICATE_UPDATE &&
1099 ($params['contribution_id'] || $params['trxn_id'] || $params['invoice_id'])
1100 ) {
1101 $contribution = new CRM_Contribute_DAO_Contribution();
1102 if ($params['contribution_id']) {
1103 $contribution->id = $params['contribution_id'];
1104 }
1105 elseif ($params['trxn_id']) {
1106 $contribution->trxn_id = $params['trxn_id'];
1107 }
1108 elseif ($params['invoice_id']) {
1109 $contribution->invoice_id = $params['invoice_id'];
1110 }
1111
1112 if ($contribution->find(TRUE)) {
1113 $contributionContactID = $contribution->contact_id;
1114 if (!$totalAmount) {
1115 $totalAmount = $contribution->total_amount;
1116 }
1117 }
1118 else {
1119 return civicrm_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment');
1120 }
1121 }
1122 else {
1123 // first get the contact id for given contribution record.
1124 if (CRM_Utils_Array::value('contribution_contact_id', $params)) {
1125 $contributionContactID = $params['contribution_contact_id'];
1126 }
1127 elseif (CRM_Utils_Array::value('external_identifier', $params)) {
1128 require_once 'CRM/Contact/DAO/Contact.php';
1129 $contact = new CRM_Contact_DAO_Contact();
1130 $contact->external_identifier = $params['external_identifier'];
1131 if ($contact->find(TRUE)) {
1132 $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $contact->id;
1133 }
1134 else {
1135 return civicrm_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment');
1136 }
1137 }
1138 else {
1139 // we need to get contribution contact using de dupe
1140 $error = civicrm_check_contact_dedupe($params);
1141
1142 if (isset($error['error_message']['params'][0])) {
1143 $matchedIDs = explode(',', $error['error_message']['params'][0]);
1144
1145 // check if only one contact is found
1146 if (count($matchedIDs) > 1) {
1147 return civicrm_create_error($error['error_message']['message'], 'pledge_payment');
1148 }
1149 else {
1150 $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $matchedIDs[0];
1151 }
1152 }
1153 else {
1154 return civicrm_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment');
1155 }
1156 }
1157 }
1158
1159 if (CRM_Utils_Array::value('pledge_id', $params)) {
1160 if (CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $params['pledge_id'], 'contact_id') != $contributionContactID) {
1161 return civicrm_create_error('Invalid Pledge ID provided. Contribution row was skipped.', 'pledge_payment');
1162 }
1163 $values['pledge_id'] = $params['pledge_id'];
1164 }
1165 else {
1166 //check if there are any pledge related to this contact, with payments pending or in progress
1167 require_once 'CRM/Pledge/BAO/Pledge.php';
1168 $pledgeDetails = CRM_Pledge_BAO_Pledge::getContactPledges($contributionContactID);
1169
1170 if (empty($pledgeDetails)) {
1171 return civicrm_create_error('No open pledges found for this contact. Contribution row was skipped.', 'pledge_payment');
1172 }
1173 elseif (count($pledgeDetails) > 1) {
1174 return civicrm_create_error('This contact has more than one open pledge. Unable to determine which pledge to apply the contribution to. Contribution row was skipped.', 'pledge_payment');
1175 }
1176
1177 // this mean we have only one pending / in progress pledge
1178 $values['pledge_id'] = $pledgeDetails[0];
1179 }
1180
1181 //we need to check if oldest payment amount equal to contribution amount
1182 require_once 'CRM/Pledge/BAO/PledgePayment.php';
1183 $pledgePaymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($values['pledge_id']);
1184
1185 if ($pledgePaymentDetails['amount'] == $totalAmount) {
1186 $values['pledge_payment_id'] = $pledgePaymentDetails['id'];
1187 }
1188 else {
1189 return civicrm_create_error('Contribution and Pledge Payment amount mismatch for this record. Contribution row was skipped.', 'pledge_payment');
1190 }
1191 break;
1192
1193 default:
1194 break;
1195 }
1196 }
1197
1198 if (array_key_exists('note', $params)) {
1199 $values['note'] = $params['note'];
1200 }
1201
1202 if ($create) {
1203 // CRM_Contribute_BAO_Contribution::add() handles contribution_source
1204 // So, if $values contains contribution_source, convert it to source
1205 $changes = array('contribution_source' => 'source');
1206
1207 foreach ($changes as $orgVal => $changeVal) {
1208 if (isset($values[$orgVal])) {
1209 $values[$changeVal] = $values[$orgVal];
1210 unset($values[$orgVal]);
1211 }
1212 }
1213 }
1214
1215 return NULL;
1216}
1217
1218/**
1219 * take the input parameter list as specified in the data model and
1220 * convert it into the same format that we use in QF and BAO object
1221 *
1222 * @todo shouldn't it be moved to Membership.php?
1223 *
1224 * @param array $params Associative array of property name/value
1225 * pairs to insert in new contact.
1226 * @param array $values The reformatted properties that we can use internally
1227 *
1228 * @param array $create Is the formatted Values array going to
1229 * be used for CRM_Member_BAO_Membership:create()
1230 *
1231 * @return array|CRM_Error
1232 * @access public
1233 */
1234function _civicrm_membership_formatted_param(&$params, &$values, $create = FALSE) {
1235 require_once "CRM/Member/DAO/Membership.php";
1236 $fields = CRM_Member_DAO_Membership::fields();
1237
1238 _civicrm_store_values($fields, $params, $values);
1239
1240 require_once 'CRM/Core/OptionGroup.php';
1241 $customFields = CRM_Core_BAO_CustomField::getFields('Membership');
1242
1243 foreach ($params as $key => $value) {
1244 // ignore empty values or empty arrays etc
1245 if (CRM_Utils_System::isNull($value)) {
1246 continue;
1247 }
1248
1249 //Handling Custom Data
1250 _civicrm_generic_handle_custom_data($key, $value, $values, $customFields);
1251
1252 switch ($key) {
1253 case 'membership_contact_id':
1254 if (!CRM_Utils_Rule::integer($value)) {
1255 return civicrm_create_error("contact_id not valid: $value");
1256 }
1257 $dao = new CRM_Core_DAO();
1258 $qParams = array();
1259 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value",
1260 $qParams
1261 );
1262 if (!$svq) {
1263 return civicrm_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
1264 }
1265 $values['contact_id'] = $values['membership_contact_id'];
1266 unset($values['membership_contact_id']);
1267 break;
1268
1269 case 'join_date':
1270 case 'membership_start_date':
1271 case 'membership_end_date':
1272 if (!CRM_Utils_Rule::date($value)) {
1273 return civicrm_create_error("$key not a valid date: $value");
1274 }
1275 break;
1276
1277 case 'membership_type_id':
1278 $id = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_MembershipType", $value, 'id', 'name');
1279 $values[$key] = $id;
1280 break;
1281
1282 case 'status_id':
1283 $id = CRM_Core_DAO::getFieldValue("CRM_Member_DAO_MembershipStatus", $value, 'id', 'name');
1284 $values[$key] = $id;
1285 break;
1286
1287 case 'member_is_test':
1288 $values['is_test'] = CRM_Utils_Array::value($key, $params, FALSE);
1289 unset($values['member_is_test']);
1290 break;
1291
1292 default:
1293 break;
1294 }
1295 }
1296
1297 if ($create) {
1298 // CRM_Member_BAO_Membership::create() handles membership_start_date,
1299 // membership_end_date and membership_source. So, if $values contains
1300 // membership_start_date, membership_end_date or membership_source,
1301 // convert it to start_date, end_date or source
1302 $changes = array(
1303 'membership_start_date' => 'start_date',
1304 'membership_end_date' => 'end_date',
1305 'membership_source' => 'source',
1306 );
1307
1308 foreach ($changes as $orgVal => $changeVal) {
1309 if (isset($values[$orgVal])) {
1310 $values[$changeVal] = $values[$orgVal];
1311 unset($values[$orgVal]);
1312 }
1313 }
1314 }
1315
1316 return NULL;
1317}
1318
1319/**
1320 * take the input parameter list as specified in the data model and
1321 * convert it into the same format that we use in QF and BAO object
1322 *
1323 * @param array $params Associative array of property name/value
1324 * pairs to insert in new contact.
1325 * @param array $values The reformatted properties that we can use internally
1326 *
1327 * @param array $create Is the formatted Values array going to
1328 * be used for CRM_Activity_BAO_Activity::create()
1329 *
1330 * @return array|CRM_Error
1331 * @access public
1332 */
1333function _civicrm_activity_formatted_param(&$params, &$values, $create = FALSE) {
1334 $fields = CRM_Activity_DAO_Activity::fields();
1335 _civicrm_store_values($fields, $params, $values);
1336
1337 require_once 'CRM/Core/OptionGroup.php';
1338 $customFields = CRM_Core_BAO_CustomField::getFields('Activity');
1339
1340 foreach ($params as $key => $value) {
1341 // ignore empty values or empty arrays etc
1342 if (CRM_Utils_System::isNull($value)) {
1343 continue;
1344 }
1345
1346 //Handling Custom Data
1347 _civicrm_generic_handle_custom_data($key, $value, $values, $customFields);
1348
1349 if ($key == 'target_contact_id') {
1350 if (!CRM_Utils_Rule::integer($value)) {
1351 return civicrm_create_error("contact_id not valid: $value");
1352 }
1353 $contactID = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value");
1354 if (!$contactID) {
1355 return civicrm_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
1356 }
1357 }
1358 }
1359 return NULL;
1360}
1361
1362/**
1363 * Function to check duplicate contacts based on de-deupe parameters
1364 */
1365function civicrm_check_contact_dedupe(&$params) {
1366 static $cIndieFields = NULL;
1367 static $defaultLocationId = NULL;
1368
1369 $contactType = $params['contact_type'];
1370 if ($cIndieFields == NULL) {
1371 require_once 'CRM/Contact/BAO/Contact.php';
1372 $cTempIndieFields = CRM_Contact_BAO_Contact::importableFields($contactType);
1373 $cIndieFields = $cTempIndieFields;
1374
1375 require_once "CRM/Core/BAO/LocationType.php";
1376 $defaultLocation = CRM_Core_BAO_LocationType::getDefault();
1377
1378 //set the value to default location id else set to 1
1379 if (!$defaultLocationId = (int)$defaultLocation->id) {
1380 $defaultLocationId = 1;
1381 }
1382 }
1383
1384 require_once 'CRM/Contact/BAO/Query.php';
1385 $locationFields = CRM_Contact_BAO_Query::$_locationSpecificFields;
1386
1387 $contactFormatted = array();
1388 foreach ($params as $key => $field) {
1389 if ($field == NULL || $field === '') {
1390 continue;
1391 }
1392 if (is_array($field)) {
1393 foreach ($field as $value) {
1394 $break = FALSE;
1395 if (is_array($value)) {
1396 foreach ($value as $name => $testForEmpty) {
1397 if ($name !== 'phone_type' &&
1398 ($testForEmpty === '' || $testForEmpty == NULL)
1399 ) {
1400 $break = TRUE;
1401 break;
1402 }
1403 }
1404 }
1405 else {
1406 $break = TRUE;
1407 }
1408 if (!$break) {
1409 _civicrm_add_formatted_param($value, $contactFormatted);
1410 }
1411 }
1412 continue;
1413 }
1414
1415 $value = array($key => $field);
1416
1417 // check if location related field, then we need to add primary location type
1418 if (in_array($key, $locationFields)) {
1419 $value['location_type_id'] = $defaultLocationId;
1420 }
1421 elseif (array_key_exists($key, $cIndieFields)) {
1422 $value['contact_type'] = $contactType;
1423 }
1424
1425 _civicrm_add_formatted_param($value, $contactFormatted);
1426 }
1427
1428 $contactFormatted['contact_type'] = $contactType;
1429
1430 return _civicrm_duplicate_formatted_contact($contactFormatted);
1431}
1432
1433/**
1434 * Check permissions for a given API call.
1435 *
1436 * @param $api string API method being called
1437 * @param $params array params of the API call
1438 * @param $throw bool whether to throw exception instead of returning false
1439 *
1440 * @return bool whether the current API user has the permission to make the call
1441 */
1442function civicrm_api_check_permission($api, $params, $throw = FALSE) {
1443 // return early if we’re to skip the permission check or if it’s unset
1444 if (!isset($params['check_permissions']) or !$params['check_permissions']) {
1445 return TRUE;
1446 }
1447
1448 require_once 'CRM/Core/Permission.php';
1449 $requirements = array(
1450 'civicrm_contact_create' => array('access CiviCRM', 'add contacts'),
1451 'civicrm_contact_update' => array('access CiviCRM', 'add contacts'),
1452 'civicrm_event_create' => array('access CiviEvent'),
1453 );
1454 foreach ($requirements[$api] as $perm) {
1455 if (!CRM_Core_Permission::check($perm)) {
1456 if ($throw) {
1457 throw new Exception("API permission check failed for $api call; missing permission: $perm.");
1458 }
1459 else {
1460 return FALSE;
1461 }
1462 }
1463 }
1464 return TRUE;
1465}
1466
1467
1468// at some point we should unify this with
1469// _civicrm_custom_format_params
1470// seems like there are some differences that i dont understand, so taking the first
1471// step in a cleanup: CRM-7337
1472function _civicrm_generic_handle_custom_data($key, $value, &$values, &$customFields) {
1473
1474 //Handling Custom Data
1475 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
1476 $values[$key] = $value;
1477 $type = $customFields[$customFieldID]['html_type'];
1478 if ($type == 'CheckBox' || $type == 'Multi-Select') {
1479 $mulValues = explode(',', $value);
1480 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
1481 $values[$key] = array();
1482 foreach ($mulValues as $v1) {
1483 foreach ($customOption as $customValueID => $customLabel) {
1484 $customValue = $customLabel['value'];
1485 if ((strtolower(trim($customLabel['label'])) == strtolower(trim($v1))) ||
1486 (strtolower(trim($customValue)) == strtolower(trim($v1)))
1487 ) {
1488 if ($type == 'CheckBox') {
1489 $values[$key][$customValue] = 1;
1490 }
1491 else {
1492 $values[$key][] = $customValue;
1493 }
1494 }
1495 }
1496 }
1497 }
1498 elseif ($type == 'Select' || $type == 'Radio') {
1499 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
1500 foreach ($customOption as $customFldID => $customValue) {
1501 $val = CRM_Utils_Array::value('value', $customValue);
1502 $label = CRM_Utils_Array::value('label', $customValue);
1503 $label = strtolower($label);
1504 $value = strtolower(trim($value));
1505 if (($value == $label) || ($value == strtolower($val))) {
1506 $values[$key] = $val;
1507 }
1508 }
1509 }
1510 }
1511}
1512
1513function _civicrm_add_custom_formatted_param($customFieldID, $key, $field, &$formatted, $type) {
1514 require_once 'CRM/Core/BAO/CustomOption.php';
1515 require_once 'CRM/Core/PseudoConstant.php';
1516
1517 if (empty($type)) {
1518 return;
1519 }
1520 switch ($type) {
1521 case 'Text':
1522 $formatted[$key] = $field;
1523 break;
1524
1525 case 'CheckBox':
1526 case 'AdvMulti-Select':
1527 case 'Multi-Select':
1528
1529 $mulValues = explode(',', $field);
1530 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
1531 $formatted[$key] = array();
1532 foreach ($mulValues as $v1) {
1533 foreach ($customOption as $v2) {
1534 if ((strtolower($v2['label']) == strtolower(trim($v1))) ||
1535 (strtolower($v2['value']) == strtolower(trim($v1)))
1536 ) {
1537 if ($type == 'CheckBox') {
1538 $formatted[$key][$v2['value']] = 1;
1539 }
1540 else {
1541 $formatted[$key][] = $v2['value'];
1542 }
1543 }
1544 }
1545 }
1546 break;
1547
1548 case 'Select':
1549 case 'Radio':
1550
1551 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
1552 foreach ($customOption as $v2) {
1553 if ((strtolower($v2['label']) == strtolower(trim($field))) ||
1554 (strtolower($v2['value']) == strtolower(trim($field)))
1555 ) {
1556 $formatted[$key] = $v2['value'];
1557 }
1558 }
1559 break;
1560
1561 case 'Multi-Select State/Province':
1562
1563 $mulValues = explode(',', $field);
1564 $stateAbbr = CRM_Core_PseudoConstant::stateProvinceAbbreviation();
1565 $stateName = CRM_Core_PseudoConstant::stateProvince();
1566 $formatted[$key] = $stateValues = array();
1567 foreach ($mulValues as $values) {
1568 if ($val = CRM_Utils_Array::key($values, $stateAbbr)) {
1569 $formatted[$key][] = $val;
1570 }
1571 elseif ($val = CRM_Utils_Array::key($values, $stateName)) {
1572 $formatted[$key][] = $val;
1573 }
1574 }
1575 break;
1576
1577 case 'Multi-Select Country':
1578
1579 $config = CRM_Core_Config::singleton();
1580 $limitCodes = $config->countryLimit();
1581 $mulValues = explode(',', $field);
1582 $formatted[$key] = array();
1583 CRM_Core_PseudoConstant::populate($countryNames, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active');
1584 CRM_Core_PseudoConstant::populate($countryIsoCodes, 'CRM_Core_DAO_Country', TRUE, 'iso_code');
1585 foreach ($mulValues as $values) {
1586 if ($val = CRM_Utils_Array::key($values, $countryNames)) {
1587 $formatted[$key][] = $val;
1588 }
1589 elseif ($val = CRM_Utils_Array::key($values, $countryIsoCodes)) {
1590 $formatted[$key][] = $val;
1591 }
1592 elseif ($val = CRM_Utils_Array::key($values, $limitCodes)) {
1593 $formatted[$key][] = $val;
1594 }
1595 }
1596 break;
1597 }
1598}
1599