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