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