Merge pull request #8633 from totten/master-fts-empty-to
[civicrm-core.git] / CRM / Contact / Page / AJAX.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
6a488035
TO
32 *
33 */
34
35/**
36 * This class contains all contact related functions that are called using AJAX (jQuery)
37 */
38class CRM_Contact_Page_AJAX {
272081ca
TO
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
b1dba111
TO
46 const AUTOCOMPLETE_TTL = 21600; // 6hr; 6*60*60
47
06508628 48 /**
06508628
CW
49 * Ajax callback for custom fields of type ContactReference
50 *
51 * Todo: Migrate contact reference fields to use EntityRef
52 */
00be9182 53 public static function contactReference() {
06508628 54 $name = CRM_Utils_Array::value('term', $_GET);
6a488035
TO
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
06508628 59 $params = array('id' => $cfID);
6a488035 60 $returnProperties = array('filter', 'data_type', 'is_active');
06508628 61 $cf = array();
6a488035 62 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $cf, $returnProperties);
a4cce21a 63 if (!$cf['id'] || !$cf['is_active'] || $cf['data_type'] != 'ContactReference') {
06508628 64 CRM_Utils_System::civiExit('error');
6a488035
TO
65 }
66
9624538c 67 if (!empty($cf['filter'])) {
6a488035
TO
68 $filterParams = array();
69 parse_str($cf['filter'], $filterParams);
70
71 $action = CRM_Utils_Array::value('action', $filterParams);
da0136df 72 if (!empty($action) && !in_array($action, array('get', 'lookup'))) {
06508628 73 CRM_Utils_System::civiExit('error');
6a488035 74 }
da0136df 75
76 if (!empty($filterParams['group'])) {
77 $filterParams['group'] = explode(',', $filterParams['group']);
78 }
6a488035
TO
79 }
80
81 $list = array_keys(CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
353ffa53
TO
82 'contact_reference_options'
83 ), '1');
6a488035
TO
84
85 $return = array_unique(array_merge(array('sort_name'), $list));
86
89595c92 87 $limit = Civi::settings()->get('search_autocomplete_count');
6a488035
TO
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)) {
353ffa53
TO
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',
408b79bf 108 'action',
353ffa53 109 );
6a488035
TO
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
a7488080 138 if (!empty($contact['is_error'])) {
06508628 139 CRM_Utils_System::civiExit('error');
6a488035
TO
140 }
141
d6408252 142 $contactList = array();
6a488035
TO
143 foreach ($contact['values'] as $value) {
144 $view = array();
145 foreach ($return as $fld) {
a7488080 146 if (!empty($value[$fld])) {
6a488035
TO
147 $view[] = $value[$fld];
148 }
149 }
06508628 150 $contactList[] = array('id' => $value['id'], 'text' => implode(' :: ', $view));
6a488035
TO
151 }
152
da0136df 153 if (!empty($_GET['is_unit_test'])) {
154 return $contactList;
155 }
8be1a839 156 CRM_Utils_JSON::output($contactList);
6a488035
TO
157 }
158
159 /**
100fef9d 160 * Fetch PCP ID by PCP Supporter sort_name, also displays PCP title and associated Contribution Page title
6a488035 161 */
00be9182 162 public static function getPCPList() {
7d86179d 163 $name = CRM_Utils_Array::value('term', $_GET);
353ffa53 164 $name = CRM_Utils_Type::escape($name, 'String');
89595c92 165 $limit = $max = Civi::settings()->get('search_autocomplete_count');
6a488035
TO
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
8da35492 188 $offset = $count = 0;
4feb1cad
CW
189 if (!empty($_GET['page_num'])) {
190 $page = (int) $_GET['page_num'];
8da35492
CW
191 $offset = $limit * ($page - 1);
192 $limit++;
6a488035
TO
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}
900e6829 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'
6a488035
TO
208 ) t
209 ORDER BY sort_name
8da35492 210 LIMIT $offset, $limit
6a488035
TO
211 ";
212
213 $dao = CRM_Core_DAO::executeQuery($query);
8da35492 214 $output = array('results' => array(), 'more' => FALSE);
6a488035 215 while ($dao->fetch()) {
8da35492
CW
216 if (++$count > $max) {
217 $output['more'] = TRUE;
218 }
219 else {
220 $output['results'][] = array('id' => $dao->id, 'text' => $dao->data);
221 }
6a488035 222 }
8da35492 223 CRM_Utils_JSON::output($output);
6a488035
TO
224 }
225
00be9182 226 public static function relationship() {
3b1c37fe 227 $relType = CRM_Utils_Request::retrieve('rel_type', 'String', CRM_Core_DAO::$_nullObject, TRUE);
c91df8b4 228 $relContactID = CRM_Utils_Request::retrieve('rel_contact', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
3b1c37fe
CW
229 $originalCid = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject);
230 $relationshipID = CRM_Utils_Request::retrieve('rel_id', 'Positive', CRM_Core_DAO::$_nullObject);
c91df8b4 231 $caseID = CRM_Utils_Request::retrieve('case_id', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
6a488035 232
3b1c37fe
CW
233 if (!CRM_Case_BAO_Case::accessCase($caseID)) {
234 CRM_Utils_System::permissionDenied();
235 }
6a488035 236
c91df8b4
CW
237 $ret = array('is_error' => 0);
238
3b1c37fe 239 list($relTypeId, $b, $a) = explode('_', $relType);
14a679f1 240
3b1c37fe
CW
241 if ($relationshipID && $originalCid) {
242 CRM_Case_BAO_Case::endCaseRole($caseID, $a, $originalCid, $relTypeId);
243 }
14a679f1 244
3b1c37fe 245 $clientList = CRM_Case_BAO_Case::getCaseClients($caseID);
14a679f1 246
3b1c37fe
CW
247 // Loop through multiple case clients
248 foreach ($clientList as $i => $sourceContactID) {
bb76ee5a
FG
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 }
3b1c37fe
CW
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);
c91df8b4 265 }
6a488035 266 }
6a488035 267
ecdef330 268 CRM_Utils_JSON::output($ret);
6a488035
TO
269 }
270
271 /**
fe482240 272 * Fetch the custom field help.
6a488035 273 */
00be9182 274 public static function customField() {
353ffa53
TO
275 $fieldId = CRM_Utils_Type::escape($_REQUEST['id'], 'Integer');
276 $params = array('id' => $fieldId);
6a488035 277 $returnProperties = array('help_pre', 'help_post');
353ffa53 278 $values = array();
6a488035
TO
279
280 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $values, $returnProperties);
ecdef330 281 CRM_Utils_JSON::output($values);
6a488035
TO
282 }
283
00be9182 284 public static function groupTree() {
d42a224c 285 CRM_Utils_System::setHttpHeader('Content-Type', 'application/json');
6a488035
TO
286 $gids = CRM_Utils_Type::escape($_GET['gids'], 'String');
287 echo CRM_Contact_BAO_GroupNestingCache::json($gids);
288 CRM_Utils_System::civiExit();
289 }
290
6a488035 291 /**
fe482240 292 * Delete custom value.
6a488035 293 */
00be9182 294 public static function deleteCustomValue() {
d42a224c 295 CRM_Utils_System::setHttpHeader('Content-Type', 'text/plain');
6a488035
TO
296 $customValueID = CRM_Utils_Type::escape($_REQUEST['valueID'], 'Positive');
297 $customGroupID = CRM_Utils_Type::escape($_REQUEST['groupID'], 'Positive');
015bf0da 298 $contactId = CRM_Utils_Request::retrieve('contactId', 'Positive', CRM_Core_DAO::$_nullObject);
6a488035 299 CRM_Core_BAO_CustomValue::deleteCustomValue($customValueID, $customGroupID);
a4cce21a 300 if ($contactId) {
7fa9167d 301 echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $customGroupID, $contactId);
6a488035
TO
302 }
303
2b68a50c 304 CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
6a488035
TO
305 CRM_Utils_System::civiExit();
306 }
307
6a488035 308 /**
fe482240 309 * check the CMS username.
ce80b209 310 */
6a488035 311 static public function checkUserName() {
272081ca 312 $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('for', 'ts'));
7fa9167d 313 $sig = CRM_Utils_Request::retrieve('sig', 'String', CRM_Core_DAO::$_nullObject);
314 $for = CRM_Utils_Request::retrieve('for', 'String', CRM_Core_DAO::$_nullObject);
272081ca
TO
315 if (
316 CRM_Utils_Time::getTimeRaw() > $_REQUEST['ts'] + self::CHECK_USERNAME_TTL
7fa9167d 317 || $for != 'civicrm/ajax/cmsuser'
318 || !$signer->validate($sig, $_REQUEST)
272081ca
TO
319 ) {
320 $user = array('name' => 'error');
8be1a839 321 CRM_Utils_JSON::output($user);
272081ca
TO
322 }
323
6a488035 324 $config = CRM_Core_Config::singleton();
4c68cf7b 325 $username = trim(CRM_Utils_Array::value('cms_name', $_REQUEST));
6a488035
TO
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'])) {
b44e3f84 333 //user name is not available
6a488035 334 $user = array('name' => 'no');
8be1a839 335 CRM_Utils_JSON::output($user);
6a488035
TO
336 }
337 else {
338 //user name is available
339 $user = array('name' => 'yes');
8be1a839 340 CRM_Utils_JSON::output($user);
6a488035 341 }
8be1a839
TO
342
343 // Not reachable: JSON::output() above exits.
6a488035
TO
344 CRM_Utils_System::civiExit();
345 }
346
347 /**
fe482240 348 * Function to get email address of a contact.
6a488035 349 */
00be9182 350 public static function getContactEmail() {
a7488080 351 if (!empty($_REQUEST['contact_id'])) {
6a488035 352 $contactID = CRM_Utils_Type::escape($_REQUEST['contact_id'], 'Positive');
8c0ea1d7
TO
353 if (!CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::EDIT)) {
354 return;
355 }
6a488035
TO
356 list($displayName,
357 $userEmail
353ffa53 358 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
effdc2d9 359
d42a224c 360 CRM_Utils_System::setHttpHeader('Content-Type', 'text/plain');
6a488035
TO
361 if ($userEmail) {
362 echo $userEmail;
363 }
364 }
365 else {
366 $noemail = CRM_Utils_Array::value('noemail', $_GET);
367 $queryString = NULL;
a4cce21a
JM
368 $name = CRM_Utils_Array::value('name', $_GET);
369 if ($name) {
6a488035
TO
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 }
a4cce21a 378 else {
d75f2f47
EM
379 $cid = CRM_Utils_Array::value('cid', $_GET);
380 if ($cid) {
b44e3f84 381 //check cid for integer
a4cce21a
JM
382 $contIDS = explode(',', $cid);
383 foreach ($contIDS as $contID) {
384 CRM_Utils_Type::escape($contID, 'Integer');
385 }
386 $queryString = " cc.id IN ( $cid )";
d75f2f47 387 }
6a488035
TO
388 }
389
390 if ($queryString) {
391 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
89595c92 392 $rowCount = Civi::settings()->get('search_autocomplete_count');
6a488035 393
bf00d1b6 394 $offset = CRM_Utils_Type::escape($offset, 'Int');
bf00d1b6 395
6a488035
TO
396 // add acl clause here
397 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
398 if ($aclWhere) {
399 $aclWhere = " AND $aclWhere";
400 }
401 if ($noemail) {
402 $query = "
403SELECT sort_name name, cc.id
404FROM civicrm_contact cc
405 {$aclFrom}
406WHERE cc.is_deceased = 0 AND {$queryString}
407 {$aclWhere}
408LIMIT {$offset}, {$rowCount}
409";
410
411 // send query to hook to be modified if needed
412 CRM_Utils_Hook::contactListQuery($query,
413 $name,
7fa9167d 414 CRM_Utils_Request::retrieve('context', 'String', CRM_Core_DAO::$_nullObject),
415 CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject)
6a488035
TO
416 );
417
418 $dao = CRM_Core_DAO::executeQuery($query);
419 while ($dao->fetch()) {
420 $result[] = array(
6a488035 421 'id' => $dao->id,
cac1236c 422 'text' => $dao->name,
6a488035
TO
423 );
424 }
425 }
426 else {
427 $query = "
428SELECT sort_name name, ce.email, cc.id
429FROM civicrm_email ce INNER JOIN civicrm_contact cc ON cc.id = ce.contact_id
430 {$aclFrom}
431WHERE ce.on_hold = 0 AND cc.is_deceased = 0 AND cc.do_not_email = 0 AND {$queryString}
432 {$aclWhere}
433LIMIT {$offset}, {$rowCount}
434";
435
436 // send query to hook to be modified if needed
437 CRM_Utils_Hook::contactListQuery($query,
438 $name,
7fa9167d 439 CRM_Utils_Request::retrieve('context', 'String', CRM_Core_DAO::$_nullObject),
015bf0da 440 CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject)
6a488035
TO
441 );
442
6a488035
TO
443 $dao = CRM_Core_DAO::executeQuery($query);
444
445 while ($dao->fetch()) {
ce80b209 446 //working here
6a488035 447 $result[] = array(
cac1236c 448 'text' => '"' . $dao->name . '" <' . $dao->email . '>',
6a488035
TO
449 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->email}" : '"' . $dao->name . '" <' . $dao->email . '>',
450 );
451 }
452 }
6a488035 453 if ($result) {
8be1a839 454 CRM_Utils_JSON::output($result);
6a488035
TO
455 }
456 }
457 }
458 CRM_Utils_System::civiExit();
459 }
460
00be9182 461 public static function getContactPhone() {
6a488035
TO
462
463 $queryString = NULL;
464 //check for mobile type
465 $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
466 $mobileType = CRM_Utils_Array::value('Mobile', $phoneTypes);
467
a4cce21a
JM
468 $name = CRM_Utils_Array::value('name', $_GET);
469 if ($name) {
6a488035
TO
470 $name = CRM_Utils_Type::escape($name, 'String');
471 $queryString = " ( cc.sort_name LIKE '%$name%' OR cp.phone LIKE '%$name%' ) ";
472 }
a4cce21a 473 else {
d75f2f47
EM
474 $cid = CRM_Utils_Array::value('cid', $_GET);
475 if ($cid) {
b44e3f84 476 //check cid for integer
a4cce21a
JM
477 $contIDS = explode(',', $cid);
478 foreach ($contIDS as $contID) {
479 CRM_Utils_Type::escape($contID, 'Integer');
480 }
481 $queryString = " cc.id IN ( $cid )";
6a488035 482 }
6a488035
TO
483 }
484
485 if ($queryString) {
486 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
487 $rowCount = CRM_Utils_Array::value('rowcount', $_GET, 20);
488
bf00d1b6
DL
489 $offset = CRM_Utils_Type::escape($offset, 'Int');
490 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
491
6a488035
TO
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,
7fa9167d 510 CRM_Utils_Request::retrieve('context', 'String', CRM_Core_DAO::$_nullObject),
015bf0da 511 CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject)
6a488035
TO
512 );
513
514 $dao = CRM_Core_DAO::executeQuery($query);
515
516 while ($dao->fetch()) {
517 $result[] = array(
b792e485 518 'text' => '"' . $dao->name . '" (' . $dao->phone . ')',
6a488035
TO
519 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->phone}" : '"' . $dao->name . '" <' . $dao->phone . '>',
520 );
521 }
522 }
523
524 if ($result) {
8be1a839 525 CRM_Utils_JSON::output($result);
6a488035
TO
526 }
527 CRM_Utils_System::civiExit();
528 }
529
530
00be9182 531 public static function buildSubTypes() {
7fa9167d 532 $parent = CRM_Utils_Request::retrieve('parentId', 'Positive', CRM_Core_DAO::$_nullObject);
6a488035
TO
533
534 switch ($parent) {
535 case 1:
536 $contactType = 'Individual';
537 break;
538
539 case 2:
540 $contactType = 'Household';
541 break;
542
543 case 4:
544 $contactType = 'Organization';
545 break;
546 }
547
548 $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($contactType, FALSE, NULL);
549 asort($subTypes);
ecdef330 550 CRM_Utils_JSON::output($subTypes);
6a488035
TO
551 }
552
00be9182 553 public static function buildDedupeRules() {
015bf0da 554 $parent = CRM_Utils_Request::retrieve('parentId', 'Positive', CRM_Core_DAO::$_nullObject);
6a488035
TO
555
556 switch ($parent) {
557 case 1:
558 $contactType = 'Individual';
559 break;
560
561 case 2:
562 $contactType = 'Household';
563 break;
564
565 case 4:
566 $contactType = 'Organization';
567 break;
568 }
569
570 $dedupeRules = CRM_Dedupe_BAO_RuleGroup::getByType($contactType);
571
ecdef330 572 CRM_Utils_JSON::output($dedupeRules);
6a488035
TO
573 }
574
575 /**
fe482240 576 * Function used for CiviCRM dashboard operations.
6a488035 577 */
00be9182 578 public static function dashboard() {
ce2cc43e 579 switch ($_REQUEST['op']) {
6a488035
TO
580 case 'save_columns':
581 CRM_Core_BAO_Dashboard::saveDashletChanges($_REQUEST['columns']);
ce2cc43e
CW
582 break;
583
6a488035
TO
584 case 'delete_dashlet':
585 $dashletID = CRM_Utils_Type::escape($_REQUEST['dashlet_id'], 'Positive');
586 CRM_Core_BAO_Dashboard::deleteDashlet($dashletID);
6a488035
TO
587 }
588
ce2cc43e 589 CRM_Utils_System::civiExit();
6a488035
TO
590 }
591
592 /**
fe482240 593 * Retrieve signature based on email id.
6a488035 594 */
00be9182 595 public static function getSignature() {
6a488035 596 $emailID = CRM_Utils_Type::escape($_REQUEST['emailID'], 'Positive');
353ffa53
TO
597 $query = "SELECT signature_text, signature_html FROM civicrm_email WHERE id = {$emailID}";
598 $dao = CRM_Core_DAO::executeQuery($query);
6a488035
TO
599
600 $signatures = array();
601 while ($dao->fetch()) {
602 $signatures = array(
603 'signature_text' => $dao->signature_text,
604 'signature_html' => $dao->signature_html,
605 );
606 }
607
ecdef330 608 CRM_Utils_JSON::output($signatures);
6a488035
TO
609 }
610
611 /**
100fef9d 612 * Process dupes.
6a488035 613 */
00be9182 614 public static function processDupes() {
6a488035 615 $oper = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
353ffa53
TO
616 $cid = CRM_Utils_Type::escape($_REQUEST['cid'], 'Positive');
617 $oid = CRM_Utils_Type::escape($_REQUEST['oid'], 'Positive');
6a488035
TO
618
619 if (!$oper || !$cid || !$oid) {
620 return;
621 }
622
623 $exception = new CRM_Dedupe_DAO_Exception();
624 $exception->contact_id1 = $cid;
625 $exception->contact_id2 = $oid;
626 //make sure contact2 > contact1.
627 if ($cid > $oid) {
628 $exception->contact_id1 = $oid;
629 $exception->contact_id2 = $cid;
630 }
631 $exception->find(TRUE);
632 $status = NULL;
633 if ($oper == 'dupe-nondupe') {
634 $status = $exception->save();
635 }
636 if ($oper == 'nondupe-dupe') {
637 $status = $exception->delete();
638 }
639
ecdef330 640 CRM_Utils_JSON::output(array('status' => ($status) ? $oper : $status));
6a488035
TO
641 }
642
183ec330 643 /**
644 * Retrieve list of duplicate pairs from cache table.
645 */
00be9182 646 public static function getDedupes() {
63ef778e 647 $offset = isset($_REQUEST['start']) ? CRM_Utils_Type::escape($_REQUEST['start'], 'Integer') : 0;
648 $rowCount = isset($_REQUEST['length']) ? CRM_Utils_Type::escape($_REQUEST['length'], 'Integer') : 25;
6a488035 649
dc6285d5 650 $gid = CRM_Utils_Request::retrieve('gid', 'Positive');
651 $rgid = CRM_Utils_Request::retrieve('rgid', 'Positive');
63ef778e 652 $selected = isset($_REQUEST['selected']) ? CRM_Utils_Type::escape($_REQUEST['selected'], 'Integer') : 0;
653 if ($rowCount < 0) {
654 $rowCount = 0;
655 }
6a488035 656
1f51ef4e 657 $whereClause = $orderByClause = '';
e23e26ec 658 $cacheKeyString = CRM_Dedupe_Merger::getMergeCacheKeyString($rgid, $gid);
63ef778e 659 $searchRows = array();
6a488035 660
ed92673b 661 $searchParams = self::getSearchOptionsFromRequest();
662 $queryParams = array();
663
63ef778e 664 $join = '';
665 $where = array();
579ea9bc 666
ed92673b 667 $isOrQuery = self::isOrQuery();
668
669 $nextParamKey = 3;
670 $mappings = array(
e67dcaf8 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',
ed92673b 679 );
680
681 foreach ($mappings as $key => $dbName) {
682 if (!empty($searchParams[$key])) {
12af7add 683 // CRM-18694.
684 $wildcard = strstr($key, 'postcode') ? '' : '%';
685 $queryParams[$nextParamKey] = array($wildcard . $searchParams[$key] . '%', 'String');
ed92673b 686 $where[] = $dbName . " LIKE %{$nextParamKey} ";
687 $nextParamKey++;
688 }
63ef778e 689 }
ed92673b 690
691 if ($isOrQuery) {
f931b74c 692 $whereClause = ' ( ' . implode(' OR ', $where) . ' ) ';
63ef778e 693 }
694 else {
695 if (!empty($where)) {
696 $whereClause = implode(' AND ', $where);
697 }
f931b74c 698 }
63ef778e 699 $whereClause .= $whereClause ? ' AND de.id IS NULL' : ' de.id IS NULL';
6a488035 700
63ef778e 701 if ($selected) {
702 $whereClause .= ' AND pn.is_selected = 1';
703 }
2988f5c7 704 $join .= CRM_Dedupe_Merger::getJoinOnDedupeTable();
63ef778e 705
63ef778e 706 $select = array(
e67dcaf8 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',
63ef778e 719 );
720
f931b74c 721 if ($select) {
63ef778e 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 }
ed92673b 729 $iTotal = CRM_Core_BAO_PrevNextCache::getCount($cacheKeyString, $join, $whereClause, '=', $queryParams);
1f51ef4e 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 }
63ef778e 736 }
1f51ef4e 737 $columnDetails = CRM_Utils_Array::value($orderColumnNumber, $_REQUEST['columns']);
63ef778e 738 }
f931b74c 739 if (!empty($columnDetails)) {
63ef778e 740 switch ($columnDetails['data']) {
f931b74c 741 case 'src':
e67dcaf8 742 $orderByClause = " ORDER BY cc2.display_name {$dir}";
f931b74c 743 break;
744
745 case 'src_email':
e67dcaf8 746 $orderByClause = " ORDER BY ce2.email {$dir}";
f931b74c 747 break;
748
749 case 'src_street':
e67dcaf8 750 $orderByClause = " ORDER BY ca2.street_address {$dir}";
f931b74c 751 break;
752
753 case 'src_postcode':
e67dcaf8 754 $orderByClause = " ORDER BY ca2.postal_code {$dir}";
f931b74c 755 break;
756
757 case 'dst':
e67dcaf8 758 $orderByClause = " ORDER BY cc1.display_name {$dir}";
f931b74c 759 break;
760
761 case 'dst_email':
e67dcaf8 762 $orderByClause = " ORDER BY ce1.email {$dir}";
f931b74c 763 break;
764
765 case 'dst_street':
e67dcaf8 766 $orderByClause = " ORDER BY ca1.street_address {$dir}";
f931b74c 767 break;
768
769 case 'dst_postcode':
e67dcaf8 770 $orderByClause = " ORDER BY ca1.postal_code {$dir}";
f931b74c 771 break;
772
773 default:
063ffcb7 774 $orderByClause = " ORDER BY cc1.display_name ASC";
f931b74c 775 break;
63ef778e 776 }
777 }
6a488035 778
ed92673b 779 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $whereClause, $offset, $rowCount, $select, $orderByClause, TRUE, $queryParams);
63ef778e 780 $iFilteredTotal = CRM_Core_DAO::singleValueQuery("SELECT FOUND_ROWS()");
6a488035 781
63ef778e 782 $count = 0;
783 foreach ($dupePairs as $key => $pairInfo) {
e67dcaf8 784 $pair = $pairInfo['data'];
63ef778e 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,
e67dcaf8 790 $pairInfo['entity_id2']
63ef778e 791 );
792 $dstTypeImage = CRM_Contact_BAO_Contact_Utils::getImage($dstContactSubType ?
793 $dstContactSubType : $pairInfo['dst_contact_type'],
794 FALSE,
e67dcaf8 795 $pairInfo['entity_id1']
63ef778e 796 );
6a488035 797
63ef778e 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;
e67dcaf8 801 $searchRows[$count]['src'] = CRM_Utils_System::href($pair['srcName'], 'civicrm/contact/view', "reset=1&cid={$pairInfo['entity_id2']}");
63ef778e 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;
e67dcaf8 806 $searchRows[$count]['dst'] = CRM_Utils_System::href($pair['dstName'], 'civicrm/contact/view', "reset=1&cid={$pairInfo['entity_id1']}");
63ef778e 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);
da3afd4a 810 $searchRows[$count]['conflicts'] = str_replace("',", "',<br/>", CRM_Utils_Array::value('conflicts', $pair));
63ef778e 811 $searchRows[$count]['weight'] = CRM_Utils_Array::value('weight', $pair);
812
fd630ef9 813 if (!empty($pairInfo['data']['canMerge'])) {
dc6285d5 814 $mergeParams = "reset=1&cid={$pairInfo['entity_id1']}&oid={$pairInfo['entity_id2']}&action=update&rgid={$rgid}&limit=" . CRM_Utils_Request::retrieve('limit', 'Integer');
6a488035
TO
815 if ($gid) {
816 $mergeParams .= "&gid={$gid}";
817 }
818
fd630ef9 819 $searchRows[$count]['actions'] = "<a class='crm-dedupe-flip' href='#' data-pnid={$pairInfo['prevnext_id']}>" . ts('flip') . "</a>&nbsp;|&nbsp;";
da3afd4a 820 $searchRows[$count]['actions'] .= CRM_Utils_System::href(ts('merge'), 'civicrm/contact/merge', $mergeParams);
fd630ef9 821 $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>";
6a488035
TO
822 }
823 else {
63ef778e 824 $searchRows[$count]['actions'] = '<em>' . ts('Insufficient access rights - cannot merge') . '</em>';
6a488035 825 }
63ef778e 826 $count++;
6a488035
TO
827 }
828
22b232f3 829 $dupePairs = array(
830 'data' => $searchRows,
831 'recordsTotal' => $iTotal,
832 'recordsFiltered' => $iFilteredTotal,
833 );
1f51ef4e 834 if (!empty($_REQUEST['is_unit_test'])) {
835 return $dupePairs;
836 }
22b232f3 837 CRM_Utils_JSON::output($dupePairs);
6a488035
TO
838 }
839
ed92673b 840 /**
841 * Get the searchable options from the request.
842 *
843 * @return array
844 */
845 public static function getSearchOptionsFromRequest() {
846 $searchParams = array();
847 $searchData = CRM_Utils_Array::value('search', $_REQUEST);
848 $searchData['value'] = CRM_Utils_Type::escape($searchData['value'], 'String');
849 $selectorElements = array(
850 'is_selected',
851 'is_selected_input',
852 'src_image',
853 'src',
854 'src_email',
855 'src_street',
856 'src_postcode',
857 'dst_image',
858 'dst',
859 'dst_email',
860 'dst_street',
861 'dst_postcode',
862 'conflicts',
863 'weight',
864 'actions',
865 );
866 $columns = $_REQUEST['columns'];
867
868 foreach ($columns as $column) {
869 if (!empty($column['search']['value']) && in_array($column['data'], $selectorElements)) {
870 $searchParams[$column['data']] = CRM_Utils_Type::escape($column['search']['value'], 'String');
871 }
872 elseif (!empty($searchData['value'])) {
873 $searchParams[$column['data']] = $searchData['value'];
874 }
875 }
876 return $searchParams;
877 }
878
879 /**
880 * Is the query an OR query.
881 *
882 * If a generic search value is passed in - ie. $_REQUEST['search']['value'] = 'abc'
883 * then all fields are searched for this.
884 *
885 * It is unclear if there is any code that still passes this in or whether is is just legacy. It
886 * could cause a server-killing query on a large site so it probably is NOT in use if we haven't
887 * had complaints.
888 *
889 * @return bool
890 */
891 public static function isOrQuery() {
892 $searchData = CRM_Utils_Array::value('search', $_REQUEST);
893 return !empty($searchData['value']);
894 }
895
6a488035 896 /**
fe482240 897 * Retrieve a PDF Page Format for the PDF Letter form.
6a488035 898 */
00be9182 899 public function pdfFormat() {
6a488035
TO
900 $formatId = CRM_Utils_Type::escape($_REQUEST['formatId'], 'Integer');
901
902 $pdfFormat = CRM_Core_BAO_PdfFormat::getById($formatId);
903
ecdef330 904 CRM_Utils_JSON::output($pdfFormat);
6a488035
TO
905 }
906
907 /**
fe482240 908 * Retrieve Paper Size dimensions.
6a488035 909 */
00be9182 910 public static function paperSize() {
6a488035
TO
911 $paperSizeName = CRM_Utils_Type::escape($_REQUEST['paperSizeName'], 'String');
912
913 $paperSize = CRM_Core_BAO_PaperSize::getByName($paperSizeName);
914
ecdef330 915 CRM_Utils_JSON::output($paperSize);
6a488035
TO
916 }
917
183ec330 918 /**
919 * Swap contacts in a dupe pair i.e main with duplicate contact.
ea3ddccf 920 *
921 * @param int $prevNextId
183ec330 922 */
f931b74c 923 public static function flipDupePairs($prevNextId = NULL) {
fd630ef9 924 if (!$prevNextId) {
808c05a9 925 // @todo figure out if this is always POST & specify that rather than inexact GET
926 $prevNextId = CRM_Utils_Request::retrieve('pnid', 'Integer');
fd630ef9 927 }
808c05a9 928
929 $onlySelected = FALSE;
fd630ef9 930 if (is_array($prevNextId) && !CRM_Utils_Array::crmIsEmptyArray($prevNextId)) {
808c05a9 931 $onlySelected = TRUE;
fd630ef9 932 }
808c05a9 933 $prevNextId = CRM_Utils_Type::escapeAll((array) $prevNextId, 'Positive');
934 CRM_Core_BAO_PrevNextCache::flipPair($prevNextId, $onlySelected);
558cd7c7 935 CRM_Utils_System::civiExit();
fd630ef9 936 }
937
aeb97cc1
CW
938 /**
939 * Used to store selected contacts across multiple pages in advanced search.
940 */
00be9182 941 public static function selectUnselectContacts() {
353ffa53
TO
942 $name = CRM_Utils_Array::value('name', $_REQUEST);
943 $cacheKey = CRM_Utils_Array::value('qfKey', $_REQUEST);
944 $state = CRM_Utils_Array::value('state', $_REQUEST, 'checked');
6a488035
TO
945 $variableType = CRM_Utils_Array::value('variableType', $_REQUEST, 'single');
946
947 $actionToPerform = CRM_Utils_Array::value('action', $_REQUEST, 'select');
948
949 if ($variableType == 'multiple') {
950 // action post value only works with multiple type variable
951 if ($name) {
952 //multiple names like mark_x_1-mark_x_2 where 1,2 are cids
953 $elements = explode('-', $name);
954 foreach ($elements as $key => $element) {
955 $elements[$key] = self::_convertToId($element);
956 }
91209206 957 CRM_Utils_Type::escapeAll($elements, 'Integer');
6a488035
TO
958 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $actionToPerform, $elements);
959 }
960 else {
961 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $actionToPerform);
962 }
963 }
964 elseif ($variableType == 'single') {
965 $cId = self::_convertToId($name);
91209206 966 CRM_Utils_Type::escape($cId, 'Integer');
6a488035
TO
967 $action = ($state == 'checked') ? 'select' : 'unselect';
968 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $action, $cId);
969 }
970 $contactIds = CRM_Core_BAO_PrevNextCache::getSelection($cacheKey);
971 $countSelectionCids = count($contactIds[$cacheKey]);
972
973 $arrRet = array('getCount' => $countSelectionCids);
ecdef330 974 CRM_Utils_JSON::output($arrRet);
6a488035
TO
975 }
976
4319322b 977 /**
100fef9d 978 * @param string $name
4319322b
EM
979 *
980 * @return string
981 */
00be9182 982 public static function _convertToId($name) {
6a488035
TO
983 if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
984 $cId = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
985 }
986 return $cId;
987 }
988
00be9182 989 public static function getAddressDisplay() {
7fa9167d 990 $contactId = CRM_Utils_Request::retrieve('contact_id', 'Positive', CRM_Core_DAO::$_nullObject);
6a488035
TO
991 if (!$contactId) {
992 $addressVal["error_message"] = "no contact id found";
993 }
994 else {
408b79bf 995 $entityBlock = array(
996 'contact_id' => $contactId,
997 'entity_id' => $contactId,
998 );
6a488035
TO
999 $addressVal = CRM_Core_BAO_Address::getValues($entityBlock);
1000 }
1001
ecdef330 1002 CRM_Utils_JSON::output($addressVal);
6a488035 1003 }
40458f6c 1004
183ec330 1005 /**
1006 * Mark dupe pairs as selected from un-selected state or vice-versa, in dupe cache table.
1007 */
f931b74c 1008 public static function toggleDedupeSelect() {
63ef778e 1009 $rgid = CRM_Utils_Type::escape($_REQUEST['rgid'], 'Integer');
1010 $gid = CRM_Utils_Type::escape($_REQUEST['gid'], 'Integer');
1011 $pnid = $_REQUEST['pnid'];
1012 $isSelected = CRM_Utils_Type::escape($_REQUEST['is_selected'], 'Boolean');
1013
2ae26001 1014 $cacheKeyString = CRM_Dedupe_Merger::getMergeCacheKeyString($rgid, $gid);
63ef778e 1015
1016 $params = array(
1017 1 => array($isSelected, 'Boolean'),
f931b74c 1018 3 => array("$cacheKeyString%", 'String'), // using % to address rows with conflicts as well
63ef778e 1019 );
1020
1021 //check pnid is_array or integer
1022 $whereClause = NULL;
1023 if (is_array($pnid) && !CRM_Utils_Array::crmIsEmptyArray($pnid)) {
13c42e60 1024 CRM_Utils_Type::escapeAll($pnid, 'Positive');
63ef778e 1025 $pnid = implode(', ', $pnid);
63ef778e 1026 $whereClause = " id IN ( {$pnid} ) ";
1027 }
1028 else {
1029 $pnid = CRM_Utils_Type::escape($pnid, 'Integer');
1030 $whereClause = " id = %2";
1031 $params[2] = array($pnid, 'Integer');
1032 }
1033
1034 $sql = "UPDATE civicrm_prevnext_cache SET is_selected = %1 WHERE {$whereClause} AND cacheKey LIKE %3";
1035 CRM_Core_DAO::executeQuery($sql, $params);
1036
1037 CRM_Utils_System::civiExit();
1038 }
1039
40458f6c 1040 /**
fe482240 1041 * Retrieve contact relationships.
40458f6c 1042 */
1043 public static function getContactRelationships() {
1044 $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
1045 $context = CRM_Utils_Type::escape($_GET['context'], 'String');
7d12de7f 1046 $relationship_type_id = CRM_Utils_Type::escape(CRM_Utils_Array::value('relationship_type_id', $_GET), 'Integer', FALSE);
40458f6c 1047
b0266403
CW
1048 if (!CRM_Contact_BAO_Contact_Permission::allow($contactID)) {
1049 return CRM_Utils_System::permissionDenied();
1050 }
1051
00f11506 1052 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
40458f6c 1053
1054 $params['contact_id'] = $contactID;
1055 $params['context'] = $context;
4c5f31d0 1056 if ($relationship_type_id) {
cdee9432
TM
1057 $params['relationship_type_id'] = $relationship_type_id;
1058 }
40458f6c 1059
1060 // get the contact relationships
1061 $relationships = CRM_Contact_BAO_Relationship::getContactRelationshipSelector($params);
1062
7d12de7f 1063 CRM_Utils_JSON::output($relationships);
40458f6c 1064 }
96025800 1065
6a488035 1066}