3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
35 * These functions have been deprecated out of API v3 Utils folder as they are not part of the
36 * API. Calling API functions directly is not supported & these functions are not called by any
37 * part of the API so are not really part of the api
41 require_once 'api/v3/utils.php';
44 * take the input parameter list as specified in the data model and
45 * convert it into the same format that we use in QF and BAO object
47 * @param array $params
48 * Associative array of property name/value.
49 * pairs to insert in new contact.
50 * @param array $values
51 * The reformatted properties that we can use internally.
53 * @param array|bool $create Is the formatted Values array going to
54 * be used for CRM_vent_BAO_Participant:create()
56 * @return array|CRM_Error
58 function _civicrm_api3_deprecated_participant_formatted_param($params, &$values, $create = FALSE) {
59 $fields = CRM_Event_DAO_Participant
::fields();
60 _civicrm_api3_store_values($fields, $params, $values);
62 require_once 'CRM/Core/OptionGroup.php';
63 $customFields = CRM_Core_BAO_CustomField
::getFields('Participant', FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE);
65 foreach ($params as $key => $value) {
66 // ignore empty values or empty arrays etc
67 if (CRM_Utils_System
::isNull($value)) {
71 // Handling Custom Data
72 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
73 $values[$key] = $value;
74 $type = $customFields[$customFieldID]['html_type'];
75 if ($type == 'CheckBox' ||
$type == 'Multi-Select') {
76 $mulValues = explode(',', $value);
77 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
78 $values[$key] = array();
79 foreach ($mulValues as $v1) {
80 foreach ($customOption as $customValueID => $customLabel) {
81 $customValue = $customLabel['value'];
82 if ((strtolower(trim($customLabel['label'])) == strtolower(trim($v1))) ||
83 (strtolower(trim($customValue)) == strtolower(trim($v1)))
85 if ($type == 'CheckBox') {
86 $values[$key][$customValue] = 1;
89 $values[$key][] = $customValue;
95 elseif ($type == 'Select' ||
$type == 'Radio') {
96 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
97 foreach ($customOption as $customFldID => $customValue) {
98 $val = CRM_Utils_Array
::value('value', $customValue);
99 $label = CRM_Utils_Array
::value('label', $customValue);
100 $label = strtolower($label);
101 $value = strtolower(trim($value));
102 if (($value == $label) ||
($value == strtolower($val))) {
103 $values[$key] = $val;
110 case 'participant_contact_id':
111 if (!CRM_Utils_Rule
::integer($value)) {
112 return civicrm_api3_create_error("contact_id not valid: $value");
114 $dao = new CRM_Core_DAO();
116 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value",
120 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
122 $values['contact_id'] = $values['participant_contact_id'];
123 unset($values['participant_contact_id']);
126 case 'participant_register_date':
127 if (!CRM_Utils_Rule
::dateTime($value)) {
128 return civicrm_api3_create_error("$key not a valid date: $value");
133 $id = CRM_Core_DAO
::getFieldValue("CRM_Event_DAO_Event", $value, 'id', 'title');
134 $values['event_id'] = $id;
138 if (!CRM_Utils_Rule
::integer($value)) {
139 return civicrm_api3_create_error("Event ID is not valid: $value");
141 $dao = new CRM_Core_DAO();
143 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_event WHERE id = $value",
147 return civicrm_api3_create_error("Invalid Event ID: There is no event record with event_id = $value.");
151 case 'participant_status_id':
152 if (!CRM_Utils_Rule
::integer($value)) {
153 return civicrm_api3_create_error("Event Status ID is not valid: $value");
157 case 'participant_status':
158 $status = CRM_Event_PseudoConstant
::participantStatus();
159 $values['participant_status_id'] = CRM_Utils_Array
::key($value, $status);;
162 case 'participant_role_id':
163 case 'participant_role':
164 $role = CRM_Event_PseudoConstant
::participantRole();
165 $participantRoles = explode(",", $value);
166 foreach ($participantRoles as $k => $v) {
168 if ($key == 'participant_role') {
169 $participantRoles[$k] = CRM_Utils_Array
::key($v, $role);
172 $participantRoles[$k] = $v;
175 require_once 'CRM/Core/DAO.php';
176 $values['role_id'] = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $participantRoles);
177 unset($values[$key]);
185 if (array_key_exists('participant_note', $params)) {
186 $values['participant_note'] = $params['participant_note'];
190 // CRM_Event_BAO_Participant::create() handles register_date,
191 // status_id and source. So, if $values contains
192 // participant_register_date, participant_status_id or participant_source,
193 // convert it to register_date, status_id or source
195 'participant_register_date' => 'register_date',
196 'participant_source' => 'source',
197 'participant_status_id' => 'status_id',
198 'participant_role_id' => 'role_id',
199 'participant_fee_level' => 'fee_level',
200 'participant_fee_amount' => 'fee_amount',
201 'participant_id' => 'id',
204 foreach ($changes as $orgVal => $changeVal) {
205 if (isset($values[$orgVal])) {
206 $values[$changeVal] = $values[$orgVal];
207 unset($values[$orgVal]);
216 * take the input parameter list as specified in the data model and
217 * convert it into the same format that we use in QF and BAO object
219 * @param array $params
220 * Associative array of property name/value.
221 * pairs to insert in new contact.
222 * @param array $values
223 * The reformatted properties that we can use internally.
226 * @param bool $create
227 * @param null $onDuplicate
229 * @return array|CRM_Error
231 function _civicrm_api3_deprecated_formatted_param($params, &$values, $create = FALSE, $onDuplicate = NULL) {
232 // copy all the contribution fields as is
234 $fields = CRM_Contribute_DAO_Contribution
::fields();
236 _civicrm_api3_store_values($fields, $params, $values);
238 require_once 'CRM/Core/OptionGroup.php';
239 $customFields = CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE);
241 foreach ($params as $key => $value) {
242 // ignore empty values or empty arrays etc
243 if (CRM_Utils_System
::isNull($value)) {
247 // Handling Custom Data
248 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
249 $values[$key] = $value;
250 $type = $customFields[$customFieldID]['html_type'];
251 if ($type == 'CheckBox' ||
$type == 'Multi-Select') {
252 $mulValues = explode(',', $value);
253 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
254 $values[$key] = array();
255 foreach ($mulValues as $v1) {
256 foreach ($customOption as $customValueID => $customLabel) {
257 $customValue = $customLabel['value'];
258 if ((strtolower($customLabel['label']) == strtolower(trim($v1))) ||
259 (strtolower($customValue) == strtolower(trim($v1)))
261 if ($type == 'CheckBox') {
262 $values[$key][$customValue] = 1;
265 $values[$key][] = $customValue;
271 elseif ($type == 'Select' ||
$type == 'Radio' ||
272 ($type == 'Autocomplete-Select' &&
273 $customFields[$customFieldID]['data_type'] == 'String'
276 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
277 foreach ($customOption as $customFldID => $customValue) {
278 $val = CRM_Utils_Array
::value('value', $customValue);
279 $label = CRM_Utils_Array
::value('label', $customValue);
280 $label = strtolower($label);
281 $value = strtolower(trim($value));
282 if (($value == $label) ||
($value == strtolower($val))) {
283 $values[$key] = $val;
290 case 'contribution_contact_id':
291 if (!CRM_Utils_Rule
::integer($value)) {
292 return civicrm_api3_create_error("contact_id not valid: $value");
294 $dao = new CRM_Core_DAO();
296 $svq = $dao->singleValueQuery("SELECT is_deleted FROM civicrm_contact WHERE id = $value",
300 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
303 return civicrm_api3_create_error("Invalid Contact ID: contact_id $value is a soft-deleted contact.");
306 $values['contact_id'] = $values['contribution_contact_id'];
307 unset($values['contribution_contact_id']);
311 // import contribution record according to select contact type
312 require_once 'CRM/Contact/DAO/Contact.php';
313 $contactType = new CRM_Contact_DAO_Contact();
314 $contactId = CRM_Utils_Array
::value('contribution_contact_id', $params);
315 $externalId = CRM_Utils_Array
::value('external_identifier', $params);
316 $email = CRM_Utils_Array
::value('email', $params);
317 //when insert mode check contact id or external identifier
318 if ($contactId ||
$externalId) {
319 $contactType->id
= $contactId;
320 $contactType->external_identifier
= $externalId;
321 if ($contactType->find(TRUE)) {
322 if ($params['contact_type'] != $contactType->contact_type
) {
323 return civicrm_api3_create_error("Contact Type is wrong: $contactType->contact_type");
328 if (!CRM_Utils_Rule
::email($email)) {
329 return civicrm_api3_create_error("Invalid email address $email provided. Row was skipped");
332 // get the contact id from duplicate contact rule, if more than one contact is returned
333 // we should return error, since current interface allows only one-one mapping
334 $emailParams = array('email' => $email, 'contact_type' => $params['contact_type']);
335 $checkDedupe = _civicrm_api3_deprecated_duplicate_formatted_contact($emailParams);
336 if (!$checkDedupe['is_error']) {
337 return civicrm_api3_create_error("Invalid email address(doesn't exist) $email. Row was skipped");
340 $matchingContactIds = explode(',', $checkDedupe['error_message']['params'][0]);
341 if (count($matchingContactIds) > 1) {
342 return civicrm_api3_create_error("Invalid email address(duplicate) $email. Row was skipped");
344 elseif (count($matchingContactIds) == 1) {
345 $params['contribution_contact_id'] = $matchingContactIds[0];
349 elseif (!empty($params['contribution_id']) ||
!empty($params['trxn_id']) ||
!empty($params['invoice_id'])) {
350 // when update mode check contribution id or trxn id or
352 $contactId = new CRM_Contribute_DAO_Contribution();
353 if (!empty($params['contribution_id'])) {
354 $contactId->id
= $params['contribution_id'];
356 elseif (!empty($params['trxn_id'])) {
357 $contactId->trxn_id
= $params['trxn_id'];
359 elseif (!empty($params['invoice_id'])) {
360 $contactId->invoice_id
= $params['invoice_id'];
362 if ($contactId->find(TRUE)) {
363 $contactType->id
= $contactId->contact_id
;
364 if ($contactType->find(TRUE)) {
365 if ($params['contact_type'] != $contactType->contact_type
) {
366 return civicrm_api3_create_error("Contact Type is wrong: $contactType->contact_type");
372 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_UPDATE
) {
373 return civicrm_api3_create_error("Empty Contribution and Invoice and Transaction ID. Row was skipped.");
381 case 'thankyou_date':
382 if (!CRM_Utils_Rule
::dateTime($value)) {
383 return civicrm_api3_create_error("$key not a valid date: $value");
387 case 'non_deductible_amount':
391 if (!CRM_Utils_Rule
::money($value)) {
392 return civicrm_api3_create_error("$key not a valid amount: $value");
397 if (!CRM_Utils_Rule
::currencyCode($value)) {
398 return civicrm_api3_create_error("currency not a valid code: $value");
402 case 'financial_type':
403 require_once 'CRM/Contribute/PseudoConstant.php';
404 $contriTypes = CRM_Contribute_PseudoConstant
::financialType();
405 foreach ($contriTypes as $val => $type) {
406 if (strtolower($value) == strtolower($type)) {
407 $values['financial_type_id'] = $val;
411 if (empty($values['financial_type_id'])) {
412 return civicrm_api3_create_error("Financial Type is not valid: $value");
416 case 'payment_instrument':
417 require_once 'CRM/Core/OptionGroup.php';
418 $values['payment_instrument_id'] = CRM_Core_OptionGroup
::getValue('payment_instrument', $value);
419 if (empty($values['payment_instrument_id'])) {
420 return civicrm_api3_create_error("Payment Instrument is not valid: $value");
424 case 'contribution_status_id':
425 require_once 'CRM/Core/OptionGroup.php';
426 if (!$values['contribution_status_id'] = CRM_Core_OptionGroup
::getValue('contribution_status', $value)) {
427 return civicrm_api3_create_error("Contribution Status is not valid: $value");
432 // import contribution record according to select contact type
433 // validate contact id and external identifier.
434 $value[$key] = $mismatchContactType = $softCreditContactIds = '';
435 if (isset($params[$key]) && is_array($params[$key])) {
436 foreach ($params[$key] as $softKey => $softParam) {
437 $contactId = CRM_Utils_Array
::value('contact_id', $softParam);
438 $externalId = CRM_Utils_Array
::value('external_identifier', $softParam);
439 $email = CRM_Utils_Array
::value('email', $softParam);
440 if ($contactId ||
$externalId) {
441 require_once 'CRM/Contact/DAO/Contact.php';
442 $contact = new CRM_Contact_DAO_Contact();
443 $contact->id
= $contactId;
444 $contact->external_identifier
= $externalId;
446 if (!$contact->find(TRUE)) {
447 $field = $contactId ?
ts('Contact ID') : ts('External ID');
448 $errorMsg = ts("Soft Credit %1 - %2 doesn't exist. Row was skipped.",
449 array(1 => $field, 2 => $contactId ?
$contactId : $externalId));
453 return civicrm_api3_create_error($errorMsg);
456 // finally get soft credit contact id.
457 $values[$key][$softKey] = $softParam;
458 $values[$key][$softKey]['contact_id'] = $contact->id
;
461 if (!CRM_Utils_Rule
::email($email)) {
462 return civicrm_api3_create_error("Invalid email address $email provided for Soft Credit. Row was skipped");
465 // get the contact id from duplicate contact rule, if more than one contact is returned
466 // we should return error, since current interface allows only one-one mapping
467 $emailParams = array('email' => $email, 'contact_type' => $params['contact_type']);
468 $checkDedupe = _civicrm_api3_deprecated_duplicate_formatted_contact($emailParams);
469 if (!$checkDedupe['is_error']) {
470 return civicrm_api3_create_error("Invalid email address(doesn't exist) $email for Soft Credit. Row was skipped");
473 $matchingContactIds = explode(',', $checkDedupe['error_message']['params'][0]);
474 if (count($matchingContactIds) > 1) {
475 return civicrm_api3_create_error("Invalid email address(duplicate) $email for Soft Credit. Row was skipped");
477 elseif (count($matchingContactIds) == 1) {
478 $contactId = $matchingContactIds[0];
479 unset($softParam['email']);
480 $values[$key][$softKey] = $softParam +
array('contact_id' => $contactId);
488 case 'pledge_payment':
491 // giving respect to pledge_payment flag.
492 if (empty($params['pledge_payment'])) {
496 // get total amount of from import fields
497 $totalAmount = CRM_Utils_Array
::value('total_amount', $params);
499 $onDuplicate = CRM_Utils_Array
::value('onDuplicate', $params);
501 // we need to get contact id $contributionContactID to
502 // retrieve pledge details as well as to validate pledge ID
504 // first need to check for update mode
505 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_UPDATE
&&
506 ($params['contribution_id'] ||
$params['trxn_id'] ||
$params['invoice_id'])
508 $contribution = new CRM_Contribute_DAO_Contribution();
509 if ($params['contribution_id']) {
510 $contribution->id
= $params['contribution_id'];
512 elseif ($params['trxn_id']) {
513 $contribution->trxn_id
= $params['trxn_id'];
515 elseif ($params['invoice_id']) {
516 $contribution->invoice_id
= $params['invoice_id'];
519 if ($contribution->find(TRUE)) {
520 $contributionContactID = $contribution->contact_id
;
522 $totalAmount = $contribution->total_amount
;
526 return civicrm_api3_create_error('No match found for specified contact in pledge payment data. Row was skipped.');
530 // first get the contact id for given contribution record.
531 if (!empty($params['contribution_contact_id'])) {
532 $contributionContactID = $params['contribution_contact_id'];
534 elseif (!empty($params['external_identifier'])) {
535 require_once 'CRM/Contact/DAO/Contact.php';
536 $contact = new CRM_Contact_DAO_Contact();
537 $contact->external_identifier
= $params['external_identifier'];
538 if ($contact->find(TRUE)) {
539 $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $contact->id
;
542 return civicrm_api3_create_error('No match found for specified contact in pledge payment data. Row was skipped.');
546 // we need to get contribution contact using de dupe
547 $error = _civicrm_api3_deprecated_check_contact_dedupe($params);
549 if (isset($error['error_message']['params'][0])) {
550 $matchedIDs = explode(',', $error['error_message']['params'][0]);
552 // check if only one contact is found
553 if (count($matchedIDs) > 1) {
554 return civicrm_api3_create_error($error['error_message']['message']);
557 $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $matchedIDs[0];
561 return civicrm_api3_create_error('No match found for specified contact in contribution data. Row was skipped.');
566 if (!empty($params['pledge_id'])) {
567 if (CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge', $params['pledge_id'], 'contact_id') != $contributionContactID) {
568 return civicrm_api3_create_error('Invalid Pledge ID provided. Contribution row was skipped.');
570 $values['pledge_id'] = $params['pledge_id'];
573 // check if there are any pledge related to this contact, with payments pending or in progress
574 require_once 'CRM/Pledge/BAO/Pledge.php';
575 $pledgeDetails = CRM_Pledge_BAO_Pledge
::getContactPledges($contributionContactID);
577 if (empty($pledgeDetails)) {
578 return civicrm_api3_create_error('No open pledges found for this contact. Contribution row was skipped.');
580 elseif (count($pledgeDetails) > 1) {
581 return civicrm_api3_create_error('This contact has more than one open pledge. Unable to determine which pledge to apply the contribution to. Contribution row was skipped.');
584 // this mean we have only one pending / in progress pledge
585 $values['pledge_id'] = $pledgeDetails[0];
588 // we need to check if oldest payment amount equal to contribution amount
589 require_once 'CRM/Pledge/BAO/PledgePayment.php';
590 $pledgePaymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($values['pledge_id']);
592 if ($pledgePaymentDetails['amount'] == $totalAmount) {
593 $values['pledge_payment_id'] = $pledgePaymentDetails['id'];
596 return civicrm_api3_create_error('Contribution and Pledge Payment amount mismatch for this record. Contribution row was skipped.');
605 if (array_key_exists('note', $params)) {
606 $values['note'] = $params['note'];
610 // CRM_Contribute_BAO_Contribution::add() handles contribution_source
611 // So, if $values contains contribution_source, convert it to source
612 $changes = array('contribution_source' => 'source');
614 foreach ($changes as $orgVal => $changeVal) {
615 if (isset($values[$orgVal])) {
616 $values[$changeVal] = $values[$orgVal];
617 unset($values[$orgVal]);
626 * Check duplicate contacts based on de-dupe parameters.
628 * @param array $params
632 function _civicrm_api3_deprecated_check_contact_dedupe($params) {
633 static $cIndieFields = NULL;
634 static $defaultLocationId = NULL;
636 $contactType = $params['contact_type'];
637 if ($cIndieFields == NULL) {
638 require_once 'CRM/Contact/BAO/Contact.php';
639 $cTempIndieFields = CRM_Contact_BAO_Contact
::importableFields($contactType);
640 $cIndieFields = $cTempIndieFields;
642 require_once "CRM/Core/BAO/LocationType.php";
643 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
645 // set the value to default location id else set to 1
646 if (!$defaultLocationId = (int) $defaultLocation->id
) {
647 $defaultLocationId = 1;
651 require_once 'CRM/Contact/BAO/Query.php';
652 $locationFields = CRM_Contact_BAO_Query
::$_locationSpecificFields;
654 $contactFormatted = array();
655 foreach ($params as $key => $field) {
656 if ($field == NULL ||
$field === '') {
659 if (is_array($field)) {
660 foreach ($field as $value) {
662 if (is_array($value)) {
663 foreach ($value as $name => $testForEmpty) {
664 if ($name !== 'phone_type' &&
665 ($testForEmpty === '' ||
$testForEmpty == NULL)
676 _civicrm_api3_deprecated_add_formatted_param($value, $contactFormatted);
682 $value = array($key => $field);
684 // check if location related field, then we need to add primary location type
685 if (in_array($key, $locationFields)) {
686 $value['location_type_id'] = $defaultLocationId;
688 elseif (array_key_exists($key, $cIndieFields)) {
689 $value['contact_type'] = $contactType;
692 _civicrm_api3_deprecated_add_formatted_param($value, $contactFormatted);
695 $contactFormatted['contact_type'] = $contactType;
697 return _civicrm_api3_deprecated_duplicate_formatted_contact($contactFormatted);
701 * take the input parameter list as specified in the data model and
702 * convert it into the same format that we use in QF and BAO object
704 * @param array $params
705 * Associative array of property name/value.
706 * pairs to insert in new contact.
707 * @param array $values
708 * The reformatted properties that we can use internally.
710 * @param array|bool $create Is the formatted Values array going to
711 * be used for CRM_Activity_BAO_Activity::create()
713 * @return array|CRM_Error
715 function _civicrm_api3_deprecated_activity_formatted_param(&$params, &$values, $create = FALSE) {
716 // copy all the activity fields as is
717 $fields = CRM_Activity_DAO_Activity
::fields();
718 _civicrm_api3_store_values($fields, $params, $values);
720 require_once 'CRM/Core/OptionGroup.php';
721 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity');
723 foreach ($params as $key => $value) {
724 // ignore empty values or empty arrays etc
725 if (CRM_Utils_System
::isNull($value)) {
729 //Handling Custom Data
730 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
731 $values[$key] = $value;
732 $type = $customFields[$customFieldID]['html_type'];
733 if ($type == 'CheckBox' ||
$type == 'Multi-Select') {
734 $mulValues = explode(',', $value);
735 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
736 $values[$key] = array();
737 foreach ($mulValues as $v1) {
738 foreach ($customOption as $customValueID => $customLabel) {
739 $customValue = $customLabel['value'];
740 if ((strtolower(trim($customLabel['label'])) == strtolower(trim($v1))) ||
741 (strtolower(trim($customValue)) == strtolower(trim($v1)))
743 if ($type == 'CheckBox') {
744 $values[$key][$customValue] = 1;
747 $values[$key][] = $customValue;
753 elseif ($type == 'Select' ||
$type == 'Radio') {
754 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
755 foreach ($customOption as $customFldID => $customValue) {
756 $val = CRM_Utils_Array
::value('value', $customValue);
757 $label = CRM_Utils_Array
::value('label', $customValue);
758 $label = strtolower($label);
759 $value = strtolower(trim($value));
760 if (($value == $label) ||
($value == strtolower($val))) {
761 $values[$key] = $val;
767 if ($key == 'target_contact_id') {
768 if (!CRM_Utils_Rule
::integer($value)) {
769 return civicrm_api3_create_error("contact_id not valid: $value");
771 $contactID = CRM_Core_DAO
::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value");
773 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
781 * This function adds the contact variable in $values to the
782 * parameter list $params. For most cases, $values should have length 1. If
783 * the variable being added is a child of Location, a location_type_id must
784 * also be included. If it is a child of phone, a phone_type must be included.
786 * @param array $values
787 * The variable(s) to be added.
788 * @param array $params
789 * The structured parameter list.
791 * @return bool|CRM_Utils_Error
793 function _civicrm_api3_deprecated_add_formatted_param(&$values, &$params) {
794 // Crawl through the possible classes:
807 // Cache the various object fields
808 static $fields = NULL;
810 if ($fields == NULL) {
814 // first add core contact values since for other Civi modules they are not added
815 require_once 'CRM/Contact/BAO/Contact.php';
816 $contactFields = CRM_Contact_DAO_Contact
::fields();
817 _civicrm_api3_store_values($contactFields, $values, $params);
819 if (isset($values['contact_type'])) {
820 // we're an individual/household/org property
822 $fields[$values['contact_type']] = CRM_Contact_DAO_Contact
::fields();
824 _civicrm_api3_store_values($fields[$values['contact_type']], $values, $params);
828 if (isset($values['individual_prefix'])) {
829 if (!empty($params['prefix_id'])) {
830 $prefixes = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'prefix_id');
831 $params['prefix'] = $prefixes[$params['prefix_id']];
834 $params['prefix'] = $values['individual_prefix'];
839 if (isset($values['individual_suffix'])) {
840 if (!empty($params['suffix_id'])) {
841 $suffixes = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'suffix_id');
842 $params['suffix'] = $suffixes[$params['suffix_id']];
845 $params['suffix'] = $values['individual_suffix'];
851 if (isset($values['email_greeting'])) {
852 if (!empty($params['email_greeting_id'])) {
853 $emailGreetingFilter = array(
854 'contact_type' => CRM_Utils_Array
::value('contact_type', $params),
855 'greeting_type' => 'email_greeting',
857 $emailGreetings = CRM_Core_PseudoConstant
::greeting($emailGreetingFilter);
858 $params['email_greeting'] = $emailGreetings[$params['email_greeting_id']];
861 $params['email_greeting'] = $values['email_greeting'];
867 if (isset($values['postal_greeting'])) {
868 if (!empty($params['postal_greeting_id'])) {
869 $postalGreetingFilter = array(
870 'contact_type' => CRM_Utils_Array
::value('contact_type', $params),
871 'greeting_type' => 'postal_greeting',
873 $postalGreetings = CRM_Core_PseudoConstant
::greeting($postalGreetingFilter);
874 $params['postal_greeting'] = $postalGreetings[$params['postal_greeting_id']];
877 $params['postal_greeting'] = $values['postal_greeting'];
882 if (isset($values['addressee'])) {
883 if (!empty($params['addressee_id'])) {
884 $addresseeFilter = array(
885 'contact_type' => CRM_Utils_Array
::value('contact_type', $params),
886 'greeting_type' => 'addressee',
888 $addressee = CRM_Core_PseudoConstant
::addressee($addresseeFilter);
889 $params['addressee'] = $addressee[$params['addressee_id']];
892 $params['addressee'] = $values['addressee'];
897 if (isset($values['gender'])) {
898 if (!empty($params['gender_id'])) {
899 $genders = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'gender_id');
900 $params['gender'] = $genders[$params['gender_id']];
903 $params['gender'] = $values['gender'];
908 if (!empty($values['preferred_communication_method'])) {
910 $pcm = array_change_key_case(array_flip(CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method')), CASE_LOWER
);
912 $preffComm = explode(',', $values['preferred_communication_method']);
913 foreach ($preffComm as $v) {
914 $v = strtolower(trim($v));
915 if (array_key_exists($v, $pcm)) {
920 $params['preferred_communication_method'] = $comm;
924 // format the website params.
925 if (!empty($values['url'])) {
926 static $websiteFields;
927 if (!is_array($websiteFields)) {
928 require_once 'CRM/Core/DAO/Website.php';
929 $websiteFields = CRM_Core_DAO_Website
::fields();
931 if (!array_key_exists('website', $params) ||
932 !is_array($params['website'])
934 $params['website'] = array();
937 $websiteCount = count($params['website']);
938 _civicrm_api3_store_values($websiteFields, $values,
939 $params['website'][++
$websiteCount]
945 // get the formatted location blocks into params - w/ 3.0 format, CRM-4605
946 if (!empty($values['location_type_id'])) {
947 _civicrm_api3_deprecated_add_formatted_location_blocks($values, $params);
951 if (isset($values['note'])) {
953 if (!isset($params['note'])) {
954 $params['note'] = array();
956 $noteBlock = count($params['note']) +
1;
958 $params['note'][$noteBlock] = array();
959 if (!isset($fields['Note'])) {
960 $fields['Note'] = CRM_Core_DAO_Note
::fields();
963 // get the current logged in civicrm user
964 $session = CRM_Core_Session
::singleton();
965 $userID = $session->get('userID');
968 $values['contact_id'] = $userID;
971 _civicrm_api3_store_values($fields['Note'], $values, $params['note'][$noteBlock]);
976 // Check for custom field values
978 if (empty($fields['custom'])) {
979 $fields['custom'] = &CRM_Core_BAO_CustomField
::getFields(CRM_Utils_Array
::value('contact_type', $values),
980 FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE
984 foreach ($values as $key => $value) {
985 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
986 // check if it's a valid custom field id
988 if (!array_key_exists($customFieldID, $fields['custom'])) {
989 return civicrm_api3_create_error('Invalid custom field ID');
992 $params[$key] = $value;
999 * This function format location blocks w/ v3.0 format.
1001 * @param array $values
1002 * The variable(s) to be added.
1003 * @param array $params
1004 * The structured parameter list.
1008 function _civicrm_api3_deprecated_add_formatted_location_blocks(&$values, &$params) {
1009 static $fields = NULL;
1010 if ($fields == NULL) {
1021 $name = strtolower($block);
1022 if (!array_key_exists($name, $values)) {
1026 if ($name == 'phone_ext') {
1030 // block present in value array.
1031 if (!array_key_exists($name, $params) ||
!is_array($params[$name])) {
1032 $params[$name] = array();
1035 if (!array_key_exists($block, $fields)) {
1036 $className = "CRM_Core_DAO_$block";
1037 $fields[$block] =& $className::fields();
1040 $blockCnt = count($params[$name]);
1042 // copy value to dao field name.
1043 if ($name == 'im') {
1044 $values['name'] = $values[$name];
1047 _civicrm_api3_store_values($fields[$block], $values,
1048 $params[$name][++
$blockCnt]
1051 if (empty($params['id']) && ($blockCnt == 1)) {
1052 $params[$name][$blockCnt]['is_primary'] = TRUE;
1055 // we only process single block at a time.
1059 // handle address fields.
1060 if (!array_key_exists('address', $params) ||
!is_array($params['address'])) {
1061 $params['address'] = array();
1065 foreach ($params['address'] as $cnt => $addressBlock) {
1066 if (CRM_Utils_Array
::value('location_type_id', $values) ==
1067 CRM_Utils_Array
::value('location_type_id', $addressBlock)
1075 if (!array_key_exists('Address', $fields)) {
1076 require_once 'CRM/Core/DAO/Address.php';
1077 $fields['Address'] = CRM_Core_DAO_Address
::fields();
1080 // Note: we doing multiple value formatting here for address custom fields, plus putting into right format.
1081 // The actual formatting (like date, country ..etc) for address custom fields is taken care of while saving
1082 // the address in CRM_Core_BAO_Address::create method
1083 if (!empty($values['location_type_id'])) {
1084 static $customFields = array();
1085 if (empty($customFields)) {
1086 $customFields = CRM_Core_BAO_CustomField
::getFields('Address');
1088 // make a copy of values, as we going to make changes
1089 $newValues = $values;
1090 foreach ($values as $key => $val) {
1091 $customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key);
1092 if ($customFieldID && array_key_exists($customFieldID, $customFields)) {
1093 // mark an entry in fields array since we want the value of custom field to be copied
1094 $fields['Address'][$key] = NULL;
1096 $htmlType = CRM_Utils_Array
::value('html_type', $customFields[$customFieldID]);
1097 switch ($htmlType) {
1099 case 'AdvMulti-Select':
1100 case 'Multi-Select':
1102 $mulValues = explode(',', $val);
1103 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
1104 $newValues[$key] = array();
1105 foreach ($mulValues as $v1) {
1106 foreach ($customOption as $v2) {
1107 if ((strtolower($v2['label']) == strtolower(trim($v1))) ||
1108 (strtolower($v2['value']) == strtolower(trim($v1)))
1110 if ($htmlType == 'CheckBox') {
1111 $newValues[$key][$v2['value']] = 1;
1114 $newValues[$key][] = $v2['value'];
1124 // consider new values
1125 $values = $newValues;
1128 _civicrm_api3_store_values($fields['Address'], $values, $params['address'][$addressCnt]);
1130 $addressFields = array(
1134 'supplemental_address_1',
1135 'supplemental_address_2',
1136 'supplemental_address_3',
1137 'StateProvince.name',
1140 foreach ($addressFields as $field) {
1141 if (array_key_exists($field, $values)) {
1142 if (!array_key_exists('address', $params)) {
1143 $params['address'] = array();
1145 $params['address'][$addressCnt][$field] = $values[$field];
1149 if ($addressCnt == 1) {
1151 $params['address'][$addressCnt]['is_primary'] = TRUE;
1159 * @param array $params
1164 function _civicrm_api3_deprecated_duplicate_formatted_contact($params) {
1165 $id = CRM_Utils_Array
::value('id', $params);
1166 $externalId = CRM_Utils_Array
::value('external_identifier', $params);
1167 if ($id ||
$externalId) {
1168 $contact = new CRM_Contact_DAO_Contact();
1171 $contact->external_identifier
= $externalId;
1173 if ($contact->find(TRUE)) {
1174 if ($params['contact_type'] != $contact->contact_type
) {
1175 return civicrm_api3_create_error("Mismatched contact IDs OR Mismatched contact Types");
1178 $error = CRM_Core_Error
::createError("Found matching contacts: $contact->id",
1179 CRM_Core_Error
::DUPLICATE_CONTACT
,
1180 'Fatal', $contact->id
1182 return civicrm_api3_create_error($error->pop());
1186 $ids = CRM_Contact_BAO_Contact
::getDuplicateContacts($params, $params['contact_type'], 'Unsupervised');
1189 $ids = implode(',', $ids);
1190 $error = CRM_Core_Error
::createError("Found matching contacts: $ids",
1191 CRM_Core_Error
::DUPLICATE_CONTACT
,
1194 return civicrm_api3_create_error($error->pop());
1197 return civicrm_api3_create_success(TRUE);
1201 * Validate a formatted contact parameter list.
1203 * @param array $params
1204 * Structured parameter list (as in crm_format_params).
1206 * @return bool|CRM_Core_Error
1208 function _civicrm_api3_deprecated_validate_formatted_contact(&$params) {
1209 // Look for offending email addresses
1211 if (array_key_exists('email', $params)) {
1212 foreach ($params['email'] as $count => $values) {
1213 if (!is_array($values)) {
1216 if ($email = CRM_Utils_Array
::value('email', $values)) {
1217 // validate each email
1218 if (!CRM_Utils_Rule
::email($email)) {
1219 return civicrm_api3_create_error('No valid email address');
1222 // check for loc type id.
1223 if (empty($values['location_type_id'])) {
1224 return civicrm_api3_create_error('Location Type Id missing.');
1230 // Validate custom data fields
1231 if (array_key_exists('custom', $params) && is_array($params['custom'])) {
1232 foreach ($params['custom'] as $key => $custom) {
1233 if (is_array($custom)) {
1234 foreach ($custom as $fieldId => $value) {
1235 $valid = CRM_Core_BAO_CustomValue
::typecheck(CRM_Utils_Array
::value('type', $value),
1236 CRM_Utils_Array
::value('value', $value)
1238 if (!$valid && $value['is_required']) {
1239 return civicrm_api3_create_error('Invalid value for custom field \'' .
1240 CRM_Utils_Array
::value('name', $custom) . '\''
1243 if (CRM_Utils_Array
::value('type', $custom) == 'Date') {
1244 $params['custom'][$key][$fieldId]['value'] = str_replace('-', '', $params['custom'][$key][$fieldId]['value']);
1251 return civicrm_api3_create_success(TRUE);
1256 * @deprecated - this is part of the import parser not the API & needs to be moved on out
1258 * @param array $params
1259 * @param $onDuplicate
1261 * @return array|bool
1264 function _civicrm_api3_deprecated_create_participant_formatted($params, $onDuplicate) {
1265 require_once 'CRM/Event/Import/Parser.php';
1266 if ($onDuplicate != CRM_Import_Parser
::DUPLICATE_NOCHECK
) {
1267 CRM_Core_Error
::reset();
1268 $error = _civicrm_api3_deprecated_participant_check_params($params, TRUE);
1269 if (civicrm_error($error)) {
1273 require_once "api/v3/Participant.php";
1274 return civicrm_api3_participant_create($params);
1279 * @param array $params
1281 * @param bool $checkDuplicate
1283 * @return array|bool
1286 function _civicrm_api3_deprecated_participant_check_params($params, $checkDuplicate = FALSE) {
1288 // check if participant id is valid or not
1289 if (!empty($params['id'])) {
1290 $participant = new CRM_Event_BAO_Participant();
1291 $participant->id
= $params['id'];
1292 if (!$participant->find(TRUE)) {
1293 return civicrm_api3_create_error(ts('Participant id is not valid'));
1296 require_once 'CRM/Contact/BAO/Contact.php';
1297 // check if contact id is valid or not
1298 if (!empty($params['contact_id'])) {
1299 $contact = new CRM_Contact_BAO_Contact();
1300 $contact->id
= $params['contact_id'];
1301 if (!$contact->find(TRUE)) {
1302 return civicrm_api3_create_error(ts('Contact id is not valid'));
1306 // check that event id is not an template
1307 if (!empty($params['event_id'])) {
1308 $isTemplate = CRM_Core_DAO
::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'is_template');
1309 if (!empty($isTemplate)) {
1310 return civicrm_api3_create_error(ts('Event templates are not meant to be registered.'));
1315 if ($checkDuplicate) {
1316 if (CRM_Event_BAO_Participant
::checkDuplicate($params, $result)) {
1317 $participantID = array_pop($result);
1319 $error = CRM_Core_Error
::createError("Found matching participant record.",
1320 CRM_Core_Error
::DUPLICATE_PARTICIPANT
,
1321 'Fatal', $participantID
1324 return civicrm_api3_create_error($error->pop(),
1326 'contactID' => $params['contact_id'],
1327 'participantID' => $participantID,
1336 * Ensure that we have the right input parameters for custom data
1338 * @param array $params
1339 * Associative array of property name/value.
1340 * pairs to insert in new contact.
1341 * @param string $csType
1342 * Contact subtype if exists/passed.
1345 * on success, error message otherwise
1347 function _civicrm_api3_deprecated_contact_check_custom_params($params, $csType = NULL) {
1348 empty($csType) ?
$onlyParent = TRUE : $onlyParent = FALSE;
1350 require_once 'CRM/Core/BAO/CustomField.php';
1351 $customFields = CRM_Core_BAO_CustomField
::getFields($params['contact_type'],
1361 foreach ($params as $key => $value) {
1362 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
1363 // check if it's a valid custom field id
1364 if (!array_key_exists($customFieldID, $customFields)) {
1366 $errorMsg = "Invalid Custom Field Contact Type: {$params['contact_type']}";
1367 if (!empty($csType)) {
1368 $errorMsg .= " or Mismatched SubType: " . implode(', ', (array) $csType);
1370 return civicrm_api3_create_error($errorMsg);
1377 * @param array $params
1378 * @param bool $dupeCheck
1379 * @param int $dedupeRuleGroupID
1381 * @return array|null
1383 function _civicrm_api3_deprecated_contact_check_params(
1386 $dedupeRuleGroupID = NULL) {
1388 $requiredCheck = TRUE;
1390 if (isset($params['id']) && is_numeric($params['id'])) {
1391 $requiredCheck = FALSE;
1393 if ($requiredCheck) {
1394 if (isset($params['id'])) {
1395 $required = array('Individual', 'Household', 'Organization');
1398 'Individual' => array(
1399 array('first_name', 'last_name'),
1402 'Household' => array(
1405 'Organization' => array(
1406 'organization_name',
1410 // contact_type has a limited number of valid values
1411 if (empty($params['contact_type'])) {
1412 return civicrm_api3_create_error("No Contact Type");
1414 $fields = CRM_Utils_Array
::value($params['contact_type'], $required);
1415 if ($fields == NULL) {
1416 return civicrm_api3_create_error("Invalid Contact Type: {$params['contact_type']}");
1419 if ($csType = CRM_Utils_Array
::value('contact_sub_type', $params)) {
1420 if (!(CRM_Contact_BAO_ContactType
::isExtendsContactType($csType, $params['contact_type']))) {
1421 return civicrm_api3_create_error("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $csType));
1425 if (empty($params['contact_id']) && !empty($params['id'])) {
1428 foreach ($fields as $field) {
1429 if (is_array($field)) {
1431 foreach ($field as $element) {
1432 if (empty($params[$element])) {
1440 if (!empty($params[$field])) {
1450 return civicrm_api3_create_error("Required fields not found for {$params['contact_type']} : $error");
1456 // @todo switch to using api version
1457 // $dupes = civicrm_api3('Contact', 'duplicatecheck', (array('match' => $params, 'dedupe_rule_id' => $dedupeRuleGroupID)));
1458 // $ids = $dupes['count'] ? implode(',', array_keys($dupes['values'])) : NULL;
1459 $ids = CRM_Contact_BAO_Contact
::getDuplicateContacts($params, $params['contact_type'], 'Unsupervised', array(), CRM_Utils_Array
::value('check_permissions', $params, $dedupeRuleGroupID));
1461 $error = CRM_Core_Error
::createError("Found matching contacts: " . implode(',', $ids),
1462 CRM_Core_Error
::DUPLICATE_CONTACT
,
1465 return civicrm_api3_create_error($error->pop());
1469 // check for organisations with same name
1470 if (!empty($params['current_employer'])) {
1471 $organizationParams = array('organization_name' => $params['current_employer']);
1472 $dupeIds = CRM_Contact_BAO_Contact
::getDuplicateContacts($organizationParams, 'Organization', 'Supervised', array(), FALSE);
1474 // check for mismatch employer name and id
1475 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)
1477 return civicrm_api3_create_error('Employer name and Employer id Mismatch');
1480 // show error if multiple organisation with same name exist
1481 if (empty($params['employer_id']) && (count($dupeIds) > 1)
1483 return civicrm_api3_create_error('Found more than one Organisation with same Name.');
1492 * @param int $activityTypeID
1497 function _civicrm_api3_deprecated_activity_buildmailparams($result, $activityTypeID) {
1498 // get ready for collecting data about activity to be created
1501 $params['activity_type_id'] = $activityTypeID;
1503 $params['status_id'] = 'Completed';
1504 if (!empty($result['from']['id'])) {
1505 $params['source_contact_id'] = $params['assignee_contact_id'] = $result['from']['id'];
1507 $params['target_contact_id'] = array();
1508 $keys = array('to', 'cc', 'bcc');
1509 foreach ($keys as $key) {
1510 if (is_array($result[$key])) {
1511 foreach ($result[$key] as $key => $keyValue) {
1512 if (!empty($keyValue['id'])) {
1513 $params['target_contact_id'][] = $keyValue['id'];
1518 $params['subject'] = $result['subject'];
1519 $params['activity_date_time'] = $result['date'];
1520 $params['details'] = $result['body'];
1522 for ($i = 1; $i <= 5; $i++
) {
1523 if (isset($result["attachFile_$i"])) {
1524 $params["attachFile_$i"] = $result["attachFile_$i"];