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