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