Merge pull request #5052 from colemanw/CRM-15903
[civicrm-core.git] / api / v3 / Contact.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 * new version of civicrm apis. See blog post at
30 * http://civicrm.org/node/131
31 * @todo Write sth
32 *
33 * @package CiviCRM_APIv3
34 * @subpackage API_Contact
35 * @copyright CiviCRM LLC (c) 2004-2014
36 * $Id: Contact.php 30879 2010-11-22 15:45:55Z shot $
37 *
38 */
39
40 /**
41 * Create or update a contact (note you should always call this via civicrm_api() & never directly)
42 *
43 * @param array $params
44 * Input parameters.
45 *
46 * Allowed @params array keys are:
47 * {@getfields contact_create}
48 *
49 *
50 * @throws API_Exception
51 * @example ContactCreate.php Example of Create Call
52 *
53 * @return array
54 * API Result Array
55 *
56 */
57 function civicrm_api3_contact_create($params) {
58
59 $contactID = CRM_Utils_Array::value('contact_id', $params, CRM_Utils_Array::value('id', $params));
60 $dupeCheck = CRM_Utils_Array::value('dupe_check', $params, FALSE);
61 $values = _civicrm_api3_contact_check_params($params, $dupeCheck);
62 if ($values) {
63 return $values;
64 }
65
66 if (!$contactID) {
67 // If we get here, we're ready to create a new contact
68 if (($email = CRM_Utils_Array::value('email', $params)) && !is_array($params['email'])) {
69 $defLocType = CRM_Core_BAO_LocationType::getDefault();
70 $params['email'] = array(
71 1 => array(
72 'email' => $email,
73 'is_primary' => 1,
74 'location_type_id' => ($defLocType->id) ? $defLocType->id : 1,
75 ),
76 );
77 }
78 }
79
80 if (!empty($params['home_url'])) {
81 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
82 $params['website'] = array(
83 1 => array(
84 'website_type_id' => key($websiteTypes),
85 'url' => $params['home_url'],
86 ),
87 );
88 }
89
90 _civicrm_api3_greeting_format_params($params);
91
92 $values = array();
93
94 if (empty($params['contact_type']) && $contactID) {
95 $params['contact_type'] = CRM_Contact_BAO_Contact::getContactType($contactID);
96 }
97
98 if (!isset($params['contact_sub_type']) && $contactID) {
99 $params['contact_sub_type'] = CRM_Contact_BAO_Contact::getContactSubType($contactID);
100 }
101
102 _civicrm_api3_custom_format_params($params, $values, $params['contact_type'], $contactID);
103
104 $params = array_merge($params, $values);
105 //@todo we should just call basic_create here - but need to make contact:create accept 'id' on the bao
106 $contact = _civicrm_api3_contact_update($params, $contactID);
107
108 if (is_a($contact, 'CRM_Core_Error')) {
109 throw new API_Exception($contact->_errors[0]['message']);
110 }
111 else {
112 $values = array();
113 _civicrm_api3_object_to_array_unique_fields($contact, $values[$contact->id]);
114 }
115
116 return civicrm_api3_create_success($values, $params, 'Contact', 'create');
117 }
118
119 /**
120 * Adjust Metadata for Create action.
121 *
122 * @param array $params
123 * Array or parameters determined by getfields.
124 */
125 function _civicrm_api3_contact_create_spec(&$params) {
126 $params['contact_type']['api.required'] = 1;
127 $params['id']['api.aliases'] = array('contact_id');
128 $params['current_employer'] = array(
129 'title' => 'Current Employer',
130 'description' => 'Name of Current Employer',
131 'type' => CRM_Utils_Type::T_STRING,
132 );
133 $params['dupe_check'] = array(
134 'title' => 'Check for Duplicates',
135 'description' => 'Throw error if contact create matches dedupe rule',
136 );
137 $params['prefix_id']['api.aliases'] = array('individual_prefix', 'individual_prefix_id');
138 $params['suffix_id']['api.aliases'] = array('individual_suffix', 'individual_suffix_id');
139 }
140
141 /**
142 * Retrieve one or more contacts, given a set of search params
143 *
144 * @return array
145 * API Result Array
146 */
147 function civicrm_api3_contact_get($params) {
148 $options = array();
149 _civicrm_api3_contact_get_supportanomalies($params, $options);
150 $contacts = _civicrm_api3_get_using_query_object('contact', $params, $options);
151 return civicrm_api3_create_success($contacts, $params, 'contact');
152 }
153
154 /**
155 * @param array $params
156 *
157 * @return int
158 */
159 function civicrm_api3_contact_getcount($params) {
160 $options = array();
161 _civicrm_api3_contact_get_supportanomalies($params, $options);
162 $count = _civicrm_api3_get_using_query_object('contact', $params, $options, 1);
163 return (int) $count;
164 }
165
166 /**
167 * Adjust Metadata for Get action
168 *
169 * @param array $params
170 * Array or parameters determined by getfields.
171 */
172 function _civicrm_api3_contact_get_spec(&$params) {
173 $params['contact_is_deleted']['api.default'] = 0;
174
175 //we declare all these pseudofields as there are other undocumented fields accessible
176 // via the api - but if check permissions is set we only allow declared fields
177 $params['address_id']['title'] = 'Primary Address ID';
178 $params['street_address']['title'] = 'Primary Address Street Address';
179 $params['supplemental_address_1']['title'] = 'Primary Address Supplemental Address 1';
180 $params['supplemental_address_2']['title'] = 'Primary Address Supplemental Address 2';
181 $params['current_employer']['title'] = 'Current Employer';
182 $params['city']['title'] = 'Primary Address City';
183 $params['postal_code_suffix']['title'] = 'Primary Address Post Code Suffix';
184 $params['postal_code']['title'] = 'Primary Address Post Code';
185 $params['geo_code_1']['title'] = 'Primary Address Latitude';
186 $params['geo_code_2']['title'] = 'Primary Address Longitude';
187 $params['state_province_id']['title'] = 'Primary Address State Province ID';
188 $params['state_province_name']['title'] = 'Primary Address State Province Name';
189 $params['state_province']['title'] = 'Primary Address State Province';
190 $params['country_id']['title'] = 'Primary Address Country ID';
191 $params['country']['title'] = 'Primary Address country';
192 $params['worldregion_id']['title'] = 'Primary Address World Region ID';
193 $params['worldregion']['title'] = 'Primary Address World Region';
194 $params['phone_id']['title'] = 'Primary Phone ID';
195 $params['phone']['title'] = 'Primary Phone';
196 $params['phone_type_id']['title'] = 'Primary Phone Type ID';
197 $params['provider_id']['title'] = 'Primary Phone Provider ID';
198 $params['email_id']['title'] = 'Primary Email ID';
199 $params['email']['title'] = 'Primary Email';
200 $params['gender_id']['title'] = 'Gender ID';
201 $params['gender']['title'] = 'Gender';
202 $params['on_hold']['title'] = 'Primary Email On Hold';
203 $params['im']['title'] = 'Primary Instant Messenger';
204 $params['im_id']['title'] = 'Primary Instant Messenger ID';
205 $params['group_id']['title'] = 'Group Memberships (filter)';
206 $params['group']['title'] = 'Group Memberships (filter, array)';
207 $params['tag']['title'] = 'Assigned tags (filter, array)';
208 $params['birth_date_low'] = array('name' => 'birth_date_low', 'type' => CRM_Utils_Type::T_DATE, 'title' => ts('Birth Date is equal to or greater than'));
209 $params['birth_date_high'] = array('name' => 'birth_date_high', 'type' => CRM_Utils_Type::T_DATE, 'title' => ts('Birth Date is equal to or less than'));
210 $params['deceased_date_low'] = array('name' => 'deceased_date_low', 'type' => CRM_Utils_Type::T_DATE, 'title' => ts('Deceased Date is equal to or greater than'));
211 $params['deceased_date_high'] = array('name' => 'deceased_date_high', 'type' => CRM_Utils_Type::T_DATE, 'title' => ts('Deceased Date is equal to or less than'));
212 }
213
214 /**
215 * We are supporting 'showAll' = 'all', 'trash' or 'active' for contact get
216 * and for getcount
217 * - hopefully some day we'll come up with a std syntax for the 3-way-boolean of
218 * 0, 1 or not set
219 *
220 * We also support 'filter_group_id' & 'filter.group_id'
221 *
222 * @param array $params
223 * As passed into api get or getcount function.
224 * @param array $options
225 * Array of options (so we can modify the filter).
226 */
227 function _civicrm_api3_contact_get_supportanomalies(&$params, &$options) {
228 if (isset($params['showAll'])) {
229 if (strtolower($params['showAll']) == "active") {
230 $params['contact_is_deleted'] = 0;
231 }
232 if (strtolower($params['showAll']) == "trash") {
233 $params['contact_is_deleted'] = 1;
234 }
235 if (strtolower($params['showAll']) == "all" && isset($params['contact_is_deleted'])) {
236 unset($params['contact_is_deleted']);
237 }
238 }
239 // support for group filters
240 if (array_key_exists('filter_group_id', $params)) {
241 $params['filter.group_id'] = $params['filter_group_id'];
242 unset($params['filter_group_id']);
243 }
244 // filter.group_id works both for 1,2,3 and array (1,2,3)
245 if (array_key_exists('filter.group_id', $params)) {
246 if (is_array($params['filter.group_id'])) {
247 $groups = $params['filter.group_id'];
248 }
249 else {
250 $groups = explode(',', $params['filter.group_id']);
251 }
252 unset($params['filter.group_id']);
253 $groups = array_flip($groups);
254 $groups[key($groups)] = 1;
255 $options['input_params']['group'] = $groups;
256 }
257 }
258
259 /**
260 * Delete a contact with given contact id
261 *
262 * @param array $params
263 * input parameters per getfields
264 *
265 * @return array
266 * API Result Array
267 */
268 function civicrm_api3_contact_delete($params) {
269
270 $contactID = CRM_Utils_Array::value('id', $params);
271
272 $session = CRM_Core_Session::singleton();
273 if ($contactID == $session->get('userID')) {
274 return civicrm_api3_create_error('This contact record is linked to the currently logged in user account - and cannot be deleted.');
275 }
276 $restore = !empty($params['restore']) ? $params['restore'] : FALSE;
277 $skipUndelete = !empty($params['skip_undelete']) ? $params['skip_undelete'] : FALSE;
278
279 // CRM-12929
280 // restrict permanent delete if a contact has financial trxn associated with it
281 $error = NULL;
282 if ($skipUndelete && CRM_Financial_BAO_FinancialItem::checkContactPresent(array($contactID), $error)) {
283 return civicrm_api3_create_error($error['_qf_default']);
284 }
285 if (CRM_Contact_BAO_Contact::deleteContact($contactID, $restore, $skipUndelete)) {
286 return civicrm_api3_create_success();
287 }
288 else {
289 return civicrm_api3_create_error('Could not delete contact');
290 }
291 }
292
293
294 /**
295 * @param array $params
296 * @param bool $dupeCheck
297 *
298 * @return null
299 * @throws API_Exception
300 * @throws CiviCRM_API3_Exception
301 */
302 function _civicrm_api3_contact_check_params(&$params, $dupeCheck) {
303
304 switch (strtolower(CRM_Utils_Array::value('contact_type', $params))) {
305 case 'household':
306 civicrm_api3_verify_mandatory($params, NULL, array('household_name'));
307 break;
308
309 case 'organization':
310 civicrm_api3_verify_mandatory($params, NULL, array('organization_name'));
311 break;
312
313 case 'individual':
314 civicrm_api3_verify_one_mandatory($params, NULL, array(
315 'first_name',
316 'last_name',
317 'email',
318 'display_name',
319 )
320 );
321 break;
322 }
323
324 // Fixme: This really needs to be handled at a lower level. @See CRM-13123
325 if (isset($params['preferred_communication_method'])) {
326 $params['preferred_communication_method'] = CRM_Utils_Array::implodePadded($params['preferred_communication_method']);
327 }
328
329 if (!empty($params['contact_sub_type']) && !empty($params['contact_type'])) {
330 if (!(CRM_Contact_BAO_ContactType::isExtendsContactType($params['contact_sub_type'], $params['contact_type']))) {
331 throw new API_Exception("Invalid or Mismatched Contact Subtype: " . implode(', ', (array) $params['contact_sub_type']));
332 }
333 }
334
335 if ($dupeCheck) {
336 // check for record already existing
337 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, $params['contact_type']);
338
339 // CRM-6431
340 // setting 'check_permission' here means that the dedupe checking will be carried out even if the
341 // person does not have permission to carry out de-dupes
342 // this is similar to the front end form
343 if (isset($params['check_permission'])) {
344 $dedupeParams['check_permission'] = $params['check_permission'];
345 }
346
347 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, $params['contact_type'], 'Unsupervised', array());
348
349 if (count($ids) > 0) {
350 throw new API_Exception("Found matching contacts: " . implode(',', $ids), "duplicate", array("ids" => $ids));
351 }
352 }
353
354 // The BAO no longer supports the legacy param "current_employer" so here is a shim for api backward-compatability
355 if (!empty($params['current_employer'])) {
356 $organizationParams = array(
357 'organization_name' => $params['current_employer'],
358 );
359
360 $dedupParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization');
361
362 $dedupParams['check_permission'] = FALSE;
363 $dupeIds = CRM_Dedupe_Finder::dupesByParams($dedupParams, 'Organization', 'Supervised');
364
365 // check for mismatch employer name and id
366 if (!empty($params['employer_id']) && !in_array($params['employer_id'], $dupeIds)) {
367 throw new API_Exception('Employer name and Employer id Mismatch');
368 }
369
370 // show error if multiple organisation with same name exist
371 if (empty($params['employer_id']) && (count($dupeIds) > 1)) {
372 throw new API_Exception('Found more than one Organisation with same Name.');
373 }
374
375 if ($dupeIds) {
376 $params['employer_id'] = $dupeIds[0];
377 }
378 else {
379 $result = civicrm_api3('contact', 'create', array(
380 'organization_name' => $params['current_employer'],
381 'contact_type' => 'Organization',
382 ));
383 $params['employer_id'] = $result['id'];
384 }
385 }
386
387 return NULL;
388 }
389
390 /**
391 * Takes an associative array and creates a contact object and all the associated
392 * derived objects (i.e. individual, location, email, phone etc)
393 *
394 * @param array $params
395 * (reference ) an assoc array of name/value pairs.
396 * @param int $contactID
397 * If present the contact with that ID is updated.
398 *
399 * @return CRM_Contact_BAO_Contact|CRM_Core_Error
400 */
401 function _civicrm_api3_contact_update($params, $contactID = NULL) {
402 //@todo - doesn't contact create support 'id' which is already set- check & remove
403 if ($contactID) {
404 $params['contact_id'] = $contactID;
405 }
406
407 return CRM_Contact_BAO_Contact::create($params);
408 }
409
410 /**
411 * Validate the addressee or email or postal greetings
412 *
413 * @param array $params
414 * Associative array of property name/value.
415 * pairs to insert in new contact.
416 *
417 * @throws API_Exception
418 *
419 */
420 function _civicrm_api3_greeting_format_params($params) {
421 $greetingParams = array('', '_id', '_custom');
422 foreach (array('email', 'postal', 'addressee') as $key) {
423 $greeting = '_greeting';
424 if ($key == 'addressee') {
425 $greeting = '';
426 }
427
428 $formatParams = FALSE;
429 // unset display value from params.
430 if (isset($params["{$key}{$greeting}_display"])) {
431 unset($params["{$key}{$greeting}_display"]);
432 }
433
434 // check if greetings are present in present
435 foreach ($greetingParams as $greetingValues) {
436 if (array_key_exists("{$key}{$greeting}{$greetingValues}", $params)) {
437 $formatParams = TRUE;
438 break;
439 }
440 }
441
442 if (!$formatParams) {
443 continue;
444 }
445
446 $nullValue = FALSE;
447 $filter = array(
448 'contact_type' => $params['contact_type'],
449 'greeting_type' => "{$key}{$greeting}",
450 );
451
452 $greetings = CRM_Core_PseudoConstant::greeting($filter);
453 $greetingId = CRM_Utils_Array::value("{$key}{$greeting}_id", $params);
454 $greetingVal = CRM_Utils_Array::value("{$key}{$greeting}", $params);
455 $customGreeting = CRM_Utils_Array::value("{$key}{$greeting}_custom", $params);
456
457 if (!$greetingId && $greetingVal) {
458 $params["{$key}{$greeting}_id"] = CRM_Utils_Array::key($params["{$key}{$greeting}"], $greetings);
459 }
460
461 if ($customGreeting && $greetingId &&
462 ($greetingId != array_search('Customized', $greetings))
463 ) {
464 throw new API_Exception(ts('Provide either %1 greeting id and/or %1 greeting or custom %1 greeting',
465 array(1 => $key)
466 ));
467 }
468
469 if ($greetingVal && $greetingId &&
470 ($greetingId != CRM_Utils_Array::key($greetingVal, $greetings))
471 ) {
472 throw new API_Exception(ts('Mismatch in %1 greeting id and %1 greeting',
473 array(1 => $key)
474 ));
475 }
476
477 if ($greetingId) {
478
479 if (!array_key_exists($greetingId, $greetings)) {
480 throw new API_Exception(ts('Invalid %1 greeting Id', array(1 => $key)));
481 }
482
483 if (!$customGreeting && ($greetingId == array_search('Customized', $greetings))) {
484 throw new API_Exception(ts('Please provide a custom value for %1 greeting',
485 array(1 => $key)
486 ));
487 }
488 }
489 elseif ($greetingVal) {
490
491 if (!in_array($greetingVal, $greetings)) {
492 throw new API_Exception(ts('Invalid %1 greeting', array(1 => $key)));
493 }
494
495 $greetingId = CRM_Utils_Array::key($greetingVal, $greetings);
496 }
497
498 if ($customGreeting) {
499 $greetingId = CRM_Utils_Array::key('Customized', $greetings);
500 }
501
502 $customValue = isset($params['contact_id']) ? CRM_Core_DAO::getFieldValue(
503 'CRM_Contact_DAO_Contact',
504 $params['contact_id'],
505 "{$key}{$greeting}_custom"
506 ) : FALSE;
507
508 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
509 $nullValue = TRUE;
510 }
511 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
512 $nullValue = TRUE;
513 }
514 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
515 && empty($params["{$key}{$greeting}_custom"])
516 ) {
517 $nullValue = TRUE;
518 }
519
520 $params["{$key}{$greeting}_id"] = $greetingId;
521
522 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
523 unset($params["{$key}{$greeting}_custom"]);
524 }
525
526 if ($nullValue) {
527 $params["{$key}{$greeting}_id"] = '';
528 $params["{$key}{$greeting}_custom"] = '';
529 }
530
531 if (isset($params["{$key}{$greeting}"])) {
532 unset($params["{$key}{$greeting}"]);
533 }
534 }
535 }
536
537 /**
538 * Old contact quick search api
539 *
540 * @deprecated
541 *
542 * {@example ContactGetquick.php 0}
543 * @param array $params
544 * @return array
545 * @throws \API_Exception
546 */
547 function civicrm_api3_contact_getquick($params) {
548 civicrm_api3_verify_mandatory($params, NULL, array('name'));
549 $name = CRM_Utils_Type::escape(CRM_Utils_Array::value('name', $params), 'String');
550
551 // get the autocomplete options from settings
552 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
553 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
554 'contact_autocomplete_options'
555 )
556 );
557
558 // get the option values for contact autocomplete
559 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
560
561 $list = array();
562 foreach ($acpref as $value) {
563 if ($value && !empty($acOptions[$value])) {
564 $list[$value] = $acOptions[$value];
565 }
566 }
567 // If we are doing quicksearch by a field other than name, make sure that field is added to results
568 if (!empty($params['field_name'])) {
569 $field_name = CRM_Utils_String::munge($params['field_name']);
570 // Unique name contact_id = id
571 if ($field_name == 'contact_id') {
572 $field_name = 'id';
573 }
574 // phone_numeric should be phone
575 $searchField = str_replace('_numeric', '', $field_name);
576 if (!in_array($searchField, $list)) {
577 $list[] = $searchField;
578 }
579 }
580
581 $select = $actualSelectElements = array('sort_name');
582 $where = '';
583 $from = array();
584 foreach ($list as $value) {
585 $suffix = substr($value, 0, 2) . substr($value, -1);
586 switch ($value) {
587 case 'street_address':
588 case 'city':
589 case 'postal_code':
590 $selectText = $value;
591 $value = "address";
592 $suffix = 'sts';
593 case 'phone':
594 case 'email':
595 $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value;
596 if ($value == 'phone') {
597 $actualSelectElements[] = $select[] = 'phone_ext';
598 }
599 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
600 break;
601
602 case 'country':
603 case 'state_province':
604 $select[] = "{$suffix}.name as {$value}";
605 $actualSelectElements[] = "{$suffix}.name";
606 if (!in_array('address', $from)) {
607 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
608 }
609 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
610 break;
611
612 default:
613 if ($value != 'id') {
614 $suffix = 'cc';
615 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
616 $suffix = CRM_Utils_String::munge(CRM_Utils_Array::value('table_name', $params, 'cc'));
617 }
618 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
619 }
620 break;
621 }
622 }
623
624 $config = CRM_Core_Config::singleton();
625 $as = $select;
626 $select = implode(', ', $select);
627 if (!empty($select)) {
628 $select = ", $select";
629 }
630 $actualSelectElements = implode(', ', $actualSelectElements);
631 $selectAliases = $from;
632 unset($selectAliases['address']);
633 $selectAliases = implode(', ', array_keys($selectAliases));
634 if (!empty($selectAliases)) {
635 $selectAliases = ", $selectAliases";
636 }
637 $from = implode(' ', $from);
638 $limit = (int) CRM_Utils_Array::value('limit', $params);
639 $limit = $limit > 0 ? $limit : 10;
640
641 // add acl clause here
642 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
643
644 if ($aclWhere) {
645 $where .= " AND $aclWhere ";
646 }
647
648 if (!empty($params['org'])) {
649 $where .= " AND contact_type = \"Organization\"";
650
651 // CRM-7157, hack: get current employer details when
652 // employee_id is present.
653 $currEmpDetails = array();
654 if (!empty($params['employee_id'])) {
655 if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
656 (int) $params['employee_id'],
657 'employer_id'
658 )) {
659 if ($config->includeWildCardInName) {
660 $strSearch = "%$name%";
661 }
662 else {
663 $strSearch = "$name%";
664 }
665
666 // get current employer details
667 $dao = CRM_Core_DAO::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
668 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
669 if ($dao->fetch()) {
670 $currEmpDetails = array(
671 'id' => $dao->id,
672 'data' => $dao->data,
673 );
674 }
675 }
676 }
677 }
678
679 if (!empty($params['contact_sub_type'])) {
680 $contactSubType = CRM_Utils_Type::escape($params['contact_sub_type'], 'String');
681 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
682 }
683
684 if (!empty($params['contact_type'])) {
685 $contactType = CRM_Utils_Type::escape($params['contact_type'], 'String');
686 $where .= " AND cc.contact_type LIKE '{$contactType}'";
687 }
688
689 //set default for current_employer or return contact with particular id
690 if (!empty($params['id'])) {
691 $where .= " AND cc.id = " . (int) $params['id'];
692 }
693
694 if (!empty($params['cid'])) {
695 $where .= " AND cc.id <> " . (int) $params['cid'];
696 }
697
698 //contact's based of relationhip type
699 $relType = NULL;
700 if (!empty($params['rel'])) {
701 $relation = explode('_', CRM_Utils_Array::value('rel', $params));
702 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
703 $rel = CRM_Utils_Type::escape($relation[2], 'String');
704 }
705
706 if ($config->includeWildCardInName) {
707 $strSearch = "%$name%";
708 }
709 else {
710 $strSearch = "$name%";
711 }
712 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
713 if ($config->includeNickNameInName) {
714 $includeNickName = " OR nick_name LIKE '$strSearch'";
715 $exactIncludeNickName = " OR nick_name LIKE '$name'";
716 }
717
718 //CRM-10687
719 if (!empty($params['field_name']) && !empty($params['table_name'])) {
720 $table_name = CRM_Utils_String::munge($params['table_name']);
721 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
722 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
723 // Search by id should be exact
724 if ($field_name == 'id' || $field_name == 'external_identifier') {
725 $whereClause = $exactWhereClause;
726 }
727 }
728 else {
729 if ($config->includeEmailInName) {
730 if (!in_array('email', $list)) {
731 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
732 }
733 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
734 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
735 }
736 else {
737 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
738 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
739 }
740 }
741
742 $additionalFrom = '';
743 if ($relType) {
744 $additionalFrom = "
745 INNER JOIN civicrm_relationship_type r ON (
746 r.id = {$relType}
747 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
748 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
749 )";
750 }
751
752 // check if only CMS users are requested
753 if (!empty($params['cmsuser'])) {
754 $additionalFrom = "
755 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
756 ";
757 }
758
759 $orderByInner = "";
760 $orderByOuter = "ORDER BY exactFirst";
761 if ($config->includeOrderByClause) {
762 $orderByInner = "ORDER BY sort_name";
763 $orderByOuter .= ", sort_name";
764 }
765
766 //CRM-5954
767 $query = "
768 SELECT DISTINCT(id), data, sort_name {$selectAliases}
769 FROM (
770 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
771 FROM civicrm_contact cc {$from}
772 {$aclFrom}
773 {$additionalFrom} {$includeEmailFrom}
774 {$exactWhereClause}
775 LIMIT 0, {$limit} )
776 UNION
777 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
778 FROM civicrm_contact cc {$from}
779 {$aclFrom}
780 {$additionalFrom} {$includeEmailFrom}
781 {$whereClause}
782 {$orderByInner}
783 LIMIT 0, {$limit} )
784 ) t
785 {$orderByOuter}
786 LIMIT 0, {$limit}
787 ";
788 // send query to hook to be modified if needed
789 CRM_Utils_Hook::contactListQuery($query,
790 $name,
791 empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'),
792 empty($params['id']) ? NULL : $params['id']
793 );
794
795 $dao = CRM_Core_DAO::executeQuery($query);
796
797 $contactList = array();
798 $listCurrentEmployer = TRUE;
799 while ($dao->fetch()) {
800 $t = array('id' => $dao->id);
801 foreach ($as as $k) {
802 $t[$k] = isset($dao->$k) ? $dao->$k : '';
803 }
804 $t['data'] = $dao->data;
805 $contactList[] = $t;
806 if (!empty($params['org']) &&
807 !empty($currEmpDetails) &&
808 $dao->id == $currEmpDetails['id']
809 ) {
810 $listCurrentEmployer = FALSE;
811 }
812 }
813
814 //return organization name if doesn't exist in db
815 if (empty($contactList)) {
816 if (!empty($params['org'])) {
817 if ($listCurrentEmployer && !empty($currEmpDetails)) {
818 $contactList = array(
819 array(
820 'data' => $currEmpDetails['data'],
821 'id' => $currEmpDetails['id'],
822 ),
823 );
824 }
825 else {
826 $contactList = array(
827 array(
828 'data' => $name,
829 'id' => $name,
830 ),
831 );
832 }
833 }
834 }
835
836 return civicrm_api3_create_success($contactList, $params, 'contact', 'getquick');
837 }
838
839 /**
840 * @deprecated api notice
841 * @return array
842 * Array of deprecated actions
843 */
844 function _civicrm_api3_contact_deprecation() {
845 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
846 }
847
848 /**
849 * Merges given pair of duplicate contacts.
850 *
851 * @param array $params
852 * Input parameters.
853 *
854 * Allowed @params array keys are:
855 * {int main_id main contact id with whom merge has to happen}
856 * {int other_id duplicate contact which would be deleted after merge operation}
857 * {string mode helps decide how to behave when there are conflicts.
858 * A 'safe' value skips the merge if there are no conflicts. Does a force merge otherwise.}
859 * {boolean auto_flip wether to let api decide which contact to retain and which to delete.}
860 *
861 * @return array
862 * API Result Array
863 *
864 */
865 function civicrm_api3_contact_merge($params) {
866 $mode = CRM_Utils_Array::value('mode', $params, 'safe');
867 $autoFlip = CRM_Utils_Array::value('auto_flip', $params, TRUE);
868
869 $dupePairs = array(array(
870 'srcID' => CRM_Utils_Array::value('main_id', $params),
871 'dstID' => CRM_Utils_Array::value('other_id', $params),
872 ));
873 $result = CRM_Dedupe_Merger::merge($dupePairs, array(), $mode, $autoFlip);
874
875 if ($result['is_error'] == 0) {
876 return civicrm_api3_create_success();
877 }
878 else {
879 return civicrm_api3_create_error($result['messages']);
880 }
881 }
882
883 /**
884 * @param array $params
885 */
886 function _civicrm_api3_contact_proximity_spec(&$params) {
887 $params['latitude']['api.required'] = 1;
888 $params['latitude']['title'] = 'Latitude';
889 $params['longitude']['api.required'] = 1;
890 $params['longitude']['title'] = 'Longitude';
891 $params['unit']['api.default'] = 'meter';
892 $params['unit']['title'] = 'Unit of Measurement';
893 }
894
895 /**
896 * @param array $params
897 *
898 * @return array
899 * @throws Exception
900 */
901 function civicrm_api3_contact_proximity($params) {
902 $latitude = CRM_Utils_Array::value('latitude', $params);
903 $longitude = CRM_Utils_Array::value('longitude', $params);
904 $distance = CRM_Utils_Array::value('distance', $params);
905
906 $unit = CRM_Utils_Array::value('unit', $params);
907
908 // check and ensure that lat/long and distance are floats
909 if (
910 !CRM_Utils_Rule::numeric($latitude) ||
911 !CRM_Utils_Rule::numeric($longitude) ||
912 !CRM_Utils_Rule::numeric($distance)
913 ) {
914 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
915 }
916
917 if ($unit == "mile") {
918 $conversionFactor = 1609.344;
919 }
920 else {
921 $conversionFactor = 1000;
922 }
923 //Distance in meters
924 $distance = $distance * $conversionFactor;
925
926 $whereClause = CRM_Contact_BAO_ProximityQuery::where($latitude, $longitude, $distance);
927
928 $query = "
929 SELECT civicrm_contact.id as contact_id,
930 civicrm_contact.display_name as display_name
931 FROM civicrm_contact
932 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
933 WHERE $whereClause
934 ";
935
936 $dao = CRM_Core_DAO::executeQuery($query);
937 $contacts = array();
938 while ($dao->fetch()) {
939 $contacts[] = $dao->toArray();
940 }
941
942 return civicrm_api3_create_success($contacts, $params, 'contact', 'get_by_location', $dao);
943 }
944
945
946 /**
947 * @see _civicrm_api3_generic_getlist_params
948 *
949 * @param array $request
950 */
951 function _civicrm_api3_contact_getlist_params(&$request) {
952 // get the autocomplete options from settings
953 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
954 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
955 'contact_autocomplete_options'
956 )
957 );
958
959 // get the option values for contact autocomplete
960 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
961
962 $list = array();
963 foreach ($acpref as $value) {
964 if ($value && !empty($acOptions[$value])) {
965 $list[] = $acOptions[$value];
966 }
967 }
968 // If we are doing quicksearch by a field other than name, make sure that field is added to results
969 $field_name = CRM_Utils_String::munge($request['search_field']);
970 // Unique name contact_id = id
971 if ($field_name == 'contact_id') {
972 $field_name = 'id';
973 }
974 // phone_numeric should be phone
975 $searchField = str_replace('_numeric', '', $field_name);
976 if (!in_array($searchField, $list)) {
977 $list[] = $searchField;
978 }
979 $request['description_field'] = $list;
980 $list[] = 'contact_type';
981 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
982 $request['params']['options']['sort'] = 'sort_name';
983 // Contact api doesn't support array(LIKE => 'foo') syntax
984 if (!empty($request['input'])) {
985 $request['params'][$request['search_field']] = $request['input'];
986 }
987 }
988
989 /**
990 * @see _civicrm_api3_generic_getlist_output
991 *
992 * @param array $result
993 * @param array $request
994 *
995 * @return array
996 */
997 function _civicrm_api3_contact_getlist_output($result, $request) {
998 $output = array();
999 if (!empty($result['values'])) {
1000 $addressFields = array_intersect(array('street_address', 'city', 'state_province', 'country'), $request['params']['return']);
1001 foreach ($result['values'] as $row) {
1002 $data = array(
1003 'id' => $row[$request['id_field']],
1004 'label' => $row[$request['label_field']],
1005 'description' => array(),
1006 );
1007 foreach ($request['description_field'] as $item) {
1008 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1009 $data['description'][] = $row[$item];
1010 }
1011 }
1012 $address = array();
1013 foreach ($addressFields as $item) {
1014 if (!empty($row[$item])) {
1015 $address[] = $row[$item];
1016 }
1017 }
1018 if ($address) {
1019 $data['description'][] = implode(' ', $address);
1020 }
1021 if (!empty($request['image_field'])) {
1022 $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
1023 }
1024 else {
1025 $data['icon_class'] = $row['contact_type'];
1026 }
1027 foreach ($request['extra'] as $field) {
1028 $data['extra'][$field] = isset($row[$field]) ? $row[$field] : NULL;
1029 }
1030 $output[] = $data;
1031 }
1032 }
1033 return $output;
1034 }