CRM-13127
[civicrm-core.git] / api / v3 / Contact.php
1 <?php
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 */
56 function 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'])) {
79 $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
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']))) {
87 $params['suffix_id'] = array_search($params['suffix_id'], CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'));
88 }
89
90 if (isset($params['prefix_id']) && !(is_numeric($params['prefix_id']))) {
91 $params['prefix_id'] = array_search($params['prefix_id'], CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'));
92 }
93
94 if (isset($params['gender_id']) && !(is_numeric($params['gender_id']))) {
95 $params['gender_id'] = array_search($params['gender_id'], CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'));
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
131 /**
132 * Adjust Metadata for Create action
133 *
134 * @param array $params array or parameters determined by getfields
135 */
136 function _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 );
143 $params['dupe_check'] = array(
144 'title' => 'Check for Duplicates',
145 'description' => 'Throw error if contact create matches dedupe rule',
146 );
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 */
162 function 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
188 function 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);
192 return (int) $count;
193 }
194
195 /**
196 * Adjust Metadata for Get action
197 *
198 * @param array $params array or parameters determined by getfields
199 */
200 function _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
234 /**
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 */
245 function _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 */
286 function 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;
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 }
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
312 function _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 */
393 function _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 */
417 function _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 = isset($params['contact_id']) ?
500 CRM_Core_DAO::getFieldValue(
501 'CRM_Contact_DAO_Contact',
502 $params['contact_id'],
503 "{$key}{$greeting}_custom"
504 ) :
505 FALSE;
506
507 if (array_key_exists("{$key}{$greeting}_id", $params) && empty($params["{$key}{$greeting}_id"])) {
508 $nullValue = TRUE;
509 }
510 elseif (array_key_exists("{$key}{$greeting}", $params) && empty($params["{$key}{$greeting}"])) {
511 $nullValue = TRUE;
512 }
513 elseif ($customValue && array_key_exists("{$key}{$greeting}_custom", $params)
514 && empty($params["{$key}{$greeting}_custom"])
515 ) {
516 $nullValue = TRUE;
517 }
518
519 $params["{$key}{$greeting}_id"] = $greetingId;
520
521 if (!$customValue && !$customGreeting && array_key_exists("{$key}{$greeting}_custom", $params)) {
522 unset($params["{$key}{$greeting}_custom"]);
523 }
524
525 if ($nullValue) {
526 $params["{$key}{$greeting}_id"] = '';
527 $params["{$key}{$greeting}_custom"] = '';
528 }
529
530 if (isset($params["{$key}{$greeting}"])) {
531 unset($params["{$key}{$greeting}"]);
532 }
533 }
534 }
535
536 /**
537 * Contact quick search api
538 *
539 * @access public
540 *
541 * {@example ContactGetquick.php 0}
542 *
543 */
544 function civicrm_api3_contact_quicksearch($params) {
545 // kept as an alias for compatibility reasons. CRM-11136
546 return civicrm_api3_contact_getquick($params);
547 }
548
549 function civicrm_api3_contact_getquick($params) {
550 civicrm_api3_verify_mandatory($params, NULL, array('name'));
551 $name = CRM_Utils_Type::escape($params['name'], 'String');
552
553 // get the autocomplete options from settings
554 $acpref = explode(CRM_Core_DAO::VALUE_SEPARATOR,
555 CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
556 'contact_autocomplete_options'
557 )
558 );
559
560 // get the option values for contact autocomplete
561 $acOptions = CRM_Core_OptionGroup::values('contact_autocomplete_options', FALSE, FALSE, FALSE, NULL, 'name');
562
563 $list = array();
564 foreach ($acpref as $value) {
565 if ($value && CRM_Utils_Array::value($value, $acOptions)) {
566 $list[$value] = $acOptions[$value];
567 }
568 }
569 // If we are doing quicksearch by a field other than name, make sure that field is added to results
570 if (!empty($params['field_name'])) {
571 $field_name = CRM_Utils_String::munge($params['field_name']);
572 // Unique name contact_id = id
573 if ($field_name == 'contact_id') {
574 $field_name = 'id';
575 }
576 // phone_numeric should be phone
577 $searchField = str_replace('_numeric', '', $field_name);
578 if(!in_array($searchField, $list)) {
579 $list[] = $searchField;
580 }
581 }
582
583 $select = $actualSelectElements = array('sort_name');
584 $where = '';
585 $from = array();
586 foreach ($list as $value) {
587 $suffix = substr($value, 0, 2) . substr($value, -1);
588 switch ($value) {
589 case 'street_address':
590 case 'city':
591 case 'postal_code':
592 $selectText = $value;
593 $value = "address";
594 $suffix = 'sts';
595 case 'phone':
596 case 'email':
597 $actualSelectElements[] = $select[] = ($value == 'address') ? $selectText : $value;
598 $from[$value] = "LEFT JOIN civicrm_{$value} {$suffix} ON ( cc.id = {$suffix}.contact_id AND {$suffix}.is_primary = 1 ) ";
599 break;
600
601 case 'country':
602 case 'state_province':
603 $select[] = "{$suffix}.name as {$value}";
604 $actualSelectElements[] = "{$suffix}.name";
605 if (!in_array('address', $from)) {
606 $from['address'] = 'LEFT JOIN civicrm_address sts ON ( cc.id = sts.contact_id AND sts.is_primary = 1) ';
607 }
608 $from[$value] = " LEFT JOIN civicrm_{$value} {$suffix} ON ( sts.{$value}_id = {$suffix}.id ) ";
609 break;
610
611 default:
612 if ($value != 'id') {
613 $suffix = 'cc';
614 if (!empty($params['field_name']) && $params['field_name'] == 'value') {
615 $suffix = CRM_Utils_String::munge(CRM_Utils_Array::value('table_name', $params, 'cc'));
616 }
617 $actualSelectElements[] = $select[] = $suffix . '.' . $value;
618 }
619 break;
620 }
621 }
622
623 $config = CRM_Core_Config::singleton();
624 $as = $select;
625 $select = implode(', ', $select);
626 if (!empty($select)) {
627 $select = ", $select";
628 }
629 $actualSelectElements = implode(', ', $actualSelectElements);
630 $selectAliases = $from;
631 unset($selectAliases['address']);
632 $selectAliases = implode(', ', array_keys($selectAliases));
633 if (!empty($selectAliases)) {
634 $selectAliases = ", $selectAliases";
635 }
636 $from = implode(' ', $from);
637 $limit = (int) CRM_Utils_Array::value('limit', $params);
638 $limit = $limit > 0 ? $limit : 10;
639
640 // add acl clause here
641 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
642
643 if ($aclWhere) {
644 $where .= " AND $aclWhere ";
645 }
646
647 if (CRM_Utils_Array::value('org', $params)) {
648 $where .= " AND contact_type = \"Organization\"";
649
650 // CRM-7157, hack: get current employer details when
651 // employee_id is present.
652 $currEmpDetails = array();
653 if (CRM_Utils_Array::value('employee_id', $params)) {
654 if ($currentEmployer = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
655 (int) $params['employee_id'],
656 'employer_id'
657 )) {
658 if ($config->includeWildCardInName) {
659 $strSearch = "%$name%";
660 }
661 else {
662 $strSearch = "$name%";
663 }
664
665 // get current employer details
666 $dao = CRM_Core_DAO::executeQuery("SELECT cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data, sort_name
667 FROM civicrm_contact cc {$from} WHERE cc.contact_type = \"Organization\" AND cc.id = {$currentEmployer} AND cc.sort_name LIKE '$strSearch'");
668 if ($dao->fetch()) {
669 $currEmpDetails = array(
670 'id' => $dao->id,
671 'data' => $dao->data,
672 );
673 }
674 }
675 }
676 }
677
678 //set default for current_employer or return contact with particular id
679 if (CRM_Utils_Array::value('id', $params)) {
680 $where .= " AND cc.id = " . (int) $params['id'];
681 }
682
683 if (CRM_Utils_Array::value('cid', $params)) {
684 $where .= " AND cc.id <> " . (int) $params['cid'];
685 }
686
687 //contact's based of relationhip type
688 $relType = NULL;
689 if (CRM_Utils_Array::value('rel', $params)) {
690 $relation = explode('_', CRM_Utils_Array::value('rel', $params));
691 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
692 $rel = CRM_Utils_Type::escape($relation[2], 'String');
693 }
694
695 if ($config->includeWildCardInName) {
696 $strSearch = "%$name%";
697 }
698 else {
699 $strSearch = "$name%";
700 }
701 $includeEmailFrom = $includeNickName = $exactIncludeNickName = '';
702 if ($config->includeNickNameInName) {
703 $includeNickName = " OR nick_name LIKE '$strSearch'";
704 $exactIncludeNickName = " OR nick_name LIKE '$name'";
705 }
706
707 //CRM-10687
708 if (!empty($params['field_name']) && !empty($params['table_name'])) {
709 $table_name = CRM_Utils_String::munge($params['table_name']);
710 $whereClause = " WHERE ( $table_name.$field_name LIKE '$strSearch')";
711 $exactWhereClause = " WHERE ( $table_name.$field_name = '$name')";
712 // Search by id should be exact
713 if ($field_name == 'id' || $field_name == 'external_identifier') {
714 $whereClause = $exactWhereClause;
715 }
716 }
717 else {
718 if ($config->includeEmailInName) {
719 if (!in_array('email', $list)) {
720 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
721 }
722 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
723 $exactWhereClause = " WHERE ( email LIKE '$name' OR sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
724 }
725 else {
726 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
727 $exactWhereClause = " WHERE ( sort_name LIKE '$name' $exactIncludeNickName ) {$where} ";
728 }
729 }
730
731 $additionalFrom = '';
732 if ($relType) {
733 $additionalFrom = "
734 INNER JOIN civicrm_relationship_type r ON (
735 r.id = {$relType}
736 AND ( cc.contact_type = r.contact_type_{$rel} OR r.contact_type_{$rel} IS NULL )
737 AND ( cc.contact_sub_type = r.contact_sub_type_{$rel} OR r.contact_sub_type_{$rel} IS NULL )
738 )";
739 }
740
741 // check if only CMS users are requested
742 if (CRM_Utils_Array::value('cmsuser', $params)) {
743 $additionalFrom = "
744 INNER JOIN civicrm_uf_match um ON (um.contact_id=cc.id)
745 ";
746 }
747
748 $orderByInner = "";
749 $orderByOuter = "ORDER BY exactFirst";
750 if ($config->includeOrderByClause) {
751 $orderByInner = "ORDER BY sort_name";
752 $orderByOuter .= ", sort_name";
753 }
754
755 //CRM-5954
756 $query = "
757 SELECT DISTINCT(id), data, sort_name {$selectAliases}
758 FROM (
759 ( SELECT 0 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
760 FROM civicrm_contact cc {$from}
761 {$aclFrom}
762 {$additionalFrom} {$includeEmailFrom}
763 {$exactWhereClause}
764 LIMIT 0, {$limit} )
765 UNION
766 ( SELECT 1 as exactFirst, cc.id as id, CONCAT_WS( ' :: ', {$actualSelectElements} ) as data {$select}
767 FROM civicrm_contact cc {$from}
768 {$aclFrom}
769 {$additionalFrom} {$includeEmailFrom}
770 {$whereClause}
771 {$orderByInner}
772 LIMIT 0, {$limit} )
773 ) t
774 {$orderByOuter}
775 LIMIT 0, {$limit}
776 ";
777 // send query to hook to be modified if needed
778 CRM_Utils_Hook::contactListQuery($query,
779 $name,
780 empty($params['context']) ? NULL : CRM_Utils_Type::escape($params['context'], 'String'),
781 empty($params['id']) ? NULL : $params['id']
782 );
783
784 $dao = CRM_Core_DAO::executeQuery($query);
785
786 $contactList = array();
787 $listCurrentEmployer = TRUE;
788 while ($dao->fetch()) {
789 $t = array('id' => $dao->id);
790 foreach ($as as $k) {
791 $t[$k] = isset($dao->$k)? $dao->$k: '';
792 }
793 $t['data'] = $dao->data;
794 $contactList[] = $t;
795 if (CRM_Utils_Array::value('org', $params) &&
796 !empty($currEmpDetails) &&
797 $dao->id == $currEmpDetails['id']
798 ) {
799 $listCurrentEmployer = FALSE;
800 }
801 }
802
803 //return organization name if doesn't exist in db
804 if (empty($contactList)) {
805 if (CRM_Utils_Array::value('org', $params)) {
806 if ($listCurrentEmployer && !empty($currEmpDetails)) {
807 $contactList = array(
808 array(
809 'data' => $currEmpDetails['data'],
810 'id' => $currEmpDetails['id']
811 )
812 );
813 }
814 else {
815 $contactList = array(
816 array(
817 'data' => $name,
818 'id' => $name
819 )
820 );
821 }
822 }
823 }
824
825 return civicrm_api3_create_success($contactList, $params);
826 }
827
828 /**
829 * Merges given pair of duplicate contacts.
830 *
831 * @param array $params input parameters
832 *
833 * Allowed @params array keys are:
834 * {int main_id main contact id with whom merge has to happen}
835 * {int other_id duplicate contact which would be deleted after merge operation}
836 * {string mode helps decide how to behave when there are conflicts.
837 * A 'safe' value skips the merge if there are no conflicts. Does a force merge otherwise.}
838 * {boolean auto_flip wether to let api decide which contact to retain and which to delete.}
839 *
840 * @return array API Result Array
841 *
842 * @static void
843 * @access public
844 */
845 function civicrm_api3_contact_merge($params) {
846 $mode = CRM_Utils_Array::value('mode', $params, 'safe');
847 $autoFlip = CRM_Utils_Array::value('auto_flip', $params, TRUE);
848
849 $dupePairs = array(array('srcID' => CRM_Utils_Array::value('main_id', $params),
850 'dstID' => CRM_Utils_Array::value('other_id', $params),
851 ));
852 $result = CRM_Dedupe_Merger::merge($dupePairs, array(), $mode, $autoFlip);
853
854 if ($result['is_error'] == 0) {
855 return civicrm_api3_create_success();
856 }
857 else {
858 return civicrm_api3_create_error($result['messages']);
859 }
860 }
861
862 function _civicrm_api3_contact_proximity_spec(&$params) {
863 $params['latitude']['api.required'] = 1;
864 $params['longitude']['api.required'] = 1;
865 $params['unit']['api.default'] = 'meter';
866 }
867
868 function civicrm_api3_contact_proximity($params) {
869 $latitude = CRM_Utils_Array::value('latitude', $params);
870 $longitude = CRM_Utils_Array::value('longitude', $params);
871 $distance = CRM_Utils_Array::value('distance', $params);
872
873 $unit = CRM_Utils_Array::value('unit', $params);
874
875 // check and ensure that lat/long and distance are floats
876 if (
877 !CRM_Utils_Rule::numeric($latitude) ||
878 !CRM_Utils_Rule::numeric($longitude) ||
879 !CRM_Utils_Rule::numeric($distance)
880 ) {
881 throw new Exception(ts('Latitude, Longitude and Distance should exist and be numeric'));
882 }
883
884 if ($unit == "mile") {
885 $conversionFactor = 1609.344;
886 }
887 else {
888 $conversionFactor = 1000;
889 }
890 //Distance in meters
891 $distance = $distance * $conversionFactor;
892
893 $whereClause = CRM_Contact_BAO_ProximityQuery::where($latitude, $longitude, $distance);
894
895 $query = "
896 SELECT civicrm_contact.id as contact_id,
897 civicrm_contact.display_name as display_name
898 FROM civicrm_contact
899 LEFT JOIN civicrm_address ON civicrm_contact.id = civicrm_address.contact_id
900 WHERE $whereClause
901 ";
902
903 $dao = CRM_Core_DAO::executeQuery($query);
904 $contacts = array();
905 while ($dao->fetch()) {
906 $contacts[] = $dao->toArray();
907 }
908
909 return civicrm_api3_create_success($contacts, $params, 'contact', 'get_by_location', $dao);
910 }
911