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