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