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