3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
36 * This class contains all contact related functions that are called using AJAX (jQuery)
38 class CRM_Contact_Page_AJAX
{
40 * When a user chooses a username, CHECK_USERNAME_TTL
41 * is the time window in which they can check usernames
42 * (without reloading the overall form).
45 const CHECK_USERNAME_TTL
= 10800;
48 const AUTOCOMPLETE_TTL
= 21600;
51 * Ajax callback for custom fields of type ContactReference
53 * Todo: Migrate contact reference fields to use EntityRef
55 public static function contactReference() {
56 $name = CRM_Utils_Array
::value('term', $_GET);
57 $name = CRM_Utils_Type
::escape($name, 'String');
58 $cfID = CRM_Utils_Type
::escape($_GET['id'], 'Positive');
60 // check that this is a valid, active custom field of Contact Reference type
61 $params = ['id' => $cfID];
62 $returnProperties = ['filter', 'data_type', 'is_active'];
64 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $cf, $returnProperties);
65 if (!$cf['id'] ||
!$cf['is_active'] ||
$cf['data_type'] != 'ContactReference') {
66 CRM_Utils_System
::civiExit(1);
69 if (!empty($cf['filter'])) {
71 parse_str($cf['filter'], $filterParams);
73 $action = CRM_Utils_Array
::value('action', $filterParams);
74 if (!empty($action) && !in_array($action, ['get', 'lookup'])) {
75 CRM_Utils_System
::civiExit(1);
78 if (!empty($filterParams['group'])) {
79 $filterParams['group'] = explode(',', $filterParams['group']);
83 $list = array_keys(CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
84 'contact_reference_options'
87 $return = array_unique(array_merge(['sort_name'], $list));
89 $limit = Civi
::settings()->get('search_autocomplete_count');
91 $params = ['offset' => 0, 'rowCount' => $limit, 'version' => 3];
92 foreach ($return as $fld) {
93 $params["return.{$fld}"] = 1;
96 if (!empty($action)) {
112 foreach ($_GET as $param => $val) {
114 in_array($param, $excludeGet) ||
115 strpos($param, 'return.') !== FALSE ||
116 strpos($param, 'api.') !== FALSE
120 $params[$param] = $val;
125 $params['sort_name'] = $name;
128 $params['sort'] = 'sort_name';
130 // tell api to skip permission chk. dgg
131 $params['check_permissions'] = 0;
133 // add filter variable to params
134 if (!empty($filterParams)) {
135 $params = array_merge($params, $filterParams);
138 $contact = civicrm_api('Contact', 'Get', $params);
140 if (!empty($contact['is_error'])) {
141 CRM_Utils_System
::civiExit(1);
145 foreach ($contact['values'] as $value) {
147 foreach ($return as $fld) {
148 if (!empty($value[$fld])) {
149 $view[] = $value[$fld];
152 $contactList[] = ['id' => $value['id'], 'text' => implode(' :: ', $view)];
155 if (!empty($_GET['is_unit_test'])) {
158 CRM_Utils_JSON
::output($contactList);
162 * Fetch PCP ID by PCP Supporter sort_name, also displays PCP title and associated Contribution Page title
164 public static function getPCPList() {
165 $name = CRM_Utils_Array
::value('term', $_GET);
166 $name = CRM_Utils_Type
::escape($name, 'String');
167 $limit = $max = Civi
::settings()->get('search_autocomplete_count');
169 $where = ' AND pcp.page_id = cp.id AND pcp.contact_id = cc.id';
171 $config = CRM_Core_Config
::singleton();
172 if ($config->includeWildCardInName
) {
173 $strSearch = "%$name%";
176 $strSearch = "$name%";
178 $includeEmailFrom = $includeNickName = '';
179 if ($config->includeNickNameInName
) {
180 $includeNickName = " OR nick_name LIKE '$strSearch'";
182 if ($config->includeEmailInName
) {
183 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
184 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
187 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
190 $offset = $count = 0;
191 if (!empty($_GET['page_num'])) {
192 $page = (int) $_GET['page_num'];
193 $offset = $limit * ($page - 1);
197 $select = 'cc.sort_name, pcp.title, cp.title';
201 SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
202 FROM civicrm_pcp pcp, civicrm_contribution_page cp, civicrm_contact cc
204 {$whereClause} AND pcp.page_type = 'contribute'
206 SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
207 FROM civicrm_pcp pcp, civicrm_event cp, civicrm_contact cc
209 {$whereClause} AND pcp.page_type = 'event'
212 LIMIT $offset, $limit
215 $dao = CRM_Core_DAO
::executeQuery($query);
216 $output = ['results' => [], 'more' => FALSE];
217 while ($dao->fetch()) {
218 if (++
$count > $max) {
219 $output['more'] = TRUE;
222 $output['results'][] = ['id' => $dao->id
, 'text' => $dao->data
];
225 CRM_Utils_JSON
::output($output);
228 public static function relationship() {
229 $relType = CRM_Utils_Request
::retrieve('rel_type', 'String', CRM_Core_DAO
::$_nullObject, TRUE);
230 $relContactID = CRM_Utils_Request
::retrieve('rel_contact', 'Positive', CRM_Core_DAO
::$_nullObject, TRUE);
231 $originalCid = CRM_Utils_Request
::retrieve('cid', 'Positive');
232 $relationshipID = CRM_Utils_Request
::retrieve('rel_id', 'Positive');
233 $caseID = CRM_Utils_Request
::retrieve('case_id', 'Positive', CRM_Core_DAO
::$_nullObject, TRUE);
235 if (!CRM_Case_BAO_Case
::accessCase($caseID)) {
236 CRM_Utils_System
::permissionDenied();
239 $ret = ['is_error' => 0];
241 list($relTypeId, $b, $a) = explode('_', $relType);
243 if ($relationshipID && $originalCid) {
244 CRM_Case_BAO_Case
::endCaseRole($caseID, $a, $originalCid, $relTypeId);
247 $clientList = CRM_Case_BAO_Case
::getCaseClients($caseID);
249 // Loop through multiple case clients
250 foreach ($clientList as $i => $sourceContactID) {
253 'case_id' => $caseID,
254 'relationship_type_id' => $relTypeId,
255 "contact_id_$a" => $relContactID,
256 "contact_id_$b" => $sourceContactID,
257 'sequential' => TRUE,
259 // first check if there is any existing relationship present with same parameters.
260 // If yes then update the relationship by setting active and start date to current time
261 $relationship = civicrm_api3('Relationship', 'get', $params)['values'];
262 $params = array_merge(CRM_Utils_Array
::value(0, $relationship, $params), [
263 'start_date' => 'now',
267 $result = civicrm_api3('relationship', 'create', $params);
269 catch (CiviCRM_API3_Exception
$e) {
270 $ret['is_error'] = 1;
271 $ret['error_message'] = $e->getMessage();
273 // Save activity only for the primary (first) client
274 if ($i == 0 && empty($result['is_error'])) {
275 CRM_Case_BAO_Case
::createCaseRoleActivity($caseID, $result['id'], $relContactID, $sourceContactID);
278 if (!empty($_REQUEST['is_unit_test'])) {
282 CRM_Utils_JSON
::output($ret);
286 * Fetch the custom field help.
288 public static function customField() {
289 $fieldId = CRM_Utils_Type
::escape($_REQUEST['id'], 'Integer');
290 $params = ['id' => $fieldId];
291 $returnProperties = ['help_pre', 'help_post'];
294 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_CustomField', $params, $values, $returnProperties);
295 CRM_Utils_JSON
::output($values);
298 public static function groupTree() {
299 CRM_Utils_System
::setHttpHeader('Content-Type', 'application/json');
300 $gids = CRM_Utils_Type
::escape($_GET['gids'], 'String');
301 echo CRM_Contact_BAO_GroupNestingCache
::json($gids);
302 CRM_Utils_System
::civiExit();
306 * Delete custom value.
308 public static function deleteCustomValue() {
309 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/plain');
310 $customValueID = CRM_Utils_Type
::escape($_REQUEST['valueID'], 'Positive');
311 $customGroupID = CRM_Utils_Type
::escape($_REQUEST['groupID'], 'Positive');
312 $contactId = CRM_Utils_Request
::retrieve('contactId', 'Positive');
313 CRM_Core_BAO_CustomValue
::deleteCustomValue($customValueID, $customGroupID);
315 echo CRM_Contact_BAO_Contact
::getCountComponent('custom_' . $customGroupID, $contactId);
318 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
319 CRM_Utils_System
::civiExit();
323 * check the CMS username.
325 public static function checkUserName() {
326 $signer = new CRM_Utils_Signer(CRM_Core_Key
::privateKey(), ['for', 'ts']);
327 $sig = CRM_Utils_Request
::retrieve('sig', 'String');
328 $for = CRM_Utils_Request
::retrieve('for', 'String');
330 CRM_Utils_Time
::getTimeRaw() > $_REQUEST['ts'] + self
::CHECK_USERNAME_TTL
331 ||
$for != 'civicrm/ajax/cmsuser'
332 ||
!$signer->validate($sig, $_REQUEST)
334 $user = ['name' => 'error'];
335 CRM_Utils_JSON
::output($user);
338 $config = CRM_Core_Config
::singleton();
339 $username = trim(CRM_Utils_Array
::value('cms_name', $_REQUEST));
341 $params = ['name' => $username];
344 $config->userSystem
->checkUserNameEmailExists($params, $errors);
346 if (isset($errors['cms_name']) ||
isset($errors['name'])) {
347 //user name is not available
348 $user = ['name' => 'no'];
349 CRM_Utils_JSON
::output($user);
352 //user name is available
353 $user = ['name' => 'yes'];
354 CRM_Utils_JSON
::output($user);
357 // Not reachable: JSON::output() above exits.
358 CRM_Utils_System
::civiExit();
362 * Function to get email address of a contact.
364 public static function getContactEmail() {
365 if (!empty($_REQUEST['contact_id'])) {
366 $contactID = CRM_Utils_Type
::escape($_REQUEST['contact_id'], 'Positive');
367 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactID, CRM_Core_Permission
::EDIT
)) {
372 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contactID);
374 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/plain');
380 $noemail = CRM_Utils_Array
::value('noemail', $_GET);
382 $name = CRM_Utils_Array
::value('name', $_GET);
384 $name = CRM_Utils_Type
::escape($name, 'String');
386 $queryString = " cc.sort_name LIKE '%$name%'";
389 $queryString = " ( cc.sort_name LIKE '%$name%' OR ce.email LIKE '%$name%' ) ";
393 $cid = CRM_Utils_Array
::value('cid', $_GET);
395 //check cid for integer
396 $contIDS = explode(',', $cid);
397 foreach ($contIDS as $contID) {
398 CRM_Utils_Type
::escape($contID, 'Integer');
400 $queryString = " cc.id IN ( $cid )";
406 $offset = CRM_Utils_Array
::value('offset', $_GET, 0);
407 $rowCount = Civi
::settings()->get('search_autocomplete_count');
409 $offset = CRM_Utils_Type
::escape($offset, 'Int');
411 // add acl clause here
412 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
414 $aclWhere = " AND $aclWhere";
418 SELECT sort_name name, cc.id
419 FROM civicrm_contact cc
421 WHERE cc.is_deceased = 0 AND {$queryString}
423 LIMIT {$offset}, {$rowCount}
426 // send query to hook to be modified if needed
427 CRM_Utils_Hook
::contactListQuery($query,
429 CRM_Utils_Request
::retrieve('context', 'Alphanumeric'),
430 CRM_Utils_Request
::retrieve('cid', 'Positive')
433 $dao = CRM_Core_DAO
::executeQuery($query);
434 while ($dao->fetch()) {
437 'text' => $dao->name
,
443 SELECT sort_name name, ce.email, cc.id
444 FROM civicrm_email ce INNER JOIN civicrm_contact cc ON cc.id = ce.contact_id
446 WHERE ce.on_hold = 0 AND cc.is_deceased = 0 AND cc.do_not_email = 0 AND {$queryString}
448 LIMIT {$offset}, {$rowCount}
451 // send query to hook to be modified if needed
452 CRM_Utils_Hook
::contactListQuery($query,
454 CRM_Utils_Request
::retrieve('context', 'Alphanumeric'),
455 CRM_Utils_Request
::retrieve('cid', 'Positive')
458 $dao = CRM_Core_DAO
::executeQuery($query);
460 while ($dao->fetch()) {
463 'text' => '"' . $dao->name
. '" <' . $dao->email
. '>',
464 'id' => (CRM_Utils_Array
::value('id', $_GET)) ?
"{$dao->id}::{$dao->email}" : '"' . $dao->name
. '" <' . $dao->email
. '>',
468 CRM_Utils_JSON
::output($result);
471 CRM_Utils_System
::civiExit();
474 public static function getContactPhone() {
478 //check for mobile type
479 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
480 $mobileType = CRM_Utils_Array
::value('Mobile', $phoneTypes);
482 $name = CRM_Utils_Request
::retrieveValue('name', 'String', NULL, FALSE, 'GET');
484 $key = (int) count(array_keys($sqlParmas)) +
1;
485 $queryString = " ( cc.sort_name LIKE %{$key} OR cp.phone LIKE %{$key} ) ";
486 $sqlParams[$key] = ['%' . $name . '%', 'String'];
489 $cid = CRM_Utils_Request
::retrieveValue('cid', 'CommaSeparatedIntegers', NULL, FALSE, 'GET');
491 $queryString = " cc.id IN ( $cid )";
497 $offset = (int) CRM_Utils_Request
::retrieveValue('offset', 'Integer', 0, FALSE, 'GET');
498 $rowCount = (int) CRM_Utils_Request
::retrieveValue('rowcount', 'Integer', 20, FALSE, 'GET');
500 // add acl clause here
501 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause('cc');
503 $aclWhere = " AND $aclWhere";
507 SELECT sort_name name, cp.phone, cc.id
508 FROM civicrm_phone cp INNER JOIN civicrm_contact cc ON cc.id = cp.contact_id
510 WHERE cc.is_deceased = 0 AND cc.do_not_sms = 0 AND cp.phone_type_id = {$mobileType} AND {$queryString}
512 LIMIT {$offset}, {$rowCount}
515 // send query to hook to be modified if needed
516 CRM_Utils_Hook
::contactListQuery($query,
518 CRM_Utils_Request
::retrieve('context', 'Alphanumeric'),
519 CRM_Utils_Request
::retrieve('cid', 'Positive')
522 $dao = CRM_Core_DAO
::executeQuery($query, $sqlParams);
524 while ($dao->fetch()) {
526 'text' => '"' . $dao->name
. '" (' . $dao->phone
. ')',
527 'id' => (CRM_Utils_Array
::value('id', $_GET)) ?
"{$dao->id}::{$dao->phone}" : '"' . $dao->name
. '" <' . $dao->phone
. '>',
530 CRM_Utils_JSON
::output($result);
532 CRM_Utils_System
::civiExit();
535 public static function buildSubTypes() {
536 $parent = CRM_Utils_Request
::retrieve('parentId', 'Positive');
540 $contactType = 'Individual';
544 $contactType = 'Household';
548 $contactType = 'Organization';
552 $subTypes = CRM_Contact_BAO_ContactType
::subTypePairs($contactType, FALSE, NULL);
554 CRM_Utils_JSON
::output($subTypes);
557 public static function buildDedupeRules() {
558 $parent = CRM_Utils_Request
::retrieve('parentId', 'Positive');
562 $contactType = 'Individual';
566 $contactType = 'Household';
570 $contactType = 'Organization';
574 $dedupeRules = CRM_Dedupe_BAO_RuleGroup
::getByType($contactType);
576 CRM_Utils_JSON
::output($dedupeRules);
580 * Function used for CiviCRM dashboard operations.
582 public static function dashboard() {
583 switch ($_REQUEST['op']) {
585 CRM_Core_BAO_Dashboard
::saveDashletChanges($_REQUEST['columns']);
588 case 'delete_dashlet':
589 $dashletID = CRM_Utils_Type
::escape($_REQUEST['dashlet_id'], 'Positive');
590 CRM_Core_BAO_Dashboard
::deleteDashlet($dashletID);
593 CRM_Utils_System
::civiExit();
597 * Retrieve signature based on email id.
599 public static function getSignature() {
600 $emailID = CRM_Utils_Type
::escape($_REQUEST['emailID'], 'Positive');
601 $query = "SELECT signature_text, signature_html FROM civicrm_email WHERE id = {$emailID}";
602 $dao = CRM_Core_DAO
::executeQuery($query);
605 while ($dao->fetch()) {
607 'signature_text' => $dao->signature_text
,
608 'signature_html' => $dao->signature_html
,
612 CRM_Utils_JSON
::output($signatures);
618 public static function processDupes() {
619 $oper = CRM_Utils_Type
::escape($_REQUEST['op'], 'String');
620 $cid = CRM_Utils_Type
::escape($_REQUEST['cid'], 'Positive');
621 $oid = CRM_Utils_Type
::escape($_REQUEST['oid'], 'Positive');
623 if (!$oper ||
!$cid ||
!$oid) {
627 $exception = new CRM_Dedupe_DAO_Exception();
628 $exception->contact_id1
= $cid;
629 $exception->contact_id2
= $oid;
630 //make sure contact2 > contact1.
632 $exception->contact_id1
= $oid;
633 $exception->contact_id2
= $cid;
635 $exception->find(TRUE);
637 if ($oper == 'dupe-nondupe') {
638 $status = $exception->save();
640 if ($oper == 'nondupe-dupe') {
641 $status = $exception->delete();
644 CRM_Utils_JSON
::output(['status' => ($status) ?
$oper : $status]);
648 * Retrieve list of duplicate pairs from cache table.
650 public static function getDedupes() {
651 $offset = isset($_REQUEST['start']) ? CRM_Utils_Type
::escape($_REQUEST['start'], 'Integer') : 0;
652 $rowCount = isset($_REQUEST['length']) ? CRM_Utils_Type
::escape($_REQUEST['length'], 'Integer') : 25;
654 $gid = CRM_Utils_Request
::retrieve('gid', 'Positive');
655 $rgid = CRM_Utils_Request
::retrieve('rgid', 'Positive');
657 $criteria = CRM_Utils_Request
::retrieve('criteria', 'Json', $null, FALSE, '{}');
658 $selected = CRM_Utils_Request
::retrieveValue('selected', 'Boolean');
663 $whereClause = $orderByClause = '';
664 $cacheKeyString = CRM_Dedupe_Merger
::getMergeCacheKeyString($rgid, $gid, json_decode($criteria, TRUE));
668 $searchParams = self
::getSearchOptionsFromRequest();
674 $isOrQuery = self
::isOrQuery();
678 'dst' => 'cc1.display_name',
679 'src' => 'cc2.display_name',
680 'dst_email' => 'ce1.email',
681 'src_email' => 'ce2.email',
682 'dst_postcode' => 'ca1.postal_code',
683 'src_postcode' => 'ca2.postal_code',
684 'dst_street' => 'ca1.street',
685 'src_street' => 'ca2.street',
688 foreach ($mappings as $key => $dbName) {
689 if (!empty($searchParams[$key])) {
691 $wildcard = strstr($key, 'postcode') ?
'' : '%';
692 $queryParams[$nextParamKey] = [$wildcard . $searchParams[$key] . '%', 'String'];
693 $where[] = $dbName . " LIKE %{$nextParamKey} ";
699 $whereClause = ' ( ' . implode(' OR ', $where) . ' ) ';
702 if (!empty($where)) {
703 $whereClause = implode(' AND ', $where);
706 $whereClause .= $whereClause ?
' AND de.id IS NULL' : ' de.id IS NULL';
709 $whereClause .= ' AND pn.is_selected = 1';
711 $join .= CRM_Dedupe_Merger
::getJoinOnDedupeTable();
714 'cc1.contact_type' => 'dst_contact_type',
715 'cc1.display_name' => 'dst_display_name',
716 'cc1.contact_sub_type' => 'dst_contact_sub_type',
717 'cc2.contact_type' => 'src_contact_type',
718 'cc2.display_name' => 'src_display_name',
719 'cc2.contact_sub_type' => 'src_contact_sub_type',
720 'ce1.email' => 'dst_email',
721 'ce2.email' => 'src_email',
722 'ca1.postal_code' => 'dst_postcode',
723 'ca2.postal_code' => 'src_postcode',
724 'ca1.street_address' => 'dst_street',
725 'ca2.street_address' => 'src_street',
729 $join .= " INNER JOIN civicrm_contact cc1 ON cc1.id = pn.entity_id1";
730 $join .= " INNER JOIN civicrm_contact cc2 ON cc2.id = pn.entity_id2";
731 $join .= " LEFT JOIN civicrm_email ce1 ON (ce1.contact_id = pn.entity_id1 AND ce1.is_primary = 1 )";
732 $join .= " LEFT JOIN civicrm_email ce2 ON (ce2.contact_id = pn.entity_id2 AND ce2.is_primary = 1 )";
733 $join .= " LEFT JOIN civicrm_address ca1 ON (ca1.contact_id = pn.entity_id1 AND ca1.is_primary = 1 )";
734 $join .= " LEFT JOIN civicrm_address ca2 ON (ca2.contact_id = pn.entity_id2 AND ca2.is_primary = 1 )";
736 $iTotal = CRM_Core_BAO_PrevNextCache
::getCount($cacheKeyString, $join, $whereClause, '=', $queryParams);
737 if (!empty($_REQUEST['order'])) {
738 foreach ($_REQUEST['order'] as $orderInfo) {
739 if (!empty($orderInfo['column'])) {
740 $orderColumnNumber = $orderInfo['column'];
741 $dir = $orderInfo['dir'];
744 $columnDetails = CRM_Utils_Array
::value($orderColumnNumber, $_REQUEST['columns']);
746 if (!empty($columnDetails)) {
747 switch ($columnDetails['data']) {
749 $orderByClause = " ORDER BY cc2.display_name {$dir}";
753 $orderByClause = " ORDER BY ce2.email {$dir}";
757 $orderByClause = " ORDER BY ca2.street_address {$dir}";
761 $orderByClause = " ORDER BY ca2.postal_code {$dir}";
765 $orderByClause = " ORDER BY cc1.display_name {$dir}";
769 $orderByClause = " ORDER BY ce1.email {$dir}";
773 $orderByClause = " ORDER BY ca1.street_address {$dir}";
777 $orderByClause = " ORDER BY ca1.postal_code {$dir}";
781 $orderByClause = " ORDER BY cc1.display_name ASC";
786 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString, $join, $whereClause, $offset, $rowCount, $select, $orderByClause, TRUE, $queryParams);
787 $iFilteredTotal = CRM_Core_DAO
::singleValueQuery("SELECT FOUND_ROWS()");
790 foreach ($dupePairs as $key => $pairInfo) {
791 $pair = $pairInfo['data'];
792 $srcContactSubType = CRM_Utils_Array
::value('src_contact_sub_type', $pairInfo);
793 $dstContactSubType = CRM_Utils_Array
::value('dst_contact_sub_type', $pairInfo);
794 $srcTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage($srcContactSubType ?
795 $srcContactSubType : $pairInfo['src_contact_type'],
797 $pairInfo['entity_id2']
799 $dstTypeImage = CRM_Contact_BAO_Contact_Utils
::getImage($dstContactSubType ?
800 $dstContactSubType : $pairInfo['dst_contact_type'],
802 $pairInfo['entity_id1']
805 $searchRows[$count]['is_selected'] = $pairInfo['is_selected'];
806 $searchRows[$count]['is_selected_input'] = "<input type='checkbox' class='crm-dedupe-select' name='pnid_{$pairInfo['prevnext_id']}' value='{$pairInfo['is_selected']}' onclick='toggleDedupeSelect(this)'>";
807 $searchRows[$count]['src_image'] = $srcTypeImage;
808 $searchRows[$count]['src'] = CRM_Utils_System
::href($pair['srcName'], 'civicrm/contact/view', "reset=1&cid={$pairInfo['entity_id2']}");
809 $searchRows[$count]['src_email'] = CRM_Utils_Array
::value('src_email', $pairInfo);
810 $searchRows[$count]['src_street'] = CRM_Utils_Array
::value('src_street', $pairInfo);
811 $searchRows[$count]['src_postcode'] = CRM_Utils_Array
::value('src_postcode', $pairInfo);
812 $searchRows[$count]['dst_image'] = $dstTypeImage;
813 $searchRows[$count]['dst'] = CRM_Utils_System
::href($pair['dstName'], 'civicrm/contact/view', "reset=1&cid={$pairInfo['entity_id1']}");
814 $searchRows[$count]['dst_email'] = CRM_Utils_Array
::value('dst_email', $pairInfo);
815 $searchRows[$count]['dst_street'] = CRM_Utils_Array
::value('dst_street', $pairInfo);
816 $searchRows[$count]['dst_postcode'] = CRM_Utils_Array
::value('dst_postcode', $pairInfo);
817 $searchRows[$count]['conflicts'] = str_replace("',", "',<br/>", CRM_Utils_Array
::value('conflicts', $pair));
818 $searchRows[$count]['weight'] = CRM_Utils_Array
::value('weight', $pair);
820 if (!empty($pairInfo['data']['canMerge'])) {
823 'cid' => $pairInfo['entity_id1'],
824 'oid' => $pairInfo['entity_id2'],
825 'action' => 'update',
827 'criteria' => $criteria,
828 'limit' => CRM_Utils_Request
::retrieve('limit', 'Integer'),
831 $mergeParams['gid'] = $gid;
834 $searchRows[$count]['actions'] = "<a class='crm-dedupe-flip' href='#' data-pnid={$pairInfo['prevnext_id']}>" . ts('flip') . "</a> | ";
835 $searchRows[$count]['actions'] .= CRM_Utils_System
::href(ts('merge'), 'civicrm/contact/merge', $mergeParams);
836 $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>";
839 $searchRows[$count]['actions'] = '<em>' . ts('Insufficient access rights - cannot merge') . '</em>';
845 'data' => $searchRows,
846 'recordsTotal' => $iTotal,
847 'recordsFiltered' => $iFilteredTotal,
849 if (!empty($_REQUEST['is_unit_test'])) {
852 CRM_Utils_JSON
::output($dupePairs);
856 * Get the searchable options from the request.
860 public static function getSearchOptionsFromRequest() {
862 $searchData = CRM_Utils_Array
::value('search', $_REQUEST);
863 $searchData['value'] = CRM_Utils_Type
::escape($searchData['value'], 'String');
864 $selectorElements = [
881 $columns = $_REQUEST['columns'];
883 foreach ($columns as $column) {
884 if (!empty($column['search']['value']) && in_array($column['data'], $selectorElements)) {
885 $searchParams[$column['data']] = CRM_Utils_Type
::escape($column['search']['value'], 'String');
887 elseif (!empty($searchData['value'])) {
888 $searchParams[$column['data']] = $searchData['value'];
891 return $searchParams;
895 * Is the query an OR query.
897 * If a generic search value is passed in - ie. $_REQUEST['search']['value'] = 'abc'
898 * then all fields are searched for this.
900 * It is unclear if there is any code that still passes this in or whether is is just legacy. It
901 * could cause a server-killing query on a large site so it probably is NOT in use if we haven't
906 public static function isOrQuery() {
907 $searchData = CRM_Utils_Array
::value('search', $_REQUEST);
908 return !empty($searchData['value']);
912 * Retrieve a PDF Page Format for the PDF Letter form.
914 public function pdfFormat() {
915 $formatId = CRM_Utils_Type
::escape($_REQUEST['formatId'], 'Integer');
917 $pdfFormat = CRM_Core_BAO_PdfFormat
::getById($formatId);
919 CRM_Utils_JSON
::output($pdfFormat);
923 * Retrieve Paper Size dimensions.
925 public static function paperSize() {
926 $paperSizeName = CRM_Utils_Type
::escape($_REQUEST['paperSizeName'], 'String');
928 $paperSize = CRM_Core_BAO_PaperSize
::getByName($paperSizeName);
930 CRM_Utils_JSON
::output($paperSize);
934 * Swap contacts in a dupe pair i.e main with duplicate contact.
936 * @param int $prevNextId
938 public static function flipDupePairs($prevNextId = NULL) {
940 // @todo figure out if this is always POST & specify that rather than inexact GET
942 // We cannot use CRM_Utils_Request::retrieve() because it might be an array.
943 // It later gets validated in escapeAll below.
944 $prevNextId = $_REQUEST['pnid'];
947 $onlySelected = FALSE;
948 if (is_array($prevNextId) && !CRM_Utils_Array
::crmIsEmptyArray($prevNextId)) {
949 $onlySelected = TRUE;
951 $prevNextId = CRM_Utils_Type
::escapeAll((array) $prevNextId, 'Positive');
952 CRM_Core_BAO_PrevNextCache
::flipPair($prevNextId, $onlySelected);
953 CRM_Utils_System
::civiExit();
957 * Used to store selected contacts across multiple pages in advanced search.
959 public static function selectUnselectContacts() {
960 $name = CRM_Utils_Array
::value('name', $_REQUEST);
961 $cacheKey = CRM_Utils_Array
::value('qfKey', $_REQUEST);
962 $state = CRM_Utils_Array
::value('state', $_REQUEST, 'checked');
963 $variableType = CRM_Utils_Array
::value('variableType', $_REQUEST, 'single');
965 $actionToPerform = CRM_Utils_Array
::value('action', $_REQUEST, 'select');
967 if ($variableType == 'multiple') {
968 // action post value only works with multiple type variable
970 //multiple names like mark_x_1-mark_x_2 where 1,2 are cids
971 $elements = explode('-', $name);
972 foreach ($elements as $key => $element) {
973 $elements[$key] = self
::_convertToId($element);
975 CRM_Utils_Type
::escapeAll($elements, 'Integer');
976 Civi
::service('prevnext')->markSelection($cacheKey, $actionToPerform, $elements);
979 Civi
::service('prevnext')->markSelection($cacheKey, $actionToPerform);
982 elseif ($variableType == 'single') {
983 $cId = self
::_convertToId($name);
984 CRM_Utils_Type
::escape($cId, 'Integer');
985 $action = ($state == 'checked') ?
'select' : 'unselect';
986 Civi
::service('prevnext')->markSelection($cacheKey, $action, $cId);
988 $contactIds = Civi
::service('prevnext')->getSelection($cacheKey);
989 $countSelectionCids = count($contactIds[$cacheKey]);
991 $arrRet = ['getCount' => $countSelectionCids];
992 CRM_Utils_JSON
::output($arrRet);
996 * @param string $name
1000 public static function _convertToId($name) {
1001 if (substr($name, 0, CRM_Core_Form
::CB_PREFIX_LEN
) == CRM_Core_Form
::CB_PREFIX
) {
1002 $cId = substr($name, CRM_Core_Form
::CB_PREFIX_LEN
);
1007 public static function getAddressDisplay() {
1008 $contactId = CRM_Utils_Request
::retrieve('contact_id', 'Positive');
1010 $addressVal["error_message"] = "no contact id found";
1014 'contact_id' => $contactId,
1015 'entity_id' => $contactId,
1017 $addressVal = CRM_Core_BAO_Address
::getValues($entityBlock);
1020 CRM_Utils_JSON
::output($addressVal);
1024 * Mark dupe pairs as selected from un-selected state or vice-versa, in dupe cache table.
1026 public static function toggleDedupeSelect() {
1027 $pnid = $_REQUEST['pnid'];
1028 $isSelected = CRM_Utils_Type
::escape($_REQUEST['is_selected'], 'Boolean');
1029 $cacheKeyString = CRM_Utils_Request
::retrieve('cacheKey', 'Alphanumeric', $null, FALSE);
1032 1 => [$isSelected, 'Boolean'],
1033 // using % to address rows with conflicts as well
1034 3 => ["$cacheKeyString%", 'String'],
1037 //check pnid is_array or integer
1038 $whereClause = NULL;
1039 if (is_array($pnid) && !CRM_Utils_Array
::crmIsEmptyArray($pnid)) {
1040 CRM_Utils_Type
::escapeAll($pnid, 'Positive');
1041 $pnid = implode(', ', $pnid);
1042 $whereClause = " id IN ( {$pnid} ) ";
1045 $pnid = CRM_Utils_Type
::escape($pnid, 'Integer');
1046 $whereClause = " id = %2";
1047 $params[2] = [$pnid, 'Integer'];
1050 $sql = "UPDATE civicrm_prevnext_cache SET is_selected = %1 WHERE {$whereClause} AND cacheKey LIKE %3";
1051 CRM_Core_DAO
::executeQuery($sql, $params);
1053 CRM_Utils_System
::civiExit();
1057 * Retrieve contact relationships.
1059 public static function getContactRelationships() {
1060 $contactID = CRM_Utils_Type
::escape($_GET['cid'], 'Integer');
1061 $context = CRM_Utils_Request
::retrieve('context', 'Alphanumeric');
1062 $relationship_type_id = CRM_Utils_Type
::escape(CRM_Utils_Array
::value('relationship_type_id', $_GET), 'Integer', FALSE);
1064 if (!CRM_Contact_BAO_Contact_Permission
::allow($contactID)) {
1065 return CRM_Utils_System
::permissionDenied();
1068 $params = CRM_Core_Page_AJAX
::defaultSortAndPagerParams();
1070 $params['contact_id'] = $contactID;
1071 $params['context'] = $context;
1072 if ($relationship_type_id) {
1073 $params['relationship_type_id'] = $relationship_type_id;
1076 // get the contact relationships
1077 $relationships = CRM_Contact_BAO_Relationship
::getContactRelationshipSelector($params);
1079 CRM_Utils_JSON
::output($relationships);