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