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