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