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