3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class contains all contact related functions that are called using AJAX (jQuery)
21 class CRM_Contact_Page_AJAX
{
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).
28 const CHECK_USERNAME_TTL
= 10800;
31 const AUTOCOMPLETE_TTL
= 21600;
34 * Ajax callback for custom fields of type ContactReference
36 * Todo: Migrate contact reference fields to use EntityRef
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');
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'];
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);
52 if (!empty($cf['filter'])) {
54 parse_str($cf['filter'], $filterParams);
56 $action = $filterParams['action'] ??
NULL;
57 if (!empty($action) && !in_array($action, ['get', 'lookup'])) {
58 CRM_Utils_System
::civiExit(1);
61 if (!empty($filterParams['group'])) {
62 $filterParams['group'] = explode(',', $filterParams['group']);
66 $list = array_keys(CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
67 'contact_reference_options'
70 $return = array_unique(array_merge(['sort_name'], $list));
72 $limit = Civi
::settings()->get('search_autocomplete_count');
74 $params = ['offset' => 0, 'rowCount' => $limit, 'version' => 3];
75 foreach ($return as $fld) {
76 $params["return.{$fld}"] = 1;
79 if (!empty($action)) {
95 foreach ($_GET as $param => $val) {
97 in_array($param, $excludeGet) ||
98 strpos($param, 'return.') !== FALSE ||
99 strpos($param, 'api.') !== FALSE
103 $params[$param] = $val;
108 $params['sort_name'] = $name;
111 $params['sort'] = 'sort_name';
113 // tell api to skip permission chk. dgg
114 $params['check_permissions'] = 0;
116 // add filter variable to params
117 if (!empty($filterParams)) {
118 $params = array_merge($params, $filterParams);
121 $contact = civicrm_api('Contact', 'Get', $params);
123 if (!empty($contact['is_error'])) {
124 CRM_Utils_System
::civiExit(1);
128 foreach ($contact['values'] as $value) {
130 foreach ($return as $fld) {
131 if (!empty($value[$fld])) {
132 $view[] = $value[$fld];
135 $contactList[] = ['id' => $value['id'], 'text' => implode(' :: ', $view)];
138 if (!empty($_GET['is_unit_test'])) {
141 CRM_Utils_JSON
::output($contactList);
145 * Fetch PCP ID by PCP Supporter sort_name, also displays PCP title and associated Contribution Page title
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');
152 $where = ' AND pcp.page_id = cp.id AND pcp.contact_id = cc.id';
154 $config = CRM_Core_Config
::singleton();
155 if ($config->includeWildCardInName
) {
156 $strSearch = "%$name%";
159 $strSearch = "$name%";
161 $includeEmailFrom = $includeNickName = '';
162 if ($config->includeNickNameInName
) {
163 $includeNickName = " OR nick_name LIKE '$strSearch'";
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} ";
170 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
173 $offset = $count = 0;
174 if (!empty($_GET['page_num'])) {
175 $page = (int) $_GET['page_num'];
176 $offset = $limit * ($page - 1);
180 $select = 'cc.sort_name, pcp.title, cp.title';
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
187 {$whereClause} AND pcp.page_type = 'contribute'
189 SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
190 FROM civicrm_pcp pcp, civicrm_event cp, civicrm_contact cc
192 {$whereClause} AND pcp.page_type = 'event'
195 LIMIT $offset, $limit
198 $dao = CRM_Core_DAO
::executeQuery($query);
199 $output = ['results' => [], 'more' => FALSE];
200 while ($dao->fetch()) {
201 if (++
$count > $max) {
202 $output['more'] = TRUE;
205 $output['results'][] = ['id' => $dao->id
, 'text' => $dao->data
];
208 CRM_Utils_JSON
::output($output);
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);
218 if (!CRM_Case_BAO_Case
::accessCase($caseID)) {
219 CRM_Utils_System
::permissionDenied();
222 $ret = ['is_error' => 0];
224 list($relTypeId, $b, $a) = explode('_', $relType);
226 if ($relationshipID && $originalCid) {
227 CRM_Case_BAO_Case
::endCaseRole($caseID, $a, $originalCid, $relTypeId);
230 $clientList = CRM_Case_BAO_Case
::getCaseClients($caseID);
232 // Loop through multiple case clients
233 foreach ($clientList as $i => $sourceContactID) {
236 'case_id' => $caseID,
237 'relationship_type_id' => $relTypeId,
238 "contact_id_$a" => $relContactID,
239 "contact_id_$b" => $sourceContactID,
240 'sequential' => TRUE,
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',
250 $result = civicrm_api3('relationship', 'create', $params);
252 catch (CiviCRM_API3_Exception
$e) {
253 $ret['is_error'] = 1;
254 $ret['error_message'] = $e->getMessage();
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);
261 if (!empty($_REQUEST['is_unit_test'])) {
265 CRM_Utils_JSON
::output($ret);
269 * Fetch the custom field help.
271 public static function customField() {
272 $fieldId = CRM_Utils_Type
::escape($_REQUEST['id'], 'Integer');
273 $params = ['id' => $fieldId];
274 $returnProperties = ['help_pre', 'help_post'];
277 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $values, $returnProperties);
278 CRM_Utils_JSON
::output($values);
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();
289 * Delete custom value.
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 CRM_Core_BAO_CustomValue
::deleteCustomValue($customValueID, $customGroupID);
298 echo CRM_Contact_BAO_Contact
::getCountComponent('custom_' . $customGroupID, $contactId);
301 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
302 CRM_Utils_System
::civiExit();
306 * check the CMS username.
308 public static function checkUserName() {
309 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), ['for', 'ts']);
310 $sig = CRM_Utils_Request
::retrieve('sig', 'String');
311 $for = CRM_Utils_Request
::retrieve('for', 'String');
313 CRM_Utils_Time
::getTimeRaw() > $_REQUEST['ts'] + self
::CHECK_USERNAME_TTL
314 ||
$for != 'civicrm/ajax/cmsuser'
315 ||
!$signer->validate($sig, $_REQUEST)
317 $user = ['name' => 'error'];
318 CRM_Utils_JSON
::output($user);
321 $config = CRM_Core_Config
::singleton();
322 $username = trim(CRM_Utils_Array
::value('cms_name', $_REQUEST));
324 $params = ['name' => $username];
327 $config->userSystem
->checkUserNameEmailExists($params, $errors);
329 if (isset($errors['cms_name']) ||
isset($errors['name'])) {
330 //user name is not available
331 $user = ['name' => 'no'];
332 CRM_Utils_JSON
::output($user);
335 //user name is available
336 $user = ['name' => 'yes'];
337 CRM_Utils_JSON
::output($user);
340 // Not reachable: JSON::output() above exits.
341 CRM_Utils_System
::civiExit();
345 * Function to get email address of a contact.
347 public static function getContactEmail() {
349 $name = $_GET['name'] ??
NULL;
351 $name = CRM_Utils_Type
::escape($name, 'String');
352 $wildCard = Civi
::settings()->get('includeWildCardInName') ?
'%' : '';
353 foreach (['cc.sort_name', 'ce.email'] as $column) {
354 $queryStrings[] = "{$column} LIKE '{$wildCard}{$name}%'";
357 $rowCount = Civi
::settings()->get('search_autocomplete_count');
359 // add acl clause here
360 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
362 $aclWhere = "AND {$aclWhere}";
364 foreach ($queryStrings as &$queryString) {
366 SELECT sort_name name, ce.email, cc.id
367 FROM civicrm_email ce INNER JOIN civicrm_contact cc ON cc.id = ce.contact_id
369 WHERE ce.on_hold = 0 AND cc.is_deceased = 0 AND cc.do_not_email = 0 AND {$queryString}
374 $query = implode(' UNION ', $queryStrings) . " LIMIT {$rowCount}";
376 // send query to hook to be modified if needed
377 CRM_Utils_Hook
::contactListQuery($query,
379 CRM_Utils_Request
::retrieve('context', 'Alphanumeric'),
380 CRM_Utils_Request
::retrieve('cid', 'Positive')
383 $dao = CRM_Core_DAO
::executeQuery($query);
385 while ($dao->fetch()) {
388 'text' => '"' . $dao->name
. '" <' . $dao->email
. '>',
389 'id' => (CRM_Utils_Array
::value('id', $_GET)) ?
"{$dao->id}::{$dao->email}" : '"' . $dao->name
. '" <' . $dao->email
. '>',
392 CRM_Utils_JSON
::output($result);
394 CRM_Utils_System
::civiExit();
397 public static function getContactPhone() {
401 //check for mobile type
402 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
403 $mobileType = $phoneTypes['Mobile'] ??
NULL;
405 $name = CRM_Utils_Request
::retrieveValue('name', 'String', NULL, FALSE, 'GET');
407 $key = (int) count(array_keys($sqlParmas)) +
1;
408 $queryString = " ( cc.sort_name LIKE %{$key} OR cp.phone LIKE %{$key} ) ";
409 $sqlParams[$key] = ['%' . $name . '%', 'String'];
412 $cid = CRM_Utils_Request
::retrieveValue('cid', 'CommaSeparatedIntegers', NULL, FALSE, 'GET');
414 $queryString = " cc.id IN ( $cid )";
420 $offset = (int) CRM_Utils_Request
::retrieveValue('offset', 'Integer', 0, FALSE, 'GET');
421 $rowCount = (int) CRM_Utils_Request
::retrieveValue('rowcount', 'Integer', 20, FALSE, 'GET');
423 // add acl clause here
424 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
426 $aclWhere = " AND $aclWhere";
430 SELECT sort_name name, cp.phone, cc.id
431 FROM civicrm_phone cp INNER JOIN civicrm_contact cc ON cc.id = cp.contact_id
433 WHERE cc.is_deceased = 0 AND cc.do_not_sms = 0 AND cp.phone_type_id = {$mobileType} AND {$queryString}
435 LIMIT {$offset}, {$rowCount}
438 // send query to hook to be modified if needed
439 CRM_Utils_Hook
::contactListQuery($query,
441 CRM_Utils_Request
::retrieve('context', 'Alphanumeric'),
442 CRM_Utils_Request
::retrieve('cid', 'Positive')
445 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
447 while ($dao->fetch()) {
449 'text' => '"' . $dao->name
. '" (' . $dao->phone
. ')',
450 'id' => (CRM_Utils_Array
::value('id', $_GET)) ?
"{$dao->id}::{$dao->phone}" : '"' . $dao->name
. '" <' . $dao->phone
. '>',
453 CRM_Utils_JSON
::output($result);
455 CRM_Utils_System
::civiExit();
458 public static function buildSubTypes() {
459 $parent = CRM_Utils_Request
::retrieve('parentId', 'Positive');
463 $contactType = 'Individual';
467 $contactType = 'Household';
471 $contactType = 'Organization';
475 $subTypes = CRM_Contact_BAO_ContactType
::subTypePairs($contactType, FALSE, NULL);
477 CRM_Utils_JSON
::output($subTypes);
480 public static function buildDedupeRules() {
481 $parent = CRM_Utils_Request
::retrieve('parentId', 'Positive');
485 $contactType = 'Individual';
489 $contactType = 'Household';
493 $contactType = 'Organization';
497 $dedupeRules = CRM_Dedupe_BAO_RuleGroup
::getByType($contactType);
499 CRM_Utils_JSON
::output($dedupeRules);
503 * Retrieve signature based on email id.
505 public static function getSignature() {
506 $emailID = CRM_Utils_Type
::escape($_REQUEST['emailID'], 'Positive');
507 $query = "SELECT signature_text, signature_html FROM civicrm_email WHERE id = {$emailID}";
508 $dao = CRM_Core_DAO
::executeQuery($query);
511 while ($dao->fetch()) {
513 'signature_text' => $dao->signature_text
,
514 'signature_html' => $dao->signature_html
,
518 CRM_Utils_JSON
::output($signatures);
524 public static function processDupes() {
525 $oper = CRM_Utils_Type
::escape($_REQUEST['op'], 'String');
526 $cid = CRM_Utils_Type
::escape($_REQUEST['cid'], 'Positive');
527 $oid = CRM_Utils_Type
::escape($_REQUEST['oid'], 'Positive');
529 if (!$oper ||
!$cid ||
!$oid) {
533 $status = self
::markNonDuplicates($cid, $oid, $oper);
535 CRM_Utils_JSON
::output(['status' => ($status) ?
$oper : $status]);
539 * Retrieve list of duplicate pairs from cache table.
541 public static function getDedupes() {
542 $offset = isset($_REQUEST['start']) ? CRM_Utils_Type
::escape($_REQUEST['start'], 'Integer') : 0;
543 $rowCount = isset($_REQUEST['length']) ? CRM_Utils_Type
::escape($_REQUEST['length'], 'Integer') : 25;
545 $gid = CRM_Utils_Request
::retrieve('gid', 'Positive');
546 $rgid = CRM_Utils_Request
::retrieve('rgid', 'Positive');
547 $limit = CRM_Utils_Request
::retrieveValue('limit', 'Positive', 0);
549 $criteria = CRM_Utils_Request
::retrieve('criteria', 'Json', $null, FALSE, '{}');
550 $selected = CRM_Utils_Request
::retrieveValue('selected', 'Boolean');
555 $whereClause = $orderByClause = '';
556 $cacheKeyString = CRM_Dedupe_Merger
::getMergeCacheKeyString($rgid, $gid, json_decode($criteria, TRUE), TRUE, $limit);
560 $searchParams = self
::getSearchOptionsFromRequest();
566 $isOrQuery = self
::isOrQuery();
570 'dst' => 'cc1.display_name',
571 'src' => 'cc2.display_name',
572 'dst_email' => 'ce1.email',
573 'src_email' => 'ce2.email',
574 'dst_postcode' => 'ca1.postal_code',
575 'src_postcode' => 'ca2.postal_code',
576 'dst_street' => 'ca1.street',
577 'src_street' => 'ca2.street',
580 foreach ($mappings as $key => $dbName) {
581 if (!empty($searchParams[$key])) {
583 $wildcard = strstr($key, 'postcode') ?
'' : '%';
584 $queryParams[$nextParamKey] = [$wildcard . $searchParams[$key] . '%', 'String'];
585 $where[] = $dbName . " LIKE %{$nextParamKey} ";
591 $whereClause = ' ( ' . implode(' OR ', $where) . ' ) ';
594 if (!empty($where)) {
595 $whereClause = implode(' AND ', $where);
598 $whereClause .= $whereClause ?
' AND de.id IS NULL' : ' de.id IS NULL';
601 $whereClause .= ' AND pn.is_selected = 1';
603 $join .= CRM_Dedupe_Merger
::getJoinOnDedupeTable();
606 'cc1.contact_type' => 'dst_contact_type',
607 'cc1.display_name' => 'dst_display_name',
608 'cc1.contact_sub_type' => 'dst_contact_sub_type',
609 'cc2.contact_type' => 'src_contact_type',
610 'cc2.display_name' => 'src_display_name',
611 'cc2.contact_sub_type' => 'src_contact_sub_type',
612 'ce1.email' => 'dst_email',
613 'ce2.email' => 'src_email',
614 'ca1.postal_code' => 'dst_postcode',
615 'ca2.postal_code' => 'src_postcode',
616 'ca1.street_address' => 'dst_street',
617 'ca2.street_address' => 'src_street',
621 $join .= " INNER JOIN civicrm_contact cc1 ON cc1.id = pn.entity_id1";
622 $join .= " INNER JOIN civicrm_contact cc2 ON cc2.id = pn.entity_id2";
623 $join .= " LEFT JOIN civicrm_email ce1 ON (ce1.contact_id = pn.entity_id1 AND ce1.is_primary = 1 )";
624 $join .= " LEFT JOIN civicrm_email ce2 ON (ce2.contact_id = pn.entity_id2 AND ce2.is_primary = 1 )";
625 $join .= " LEFT JOIN civicrm_address ca1 ON (ca1.contact_id = pn.entity_id1 AND ca1.is_primary = 1 )";
626 $join .= " LEFT JOIN civicrm_address ca2 ON (ca2.contact_id = pn.entity_id2 AND ca2.is_primary = 1 )";
628 $iTotal = CRM_Core_BAO_PrevNextCache
::getCount($cacheKeyString, $join, $whereClause, '=', $queryParams);
629 if (!empty($_REQUEST['order'])) {
630 foreach ($_REQUEST['order'] as $orderInfo) {
631 if (!empty($orderInfo['column'])) {
632 $orderColumnNumber = $orderInfo['column'];
633 $dir = CRM_Utils_Type
::escape($orderInfo['dir'], 'MysqlOrderByDirection', FALSE);
636 $columnDetails = $_REQUEST['columns'][$orderColumnNumber] ??
NULL;
638 if (!empty($columnDetails)) {
639 switch ($columnDetails['data']) {
641 $orderByClause = " ORDER BY cc2.display_name {$dir}";
645 $orderByClause = " ORDER BY ce2.email {$dir}";
649 $orderByClause = " ORDER BY ca2.street_address {$dir}";
653 $orderByClause = " ORDER BY ca2.postal_code {$dir}";
657 $orderByClause = " ORDER BY cc1.display_name {$dir}";
661 $orderByClause = " ORDER BY ce1.email {$dir}";
665 $orderByClause = " ORDER BY ca1.street_address {$dir}";
669 $orderByClause = " ORDER BY ca1.postal_code {$dir}";
673 $orderByClause = " ORDER BY cc1.display_name ASC";
678 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $whereClause, $offset, $rowCount, $select, $orderByClause, TRUE, $queryParams);
679 $iFilteredTotal = CRM_Core_DAO
::singleValueQuery("SELECT FOUND_ROWS()");
682 foreach ($dupePairs as $key => $pairInfo) {
683 $pair = $pairInfo['data'];
684 $srcContactSubType = $pairInfo['src_contact_sub_type'] ??
NULL;
685 $dstContactSubType = $pairInfo['dst_contact_sub_type'] ??
NULL;
686 $srcTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage($srcContactSubType ?
687 $srcContactSubType : $pairInfo['src_contact_type'],
689 $pairInfo['entity_id2']
691 $dstTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage($dstContactSubType ?
692 $dstContactSubType : $pairInfo['dst_contact_type'],
694 $pairInfo['entity_id1']
697 $searchRows[$count]['is_selected'] = $pairInfo['is_selected'];
698 $searchRows[$count]['is_selected_input'] = "<input type='checkbox' class='crm-dedupe-select' name='pnid_{$pairInfo['prevnext_id']}' value='{$pairInfo['is_selected']}' onclick='toggleDedupeSelect(this)'>";
699 $searchRows[$count]['src_image'] = $srcTypeImage;
700 $searchRows[$count]['src'] = CRM_Utils_System
::href($pair['srcName'], 'civicrm/contact/view', "reset=1&cid={$pairInfo['entity_id2']}");
701 $searchRows[$count]['src_email'] = $pairInfo['src_email'] ??
NULL;
702 $searchRows[$count]['src_street'] = $pairInfo['src_street'] ??
NULL;
703 $searchRows[$count]['src_postcode'] = $pairInfo['src_postcode'] ??
NULL;
704 $searchRows[$count]['dst_image'] = $dstTypeImage;
705 $searchRows[$count]['dst'] = CRM_Utils_System
::href($pair['dstName'], 'civicrm/contact/view', "reset=1&cid={$pairInfo['entity_id1']}");
706 $searchRows[$count]['dst_email'] = $pairInfo['dst_email'] ??
NULL;
707 $searchRows[$count]['dst_street'] = $pairInfo['dst_street'] ??
NULL;
708 $searchRows[$count]['dst_postcode'] = $pairInfo['dst_postcode'] ??
NULL;
709 $searchRows[$count]['conflicts'] = str_replace("',", "',<br/>", CRM_Utils_Array
::value('conflicts', $pair));
710 $searchRows[$count]['weight'] = $pair['weight'] ??
NULL;
712 if (!empty($pairInfo['data']['canMerge'])) {
715 'cid' => $pairInfo['entity_id1'],
716 'oid' => $pairInfo['entity_id2'],
717 'action' => 'update',
719 'criteria' => $criteria,
720 'limit' => CRM_Utils_Request
::retrieve('limit', 'Integer'),
723 $mergeParams['gid'] = $gid;
726 $searchRows[$count]['actions'] = "<a class='crm-dedupe-flip' href='#' data-pnid={$pairInfo['prevnext_id']}>" . ts('flip') . "</a> | ";
727 $searchRows[$count]['actions'] .= CRM_Utils_System
::href(ts('merge'), 'civicrm/contact/merge', $mergeParams);
728 $searchRows[$count]['actions'] .= " | <a id='notDuplicate' href='#' onClick=\"processDupes( {$pairInfo['entity_id1']}, {$pairInfo['entity_id2']}, 'dupe-nondupe', 'dupe-listing'); return false;\">" . ts('not a duplicate') . "</a>";
731 $searchRows[$count]['actions'] = '<em>' . ts('Insufficient access rights - cannot merge') . '</em>';
737 'data' => $searchRows,
738 'recordsTotal' => $iTotal,
739 'recordsFiltered' => $iFilteredTotal,
741 if (!empty($_REQUEST['is_unit_test'])) {
744 CRM_Utils_JSON
::output($dupePairs);
748 * Get the searchable options from the request.
752 public static function getSearchOptionsFromRequest() {
754 $searchData = $_REQUEST['search'] ??
NULL;
755 $searchData['value'] = CRM_Utils_Type
::escape($searchData['value'] ??
NULL, 'String');
756 $selectorElements = [
773 $columns = $_REQUEST['columns'];
775 foreach ($columns as $column) {
776 if (!empty($column['search']['value']) && in_array($column['data'], $selectorElements)) {
777 $searchParams[$column['data']] = CRM_Utils_Type
::escape($column['search']['value'], 'String');
779 elseif (!empty($searchData['value'])) {
780 $searchParams[$column['data']] = $searchData['value'];
783 return $searchParams;
787 * Is the query an OR query.
789 * If a generic search value is passed in - ie. $_REQUEST['search']['value'] = 'abc'
790 * then all fields are searched for this.
792 * It is unclear if there is any code that still passes this in or whether is is just legacy. It
793 * could cause a server-killing query on a large site so it probably is NOT in use if we haven't
798 public static function isOrQuery() {
799 $searchData = $_REQUEST['search'] ??
NULL;
800 return !empty($searchData['value']);
804 * Mark not duplicates.
806 * Note this function would sensibly be replaced by an api-call but extracting here to add a test first.
808 * I would have like to make it private but test class accesses it & it doesn't warrant being a BAO class
809 * as it should feel very endangered.
813 * @param "dupe-nondupe|nondupe-dupe" $oper
815 * @return \CRM_Core_DAO|mixed|null
817 public static function markNonDuplicates($cid, $oid, $oper) {
818 if ($oper == 'dupe-nondupe') {
820 civicrm_api3('Exception', 'create', ['contact_id1' => $cid, 'contact_id2' => $oid]);
823 catch (CiviCRM_API3_Exception
$e) {
828 $exception = new CRM_Dedupe_DAO_Exception();
829 $exception->contact_id1
= $cid;
830 $exception->contact_id2
= $oid;
831 //make sure contact2 > contact1.
833 $exception->contact_id1
= $oid;
834 $exception->contact_id2
= $cid;
836 $exception->find(TRUE);
839 if ($oper == 'nondupe-dupe') {
840 $status = $exception->delete();
846 * Retrieve a PDF Page Format for the PDF Letter form.
848 public static function pdfFormat() {
849 $formatId = CRM_Utils_Type
::escape($_REQUEST['formatId'], 'Integer');
851 $pdfFormat = CRM_Core_BAO_PdfFormat
::getById($formatId);
853 CRM_Utils_JSON
::output($pdfFormat);
857 * Retrieve Paper Size dimensions.
859 public static function paperSize() {
860 $paperSizeName = CRM_Utils_Type
::escape($_REQUEST['paperSizeName'], 'String');
862 $paperSize = CRM_Core_BAO_PaperSize
::getByName($paperSizeName);
864 CRM_Utils_JSON
::output($paperSize);
868 * Swap contacts in a dupe pair i.e main with duplicate contact.
870 * @param int $prevNextId
872 public static function flipDupePairs($prevNextId = NULL) {
874 // @todo figure out if this is always POST & specify that rather than inexact GET
876 // We cannot use CRM_Utils_Request::retrieve() because it might be an array.
877 // It later gets validated in escapeAll below.
878 $prevNextId = $_REQUEST['pnid'];
881 $onlySelected = FALSE;
882 if (is_array($prevNextId) && !CRM_Utils_Array
::crmIsEmptyArray($prevNextId)) {
883 $onlySelected = TRUE;
885 $prevNextId = CRM_Utils_Type
::escapeAll((array) $prevNextId, 'Positive');
886 CRM_Core_BAO_PrevNextCache
::flipPair($prevNextId, $onlySelected);
887 CRM_Utils_System
::civiExit();
891 * Used to store selected contacts across multiple pages in advanced search.
893 public static function selectUnselectContacts() {
894 $name = $_REQUEST['name'] ??
NULL;
895 $cacheKey = $_REQUEST['qfKey'] ??
NULL;
896 $state = CRM_Utils_Array
::value('state', $_REQUEST, 'checked');
897 $variableType = CRM_Utils_Array
::value('variableType', $_REQUEST, 'single');
899 $actionToPerform = CRM_Utils_Array
::value('action', $_REQUEST, 'select');
901 if ($variableType == 'multiple') {
902 // action post value only works with multiple type variable
904 //multiple names like mark_x_1-mark_x_2 where 1,2 are cids
905 $elements = explode('-', $name);
906 foreach ($elements as $key => $element) {
907 $elements[$key] = self
::_convertToId($element);
909 CRM_Utils_Type
::escapeAll($elements, 'Integer');
910 Civi
::service('prevnext')->markSelection($cacheKey, $actionToPerform, $elements);
913 Civi
::service('prevnext')->markSelection($cacheKey, $actionToPerform);
916 elseif ($variableType == 'single') {
917 $cId = self
::_convertToId($name);
918 CRM_Utils_Type
::escape($cId, 'Integer');
919 $action = ($state == 'checked') ?
'select' : 'unselect';
920 Civi
::service('prevnext')->markSelection($cacheKey, $action, $cId);
922 $contactIds = Civi
::service('prevnext')->getSelection($cacheKey);
923 $countSelectionCids = count($contactIds[$cacheKey]);
925 $arrRet = ['getCount' => $countSelectionCids];
926 CRM_Utils_JSON
::output($arrRet);
930 * @param string $name
934 public static function _convertToId($name) {
935 if (substr($name, 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
936 $cId = substr($name, CRM_Core_Form
::CB_PREFIX_LEN
);
941 public static function getAddressDisplay() {
942 $contactId = CRM_Utils_Request
::retrieve('contact_id', 'Positive');
944 $addressVal["error_message"] = "no contact id found";
948 'contact_id' => $contactId,
949 'entity_id' => $contactId,
951 $addressVal = CRM_Core_BAO_Address
::getValues($entityBlock);
954 CRM_Utils_JSON
::output($addressVal);
958 * Mark dupe pairs as selected from un-selected state or vice-versa, in dupe cache table.
960 public static function toggleDedupeSelect() {
961 $pnid = $_REQUEST['pnid'];
962 $isSelected = CRM_Utils_Type
::escape($_REQUEST['is_selected'], 'Boolean');
963 $cacheKeyString = CRM_Utils_Request
::retrieve('cacheKey', 'Alphanumeric', $null, FALSE);
966 1 => [$isSelected, 'Boolean'],
967 // using % to address rows with conflicts as well
968 3 => ["$cacheKeyString%", 'String'],
971 //check pnid is_array or integer
973 if (is_array($pnid) && !CRM_Utils_Array
::crmIsEmptyArray($pnid)) {
974 CRM_Utils_Type
::escapeAll($pnid, 'Positive');
975 $pnid = implode(', ', $pnid);
976 $whereClause = " id IN ( {$pnid} ) ";
979 $pnid = CRM_Utils_Type
::escape($pnid, 'Integer');
980 $whereClause = " id = %2";
981 $params[2] = [$pnid, 'Integer'];
984 $sql = "UPDATE civicrm_prevnext_cache SET is_selected = %1 WHERE {$whereClause} AND cachekey LIKE %3";
985 CRM_Core_DAO
::executeQuery($sql, $params);
987 CRM_Utils_System
::civiExit();
991 * Retrieve contact relationships.
993 public static function getContactRelationships() {
994 $contactID = CRM_Utils_Type
::escape($_GET['cid'], 'Integer');
995 $context = CRM_Utils_Request
::retrieve('context', 'Alphanumeric');
996 $relationship_type_id = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('relationship_type_id', $_GET), 'Integer', FALSE);
998 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactID)) {
999 return CRM_Utils_System
::permissionDenied();
1002 $params = CRM_Core_Page_AJAX
::defaultSortAndPagerParams();
1004 $params['contact_id'] = $contactID;
1005 $params['context'] = $context;
1006 if ($relationship_type_id) {
1007 $params['relationship_type_id'] = $relationship_type_id;
1010 // get the contact relationships
1011 $relationships = CRM_Contact_BAO_Relationship
::getContactRelationshipSelector($params);
1013 CRM_Utils_JSON
::output($relationships);