CRM-15926 - CRM_Contact_Page_AJAX::search - Remove old, unused helper
[civicrm-core.git] / CRM / Contact / Page / AJAX.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 * @deprecated
50 */
51 static function getContactList() {
52 // if context is 'customfield'
53 if (CRM_Utils_Array::value('context', $_GET) == 'customfield') {
54 return self::contactReference();
55 }
56
57 $params = array('version' => 3, 'check_permissions' => TRUE);
58
59 // String params
60 // FIXME: param keys don't match input keys, using this array to translate
61 $whitelist = array(
62 's' => 'name',
63 'fieldName' => 'field_name',
64 'tableName' => 'table_name',
65 'context' => 'context',
66 'rel' => 'rel',
67 'contact_sub_type' => 'contact_sub_type',
68 'contact_type' => 'contact_type'
69 );
70 foreach ($whitelist as $key => $param) {
71 if (!empty($_GET[$key])) {
72 $params[$param] = $_GET[$key];
73 }
74 }
75
76 //CRM-10687: Allow quicksearch by multiple fields
77 if (!empty($params['field_name'])) {
78 if ($params['field_name'] == 'phone_numeric') {
79 $params['name'] = preg_replace('/[^\d]/', '', $params['name']);
80 }
81 if (!$params['name']) {
82 CRM_Utils_System::civiExit();
83 }
84 }
85
86 // Numeric params
87 $whitelist = array(
88 'limit',
89 'org',
90 'employee_id',
91 'cid',
92 'id',
93 'cmsuser',
94 );
95 foreach ($whitelist as $key) {
96 if (!empty($_GET[$key]) && is_numeric($_GET[$key])) {
97 $params[$key] = $_GET[$key];
98 }
99 }
100
101 $result = civicrm_api('Contact', 'getquick', $params);
102 CRM_Core_Page_AJAX::autocompleteResults(CRM_Utils_Array::value('values', $result), 'data');
103 }
104
105 /**
106 * Ajax callback for custom fields of type ContactReference
107 *
108 * Todo: Migrate contact reference fields to use EntityRef
109 */
110 static function contactReference() {
111 $name = CRM_Utils_Array::value('term', $_GET);
112 $name = CRM_Utils_Type::escape($name, 'String');
113 $cfID = CRM_Utils_Type::escape($_GET['id'], 'Positive');
114
115 // check that this is a valid, active custom field of Contact Reference type
116 $params = array('id' => $cfID);
117 $returnProperties = array('filter', 'data_type', 'is_active');
118 $cf = array();
119 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $cf, $returnProperties);
120 if (!$cf['id'] || !$cf['is_active'] || $cf['data_type'] != 'ContactReference') {
121 CRM_Utils_System::civiExit('error');
122 }
123
124 if (!empty($cf['filter'])) {
125 $filterParams = array();
126 parse_str($cf['filter'], $filterParams);
127
128 $action = CRM_Utils_Array::value('action', $filterParams);
129
130 if (!empty($action) &&
131 !in_array($action, array('get', 'lookup'))
132 ) {
133 CRM_Utils_System::civiExit('error');
134 }
135 }
136
137 $list = array_keys(CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
138 'contact_reference_options'
139 ), '1');
140
141 $return = array_unique(array_merge(array('sort_name'), $list));
142
143 $limit = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'search_autocomplete_count', NULL, 10);
144
145 $params = array('offset' => 0, 'rowCount' => $limit, 'version' => 3);
146 foreach ($return as $fld) {
147 $params["return.{$fld}"] = 1;
148 }
149
150 if (!empty($action)) {
151 $excludeGet = array('reset', 'key', 'className', 'fnName', 'json', 'reset', 'context', 'timestamp', 'limit', 'id', 's', 'q', 'action');
152 foreach ($_GET as $param => $val) {
153 if (empty($val) ||
154 in_array($param, $excludeGet) ||
155 strpos($param, 'return.') !== FALSE ||
156 strpos($param, 'api.') !== FALSE
157 ) {
158 continue;
159 }
160 $params[$param] = $val;
161 }
162 }
163
164 if ($name) {
165 $params['sort_name'] = $name;
166 }
167
168 $params['sort'] = 'sort_name';
169
170 // tell api to skip permission chk. dgg
171 $params['check_permissions'] = 0;
172
173 // add filter variable to params
174 if (!empty($filterParams)) {
175 $params = array_merge($params, $filterParams);
176 }
177
178 $contact = civicrm_api('Contact', 'Get', $params);
179
180 if (!empty($contact['is_error'])) {
181 CRM_Utils_System::civiExit('error');
182 }
183
184 $contactList = array();
185 foreach ($contact['values'] as $value) {
186 $view = array();
187 foreach ($return as $fld) {
188 if (!empty($value[$fld])) {
189 $view[] = $value[$fld];
190 }
191 }
192 $contactList[] = array('id' => $value['id'], 'text' => implode(' :: ', $view));
193 }
194
195 CRM_Utils_JSON::output($contactList);
196 }
197
198 /**
199 * Function to fetch PCP ID by PCP Supporter sort_name, also displays PCP title and associated Contribution Page title
200 */
201 static function getPCPList() {
202 $name = CRM_Utils_Array::value('term', $_GET);
203 $name = CRM_Utils_Type::escape($name, 'String');
204 $limit = '10';
205
206 $where = ' AND pcp.page_id = cp.id AND pcp.contact_id = cc.id';
207
208 $config = CRM_Core_Config::singleton();
209 if ($config->includeWildCardInName) {
210 $strSearch = "%$name%";
211 }
212 else {
213 $strSearch = "$name%";
214 }
215 $includeEmailFrom = $includeNickName = '';
216 if ($config->includeNickNameInName) {
217 $includeNickName = " OR nick_name LIKE '$strSearch'";
218 }
219 if ($config->includeEmailInName) {
220 $includeEmailFrom = "LEFT JOIN civicrm_email eml ON ( cc.id = eml.contact_id AND eml.is_primary = 1 )";
221 $whereClause = " WHERE ( email LIKE '$strSearch' OR sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
222 }
223 else {
224 $whereClause = " WHERE ( sort_name LIKE '$strSearch' $includeNickName ) {$where} ";
225 }
226
227 if (!empty($_GET['limit'])) {
228 $limit = CRM_Utils_Type::escape($_GET['limit'], 'Positive');
229 }
230
231 $select = 'cc.sort_name, pcp.title, cp.title';
232 $query = "
233 SELECT id, data
234 FROM (
235 SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
236 FROM civicrm_pcp pcp, civicrm_contribution_page cp, civicrm_contact cc
237 {$includeEmailFrom}
238 {$whereClause} AND pcp.page_type = 'contribute'
239 UNION ALL
240 SELECT pcp.id as id, CONCAT_WS( ' :: ', {$select} ) as data, sort_name
241 FROM civicrm_pcp pcp, civicrm_event cp, civicrm_contact cc
242 {$includeEmailFrom}
243 {$whereClause} AND pcp.page_type = 'event'
244 LIMIT 0, {$limit}
245 ) t
246 ORDER BY sort_name
247 ";
248
249 $dao = CRM_Core_DAO::executeQuery($query);
250 $results = array();
251 while ($dao->fetch()) {
252 $results[] = array('id' => $dao->id, 'text' => $dao->data);
253 }
254 CRM_Utils_JSON::output($results);
255 }
256
257 static function relationship() {
258 $relType = CRM_Utils_Request::retrieve('rel_type', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
259 $relContactID = CRM_Utils_Request::retrieve('rel_contact', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
260 $relationshipID = CRM_Utils_Array::value('rel_id', $_REQUEST); // this used only to determine add or update mode
261 $caseID = CRM_Utils_Request::retrieve('case_id', 'Positive', CRM_Core_DAO::$_nullObject, TRUE);
262
263 // check if there are multiple clients for this case, if so then we need create
264 // relationship and also activities for each contacts
265
266 // get case client list
267 $clientList = CRM_Case_BAO_Case::getCaseClients($caseID);
268
269 $ret = array('is_error' => 0);
270
271 foreach($clientList as $sourceContactID) {
272 $relationParams = array(
273 'relationship_type_id' => $relType . '_a_b',
274 'contact_check' => array($relContactID => 1),
275 'is_active' => 1,
276 'case_id' => $caseID,
277 'start_date' => date("Ymd"),
278 );
279
280 $relationIds = array('contact' => $sourceContactID);
281
282 // check if we are editing/updating existing relationship
283 if ($relationshipID && $relationshipID != 'null') {
284 // here we need to retrieve appropriate relationshipID based on client id and relationship type id
285 $caseRelationships = new CRM_Contact_DAO_Relationship();
286 $caseRelationships->case_id = $caseID;
287 $caseRelationships->relationship_type_id = $relType;
288 $caseRelationships->contact_id_a = $sourceContactID;
289 $caseRelationships->find();
290
291 while($caseRelationships->fetch()) {
292 $relationIds['relationship'] = $caseRelationships->id;
293 $relationIds['contactTarget'] = $relContactID;
294 }
295 $caseRelationships->free();
296 }
297
298 // create new or update existing relationship
299 $return = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds);
300
301 if (!empty($return[4][0])) {
302 $relationshipID = $return[4][0];
303
304 //create an activity for case role assignment.CRM-4480
305 CRM_Case_BAO_Case::createCaseRoleActivity($caseID, $relationshipID, $relContactID);
306 }
307 else {
308 $ret = array(
309 'is_error' => 1,
310 'error_message' => ts('The relationship type definition for the case role is not valid for the client and / or staff contact types. You can review and edit relationship types at <a href="%1">Administer >> Option Lists >> Relationship Types</a>.',
311 array(1 => CRM_Utils_System::url('civicrm/admin/reltype', 'reset=1')))
312 );
313 }
314 }
315
316 CRM_Utils_JSON::output($ret);
317 }
318
319 /**
320 * Function to fetch the custom field help
321 */
322 static function customField() {
323 $fieldId = CRM_Utils_Type::escape($_REQUEST['id'], 'Integer');
324 $params = array('id' => $fieldId);
325 $returnProperties = array('help_pre', 'help_post');
326 $values = array();
327
328 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_CustomField', $params, $values, $returnProperties);
329 CRM_Utils_JSON::output($values);
330 }
331
332 static function groupTree() {
333 header('Content-Type: application/json');
334 $gids = CRM_Utils_Type::escape($_GET['gids'], 'String');
335 echo CRM_Contact_BAO_GroupNestingCache::json($gids);
336 CRM_Utils_System::civiExit();
337 }
338
339 /**
340 * Function to delete custom value
341 *
342 */
343 static function deleteCustomValue() {
344 header('Content-Type: text/plain');
345 $customValueID = CRM_Utils_Type::escape($_REQUEST['valueID'], 'Positive');
346 $customGroupID = CRM_Utils_Type::escape($_REQUEST['groupID'], 'Positive');
347
348 CRM_Core_BAO_CustomValue::deleteCustomValue($customValueID, $customGroupID);
349 $contactId = CRM_Utils_Array::value('contactId', $_REQUEST);
350 if ($contactId) {
351 echo CRM_Contact_BAO_Contact::getCountComponent('custom_' . $_REQUEST['groupID'], $contactId);
352 }
353
354 // reset the group contact cache for this group
355 CRM_Contact_BAO_GroupContactCache::remove();
356 CRM_Utils_System::civiExit();
357 }
358
359 /**
360 * Function to perform enable / disable actions on record.
361 *
362 */
363 static function enableDisable() {
364 $op = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
365 $recordID = CRM_Utils_Type::escape($_REQUEST['recordID'], 'Positive');
366 $recordBAO = CRM_Utils_Type::escape($_REQUEST['recordBAO'], 'String');
367
368 $isActive = NULL;
369 if ($op == 'disable-enable') {
370 $isActive = TRUE;
371 }
372 elseif ($op == 'enable-disable') {
373 $isActive = FALSE;
374 }
375 $status = array('status' => 'record-updated-fail');
376 if (isset($isActive)) {
377 // first munge and clean the recordBAO and get rid of any non alpha numeric characters
378 $recordBAO = CRM_Utils_String::munge($recordBAO);
379 $recordClass = explode('_', $recordBAO);
380
381 // make sure recordClass is namespaced (we cant check CRM since extensions can also use this)
382 // but it should be at least 3 levels deep
383 if (count($recordClass) >= 3) {
384 require_once (str_replace('_', DIRECTORY_SEPARATOR, $recordBAO) . ".php");
385 $method = 'setIsActive';
386
387 if (method_exists($recordBAO, $method)) {
388 $updated = call_user_func_array(array($recordBAO, $method),
389 array($recordID, $isActive)
390 );
391 if ($updated) {
392 $status = array('status' => 'record-updated-success');
393 }
394
395 // call hook enableDisable
396 CRM_Utils_Hook::enableDisable($recordBAO, $recordID, $isActive);
397 }
398 }
399 CRM_Utils_JSON::output($status);
400 }
401 }
402
403 /**
404 *Function to check the CMS username
405 *
406 */
407 static public function checkUserName() {
408 $signer = new CRM_Utils_Signer(CRM_Core_Key::privateKey(), array('for', 'ts'));
409 if (
410 CRM_Utils_Time::getTimeRaw() > $_REQUEST['ts'] + self::CHECK_USERNAME_TTL
411 || $_REQUEST['for'] != 'civicrm/ajax/cmsuser'
412 || !$signer->validate($_REQUEST['sig'], $_REQUEST)
413 ) {
414 $user = array('name' => 'error');
415 CRM_Utils_JSON::output($user);
416 }
417
418 $config = CRM_Core_Config::singleton();
419 $username = trim($_REQUEST['cms_name']);
420
421 $params = array('name' => $username);
422
423 $errors = array();
424 $config->userSystem->checkUserNameEmailExists($params, $errors);
425
426 if (isset($errors['cms_name']) || isset($errors['name'])) {
427 //user name is not availble
428 $user = array('name' => 'no');
429 CRM_Utils_JSON::output($user);
430 }
431 else {
432 //user name is available
433 $user = array('name' => 'yes');
434 CRM_Utils_JSON::output($user);
435 }
436
437 // Not reachable: JSON::output() above exits.
438 CRM_Utils_System::civiExit();
439 }
440
441 /**
442 * Function to get email address of a contact
443 */
444 static function getContactEmail() {
445 if (!empty($_REQUEST['contact_id'])) {
446 $contactID = CRM_Utils_Type::escape($_REQUEST['contact_id'], 'Positive');
447 if (!CRM_Contact_BAO_Contact_Permission::allow($contactID, CRM_Core_Permission::EDIT)) {
448 return;
449 }
450 list($displayName,
451 $userEmail
452 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
453
454 header('Content-Type: text/plain');
455 if ($userEmail) {
456 echo $userEmail;
457 }
458 }
459 else {
460 $noemail = CRM_Utils_Array::value('noemail', $_GET);
461 $queryString = NULL;
462 $name = CRM_Utils_Array::value('name', $_GET);
463 if ($name) {
464 $name = CRM_Utils_Type::escape($name, 'String');
465 if ($noemail) {
466 $queryString = " cc.sort_name LIKE '%$name%'";
467 }
468 else {
469 $queryString = " ( cc.sort_name LIKE '%$name%' OR ce.email LIKE '%$name%' ) ";
470 }
471 }
472 else {
473 $cid = CRM_Utils_Array::value('cid', $_GET);
474 if ($cid) {
475 //check cid for interger
476 $contIDS = explode(',', $cid);
477 foreach ($contIDS as $contID) {
478 CRM_Utils_Type::escape($contID, 'Integer');
479 }
480 $queryString = " cc.id IN ( $cid )";
481 }
482 }
483
484 if ($queryString) {
485 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
486 $rowCount = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'search_autocomplete_count', NULL, 10);
487
488 $offset = CRM_Utils_Type::escape($offset, 'Int');
489
490 // add acl clause here
491 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
492 if ($aclWhere) {
493 $aclWhere = " AND $aclWhere";
494 }
495 if ($noemail) {
496 $query = "
497 SELECT sort_name name, cc.id
498 FROM civicrm_contact cc
499 {$aclFrom}
500 WHERE cc.is_deceased = 0 AND {$queryString}
501 {$aclWhere}
502 LIMIT {$offset}, {$rowCount}
503 ";
504
505 // send query to hook to be modified if needed
506 CRM_Utils_Hook::contactListQuery($query,
507 $name,
508 CRM_Utils_Array::value('context', $_GET),
509 CRM_Utils_Array::value('cid', $_GET)
510 );
511
512 $dao = CRM_Core_DAO::executeQuery($query);
513 while ($dao->fetch()) {
514 $result[] = array(
515 'id' => $dao->id,
516 'text' => $dao->name,
517 );
518 }
519 }
520 else {
521 $query = "
522 SELECT sort_name name, ce.email, cc.id
523 FROM civicrm_email ce INNER JOIN civicrm_contact cc ON cc.id = ce.contact_id
524 {$aclFrom}
525 WHERE ce.on_hold = 0 AND cc.is_deceased = 0 AND cc.do_not_email = 0 AND {$queryString}
526 {$aclWhere}
527 LIMIT {$offset}, {$rowCount}
528 ";
529
530 // send query to hook to be modified if needed
531 CRM_Utils_Hook::contactListQuery($query,
532 $name,
533 CRM_Utils_Array::value('context', $_GET),
534 CRM_Utils_Array::value('cid', $_GET)
535 );
536
537
538 $dao = CRM_Core_DAO::executeQuery($query);
539
540 while ($dao->fetch()) {
541 //working here
542 $result[] = array(
543 'text' => '"' . $dao->name . '" <' . $dao->email . '>',
544 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->email}" : '"' . $dao->name . '" <' . $dao->email . '>',
545 );
546 }
547 }
548 if ($result) {
549 CRM_Utils_JSON::output($result);
550 }
551 }
552 }
553 CRM_Utils_System::civiExit();
554 }
555
556 static function getContactPhone() {
557
558 $queryString = NULL;
559 //check for mobile type
560 $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
561 $mobileType = CRM_Utils_Array::value('Mobile', $phoneTypes);
562
563 $name = CRM_Utils_Array::value('name', $_GET);
564 if ($name) {
565 $name = CRM_Utils_Type::escape($name, 'String');
566 $queryString = " ( cc.sort_name LIKE '%$name%' OR cp.phone LIKE '%$name%' ) ";
567 }
568 else {
569 $cid = CRM_Utils_Array::value('cid', $_GET);
570 if ($cid) {
571 //check cid for interger
572 $contIDS = explode(',', $cid);
573 foreach ($contIDS as $contID) {
574 CRM_Utils_Type::escape($contID, 'Integer');
575 }
576 $queryString = " cc.id IN ( $cid )";
577 }
578 }
579
580 if ($queryString) {
581 $offset = CRM_Utils_Array::value('offset', $_GET, 0);
582 $rowCount = CRM_Utils_Array::value('rowcount', $_GET, 20);
583
584 $offset = CRM_Utils_Type::escape($offset, 'Int');
585 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
586
587 // add acl clause here
588 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause('cc');
589 if ($aclWhere) {
590 $aclWhere = " AND $aclWhere";
591 }
592
593 $query = "
594 SELECT sort_name name, cp.phone, cc.id
595 FROM civicrm_phone cp INNER JOIN civicrm_contact cc ON cc.id = cp.contact_id
596 {$aclFrom}
597 WHERE cc.is_deceased = 0 AND cc.do_not_sms = 0 AND cp.phone_type_id = {$mobileType} AND {$queryString}
598 {$aclWhere}
599 LIMIT {$offset}, {$rowCount}
600 ";
601
602 // send query to hook to be modified if needed
603 CRM_Utils_Hook::contactListQuery($query,
604 $name,
605 CRM_Utils_Array::value('context', $_GET),
606 CRM_Utils_Array::value('cid', $_GET)
607 );
608
609 $dao = CRM_Core_DAO::executeQuery($query);
610
611 while ($dao->fetch()) {
612 $result[] = array(
613 'text' => '"' . $dao->name . '" (' . $dao->phone . ')',
614 'id' => (CRM_Utils_Array::value('id', $_GET)) ? "{$dao->id}::{$dao->phone}" : '"' . $dao->name . '" <' . $dao->phone . '>',
615 );
616 }
617 }
618
619 if ($result) {
620 CRM_Utils_JSON::output($result);
621 }
622 CRM_Utils_System::civiExit();
623 }
624
625
626 static function buildSubTypes() {
627 $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
628
629 switch ($parent) {
630 case 1:
631 $contactType = 'Individual';
632 break;
633
634 case 2:
635 $contactType = 'Household';
636 break;
637
638 case 4:
639 $contactType = 'Organization';
640 break;
641 }
642
643 $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($contactType, FALSE, NULL);
644 asort($subTypes);
645 CRM_Utils_JSON::output($subTypes);
646 }
647
648 static function buildDedupeRules() {
649 $parent = CRM_Utils_Array::value('parentId', $_REQUEST);
650
651 switch ($parent) {
652 case 1:
653 $contactType = 'Individual';
654 break;
655
656 case 2:
657 $contactType = 'Household';
658 break;
659
660 case 4:
661 $contactType = 'Organization';
662 break;
663 }
664
665 $dedupeRules = CRM_Dedupe_BAO_RuleGroup::getByType($contactType);
666
667 CRM_Utils_JSON::output($dedupeRules);
668 }
669
670 /**
671 * Function used for CiviCRM dashboard operations
672 */
673 static function dashboard() {
674 $operation = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
675
676 switch ($operation) {
677 case 'get_widgets_by_column':
678 // This would normally be coming from either the database (this user's settings) or a default/initial dashboard configuration.
679 // get contact id of logged in user
680
681 $dashlets = CRM_Core_BAO_Dashboard::getContactDashlets();
682 break;
683
684 case 'get_widget':
685 $dashletID = CRM_Utils_Type::escape($_GET['id'], 'Positive');
686
687 $dashlets = CRM_Core_BAO_Dashboard::getDashletInfo($dashletID);
688 break;
689
690 case 'save_columns':
691 CRM_Core_BAO_Dashboard::saveDashletChanges($_REQUEST['columns']);
692 CRM_Utils_System::civiExit();
693 case 'delete_dashlet':
694 $dashletID = CRM_Utils_Type::escape($_REQUEST['dashlet_id'], 'Positive');
695 CRM_Core_BAO_Dashboard::deleteDashlet($dashletID);
696 CRM_Utils_System::civiExit();
697 }
698
699 CRM_Utils_JSON::output($dashlets);
700 }
701
702 /**
703 * Function to retrieve signature based on email id
704 */
705 static function getSignature() {
706 $emailID = CRM_Utils_Type::escape($_REQUEST['emailID'], 'Positive');
707 $query = "SELECT signature_text, signature_html FROM civicrm_email WHERE id = {$emailID}";
708 $dao = CRM_Core_DAO::executeQuery($query);
709
710 $signatures = array();
711 while ($dao->fetch()) {
712 $signatures = array(
713 'signature_text' => $dao->signature_text,
714 'signature_html' => $dao->signature_html,
715 );
716 }
717
718 CRM_Utils_JSON::output($signatures);
719 }
720
721 /**
722 * Function to process dupes.
723 *
724 */
725 static function processDupes() {
726 $oper = CRM_Utils_Type::escape($_REQUEST['op'], 'String');
727 $cid = CRM_Utils_Type::escape($_REQUEST['cid'], 'Positive');
728 $oid = CRM_Utils_Type::escape($_REQUEST['oid'], 'Positive');
729
730 if (!$oper || !$cid || !$oid) {
731 return;
732 }
733
734 $exception = new CRM_Dedupe_DAO_Exception();
735 $exception->contact_id1 = $cid;
736 $exception->contact_id2 = $oid;
737 //make sure contact2 > contact1.
738 if ($cid > $oid) {
739 $exception->contact_id1 = $oid;
740 $exception->contact_id2 = $cid;
741 }
742 $exception->find(TRUE);
743 $status = NULL;
744 if ($oper == 'dupe-nondupe') {
745 $status = $exception->save();
746 }
747 if ($oper == 'nondupe-dupe') {
748 $status = $exception->delete();
749 }
750
751 CRM_Utils_JSON::output(array('status' => ($status) ? $oper : $status));
752 }
753
754 static function getDedupes() {
755
756 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
757 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
758 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
759 $sort = 'sort_name';
760 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
761
762 $gid = isset($_REQUEST['gid']) ? CRM_Utils_Type::escape($_REQUEST['gid'], 'Integer') : 0;
763 $rgid = isset($_REQUEST['rgid']) ? CRM_Utils_Type::escape($_REQUEST['rgid'], 'Integer') : 0;
764 $contactType = '';
765 if ($rgid) {
766 $contactType = CRM_Core_DAO::getFieldValue('CRM_Dedupe_DAO_RuleGroup', $rgid, 'contact_type');
767 }
768
769 $cacheKeyString = "merge {$contactType}_{$rgid}_{$gid}";
770 $searchRows = array();
771 $selectorElements = array('src', 'dst', 'weight', 'actions');
772
773
774 $join = "LEFT JOIN civicrm_dedupe_exception de ON ( pn.entity_id1 = de.contact_id1 AND
775 pn.entity_id2 = de.contact_id2 )";
776 $where = "de.id IS NULL";
777
778 $iFilteredTotal = $iTotal = CRM_Core_BAO_PrevNextCache::getCount($cacheKeyString, $join, $where);
779 $mainContacts = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString, $join, $where, $offset, $rowCount);
780
781 foreach ($mainContacts as $mainId => $main) {
782 $searchRows[$mainId]['src'] = CRM_Utils_System::href($main['srcName'], 'civicrm/contact/view', "reset=1&cid={$main['srcID']}");
783 $searchRows[$mainId]['dst'] = CRM_Utils_System::href($main['dstName'], 'civicrm/contact/view', "reset=1&cid={$main['dstID']}");
784 $searchRows[$mainId]['weight'] = CRM_Utils_Array::value('weight', $main);
785
786 if (!empty($main['canMerge'])) {
787 $mergeParams = "reset=1&cid={$main['srcID']}&oid={$main['dstID']}&action=update&rgid={$rgid}";
788 if ($gid) {
789 $mergeParams .= "&gid={$gid}";
790 }
791
792 $searchRows[$mainId]['actions'] = CRM_Utils_System::href(ts('merge'), 'civicrm/contact/merge', $mergeParams);
793 $searchRows[$mainId]['actions'] .= "&nbsp;|&nbsp; <a id='notDuplicate' href='#' onClick=\"processDupes( {$main['srcID']}, {$main['dstID']}, 'dupe-nondupe', 'dupe-listing'); return false;\">" . ts('not a duplicate') . "</a>";
794 }
795 else {
796 $searchRows[$mainId]['actions'] = '<em>' . ts('Insufficient access rights - cannot merge') . '</em>';
797 }
798 }
799
800 header('Content-Type: application/json');
801 echo CRM_Utils_JSON::encodeDataTableSelector($searchRows, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
802
803 CRM_Utils_System::civiExit();
804 }
805
806 /**
807 * Function to retrieve a PDF Page Format for the PDF Letter form
808 */
809 function pdfFormat() {
810 $formatId = CRM_Utils_Type::escape($_REQUEST['formatId'], 'Integer');
811
812 $pdfFormat = CRM_Core_BAO_PdfFormat::getById($formatId);
813
814 CRM_Utils_JSON::output($pdfFormat);
815 }
816
817 /**
818 * Function to retrieve Paper Size dimensions
819 */
820 static function paperSize() {
821 $paperSizeName = CRM_Utils_Type::escape($_REQUEST['paperSizeName'], 'String');
822
823 $paperSize = CRM_Core_BAO_PaperSize::getByName($paperSizeName);
824
825 CRM_Utils_JSON::output($paperSize);
826 }
827
828 static function selectUnselectContacts() {
829 $name = CRM_Utils_Array::value('name', $_REQUEST);
830 $cacheKey = CRM_Utils_Array::value('qfKey', $_REQUEST);
831 $state = CRM_Utils_Array::value('state', $_REQUEST, 'checked');
832 $variableType = CRM_Utils_Array::value('variableType', $_REQUEST, 'single');
833
834 $actionToPerform = CRM_Utils_Array::value('action', $_REQUEST, 'select');
835
836 if ($variableType == 'multiple') {
837 // action post value only works with multiple type variable
838 if ($name) {
839 //multiple names like mark_x_1-mark_x_2 where 1,2 are cids
840 $elements = explode('-', $name);
841 foreach ($elements as $key => $element) {
842 $elements[$key] = self::_convertToId($element);
843 }
844 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $actionToPerform, $elements);
845 }
846 else {
847 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $actionToPerform);
848 }
849 }
850 elseif ($variableType == 'single') {
851 $cId = self::_convertToId($name);
852 $action = ($state == 'checked') ? 'select' : 'unselect';
853 CRM_Core_BAO_PrevNextCache::markSelection($cacheKey, $action, $cId);
854 }
855 $contactIds = CRM_Core_BAO_PrevNextCache::getSelection($cacheKey);
856 $countSelectionCids = count($contactIds[$cacheKey]);
857
858 $arrRet = array('getCount' => $countSelectionCids);
859 CRM_Utils_JSON::output($arrRet);
860 }
861
862 /**
863 * @param $name
864 *
865 * @return string
866 */
867 static function _convertToId($name) {
868 if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
869 $cId = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
870 }
871 return $cId;
872 }
873
874 static function getAddressDisplay() {
875 $contactId = CRM_Utils_Array::value('contact_id', $_REQUEST);
876 if (!$contactId) {
877 $addressVal["error_message"] = "no contact id found";
878 }
879 else {
880 $entityBlock =
881 array(
882 'contact_id' => $contactId,
883 'entity_id' => $contactId,
884 );
885 $addressVal = CRM_Core_BAO_Address::getValues($entityBlock);
886 }
887
888 CRM_Utils_JSON::output($addressVal);
889 }
890
891 /**
892 * Function to retrieve contact relationships
893 */
894 public static function getContactRelationships() {
895 $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
896 $context = CRM_Utils_Type::escape($_GET['context'], 'String');
897
898 if (!CRM_Contact_BAO_Contact_Permission::allow($contactID)) {
899 return CRM_Utils_System::permissionDenied();
900 }
901
902 $sortMapper = array(
903 0 => 'relation',
904 1 => 'sort_name',
905 2 => 'start_date',
906 3 => 'end_date',
907 4 => 'city',
908 5 => 'state',
909 6 => 'email',
910 7 => 'phone',
911 8 => 'links',
912 9 => '',
913 10 => '',
914 );
915
916 $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer');
917 $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0;
918 $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25;
919 $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL;
920 $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc';
921
922 $params = $_POST;
923 if ($sort && $sortOrder) {
924 $params['sortBy'] = $sort . ' ' . $sortOrder;
925 }
926
927 $params['page'] = ($offset / $rowCount) + 1;
928 $params['rp'] = $rowCount;
929
930 $params['contact_id'] = $contactID;
931 $params['context'] = $context;
932
933 // get the contact relationships
934 $relationships = CRM_Contact_BAO_Relationship::getContactRelationshipSelector($params);
935
936 $iFilteredTotal = $iTotal = $params['total'];
937 $selectorElements = array(
938 'relation',
939 'name',
940 'start_date',
941 'end_date',
942 'city',
943 'state',
944 'email',
945 'phone',
946 'links',
947 'id',
948 'is_active',
949 );
950
951 header('Content-Type: application/json');
952 echo CRM_Utils_JSON::encodeDataTableSelector($relationships, $sEcho, $iTotal, $iFilteredTotal, $selectorElements);
953 CRM_Utils_System::civiExit();
954 }
955 }