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