Merge pull request #14249 from yashodha/959_dev
[civicrm-core.git] / CRM / Contact / Page / AJAX.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 *
33 */
34
35 /**
36 * This class contains all contact related functions that are called using AJAX (jQuery)
37 */
38 class CRM_Contact_Page_AJAX {
39 /**
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).
43 */
44 // 3hr; 3*60*60
45 const CHECK_USERNAME_TTL = 10800;
46
47 // 6hr; 6*60*60
48 const AUTOCOMPLETE_TTL = 21600;
49
50 /**
51 * Ajax callback for custom fields of type ContactReference
52 *
53 * Todo: Migrate contact reference fields to use EntityRef
54 */
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');
59
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'];
63 $cf = [];
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);
67 }
68
69 if (!empty($cf['filter'])) {
70 $filterParams = [];
71 parse_str($cf['filter'], $filterParams);
72
73 $action = CRM_Utils_Array::value('action', $filterParams);
74 if (!empty($action) && !in_array($action, ['get', 'lookup'])) {
75 CRM_Utils_System::civiExit(1);
76 }
77
78 if (!empty($filterParams['group'])) {
79 $filterParams['group'] = explode(',', $filterParams['group']);
80 }
81 }
82
83 $list = array_keys(CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
84 'contact_reference_options'
85 ), '1');
86
87 $return = array_unique(array_merge(['sort_name'], $list));
88
89 $limit = Civi::settings()->get('search_autocomplete_count');
90
91 $params = ['offset' => 0, 'rowCount' => $limit, 'version' => 3];
92 foreach ($return as $fld) {
93 $params["return.{$fld}"] = 1;
94 }
95
96 if (!empty($action)) {
97 $excludeGet = [
98 'reset',
99 'key',
100 'className',
101 'fnName',
102 'json',
103 'reset',
104 'context',
105 'timestamp',
106 'limit',
107 'id',
108 's',
109 'q',
110 'action',
111 ];
112 foreach ($_GET as $param => $val) {
113 if (empty($val) ||
114 in_array($param, $excludeGet) ||
115 strpos($param, 'return.') !== FALSE ||
116 strpos($param, 'api.') !== FALSE
117 ) {
118 continue;
119 }
120 $params[$param] = $val;
121 }
122 }
123
124 if ($name) {
125 $params['sort_name'] = $name;
126 }
127
128 $params['sort'] = 'sort_name';
129
130 // tell api to skip permission chk. dgg
131 $params['check_permissions'] = 0;
132
133 // add filter variable to params
134 if (!empty($filterParams)) {
135 $params = array_merge($params, $filterParams);
136 }
137
138 $contact = civicrm_api('Contact', 'Get', $params);
139
140 if (!empty($contact['is_error'])) {
141 CRM_Utils_System::civiExit(1);
142 }
143
144 $contactList = [];
145 foreach ($contact['values'] as $value) {
146 $view = [];
147 foreach ($return as $fld) {
148 if (!empty($value[$fld])) {
149 $view[] = $value[$fld];
150 }
151 }
152 $contactList[] = ['id' => $value['id'], 'text' => implode(' :: ', $view)];
153 }
154
155 if (!empty($_GET['is_unit_test'])) {
156 return $contactList;
157 }
158 CRM_Utils_JSON::output($contactList);
159 }
160
161 /**
162 * Fetch PCP ID by PCP Supporter sort_name, also displays PCP title and associated Contribution Page title
163 */
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');
168
169 $where = ' AND pcp.page_id = cp.id AND pcp.contact_id = cc.id';
170
171 $config = CRM_Core_Config::singleton();
172 if ($config->includeWildCardInName) {
173 $strSearch = "%$name%";
174 }
175 else {
176 $strSearch = "$name%";
177 }
178 $includeEmailFrom = $includeNickName = '';
179 if ($config->includeNickNameInName) {
180 $includeNickName = " OR nick_name LIKE '$strSearch'";
181 }
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} ";
185 }
186 else {
187 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
188 }
189
190 $offset = $count = 0;
191 if (!empty($_GET['page_num'])) {
192 $page = (int) $_GET['page_num'];
193 $offset = $limit * ($page - 1);
194 $limit++;
195 }
196
197 $select = 'cc.sort_name, pcp.title, cp.title';
198 $query = "
199 SELECT id, data
200 FROM (
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
203 {$includeEmailFrom}
204 {$whereClause} AND pcp.page_type = 'contribute'
205 UNION ALL
206 SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
207 FROM civicrm_pcp pcp, civicrm_event cp, civicrm_contact cc
208 {$includeEmailFrom}
209 {$whereClause} AND pcp.page_type = 'event'
210 ) t
211 ORDER BY sort_name
212 LIMIT $offset, $limit
213 ";
214
215 $dao = CRM_Core_DAO::executeQuery($query);
216 $output = ['results' => [], 'more' => FALSE];
217 while ($dao->fetch()) {
218 if (++$count > $max) {
219 $output['more'] = TRUE;
220 }
221 else {
222 $output['results'][] = ['id' => $dao->id, 'text' => $dao->data];
223 }
224 }
225 CRM_Utils_JSON::output($output);
226 }
227
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);
234
235 if (!CRM_Case_BAO_Case::accessCase($caseID)) {
236 CRM_Utils_System::permissionDenied();
237 }
238
239 $ret = ['is_error' => 0];
240
241 list($relTypeId, $b, $a) = explode('_', $relType);
242
243 if ($relationshipID && $originalCid) {
244 CRM_Case_BAO_Case::endCaseRole($caseID, $a, $originalCid, $relTypeId);
245 }
246
247 $clientList = CRM_Case_BAO_Case::getCaseClients($caseID);
248
249 // Loop through multiple case clients
250 foreach ($clientList as $i => $sourceContactID) {
251 try {
252 $params = [
253 'case_id' => $caseID,
254 'relationship_type_id' => $relTypeId,
255 "contact_id_$a" => $relContactID,
256 "contact_id_$b" => $sourceContactID,
257 'sequential' => TRUE,
258 ];
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',
264 'is_active' => TRUE,
265 'end_date' => '',
266 ]);
267 $result = civicrm_api3('relationship', 'create', $params);
268 }
269 catch (CiviCRM_API3_Exception $e) {
270 $ret['is_error'] = 1;
271 $ret['error_message'] = $e->getMessage();
272 }
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);
276 }
277 }
278 if (!empty($_REQUEST['is_unit_test'])) {
279 return $ret;
280 }
281
282 CRM_Utils_JSON::output($ret);
283 }
284
285 /**
286 * Fetch the custom field help.
287 */
288 public static function customField() {
289 $fieldId = CRM_Utils_Type::escape($_REQUEST['id'], 'Integer');
290 $params = ['id' => $fieldId];
291 $returnProperties = ['help_pre', 'help_post'];
292 $values = [];
293
294 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $values, $returnProperties);
295 CRM_Utils_JSON::output($values);
296 }
297
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();
303 }
304
305 /**
306 * Delete custom value.
307 */
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);
314 if ($contactId) {
315 echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $customGroupID, $contactId);
316 }
317
318 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
319 CRM_Utils_System::civiExit();
320 }
321
322 /**
323 * check the CMS username.
324 */
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');
329 if (
330 CRM_Utils_Time::getTimeRaw() > $_REQUEST['ts'] + self::CHECK_USERNAME_TTL
331 || $for != 'civicrm/ajax/cmsuser'
332 || !$signer->validate($sig, $_REQUEST)
333 ) {
334 $user = ['name' => 'error'];
335 CRM_Utils_JSON::output($user);
336 }
337
338 $config = CRM_Core_Config::singleton();
339 $username = trim(CRM_Utils_Array::value('cms_name', $_REQUEST));
340
341 $params = ['name' => $username];
342
343 $errors = [];
344 $config->userSystem->checkUserNameEmailExists($params, $errors);
345
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);
350 }
351 else {
352 //user name is available
353 $user = ['name' => 'yes'];
354 CRM_Utils_JSON::output($user);
355 }
356
357 // Not reachable: JSON::output() above exits.
358 CRM_Utils_System::civiExit();
359 }
360
361 /**
362 * Function to get email address of a contact.
363 */
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)) {
368 return;
369 }
370 list($displayName,
371 $userEmail
372 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
373
374 CRM_Utils_System::setHttpHeader('Content-Type', 'text/plain');
375 if ($userEmail) {
376 echo $userEmail;
377 }
378 }
379 else {
380 $noemail = CRM_Utils_Array::value('noemail', $_GET);
381 $queryString = NULL;
382 $name = CRM_Utils_Array::value('name', $_GET);
383 if ($name) {
384 $name = CRM_Utils_Type::escape($name, 'String');
385 if ($noemail) {
386 $queryString = " cc.sort_name LIKE '%$name%'";
387 }
388 else {
389 $queryString = " ( cc.sort_name LIKE '%$name%' OR ce.email LIKE '%$name%' ) ";
390 }
391 }
392 else {
393 $cid = CRM_Utils_Array::value('cid', $_GET);
394 if ($cid) {
395 //check cid for integer
396 $contIDS = explode(',', $cid);
397 foreach ($contIDS as $contID) {
398 CRM_Utils_Type::escape($contID, 'Integer');
399 }
400 $queryString = " cc.id IN ( $cid )";
401 }
402 }
403
404 if ($queryString) {
405 $result = [];
406 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
407 $rowCount = Civi::settings()->get('search_autocomplete_count');
408
409 $offset = CRM_Utils_Type::escape($offset, 'Int');
410
411 // add acl clause here
412 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
413 if ($aclWhere) {
414 $aclWhere = " AND $aclWhere";
415 }
416 if ($noemail) {
417 $query = "
418 SELECT sort_name name, cc.id
419 FROM civicrm_contact cc
420 {$aclFrom}
421 WHERE cc.is_deceased = 0 AND {$queryString}
422 {$aclWhere}
423 LIMIT {$offset}, {$rowCount}
424 ";
425
426 // send query to hook to be modified if needed
427 CRM_Utils_Hook::contactListQuery($query,
428 $name,
429 CRM_Utils_Request::retrieve('context', 'Alphanumeric'),
430 CRM_Utils_Request::retrieve('cid', 'Positive')
431 );
432
433 $dao = CRM_Core_DAO::executeQuery($query);
434 while ($dao->fetch()) {
435 $result[] = [
436 'id' => $dao->id,
437 'text' => $dao->name,
438 ];
439 }
440 }
441 else {
442 $query = "
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
445 {$aclFrom}
446 WHERE ce.on_hold = 0 AND cc.is_deceased = 0 AND cc.do_not_email = 0 AND {$queryString}
447 {$aclWhere}
448 LIMIT {$offset}, {$rowCount}
449 ";
450
451 // send query to hook to be modified if needed
452 CRM_Utils_Hook::contactListQuery($query,
453 $name,
454 CRM_Utils_Request::retrieve('context', 'Alphanumeric'),
455 CRM_Utils_Request::retrieve('cid', 'Positive')
456 );
457
458 $dao = CRM_Core_DAO::executeQuery($query);
459
460 while ($dao->fetch()) {
461 //working here
462 $result[] = [
463 'text' => '"' . $dao->name . '" <' . $dao->email . '>',
464 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->email}" : '"' . $dao->name . '" <' . $dao->email . '>',
465 ];
466 }
467 }
468 CRM_Utils_JSON::output($result);
469 }
470 }
471 CRM_Utils_System::civiExit();
472 }
473
474 public static function getContactPhone() {
475
476 $queryString = NULL;
477 $sqlParmas = [];
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);
481
482 $name = CRM_Utils_Request::retrieveValue('name', 'String', NULL, FALSE, 'GET');
483 if ($name) {
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'];
487 }
488 else {
489 $cid = CRM_Utils_Request::retrieveValue('cid', 'CommaSeparatedIntegers', NULL, FALSE, 'GET');
490 if ($cid) {
491 $queryString = " cc.id IN ( $cid )";
492 }
493 }
494
495 if ($queryString) {
496 $result = [];
497 $offset = (int) CRM_Utils_Request::retrieveValue('offset', 'Integer', 0, FALSE, 'GET');
498 $rowCount = (int) CRM_Utils_Request::retrieveValue('rowcount', 'Integer', 20, FALSE, 'GET');
499
500 // add acl clause here
501 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
502 if ($aclWhere) {
503 $aclWhere = " AND $aclWhere";
504 }
505
506 $query = "
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
509 {$aclFrom}
510 WHERE cc.is_deceased = 0 AND cc.do_not_sms = 0 AND cp.phone_type_id = {$mobileType} AND {$queryString}
511 {$aclWhere}
512 LIMIT {$offset}, {$rowCount}
513 ";
514
515 // send query to hook to be modified if needed
516 CRM_Utils_Hook::contactListQuery($query,
517 $name,
518 CRM_Utils_Request::retrieve('context', 'Alphanumeric'),
519 CRM_Utils_Request::retrieve('cid', 'Positive')
520 );
521
522 $dao = CRM_Core_DAO::executeQuery($query, $sqlParams);
523
524 while ($dao->fetch()) {
525 $result[] = [
526 'text' => '"' . $dao->name . '" (' . $dao->phone . ')',
527 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->phone}" : '"' . $dao->name . '" <' . $dao->phone . '>',
528 ];
529 }
530 CRM_Utils_JSON::output($result);
531 }
532 CRM_Utils_System::civiExit();
533 }
534
535 public static function buildSubTypes() {
536 $parent = CRM_Utils_Request::retrieve('parentId', 'Positive');
537
538 switch ($parent) {
539 case 1:
540 $contactType = 'Individual';
541 break;
542
543 case 2:
544 $contactType = 'Household';
545 break;
546
547 case 4:
548 $contactType = 'Organization';
549 break;
550 }
551
552 $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($contactType, FALSE, NULL);
553 asort($subTypes);
554 CRM_Utils_JSON::output($subTypes);
555 }
556
557 public static function buildDedupeRules() {
558 $parent = CRM_Utils_Request::retrieve('parentId', 'Positive');
559
560 switch ($parent) {
561 case 1:
562 $contactType = 'Individual';
563 break;
564
565 case 2:
566 $contactType = 'Household';
567 break;
568
569 case 4:
570 $contactType = 'Organization';
571 break;
572 }
573
574 $dedupeRules = CRM_Dedupe_BAO_RuleGroup::getByType($contactType);
575
576 CRM_Utils_JSON::output($dedupeRules);
577 }
578
579 /**
580 * Function used for CiviCRM dashboard operations.
581 */
582 public static function dashboard() {
583 switch ($_REQUEST['op']) {
584 case 'save_columns':
585 CRM_Core_BAO_Dashboard::saveDashletChanges($_REQUEST['columns']);
586 break;
587
588 case 'delete_dashlet':
589 $dashletID = CRM_Utils_Type::escape($_REQUEST['dashlet_id'], 'Positive');
590 CRM_Core_BAO_Dashboard::deleteDashlet($dashletID);
591 }
592
593 CRM_Utils_System::civiExit();
594 }
595
596 /**
597 * Retrieve signature based on email id.
598 */
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);
603
604 $signatures = [];
605 while ($dao->fetch()) {
606 $signatures = [
607 'signature_text' => $dao->signature_text,
608 'signature_html' => $dao->signature_html,
609 ];
610 }
611
612 CRM_Utils_JSON::output($signatures);
613 }
614
615 /**
616 * Process dupes.
617 */
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');
622
623 if (!$oper || !$cid || !$oid) {
624 return;
625 }
626
627 $exception = new CRM_Dedupe_DAO_Exception();
628 $exception->contact_id1 = $cid;
629 $exception->contact_id2 = $oid;
630 //make sure contact2 > contact1.
631 if ($cid > $oid) {
632 $exception->contact_id1 = $oid;
633 $exception->contact_id2 = $cid;
634 }
635 $exception->find(TRUE);
636 $status = NULL;
637 if ($oper == 'dupe-nondupe') {
638 $status = $exception->save();
639 }
640 if ($oper == 'nondupe-dupe') {
641 $status = $exception->delete();
642 }
643
644 CRM_Utils_JSON::output(['status' => ($status) ? $oper : $status]);
645 }
646
647 /**
648 * Retrieve list of duplicate pairs from cache table.
649 */
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;
653
654 $gid = CRM_Utils_Request::retrieve('gid', 'Positive');
655 $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive');
656 $null = NULL;
657 $criteria = CRM_Utils_Request::retrieve('criteria', 'Json', $null, FALSE, '{}');
658 $selected = CRM_Utils_Request::retrieveValue('selected', 'Boolean');
659 if ($rowCount < 0) {
660 $rowCount = 0;
661 }
662
663 $whereClause = $orderByClause = '';
664 $cacheKeyString = CRM_Dedupe_Merger::getMergeCacheKeyString($rgid, $gid, json_decode($criteria, TRUE));
665
666 $searchRows = [];
667
668 $searchParams = self::getSearchOptionsFromRequest();
669 $queryParams = [];
670
671 $join = '';
672 $where = [];
673
674 $isOrQuery = self::isOrQuery();
675
676 $nextParamKey = 3;
677 $mappings = [
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',
686 ];
687
688 foreach ($mappings as $key => $dbName) {
689 if (!empty($searchParams[$key])) {
690 // CRM-18694.
691 $wildcard = strstr($key, 'postcode') ? '' : '%';
692 $queryParams[$nextParamKey] = [$wildcard . $searchParams[$key] . '%', 'String'];
693 $where[] = $dbName . " LIKE %{$nextParamKey} ";
694 $nextParamKey++;
695 }
696 }
697
698 if ($isOrQuery) {
699 $whereClause = ' ( ' . implode(' OR ', $where) . ' ) ';
700 }
701 else {
702 if (!empty($where)) {
703 $whereClause = implode(' AND ', $where);
704 }
705 }
706 $whereClause .= $whereClause ? ' AND de.id IS NULL' : ' de.id IS NULL';
707
708 if ($selected) {
709 $whereClause .= ' AND pn.is_selected = 1';
710 }
711 $join .= CRM_Dedupe_Merger::getJoinOnDedupeTable();
712
713 $select = [
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',
726 ];
727
728 if ($select) {
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 )";
735 }
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'];
742 }
743 }
744 $columnDetails = CRM_Utils_Array::value($orderColumnNumber, $_REQUEST['columns']);
745 }
746 if (!empty($columnDetails)) {
747 switch ($columnDetails['data']) {
748 case 'src':
749 $orderByClause = " ORDER BY cc2.display_name {$dir}";
750 break;
751
752 case 'src_email':
753 $orderByClause = " ORDER BY ce2.email {$dir}";
754 break;
755
756 case 'src_street':
757 $orderByClause = " ORDER BY ca2.street_address {$dir}";
758 break;
759
760 case 'src_postcode':
761 $orderByClause = " ORDER BY ca2.postal_code {$dir}";
762 break;
763
764 case 'dst':
765 $orderByClause = " ORDER BY cc1.display_name {$dir}";
766 break;
767
768 case 'dst_email':
769 $orderByClause = " ORDER BY ce1.email {$dir}";
770 break;
771
772 case 'dst_street':
773 $orderByClause = " ORDER BY ca1.street_address {$dir}";
774 break;
775
776 case 'dst_postcode':
777 $orderByClause = " ORDER BY ca1.postal_code {$dir}";
778 break;
779
780 default:
781 $orderByClause = " ORDER BY cc1.display_name ASC";
782 break;
783 }
784 }
785
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()");
788
789 $count = 0;
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'],
796 FALSE,
797 $pairInfo['entity_id2']
798 );
799 $dstTypeImage = CRM_Contact_BAO_Contact_Utils::getImage($dstContactSubType ?
800 $dstContactSubType : $pairInfo['dst_contact_type'],
801 FALSE,
802 $pairInfo['entity_id1']
803 );
804
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);
819
820 if (!empty($pairInfo['data']['canMerge'])) {
821 $mergeParams = [
822 'reset' => 1,
823 'cid' => $pairInfo['entity_id1'],
824 'oid' => $pairInfo['entity_id2'],
825 'action' => 'update',
826 'rgid' => $rgid,
827 'criteria' => $criteria,
828 'limit' => CRM_Utils_Request::retrieve('limit', 'Integer'),
829 ];
830 if ($gid) {
831 $mergeParams['gid'] = $gid;
832 }
833
834 $searchRows[$count]['actions'] = "<a class='crm-dedupe-flip' href='#' data-pnid={$pairInfo['prevnext_id']}>" . ts('flip') . "</a>&nbsp;|&nbsp;";
835 $searchRows[$count]['actions'] .= CRM_Utils_System::href(ts('merge'), 'civicrm/contact/merge', $mergeParams);
836 $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>";
837 }
838 else {
839 $searchRows[$count]['actions'] = '<em>' . ts('Insufficient access rights - cannot merge') . '</em>';
840 }
841 $count++;
842 }
843
844 $dupePairs = [
845 'data' => $searchRows,
846 'recordsTotal' => $iTotal,
847 'recordsFiltered' => $iFilteredTotal,
848 ];
849 if (!empty($_REQUEST['is_unit_test'])) {
850 return $dupePairs;
851 }
852 CRM_Utils_JSON::output($dupePairs);
853 }
854
855 /**
856 * Get the searchable options from the request.
857 *
858 * @return array
859 */
860 public static function getSearchOptionsFromRequest() {
861 $searchParams = [];
862 $searchData = CRM_Utils_Array::value('search', $_REQUEST);
863 $searchData['value'] = CRM_Utils_Type::escape($searchData['value'], 'String');
864 $selectorElements = [
865 'is_selected',
866 'is_selected_input',
867 'src_image',
868 'src',
869 'src_email',
870 'src_street',
871 'src_postcode',
872 'dst_image',
873 'dst',
874 'dst_email',
875 'dst_street',
876 'dst_postcode',
877 'conflicts',
878 'weight',
879 'actions',
880 ];
881 $columns = $_REQUEST['columns'];
882
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');
886 }
887 elseif (!empty($searchData['value'])) {
888 $searchParams[$column['data']] = $searchData['value'];
889 }
890 }
891 return $searchParams;
892 }
893
894 /**
895 * Is the query an OR query.
896 *
897 * If a generic search value is passed in - ie. $_REQUEST['search']['value'] = 'abc'
898 * then all fields are searched for this.
899 *
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
902 * had complaints.
903 *
904 * @return bool
905 */
906 public static function isOrQuery() {
907 $searchData = CRM_Utils_Array::value('search', $_REQUEST);
908 return !empty($searchData['value']);
909 }
910
911 /**
912 * Retrieve a PDF Page Format for the PDF Letter form.
913 */
914 public function pdfFormat() {
915 $formatId = CRM_Utils_Type::escape($_REQUEST['formatId'], 'Integer');
916
917 $pdfFormat = CRM_Core_BAO_PdfFormat::getById($formatId);
918
919 CRM_Utils_JSON::output($pdfFormat);
920 }
921
922 /**
923 * Retrieve Paper Size dimensions.
924 */
925 public static function paperSize() {
926 $paperSizeName = CRM_Utils_Type::escape($_REQUEST['paperSizeName'], 'String');
927
928 $paperSize = CRM_Core_BAO_PaperSize::getByName($paperSizeName);
929
930 CRM_Utils_JSON::output($paperSize);
931 }
932
933 /**
934 * Swap contacts in a dupe pair i.e main with duplicate contact.
935 *
936 * @param int $prevNextId
937 */
938 public static function flipDupePairs($prevNextId = NULL) {
939 if (!$prevNextId) {
940 // @todo figure out if this is always POST & specify that rather than inexact GET
941
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'];
945 }
946
947 $onlySelected = FALSE;
948 if (is_array($prevNextId) && !CRM_Utils_Array::crmIsEmptyArray($prevNextId)) {
949 $onlySelected = TRUE;
950 }
951 $prevNextId = CRM_Utils_Type::escapeAll((array) $prevNextId, 'Positive');
952 CRM_Core_BAO_PrevNextCache::flipPair($prevNextId, $onlySelected);
953 CRM_Utils_System::civiExit();
954 }
955
956 /**
957 * Used to store selected contacts across multiple pages in advanced search.
958 */
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');
964
965 $actionToPerform = CRM_Utils_Array::value('action', $_REQUEST, 'select');
966
967 if ($variableType == 'multiple') {
968 // action post value only works with multiple type variable
969 if ($name) {
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);
974 }
975 CRM_Utils_Type::escapeAll($elements, 'Integer');
976 Civi::service('prevnext')->markSelection($cacheKey, $actionToPerform, $elements);
977 }
978 else {
979 Civi::service('prevnext')->markSelection($cacheKey, $actionToPerform);
980 }
981 }
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);
987 }
988 $contactIds = Civi::service('prevnext')->getSelection($cacheKey);
989 $countSelectionCids = count($contactIds[$cacheKey]);
990
991 $arrRet = ['getCount' => $countSelectionCids];
992 CRM_Utils_JSON::output($arrRet);
993 }
994
995 /**
996 * @param string $name
997 *
998 * @return string
999 */
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);
1003 }
1004 return $cId;
1005 }
1006
1007 public static function getAddressDisplay() {
1008 $contactId = CRM_Utils_Request::retrieve('contact_id', 'Positive');
1009 if (!$contactId) {
1010 $addressVal["error_message"] = "no contact id found";
1011 }
1012 else {
1013 $entityBlock = [
1014 'contact_id' => $contactId,
1015 'entity_id' => $contactId,
1016 ];
1017 $addressVal = CRM_Core_BAO_Address::getValues($entityBlock);
1018 }
1019
1020 CRM_Utils_JSON::output($addressVal);
1021 }
1022
1023 /**
1024 * Mark dupe pairs as selected from un-selected state or vice-versa, in dupe cache table.
1025 */
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);
1030
1031 $params = [
1032 1 => [$isSelected, 'Boolean'],
1033 // using % to address rows with conflicts as well
1034 3 => ["$cacheKeyString%", 'String'],
1035 ];
1036
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} ) ";
1043 }
1044 else {
1045 $pnid = CRM_Utils_Type::escape($pnid, 'Integer');
1046 $whereClause = " id = %2";
1047 $params[2] = [$pnid, 'Integer'];
1048 }
1049
1050 $sql = "UPDATE civicrm_prevnext_cache SET is_selected = %1 WHERE {$whereClause} AND cacheKey LIKE %3";
1051 CRM_Core_DAO::executeQuery($sql, $params);
1052
1053 CRM_Utils_System::civiExit();
1054 }
1055
1056 /**
1057 * Retrieve contact relationships.
1058 */
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);
1063
1064 if (!CRM_Contact_BAO_Contact_Permission::allow($contactID)) {
1065 return CRM_Utils_System::permissionDenied();
1066 }
1067
1068 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
1069
1070 $params['contact_id'] = $contactID;
1071 $params['context'] = $context;
1072 if ($relationship_type_id) {
1073 $params['relationship_type_id'] = $relationship_type_id;
1074 }
1075
1076 // get the contact relationships
1077 $relationships = CRM_Contact_BAO_Relationship::getContactRelationshipSelector($params);
1078
1079 CRM_Utils_JSON::output($relationships);
1080 }
1081
1082 }