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