Merge pull request #679 from davecivicrm/CRM-12397
[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
109ff2ac 54 * be used for CRM_vent_BAO_Participant:create()
6a488035
TO
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 */
6a488035
TO
777 static $fields = NULL;
778
779 if ($fields == NULL) {
780 $fields = array();
781 }
782
783 //first add core contact values since for other Civi modules they are not added
784 require_once 'CRM/Contact/BAO/Contact.php';
785 $contactFields = CRM_Contact_DAO_Contact::fields();
786 _civicrm_api3_store_values($contactFields, $values, $params);
787
788 if (isset($values['contact_type'])) {
789 /* we're an individual/household/org property */
790
791
792
793 $fields[$values['contact_type']] = CRM_Contact_DAO_Contact::fields();
794
795 _civicrm_api3_store_values($fields[$values['contact_type']], $values, $params);
796 return TRUE;
797 }
798
799 if (isset($values['individual_prefix'])) {
800 if (CRM_Utils_Array::value('prefix_id', $params)) {
801 $prefixes = array();
802 $prefixes = CRM_Core_PseudoConstant::individualPrefix();
803 $params['prefix'] = $prefixes[$params['prefix_id']];
804 }
805 else {
806 $params['prefix'] = $values['individual_prefix'];
807 }
808 return TRUE;
809 }
810
811 if (isset($values['individual_suffix'])) {
812 if (CRM_Utils_Array::value('suffix_id', $params)) {
813 $suffixes = array();
814 $suffixes = CRM_Core_PseudoConstant::individualSuffix();
815 $params['suffix'] = $suffixes[$params['suffix_id']];
816 }
817 else {
818 $params['suffix'] = $values['individual_suffix'];
819 }
820 return TRUE;
821 }
822
823 //CRM-4575
824 if (isset($values['email_greeting'])) {
825 if (CRM_Utils_Array::value('email_greeting_id', $params)) {
826 $emailGreetings = array();
827 $emailGreetingFilter = array('contact_type' => CRM_Utils_Array::value('contact_type', $params),
828 'greeting_type' => 'email_greeting',
829 );
830 $emailGreetings = CRM_Core_PseudoConstant::greeting($emailGreetingFilter);
831 $params['email_greeting'] = $emailGreetings[$params['email_greeting_id']];
832 }
833 else {
834 $params['email_greeting'] = $values['email_greeting'];
835 }
836
837 return TRUE;
838 }
839
840 if (isset($values['postal_greeting'])) {
841 if (CRM_Utils_Array::value('postal_greeting_id', $params)) {
842 $postalGreetings = array();
843 $postalGreetingFilter = array('contact_type' => CRM_Utils_Array::value('contact_type', $params),
844 'greeting_type' => 'postal_greeting',
845 );
846 $postalGreetings = CRM_Core_PseudoConstant::greeting($postalGreetingFilter);
847 $params['postal_greeting'] = $postalGreetings[$params['postal_greeting_id']];
848 }
849 else {
850 $params['postal_greeting'] = $values['postal_greeting'];
851 }
852 return TRUE;
853 }
854
855 if (isset($values['addressee'])) {
856 if (CRM_Utils_Array::value('addressee_id', $params)) {
857 $addressee = array();
858 $addresseeFilter = array('contact_type' => CRM_Utils_Array::value('contact_type', $params),
859 'greeting_type' => 'addressee',
860 );
861 $addressee = CRM_Core_PseudoConstant::addressee($addresseeFilter);
862 $params['addressee'] = $addressee[$params['addressee_id']];
863 }
864 else {
865 $params['addressee'] = $values['addressee'];
866 }
867 return TRUE;
868 }
869
870 if (isset($values['gender'])) {
871 if (CRM_Utils_Array::value('gender_id', $params)) {
872 $genders = array();
873 $genders = CRM_Core_PseudoConstant::gender();
874 $params['gender'] = $genders[$params['gender_id']];
875 }
876 else {
877 $params['gender'] = $values['gender'];
878 }
879 return TRUE;
880 }
881
882 if (isset($values['preferred_communication_method'])) {
883 $comm = array();
884 $preffComm = array();
885 $pcm = array();
886 $pcm = array_change_key_case(array_flip(CRM_Core_PseudoConstant::pcm()), CASE_LOWER);
887
888 $preffComm = explode(',', $values['preferred_communication_method']);
889 foreach ($preffComm as $v) {
890 $v = strtolower(trim($v));
891 if (array_key_exists($v, $pcm)) {
892 $comm[$pcm[$v]] = 1;
893 }
894 }
895
896 $params['preferred_communication_method'] = $comm;
897 return TRUE;
898 }
899
900 //format the website params.
901 if (CRM_Utils_Array::value('url', $values)) {
902 static $websiteFields;
903 if (!is_array($websiteFields)) {
904 require_once 'CRM/Core/DAO/Website.php';
905 $websiteFields = CRM_Core_DAO_Website::fields();
906 }
907 if (!array_key_exists('website', $params) ||
908 !is_array($params['website'])
909 ) {
910 $params['website'] = array();
911 }
912
913 $websiteCount = count($params['website']);
914 _civicrm_api3_store_values($websiteFields, $values,
915 $params['website'][++$websiteCount]
916 );
917
918 return TRUE;
919 }
920
921 // get the formatted location blocks into params - w/ 3.0 format, CRM-4605
922 if (CRM_Utils_Array::value('location_type_id', $values)) {
923 _civicrm_api3_deprecated_add_formatted_location_blocks($values, $params);
924 return TRUE;
925 }
926
927 if (isset($values['note'])) {
928 /* add a note field */
929
930
931 if (!isset($params['note'])) {
932 $params['note'] = array();
933 }
934 $noteBlock = count($params['note']) + 1;
935
936 $params['note'][$noteBlock] = array();
937 if (!isset($fields['Note'])) {
938 $fields['Note'] = CRM_Core_DAO_Note::fields();
939 }
940
941 // get the current logged in civicrm user
942 $session = CRM_Core_Session::singleton();
943 $userID = $session->get('userID');
944
945 if ($userID) {
946 $values['contact_id'] = $userID;
947 }
948
949 _civicrm_api3_store_values($fields['Note'], $values, $params['note'][$noteBlock]);
950
951 return TRUE;
952 }
953
954 /* Check for custom field values */
955
956 if (!CRM_Utils_Array::value('custom', $fields)) {
957 $fields['custom'] = &CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $values),
958 FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE
959 );
960 }
961
962 foreach ($values as $key => $value) {
963 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
964 /* check if it's a valid custom field id */
965
966
967 if (!array_key_exists($customFieldID, $fields['custom'])) {
968 return civicrm_api3_create_error('Invalid custom field ID');
969 }
970 else {
971 $params[$key] = $value;
972 }
973 }
974 }
975}
976
977/**
978 * This function format location blocks w/ v3.0 format.
979 *
980 * @param array $values The variable(s) to be added
981 * @param array $params The structured parameter list
982 *
983 * @return bool
984 * @access public
985 */
986function _civicrm_api3_deprecated_add_formatted_location_blocks(&$values, &$params) {
987 static $fields = NULL;
988 if ($fields == NULL) {
989 $fields = array();
990 }
991
992 foreach (array(
993 'Phone', 'Email', 'IM', 'OpenID','Phone_Ext') as $block) {
994 $name = strtolower($block);
995 if (!array_key_exists($name, $values)) {
996 continue;
997 }
998
999 if($name == 'phone_ext'){
1000 $block = 'Phone';
1001 }
1002
1003 // block present in value array.
1004 if (!array_key_exists($name, $params) || !is_array($params[$name])) {
1005 $params[$name] = array();
1006 }
1007
1008 if (!array_key_exists($block, $fields)) {
1009 require_once (str_replace('_', DIRECTORY_SEPARATOR, "CRM_Core_DAO_" . $block) . ".php");
1010 eval('$fields[$block] =& CRM_Core_DAO_' . $block . '::fields( );');
1011 }
1012
1013 $blockCnt = count($params[$name]);
1014
1015 // copy value to dao field name.
1016 if ($name == 'im') {
1017 $values['name'] = $values[$name];
1018 }
1019
1020 _civicrm_api3_store_values($fields[$block], $values,
1021 $params[$name][++$blockCnt]
1022 );
1023
1024 if (!CRM_Utils_Array::value('id', $params) && ($blockCnt == 1)) {
1025 $params[$name][$blockCnt]['is_primary'] = TRUE;
1026 }
1027
1028 // we only process single block at a time.
1029 return TRUE;
1030 }
1031
1032 // handle address fields.
1033 if (!array_key_exists('address', $params) || !is_array($params['address'])) {
1034 $params['address'] = array();
1035 }
1036
1037 $addressCnt = 1;
1038 foreach ($params['address'] as $cnt => $addressBlock) {
1039 if (CRM_Utils_Array::value('location_type_id', $values) ==
1040 CRM_Utils_Array::value('location_type_id', $addressBlock)
1041 ) {
1042 $addressCnt = $cnt;
1043 break;
1044 }
1045 $addressCnt++;
1046 }
1047
1048 if (!array_key_exists('Address', $fields)) {
1049 require_once 'CRM/Core/DAO/Address.php';
1050 $fields['Address'] = CRM_Core_DAO_Address::fields();
1051 }
1052
1053 // Note: we doing multiple value formatting here for address custom fields, plus putting into right format.
1054 // The actual formatting (like date, country ..etc) for address custom fields is taken care of while saving
1055 // the address in CRM_Core_BAO_Address::create method
1056 if (CRM_Utils_Array::value('location_type_id', $values)) {
1057 static $customFields = array();
1058 if (empty($customFields)) {
1059 $customFields = CRM_Core_BAO_CustomField::getFields('Address');
1060 }
1061 // make a copy of values, as we going to make changes
1062 $newValues = $values;
1063 foreach ($values as $key => $val) {
1064 $customFieldID = CRM_Core_BAO_CustomField::getKeyID($key);
1065 if ($customFieldID && array_key_exists($customFieldID, $customFields)) {
1066 // mark an entry in fields array since we want the value of custom field to be copied
1067 $fields['Address'][$key] = null;
1068
1069 $htmlType = CRM_Utils_Array::value( 'html_type', $customFields[$customFieldID] );
1070 switch ( $htmlType ) {
1071 case 'CheckBox':
1072 case 'AdvMulti-Select':
1073 case 'Multi-Select':
1074 if ( $val ) {
1075 $mulValues = explode( ',', $val );
1076 $customOption = CRM_Core_BAO_CustomOption::getCustomOption( $customFieldID, true );
1077 $newValues[$key] = array( );
1078 foreach ( $mulValues as $v1 ) {
1079 foreach ( $customOption as $v2 ) {
1080 if ( ( strtolower( $v2['label'] ) == strtolower( trim( $v1 ) ) ) ||
1081 ( strtolower( $v2['value'] ) == strtolower( trim( $v1 ) ) ) ) {
1082 if ( $htmlType == 'CheckBox' ) {
1083 $newValues[$key][$v2['value']] = 1;
1084 } else {
1085 $newValues[$key][] = $v2['value'];
1086 }
1087 }
1088 }
1089 }
1090 }
1091 break;
1092 }
1093 }
1094 }
1095 // consider new values
1096 $values = $newValues;
1097 }
1098
1099 _civicrm_api3_store_values($fields['Address'], $values, $params['address'][$addressCnt]);
1100
1101 $addressFields = array(
1102 'county', 'country', 'state_province',
1103 'supplemental_address_1', 'supplemental_address_2',
1104 'StateProvince.name',
1105 );
1106
1107 foreach ($addressFields as $field) {
1108 if (array_key_exists($field, $values)) {
1109 if (!array_key_exists('address', $params)) {
1110 $params['address'] = array();
1111 }
1112 $params['address'][$addressCnt][$field] = $values[$field];
1113 }
1114 }
1115
1116 if ($addressCnt == 1) {
1117
1118 $params['address'][$addressCnt]['is_primary'] = TRUE;
1119 }
1120
1121 return TRUE;
1122}
1123
1124/**
1125 *
1126 * @param <type> $params
1127 *
1128 * @return <type>
1129 */
1130function _civicrm_api3_deprecated_duplicate_formatted_contact($params) {
1131 $id = CRM_Utils_Array::value('id', $params);
1132 $externalId = CRM_Utils_Array::value('external_identifier', $params);
1133 if ($id || $externalId) {
1134 $contact = new CRM_Contact_DAO_Contact();
1135
1136 $contact->id = $id;
1137 $contact->external_identifier = $externalId;
1138
1139 if ($contact->find(TRUE)) {
1140 if ($params['contact_type'] != $contact->contact_type) {
1141 return civicrm_api3_create_error("Mismatched contact IDs OR Mismatched contact Types");
1142 }
1143
1144 $error = CRM_Core_Error::createError("Found matching contacts: $contact->id",
1145 CRM_Core_Error::DUPLICATE_CONTACT,
1146 'Fatal', $contact->id
1147 );
1148 return civicrm_api3_create_error($error->pop());
1149 }
1150 }
1151 else {
1152 require_once 'CRM/Dedupe/Finder.php';
1153 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
1154 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised');
1155
1156 if (!empty($ids)) {
1157 $ids = implode(',', $ids);
1158 $error = CRM_Core_Error::createError("Found matching contacts: $ids",
1159 CRM_Core_Error::DUPLICATE_CONTACT,
1160 'Fatal', $ids
1161 );
1162 return civicrm_api3_create_error($error->pop());
1163 }
1164 }
1165 return civicrm_api3_create_success(TRUE);
1166}
1167
1168/**
1169 * Validate a formatted contact parameter list.
1170 *
1171 * @param array $params Structured parameter list (as in crm_format_params)
1172 *
1173 * @return bool|CRM_Core_Error
1174 * @access public
1175 */
1176function _civicrm_api3_deprecated_validate_formatted_contact(&$params) {
1177 /* Look for offending email addresses */
1178
1179
1180 if (array_key_exists('email', $params)) {
1181 foreach ($params['email'] as $count => $values) {
1182 if (!is_array($values)) {
1183 continue;
1184 }
1185 if ($email = CRM_Utils_Array::value('email', $values)) {
1186 //validate each email
1187 if (!CRM_Utils_Rule::email($email)) {
1188 return civicrm_api3_create_error('No valid email address');
1189 }
1190
1191 //check for loc type id.
1192 if (!CRM_Utils_Array::value('location_type_id', $values)) {
1193 return civicrm_api3_create_error('Location Type Id missing.');
1194 }
1195 }
1196 }
1197 }
1198
1199 /* Validate custom data fields */
1200
1201
1202 if (array_key_exists('custom', $params) && is_array($params['custom'])) {
1203 foreach ($params['custom'] as $key => $custom) {
1204 if (is_array($custom)) {
1205 foreach ($custom as $fieldId => $value) {
1206 $valid = CRM_Core_BAO_CustomValue::typecheck(CRM_Utils_Array::value('type', $value),
1207 CRM_Utils_Array::value('value', $value)
1208 );
1209 if (!$valid) {
1210 return civicrm_api3_create_error('Invalid value for custom field \'' .
1211 CRM_Utils_Array::value('name', $custom) . '\''
1212 );
1213 }
1214 if (CRM_Utils_Array::value('type', $custom) == 'Date') {
1215 $params['custom'][$key][$fieldId]['value'] = str_replace('-', '', $params['custom'][$key][$fieldId]['value']);
1216 }
1217 }
1218 }
1219 }
1220 }
1221
1222 return civicrm_api3_create_success(TRUE);
1223}
1224
1225/**
1226 * take the input parameter list as specified in the data model and
1227 * convert it into the same format that we use in QF and BAO object
1228 *
1229 * @param array $params Associative array of property name/value
1230 * pairs to insert in new contact.
1231 * @param array $values The reformatted properties that we can use internally
1232 *
1233 * @param array $create Is the formatted Values array going to
1234 * be used for CRM_Member_BAO_Membership:create()
1235 *
1236 * @return array|error
1237 * @access public
1238 */
1239function _civicrm_api3_deprecated_membership_format_params($params, &$values, $create = FALSE) {
1240
1241 $fields = CRM_Member_DAO_Membership::fields();
1242 _civicrm_api3_store_values($fields, $params, $values);
1243
1244 require_once 'CRM/Core/OptionGroup.php';
1245 $customFields = CRM_Core_BAO_CustomField::getFields( 'Membership');
1246
1247 foreach ($params as $key => $value) {
1248 // ignore empty values or empty arrays etc
1249 if (CRM_Utils_System::isNull($value)) {
1250 continue;
1251 }
1252
1253 //Handling Custom Data
1254 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
1255 $values[$key] = $value;
1256 $type = $customFields[$customFieldID]['html_type'];
1257 if( $type == 'CheckBox' || $type == 'Multi-Select' || $type == 'AdvMulti-Select') {
1258 $mulValues = explode( ',' , $value );
1259 $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true);
1260 $values[$key] = array();
1261 foreach( $mulValues as $v1 ) {
1262 foreach($customOption as $customValueID => $customLabel) {
1263 $customValue = $customLabel['value'];
1264 if (( strtolower($customLabel['label']) == strtolower(trim($v1)) ) ||
1265 ( strtolower($customValue) == strtolower(trim($v1)) )) {
1266 if ( $type == 'CheckBox' ) {
1267 $values[$key][$customValue] = 1;
1268 } else {
1269 $values[$key][] = $customValue;
1270 }
1271 }
1272 }
1273 }
1274 }
1275 }
1276
1277 switch ($key) {
1278 case 'membership_contact_id':
1279 if (!CRM_Utils_Rule::integer($value)) {
1280 return civicrm_api3_create_error("contact_id not valid: $value");
1281 }
1282 $dao = new CRM_Core_DAO();
1283 $qParams = array();
1284 $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value",
1285 $qParams
1286 );
1287 if (!$svq) {
1288 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
1289 }
1290 $values['contact_id'] = $values['membership_contact_id'];
1291 unset($values['membership_contact_id']);
1292 break;
1293
1294 case 'membership_type_id':
1295 if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipType())) {
1296 return civicrm_api3_create_error('Invalid Membership Type Id');
1297 }
1298 $values[$key] = $value;
1299 break;
1300
1301 case 'membership_type':
1302 $membershipTypeId = CRM_Utils_Array::key(ucfirst($value),
1303 CRM_Member_PseudoConstant::membershipType()
1304 );
1305 if ($membershipTypeId) {
1306 if (CRM_Utils_Array::value('membership_type_id', $values) &&
1307 $membershipTypeId != $values['membership_type_id']
1308 ) {
1309 return civicrm_api3_create_error('Mismatched membership Type and Membership Type Id');
1310 }
1311 }
1312 else {
1313 return civicrm_api3_create_error('Invalid Membership Type');
1314 }
1315 $values['membership_type_id'] = $membershipTypeId;
1316 break;
1317
1318 case 'status_id':
1319 if (!CRM_Utils_Array::value($value, CRM_Member_PseudoConstant::membershipStatus())) {
1320 return civicrm_api3_create_error('Invalid Membership Status Id');
1321 }
1322 $values[$key] = $value;
1323 break;
1324
1325 case 'membership_status':
1326 $membershipStatusId = CRM_Utils_Array::key(ucfirst($value),
1327 CRM_Member_PseudoConstant::membershipStatus()
1328 );
1329 if ($membershipStatusId) {
1330 if (CRM_Utils_Array::value('status_id', $values) &&
1331 $membershipStatusId != $values['status_id']
1332 ) {
1333 return civicrm_api3_create_error('Mismatched membership Status and Membership Status Id');
1334 }
1335 }
1336 else {
1337 return civicrm_api3_create_error('Invalid Membership Status');
1338 }
1339 $values['status_id'] = $membershipStatusId;
1340 break;
1341
1342 default:
1343 break;
1344 }
1345 }
1346
1347 _civicrm_api3_custom_format_params($params, $values, 'Membership');
1348
1349
1350 if ($create) {
1351 // CRM_Member_BAO_Membership::create() handles membership_start_date,
1352 // membership_end_date and membership_source. So, if $values contains
1353 // membership_start_date, membership_end_date or membership_source,
1354 // convert it to start_date, end_date or source
1355 $changes = array(
1356 'membership_start_date' => 'start_date',
1357 'membership_end_date' => 'end_date',
1358 'membership_source' => 'source',
1359 );
1360
1361 foreach ($changes as $orgVal => $changeVal) {
1362 if (isset($values[$orgVal])) {
1363 $values[$changeVal] = $values[$orgVal];
1364 unset($values[$orgVal]);
1365 }
1366 }
1367 }
1368
1369 return NULL;
1370}
1371
1372/**
1373 * @deprecated - this is part of the import parser not the API & needs to be moved on out
1374 *
1375 * @param <type> $params
1376 * @param <type> $onDuplicate
1377 *
1378 * @return <type>
1379 */
1380function _civicrm_api3_deprecated_create_participant_formatted($params, $onDuplicate) {
1381 require_once 'CRM/Event/Import/Parser.php';
1382 if ($onDuplicate != CRM_Event_Import_Parser::DUPLICATE_NOCHECK) {
1383 CRM_Core_Error::reset();
1384 $error = _civicrm_api3_deprecated_participant_check_params($params, TRUE);
1385 if (civicrm_error($error)) {
1386 return $error;
1387 }
1388 }
1389 require_once "api/v3/Participant.php";
1390 return civicrm_api3_participant_create($params);
1391}
1392
1393/**
1394 *
1395 * @param <type> $params
1396 *
1397 * @return <type>
1398 */
1399function _civicrm_api3_deprecated_participant_check_params($params, $checkDuplicate = FALSE) {
1400
1401 //check if participant id is valid or not
1402 if (CRM_Utils_Array::value('id', $params)) {
1403 $participant = new CRM_Event_BAO_Participant();
1404 $participant->id = $params['id'];
1405 if (!$participant->find(TRUE)) {
1406 return civicrm_api3_create_error(ts('Participant id is not valid'));
1407 }
1408 }
1409 require_once 'CRM/Contact/BAO/Contact.php';
1410 //check if contact id is valid or not
1411 if (CRM_Utils_Array::value('contact_id', $params)) {
1412 $contact = new CRM_Contact_BAO_Contact();
1413 $contact->id = $params['contact_id'];
1414 if (!$contact->find(TRUE)) {
1415 return civicrm_api3_create_error(ts('Contact id is not valid'));
1416 }
1417 }
1418
1419 //check that event id is not an template
1420 if (CRM_Utils_Array::value('event_id', $params)) {
1421 $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'is_template');
1422 if (!empty($isTemplate)) {
1423 return civicrm_api3_create_error(ts('Event templates are not meant to be registered'));
1424 }
1425 }
1426
1427 $result = array();
1428 if ($checkDuplicate) {
1429 if (CRM_Event_BAO_Participant::checkDuplicate($params, $result)) {
1430 $participantID = array_pop($result);
1431
1432 $error = CRM_Core_Error::createError("Found matching participant record.",
1433 CRM_Core_Error::DUPLICATE_PARTICIPANT,
1434 'Fatal', $participantID
1435 );
1436
1437 return civicrm_api3_create_error($error->pop(),
1438 array(
1439 'contactID' => $params['contact_id'],
1440 'participantID' => $participantID,
1441 )
1442 );
1443 }
1444 }
1445 return TRUE;
1446}
1447
1448/**
1449 * Ensure that we have the right input parameters for custom data
1450 *
1451 * @param array $params Associative array of property name/value
1452 * pairs to insert in new contact.
1453 * @param string $csType contact subtype if exists/passed.
1454 *
1455 * @return null on success, error message otherwise
1456 * @access public
1457 */
1458function _civicrm_api3_deprecated_contact_check_custom_params($params, $csType = NULL) {
1459 empty($csType) ? $onlyParent = TRUE : $onlyParent = FALSE;
1460
1461 require_once 'CRM/Core/BAO/CustomField.php';
1462 $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'],
1463 FALSE,
1464 FALSE,
1465 $csType,
1466 NULL,
1467 $onlyParent,
1468 FALSE,
1469 FALSE
1470 );
1471
1472 foreach ($params as $key => $value) {
1473 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
1474 /* check if it's a valid custom field id */
1475
1476
1477 if (!array_key_exists($customFieldID, $customFields)) {
1478
1479 $errorMsg = "Invalid Custom Field Contact Type: {$params['contact_type']}";
1480 if (!empty($csType)) {
1481 $errorMsg .= " or Mismatched SubType: " . implode(', ', (array)$csType);
1482 }
1483 return civicrm_api3_create_error($errorMsg);
1484 }
1485 }
1486 }
1487}
1488
109ff2ac
DL
1489function _civicrm_api3_deprecated_contact_check_params(
1490 &$params,
1491 $dupeCheck = TRUE,
1492 $dupeErrorArray = FALSE,
1493 $requiredCheck = TRUE,
1494 $dedupeRuleGroupID = NULL) {
6a488035
TO
1495 if (isset($params['id']) && is_numeric($params['id'])) {
1496 $requiredCheck = FALSE;
1497 }
1498 if ($requiredCheck) {
1499 if (isset($params['id'])) {
1500 $required = array('Individual', 'Household', 'Organization');
1501 }
1502 $required = array(
1503 'Individual' => array(
1504 array('first_name', 'last_name'),
1505 'email',
1506 ),
1507 'Household' => array(
1508 'household_name',
1509 ),
1510 'Organization' => array(
1511 'organization_name',
1512 ),
1513 );
1514
1515
1516 // contact_type has a limited number of valid values
1517 $fields = CRM_Utils_Array::value($params['contact_type'], $required);
1518 if ($fields == NULL) {
1519 return civicrm_api3_create_error("Invalid Contact Type: {$params['contact_type']}");
1520 }
1521
1522 if ($csType = CRM_Utils_Array::value('contact_sub_type', $params)) {
1523 if (!(CRM_Contact_BAO_ContactType::isExtendsContactType($csType, $params['contact_type']))) {
1524 return civicrm_api3_create_error("Invalid or Mismatched Contact SubType: " . implode(', ', (array)$csType));
1525 }
1526 }
1527
1528 if (!CRM_Utils_Array::value('contact_id', $params) && CRM_Utils_Array::value('id', $params)) {
1529 $valid = FALSE;
1530 $error = '';
1531 foreach ($fields as $field) {
1532 if (is_array($field)) {
1533 $valid = TRUE;
1534 foreach ($field as $element) {
1535 if (!CRM_Utils_Array::value($element, $params)) {
1536 $valid = FALSE;
1537 $error .= $element;
1538 break;
1539 }
1540 }
1541 }
1542 else {
1543 if (CRM_Utils_Array::value($field, $params)) {
1544 $valid = TRUE;
1545 }
1546 }
1547 if ($valid) {
1548 break;
1549 }
1550 }
1551
1552 if (!$valid) {
1553 return civicrm_api3_create_error("Required fields not found for {$params['contact_type']} : $error");
1554 }
1555 }
1556 }
1557
1558 if ($dupeCheck) {
1559 // check for record already existing
1560 require_once 'CRM/Dedupe/Finder.php';
1561 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
1562
1563 // CRM-6431
1564 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
1565 // person does not have permission to carry out de-dupes
1566 // this is similar to the front end form
1567 if (isset($params['check_permission'])) {
1568 $dedupeParams['check_permission'] = $params['check_permission'];
1569 }
1570
1571 $ids = implode(',', CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array(), $dedupeRuleGroupID));
1572
1573 if ($ids != NULL) {
1574 if ($dupeErrorArray) {
1575 $error = CRM_Core_Error::createError("Found matching contacts: $ids",
1576 CRM_Core_Error::DUPLICATE_CONTACT,
1577 'Fatal', $ids
1578 );
1579 return civicrm_api3_create_error($error->pop());
1580 }
1581
1582 return civicrm_api3_create_error("Found matching contacts: $ids");
1583 }
1584 }
1585
1586 //check for organisations with same name
1587 if (CRM_Utils_Array::value('current_employer', $params)) {
1588 $organizationParams = array();
1589 $organizationParams['organization_name'] = $params['current_employer'];
1590
1591 require_once 'CRM/Dedupe/Finder.php';
1592 $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
1593
1594 $dedupParams['check_permission'] = FALSE;
1595 $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Supervised');
1596
1597 // check for mismatch employer name and id
1598 if (CRM_Utils_Array::value('employer_id', $params)
1599 && !in_array($params['employer_id'], $dupeIds)
1600 ) {
1601 return civicrm_api3_create_error('Employer name and Employer id Mismatch');
1602 }
1603
1604 // show error if multiple organisation with same name exist
1605 if (!CRM_Utils_Array::value('employer_id', $params)
1606 && (count($dupeIds) > 1)
1607 ) {
1608 return civicrm_api3_create_error('Found more than one Organisation with same Name.');
1609 }
1610 }
1611
1612 return NULL;
1613}
1614
109ff2ac
DL
1615/**
1616 *
1617 * @param <type> $result
1618 * @param <type> $activityTypeID
1619 *
1620 * @return <type> $params
1621 */
1622function _civicrm_api3_deprecated_activity_buildmailparams($result, $activityTypeID) {
1623 // get ready for collecting data about activity to be created
1624 $params = array();
1625
1626 $params['activity_type_id'] = $activityTypeID;
1627
1628 $params['status_id'] = 2;
1629 $params['source_contact_id'] = $params['assignee_contact_id'] = $result['from']['id'];
1630 $params['target_contact_id'] = array();
1631 $keys = array('to', 'cc', 'bcc');
1632 foreach ($keys as $key) {
1633 if (is_array($result[$key])) {
1634 foreach ($result[$key] as $key => $keyValue) {
1635 if (!empty($keyValue['id'])) {
1636 $params['target_contact_id'][] = $keyValue['id'];
1637 }
1638 }
1639 }
1640 }
1641 $params['subject'] = $result['subject'];
1642 $params['activity_date_time'] = $result['date'];
1643 $params['details'] = $result['body'];
1644
1645 for ($i = 1; $i <= 5; $i++) {
1646 if (isset($result["attachFile_$i"])) {
1647 $params["attachFile_$i"] = $result["attachFile_$i"];
1648 }
1649 }
1650
1651 return $params;
1652}