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