INFRA-132 - Put space after flow-control (if/switch/for/foreach/while)
[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 else if ($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', 'Email', 'IM', 'OpenID', 'Phone_Ext') as $block) {
989 $name = strtolower($block);
990 if (!array_key_exists($name, $values)) {
991 continue;
992 }
993
994 if ($name == 'phone_ext'){
995 $block = 'Phone';
996 }
997
998 // block present in value array.
999 if (!array_key_exists($name, $params) || !is_array($params[$name])) {
1000 $params[$name] = array();
1001 }
1002
1003 if (!array_key_exists($block, $fields)) {
1004 $className = "CRM_Core_DAO_$block";
1005 $fields[$block] =& $className::fields( );
1006 }
1007
1008 $blockCnt = count($params[$name]);
1009
1010 // copy value to dao field name.
1011 if ($name == 'im') {
1012 $values['name'] = $values[$name];
1013 }
1014
1015 _civicrm_api3_store_values($fields[$block], $values,
1016 $params[$name][++$blockCnt]
1017 );
1018
1019 if (empty($params['id']) && ($blockCnt == 1)) {
1020 $params[$name][$blockCnt]['is_primary'] = TRUE;
1021 }
1022
1023 // we only process single block at a time.
1024 return TRUE;
1025 }
1026
1027 // handle address fields.
1028 if (!array_key_exists('address', $params) || !is_array($params['address'])) {
1029 $params['address'] = array();
1030 }
1031
1032 $addressCnt = 1;
1033 foreach ($params['address'] as $cnt => $addressBlock) {
1034 if (CRM_Utils_Array::value('location_type_id', $values) ==
1035 CRM_Utils_Array::value('location_type_id', $addressBlock)
1036 ) {
1037 $addressCnt = $cnt;
1038 break;
1039 }
1040 $addressCnt++;
1041 }
1042
1043 if (!array_key_exists('Address', $fields)) {
1044 require_once 'CRM/Core/DAO/Address.php';
1045 $fields['Address'] = CRM_Core_DAO_Address::fields();
1046 }
1047
1048 // Note: we doing multiple value formatting here for address custom fields, plus putting into right format.
1049 // The actual formatting (like date, country ..etc) for address custom fields is taken care of while saving
1050 // the address in CRM_Core_BAO_Address::create method
1051 if (!empty($values['location_type_id'])) {
1052 static $customFields = array();
1053 if (empty($customFields)) {
1054 $customFields = CRM_Core_BAO_CustomField::getFields('Address');
1055 }
1056 // make a copy of values, as we going to make changes
1057 $newValues = $values;
1058 foreach ($values as $key => $val) {
1059 $customFieldID = CRM_Core_BAO_CustomField::getKeyID($key);
1060 if ($customFieldID && array_key_exists($customFieldID, $customFields)) {
1061 // mark an entry in fields array since we want the value of custom field to be copied
1062 $fields['Address'][$key] = NULL;
1063
1064 $htmlType = CRM_Utils_Array::value( 'html_type', $customFields[$customFieldID] );
1065 switch ( $htmlType ) {
1066 case 'CheckBox':
1067 case 'AdvMulti-Select':
1068 case 'Multi-Select':
1069 if ( $val ) {
1070 $mulValues = explode( ',', $val );
1071 $customOption = CRM_Core_BAO_CustomOption::getCustomOption( $customFieldID, TRUE );
1072 $newValues[$key] = array();
1073 foreach ( $mulValues as $v1 ) {
1074 foreach ( $customOption as $v2 ) {
1075 if ( ( strtolower( $v2['label'] ) == strtolower( trim( $v1 ) ) ) ||
1076 ( strtolower( $v2['value'] ) == strtolower( trim( $v1 ) ) ) ) {
1077 if ( $htmlType == 'CheckBox' ) {
1078 $newValues[$key][$v2['value']] = 1;
1079 }
1080 else {
1081 $newValues[$key][] = $v2['value'];
1082 }
1083 }
1084 }
1085 }
1086 }
1087 break;
1088 }
1089 }
1090 }
1091 // consider new values
1092 $values = $newValues;
1093 }
1094
1095 _civicrm_api3_store_values($fields['Address'], $values, $params['address'][$addressCnt]);
1096
1097 $addressFields = array(
1098 'county', 'country', 'state_province',
1099 'supplemental_address_1', 'supplemental_address_2',
1100 'StateProvince.name',
1101 );
1102
1103 foreach ($addressFields as $field) {
1104 if (array_key_exists($field, $values)) {
1105 if (!array_key_exists('address', $params)) {
1106 $params['address'] = array();
1107 }
1108 $params['address'][$addressCnt][$field] = $values[$field];
1109 }
1110 }
1111
1112 if ($addressCnt == 1) {
1113
1114 $params['address'][$addressCnt]['is_primary'] = TRUE;
1115 }
1116
1117 return TRUE;
1118 }
1119
1120 /**
1121 *
1122 * @param <type> $params
1123 *
1124 * @return array <type>
1125 */
1126 function _civicrm_api3_deprecated_duplicate_formatted_contact($params) {
1127 $id = CRM_Utils_Array::value('id', $params);
1128 $externalId = CRM_Utils_Array::value('external_identifier', $params);
1129 if ($id || $externalId) {
1130 $contact = new CRM_Contact_DAO_Contact();
1131
1132 $contact->id = $id;
1133 $contact->external_identifier = $externalId;
1134
1135 if ($contact->find(TRUE)) {
1136 if ($params['contact_type'] != $contact->contact_type) {
1137 return civicrm_api3_create_error("Mismatched contact IDs OR Mismatched contact Types");
1138 }
1139
1140 $error = CRM_Core_Error::createError("Found matching contacts: $contact->id",
1141 CRM_Core_Error::DUPLICATE_CONTACT,
1142 'Fatal', $contact->id
1143 );
1144 return civicrm_api3_create_error($error->pop());
1145 }
1146 }
1147 else {
1148 require_once 'CRM/Dedupe/Finder.php';
1149 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
1150 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised');
1151
1152 if (!empty($ids)) {
1153 $ids = implode(',', $ids);
1154 $error = CRM_Core_Error::createError("Found matching contacts: $ids",
1155 CRM_Core_Error::DUPLICATE_CONTACT,
1156 'Fatal', $ids
1157 );
1158 return civicrm_api3_create_error($error->pop());
1159 }
1160 }
1161 return civicrm_api3_create_success(TRUE);
1162 }
1163
1164 /**
1165 * Validate a formatted contact parameter list.
1166 *
1167 * @param array $params
1168 * Structured parameter list (as in crm_format_params).
1169 *
1170 * @return bool|CRM_Core_Error
1171 */
1172 function _civicrm_api3_deprecated_validate_formatted_contact(&$params) {
1173 /* Look for offending email addresses */
1174
1175 if (array_key_exists('email', $params)) {
1176 foreach ($params['email'] as $count => $values) {
1177 if (!is_array($values)) {
1178 continue;
1179 }
1180 if ($email = CRM_Utils_Array::value('email', $values)) {
1181 //validate each email
1182 if (!CRM_Utils_Rule::email($email)) {
1183 return civicrm_api3_create_error('No valid email address');
1184 }
1185
1186 //check for loc type id.
1187 if (empty($values['location_type_id'])) {
1188 return civicrm_api3_create_error('Location Type Id missing.');
1189 }
1190 }
1191 }
1192 }
1193
1194 /* Validate custom data fields */
1195 if (array_key_exists('custom', $params) && is_array($params['custom'])) {
1196 foreach ($params['custom'] as $key => $custom) {
1197 if (is_array($custom)) {
1198 foreach ($custom as $fieldId => $value) {
1199 $valid = CRM_Core_BAO_CustomValue::typecheck(CRM_Utils_Array::value('type', $value),
1200 CRM_Utils_Array::value('value', $value)
1201 );
1202 if (!$valid && $value['is_required']) {
1203 return civicrm_api3_create_error('Invalid value for custom field \'' .
1204 CRM_Utils_Array::value('name', $custom) . '\''
1205 );
1206 }
1207 if (CRM_Utils_Array::value('type', $custom) == 'Date') {
1208 $params['custom'][$key][$fieldId]['value'] = str_replace('-', '', $params['custom'][$key][$fieldId]['value']);
1209 }
1210 }
1211 }
1212 }
1213 }
1214
1215 return civicrm_api3_create_success(TRUE);
1216 }
1217
1218
1219 /**
1220 * @deprecated - this is part of the import parser not the API & needs to be moved on out
1221 *
1222 * @param array $params
1223 * @param $onDuplicate
1224 *
1225 * @return array|bool <type>
1226 */
1227 function _civicrm_api3_deprecated_create_participant_formatted($params, $onDuplicate) {
1228 require_once 'CRM/Event/Import/Parser.php';
1229 if ($onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) {
1230 CRM_Core_Error::reset();
1231 $error = _civicrm_api3_deprecated_participant_check_params($params, TRUE);
1232 if (civicrm_error($error)) {
1233 return $error;
1234 }
1235 }
1236 require_once "api/v3/Participant.php";
1237 return civicrm_api3_participant_create($params);
1238 }
1239
1240 /**
1241 *
1242 * @param <type> $params
1243 *
1244 * @param bool $checkDuplicate
1245 *
1246 * @return array|bool <type>
1247 */
1248 function _civicrm_api3_deprecated_participant_check_params($params, $checkDuplicate = FALSE) {
1249
1250 //check if participant id is valid or not
1251 if (!empty($params['id'])) {
1252 $participant = new CRM_Event_BAO_Participant();
1253 $participant->id = $params['id'];
1254 if (!$participant->find(TRUE)) {
1255 return civicrm_api3_create_error(ts('Participant id is not valid'));
1256 }
1257 }
1258 require_once 'CRM/Contact/BAO/Contact.php';
1259 //check if contact id is valid or not
1260 if (!empty($params['contact_id'])) {
1261 $contact = new CRM_Contact_BAO_Contact();
1262 $contact->id = $params['contact_id'];
1263 if (!$contact->find(TRUE)) {
1264 return civicrm_api3_create_error(ts('Contact id is not valid'));
1265 }
1266 }
1267
1268 //check that event id is not an template
1269 if (!empty($params['event_id'])) {
1270 $isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'is_template');
1271 if (!empty($isTemplate)) {
1272 return civicrm_api3_create_error(ts('Event templates are not meant to be registered.'));
1273 }
1274 }
1275
1276 $result = array();
1277 if ($checkDuplicate) {
1278 if (CRM_Event_BAO_Participant::checkDuplicate($params, $result)) {
1279 $participantID = array_pop($result);
1280
1281 $error = CRM_Core_Error::createError("Found matching participant record.",
1282 CRM_Core_Error::DUPLICATE_PARTICIPANT,
1283 'Fatal', $participantID
1284 );
1285
1286 return civicrm_api3_create_error($error->pop(),
1287 array(
1288 'contactID' => $params['contact_id'],
1289 'participantID' => $participantID,
1290 )
1291 );
1292 }
1293 }
1294 return TRUE;
1295 }
1296
1297 /**
1298 * Ensure that we have the right input parameters for custom data
1299 *
1300 * @param array $params
1301 * Associative array of property name/value.
1302 * pairs to insert in new contact.
1303 * @param string $csType
1304 * Contact subtype if exists/passed.
1305 *
1306 * @return null on success, error message otherwise
1307 */
1308 function _civicrm_api3_deprecated_contact_check_custom_params($params, $csType = NULL) {
1309 empty($csType) ? $onlyParent = TRUE : $onlyParent = FALSE;
1310
1311 require_once 'CRM/Core/BAO/CustomField.php';
1312 $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'],
1313 FALSE,
1314 FALSE,
1315 $csType,
1316 NULL,
1317 $onlyParent,
1318 FALSE,
1319 FALSE
1320 );
1321
1322 foreach ($params as $key => $value) {
1323 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
1324 /* check if it's a valid custom field id */
1325 if (!array_key_exists($customFieldID, $customFields)) {
1326
1327 $errorMsg = "Invalid Custom Field Contact Type: {$params['contact_type']}";
1328 if (!empty($csType)) {
1329 $errorMsg .= " or Mismatched SubType: " . implode(', ', (array) $csType);
1330 }
1331 return civicrm_api3_create_error($errorMsg);
1332 }
1333 }
1334 }
1335 }
1336
1337 /**
1338 * @param array $params
1339 * @param bool $dupeCheck
1340 * @param bool $dupeErrorArray
1341 * @param bool $requiredCheck
1342 * @param int $dedupeRuleGroupID
1343 *
1344 * @return array|null
1345 */
1346 function _civicrm_api3_deprecated_contact_check_params(
1347 &$params,
1348 $dupeCheck = TRUE,
1349 $dupeErrorArray = FALSE,
1350 $requiredCheck = TRUE,
1351 $dedupeRuleGroupID = NULL) {
1352 if (isset($params['id']) && is_numeric($params['id'])) {
1353 $requiredCheck = FALSE;
1354 }
1355 if ($requiredCheck) {
1356 if (isset($params['id'])) {
1357 $required = array('Individual', 'Household', 'Organization');
1358 }
1359 $required = array(
1360 'Individual' => array(
1361 array('first_name', 'last_name'),
1362 'email',
1363 ),
1364 'Household' => array(
1365 'household_name',
1366 ),
1367 'Organization' => array(
1368 'organization_name',
1369 ),
1370 );
1371
1372 // contact_type has a limited number of valid values
1373 if (empty($params['contact_type'])) {
1374 return civicrm_api3_create_error("No Contact Type");
1375 }
1376 $fields = CRM_Utils_Array::value($params['contact_type'], $required);
1377 if ($fields == NULL) {
1378 return civicrm_api3_create_error("Invalid Contact Type: {$params['contact_type']}");
1379 }
1380
1381 if ($csType = CRM_Utils_Array::value('contact_sub_type', $params)) {
1382 if (!(CRM_Contact_BAO_ContactType::isExtendsContactType($csType, $params['contact_type']))) {
1383 return civicrm_api3_create_error("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $csType));
1384 }
1385 }
1386
1387 if (empty($params['contact_id']) && !empty($params['id'])) {
1388 $valid = FALSE;
1389 $error = '';
1390 foreach ($fields as $field) {
1391 if (is_array($field)) {
1392 $valid = TRUE;
1393 foreach ($field as $element) {
1394 if (empty($params[$element])) {
1395 $valid = FALSE;
1396 $error .= $element;
1397 break;
1398 }
1399 }
1400 }
1401 else {
1402 if (!empty($params[$field])) {
1403 $valid = TRUE;
1404 }
1405 }
1406 if ($valid) {
1407 break;
1408 }
1409 }
1410
1411 if (!$valid) {
1412 return civicrm_api3_create_error("Required fields not found for {$params['contact_type']} : $error");
1413 }
1414 }
1415 }
1416
1417 if ($dupeCheck) {
1418 // check for record already existing
1419 require_once 'CRM/Dedupe/Finder.php';
1420 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
1421
1422 // CRM-6431
1423 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
1424 // person does not have permission to carry out de-dupes
1425 // this is similar to the front end form
1426 if (isset($params['check_permission'])) {
1427 $dedupeParams['check_permission'] = $params['check_permission'];
1428 }
1429
1430 $ids = implode(',', CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array(), $dedupeRuleGroupID));
1431
1432 if ($ids != NULL) {
1433 if ($dupeErrorArray) {
1434 $error = CRM_Core_Error::createError("Found matching contacts: $ids",
1435 CRM_Core_Error::DUPLICATE_CONTACT,
1436 'Fatal', $ids
1437 );
1438 return civicrm_api3_create_error($error->pop());
1439 }
1440
1441 return civicrm_api3_create_error("Found matching contacts: $ids");
1442 }
1443 }
1444
1445 //check for organisations with same name
1446 if (!empty($params['current_employer'])) {
1447 $organizationParams = array();
1448 $organizationParams['organization_name'] = $params['current_employer'];
1449
1450 require_once 'CRM/Dedupe/Finder.php';
1451 $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
1452
1453 $dedupParams['check_permission'] = FALSE;
1454 $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Supervised');
1455
1456 // check for mismatch employer name and id
1457 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)
1458 ) {
1459 return civicrm_api3_create_error('Employer name and Employer id Mismatch');
1460 }
1461
1462 // show error if multiple organisation with same name exist
1463 if (empty($params['employer_id']) && (count($dupeIds) > 1)
1464 ) {
1465 return civicrm_api3_create_error('Found more than one Organisation with same Name.');
1466 }
1467 }
1468
1469 return NULL;
1470 }
1471
1472 /**
1473 *
1474 * @param $result
1475 * @param int $activityTypeID
1476 *
1477 * @return array <type> $params
1478 */
1479 function _civicrm_api3_deprecated_activity_buildmailparams($result, $activityTypeID) {
1480 // get ready for collecting data about activity to be created
1481 $params = array();
1482
1483 $params['activity_type_id'] = $activityTypeID;
1484
1485 $params['status_id'] = 2;
1486 $params['source_contact_id'] = $params['assignee_contact_id'] = $result['from']['id'];
1487 $params['target_contact_id'] = array();
1488 $keys = array('to', 'cc', 'bcc');
1489 foreach ($keys as $key) {
1490 if (is_array($result[$key])) {
1491 foreach ($result[$key] as $key => $keyValue) {
1492 if (!empty($keyValue['id'])) {
1493 $params['target_contact_id'][] = $keyValue['id'];
1494 }
1495 }
1496 }
1497 }
1498 $params['subject'] = $result['subject'];
1499 $params['activity_date_time'] = $result['date'];
1500 $params['details'] = $result['body'];
1501
1502 for ($i = 1; $i <= 5; $i++) {
1503 if (isset($result["attachFile_$i"])) {
1504 $params["attachFile_$i"] = $result["attachFile_$i"];
1505 }
1506 }
1507
1508 return $params;
1509 }