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