INFRA-132 - api/ - Misc
[civicrm-core.git] / CRM / Contact / Page / AJAX.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
32 *
33 */
34
35/**
36 * This class contains all contact related functions that are called using AJAX (jQuery)
37 */
38class CRM_Contact_Page_AJAX {
272081ca
TO
39 /**
40 * When a user chooses a username, CHECK_USERNAME_TTL
41 * is the time window in which they can check usernames
42 * (without reloading the overall form).
43 */
44 const CHECK_USERNAME_TTL = 10800; // 3hr; 3*60*60
45
b1dba111
TO
46 const AUTOCOMPLETE_TTL = 21600; // 6hr; 6*60*60
47
06508628
CW
48 /**
49 * @deprecated
50 */
00be9182 51 public static function getContactList() {
6a488035
TO
52 // if context is 'customfield'
53 if (CRM_Utils_Array::value('context', $_GET) == 'customfield') {
54 return self::contactReference();
55 }
56
57 $params = array('version' => 3, 'check_permissions' => TRUE);
58
133da98d
CW
59 // String params
60 // FIXME: param keys don't match input keys, using this array to translate
61 $whitelist = array(
62 's' => 'name',
63 'fieldName' => 'field_name',
64 'tableName' => 'table_name',
65 'context' => 'context',
2ddaadeb 66 'rel' => 'rel',
e1b717cb
P
67 'contact_sub_type' => 'contact_sub_type',
68 'contact_type' => 'contact_type'
133da98d
CW
69 );
70 foreach ($whitelist as $key => $param) {
71 if (!empty($_GET[$key])) {
72 $params[$param] = $_GET[$key];
73 }
6a488035
TO
74 }
75
76 //CRM-10687: Allow quicksearch by multiple fields
133da98d 77 if (!empty($params['field_name'])) {
6a488035
TO
78 if ($params['field_name'] == 'phone_numeric') {
79 $params['name'] = preg_replace('/[^\d]/', '', $params['name']);
80 }
81 if (!$params['name']) {
82 CRM_Utils_System::civiExit();
83 }
84 }
85
133da98d
CW
86 // Numeric params
87 $whitelist = array(
88 'limit',
89 'org',
90 'employee_id',
91 'cid',
92 'id',
93 'cmsuser',
94 );
95 foreach ($whitelist as $key) {
96 if (!empty($_GET[$key]) && is_numeric($_GET[$key])) {
97 $params[$key] = $_GET[$key];
98 }
6a488035
TO
99 }
100
101 $result = civicrm_api('Contact', 'getquick', $params);
d6408252 102 CRM_Core_Page_AJAX::autocompleteResults(CRM_Utils_Array::value('values', $result), 'data');
6a488035
TO
103 }
104
06508628
CW
105 /**
106 * Ajax callback for custom fields of type ContactReference
107 *
108 * Todo: Migrate contact reference fields to use EntityRef
109 */
00be9182 110 public static function contactReference() {
06508628 111 $name = CRM_Utils_Array::value('term', $_GET);
6a488035
TO
112 $name = CRM_Utils_Type::escape($name, 'String');
113 $cfID = CRM_Utils_Type::escape($_GET['id'], 'Positive');
114
115 // check that this is a valid, active custom field of Contact Reference type
06508628 116 $params = array('id' => $cfID);
6a488035 117 $returnProperties = array('filter', 'data_type', 'is_active');
06508628 118 $cf = array();
6a488035 119 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $cf, $returnProperties);
a4cce21a 120 if (!$cf['id'] || !$cf['is_active'] || $cf['data_type'] != 'ContactReference') {
06508628 121 CRM_Utils_System::civiExit('error');
6a488035
TO
122 }
123
9624538c 124 if (!empty($cf['filter'])) {
6a488035
TO
125 $filterParams = array();
126 parse_str($cf['filter'], $filterParams);
127
128 $action = CRM_Utils_Array::value('action', $filterParams);
129
130 if (!empty($action) &&
131 !in_array($action, array('get', 'lookup'))
132 ) {
06508628 133 CRM_Utils_System::civiExit('error');
6a488035
TO
134 }
135 }
136
137 $list = array_keys(CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
138 'contact_reference_options'
139 ), '1');
140
141 $return = array_unique(array_merge(array('sort_name'), $list));
142
06508628 143 $limit = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'search_autocomplete_count', NULL, 10);
6a488035
TO
144
145 $params = array('offset' => 0, 'rowCount' => $limit, 'version' => 3);
146 foreach ($return as $fld) {
147 $params["return.{$fld}"] = 1;
148 }
149
150 if (!empty($action)) {
151 $excludeGet = array('reset', 'key', 'className', 'fnName', 'json', 'reset', 'context', 'timestamp', 'limit', 'id', 's', 'q', 'action');
152 foreach ($_GET as $param => $val) {
153 if (empty($val) ||
154 in_array($param, $excludeGet) ||
155 strpos($param, 'return.') !== FALSE ||
156 strpos($param, 'api.') !== FALSE
157 ) {
158 continue;
159 }
160 $params[$param] = $val;
161 }
162 }
163
164 if ($name) {
165 $params['sort_name'] = $name;
166 }
167
168 $params['sort'] = 'sort_name';
169
170 // tell api to skip permission chk. dgg
171 $params['check_permissions'] = 0;
172
173 // add filter variable to params
174 if (!empty($filterParams)) {
175 $params = array_merge($params, $filterParams);
176 }
177
178 $contact = civicrm_api('Contact', 'Get', $params);
179
a7488080 180 if (!empty($contact['is_error'])) {
06508628 181 CRM_Utils_System::civiExit('error');
6a488035
TO
182 }
183
d6408252 184 $contactList = array();
6a488035
TO
185 foreach ($contact['values'] as $value) {
186 $view = array();
187 foreach ($return as $fld) {
a7488080 188 if (!empty($value[$fld])) {
6a488035
TO
189 $view[] = $value[$fld];
190 }
191 }
06508628 192 $contactList[] = array('id' => $value['id'], 'text' => implode(' :: ', $view));
6a488035
TO
193 }
194
06508628 195 CRM_Utils_System::civiExit(json_encode($contactList));
6a488035
TO
196 }
197
198 /**
100fef9d 199 * Fetch PCP ID by PCP Supporter sort_name, also displays PCP title and associated Contribution Page title
6a488035 200 */
00be9182 201 public static function getPCPList() {
6a488035
TO
202 $name = CRM_Utils_Array::value('s', $_GET);
203 $name = CRM_Utils_Type::escape($name, 'String');
204 $limit = '10';
205
206 $where = ' AND pcp.page_id = cp.id AND pcp.contact_id = cc.id';
207
208 $config = CRM_Core_Config::singleton();
209 if ($config->includeWildCardInName) {
210 $strSearch = "%$name%";
211 }
212 else {
213 $strSearch = "$name%";
214 }
215 $includeEmailFrom = $includeNickName = '';
216 if ($config->includeNickNameInName) {
217 $includeNickName = " OR nick_name LIKE '$strSearch'";
218 }
219 if ($config->includeEmailInName) {
220 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
221 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
222 }
223 else {
224 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
225 }
226
a7488080 227 if (!empty($_GET['limit'])) {
6a488035
TO
228 $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
229 }
230
231 $select = 'cc.sort_name, pcp.title, cp.title';
232 $query = "
233 SELECT id, data
234 FROM (
235 SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
236 FROM civicrm_pcp pcp, civicrm_contribution_page cp, civicrm_contact cc
237 {$includeEmailFrom}
900e6829 238 {$whereClause} AND pcp.page_type = 'contribute'
239 UNION ALL
240 SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
241 FROM civicrm_pcp pcp, civicrm_event cp, civicrm_contact cc
242 {$includeEmailFrom}
243 {$whereClause} AND pcp.page_type = 'event'
6a488035
TO
244 LIMIT 0, {$limit}
245 ) t
246 ORDER BY sort_name
247 ";
248
249 $dao = CRM_Core_DAO::executeQuery($query);
d6408252 250 $results = array();
6a488035 251 while ($dao->fetch()) {
6bb107ce 252 $results[] = array('id' => $dao->id, 'text' => $dao->data);
6a488035 253 }
ecdef330 254 CRM_Utils_JSON::output($results);
6a488035
TO
255 }
256
00be9182 257 public static function relationship() {
c91df8b4
CW
258 $relType = CRM_Utils_Request::retrieve('rel_type', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
259 $relContactID = CRM_Utils_Request::retrieve('rel_contact', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
260 $relationshipID = CRM_Utils_Array::value('rel_id', $_REQUEST); // this used only to determine add or update mode
261 $caseID = CRM_Utils_Request::retrieve('case_id', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
6a488035 262
14a679f1
KJ
263 // check if there are multiple clients for this case, if so then we need create
264 // relationship and also activities for each contacts
6a488035 265
14a679f1
KJ
266 // get case client list
267 $clientList = CRM_Case_BAO_Case::getCaseClients($caseID);
6a488035 268
c91df8b4
CW
269 $ret = array('is_error' => 0);
270
22e263ad 271 foreach ($clientList as $sourceContactID) {
14a679f1
KJ
272 $relationParams = array(
273 'relationship_type_id' => $relType . '_a_b',
274 'contact_check' => array($relContactID => 1),
275 'is_active' => 1,
276 'case_id' => $caseID,
277 'start_date' => date("Ymd"),
6a488035
TO
278 );
279
14a679f1
KJ
280 $relationIds = array('contact' => $sourceContactID);
281
282 // check if we are editing/updating existing relationship
283 if ($relationshipID && $relationshipID != 'null') {
284 // here we need to retrieve appropriate relationshipID based on client id and relationship type id
285 $caseRelationships = new CRM_Contact_DAO_Relationship();
286 $caseRelationships->case_id = $caseID;
287 $caseRelationships->relationship_type_id = $relType;
288 $caseRelationships->contact_id_a = $sourceContactID;
289 $caseRelationships->find();
290
22e263ad 291 while ($caseRelationships->fetch()) {
14a679f1
KJ
292 $relationIds['relationship'] = $caseRelationships->id;
293 $relationIds['contactTarget'] = $relContactID;
294 }
295 $caseRelationships->free();
296 }
297
298 // create new or update existing relationship
7ecf6275 299 $return = CRM_Contact_BAO_Relationship::createMultiple($relationParams, $relationIds);
14a679f1 300
a7488080 301 if (!empty($return[4][0])) {
14a679f1 302 $relationshipID = $return[4][0];
14a679f1
KJ
303
304 //create an activity for case role assignment.CRM-4480
305 CRM_Case_BAO_Case::createCaseRoleActivity($caseID, $relationshipID, $relContactID);
306 }
c91df8b4
CW
307 else {
308 $ret = array(
309 'is_error' => 1,
310 'error_message' => ts('The relationship type definition for the case role is not valid for the client and / or staff contact types. You can review and edit relationship types at <a href="%1">Administer >> Option Lists >> Relationship Types</a>.',
311 array(1 => CRM_Utils_System::url('civicrm/admin/reltype', 'reset=1')))
312 );
313 }
6a488035 314 }
6a488035 315
ecdef330 316 CRM_Utils_JSON::output($ret);
6a488035
TO
317 }
318
319 /**
100fef9d 320 * Fetch the custom field help
6a488035 321 */
00be9182 322 public static function customField() {
6a488035
TO
323 $fieldId = CRM_Utils_Type::escape($_REQUEST['id'], 'Integer');
324 $params = array('id' => $fieldId);
325 $returnProperties = array('help_pre', 'help_post');
326 $values = array();
327
328 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $values, $returnProperties);
ecdef330 329 CRM_Utils_JSON::output($values);
6a488035
TO
330 }
331
00be9182 332 public static function groupTree() {
6a488035
TO
333 $gids = CRM_Utils_Type::escape($_GET['gids'], 'String');
334 echo CRM_Contact_BAO_GroupNestingCache::json($gids);
335 CRM_Utils_System::civiExit();
336 }
337
338 /**
d6408252
CW
339 * @deprecated
340 * Old quicksearch function. No longer used in core.
341 * @todo: Remove this function and associated menu entry in CiviCRM 5
6a488035 342 */
00be9182 343 public static function search() {
6a488035
TO
344 $json = TRUE;
345 $name = CRM_Utils_Array::value('name', $_GET, '');
346 if (!array_key_exists('name', $_GET)) {
347 $name = CRM_Utils_Array::value('s', $_GET) . '%';
348 $json = FALSE;
349 }
350 $name = CRM_Utils_Type::escape($name, 'String');
351 $whereIdClause = '';
a7488080 352 if (!empty($_GET['id'])) {
6a488035
TO
353 $json = TRUE;
354 if (is_numeric($_GET['id'])) {
355 $id = CRM_Utils_Type::escape($_GET['id'], 'Integer');
356 $whereIdClause = " AND civicrm_contact.id = {$id}";
357 }
358 else {
359 $name = $_GET['id'];
360 }
361 }
362
363 $elements = array();
364 if ($name || isset($id)) {
365 $name = $name . '%';
366
367 //contact's based of relationhip type
368 $relType = NULL;
369 if (isset($_GET['rel'])) {
370 $relation = explode('_', $_GET['rel']);
371 $relType = CRM_Utils_Type::escape($relation[0], 'Integer');
372 $rel = CRM_Utils_Type::escape($relation[2], 'String');
373 }
374
375 //shared household info
376 $shared = NULL;
377 if (isset($_GET['sh'])) {
378 $shared = CRM_Utils_Type::escape($_GET['sh'], 'Integer');
379 if ($shared == 1) {
380 $contactType = 'Household';
381 $cName = 'household_name';
382 }
383 else {
384 $contactType = 'Organization';
385 $cName = 'organization_name';
386 }
387 }
388
389 // contacts of type household
390 $hh = $addStreet = $addCity = NULL;
391 if (isset($_GET['hh'])) {
392 $hh = CRM_Utils_Type::escape($_GET['hh'], 'Integer');
393 }
394
395 //organization info
396 $organization = $street = $city = NULL;
397 if (isset($_GET['org'])) {
398 $organization = CRM_Utils_Type::escape($_GET['org'], 'Integer');
399 }
400
401 if (isset($_GET['org']) || isset($_GET['hh'])) {
402 $json = FALSE;
a4cce21a
JM
403 $splitName = explode(' :: ', $name);
404 if ($splitName) {
6a488035
TO
405 $contactName = trim(CRM_Utils_Array::value('0', $splitName));
406 $street = trim(CRM_Utils_Array::value('1', $splitName));
407 $city = trim(CRM_Utils_Array::value('2', $splitName));
408 }
409 else {
410 $contactName = $name;
411 }
412
413 if ($street) {
414 $addStreet = "AND civicrm_address.street_address LIKE '$street%'";
415 }
416 if ($city) {
417 $addCity = "AND civicrm_address.city LIKE '$city%'";
418 }
419 }
420
421 if ($organization) {
422
423 $query = "
424SELECT CONCAT_WS(' :: ',sort_name,LEFT(street_address,25),city) 'sort_name',
425civicrm_contact.id 'id'
426FROM civicrm_contact
427LEFT JOIN civicrm_address ON ( civicrm_contact.id = civicrm_address.contact_id
428 AND civicrm_address.is_primary=1
429 )
430WHERE civicrm_contact.contact_type='Organization' AND organization_name LIKE '%$contactName%'
431{$addStreet} {$addCity} {$whereIdClause}
432ORDER BY organization_name ";
433 }
434 elseif ($shared) {
435 $query = "
436SELECT CONCAT_WS(':::' , sort_name, supplemental_address_1, sp.abbreviation, postal_code, cc.name )'sort_name' , civicrm_contact.id 'id' , civicrm_contact.display_name 'disp' FROM civicrm_contact LEFT JOIN civicrm_address ON (civicrm_contact.id =civicrm_address.contact_id AND civicrm_address.is_primary =1 )LEFT JOIN civicrm_state_province sp ON (civicrm_address.state_province_id =sp.id )LEFT JOIN civicrm_country cc ON (civicrm_address.country_id =cc.id )WHERE civicrm_contact.contact_type ='{$contactType}' AND {$cName} LIKE '%$name%' {$whereIdClause} ORDER BY {$cName} ";
437 }
438 elseif ($hh) {
439 $query = "
440SELECT CONCAT_WS(' :: ' , sort_name, LEFT(street_address,25),city) 'sort_name' , location_type_id 'location_type_id', is_primary 'is_primary', is_billing 'is_billing', civicrm_contact.id 'id'
441FROM civicrm_contact
442LEFT JOIN civicrm_address ON (civicrm_contact.id =civicrm_address.contact_id AND civicrm_address.is_primary =1 )
443WHERE civicrm_contact.contact_type ='Household'
444AND household_name LIKE '%$contactName%' {$addStreet} {$addCity} {$whereIdClause} ORDER BY household_name ";
445 }
446 elseif ($relType) {
a7488080 447 if (!empty($_GET['case'])) {
6a488035
TO
448 $query = "
449SELECT distinct(c.id), c.sort_name
450FROM civicrm_contact c
451LEFT JOIN civicrm_relationship ON civicrm_relationship.contact_id_{$rel} = c.id
452WHERE c.sort_name LIKE '%$name%'
453AND civicrm_relationship.relationship_type_id = $relType
454GROUP BY sort_name
455";
456 }
457 }
458 else {
459
460 $query = "
461SELECT sort_name, id
462FROM civicrm_contact
463WHERE sort_name LIKE '%$name'
464{$whereIdClause}
465ORDER BY sort_name ";
466 }
467
468 $limit = 10;
469 if (isset($_GET['limit'])) {
470 $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
471 }
472
473 $query .= " LIMIT 0,{$limit}";
474
475 $dao = CRM_Core_DAO::executeQuery($query);
476
477 if ($shared) {
478 while ($dao->fetch()) {
479 echo $dao->sort_name;
480 CRM_Utils_System::civiExit();
481 }
482 }
483 else {
484 while ($dao->fetch()) {
485 if ($json) {
ce80b209
TO
486 $elements[] = array(
487 'name' => addslashes($dao->sort_name),
6a488035
TO
488 'id' => $dao->id,
489 );
490 }
491 else {
492 echo $elements = "$dao->sort_name|$dao->id|$dao->location_type_id|$dao->is_primary|$dao->is_billing\n";
493 }
494 }
495 //for adding new household address / organization
496 if (empty($elements) && !$json && ($hh || $organization)) {
497 echo CRM_Utils_Array::value('s', $_GET);
498 }
499 }
500 }
501
502 if (isset($_GET['sh'])) {
503 echo "";
504 CRM_Utils_System::civiExit();
505 }
506
507 if (empty($elements)) {
508 $name = str_replace('%', '', $name);
509 $elements[] = array(
510 'name' => $name,
511 'id' => $name,
512 );
513 }
514
515 if ($json) {
516 echo json_encode($elements);
517 }
518 CRM_Utils_System::civiExit();
519 }
520
6a488035 521 /**
100fef9d 522 * Delete custom value
6a488035
TO
523 *
524 */
00be9182 525 public static function deleteCustomValue() {
6a488035
TO
526 $customValueID = CRM_Utils_Type::escape($_REQUEST['valueID'], 'Positive');
527 $customGroupID = CRM_Utils_Type::escape($_REQUEST['groupID'], 'Positive');
528
529 CRM_Core_BAO_CustomValue::deleteCustomValue($customValueID, $customGroupID);
a4cce21a
JM
530 $contactId = CRM_Utils_Array::value('contactId', $_REQUEST);
531 if ($contactId) {
6a488035
TO
532 echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $_REQUEST['groupID'], $contactId);
533 }
534
535 // reset the group contact cache for this group
536 CRM_Contact_BAO_GroupContactCache::remove();
537 CRM_Utils_System::civiExit();
538 }
539
540 /**
100fef9d 541 * Perform enable / disable actions on record.
6a488035
TO
542 *
543 */
00be9182 544 public static function enableDisable() {
6a488035
TO
545 $op = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
546 $recordID = CRM_Utils_Type::escape($_REQUEST['recordID'], 'Positive');
547 $recordBAO = CRM_Utils_Type::escape($_REQUEST['recordBAO'], 'String');
548
549 $isActive = NULL;
550 if ($op == 'disable-enable') {
551 $isActive = TRUE;
552 }
553 elseif ($op == 'enable-disable') {
554 $isActive = FALSE;
555 }
556 $status = array('status' => 'record-updated-fail');
557 if (isset($isActive)) {
558 // first munge and clean the recordBAO and get rid of any non alpha numeric characters
559 $recordBAO = CRM_Utils_String::munge($recordBAO);
560 $recordClass = explode('_', $recordBAO);
561
562 // make sure recordClass is namespaced (we cant check CRM since extensions can also use this)
563 // but it should be at least 3 levels deep
564 if (count($recordClass) >= 3) {
ce80b209 565 require_once str_replace('_', DIRECTORY_SEPARATOR, $recordBAO) . ".php";
6a488035
TO
566 $method = 'setIsActive';
567
568 if (method_exists($recordBAO, $method)) {
569 $updated = call_user_func_array(array($recordBAO, $method),
570 array($recordID, $isActive)
571 );
572 if ($updated) {
573 $status = array('status' => 'record-updated-success');
574 }
575
576 // call hook enableDisable
577 CRM_Utils_Hook::enableDisable($recordBAO, $recordID, $isActive);
578 }
579 }
ecdef330 580 CRM_Utils_JSON::output($status);
6a488035
TO
581 }
582 }
583
584 /**
ce80b209
TO
585 * check the CMS username
586 *
587 */
6a488035 588 static public function checkUserName() {
272081ca
TO
589 $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('for', 'ts'));
590 if (
591 CRM_Utils_Time::getTimeRaw() > $_REQUEST['ts'] + self::CHECK_USERNAME_TTL
592 || $_REQUEST['for'] != 'civicrm/ajax/cmsuser'
593 || !$signer->validate($_REQUEST['sig'], $_REQUEST)
594 ) {
595 $user = array('name' => 'error');
596 echo json_encode($user);
597 CRM_Utils_System::civiExit();
598 }
599
6a488035
TO
600 $config = CRM_Core_Config::singleton();
601 $username = trim($_REQUEST['cms_name']);
602
603 $params = array('name' => $username);
604
605 $errors = array();
606 $config->userSystem->checkUserNameEmailExists($params, $errors);
607
608 if (isset($errors['cms_name']) || isset($errors['name'])) {
609 //user name is not availble
610 $user = array('name' => 'no');
611 echo json_encode($user);
612 }
613 else {
614 //user name is available
615 $user = array('name' => 'yes');
616 echo json_encode($user);
617 }
618 CRM_Utils_System::civiExit();
619 }
620
621 /**
622 * Function to get email address of a contact
623 */
00be9182 624 public static function getContactEmail() {
a7488080 625 if (!empty($_REQUEST['contact_id'])) {
6a488035 626 $contactID = CRM_Utils_Type::escape($_REQUEST['contact_id'], 'Positive');
8c0ea1d7
TO
627 if (!CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::EDIT)) {
628 return;
629 }
6a488035
TO
630 list($displayName,
631 $userEmail
632 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
633 if ($userEmail) {
634 echo $userEmail;
635 }
636 }
637 else {
638 $noemail = CRM_Utils_Array::value('noemail', $_GET);
639 $queryString = NULL;
a4cce21a
JM
640 $name = CRM_Utils_Array::value('name', $_GET);
641 if ($name) {
6a488035
TO
642 $name = CRM_Utils_Type::escape($name, 'String');
643 if ($noemail) {
644 $queryString = " cc.sort_name LIKE '%$name%'";
645 }
646 else {
647 $queryString = " ( cc.sort_name LIKE '%$name%' OR ce.email LIKE '%$name%' ) ";
648 }
649 }
a4cce21a 650 else {
d75f2f47
EM
651 $cid = CRM_Utils_Array::value('cid', $_GET);
652 if ($cid) {
a4cce21a
JM
653 //check cid for interger
654 $contIDS = explode(',', $cid);
655 foreach ($contIDS as $contID) {
656 CRM_Utils_Type::escape($contID, 'Integer');
657 }
658 $queryString = " cc.id IN ( $cid )";
d75f2f47 659 }
6a488035
TO
660 }
661
662 if ($queryString) {
663 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
cac1236c 664 $rowCount = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'search_autocomplete_count', NULL, 10);
6a488035 665
bf00d1b6 666 $offset = CRM_Utils_Type::escape($offset, 'Int');
bf00d1b6 667
6a488035
TO
668 // add acl clause here
669 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
670 if ($aclWhere) {
671 $aclWhere = " AND $aclWhere";
672 }
673 if ($noemail) {
674 $query = "
675SELECT sort_name name, cc.id
676FROM civicrm_contact cc
677 {$aclFrom}
678WHERE cc.is_deceased = 0 AND {$queryString}
679 {$aclWhere}
680LIMIT {$offset}, {$rowCount}
681";
682
683 // send query to hook to be modified if needed
684 CRM_Utils_Hook::contactListQuery($query,
685 $name,
686 CRM_Utils_Array::value('context', $_GET),
687 CRM_Utils_Array::value('cid', $_GET)
688 );
689
690 $dao = CRM_Core_DAO::executeQuery($query);
691 while ($dao->fetch()) {
692 $result[] = array(
6a488035 693 'id' => $dao->id,
cac1236c 694 'text' => $dao->name,
6a488035
TO
695 );
696 }
697 }
698 else {
699 $query = "
700SELECT sort_name name, ce.email, cc.id
701FROM civicrm_email ce INNER JOIN civicrm_contact cc ON cc.id = ce.contact_id
702 {$aclFrom}
703WHERE ce.on_hold = 0 AND cc.is_deceased = 0 AND cc.do_not_email = 0 AND {$queryString}
704 {$aclWhere}
705LIMIT {$offset}, {$rowCount}
706";
707
708 // send query to hook to be modified if needed
709 CRM_Utils_Hook::contactListQuery($query,
710 $name,
711 CRM_Utils_Array::value('context', $_GET),
712 CRM_Utils_Array::value('cid', $_GET)
713 );
714
6a488035
TO
715 $dao = CRM_Core_DAO::executeQuery($query);
716
717 while ($dao->fetch()) {
ce80b209 718 //working here
6a488035 719 $result[] = array(
cac1236c 720 'text' => '"' . $dao->name . '" <' . $dao->email . '>',
6a488035
TO
721 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->email}" : '"' . $dao->name . '" <' . $dao->email . '>',
722 );
723 }
724 }
6a488035
TO
725 if ($result) {
726 echo json_encode($result);
727 }
728 }
729 }
730 CRM_Utils_System::civiExit();
731 }
732
00be9182 733 public static function getContactPhone() {
6a488035
TO
734
735 $queryString = NULL;
736 //check for mobile type
737 $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
738 $mobileType = CRM_Utils_Array::value('Mobile', $phoneTypes);
739
a4cce21a
JM
740 $name = CRM_Utils_Array::value('name', $_GET);
741 if ($name) {
6a488035
TO
742 $name = CRM_Utils_Type::escape($name, 'String');
743 $queryString = " ( cc.sort_name LIKE '%$name%' OR cp.phone LIKE '%$name%' ) ";
744 }
a4cce21a 745 else {
d75f2f47
EM
746 $cid = CRM_Utils_Array::value('cid', $_GET);
747 if ($cid) {
a4cce21a
JM
748 //check cid for interger
749 $contIDS = explode(',', $cid);
750 foreach ($contIDS as $contID) {
751 CRM_Utils_Type::escape($contID, 'Integer');
752 }
753 $queryString = " cc.id IN ( $cid )";
6a488035 754 }
6a488035
TO
755 }
756
757 if ($queryString) {
758 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
759 $rowCount = CRM_Utils_Array::value('rowcount', $_GET, 20);
760
bf00d1b6
DL
761 $offset = CRM_Utils_Type::escape($offset, 'Int');
762 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
763
6a488035
TO
764 // add acl clause here
765 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
766 if ($aclWhere) {
767 $aclWhere = " AND $aclWhere";
768 }
769
770 $query = "
771SELECT sort_name name, cp.phone, cc.id
772FROM civicrm_phone cp INNER JOIN civicrm_contact cc ON cc.id = cp.contact_id
773 {$aclFrom}
774WHERE cc.is_deceased = 0 AND cc.do_not_sms = 0 AND cp.phone_type_id = {$mobileType} AND {$queryString}
775 {$aclWhere}
776LIMIT {$offset}, {$rowCount}
777";
778
779 // send query to hook to be modified if needed
780 CRM_Utils_Hook::contactListQuery($query,
781 $name,
782 CRM_Utils_Array::value('context', $_GET),
783 CRM_Utils_Array::value('cid', $_GET)
784 );
785
786 $dao = CRM_Core_DAO::executeQuery($query);
787
788 while ($dao->fetch()) {
789 $result[] = array(
b792e485 790 'text' => '"' . $dao->name . '" (' . $dao->phone . ')',
6a488035
TO
791 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->phone}" : '"' . $dao->name . '" <' . $dao->phone . '>',
792 );
793 }
794 }
795
796 if ($result) {
797 echo json_encode($result);
798 }
799 CRM_Utils_System::civiExit();
800 }
801
802
00be9182 803 public static function buildSubTypes() {
6a488035
TO
804 $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
805
806 switch ($parent) {
807 case 1:
808 $contactType = 'Individual';
809 break;
810
811 case 2:
812 $contactType = 'Household';
813 break;
814
815 case 4:
816 $contactType = 'Organization';
817 break;
818 }
819
820 $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($contactType, FALSE, NULL);
821 asort($subTypes);
ecdef330 822 CRM_Utils_JSON::output($subTypes);
6a488035
TO
823 }
824
00be9182 825 public static function buildDedupeRules() {
6a488035
TO
826 $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
827
828 switch ($parent) {
829 case 1:
830 $contactType = 'Individual';
831 break;
832
833 case 2:
834 $contactType = 'Household';
835 break;
836
837 case 4:
838 $contactType = 'Organization';
839 break;
840 }
841
842 $dedupeRules = CRM_Dedupe_BAO_RuleGroup::getByType($contactType);
843
ecdef330 844 CRM_Utils_JSON::output($dedupeRules);
6a488035
TO
845 }
846
847 /**
848 * Function used for CiviCRM dashboard operations
849 */
00be9182 850 public static function dashboard() {
6a488035
TO
851 $operation = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
852
853 switch ($operation) {
854 case 'get_widgets_by_column':
855 // This would normally be coming from either the database (this user's settings) or a default/initial dashboard configuration.
856 // get contact id of logged in user
857
858 $dashlets = CRM_Core_BAO_Dashboard::getContactDashlets();
859 break;
860
861 case 'get_widget':
862 $dashletID = CRM_Utils_Type::escape($_GET['id'], 'Positive');
863
864 $dashlets = CRM_Core_BAO_Dashboard::getDashletInfo($dashletID);
865 break;
866
867 case 'save_columns':
868 CRM_Core_BAO_Dashboard::saveDashletChanges($_REQUEST['columns']);
869 CRM_Utils_System::civiExit();
870 case 'delete_dashlet':
871 $dashletID = CRM_Utils_Type::escape($_REQUEST['dashlet_id'], 'Positive');
872 CRM_Core_BAO_Dashboard::deleteDashlet($dashletID);
873 CRM_Utils_System::civiExit();
874 }
875
ecdef330 876 CRM_Utils_JSON::output($dashlets);
6a488035
TO
877 }
878
879 /**
100fef9d 880 * Retrieve signature based on email id
6a488035 881 */
00be9182 882 public static function getSignature() {
6a488035
TO
883 $emailID = CRM_Utils_Type::escape($_REQUEST['emailID'], 'Positive');
884 $query = "SELECT signature_text, signature_html FROM civicrm_email WHERE id = {$emailID}";
885 $dao = CRM_Core_DAO::executeQuery($query);
886
887 $signatures = array();
888 while ($dao->fetch()) {
889 $signatures = array(
890 'signature_text' => $dao->signature_text,
891 'signature_html' => $dao->signature_html,
892 );
893 }
894
ecdef330 895 CRM_Utils_JSON::output($signatures);
6a488035
TO
896 }
897
898 /**
100fef9d 899 * Process dupes.
6a488035
TO
900 *
901 */
00be9182 902 public static function processDupes() {
6a488035
TO
903 $oper = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
904 $cid = CRM_Utils_Type::escape($_REQUEST['cid'], 'Positive');
905 $oid = CRM_Utils_Type::escape($_REQUEST['oid'], 'Positive');
906
907 if (!$oper || !$cid || !$oid) {
908 return;
909 }
910
911 $exception = new CRM_Dedupe_DAO_Exception();
912 $exception->contact_id1 = $cid;
913 $exception->contact_id2 = $oid;
914 //make sure contact2 > contact1.
915 if ($cid > $oid) {
916 $exception->contact_id1 = $oid;
917 $exception->contact_id2 = $cid;
918 }
919 $exception->find(TRUE);
920 $status = NULL;
921 if ($oper == 'dupe-nondupe') {
922 $status = $exception->save();
923 }
924 if ($oper == 'nondupe-dupe') {
925 $status = $exception->delete();
926 }
927
ecdef330 928 CRM_Utils_JSON::output(array('status' => ($status) ? $oper : $status));
6a488035
TO
929 }
930
00be9182 931 public static function getDedupes() {
6a488035
TO
932
933 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
934 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
935 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
1049d019 936 $sort = 'sort_name';
6a488035
TO
937 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
938
939 $gid = isset($_REQUEST['gid']) ? CRM_Utils_Type::escape($_REQUEST['gid'], 'Integer') : 0;
940 $rgid = isset($_REQUEST['rgid']) ? CRM_Utils_Type::escape($_REQUEST['rgid'], 'Integer') : 0;
941 $contactType = '';
942 if ($rgid) {
943 $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
944 }
945
946 $cacheKeyString = "merge {$contactType}_{$rgid}_{$gid}";
947 $searchRows = array();
948 $selectorElements = array('src', 'dst', 'weight', 'actions');
949
6a488035
TO
950 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
951 pn.entity_id2 = de.contact_id2 )";
952 $where = "de.id IS NULL";
953
954 $iFilteredTotal = $iTotal = CRM_Core_BAO_PrevNextCache::getCount($cacheKeyString, $join, $where);
955 $mainContacts = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, $offset, $rowCount);
956
957 foreach ($mainContacts as $mainId => $main) {
958 $searchRows[$mainId]['src'] = CRM_Utils_System::href($main['srcName'], 'civicrm/contact/view', "reset=1&cid={$main['srcID']}");
959 $searchRows[$mainId]['dst'] = CRM_Utils_System::href($main['dstName'], 'civicrm/contact/view', "reset=1&cid={$main['dstID']}");
960 $searchRows[$mainId]['weight'] = CRM_Utils_Array::value('weight', $main);
961
a7488080 962 if (!empty($main['canMerge'])) {
6a488035
TO
963 $mergeParams = "reset=1&cid={$main['srcID']}&oid={$main['dstID']}&action=update&rgid={$rgid}";
964 if ($gid) {
965 $mergeParams .= "&gid={$gid}";
966 }
967
968 $searchRows[$mainId]['actions'] = CRM_Utils_System::href(ts('merge'), 'civicrm/contact/merge', $mergeParams);
969 $searchRows[$mainId]['actions'] .= "&nbsp;|&nbsp; <a id='notDuplicate' href='#' onClick=\"processDupes( {$main['srcID']}, {$main['dstID']}, 'dupe-nondupe', 'dupe-listing'); return false;\">" . ts('not a duplicate') . "</a>";
970 }
971 else {
972 $searchRows[$mainId]['actions'] = '<em>' . ts('Insufficient access rights - cannot merge') . '</em>';
973 }
974 }
975
976 echo CRM_Utils_JSON::encodeDataTableSelector($searchRows, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
977
978 CRM_Utils_System::civiExit();
979 }
980
981 /**
100fef9d 982 * Retrieve a PDF Page Format for the PDF Letter form
6a488035 983 */
00be9182 984 public function pdfFormat() {
6a488035
TO
985 $formatId = CRM_Utils_Type::escape($_REQUEST['formatId'], 'Integer');
986
987 $pdfFormat = CRM_Core_BAO_PdfFormat::getById($formatId);
988
ecdef330 989 CRM_Utils_JSON::output($pdfFormat);
6a488035
TO
990 }
991
992 /**
100fef9d 993 * Retrieve Paper Size dimensions
6a488035 994 */
00be9182 995 public static function paperSize() {
6a488035
TO
996 $paperSizeName = CRM_Utils_Type::escape($_REQUEST['paperSizeName'], 'String');
997
998 $paperSize = CRM_Core_BAO_PaperSize::getByName($paperSizeName);
999
ecdef330 1000 CRM_Utils_JSON::output($paperSize);
6a488035
TO
1001 }
1002
00be9182 1003 public static function selectUnselectContacts() {
6a488035
TO
1004 $name = CRM_Utils_Array::value('name', $_REQUEST);
1005 $cacheKey = CRM_Utils_Array::value('qfKey', $_REQUEST);
1006 $state = CRM_Utils_Array::value('state', $_REQUEST, 'checked');
1007 $variableType = CRM_Utils_Array::value('variableType', $_REQUEST, 'single');
1008
1009 $actionToPerform = CRM_Utils_Array::value('action', $_REQUEST, 'select');
1010
1011 if ($variableType == 'multiple') {
1012 // action post value only works with multiple type variable
1013 if ($name) {
1014 //multiple names like mark_x_1-mark_x_2 where 1,2 are cids
1015 $elements = explode('-', $name);
1016 foreach ($elements as $key => $element) {
1017 $elements[$key] = self::_convertToId($element);
1018 }
1019 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $actionToPerform, $elements);
1020 }
1021 else {
1022 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $actionToPerform);
1023 }
1024 }
1025 elseif ($variableType == 'single') {
1026 $cId = self::_convertToId($name);
1027 $action = ($state == 'checked') ? 'select' : 'unselect';
1028 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $action, $cId);
1029 }
1030 $contactIds = CRM_Core_BAO_PrevNextCache::getSelection($cacheKey);
1031 $countSelectionCids = count($contactIds[$cacheKey]);
1032
1033 $arrRet = array('getCount' => $countSelectionCids);
ecdef330 1034 CRM_Utils_JSON::output($arrRet);
6a488035
TO
1035 }
1036
4319322b 1037 /**
100fef9d 1038 * @param string $name
4319322b
EM
1039 *
1040 * @return string
1041 */
00be9182 1042 public static function _convertToId($name) {
6a488035
TO
1043 if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
1044 $cId = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
1045 }
1046 return $cId;
1047 }
1048
00be9182 1049 public static function getAddressDisplay() {
6a488035
TO
1050 $contactId = CRM_Utils_Array::value('contact_id', $_REQUEST);
1051 if (!$contactId) {
1052 $addressVal["error_message"] = "no contact id found";
1053 }
1054 else {
1055 $entityBlock =
1056 array(
1057 'contact_id' => $contactId,
1058 'entity_id' => $contactId,
1059 );
1060 $addressVal = CRM_Core_BAO_Address::getValues($entityBlock);
1061 }
1062
ecdef330 1063 CRM_Utils_JSON::output($addressVal);
6a488035 1064 }
40458f6c 1065
1066 /**
100fef9d 1067 * Retrieve contact relationships
40458f6c 1068 */
1069 public static function getContactRelationships() {
1070 $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
1071 $context = CRM_Utils_Type::escape($_GET['context'], 'String');
1072
1073 $sortMapper = array(
1074 0 => 'relation',
1075 1 => 'sort_name',
1076 2 => 'start_date',
1077 3 => 'end_date',
1078 4 => 'city',
1079 5 => 'state',
1080 6 => 'email',
1081 7 => 'phone',
1082 8 => 'links',
e1cad725 1083 9 => '',
f1321272 1084 10 => '',
40458f6c 1085 );
1086
1087 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
1088 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
1089 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
1090 $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
1091 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
1092
1093 $params = $_POST;
1094 if ($sort && $sortOrder) {
1095 $params['sortBy'] = $sort . ' ' . $sortOrder;
1096 }
1097
1098 $params['page'] = ($offset / $rowCount) + 1;
1099 $params['rp'] = $rowCount;
1100
1101 $params['contact_id'] = $contactID;
1102 $params['context'] = $context;
1103
1104 // get the contact relationships
1105 $relationships = CRM_Contact_BAO_Relationship::getContactRelationshipSelector($params);
1106
1107 $iFilteredTotal = $iTotal = $params['total'];
1108 $selectorElements = array(
1109 'relation',
1110 'name',
1111 'start_date',
1112 'end_date',
1113 'city',
1114 'state',
1115 'email',
1116 'phone',
1117 'links',
e1cad725 1118 'id',
f1321272 1119 'is_active',
40458f6c 1120 );
1121
1122 echo CRM_Utils_JSON::encodeDataTableSelector($relationships, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
1123 CRM_Utils_System::civiExit();
1124 }
6a488035 1125}