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