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
20 * This class contains all contact related functions that are called using AJAX (jQuery)
22 class CRM_Contact_Page_AJAX
{
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).
29 const CHECK_USERNAME_TTL
= 10800;
32 const AUTOCOMPLETE_TTL
= 21600;
35 * Ajax callback for custom fields of type ContactReference
37 * Todo: Migrate contact reference fields to use EntityRef
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');
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'];
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);
53 if (!empty($cf['filter'])) {
55 parse_str($cf['filter'], $filterParams);
57 $action = CRM_Utils_Array
::value('action', $filterParams);
58 if (!empty($action) && !in_array($action, ['get', 'lookup'])) {
59 CRM_Utils_System
::civiExit(1);
62 if (!empty($filterParams['group'])) {
63 $filterParams['group'] = explode(',', $filterParams['group']);
67 $list = array_keys(CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
68 'contact_reference_options'
71 $return = array_unique(array_merge(['sort_name'], $list));
73 $limit = Civi
::settings()->get('search_autocomplete_count');
75 $params = ['offset' => 0, 'rowCount' => $limit, 'version' => 3];
76 foreach ($return as $fld) {
77 $params["return.{$fld}"] = 1;
80 if (!empty($action)) {
96 foreach ($_GET as $param => $val) {
98 in_array($param, $excludeGet) ||
99 strpos($param, 'return.') !== FALSE ||
100 strpos($param, 'api.') !== FALSE
104 $params[$param] = $val;
109 $params['sort_name'] = $name;
112 $params['sort'] = 'sort_name';
114 // tell api to skip permission chk. dgg
115 $params['check_permissions'] = 0;
117 // add filter variable to params
118 if (!empty($filterParams)) {
119 $params = array_merge($params, $filterParams);
122 $contact = civicrm_api('Contact', 'Get', $params);
124 if (!empty($contact['is_error'])) {
125 CRM_Utils_System
::civiExit(1);
129 foreach ($contact['values'] as $value) {
131 foreach ($return as $fld) {
132 if (!empty($value[$fld])) {
133 $view[] = $value[$fld];
136 $contactList[] = ['id' => $value['id'], 'text' => implode(' :: ', $view)];
139 if (!empty($_GET['is_unit_test'])) {
142 CRM_Utils_JSON
::output($contactList);
146 * Fetch PCP ID by PCP Supporter sort_name, also displays PCP title and associated Contribution Page title
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');
153 $where = ' AND pcp.page_id = cp.id AND pcp.contact_id = cc.id';
155 $config = CRM_Core_Config
::singleton();
156 if ($config->includeWildCardInName
) {
157 $strSearch = "%$name%";
160 $strSearch = "$name%";
162 $includeEmailFrom = $includeNickName = '';
163 if ($config->includeNickNameInName
) {
164 $includeNickName = " OR nick_name LIKE '$strSearch'";
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} ";
171 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
174 $offset = $count = 0;
175 if (!empty($_GET['page_num'])) {
176 $page = (int) $_GET['page_num'];
177 $offset = $limit * ($page - 1);
181 $select = 'cc.sort_name, pcp.title, cp.title';
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
188 {$whereClause} AND pcp.page_type = 'contribute'
190 SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
191 FROM civicrm_pcp pcp, civicrm_event cp, civicrm_contact cc
193 {$whereClause} AND pcp.page_type = 'event'
196 LIMIT $offset, $limit
199 $dao = CRM_Core_DAO
::executeQuery($query);
200 $output = ['results' => [], 'more' => FALSE];
201 while ($dao->fetch()) {
202 if (++
$count > $max) {
203 $output['more'] = TRUE;
206 $output['results'][] = ['id' => $dao->id
, 'text' => $dao->data
];
209 CRM_Utils_JSON
::output($output);
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);
219 if (!CRM_Case_BAO_Case
::accessCase($caseID)) {
220 CRM_Utils_System
::permissionDenied();
223 $ret = ['is_error' => 0];
225 list($relTypeId, $b, $a) = explode('_', $relType);
227 if ($relationshipID && $originalCid) {
228 CRM_Case_BAO_Case
::endCaseRole($caseID, $a, $originalCid, $relTypeId);
231 $clientList = CRM_Case_BAO_Case
::getCaseClients($caseID);
233 // Loop through multiple case clients
234 foreach ($clientList as $i => $sourceContactID) {
237 'case_id' => $caseID,
238 'relationship_type_id' => $relTypeId,
239 "contact_id_$a" => $relContactID,
240 "contact_id_$b" => $sourceContactID,
241 'sequential' => TRUE,
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',
251 $result = civicrm_api3('relationship', 'create', $params);
253 catch (CiviCRM_API3_Exception
$e) {
254 $ret['is_error'] = 1;
255 $ret['error_message'] = $e->getMessage();
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);
262 if (!empty($_REQUEST['is_unit_test'])) {
266 CRM_Utils_JSON
::output($ret);
270 * Fetch the custom field help.
272 public static function customField() {
273 $fieldId = CRM_Utils_Type
::escape($_REQUEST['id'], 'Integer');
274 $params = ['id' => $fieldId];
275 $returnProperties = ['help_pre', 'help_post'];
278 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $values, $returnProperties);
279 CRM_Utils_JSON
::output($values);
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();
290 * Delete custom value.
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);
299 echo CRM_Contact_BAO_Contact
::getCountComponent('custom_' . $customGroupID, $contactId);
302 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
303 CRM_Utils_System
::civiExit();
307 * check the CMS username.
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');
314 CRM_Utils_Time
::getTimeRaw() > $_REQUEST['ts'] + self
::CHECK_USERNAME_TTL
315 ||
$for != 'civicrm/ajax/cmsuser'
316 ||
!$signer->validate($sig, $_REQUEST)
318 $user = ['name' => 'error'];
319 CRM_Utils_JSON
::output($user);
322 $config = CRM_Core_Config
::singleton();
323 $username = trim(CRM_Utils_Array
::value('cms_name', $_REQUEST));
325 $params = ['name' => $username];
328 $config->userSystem
->checkUserNameEmailExists($params, $errors);
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);
336 //user name is available
337 $user = ['name' => 'yes'];
338 CRM_Utils_JSON
::output($user);
341 // Not reachable: JSON::output() above exits.
342 CRM_Utils_System
::civiExit();
346 * Function to get email address of a contact.
348 public static function getContactEmail() {
349 if (!empty($_REQUEST['contact_id'])) {
350 $contactID = CRM_Utils_Type
::escape($_REQUEST['contact_id'], 'Positive');
351 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactID, CRM_Core_Permission
::EDIT
)) {
356 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
358 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/plain');
364 $noemail = CRM_Utils_Array
::value('noemail', $_GET);
366 $name = CRM_Utils_Array
::value('name', $_GET);
368 $name = CRM_Utils_Type
::escape($name, 'String');
370 $queryString = " cc.sort_name LIKE '%$name%'";
373 $queryString = " ( cc.sort_name LIKE '%$name%' OR ce.email LIKE '%$name%' ) ";
377 $cid = CRM_Utils_Array
::value('cid', $_GET);
379 //check cid for integer
380 $contIDS = explode(',', $cid);
381 foreach ($contIDS as $contID) {
382 CRM_Utils_Type
::escape($contID, 'Integer');
384 $queryString = " cc.id IN ( $cid )";
390 $offset = CRM_Utils_Array
::value('offset', $_GET, 0);
391 $rowCount = Civi
::settings()->get('search_autocomplete_count');
393 $offset = CRM_Utils_Type
::escape($offset, 'Int');
395 // add acl clause here
396 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
398 $aclWhere = " AND $aclWhere";
402 SELECT sort_name name, cc.id
403 FROM civicrm_contact cc
405 WHERE cc.is_deceased = 0 AND {$queryString}
407 LIMIT {$offset}, {$rowCount}
410 // send query to hook to be modified if needed
411 CRM_Utils_Hook
::contactListQuery($query,
413 CRM_Utils_Request
::retrieve('context', 'Alphanumeric'),
414 CRM_Utils_Request
::retrieve('cid', 'Positive')
417 $dao = CRM_Core_DAO
::executeQuery($query);
418 while ($dao->fetch()) {
421 'text' => $dao->name
,
427 SELECT sort_name name, ce.email, cc.id
428 FROM civicrm_email ce INNER JOIN civicrm_contact cc ON cc.id = ce.contact_id
430 WHERE ce.on_hold = 0 AND cc.is_deceased = 0 AND cc.do_not_email = 0 AND {$queryString}
432 LIMIT {$offset}, {$rowCount}
435 // send query to hook to be modified if needed
436 CRM_Utils_Hook
::contactListQuery($query,
438 CRM_Utils_Request
::retrieve('context', 'Alphanumeric'),
439 CRM_Utils_Request
::retrieve('cid', 'Positive')
442 $dao = CRM_Core_DAO
::executeQuery($query);
444 while ($dao->fetch()) {
447 'text' => '"' . $dao->name
. '" <' . $dao->email
. '>',
448 'id' => (CRM_Utils_Array
::value('id', $_GET)) ?
"{$dao->id}::{$dao->email}" : '"' . $dao->name
. '" <' . $dao->email
. '>',
452 CRM_Utils_JSON
::output($result);
455 CRM_Utils_System
::civiExit();
458 public static function getContactPhone() {
462 //check for mobile type
463 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
464 $mobileType = CRM_Utils_Array
::value('Mobile', $phoneTypes);
466 $name = CRM_Utils_Request
::retrieveValue('name', 'String', NULL, FALSE, 'GET');
468 $key = (int) count(array_keys($sqlParmas)) +
1;
469 $queryString = " ( cc.sort_name LIKE %{$key} OR cp.phone LIKE %{$key} ) ";
470 $sqlParams[$key] = ['%' . $name . '%', 'String'];
473 $cid = CRM_Utils_Request
::retrieveValue('cid', 'CommaSeparatedIntegers', NULL, FALSE, 'GET');
475 $queryString = " cc.id IN ( $cid )";
481 $offset = (int) CRM_Utils_Request
::retrieveValue('offset', 'Integer', 0, FALSE, 'GET');
482 $rowCount = (int) CRM_Utils_Request
::retrieveValue('rowcount', 'Integer', 20, FALSE, 'GET');
484 // add acl clause here
485 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
487 $aclWhere = " AND $aclWhere";
491 SELECT sort_name name, cp.phone, cc.id
492 FROM civicrm_phone cp INNER JOIN civicrm_contact cc ON cc.id = cp.contact_id
494 WHERE cc.is_deceased = 0 AND cc.do_not_sms = 0 AND cp.phone_type_id = {$mobileType} AND {$queryString}
496 LIMIT {$offset}, {$rowCount}
499 // send query to hook to be modified if needed
500 CRM_Utils_Hook
::contactListQuery($query,
502 CRM_Utils_Request
::retrieve('context', 'Alphanumeric'),
503 CRM_Utils_Request
::retrieve('cid', 'Positive')
506 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
508 while ($dao->fetch()) {
510 'text' => '"' . $dao->name
. '" (' . $dao->phone
. ')',
511 'id' => (CRM_Utils_Array
::value('id', $_GET)) ?
"{$dao->id}::{$dao->phone}" : '"' . $dao->name
. '" <' . $dao->phone
. '>',
514 CRM_Utils_JSON
::output($result);
516 CRM_Utils_System
::civiExit();
519 public static function buildSubTypes() {
520 $parent = CRM_Utils_Request
::retrieve('parentId', 'Positive');
524 $contactType = 'Individual';
528 $contactType = 'Household';
532 $contactType = 'Organization';
536 $subTypes = CRM_Contact_BAO_ContactType
::subTypePairs($contactType, FALSE, NULL);
538 CRM_Utils_JSON
::output($subTypes);
541 public static function buildDedupeRules() {
542 $parent = CRM_Utils_Request
::retrieve('parentId', 'Positive');
546 $contactType = 'Individual';
550 $contactType = 'Household';
554 $contactType = 'Organization';
558 $dedupeRules = CRM_Dedupe_BAO_RuleGroup
::getByType($contactType);
560 CRM_Utils_JSON
::output($dedupeRules);
564 * Function used for CiviCRM dashboard operations.
566 public static function dashboard() {
567 switch ($_REQUEST['op']) {
569 CRM_Core_BAO_Dashboard
::saveDashletChanges($_REQUEST['columns']);
572 case 'delete_dashlet':
573 $dashletID = CRM_Utils_Type
::escape($_REQUEST['dashlet_id'], 'Positive');
574 CRM_Core_BAO_Dashboard
::deleteDashlet($dashletID);
577 CRM_Utils_System
::civiExit();
581 * Retrieve signature based on email id.
583 public static function getSignature() {
584 $emailID = CRM_Utils_Type
::escape($_REQUEST['emailID'], 'Positive');
585 $query = "SELECT signature_text, signature_html FROM civicrm_email WHERE id = {$emailID}";
586 $dao = CRM_Core_DAO
::executeQuery($query);
589 while ($dao->fetch()) {
591 'signature_text' => $dao->signature_text
,
592 'signature_html' => $dao->signature_html
,
596 CRM_Utils_JSON
::output($signatures);
602 public static function processDupes() {
603 $oper = CRM_Utils_Type
::escape($_REQUEST['op'], 'String');
604 $cid = CRM_Utils_Type
::escape($_REQUEST['cid'], 'Positive');
605 $oid = CRM_Utils_Type
::escape($_REQUEST['oid'], 'Positive');
607 if (!$oper ||
!$cid ||
!$oid) {
611 $status = self
::markNonDuplicates($cid, $oid, $oper);
613 CRM_Utils_JSON
::output(['status' => ($status) ?
$oper : $status]);
617 * Retrieve list of duplicate pairs from cache table.
619 public static function getDedupes() {
620 $offset = isset($_REQUEST['start']) ? CRM_Utils_Type
::escape($_REQUEST['start'], 'Integer') : 0;
621 $rowCount = isset($_REQUEST['length']) ? CRM_Utils_Type
::escape($_REQUEST['length'], 'Integer') : 25;
623 $gid = CRM_Utils_Request
::retrieve('gid', 'Positive');
624 $rgid = CRM_Utils_Request
::retrieve('rgid', 'Positive');
625 $limit = CRM_Utils_Request
::retrieveValue('limit', 'Positive', 0);
627 $criteria = CRM_Utils_Request
::retrieve('criteria', 'Json', $null, FALSE, '{}');
628 $selected = CRM_Utils_Request
::retrieveValue('selected', 'Boolean');
633 $whereClause = $orderByClause = '';
634 $cacheKeyString = CRM_Dedupe_Merger
::getMergeCacheKeyString($rgid, $gid, json_decode($criteria, TRUE), TRUE, $limit);
638 $searchParams = self
::getSearchOptionsFromRequest();
644 $isOrQuery = self
::isOrQuery();
648 'dst' => 'cc1.display_name',
649 'src' => 'cc2.display_name',
650 'dst_email' => 'ce1.email',
651 'src_email' => 'ce2.email',
652 'dst_postcode' => 'ca1.postal_code',
653 'src_postcode' => 'ca2.postal_code',
654 'dst_street' => 'ca1.street',
655 'src_street' => 'ca2.street',
658 foreach ($mappings as $key => $dbName) {
659 if (!empty($searchParams[$key])) {
661 $wildcard = strstr($key, 'postcode') ?
'' : '%';
662 $queryParams[$nextParamKey] = [$wildcard . $searchParams[$key] . '%', 'String'];
663 $where[] = $dbName . " LIKE %{$nextParamKey} ";
669 $whereClause = ' ( ' . implode(' OR ', $where) . ' ) ';
672 if (!empty($where)) {
673 $whereClause = implode(' AND ', $where);
676 $whereClause .= $whereClause ?
' AND de.id IS NULL' : ' de.id IS NULL';
679 $whereClause .= ' AND pn.is_selected = 1';
681 $join .= CRM_Dedupe_Merger
::getJoinOnDedupeTable();
684 'cc1.contact_type' => 'dst_contact_type',
685 'cc1.display_name' => 'dst_display_name',
686 'cc1.contact_sub_type' => 'dst_contact_sub_type',
687 'cc2.contact_type' => 'src_contact_type',
688 'cc2.display_name' => 'src_display_name',
689 'cc2.contact_sub_type' => 'src_contact_sub_type',
690 'ce1.email' => 'dst_email',
691 'ce2.email' => 'src_email',
692 'ca1.postal_code' => 'dst_postcode',
693 'ca2.postal_code' => 'src_postcode',
694 'ca1.street_address' => 'dst_street',
695 'ca2.street_address' => 'src_street',
699 $join .= " INNER JOIN civicrm_contact cc1 ON cc1.id = pn.entity_id1";
700 $join .= " INNER JOIN civicrm_contact cc2 ON cc2.id = pn.entity_id2";
701 $join .= " LEFT JOIN civicrm_email ce1 ON (ce1.contact_id = pn.entity_id1 AND ce1.is_primary = 1 )";
702 $join .= " LEFT JOIN civicrm_email ce2 ON (ce2.contact_id = pn.entity_id2 AND ce2.is_primary = 1 )";
703 $join .= " LEFT JOIN civicrm_address ca1 ON (ca1.contact_id = pn.entity_id1 AND ca1.is_primary = 1 )";
704 $join .= " LEFT JOIN civicrm_address ca2 ON (ca2.contact_id = pn.entity_id2 AND ca2.is_primary = 1 )";
706 $iTotal = CRM_Core_BAO_PrevNextCache
::getCount($cacheKeyString, $join, $whereClause, '=', $queryParams);
707 if (!empty($_REQUEST['order'])) {
708 foreach ($_REQUEST['order'] as $orderInfo) {
709 if (!empty($orderInfo['column'])) {
710 $orderColumnNumber = $orderInfo['column'];
711 $dir = CRM_Utils_Type
::escape($orderInfo['dir'], 'MysqlOrderByDirection', FALSE);
714 $columnDetails = CRM_Utils_Array
::value($orderColumnNumber, $_REQUEST['columns']);
716 if (!empty($columnDetails)) {
717 switch ($columnDetails['data']) {
719 $orderByClause = " ORDER BY cc2.display_name {$dir}";
723 $orderByClause = " ORDER BY ce2.email {$dir}";
727 $orderByClause = " ORDER BY ca2.street_address {$dir}";
731 $orderByClause = " ORDER BY ca2.postal_code {$dir}";
735 $orderByClause = " ORDER BY cc1.display_name {$dir}";
739 $orderByClause = " ORDER BY ce1.email {$dir}";
743 $orderByClause = " ORDER BY ca1.street_address {$dir}";
747 $orderByClause = " ORDER BY ca1.postal_code {$dir}";
751 $orderByClause = " ORDER BY cc1.display_name ASC";
756 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $whereClause, $offset, $rowCount, $select, $orderByClause, TRUE, $queryParams);
757 $iFilteredTotal = CRM_Core_DAO
::singleValueQuery("SELECT FOUND_ROWS()");
760 foreach ($dupePairs as $key => $pairInfo) {
761 $pair = $pairInfo['data'];
762 $srcContactSubType = CRM_Utils_Array
::value('src_contact_sub_type', $pairInfo);
763 $dstContactSubType = CRM_Utils_Array
::value('dst_contact_sub_type', $pairInfo);
764 $srcTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage($srcContactSubType ?
765 $srcContactSubType : $pairInfo['src_contact_type'],
767 $pairInfo['entity_id2']
769 $dstTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage($dstContactSubType ?
770 $dstContactSubType : $pairInfo['dst_contact_type'],
772 $pairInfo['entity_id1']
775 $searchRows[$count]['is_selected'] = $pairInfo['is_selected'];
776 $searchRows[$count]['is_selected_input'] = "<input type='checkbox' class='crm-dedupe-select' name='pnid_{$pairInfo['prevnext_id']}' value='{$pairInfo['is_selected']}' onclick='toggleDedupeSelect(this)'>";
777 $searchRows[$count]['src_image'] = $srcTypeImage;
778 $searchRows[$count]['src'] = CRM_Utils_System
::href($pair['srcName'], 'civicrm/contact/view', "reset=1&cid={$pairInfo['entity_id2']}");
779 $searchRows[$count]['src_email'] = CRM_Utils_Array
::value('src_email', $pairInfo);
780 $searchRows[$count]['src_street'] = CRM_Utils_Array
::value('src_street', $pairInfo);
781 $searchRows[$count]['src_postcode'] = CRM_Utils_Array
::value('src_postcode', $pairInfo);
782 $searchRows[$count]['dst_image'] = $dstTypeImage;
783 $searchRows[$count]['dst'] = CRM_Utils_System
::href($pair['dstName'], 'civicrm/contact/view', "reset=1&cid={$pairInfo['entity_id1']}");
784 $searchRows[$count]['dst_email'] = CRM_Utils_Array
::value('dst_email', $pairInfo);
785 $searchRows[$count]['dst_street'] = CRM_Utils_Array
::value('dst_street', $pairInfo);
786 $searchRows[$count]['dst_postcode'] = CRM_Utils_Array
::value('dst_postcode', $pairInfo);
787 $searchRows[$count]['conflicts'] = str_replace("',", "',<br/>", CRM_Utils_Array
::value('conflicts', $pair));
788 $searchRows[$count]['weight'] = CRM_Utils_Array
::value('weight', $pair);
790 if (!empty($pairInfo['data']['canMerge'])) {
793 'cid' => $pairInfo['entity_id1'],
794 'oid' => $pairInfo['entity_id2'],
795 'action' => 'update',
797 'criteria' => $criteria,
798 'limit' => CRM_Utils_Request
::retrieve('limit', 'Integer'),
801 $mergeParams['gid'] = $gid;
804 $searchRows[$count]['actions'] = "<a class='crm-dedupe-flip' href='#' data-pnid={$pairInfo['prevnext_id']}>" . ts('flip') . "</a> | ";
805 $searchRows[$count]['actions'] .= CRM_Utils_System
::href(ts('merge'), 'civicrm/contact/merge', $mergeParams);
806 $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>";
809 $searchRows[$count]['actions'] = '<em>' . ts('Insufficient access rights - cannot merge') . '</em>';
815 'data' => $searchRows,
816 'recordsTotal' => $iTotal,
817 'recordsFiltered' => $iFilteredTotal,
819 if (!empty($_REQUEST['is_unit_test'])) {
822 CRM_Utils_JSON
::output($dupePairs);
826 * Get the searchable options from the request.
830 public static function getSearchOptionsFromRequest() {
832 $searchData = CRM_Utils_Array
::value('search', $_REQUEST);
833 $searchData['value'] = CRM_Utils_Type
::escape($searchData['value'], 'String');
834 $selectorElements = [
851 $columns = $_REQUEST['columns'];
853 foreach ($columns as $column) {
854 if (!empty($column['search']['value']) && in_array($column['data'], $selectorElements)) {
855 $searchParams[$column['data']] = CRM_Utils_Type
::escape($column['search']['value'], 'String');
857 elseif (!empty($searchData['value'])) {
858 $searchParams[$column['data']] = $searchData['value'];
861 return $searchParams;
865 * Is the query an OR query.
867 * If a generic search value is passed in - ie. $_REQUEST['search']['value'] = 'abc'
868 * then all fields are searched for this.
870 * It is unclear if there is any code that still passes this in or whether is is just legacy. It
871 * could cause a server-killing query on a large site so it probably is NOT in use if we haven't
876 public static function isOrQuery() {
877 $searchData = CRM_Utils_Array
::value('search', $_REQUEST);
878 return !empty($searchData['value']);
882 * Mark not duplicates.
884 * Note this function would sensibly be replaced by an api-call but extracting here to add a test first.
886 * I would have like to make it private but test class accesses it & it doesn't warrant being a BAO class
887 * as it should feel very endangered.
891 * @param "dupe-nondupe|nondupe-dupe" $oper
893 * @return \CRM_Core_DAO|mixed|null
895 public static function markNonDuplicates($cid, $oid, $oper) {
896 if ($oper == 'dupe-nondupe') {
898 civicrm_api3('Exception', 'create', ['contact_id1' => $cid, 'contact_id2' => $oid]);
901 catch (CiviCRM_API3_Exception
$e) {
906 $exception = new CRM_Dedupe_DAO_Exception();
907 $exception->contact_id1
= $cid;
908 $exception->contact_id2
= $oid;
909 //make sure contact2 > contact1.
911 $exception->contact_id1
= $oid;
912 $exception->contact_id2
= $cid;
914 $exception->find(TRUE);
917 if ($oper == 'nondupe-dupe') {
918 $status = $exception->delete();
924 * Retrieve a PDF Page Format for the PDF Letter form.
926 public function pdfFormat() {
927 $formatId = CRM_Utils_Type
::escape($_REQUEST['formatId'], 'Integer');
929 $pdfFormat = CRM_Core_BAO_PdfFormat
::getById($formatId);
931 CRM_Utils_JSON
::output($pdfFormat);
935 * Retrieve Paper Size dimensions.
937 public static function paperSize() {
938 $paperSizeName = CRM_Utils_Type
::escape($_REQUEST['paperSizeName'], 'String');
940 $paperSize = CRM_Core_BAO_PaperSize
::getByName($paperSizeName);
942 CRM_Utils_JSON
::output($paperSize);
946 * Swap contacts in a dupe pair i.e main with duplicate contact.
948 * @param int $prevNextId
950 public static function flipDupePairs($prevNextId = NULL) {
952 // @todo figure out if this is always POST & specify that rather than inexact GET
954 // We cannot use CRM_Utils_Request::retrieve() because it might be an array.
955 // It later gets validated in escapeAll below.
956 $prevNextId = $_REQUEST['pnid'];
959 $onlySelected = FALSE;
960 if (is_array($prevNextId) && !CRM_Utils_Array
::crmIsEmptyArray($prevNextId)) {
961 $onlySelected = TRUE;
963 $prevNextId = CRM_Utils_Type
::escapeAll((array) $prevNextId, 'Positive');
964 CRM_Core_BAO_PrevNextCache
::flipPair($prevNextId, $onlySelected);
965 CRM_Utils_System
::civiExit();
969 * Used to store selected contacts across multiple pages in advanced search.
971 public static function selectUnselectContacts() {
972 $name = CRM_Utils_Array
::value('name', $_REQUEST);
973 $cacheKey = CRM_Utils_Array
::value('qfKey', $_REQUEST);
974 $state = CRM_Utils_Array
::value('state', $_REQUEST, 'checked');
975 $variableType = CRM_Utils_Array
::value('variableType', $_REQUEST, 'single');
977 $actionToPerform = CRM_Utils_Array
::value('action', $_REQUEST, 'select');
979 if ($variableType == 'multiple') {
980 // action post value only works with multiple type variable
982 //multiple names like mark_x_1-mark_x_2 where 1,2 are cids
983 $elements = explode('-', $name);
984 foreach ($elements as $key => $element) {
985 $elements[$key] = self
::_convertToId($element);
987 CRM_Utils_Type
::escapeAll($elements, 'Integer');
988 Civi
::service('prevnext')->markSelection($cacheKey, $actionToPerform, $elements);
991 Civi
::service('prevnext')->markSelection($cacheKey, $actionToPerform);
994 elseif ($variableType == 'single') {
995 $cId = self
::_convertToId($name);
996 CRM_Utils_Type
::escape($cId, 'Integer');
997 $action = ($state == 'checked') ?
'select' : 'unselect';
998 Civi
::service('prevnext')->markSelection($cacheKey, $action, $cId);
1000 $contactIds = Civi
::service('prevnext')->getSelection($cacheKey);
1001 $countSelectionCids = count($contactIds[$cacheKey]);
1003 $arrRet = ['getCount' => $countSelectionCids];
1004 CRM_Utils_JSON
::output($arrRet);
1008 * @param string $name
1012 public static function _convertToId($name) {
1013 if (substr($name, 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
1014 $cId = substr($name, CRM_Core_Form
::CB_PREFIX_LEN
);
1019 public static function getAddressDisplay() {
1020 $contactId = CRM_Utils_Request
::retrieve('contact_id', 'Positive');
1022 $addressVal["error_message"] = "no contact id found";
1026 'contact_id' => $contactId,
1027 'entity_id' => $contactId,
1029 $addressVal = CRM_Core_BAO_Address
::getValues($entityBlock);
1032 CRM_Utils_JSON
::output($addressVal);
1036 * Mark dupe pairs as selected from un-selected state or vice-versa, in dupe cache table.
1038 public static function toggleDedupeSelect() {
1039 $pnid = $_REQUEST['pnid'];
1040 $isSelected = CRM_Utils_Type
::escape($_REQUEST['is_selected'], 'Boolean');
1041 $cacheKeyString = CRM_Utils_Request
::retrieve('cacheKey', 'Alphanumeric', $null, FALSE);
1044 1 => [$isSelected, 'Boolean'],
1045 // using % to address rows with conflicts as well
1046 3 => ["$cacheKeyString%", 'String'],
1049 //check pnid is_array or integer
1050 $whereClause = NULL;
1051 if (is_array($pnid) && !CRM_Utils_Array
::crmIsEmptyArray($pnid)) {
1052 CRM_Utils_Type
::escapeAll($pnid, 'Positive');
1053 $pnid = implode(', ', $pnid);
1054 $whereClause = " id IN ( {$pnid} ) ";
1057 $pnid = CRM_Utils_Type
::escape($pnid, 'Integer');
1058 $whereClause = " id = %2";
1059 $params[2] = [$pnid, 'Integer'];
1062 $sql = "UPDATE civicrm_prevnext_cache SET is_selected = %1 WHERE {$whereClause} AND cachekey LIKE %3";
1063 CRM_Core_DAO
::executeQuery($sql, $params);
1065 CRM_Utils_System
::civiExit();
1069 * Retrieve contact relationships.
1071 public static function getContactRelationships() {
1072 $contactID = CRM_Utils_Type
::escape($_GET['cid'], 'Integer');
1073 $context = CRM_Utils_Request
::retrieve('context', 'Alphanumeric');
1074 $relationship_type_id = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('relationship_type_id', $_GET), 'Integer', FALSE);
1076 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactID)) {
1077 return CRM_Utils_System
::permissionDenied();
1080 $params = CRM_Core_Page_AJAX
::defaultSortAndPagerParams();
1082 $params['contact_id'] = $contactID;
1083 $params['context'] = $context;
1084 if ($relationship_type_id) {
1085 $params['relationship_type_id'] = $relationship_type_id;
1088 // get the contact relationships
1089 $relationships = CRM_Contact_BAO_Relationship
::getContactRelationshipSelector($params);
1091 CRM_Utils_JSON
::output($relationships);