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