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