7029bc5f716452f1bd80f9b85b4a99609f903bb7
[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
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
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
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 * @param $params
564 * @return array
565 * @throws \API_Exception
566 */
567 function civicrm_api3_contact_getquick($params) {
568 civicrm_api3_verify_mandatory($params, NULL, array('name'));
569 $name = CRM_Utils_Type::escape(CRM_Utils_Array::value('name', $params), 'String');
570
571 // get the autocomplete options from settings
572 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
573 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
574 'contact_autocomplete_options'
575 )
576 );
577
578 // get the option values for contact autocomplete
579 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
580
581 $list = array();
582 foreach ($acpref as $value) {
583 if ($value && !empty($acOptions[$value])) {
584 $list[$value] = $acOptions[$value];
585 }
586 }
587 // If we are doing quicksearch by a field other than name, make sure that field is added to results
588 if (!empty($params['field_name'])) {
589 $field_name = CRM_Utils_String::munge($params['field_name']);
590 // Unique name contact_id = id
591 if ($field_name == 'contact_id') {
592 $field_name = 'id';
593 }
594 // phone_numeric should be phone
595 $searchField = str_replace('_numeric', '', $field_name);
596 if (!in_array($searchField, $list)) {
597 $list[] = $searchField;
598 }
599 }
600
601 $select = $actualSelectElements = array('sort_name');
602 $where = '';
603 $from = array();
604 foreach ($list as $value) {
605 $suffix = substr($value, 0, 2) . substr($value, -1);
606 switch ($value) {
607 case 'street_address':
608 case 'city':
609 case 'postal_code':
610 $selectText = $value;
611 $value = "address";
612 $suffix = 'sts';
613 case 'phone':
614 case 'email':
615 $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value;
616 if ($value == 'phone') {
617 $actualSelectElements[] = $select[] = 'phone_ext';
618 }
619 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
620 break;
621
622 case 'country':
623 case 'state_province':
624 $select[] = "{$suffix}.name as {$value}";
625 $actualSelectElements[] = "{$suffix}.name";
626 if (!in_array('address', $from)) {
627 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
628 }
629 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
630 break;
631
632 default:
633 if ($value != 'id') {
634 $suffix = 'cc';
635 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
636 $suffix = CRM_Utils_String::munge(CRM_Utils_Array::value('table_name', $params, 'cc'));
637 }
638 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
639 }
640 break;
641 }
642 }
643
644 $config = CRM_Core_Config::singleton();
645 $as = $select;
646 $select = implode(', ', $select);
647 if (!empty($select)) {
648 $select = ", $select";
649 }
650 $actualSelectElements = implode(', ', $actualSelectElements);
651 $selectAliases = $from;
652 unset($selectAliases['address']);
653 $selectAliases = implode(', ', array_keys($selectAliases));
654 if (!empty($selectAliases)) {
655 $selectAliases = ", $selectAliases";
656 }
657 $from = implode(' ', $from);
658 $limit = (int) CRM_Utils_Array::value('limit', $params);
659 $limit = $limit > 0 ? $limit : 10;
660
661 // add acl clause here
662 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
663
664 if ($aclWhere) {
665 $where .= " AND $aclWhere ";
666 }
667
668 if (!empty($params['org'])) {
669 $where .= " AND contact_type = \"Organization\"";
670
671 // CRM-7157, hack: get current employer details when
672 // employee_id is present.
673 $currEmpDetails = array();
674 if (!empty($params['employee_id'])) {
675 if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
676 (int) $params['employee_id'],
677 'employer_id'
678 )) {
679 if ($config->includeWildCardInName) {
680 $strSearch = "%$name%";
681 }
682 else {
683 $strSearch = "$name%";
684 }
685
686 // get current employer details
687 $dao = CRM_Core_DAO::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
688 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
689 if ($dao->fetch()) {
690 $currEmpDetails = array(
691 'id' => $dao->id,
692 'data' => $dao->data,
693 );
694 }
695 }
696 }
697 }
698
699 if (!empty($params['contact_sub_type'])) {
700 $contactSubType = CRM_Utils_Type::escape($params['contact_sub_type'], 'String');
701 $where .= " AND cc.contact_sub_type = '{$contactSubType}'";
702 }
703
704 if (!empty($params['contact_type'])) {
705 $contactType = CRM_Utils_Type::escape($params['contact_type'], 'String');
706 $where .= " AND cc.contact_type LIKE '{$contactType}'";
707 }
708
709 //set default for current_employer or return contact with particular id
710 if (!empty($params['id'])) {
711 $where .= " AND cc.id = " . (int) $params['id'];
712 }
713
714 if (!empty($params['cid'])) {
715 $where .= " AND cc.id <> " . (int) $params['cid'];
716 }
717
718 //contact's based of relationhip type
719 $relType = NULL;
720 if (!empty($params['rel'])) {
721 $relation = explode('_', CRM_Utils_Array::value('rel', $params));
722 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
723 $rel = CRM_Utils_Type::escape($relation[2], 'String');
724 }
725
726 if ($config->includeWildCardInName) {
727 $strSearch = "%$name%";
728 }
729 else {
730 $strSearch = "$name%";
731 }
732 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
733 if ($config->includeNickNameInName) {
734 $includeNickName = " OR nick_name LIKE '$strSearch'";
735 $exactIncludeNickName = " OR nick_name LIKE '$name'";
736 }
737
738 //CRM-10687
739 if (!empty($params['field_name']) && !empty($params['table_name'])) {
740 $table_name = CRM_Utils_String::munge($params['table_name']);
741 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch') {$where}";
742 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name') {$where}";
743 // Search by id should be exact
744 if ($field_name == 'id' || $field_name == 'external_identifier') {
745 $whereClause = $exactWhereClause;
746 }
747 }
748 else {
749 if ($config->includeEmailInName) {
750 if (!in_array('email', $list)) {
751 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
752 }
753 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
754 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
755 }
756 else {
757 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
758 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
759 }
760 }
761
762 $additionalFrom = '';
763 if ($relType) {
764 $additionalFrom = "
765 INNER JOIN civicrm_relationship_type r ON (
766 r.id = {$relType}
767 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
768 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
769 )";
770 }
771
772 // check if only CMS users are requested
773 if (!empty($params['cmsuser'])) {
774 $additionalFrom = "
775 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
776 ";
777 }
778
779 $orderByInner = "";
780 $orderByOuter = "ORDER BY exactFirst";
781 if ($config->includeOrderByClause) {
782 $orderByInner = "ORDER BY sort_name";
783 $orderByOuter .= ", sort_name";
784 }
785
786 //CRM-5954
787 $query = "
788 SELECT DISTINCT(id), data, sort_name {$selectAliases}
789 FROM (
790 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
791 FROM civicrm_contact cc {$from}
792 {$aclFrom}
793 {$additionalFrom} {$includeEmailFrom}
794 {$exactWhereClause}
795 LIMIT 0, {$limit} )
796 UNION
797 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
798 FROM civicrm_contact cc {$from}
799 {$aclFrom}
800 {$additionalFrom} {$includeEmailFrom}
801 {$whereClause}
802 {$orderByInner}
803 LIMIT 0, {$limit} )
804 ) t
805 {$orderByOuter}
806 LIMIT 0, {$limit}
807 ";
808 // send query to hook to be modified if needed
809 CRM_Utils_Hook::contactListQuery($query,
810 $name,
811 empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'),
812 empty($params['id']) ? NULL : $params['id']
813 );
814
815 $dao = CRM_Core_DAO::executeQuery($query);
816
817 $contactList = array();
818 $listCurrentEmployer = TRUE;
819 while ($dao->fetch()) {
820 $t = array('id' => $dao->id);
821 foreach ($as as $k) {
822 $t[$k] = isset($dao->$k) ? $dao->$k : '';
823 }
824 $t['data'] = $dao->data;
825 $contactList[] = $t;
826 if (!empty($params['org']) &&
827 !empty($currEmpDetails) &&
828 $dao->id == $currEmpDetails['id']
829 ) {
830 $listCurrentEmployer = FALSE;
831 }
832 }
833
834 //return organization name if doesn't exist in db
835 if (empty($contactList)) {
836 if (!empty($params['org'])) {
837 if ($listCurrentEmployer && !empty($currEmpDetails)) {
838 $contactList = array(
839 array(
840 'data' => $currEmpDetails['data'],
841 'id' => $currEmpDetails['id'],
842 ),
843 );
844 }
845 else {
846 $contactList = array(
847 array(
848 'data' => $name,
849 'id' => $name,
850 ),
851 );
852 }
853 }
854 }
855
856 return civicrm_api3_create_success($contactList, $params, 'contact', 'getquick');
857 }
858
859 /**
860 * @deprecated api notice
861 * @return array
862 * Array of deprecated actions
863 */
864 function _civicrm_api3_contact_deprecation() {
865 return array('getquick' => 'The "getquick" action is deprecated in favor of "getlist".');
866 }
867
868 /**
869 * Merges given pair of duplicate contacts.
870 *
871 * @param array $params
872 * Input parameters.
873 *
874 * Allowed @params array keys are:
875 * {int main_id main contact id with whom merge has to happen}
876 * {int other_id duplicate contact which would be deleted after merge operation}
877 * {string mode helps decide how to behave when there are conflicts.
878 * A 'safe' value skips the merge if there are no conflicts. Does a force merge otherwise.}
879 * {boolean auto_flip wether to let api decide which contact to retain and which to delete.}
880 *
881 * @return array
882 * API Result Array
883 *
884 * @static
885 * @access public
886 */
887 function civicrm_api3_contact_merge($params) {
888 $mode = CRM_Utils_Array::value('mode', $params, 'safe');
889 $autoFlip = CRM_Utils_Array::value('auto_flip', $params, TRUE);
890
891 $dupePairs = array(array(
892 'srcID' => CRM_Utils_Array::value('main_id', $params),
893 'dstID' => CRM_Utils_Array::value('other_id', $params),
894 ));
895 $result = CRM_Dedupe_Merger::merge($dupePairs, array(), $mode, $autoFlip);
896
897 if ($result['is_error'] == 0) {
898 return civicrm_api3_create_success();
899 }
900 else {
901 return civicrm_api3_create_error($result['messages']);
902 }
903 }
904
905 /**
906 * @param array $params
907 */
908 function _civicrm_api3_contact_proximity_spec(&$params) {
909 $params['latitude']['api.required'] = 1;
910 $params['latitude']['title'] = 'Latitude';
911 $params['longitude']['api.required'] = 1;
912 $params['longitude']['title'] = 'Longitude';
913 $params['unit']['api.default'] = 'meter';
914 $params['unit']['title'] = 'Unit of Measurement';
915 }
916
917 /**
918 * @param array $params
919 *
920 * @return array
921 * @throws Exception
922 */
923 function civicrm_api3_contact_proximity($params) {
924 $latitude = CRM_Utils_Array::value('latitude', $params);
925 $longitude = CRM_Utils_Array::value('longitude', $params);
926 $distance = CRM_Utils_Array::value('distance', $params);
927
928 $unit = CRM_Utils_Array::value('unit', $params);
929
930 // check and ensure that lat/long and distance are floats
931 if (
932 !CRM_Utils_Rule::numeric($latitude) ||
933 !CRM_Utils_Rule::numeric($longitude) ||
934 !CRM_Utils_Rule::numeric($distance)
935 ) {
936 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
937 }
938
939 if ($unit == "mile") {
940 $conversionFactor = 1609.344;
941 }
942 else {
943 $conversionFactor = 1000;
944 }
945 //Distance in meters
946 $distance = $distance * $conversionFactor;
947
948 $whereClause = CRM_Contact_BAO_ProximityQuery::where($latitude, $longitude, $distance);
949
950 $query = "
951 SELECT civicrm_contact.id as contact_id,
952 civicrm_contact.display_name as display_name
953 FROM civicrm_contact
954 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
955 WHERE $whereClause
956 ";
957
958 $dao = CRM_Core_DAO::executeQuery($query);
959 $contacts = array();
960 while ($dao->fetch()) {
961 $contacts[] = $dao->toArray();
962 }
963
964 return civicrm_api3_create_success($contacts, $params, 'contact', 'get_by_location', $dao);
965 }
966
967
968 /**
969 * @see _civicrm_api3_generic_getlist_params
970 *
971 * @param $request
972 * Array.
973 */
974 function _civicrm_api3_contact_getlist_params(&$request) {
975 // get the autocomplete options from settings
976 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
977 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
978 'contact_autocomplete_options'
979 )
980 );
981
982 // get the option values for contact autocomplete
983 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
984
985 $list = array();
986 foreach ($acpref as $value) {
987 if ($value && !empty($acOptions[$value])) {
988 $list[] = $acOptions[$value];
989 }
990 }
991 // If we are doing quicksearch by a field other than name, make sure that field is added to results
992 $field_name = CRM_Utils_String::munge($request['search_field']);
993 // Unique name contact_id = id
994 if ($field_name == 'contact_id') {
995 $field_name = 'id';
996 }
997 // phone_numeric should be phone
998 $searchField = str_replace('_numeric', '', $field_name);
999 if (!in_array($searchField, $list)) {
1000 $list[] = $searchField;
1001 }
1002 $request['description_field'] = $list;
1003 $list[] = 'contact_type';
1004 $request['params']['return'] = array_unique(array_merge($list, $request['extra']));
1005 $request['params']['options']['sort'] = 'sort_name';
1006 // Contact api doesn't support array(LIKE => 'foo') syntax
1007 if (!empty($request['input'])) {
1008 $request['params'][$request['search_field']] = $request['input'];
1009 }
1010 }
1011
1012 /**
1013 * @see _civicrm_api3_generic_getlist_output
1014 *
1015 * @param $result
1016 * Array.
1017 * @param $request
1018 * Array.
1019 *
1020 * @return array
1021 */
1022 function _civicrm_api3_contact_getlist_output($result, $request) {
1023 $output = array();
1024 if (!empty($result['values'])) {
1025 $addressFields = array_intersect(array('street_address', 'city', 'state_province', 'country'), $request['params']['return']);
1026 foreach ($result['values'] as $row) {
1027 $data = array(
1028 'id' => $row[$request['id_field']],
1029 'label' => $row[$request['label_field']],
1030 'description' => array(),
1031 );
1032 foreach ($request['description_field'] as $item) {
1033 if (!strpos($item, '_name') && !in_array($item, $addressFields) && !empty($row[$item])) {
1034 $data['description'][] = $row[$item];
1035 }
1036 }
1037 $address = array();
1038 foreach ($addressFields as $item) {
1039 if (!empty($row[$item])) {
1040 $address[] = $row[$item];
1041 }
1042 }
1043 if ($address) {
1044 $data['description'][] = implode(' ', $address);
1045 }
1046 if (!empty($request['image_field'])) {
1047 $data['image'] = isset($row[$request['image_field']]) ? $row[$request['image_field']] : '';
1048 }
1049 else {
1050 $data['icon_class'] = $row['contact_type'];
1051 }
1052 foreach ($request['extra'] as $field) {
1053 $data['extra'][$field] = isset($row[$field]) ? $row[$field] : NULL;
1054 }
1055 $output[] = $data;
1056 }
1057 }
1058 return $output;
1059 }