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