Merge pull request #12615 from eileenmcnaughton/amex
[civicrm-core.git] / CRM / Contact / Page / AJAX.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
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 48 /**
06508628
CW
49 * Ajax callback for custom fields of type ContactReference
50 *
51 * Todo: Migrate contact reference fields to use EntityRef
52 */
00be9182 53 public static function contactReference() {
06508628 54 $name = CRM_Utils_Array::value('term', $_GET);
6a488035
TO
55 $name = CRM_Utils_Type::escape($name, 'String');
56 $cfID = CRM_Utils_Type::escape($_GET['id'], 'Positive');
57
58 // check that this is a valid, active custom field of Contact Reference type
06508628 59 $params = array('id' => $cfID);
6a488035 60 $returnProperties = array('filter', 'data_type', 'is_active');
06508628 61 $cf = array();
6a488035 62 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $cf, $returnProperties);
a4cce21a 63 if (!$cf['id'] || !$cf['is_active'] || $cf['data_type'] != 'ContactReference') {
d8cdb7e5 64 CRM_Utils_System::civiExit(1);
6a488035
TO
65 }
66
9624538c 67 if (!empty($cf['filter'])) {
6a488035
TO
68 $filterParams = array();
69 parse_str($cf['filter'], $filterParams);
70
71 $action = CRM_Utils_Array::value('action', $filterParams);
da0136df 72 if (!empty($action) && !in_array($action, array('get', 'lookup'))) {
d8cdb7e5 73 CRM_Utils_System::civiExit(1);
6a488035 74 }
da0136df 75
76 if (!empty($filterParams['group'])) {
77 $filterParams['group'] = explode(',', $filterParams['group']);
78 }
6a488035
TO
79 }
80
81 $list = array_keys(CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
353ffa53
TO
82 'contact_reference_options'
83 ), '1');
6a488035
TO
84
85 $return = array_unique(array_merge(array('sort_name'), $list));
86
89595c92 87 $limit = Civi::settings()->get('search_autocomplete_count');
6a488035
TO
88
89 $params = array('offset' => 0, 'rowCount' => $limit, 'version' => 3);
90 foreach ($return as $fld) {
91 $params["return.{$fld}"] = 1;
92 }
93
94 if (!empty($action)) {
353ffa53
TO
95 $excludeGet = array(
96 'reset',
97 'key',
98 'className',
99 'fnName',
100 'json',
101 'reset',
102 'context',
103 'timestamp',
104 'limit',
105 'id',
106 's',
107 'q',
408b79bf 108 'action',
353ffa53 109 );
6a488035
TO
110 foreach ($_GET as $param => $val) {
111 if (empty($val) ||
112 in_array($param, $excludeGet) ||
113 strpos($param, 'return.') !== FALSE ||
114 strpos($param, 'api.') !== FALSE
115 ) {
116 continue;
117 }
118 $params[$param] = $val;
119 }
120 }
121
122 if ($name) {
123 $params['sort_name'] = $name;
124 }
125
126 $params['sort'] = 'sort_name';
127
128 // tell api to skip permission chk. dgg
129 $params['check_permissions'] = 0;
130
131 // add filter variable to params
132 if (!empty($filterParams)) {
133 $params = array_merge($params, $filterParams);
134 }
135
136 $contact = civicrm_api('Contact', 'Get', $params);
137
a7488080 138 if (!empty($contact['is_error'])) {
d8cdb7e5 139 CRM_Utils_System::civiExit(1);
6a488035
TO
140 }
141
d6408252 142 $contactList = array();
6a488035
TO
143 foreach ($contact['values'] as $value) {
144 $view = array();
145 foreach ($return as $fld) {
a7488080 146 if (!empty($value[$fld])) {
6a488035
TO
147 $view[] = $value[$fld];
148 }
149 }
06508628 150 $contactList[] = array('id' => $value['id'], 'text' => implode(' :: ', $view));
6a488035
TO
151 }
152
da0136df 153 if (!empty($_GET['is_unit_test'])) {
154 return $contactList;
155 }
8be1a839 156 CRM_Utils_JSON::output($contactList);
6a488035
TO
157 }
158
159 /**
100fef9d 160 * Fetch PCP ID by PCP Supporter sort_name, also displays PCP title and associated Contribution Page title
6a488035 161 */
00be9182 162 public static function getPCPList() {
7d86179d 163 $name = CRM_Utils_Array::value('term', $_GET);
353ffa53 164 $name = CRM_Utils_Type::escape($name, 'String');
89595c92 165 $limit = $max = Civi::settings()->get('search_autocomplete_count');
6a488035
TO
166
167 $where = ' AND pcp.page_id = cp.id AND pcp.contact_id = cc.id';
168
169 $config = CRM_Core_Config::singleton();
170 if ($config->includeWildCardInName) {
171 $strSearch = "%$name%";
172 }
173 else {
174 $strSearch = "$name%";
175 }
176 $includeEmailFrom = $includeNickName = '';
177 if ($config->includeNickNameInName) {
178 $includeNickName = " OR nick_name LIKE '$strSearch'";
179 }
180 if ($config->includeEmailInName) {
181 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
182 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
183 }
184 else {
185 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
186 }
187
8da35492 188 $offset = $count = 0;
4feb1cad
CW
189 if (!empty($_GET['page_num'])) {
190 $page = (int) $_GET['page_num'];
8da35492
CW
191 $offset = $limit * ($page - 1);
192 $limit++;
6a488035
TO
193 }
194
195 $select = 'cc.sort_name, pcp.title, cp.title';
196 $query = "
197 SELECT id, data
198 FROM (
199 SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
200 FROM civicrm_pcp pcp, civicrm_contribution_page cp, civicrm_contact cc
201 {$includeEmailFrom}
900e6829 202 {$whereClause} AND pcp.page_type = 'contribute'
203 UNION ALL
204 SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
205 FROM civicrm_pcp pcp, civicrm_event cp, civicrm_contact cc
206 {$includeEmailFrom}
207 {$whereClause} AND pcp.page_type = 'event'
6a488035
TO
208 ) t
209 ORDER BY sort_name
8da35492 210 LIMIT $offset, $limit
6a488035
TO
211 ";
212
213 $dao = CRM_Core_DAO::executeQuery($query);
8da35492 214 $output = array('results' => array(), 'more' => FALSE);
6a488035 215 while ($dao->fetch()) {
8da35492
CW
216 if (++$count > $max) {
217 $output['more'] = TRUE;
218 }
219 else {
220 $output['results'][] = array('id' => $dao->id, 'text' => $dao->data);
221 }
6a488035 222 }
8da35492 223 CRM_Utils_JSON::output($output);
6a488035
TO
224 }
225
00be9182 226 public static function relationship() {
3b1c37fe 227 $relType = CRM_Utils_Request::retrieve('rel_type', 'String', CRM_Core_DAO::$_nullObject, TRUE);
c91df8b4 228 $relContactID = CRM_Utils_Request::retrieve('rel_contact', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
a3d827a7
CW
229 $originalCid = CRM_Utils_Request::retrieve('cid', 'Positive');
230 $relationshipID = CRM_Utils_Request::retrieve('rel_id', 'Positive');
c91df8b4 231 $caseID = CRM_Utils_Request::retrieve('case_id', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
6a488035 232
3b1c37fe
CW
233 if (!CRM_Case_BAO_Case::accessCase($caseID)) {
234 CRM_Utils_System::permissionDenied();
235 }
6a488035 236
c91df8b4
CW
237 $ret = array('is_error' => 0);
238
3b1c37fe 239 list($relTypeId, $b, $a) = explode('_', $relType);
14a679f1 240
3b1c37fe
CW
241 if ($relationshipID && $originalCid) {
242 CRM_Case_BAO_Case::endCaseRole($caseID, $a, $originalCid, $relTypeId);
243 }
14a679f1 244
3b1c37fe 245 $clientList = CRM_Case_BAO_Case::getCaseClients($caseID);
14a679f1 246
3b1c37fe
CW
247 // Loop through multiple case clients
248 foreach ($clientList as $i => $sourceContactID) {
bb76ee5a
FG
249 try {
250 $result = civicrm_api3('relationship', 'create', array(
251 'case_id' => $caseID,
252 'relationship_type_id' => $relTypeId,
253 "contact_id_$a" => $relContactID,
254 "contact_id_$b" => $sourceContactID,
255 'start_date' => 'now',
256 ));
257 }
258 catch (CiviCRM_API3_Exception $e) {
259 $ret['is_error'] = 1;
260 $ret['error_message'] = $e->getMessage();
261 }
3b1c37fe
CW
262 // Save activity only for the primary (first) client
263 if ($i == 0 && empty($result['is_error'])) {
3e4eb9aa 264 CRM_Case_BAO_Case::createCaseRoleActivity($caseID, $result['id'], $relContactID, $sourceContactID);
c91df8b4 265 }
6a488035 266 }
3e4eb9aa
JP
267 if (!empty($_REQUEST['is_unit_test'])) {
268 return $ret;
269 }
6a488035 270
ecdef330 271 CRM_Utils_JSON::output($ret);
6a488035
TO
272 }
273
274 /**
fe482240 275 * Fetch the custom field help.
6a488035 276 */
00be9182 277 public static function customField() {
353ffa53
TO
278 $fieldId = CRM_Utils_Type::escape($_REQUEST['id'], 'Integer');
279 $params = array('id' => $fieldId);
6a488035 280 $returnProperties = array('help_pre', 'help_post');
353ffa53 281 $values = array();
6a488035
TO
282
283 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $values, $returnProperties);
ecdef330 284 CRM_Utils_JSON::output($values);
6a488035
TO
285 }
286
00be9182 287 public static function groupTree() {
d42a224c 288 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
6a488035
TO
289 $gids = CRM_Utils_Type::escape($_GET['gids'], 'String');
290 echo CRM_Contact_BAO_GroupNestingCache::json($gids);
291 CRM_Utils_System::civiExit();
292 }
293
6a488035 294 /**
fe482240 295 * Delete custom value.
6a488035 296 */
00be9182 297 public static function deleteCustomValue() {
d42a224c 298 CRM_Utils_System::setHttpHeader('Content-Type', 'text/plain');
6a488035
TO
299 $customValueID = CRM_Utils_Type::escape($_REQUEST['valueID'], 'Positive');
300 $customGroupID = CRM_Utils_Type::escape($_REQUEST['groupID'], 'Positive');
a3d827a7 301 $contactId = CRM_Utils_Request::retrieve('contactId', 'Positive');
6a488035 302 CRM_Core_BAO_CustomValue::deleteCustomValue($customValueID, $customGroupID);
a4cce21a 303 if ($contactId) {
7fa9167d 304 echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $customGroupID, $contactId);
6a488035
TO
305 }
306
2b68a50c 307 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
6a488035
TO
308 CRM_Utils_System::civiExit();
309 }
310
6a488035 311 /**
fe482240 312 * check the CMS username.
ce80b209 313 */
6a488035 314 static public function checkUserName() {
272081ca 315 $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('for', 'ts'));
a3d827a7
CW
316 $sig = CRM_Utils_Request::retrieve('sig', 'String');
317 $for = CRM_Utils_Request::retrieve('for', 'String');
272081ca
TO
318 if (
319 CRM_Utils_Time::getTimeRaw() > $_REQUEST['ts'] + self::CHECK_USERNAME_TTL
7fa9167d 320 || $for != 'civicrm/ajax/cmsuser'
321 || !$signer->validate($sig, $_REQUEST)
272081ca
TO
322 ) {
323 $user = array('name' => 'error');
8be1a839 324 CRM_Utils_JSON::output($user);
272081ca
TO
325 }
326
6a488035 327 $config = CRM_Core_Config::singleton();
4c68cf7b 328 $username = trim(CRM_Utils_Array::value('cms_name', $_REQUEST));
6a488035
TO
329
330 $params = array('name' => $username);
331
332 $errors = array();
333 $config->userSystem->checkUserNameEmailExists($params, $errors);
334
335 if (isset($errors['cms_name']) || isset($errors['name'])) {
b44e3f84 336 //user name is not available
6a488035 337 $user = array('name' => 'no');
8be1a839 338 CRM_Utils_JSON::output($user);
6a488035
TO
339 }
340 else {
341 //user name is available
342 $user = array('name' => 'yes');
8be1a839 343 CRM_Utils_JSON::output($user);
6a488035 344 }
8be1a839
TO
345
346 // Not reachable: JSON::output() above exits.
6a488035
TO
347 CRM_Utils_System::civiExit();
348 }
349
350 /**
fe482240 351 * Function to get email address of a contact.
6a488035 352 */
00be9182 353 public static function getContactEmail() {
a7488080 354 if (!empty($_REQUEST['contact_id'])) {
6a488035 355 $contactID = CRM_Utils_Type::escape($_REQUEST['contact_id'], 'Positive');
8c0ea1d7
TO
356 if (!CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::EDIT)) {
357 return;
358 }
6a488035
TO
359 list($displayName,
360 $userEmail
353ffa53 361 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
effdc2d9 362
d42a224c 363 CRM_Utils_System::setHttpHeader('Content-Type', 'text/plain');
6a488035
TO
364 if ($userEmail) {
365 echo $userEmail;
366 }
367 }
368 else {
369 $noemail = CRM_Utils_Array::value('noemail', $_GET);
370 $queryString = NULL;
a4cce21a
JM
371 $name = CRM_Utils_Array::value('name', $_GET);
372 if ($name) {
6a488035
TO
373 $name = CRM_Utils_Type::escape($name, 'String');
374 if ($noemail) {
375 $queryString = " cc.sort_name LIKE '%$name%'";
376 }
377 else {
378 $queryString = " ( cc.sort_name LIKE '%$name%' OR ce.email LIKE '%$name%' ) ";
379 }
380 }
a4cce21a 381 else {
d75f2f47
EM
382 $cid = CRM_Utils_Array::value('cid', $_GET);
383 if ($cid) {
b44e3f84 384 //check cid for integer
a4cce21a
JM
385 $contIDS = explode(',', $cid);
386 foreach ($contIDS as $contID) {
387 CRM_Utils_Type::escape($contID, 'Integer');
388 }
389 $queryString = " cc.id IN ( $cid )";
d75f2f47 390 }
6a488035
TO
391 }
392
393 if ($queryString) {
aa8ff347 394 $result = array();
6a488035 395 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
89595c92 396 $rowCount = Civi::settings()->get('search_autocomplete_count');
6a488035 397
bf00d1b6 398 $offset = CRM_Utils_Type::escape($offset, 'Int');
bf00d1b6 399
6a488035
TO
400 // add acl clause here
401 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
402 if ($aclWhere) {
403 $aclWhere = " AND $aclWhere";
404 }
405 if ($noemail) {
406 $query = "
407SELECT sort_name name, cc.id
408FROM civicrm_contact cc
409 {$aclFrom}
410WHERE cc.is_deceased = 0 AND {$queryString}
411 {$aclWhere}
412LIMIT {$offset}, {$rowCount}
413";
414
415 // send query to hook to be modified if needed
416 CRM_Utils_Hook::contactListQuery($query,
417 $name,
edc80cda 418 CRM_Utils_Request::retrieve('context', 'Alphanumeric'),
a3d827a7 419 CRM_Utils_Request::retrieve('cid', 'Positive')
6a488035
TO
420 );
421
422 $dao = CRM_Core_DAO::executeQuery($query);
423 while ($dao->fetch()) {
424 $result[] = array(
6a488035 425 'id' => $dao->id,
cac1236c 426 'text' => $dao->name,
6a488035
TO
427 );
428 }
429 }
430 else {
431 $query = "
432SELECT sort_name name, ce.email, cc.id
433FROM civicrm_email ce INNER JOIN civicrm_contact cc ON cc.id = ce.contact_id
434 {$aclFrom}
435WHERE ce.on_hold = 0 AND cc.is_deceased = 0 AND cc.do_not_email = 0 AND {$queryString}
436 {$aclWhere}
437LIMIT {$offset}, {$rowCount}
438";
439
440 // send query to hook to be modified if needed
441 CRM_Utils_Hook::contactListQuery($query,
442 $name,
edc80cda 443 CRM_Utils_Request::retrieve('context', 'Alphanumeric'),
a3d827a7 444 CRM_Utils_Request::retrieve('cid', 'Positive')
6a488035
TO
445 );
446
6a488035
TO
447 $dao = CRM_Core_DAO::executeQuery($query);
448
449 while ($dao->fetch()) {
ce80b209 450 //working here
6a488035 451 $result[] = array(
cac1236c 452 'text' => '"' . $dao->name . '" <' . $dao->email . '>',
6a488035
TO
453 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->email}" : '"' . $dao->name . '" <' . $dao->email . '>',
454 );
455 }
456 }
aa8ff347 457 CRM_Utils_JSON::output($result);
6a488035
TO
458 }
459 }
460 CRM_Utils_System::civiExit();
461 }
462
00be9182 463 public static function getContactPhone() {
6a488035
TO
464
465 $queryString = NULL;
3ae9c7d6 466 $sqlParmas = [];
6a488035
TO
467 //check for mobile type
468 $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
469 $mobileType = CRM_Utils_Array::value('Mobile', $phoneTypes);
470
3ae9c7d6 471 $name = CRM_Utils_Request::retrieveValue('name', 'String', NULL, FALSE, 'GET');
a4cce21a 472 if ($name) {
3ae9c7d6
SL
473 $key = (int) count(array_keys($sqlParmas)) + 1;
474 $queryString = " ( cc.sort_name LIKE %{$key} OR cp.phone LIKE %{$key} ) ";
475 $sqlParams[$key] = ['%' . $name . '%', 'String'];
6a488035 476 }
a4cce21a 477 else {
3ae9c7d6 478 $cid = CRM_Utils_Request::retrieveValue('cid', 'CommaSeparatedIntegers', NULL, FALSE, 'GET');
d75f2f47 479 if ($cid) {
a4cce21a 480 $queryString = " cc.id IN ( $cid )";
6a488035 481 }
6a488035
TO
482 }
483
484 if ($queryString) {
aa8ff347 485 $result = array();
3ae9c7d6
SL
486 $offset = (int) CRM_Utils_Request::retrieveValue('offset', 'Integer', 0, FALSE, 'GET');
487 $rowCount = (int) CRM_Utils_Request::retrieveValue('rowcount', 'Integer', 20, FALSE, 'GET');
bf00d1b6 488
6a488035
TO
489 // add acl clause here
490 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
491 if ($aclWhere) {
492 $aclWhere = " AND $aclWhere";
493 }
494
495 $query = "
496SELECT sort_name name, cp.phone, cc.id
497FROM civicrm_phone cp INNER JOIN civicrm_contact cc ON cc.id = cp.contact_id
498 {$aclFrom}
499WHERE cc.is_deceased = 0 AND cc.do_not_sms = 0 AND cp.phone_type_id = {$mobileType} AND {$queryString}
500 {$aclWhere}
501LIMIT {$offset}, {$rowCount}
502";
503
504 // send query to hook to be modified if needed
505 CRM_Utils_Hook::contactListQuery($query,
506 $name,
edc80cda 507 CRM_Utils_Request::retrieve('context', 'Alphanumeric'),
a3d827a7 508 CRM_Utils_Request::retrieve('cid', 'Positive')
6a488035
TO
509 );
510
3ae9c7d6 511 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
6a488035
TO
512
513 while ($dao->fetch()) {
514 $result[] = array(
b792e485 515 'text' => '"' . $dao->name . '" (' . $dao->phone . ')',
6a488035
TO
516 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->phone}" : '"' . $dao->name . '" <' . $dao->phone . '>',
517 );
518 }
8be1a839 519 CRM_Utils_JSON::output($result);
6a488035
TO
520 }
521 CRM_Utils_System::civiExit();
522 }
523
524
00be9182 525 public static function buildSubTypes() {
a3d827a7 526 $parent = CRM_Utils_Request::retrieve('parentId', 'Positive');
6a488035
TO
527
528 switch ($parent) {
529 case 1:
530 $contactType = 'Individual';
531 break;
532
533 case 2:
534 $contactType = 'Household';
535 break;
536
537 case 4:
538 $contactType = 'Organization';
539 break;
540 }
541
542 $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($contactType, FALSE, NULL);
543 asort($subTypes);
ecdef330 544 CRM_Utils_JSON::output($subTypes);
6a488035
TO
545 }
546
00be9182 547 public static function buildDedupeRules() {
a3d827a7 548 $parent = CRM_Utils_Request::retrieve('parentId', 'Positive');
6a488035
TO
549
550 switch ($parent) {
551 case 1:
552 $contactType = 'Individual';
553 break;
554
555 case 2:
556 $contactType = 'Household';
557 break;
558
559 case 4:
560 $contactType = 'Organization';
561 break;
562 }
563
564 $dedupeRules = CRM_Dedupe_BAO_RuleGroup::getByType($contactType);
565
ecdef330 566 CRM_Utils_JSON::output($dedupeRules);
6a488035
TO
567 }
568
569 /**
fe482240 570 * Function used for CiviCRM dashboard operations.
6a488035 571 */
00be9182 572 public static function dashboard() {
ce2cc43e 573 switch ($_REQUEST['op']) {
6a488035
TO
574 case 'save_columns':
575 CRM_Core_BAO_Dashboard::saveDashletChanges($_REQUEST['columns']);
ce2cc43e
CW
576 break;
577
6a488035
TO
578 case 'delete_dashlet':
579 $dashletID = CRM_Utils_Type::escape($_REQUEST['dashlet_id'], 'Positive');
580 CRM_Core_BAO_Dashboard::deleteDashlet($dashletID);
6a488035
TO
581 }
582
ce2cc43e 583 CRM_Utils_System::civiExit();
6a488035
TO
584 }
585
586 /**
fe482240 587 * Retrieve signature based on email id.
6a488035 588 */
00be9182 589 public static function getSignature() {
6a488035 590 $emailID = CRM_Utils_Type::escape($_REQUEST['emailID'], 'Positive');
353ffa53
TO
591 $query = "SELECT signature_text, signature_html FROM civicrm_email WHERE id = {$emailID}";
592 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
593
594 $signatures = array();
595 while ($dao->fetch()) {
596 $signatures = array(
597 'signature_text' => $dao->signature_text,
598 'signature_html' => $dao->signature_html,
599 );
600 }
601
ecdef330 602 CRM_Utils_JSON::output($signatures);
6a488035
TO
603 }
604
605 /**
100fef9d 606 * Process dupes.
6a488035 607 */
00be9182 608 public static function processDupes() {
6a488035 609 $oper = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
353ffa53
TO
610 $cid = CRM_Utils_Type::escape($_REQUEST['cid'], 'Positive');
611 $oid = CRM_Utils_Type::escape($_REQUEST['oid'], 'Positive');
6a488035
TO
612
613 if (!$oper || !$cid || !$oid) {
614 return;
615 }
616
617 $exception = new CRM_Dedupe_DAO_Exception();
618 $exception->contact_id1 = $cid;
619 $exception->contact_id2 = $oid;
620 //make sure contact2 > contact1.
621 if ($cid > $oid) {
622 $exception->contact_id1 = $oid;
623 $exception->contact_id2 = $cid;
624 }
625 $exception->find(TRUE);
626 $status = NULL;
627 if ($oper == 'dupe-nondupe') {
628 $status = $exception->save();
629 }
630 if ($oper == 'nondupe-dupe') {
631 $status = $exception->delete();
632 }
633
ecdef330 634 CRM_Utils_JSON::output(array('status' => ($status) ? $oper : $status));
6a488035
TO
635 }
636
183ec330 637 /**
638 * Retrieve list of duplicate pairs from cache table.
639 */
00be9182 640 public static function getDedupes() {
63ef778e 641 $offset = isset($_REQUEST['start']) ? CRM_Utils_Type::escape($_REQUEST['start'], 'Integer') : 0;
642 $rowCount = isset($_REQUEST['length']) ? CRM_Utils_Type::escape($_REQUEST['length'], 'Integer') : 25;
6a488035 643
dc6285d5 644 $gid = CRM_Utils_Request::retrieve('gid', 'Positive');
645 $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive');
9f54f049 646 $null = NULL;
647 $criteria = CRM_Utils_Request::retrieve('criteria', 'Json', $null, FALSE, '{}');
bb22928b 648 $selected = CRM_Utils_Request::retrieveValue('selected', 'Boolean');
63ef778e 649 if ($rowCount < 0) {
650 $rowCount = 0;
651 }
6a488035 652
1f51ef4e 653 $whereClause = $orderByClause = '';
9f54f049 654 $cacheKeyString = CRM_Dedupe_Merger::getMergeCacheKeyString($rgid, $gid, json_decode($criteria, TRUE));
655
63ef778e 656 $searchRows = array();
6a488035 657
ed92673b 658 $searchParams = self::getSearchOptionsFromRequest();
659 $queryParams = array();
660
63ef778e 661 $join = '';
662 $where = array();
579ea9bc 663
ed92673b 664 $isOrQuery = self::isOrQuery();
665
666 $nextParamKey = 3;
667 $mappings = array(
e67dcaf8 668 'dst' => 'cc1.display_name',
669 'src' => 'cc2.display_name',
670 'dst_email' => 'ce1.email',
671 'src_email' => 'ce2.email',
672 'dst_postcode' => 'ca1.postal_code',
673 'src_postcode' => 'ca2.postal_code',
674 'dst_street' => 'ca1.street',
675 'src_street' => 'ca2.street',
ed92673b 676 );
677
678 foreach ($mappings as $key => $dbName) {
679 if (!empty($searchParams[$key])) {
12af7add 680 // CRM-18694.
681 $wildcard = strstr($key, 'postcode') ? '' : '%';
682 $queryParams[$nextParamKey] = array($wildcard . $searchParams[$key] . '%', 'String');
ed92673b 683 $where[] = $dbName . " LIKE %{$nextParamKey} ";
684 $nextParamKey++;
685 }
63ef778e 686 }
ed92673b 687
688 if ($isOrQuery) {
f931b74c 689 $whereClause = ' ( ' . implode(' OR ', $where) . ' ) ';
63ef778e 690 }
691 else {
692 if (!empty($where)) {
693 $whereClause = implode(' AND ', $where);
694 }
f931b74c 695 }
63ef778e 696 $whereClause .= $whereClause ? ' AND de.id IS NULL' : ' de.id IS NULL';
6a488035 697
63ef778e 698 if ($selected) {
699 $whereClause .= ' AND pn.is_selected = 1';
700 }
2988f5c7 701 $join .= CRM_Dedupe_Merger::getJoinOnDedupeTable();
63ef778e 702
63ef778e 703 $select = array(
e67dcaf8 704 'cc1.contact_type' => 'dst_contact_type',
705 'cc1.display_name' => 'dst_display_name',
706 'cc1.contact_sub_type' => 'dst_contact_sub_type',
707 'cc2.contact_type' => 'src_contact_type',
708 'cc2.display_name' => 'src_display_name',
709 'cc2.contact_sub_type' => 'src_contact_sub_type',
710 'ce1.email' => 'dst_email',
711 'ce2.email' => 'src_email',
712 'ca1.postal_code' => 'dst_postcode',
713 'ca2.postal_code' => 'src_postcode',
714 'ca1.street_address' => 'dst_street',
715 'ca2.street_address' => 'src_street',
63ef778e 716 );
717
f931b74c 718 if ($select) {
63ef778e 719 $join .= " INNER JOIN civicrm_contact cc1 ON cc1.id = pn.entity_id1";
720 $join .= " INNER JOIN civicrm_contact cc2 ON cc2.id = pn.entity_id2";
721 $join .= " LEFT JOIN civicrm_email ce1 ON (ce1.contact_id = pn.entity_id1 AND ce1.is_primary = 1 )";
722 $join .= " LEFT JOIN civicrm_email ce2 ON (ce2.contact_id = pn.entity_id2 AND ce2.is_primary = 1 )";
723 $join .= " LEFT JOIN civicrm_address ca1 ON (ca1.contact_id = pn.entity_id1 AND ca1.is_primary = 1 )";
724 $join .= " LEFT JOIN civicrm_address ca2 ON (ca2.contact_id = pn.entity_id2 AND ca2.is_primary = 1 )";
725 }
ed92673b 726 $iTotal = CRM_Core_BAO_PrevNextCache::getCount($cacheKeyString, $join, $whereClause, '=', $queryParams);
1f51ef4e 727 if (!empty($_REQUEST['order'])) {
728 foreach ($_REQUEST['order'] as $orderInfo) {
729 if (!empty($orderInfo['column'])) {
730 $orderColumnNumber = $orderInfo['column'];
731 $dir = $orderInfo['dir'];
732 }
63ef778e 733 }
1f51ef4e 734 $columnDetails = CRM_Utils_Array::value($orderColumnNumber, $_REQUEST['columns']);
63ef778e 735 }
f931b74c 736 if (!empty($columnDetails)) {
63ef778e 737 switch ($columnDetails['data']) {
f931b74c 738 case 'src':
e67dcaf8 739 $orderByClause = " ORDER BY cc2.display_name {$dir}";
f931b74c 740 break;
741
742 case 'src_email':
e67dcaf8 743 $orderByClause = " ORDER BY ce2.email {$dir}";
f931b74c 744 break;
745
746 case 'src_street':
e67dcaf8 747 $orderByClause = " ORDER BY ca2.street_address {$dir}";
f931b74c 748 break;
749
750 case 'src_postcode':
e67dcaf8 751 $orderByClause = " ORDER BY ca2.postal_code {$dir}";
f931b74c 752 break;
753
754 case 'dst':
e67dcaf8 755 $orderByClause = " ORDER BY cc1.display_name {$dir}";
f931b74c 756 break;
757
758 case 'dst_email':
e67dcaf8 759 $orderByClause = " ORDER BY ce1.email {$dir}";
f931b74c 760 break;
761
762 case 'dst_street':
e67dcaf8 763 $orderByClause = " ORDER BY ca1.street_address {$dir}";
f931b74c 764 break;
765
766 case 'dst_postcode':
e67dcaf8 767 $orderByClause = " ORDER BY ca1.postal_code {$dir}";
f931b74c 768 break;
769
770 default:
063ffcb7 771 $orderByClause = " ORDER BY cc1.display_name ASC";
f931b74c 772 break;
63ef778e 773 }
774 }
6a488035 775
ed92673b 776 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $whereClause, $offset, $rowCount, $select, $orderByClause, TRUE, $queryParams);
63ef778e 777 $iFilteredTotal = CRM_Core_DAO::singleValueQuery("SELECT FOUND_ROWS()");
6a488035 778
63ef778e 779 $count = 0;
780 foreach ($dupePairs as $key => $pairInfo) {
e67dcaf8 781 $pair = $pairInfo['data'];
63ef778e 782 $srcContactSubType = CRM_Utils_Array::value('src_contact_sub_type', $pairInfo);
783 $dstContactSubType = CRM_Utils_Array::value('dst_contact_sub_type', $pairInfo);
784 $srcTypeImage = CRM_Contact_BAO_Contact_Utils::getImage($srcContactSubType ?
785 $srcContactSubType : $pairInfo['src_contact_type'],
786 FALSE,
e67dcaf8 787 $pairInfo['entity_id2']
63ef778e 788 );
789 $dstTypeImage = CRM_Contact_BAO_Contact_Utils::getImage($dstContactSubType ?
790 $dstContactSubType : $pairInfo['dst_contact_type'],
791 FALSE,
e67dcaf8 792 $pairInfo['entity_id1']
63ef778e 793 );
6a488035 794
63ef778e 795 $searchRows[$count]['is_selected'] = $pairInfo['is_selected'];
796 $searchRows[$count]['is_selected_input'] = "<input type='checkbox' class='crm-dedupe-select' name='pnid_{$pairInfo['prevnext_id']}' value='{$pairInfo['is_selected']}' onclick='toggleDedupeSelect(this)'>";
797 $searchRows[$count]['src_image'] = $srcTypeImage;
e67dcaf8 798 $searchRows[$count]['src'] = CRM_Utils_System::href($pair['srcName'], 'civicrm/contact/view', "reset=1&cid={$pairInfo['entity_id2']}");
63ef778e 799 $searchRows[$count]['src_email'] = CRM_Utils_Array::value('src_email', $pairInfo);
800 $searchRows[$count]['src_street'] = CRM_Utils_Array::value('src_street', $pairInfo);
801 $searchRows[$count]['src_postcode'] = CRM_Utils_Array::value('src_postcode', $pairInfo);
802 $searchRows[$count]['dst_image'] = $dstTypeImage;
e67dcaf8 803 $searchRows[$count]['dst'] = CRM_Utils_System::href($pair['dstName'], 'civicrm/contact/view', "reset=1&cid={$pairInfo['entity_id1']}");
63ef778e 804 $searchRows[$count]['dst_email'] = CRM_Utils_Array::value('dst_email', $pairInfo);
805 $searchRows[$count]['dst_street'] = CRM_Utils_Array::value('dst_street', $pairInfo);
806 $searchRows[$count]['dst_postcode'] = CRM_Utils_Array::value('dst_postcode', $pairInfo);
da3afd4a 807 $searchRows[$count]['conflicts'] = str_replace("',", "',<br/>", CRM_Utils_Array::value('conflicts', $pair));
63ef778e 808 $searchRows[$count]['weight'] = CRM_Utils_Array::value('weight', $pair);
809
fd630ef9 810 if (!empty($pairInfo['data']['canMerge'])) {
c0cc2ad4 811 $mergeParams = [
812 'reset' => 1,
813 'cid' => $pairInfo['entity_id1'],
814 'oid' => $pairInfo['entity_id2'],
815 'action' => 'update',
816 'rgid' => $rgid,
9f54f049 817 'criteria' => $criteria,
c0cc2ad4 818 'limit' => CRM_Utils_Request::retrieve('limit', 'Integer'),
819 ];
6a488035 820 if ($gid) {
c0cc2ad4 821 $mergeParams['gid'] = $gid;
6a488035
TO
822 }
823
fd630ef9 824 $searchRows[$count]['actions'] = "<a class='crm-dedupe-flip' href='#' data-pnid={$pairInfo['prevnext_id']}>" . ts('flip') . "</a>&nbsp;|&nbsp;";
da3afd4a 825 $searchRows[$count]['actions'] .= CRM_Utils_System::href(ts('merge'), 'civicrm/contact/merge', $mergeParams);
fd630ef9 826 $searchRows[$count]['actions'] .= "&nbsp;|&nbsp;<a id='notDuplicate' href='#' onClick=\"processDupes( {$pairInfo['entity_id1']}, {$pairInfo['entity_id2']}, 'dupe-nondupe', 'dupe-listing'); return false;\">" . ts('not a duplicate') . "</a>";
6a488035
TO
827 }
828 else {
63ef778e 829 $searchRows[$count]['actions'] = '<em>' . ts('Insufficient access rights - cannot merge') . '</em>';
6a488035 830 }
63ef778e 831 $count++;
6a488035
TO
832 }
833
22b232f3 834 $dupePairs = array(
835 'data' => $searchRows,
836 'recordsTotal' => $iTotal,
837 'recordsFiltered' => $iFilteredTotal,
838 );
1f51ef4e 839 if (!empty($_REQUEST['is_unit_test'])) {
840 return $dupePairs;
841 }
22b232f3 842 CRM_Utils_JSON::output($dupePairs);
6a488035
TO
843 }
844
ed92673b 845 /**
846 * Get the searchable options from the request.
847 *
848 * @return array
849 */
850 public static function getSearchOptionsFromRequest() {
851 $searchParams = array();
852 $searchData = CRM_Utils_Array::value('search', $_REQUEST);
853 $searchData['value'] = CRM_Utils_Type::escape($searchData['value'], 'String');
854 $selectorElements = array(
855 'is_selected',
856 'is_selected_input',
857 'src_image',
858 'src',
859 'src_email',
860 'src_street',
861 'src_postcode',
862 'dst_image',
863 'dst',
864 'dst_email',
865 'dst_street',
866 'dst_postcode',
867 'conflicts',
868 'weight',
869 'actions',
870 );
871 $columns = $_REQUEST['columns'];
872
873 foreach ($columns as $column) {
874 if (!empty($column['search']['value']) && in_array($column['data'], $selectorElements)) {
875 $searchParams[$column['data']] = CRM_Utils_Type::escape($column['search']['value'], 'String');
876 }
877 elseif (!empty($searchData['value'])) {
878 $searchParams[$column['data']] = $searchData['value'];
879 }
880 }
881 return $searchParams;
882 }
883
884 /**
885 * Is the query an OR query.
886 *
887 * If a generic search value is passed in - ie. $_REQUEST['search']['value'] = 'abc'
888 * then all fields are searched for this.
889 *
890 * It is unclear if there is any code that still passes this in or whether is is just legacy. It
891 * could cause a server-killing query on a large site so it probably is NOT in use if we haven't
892 * had complaints.
893 *
894 * @return bool
895 */
896 public static function isOrQuery() {
897 $searchData = CRM_Utils_Array::value('search', $_REQUEST);
898 return !empty($searchData['value']);
899 }
900
6a488035 901 /**
fe482240 902 * Retrieve a PDF Page Format for the PDF Letter form.
6a488035 903 */
00be9182 904 public function pdfFormat() {
6a488035
TO
905 $formatId = CRM_Utils_Type::escape($_REQUEST['formatId'], 'Integer');
906
907 $pdfFormat = CRM_Core_BAO_PdfFormat::getById($formatId);
908
ecdef330 909 CRM_Utils_JSON::output($pdfFormat);
6a488035
TO
910 }
911
912 /**
fe482240 913 * Retrieve Paper Size dimensions.
6a488035 914 */
00be9182 915 public static function paperSize() {
6a488035
TO
916 $paperSizeName = CRM_Utils_Type::escape($_REQUEST['paperSizeName'], 'String');
917
918 $paperSize = CRM_Core_BAO_PaperSize::getByName($paperSizeName);
919
ecdef330 920 CRM_Utils_JSON::output($paperSize);
6a488035
TO
921 }
922
183ec330 923 /**
924 * Swap contacts in a dupe pair i.e main with duplicate contact.
ea3ddccf 925 *
926 * @param int $prevNextId
183ec330 927 */
f931b74c 928 public static function flipDupePairs($prevNextId = NULL) {
fd630ef9 929 if (!$prevNextId) {
808c05a9 930 // @todo figure out if this is always POST & specify that rather than inexact GET
931 $prevNextId = CRM_Utils_Request::retrieve('pnid', 'Integer');
fd630ef9 932 }
808c05a9 933
934 $onlySelected = FALSE;
fd630ef9 935 if (is_array($prevNextId) && !CRM_Utils_Array::crmIsEmptyArray($prevNextId)) {
808c05a9 936 $onlySelected = TRUE;
fd630ef9 937 }
808c05a9 938 $prevNextId = CRM_Utils_Type::escapeAll((array) $prevNextId, 'Positive');
939 CRM_Core_BAO_PrevNextCache::flipPair($prevNextId, $onlySelected);
558cd7c7 940 CRM_Utils_System::civiExit();
fd630ef9 941 }
942
aeb97cc1
CW
943 /**
944 * Used to store selected contacts across multiple pages in advanced search.
945 */
00be9182 946 public static function selectUnselectContacts() {
353ffa53
TO
947 $name = CRM_Utils_Array::value('name', $_REQUEST);
948 $cacheKey = CRM_Utils_Array::value('qfKey', $_REQUEST);
949 $state = CRM_Utils_Array::value('state', $_REQUEST, 'checked');
6a488035
TO
950 $variableType = CRM_Utils_Array::value('variableType', $_REQUEST, 'single');
951
952 $actionToPerform = CRM_Utils_Array::value('action', $_REQUEST, 'select');
953
954 if ($variableType == 'multiple') {
955 // action post value only works with multiple type variable
956 if ($name) {
957 //multiple names like mark_x_1-mark_x_2 where 1,2 are cids
958 $elements = explode('-', $name);
959 foreach ($elements as $key => $element) {
960 $elements[$key] = self::_convertToId($element);
961 }
91209206 962 CRM_Utils_Type::escapeAll($elements, 'Integer');
0b8038a6 963 Civi::service('prevnext')->markSelection($cacheKey, $actionToPerform, $elements);
6a488035
TO
964 }
965 else {
0b8038a6 966 Civi::service('prevnext')->markSelection($cacheKey, $actionToPerform);
6a488035
TO
967 }
968 }
969 elseif ($variableType == 'single') {
970 $cId = self::_convertToId($name);
91209206 971 CRM_Utils_Type::escape($cId, 'Integer');
6a488035 972 $action = ($state == 'checked') ? 'select' : 'unselect';
0b8038a6 973 Civi::service('prevnext')->markSelection($cacheKey, $action, $cId);
6a488035 974 }
b7994703 975 $contactIds = Civi::service('prevnext')->getSelection($cacheKey);
6a488035
TO
976 $countSelectionCids = count($contactIds[$cacheKey]);
977
978 $arrRet = array('getCount' => $countSelectionCids);
ecdef330 979 CRM_Utils_JSON::output($arrRet);
6a488035
TO
980 }
981
4319322b 982 /**
100fef9d 983 * @param string $name
4319322b
EM
984 *
985 * @return string
986 */
00be9182 987 public static function _convertToId($name) {
6a488035
TO
988 if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
989 $cId = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
990 }
991 return $cId;
992 }
993
00be9182 994 public static function getAddressDisplay() {
a3d827a7 995 $contactId = CRM_Utils_Request::retrieve('contact_id', 'Positive');
6a488035
TO
996 if (!$contactId) {
997 $addressVal["error_message"] = "no contact id found";
998 }
999 else {
408b79bf 1000 $entityBlock = array(
1001 'contact_id' => $contactId,
1002 'entity_id' => $contactId,
1003 );
6a488035
TO
1004 $addressVal = CRM_Core_BAO_Address::getValues($entityBlock);
1005 }
1006
ecdef330 1007 CRM_Utils_JSON::output($addressVal);
6a488035 1008 }
40458f6c 1009
183ec330 1010 /**
1011 * Mark dupe pairs as selected from un-selected state or vice-versa, in dupe cache table.
1012 */
f931b74c 1013 public static function toggleDedupeSelect() {
63ef778e 1014 $pnid = $_REQUEST['pnid'];
1015 $isSelected = CRM_Utils_Type::escape($_REQUEST['is_selected'], 'Boolean');
9d2f6d53 1016 $cacheKeyString = CRM_Utils_Request::retrieve('cacheKey', 'Alphanumeric', $null, FALSE);
63ef778e 1017
1018 $params = array(
1019 1 => array($isSelected, 'Boolean'),
f931b74c 1020 3 => array("$cacheKeyString%", 'String'), // using % to address rows with conflicts as well
63ef778e 1021 );
1022
1023 //check pnid is_array or integer
1024 $whereClause = NULL;
1025 if (is_array($pnid) && !CRM_Utils_Array::crmIsEmptyArray($pnid)) {
13c42e60 1026 CRM_Utils_Type::escapeAll($pnid, 'Positive');
63ef778e 1027 $pnid = implode(', ', $pnid);
63ef778e 1028 $whereClause = " id IN ( {$pnid} ) ";
1029 }
1030 else {
1031 $pnid = CRM_Utils_Type::escape($pnid, 'Integer');
1032 $whereClause = " id = %2";
1033 $params[2] = array($pnid, 'Integer');
1034 }
1035
1036 $sql = "UPDATE civicrm_prevnext_cache SET is_selected = %1 WHERE {$whereClause} AND cacheKey LIKE %3";
1037 CRM_Core_DAO::executeQuery($sql, $params);
1038
1039 CRM_Utils_System::civiExit();
1040 }
1041
40458f6c 1042 /**
fe482240 1043 * Retrieve contact relationships.
40458f6c 1044 */
1045 public static function getContactRelationships() {
1046 $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
edc80cda 1047 $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric');
7d12de7f 1048 $relationship_type_id = CRM_Utils_Type::escape(CRM_Utils_Array::value('relationship_type_id', $_GET), 'Integer', FALSE);
40458f6c 1049
b0266403
CW
1050 if (!CRM_Contact_BAO_Contact_Permission::allow($contactID)) {
1051 return CRM_Utils_System::permissionDenied();
1052 }
1053
00f11506 1054 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
40458f6c 1055
1056 $params['contact_id'] = $contactID;
1057 $params['context'] = $context;
4c5f31d0 1058 if ($relationship_type_id) {
cdee9432
TM
1059 $params['relationship_type_id'] = $relationship_type_id;
1060 }
40458f6c 1061
1062 // get the contact relationships
1063 $relationships = CRM_Contact_BAO_Relationship::getContactRelationshipSelector($params);
1064
7d12de7f 1065 CRM_Utils_JSON::output($relationships);
40458f6c 1066 }
96025800 1067
6a488035 1068}