3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This class contains the functions for Case Management.
37 class CRM_Case_BAO_Case
extends CRM_Case_DAO_Case
{
40 * Static field for all the case information that we can potentially export.
44 public static $_exportableFields = NULL;
49 public function __construct() {
50 parent
::__construct();
54 * Is CiviCase enabled?
58 public static function enabled() {
59 $config = CRM_Core_Config
::singleton();
60 return in_array('CiviCase', $config->enableComponents
);
64 * Create a case object.
66 * The function extracts all the params it needs to initialize the create a
67 * case object. the params array could contain additional unused name/value
70 * @param array $params
71 * (reference ) an assoc array of name/value pairs.
73 * @return CRM_Case_BAO_Case
75 public static function add(&$params) {
76 $caseDAO = new CRM_Case_DAO_Case();
77 $caseDAO->copyValues($params);
78 $result = $caseDAO->save();
79 // Get other case values (required by XML processor), this adds to $result array
85 * Takes an associative array and creates a case object.
87 * @param array $params
88 * (reference) an assoc array of name/value pairs.
90 * @return CRM_Case_BAO_Case
92 public static function &create(&$params) {
93 // CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps.
94 unset($params['created_date']);
95 unset($params['modified_date']);
96 $caseStatus = CRM_Case_PseudoConstant
::caseStatus('name');
97 // for resolved case the end date should set to now
98 if (!empty($params['status_id']) && $params['status_id'] == array_search('Closed', $caseStatus)) {
99 $params['end_date'] = date("Ymd");
102 $transaction = new CRM_Core_Transaction();
104 if (!empty($params['id'])) {
105 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
108 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
111 $case = self
::add($params);
113 if (!empty($params['custom']) &&
114 is_array($params['custom'])
116 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
119 if (is_a($case, 'CRM_Core_Error')) {
120 $transaction->rollback();
124 if (!empty($params['id'])) {
125 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
128 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
130 $transaction->commit();
132 //we are not creating log for case
133 //since case log can be tracked using log for activity.
138 * Process case activity add/delete
139 * takes an associative array and
141 * @param array $params
142 * (reference ) an assoc array of name/value pairs.
145 public static function processCaseActivity(&$params) {
146 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
147 $caseActivityDAO->activity_id
= $params['activity_id'];
148 $caseActivityDAO->case_id
= $params['case_id'];
150 $caseActivityDAO->find(TRUE);
151 $caseActivityDAO->save();
155 * Get the case subject for Activity.
157 * @param int $activityId
160 * @return string|null
162 public static function getCaseSubject($activityId) {
163 $caseActivity = new CRM_Case_DAO_CaseActivity();
164 $caseActivity->activity_id
= $activityId;
165 if ($caseActivity->find(TRUE)) {
166 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
175 * @param string $colName
180 public static function getCaseType($caseId, $colName = 'title') {
182 SELECT civicrm_case_type.{$colName} FROM civicrm_case
183 LEFT JOIN civicrm_case_type ON
184 civicrm_case.case_type_id = civicrm_case_type.id
185 WHERE civicrm_case.id = %1";
187 $queryParams = array(1 => array($caseId, 'Integer'));
189 return CRM_Core_DAO
::singleValueQuery($query, $queryParams);
193 * Delete the record that are associated with this case.
194 * record are deleted from case
197 * Id of the case to delete.
199 * @param bool $moveToTrash
204 public static function deleteCase($caseId, $moveToTrash = FALSE) {
205 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
208 $activities = self
::getCaseActivityDates($caseId);
210 foreach ($activities as $value) {
211 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
216 $transaction = new CRM_Core_Transaction();
218 $case = new CRM_Case_DAO_Case();
221 $result = $case->delete();
222 $transaction->commit();
225 $result = $case->is_deleted
= 1;
230 // CRM-7364, disable relationships
231 self
::enableDisableCaseRelationships($caseId, FALSE);
233 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
235 // remove case from recent items.
240 CRM_Utils_Recent
::del($caseRecent);
248 * Enable disable case related relationships.
252 * @param bool $enable
255 public static function enableDisableCaseRelationships($caseId, $enable) {
256 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
257 if (!empty($contactIds)) {
258 foreach ($contactIds as $cid) {
259 $roles = self
::getCaseRoles($cid, $caseId);
260 if (!empty($roles)) {
261 $relationshipIds = implode(',', array_keys($roles));
262 $enable = (int) $enable;
263 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
264 WHERE id IN ( {$relationshipIds} )";
265 CRM_Core_DAO
::executeQuery($query);
272 * Retrieve contact_id by case_id.
277 * @param int $contactID
278 * @param int $startArrayAt This is to support legacy calls to Case.Get API which may rely on the first array index being set to 1
282 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL, $startArrayAt = 0) {
283 $caseContact = new CRM_Case_DAO_CaseContact();
284 $caseContact->case_id
= $caseId;
285 $caseContact->find();
286 $contactArray = array();
287 $count = $startArrayAt;
288 while ($caseContact->fetch()) {
289 if ($contactID != $caseContact->contact_id
) {
290 $contactArray[$count] = $caseContact->contact_id
;
295 return $contactArray;
299 * Look up a case using an activity ID.
301 * @param int $activityId
303 * @return int, case ID
305 public static function getCaseIdByActivityId($activityId) {
306 $originalId = CRM_Core_DAO
::singleValueQuery(
307 'SELECT original_id FROM civicrm_activity WHERE id = %1',
308 array('1' => array($activityId, 'Integer'))
310 $caseId = CRM_Core_DAO
::singleValueQuery(
311 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
313 '1' => array($activityId, 'Integer'),
314 '2' => array($originalId ?
$originalId : $activityId, 'Integer'),
321 * Retrieve contact names by caseId.
328 public static function getContactNames($caseId) {
329 $contactNames = array();
331 return $contactNames;
335 SELECT contact_a.sort_name name,
336 contact_a.display_name as display_name,
338 contact_a.birth_date as birth_date,
341 FROM civicrm_contact contact_a
342 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
343 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
344 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
345 WHERE contact_a.is_deleted = 0 AND civicrm_case_contact.case_id = %1
346 ORDER BY civicrm_case_contact.id";
348 $dao = CRM_Core_DAO
::executeQuery($query,
349 array(1 => array($caseId, 'Integer'))
351 while ($dao->fetch()) {
352 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
353 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
354 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
355 $contactNames[$dao->cid
]['email'] = $dao->email
;
356 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
357 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
358 $contactNames[$dao->cid
]['role'] = ts('Client');
361 return $contactNames;
365 * Retrieve case_id by contact_id.
367 * @param int $contactID
368 * @param bool $includeDeleted
369 * Include the deleted cases in result.
370 * @param null $caseType
374 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
377 FROM civicrm_case_contact cc
378 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
380 if (isset($caseType)) {
382 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
383 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
385 if (!isset($caseType)) {
386 $query .= "WHERE cc.contact_id = %1";
388 if (!$includeDeleted) {
389 $query .= " AND ca.is_deleted = 0";
392 $params = array(1 => array($contactID, 'Integer'));
393 $dao = CRM_Core_DAO
::executeQuery($query, $params);
395 $caseArray = array();
396 while ($dao->fetch()) {
397 $caseArray[] = $dao->id
;
404 * @param string $type
406 * @param string $condition
410 public static function getCaseActivityCountQuery($type = 'upcoming', $userID, $condition = NULL) {
411 return sprintf(" SELECT COUNT(*) FROM (%s) temp ", self
::getCaseActivityQuery($type, $userID, $condition));
415 * @param string $type
417 * @param string $condition
418 * @param string $limit
419 * @param string $order
423 public static function getCaseActivityQuery($type = 'upcoming', $userID, $condition = NULL, $limit = NULL, $order = NULL) {
424 $selectClauses = array(
425 'civicrm_case.id as case_id',
426 'civicrm_case.subject as case_subject',
427 'civicrm_contact.id as contact_id',
428 'civicrm_contact.sort_name as sort_name',
429 'civicrm_phone.phone as phone',
430 'civicrm_contact.contact_type as contact_type',
431 'civicrm_contact.contact_sub_type as contact_sub_type',
432 't_act.activity_type_id as activity_type_id',
433 'civicrm_case.case_type_id as case_type_id',
434 'civicrm_case.status_id as case_status_id',
435 't_act.status_id as status_id',
436 'civicrm_case.start_date as case_start_date',
437 "GROUP_CONCAT(DISTINCT IF(case_relationship.contact_id_b = $userID, case_relation_type.label_a_b, case_relation_type.label_b_a) SEPARATOR ', ') as case_role",
438 't_act.activity_date_time as activity_date_time',
439 't_act.id as activity_id',
442 $query = CRM_Contact_BAO_Query
::appendAnyValueToSelect($selectClauses, 'case_id');
446 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
447 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id
453 // civicrm_view_case_activity_upcoming and
454 // civicrm_view_case_activity_recent are views that show the next
455 // scheduled and most recent not-scheduled activity on each case,
458 INNER JOIN civicrm_view_case_activity_$type t_act
459 ON t_act.case_id = civicrm_case.id
465 LEFT JOIN civicrm_case_activity ca4
466 ON civicrm_case.id = ca4.case_id
467 LEFT JOIN civicrm_activity t_act
468 ON t_act.id = ca4.activity_id
469 AND t_act.is_current_revision = 1
474 LEFT JOIN civicrm_phone
475 ON civicrm_phone.contact_id = civicrm_contact.id
476 AND civicrm_phone.is_primary = 1
477 LEFT JOIN civicrm_relationship case_relationship
478 ON ((case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID})
479 OR (case_relationship.contact_id_b = civicrm_case_contact.contact_id AND case_relationship.contact_id_a = {$userID}))
480 AND case_relationship.is_active
481 AND case_relationship.case_id = civicrm_case.id
482 LEFT JOIN civicrm_relationship_type case_relation_type
483 ON case_relation_type.id = case_relationship.relationship_type_id
484 AND case_relation_type.id = case_relationship.relationship_type_id
488 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
489 $query .= " WHERE (1) AND $condition ";
491 $query .= " GROUP BY case_id ";
493 $query .= ($order) ?
: ' ORDER BY activity_date_time ASC';
503 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
505 * @param bool $allCases
506 * @param array $params
507 * @param string $context
508 * @param bool $getCount
513 public static function getCases($allCases = TRUE, $params = array(), $context = 'dashboard', $getCount = FALSE) {
515 $casesList = array();
517 // validate access for own cases.
518 if (!self
::accessCiviCase()) {
519 return $getCount ?
0 : $casesList;
522 // Return cached value instead of re-running query
523 if (isset(Civi
::$statics[__CLASS__
]['totalCount']) && $getCount) {
524 return Civi
::$statics[__CLASS__
]['totalCount'];
527 $type = CRM_Utils_Array
::value('type', $params, 'upcoming');
528 $userID = CRM_Core_Session
::singleton()->get('userID');
530 // validate access for all cases.
531 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
535 $whereClauses = array('civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1');
538 $whereClauses[] = "(case_relationship.contact_id_b = {$userID} OR case_relationship.contact_id_a = {$userID})";
539 $whereClauses[] = 'case_relationship.is_active';
541 if (empty($params['status_id']) && ($type == 'upcoming' ||
$type == 'any')) {
542 $whereClauses[] = "civicrm_case.status_id != " . CRM_Core_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
545 foreach (array('case_type_id', 'status_id') as $column) {
546 if (!empty($params[$column])) {
547 $whereClauses[] = sprintf("civicrm_case.%s IN (%s)", $column, $params[$column]);
550 $condition = implode(' AND ', $whereClauses);
552 Civi
::$statics[__CLASS__
]['totalCount'] = $totalCount = CRM_Core_DAO
::singleValueQuery(self
::getCaseActivityCountQuery($type, $userID, $condition));
556 $casesList['total'] = $totalCount;
559 if (!empty($params['rp'])) {
560 $params['offset'] = ($params['page'] - 1) * $params['rp'];
561 $params['rowCount'] = $params['rp'];
562 if (!empty($params['rowCount']) && $params['rowCount'] > 0) {
563 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
568 if (!empty($params['sortBy'])) {
569 if (strstr($params['sortBy'], 'date ')) {
570 $params['sortBy'] = str_replace('date', 'activity_date_time', $params['sortBy']);
572 $order = "ORDER BY " . $params['sortBy'];
575 $query = self
::getCaseActivityQuery($type, $userID, $condition, $limit, $order);
576 $result = CRM_Core_DAO
::executeQuery($query);
578 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
579 $actions = CRM_Case_Selector_Search
::links();
581 // check is the user has view/edit signer permission
582 $permissions = array(CRM_Core_Permission
::VIEW
);
583 if (CRM_Core_Permission
::check('access all cases and activities') ||
584 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
586 $permissions[] = CRM_Core_Permission
::EDIT
;
588 if (CRM_Core_Permission
::check('delete in CiviCase')) {
589 $permissions[] = CRM_Core_Permission
::DELETE
;
591 $mask = CRM_Core_Action
::mask($permissions);
593 // Pseudoconstants to populate labels
594 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
595 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
596 $caseTypeTitles = CRM_Case_PseudoConstant
::caseType('title', FALSE);
597 $activityTypeLabels = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id');
599 foreach ($result->fetchAll() as $case) {
600 $key = $case['case_id'];
601 $casesList[$key] = array();
602 $casesList[$key]['DT_RowId'] = $case['case_id'];
603 $casesList[$key]['DT_RowAttr'] = array('data-entity' => 'case', 'data-id' => $case['case_id']);
604 $casesList[$key]['DT_RowClass'] = "crm-entity";
606 $casesList[$key]['activity_list'] = sprintf('<a title="%s" class="crm-expand-row" href="%s"></a>',
608 CRM_Utils_System
::url('civicrm/case/details', array('caseId' => $case['case_id'], 'cid' => $case['contact_id'], 'type' => $type))
611 $phone = empty($case['phone']) ?
'' : '<br /><span class="description">' . $case['phone'] . '</span>';
612 $casesList[$key]['contact_id'] = sprintf('<a href="%s">%s</a>%s<br /><span class="description">%s: %d</span>',
613 CRM_Utils_System
::url('civicrm/contact/view', array('cid' => $case['contact_id'])),
619 $casesList[$key]['subject'] = $case['case_subject'];
620 $casesList[$key]['case_status'] = CRM_Utils_Array
::value($case['case_status_id'], $caseStatuses);
621 if ($case['case_status_id'] == CRM_Case_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Urgent')) {
622 $casesList[$key]['case_status'] = sprintf('<strong>%s</strong>', strtoupper($casesList[$key]['case_status']));
624 $casesList[$key]['case_type'] = CRM_Utils_Array
::value($case['case_type_id'], $caseTypeTitles);
625 $casesList[$key]['case_role'] = CRM_Utils_Array
::value('case_role', $case, '---');
626 $casesList[$key]['manager'] = self
::getCaseManagerContact($caseTypes[$case['case_type_id']], $case['case_id']);
628 $casesList[$key]['date'] = CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels);
629 if ($actId = CRM_Utils_Array
::value('activity_id', $case)) {
630 if (self
::checkPermission($actId, 'view', $case['activity_type_id'], $userID)) {
631 if ($type == 'recent') {
632 $casesList[$key]['date'] = sprintf('<a class="action-item crm-hover-button" href="%s" title="%s">%s</a>',
633 CRM_Utils_System
::url('civicrm/case/activity/view', array('reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id'])),
635 CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels)
639 $status = CRM_Utils_Date
::overdue($case['activity_date_time']) ?
'status-overdue' : 'status-scheduled';
640 $casesList[$key]['date'] = sprintf('<a class="crm-popup %s" href="%s" title="%s">%s</a> ',
642 CRM_Utils_System
::url('civicrm/case/activity/view', array('reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id'])),
644 CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels)
648 if (isset($case['activity_type_id']) && self
::checkPermission($actId, 'edit', $case['activity_type_id'], $userID)) {
649 $casesList[$key]['date'] .= sprintf('<a class="action-item crm-hover-button" href="%s" title="%s"><i class="crm-i fa-pencil"></i></a>',
650 CRM_Utils_System
::url('civicrm/case/activity', array('reset' => 1, 'cid' => $case['contact_id'], 'caseid' => $case['case_id'], 'action' => 'update', 'id' => $actId)),
655 $casesList[$key]['date'] .= "<br/>" . CRM_Utils_Date
::customFormat($case['activity_date_time']);
656 $casesList[$key]['links'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
658 'id' => $case['case_id'],
659 'cid' => $case['contact_id'],
664 'case.actions.primary',
674 * Get the summary of cases counts by type and status.
676 * @param bool $allCases
679 public static function getCasesSummary($allCases = TRUE) {
680 $caseSummary = array();
682 //validate access for civicase.
683 if (!self
::accessCiviCase()) {
687 $userID = CRM_Core_Session
::singleton()->get('userID');
689 //validate access for all cases.
690 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
694 $caseTypes = CRM_Case_PseudoConstant
::caseType();
695 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
696 $caseTypes = array_flip($caseTypes);
698 // get statuses as headers for the table
699 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
700 foreach ($caseStatuses as $key => $name) {
701 $caseSummary['headers'][$key]['status'] = $name;
702 $caseSummary['headers'][$key]['url'] = $url . $key;
705 // build rows with actual data
707 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClauseA = $myCaseWhereClauseB = '';
713 $myGroupByClauseB = ' GROUP BY civicrm_case.id';
718 $myCaseWhereClauseA = " AND case_relationship.contact_id_a = {$userID} AND case_relationship.is_active ";
719 $myGroupByClauseA = " GROUP BY CONCAT(civicrm_case.id,'-',case_relationship.contact_id_a)";
720 $myCaseWhereClauseB = " AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active ";
721 $myGroupByClauseB = " GROUP BY CONCAT(civicrm_case.id,'-',case_relationship.contact_id_b)";
723 $myGroupByClauseB .= ", case_status.label, status_id, case_type_id, civicrm_case.id";
724 $myGroupByClauseA = $myGroupByClauseB;
725 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
727 SELECT civicrm_case.id, case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
728 case_type_id, case_relationship.contact_id_b as case_contact
730 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
731 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
732 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
733 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
734 AND option_group_case_status.id = case_status.option_group_id )
735 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
736 AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active )
737 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
738 {$myCaseWhereClauseB} {$myGroupByClauseB}
740 SELECT civicrm_case.id, case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
741 case_type_id, case_relationship.contact_id_a as case_contact
743 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
744 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
745 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
746 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
747 AND option_group_case_status.id = case_status.option_group_id )
748 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
749 AND case_relationship.contact_id_a = {$userID})
750 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
751 {$myCaseWhereClauseA} {$myGroupByClauseA}";
753 $res = CRM_Core_DAO
::executeQuery($query);
754 while ($res->fetch()) {
755 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
756 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
759 $rows[$res->case_type
][$res->case_status
] = array(
761 'url' => CRM_Utils_System
::url('civicrm/case/search',
762 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
767 $caseSummary['rows'] = array_merge($caseTypes, $rows);
775 * @param int $contactID
779 * @param int $relationshipID
780 * @param bool $activeOnly
783 * case role / relationships
786 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL, $activeOnly = TRUE) {
788 SELECT rel.id as civicrm_relationship_id,
789 con.sort_name as sort_name,
790 civicrm_email.email as email,
791 civicrm_phone.phone as phone,
792 con.id as civicrm_contact_id,
793 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
794 civicrm_relationship_type.id as relation_type,
795 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
796 FROM civicrm_relationship rel
797 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
798 INNER JOIN civicrm_contact con ON ((con.id <> %1 AND con.id IN (rel.contact_id_a, rel.contact_id_b)) OR (con.id = %1 AND rel.contact_id_b = rel.contact_id_a AND rel.contact_id_a = %1 AND rel.is_active))
799 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
800 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
801 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
802 AND con.is_deleted = 0';
805 $query .= ' AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
809 1 => array($contactID, 'Positive'),
810 2 => array($caseID, 'Positive'),
813 if ($relationshipID) {
814 $query .= ' AND rel.id = %3 ';
815 $params[3] = array($relationshipID, 'Integer');
817 $dao = CRM_Core_DAO
::executeQuery($query, $params);
820 while ($dao->fetch()) {
821 $rid = $dao->civicrm_relationship_id
;
822 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
823 $values[$rid]['relation'] = $dao->relation
;
824 $values[$rid]['name'] = $dao->sort_name
;
825 $values[$rid]['email'] = $dao->email
;
826 $values[$rid]['phone'] = $dao->phone
;
827 $values[$rid]['relation_type'] = $dao->relation_type
;
828 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
829 $values[$rid]['client_id'] = $contactID;
830 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
837 * Get Case Activities.
841 * @param array $params
843 * @param int $contactID
846 * @param null $context
848 * @param null $type (deprecated)
851 * Array of case activities
854 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
855 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
856 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
857 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
858 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
860 // CRM-5081 - formatting the dates to omit seconds.
861 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
863 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
865 ca.activity_type_id AS type,
866 ca.activity_type_id AS activity_type_id,
867 tcc.sort_name AS target_contact_name,
868 tcc.id AS target_contact_id,
869 scc.sort_name AS source_contact_name,
870 scc.id AS source_contact_id,
871 acc.sort_name AS assignee_contact_name,
872 acc.id AS assignee_contact_id,
874 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
875 ca.activity_date_time,
876 DATE_ADD(NOW(), INTERVAL 1 YEAR)
877 ), '%Y%m%d%H%i00') AS overdue_date,
878 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
879 ca.status_id AS status,
880 ca.subject AS subject,
881 ca.is_deleted AS deleted,
882 ca.priority_id AS priority,
884 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
887 FROM civicrm_case_activity cca
888 INNER JOIN civicrm_activity ca
889 ON ca.id = cca.activity_id
890 INNER JOIN civicrm_activity_contact cas
891 ON cas.activity_id = ca.id
892 AND cas.record_type_id = {$sourceID}
893 INNER JOIN civicrm_contact scc
894 ON scc.id = cas.contact_id
895 LEFT JOIN civicrm_activity_contact caa
896 ON caa.activity_id = ca.id
897 AND caa.record_type_id = {$assigneeID}
898 LEFT JOIN civicrm_contact acc
899 ON acc.id = caa.contact_id
900 LEFT JOIN civicrm_activity_contact cat
901 ON cat.activity_id = ca.id
902 AND cat.record_type_id = {$targetID}
903 LEFT JOIN civicrm_contact tcc
904 ON tcc.id = cat.contact_id
905 INNER JOIN civicrm_option_group cog
906 ON cog.name = 'activity_type'
907 INNER JOIN civicrm_option_value cov
908 ON cov.option_group_id = cog.id
909 AND cov.value = ca.activity_type_id
910 AND cov.is_active = 1
911 LEFT JOIN civicrm_entity_file ef
912 ON ef.entity_table = 'civicrm_activity'
913 AND ef.entity_id = ca.id
914 LEFT OUTER JOIN civicrm_option_group og
915 ON og.name = 'activity_status'
916 LEFT OUTER JOIN civicrm_option_value ov
917 ON ov.option_group_id=og.id
918 AND ov.name = 'Scheduled'";
921 WHERE cca.case_id= %1
922 AND ca.is_current_revision = 1';
924 if (!empty($params['source_contact_id'])) {
926 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
929 if (!empty($params['status_id'])) {
931 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
934 if (!empty($params['activity_deleted'])) {
936 AND ca.is_deleted = 1";
940 AND ca.is_deleted = 0";
943 if (!empty($params['activity_type_id'])) {
945 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
948 if (!empty($params['activity_date_low'])) {
949 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
951 if (!empty($fromActivityDate)) {
953 AND ca.activity_date_time >= '{$fromActivityDate}'";
956 if (!empty($params['activity_date_high'])) {
957 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
958 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
960 if (!empty($toActivityDate)) {
962 AND ca.activity_date_time <= '{$toActivityDate}'";
966 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
968 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
970 // CRM-5081 - added id to act like creation date
972 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
975 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
976 $orderBy = " ORDER BY $sortBy ";
979 $page = CRM_Utils_Array
::value('page', $params);
980 $rp = CRM_Utils_Array
::value('rp', $params);
988 $start = (($page - 1) * $rp);
989 $limit = " LIMIT $start, $rp";
991 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
992 $queryParams = array(1 => array($caseID, 'Integer'));
994 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
995 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
997 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
999 $compStatusValues = array_keys(
1000 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::COMPLETED
) +
1001 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::CANCELLED
)
1005 $userID = CRM_Core_Session
::getLoggedInContactID();
1008 $caseActivities = [];
1010 while ($dao->fetch()) {
1011 $caseActivityId = $dao->id
;
1013 //Do we have permission to access given case activity record.
1014 if (!self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID)) {
1018 $caseActivities[$caseActivityId]['DT_RowId'] = $caseActivityId;
1019 //Add classes to the row, via DataTables syntax
1020 $caseActivities[$caseActivityId]['DT_RowClass'] = "crm-entity status-id-$dao->status";
1022 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1023 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-completed";
1026 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1027 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-overdue";
1030 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-scheduled";
1034 if (!empty($dao->priority
)) {
1035 if ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Urgent')) {
1036 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-urgent ";
1038 elseif ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Low')) {
1039 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-low ";
1043 //Add data to the row for inline editing, via DataTable syntax
1044 $caseActivities[$caseActivityId]['DT_RowAttr'] = array();
1045 $caseActivities[$caseActivityId]['DT_RowAttr']['data-entity'] = 'activity';
1046 $caseActivities[$caseActivityId]['DT_RowAttr']['data-id'] = $caseActivityId;
1048 //Activity Date and Time
1049 $caseActivities[$caseActivityId]['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1052 $caseActivities[$caseActivityId]['subject'] = $dao->subject
;
1055 $caseActivities[$caseActivityId]['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1056 . $activityTypes[$dao->type
]['label'];
1058 // Activity Target (With Contact) (There can be more than one)
1059 $targetContact = self
::formatContactLink($dao->target_contact_id
, $dao->target_contact_name
);
1060 if (empty($caseActivities[$caseActivityId]['target_contact_name'])) {
1061 $caseActivities[$caseActivityId]['target_contact_name'] = $targetContact;
1064 if (strpos($caseActivities[$caseActivityId]['target_contact_name'], $targetContact) === FALSE) {
1065 $caseActivities[$caseActivityId]['target_contact_name'] .= '; ' . $targetContact;
1069 // Activity Source Contact (Reporter) (There can only be one)
1070 $sourceContact = self
::formatContactLink($dao->source_contact_id
, $dao->source_contact_name
);
1071 $caseActivities[$caseActivityId]['source_contact_name'] = $sourceContact;
1073 // Activity Assignee (There can be more than one)
1074 $assigneeContact = self
::formatContactLink($dao->assignee_contact_id
, $dao->assignee_contact_name
);
1075 if (empty($caseActivities[$caseActivityId]['assignee_contact_name'])) {
1076 $caseActivities[$caseActivityId]['assignee_contact_name'] = $assigneeContact;
1079 if (strpos($caseActivities[$caseActivityId]['assignee_contact_name'], $assigneeContact) === FALSE) {
1080 $caseActivities[$caseActivityId]['assignee_contact_name'] .= '; ' . $assigneeContact;
1084 // Activity Status Label for Case activities list
1086 if ($dao->deleted
) {
1087 $deleted = '<br /> ' . ts('(deleted)');
1089 $caseActivities[$caseActivityId]['status_id'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status
) . $deleted;
1090 // if there are file attachments we will return how many
1091 if (!empty($dao->attachment_ids
)) {
1092 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1093 $caseActivity['no_attachments'] = count($attachmentIDs);
1096 $caseActivities[$caseActivityId]['links'] = self
::addCaseActivityLinks($caseID, $contactID, $userID, $context, $dao);
1099 $caseActivitiesDT = array();
1100 $caseActivitiesDT['data'] = array_values($caseActivities);
1101 $caseActivitiesDT['recordsTotal'] = $caseCount;
1102 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1104 return $caseActivitiesDT;
1108 * FIXME: This is a transitional function to facilitate a refactor of this to use CRM_Core_Action and actionLinks
1109 * Add the set of "actionLinks" to the case activity
1111 * @param int $caseID
1112 * @param int $contactID
1113 * @param int $userID
1114 * @param string $context
1115 * @param \CRM_Core_DAO $dao
1118 * HTML formatted Link
1120 private static function addCaseActivityLinks($caseID, $contactID, $userID, $context, $dao) {
1121 // FIXME: Why are we not using CRM_Core_Action for these links? This is too much manual work and likely to get out-of-sync with core markup.
1122 $caseActivityId = $dao->id
;
1123 $allowView = self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID);
1124 $allowEdit = self
::checkPermission($caseActivityId, 'edit', $dao->activity_type_id
, $userID);
1125 $allowDelete = self
::checkPermission($caseActivityId, 'delete', $dao->activity_type_id
, $userID);
1126 $emailActivityTypeIDs = [
1127 'Email' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email'),
1128 'Inbound Email' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email'),
1130 $url = CRM_Utils_System
::url("civicrm/case/activity",
1131 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1134 if ($context == 'fulltext') {
1135 $contextUrl = "&context={$context}";
1137 $editUrl = "{$url}&action=update{$contextUrl}";
1138 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1139 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1140 $viewTitle = ts('View activity');
1141 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1144 $css = 'class="action-item crm-hover-button"';
1146 $viewUrl = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1147 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1149 $additionalUrl = "&id={$caseActivityId}";
1150 if (!$dao->deleted
) {
1151 //hide edit link of activity type email.CRM-4530.
1152 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1153 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1155 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1159 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1162 elseif (!$caseDeleted) {
1163 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1166 //check for operations.
1167 if (self
::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id
)) {
1168 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1170 if (self
::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id
)) {
1171 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1173 // if there are file attachments we will return how many and, if only one, add a link to it
1174 if (!empty($dao->attachment_ids
)) {
1175 $url .= implode(' ', CRM_Core_BAO_File
::paperIconAttachment('civicrm_activity', $caseActivityId));
1182 * Helper function to generate a formatted contact link/name for display in the Case activities tab
1185 * @param $contactName
1189 private static function formatContactLink($contactId, $contactName) {
1190 if (empty($contactId)) {
1194 $hasViewContact = CRM_Contact_BAO_Contact_Permission
::allow($contactId);
1196 if ($hasViewContact) {
1197 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid={$contactId}");
1198 return "<a href=\"{$contactViewUrl}\">" . $contactName . "</a>";
1201 return $contactName;
1206 * Get Case Related Contacts.
1208 * @param int $caseID
1210 * @param bool $includeDetails
1211 * If true include details of contacts.
1214 * array of return properties
1217 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1218 $caseRoles = array();
1219 if ($includeDetails) {
1220 $caseInfo = civicrm_api3('Case', 'getsingle', array(
1222 // Most efficient way of retrieving definition is to also include case type id and name so the api doesn't have to look it up separately
1223 'return' => array('case_type_id', 'case_type_id.name', 'case_type_id.definition', 'contact_id'),
1225 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1226 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1232 SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, cr.relationship_type_id, crt.label_b_a as role, crt.name_b_a as role_name, ce.email, cp.phone
1233 FROM civicrm_relationship cr
1234 JOIN civicrm_relationship_type crt
1235 ON crt.id = cr.relationship_type_id
1236 JOIN civicrm_contact cc
1237 ON cc.id = cr.contact_id_a
1238 AND cc.is_deleted <> 1
1239 LEFT JOIN civicrm_email ce
1240 ON ce.contact_id = cc.id
1241 AND ce.is_primary= 1
1242 LEFT JOIN civicrm_phone cp
1243 ON cp.contact_id = cc.id
1244 AND cp.is_primary= 1
1245 WHERE cr.case_id = %1
1247 AND cc.id NOT IN (%2)
1249 SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, cr.relationship_type_id, crt.label_a_b as role, crt.name_a_b as role_name, ce.email, cp.phone
1250 FROM civicrm_relationship cr
1251 JOIN civicrm_relationship_type crt
1252 ON crt.id = cr.relationship_type_id
1253 JOIN civicrm_contact cc
1254 ON cc.id = cr.contact_id_b
1255 AND cc.is_deleted <> 1
1256 LEFT JOIN civicrm_email ce
1257 ON ce.contact_id = cc.id
1258 AND ce.is_primary= 1
1259 LEFT JOIN civicrm_phone cp
1260 ON cp.contact_id = cc.id
1261 AND cp.is_primary= 1
1262 WHERE cr.case_id = %1
1264 AND cc.id NOT IN (%2)
1267 1 => array($caseID, 'Integer'),
1268 2 => array(implode(',', $caseInfo['client_id']), 'String'),
1270 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1272 while ($dao->fetch()) {
1273 if (!$includeDetails) {
1274 $values[$dao->id
] = 1;
1278 'contact_id' => $dao->id
,
1279 'display_name' => $dao->name
,
1280 'sort_name' => $dao->sort_name
,
1281 'relationship_type_id' => $dao->relationship_type_id
,
1282 'role' => $dao->role
,
1283 'email' => $dao->email
,
1284 'phone' => $dao->phone
,
1286 // Add more info about the role (creator, manager)
1287 $role = CRM_Utils_Array
::value($dao->role_name
, $caseRoles);
1289 unset($role['name']);
1292 $values[] = $details;
1300 * Send e-mail copy of activity
1302 * @param int $clientId
1303 * @param int $activityId
1305 * @param array $contacts
1306 * Array of related contact.
1308 * @param null $attachments
1309 * @param int $caseId
1311 * @return bool |array
1313 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1318 $tplParams = $activityInfo = array();
1319 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1320 // If it's a case activity
1322 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1323 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1324 $anyActivity = TRUE;
1327 $anyActivity = FALSE;
1329 $tplParams['isCaseActivity'] = 1;
1330 $tplParams['client_id'] = $clientId;
1333 $anyActivity = TRUE;
1336 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1337 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1339 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1341 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1343 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1345 $tplParams['activityTypeName'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_DAO_Activity', 'activity_type_id', $activityTypeId);
1346 $tplParams['activity'] = $activityInfo;
1347 foreach ($tplParams['activity']['fields'] as $k => $val) {
1348 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1349 $activitySubject = $val['value'];
1353 $session = CRM_Core_Session
::singleton();
1354 // CRM-8926 If user is not logged in, use the activity creator as userID
1355 if (!($userID = $session->get('userID'))) {
1356 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1359 //also create activities simultaneously of this copy.
1360 $activityParams = array();
1362 $activityParams['source_record_id'] = $activityId;
1363 $activityParams['source_contact_id'] = $userID;
1364 $activityParams['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', 'Email');
1365 $activityParams['activity_date_time'] = date('YmdHis');
1366 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
1367 $activityParams['medium_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'encounter_medium', 'email');
1368 $activityParams['case_id'] = $caseId;
1369 $activityParams['is_auto'] = 0;
1370 $activityParams['target_id'] = $clientId;
1372 $tplParams['activitySubject'] = $activitySubject;
1374 // if it’s a case activity, add hashed id to the template (CRM-5916)
1376 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1380 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1381 $receiptFrom = self
::getReceiptFrom($activityId);
1383 $recordedActivityParams = array();
1385 foreach ($contacts as $mail => $info) {
1386 $tplParams['contact'] = $info;
1387 self
::buildPermissionLinks($tplParams, $activityParams);
1389 $displayName = CRM_Utils_Array
::value('display_name', $info);
1391 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1393 'groupName' => 'msg_tpl_workflow_case',
1394 'valueName' => 'case_activity',
1395 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1396 'tplParams' => $tplParams,
1397 'from' => $receiptFrom,
1398 'toName' => $displayName,
1400 'attachments' => $attachments,
1404 $activityParams['subject'] = ts('%1 - copy sent to %2', [1 => $activitySubject, 2 => $displayName]);
1405 $activityParams['details'] = $message;
1407 if (!empty($result[$info['contact_id']])) {
1409 * Really only need to record one activity with all the targets combined.
1410 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1411 * but it's always the same content at the moment.
1413 if (empty($recordedActivityParams)) {
1414 $recordedActivityParams = $activityParams;
1417 $recordedActivityParams['subject'] .= "; $displayName";
1419 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1422 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1426 if (!empty($recordedActivityParams)) {
1427 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1429 //create case_activity record if its case activity.
1431 $caseParams = array(
1432 'activity_id' => $activity->id
,
1433 'case_id' => $caseId,
1435 self
::processCaseActivity($caseParams);
1443 * Retrieve count of activities having a particular type, and
1444 * associated with a particular case.
1446 * @param int $caseId
1448 * @param int $activityTypeId
1449 * ID of the activity type.
1453 public static function getCaseActivityCount($caseId, $activityTypeId) {
1454 $queryParam = array(
1455 1 => array($caseId, 'Integer'),
1456 2 => array($activityTypeId, 'Integer'),
1458 $query = "SELECT count(ca.id) as countact
1459 FROM civicrm_activity ca
1460 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1461 WHERE ca.activity_type_id = %2
1462 AND cca.case_id = %1
1463 AND ca.is_deleted = 0";
1465 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1466 if ($dao->fetch()) {
1467 return $dao->countact
;
1474 * Create an activity for a case via email.
1479 * @return array|void
1480 * $activity object of newly creted activity via email
1482 public static function recordActivityViaEmail($file) {
1483 if (!file_exists($file) ||
1486 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1491 $result = CRM_Utils_Mail_Incoming
::parse($file);
1492 if ($result['is_error']) {
1496 foreach ($result['to'] as $to) {
1499 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1500 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1502 if ($replacement !== $to['email']) {
1503 $caseId = $replacement;
1504 //if caseId is invalid, return as error file
1505 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1506 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1515 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1516 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1517 $contactDetails = self
::getRelatedContacts($caseId, FALSE);
1519 if (!empty($contactDetails[$result['from']['id']])) {
1521 $params['subject'] = $result['subject'];
1522 $params['activity_date_time'] = $result['date'];
1523 $params['details'] = $result['body'];
1524 $params['source_contact_id'] = $result['from']['id'];
1525 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
1527 $details = CRM_Case_PseudoConstant
::caseActivityType();
1529 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1530 $result['body'], $matches
1533 if (!empty($matches) && isset($matches[1])) {
1534 $activityType = trim($matches[1]);
1535 if (isset($details[$activityType])) {
1536 $params['activity_type_id'] = $details[$activityType]['id'];
1539 if (!isset($params['activity_type_id'])) {
1540 $params['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email');
1544 $activity = CRM_Activity_BAO_Activity
::create($params);
1546 $caseParams = array(
1547 'activity_id' => $activity->id
,
1548 'case_id' => $caseId,
1550 self
::processCaseActivity($caseParams);
1553 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1554 array(1 => $result['from']['email'])
1561 * Retrieve the scheduled activity type and date.
1563 * @param array $cases
1564 * Array of contact and case id.
1566 * @param string $type
1569 * Array of scheduled activity type and date
1573 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1574 $session = CRM_Core_Session
::singleton();
1575 $userID = $session->get('userID');
1577 $caseID = implode(',', $cases['case_id']);
1578 $contactID = implode(',', $cases['contact_id']);
1580 $condition = " civicrm_case_contact.contact_id IN( {$contactID} )
1581 AND civicrm_case.id IN( {$caseID})
1582 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1584 $query = self
::getCaseActivityQuery($type, $userID, $condition);
1585 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id');
1587 $res = CRM_Core_DAO
::executeQuery($query);
1589 $activityInfo = array();
1590 while ($res->fetch()) {
1591 if ($type == 'upcoming') {
1592 $activityInfo[$res->case_id
]['date'] = $res->activity_date_time
;
1593 $activityInfo[$res->case_id
]['type'] = CRM_Utils_Array
::value($res->activity_type_id
, $activityTypes);
1596 $activityInfo[$res->case_id
]['date'] = $res->activity_date_time
;
1597 $activityInfo[$res->case_id
]['type'] = CRM_Utils_Array
::value($res->activity_type_id
, $activityTypes);
1601 return $activityInfo;
1605 * Combine all the exportable fields from the lower levels object.
1608 * array of exportable Fields
1610 public static function &exportableFields() {
1611 if (!self
::$_exportableFields) {
1612 if (!self
::$_exportableFields) {
1613 self
::$_exportableFields = array();
1616 $fields = CRM_Case_DAO_Case
::export();
1617 $fields['case_role'] = array('title' => ts('Role in Case'));
1618 $fields['case_type'] = array(
1619 'title' => ts('Case Type'),
1620 'name' => 'case_type',
1622 $fields['case_status'] = array(
1623 'title' => ts('Case Status'),
1624 'name' => 'case_status',
1627 // add custom data for cases
1628 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1630 self
::$_exportableFields = $fields;
1632 return self
::$_exportableFields;
1636 * Restore the record that are associated with this case.
1638 * @param int $caseId
1639 * Id of the case to restore.
1643 public static function restoreCase($caseId) {
1644 //restore activities
1645 $activities = self
::getCaseActivityDates($caseId);
1647 foreach ($activities as $value) {
1648 CRM_Activity_BAO_Activity
::restoreActivity($value);
1652 $case = new CRM_Case_DAO_Case();
1653 $case->id
= $caseId;
1654 $case->is_deleted
= 0;
1657 //CRM-7364, enable relationships
1658 self
::enableDisableCaseRelationships($caseId, TRUE);
1665 * @param null $showLinks
1666 * @param bool $returnOnlyCount
1667 * @param int $offset
1668 * @param int $rowCount
1672 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1673 $globalContacts = array();
1675 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1676 $settings = $settingsProcessor->run();
1677 if (!empty($settings)) {
1678 $groupInfo['name'] = $settings['groupname'];
1679 if ($groupInfo['name']) {
1680 $searchParams = array('name' => $groupInfo['name']);
1682 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1684 $groupInfo['id'] = $results['id'];
1685 $groupInfo['title'] = $results['title'];
1686 $params = array(array('group', '=', $groupInfo['id'], 0, 0));
1687 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1688 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1690 if ($returnOnlyCount) {
1691 return $globalContacts;
1695 foreach ($globalContacts as $idx => $contact) {
1696 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1702 return $globalContacts;
1706 * Convenience function to get both case contacts and global in one array.
1707 * @param int $caseId
1711 public static function getRelatedAndGlobalContacts($caseId) {
1712 $relatedContacts = self
::getRelatedContacts($caseId);
1714 $groupInfo = array();
1715 $globalContacts = self
::getGlobalContacts($groupInfo);
1717 //unset values which are not required.
1718 foreach ($globalContacts as $k => & $v) {
1719 unset($v['email_id']);
1720 unset($v['group_contact_id']);
1721 unset($v['status']);
1723 $v['role'] = $groupInfo['title'];
1725 //include multiple listings for the same contact/different roles.
1726 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1727 return $relatedGlobalContacts;
1731 * Get Case ActivitiesDueDates with given criteria.
1733 * @param int $caseID
1735 * @param array $criteriaParams
1737 * @param bool $latestDate
1738 * If set newest or oldest date is selected.
1741 * case activities due dates
1744 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1746 $selectDate = " ca.activity_date_time";
1747 $where = $groupBy = ' ';
1754 if (!empty($criteriaParams['activity_type_id'])) {
1755 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1756 $where .= " AND ca.is_current_revision = 1";
1757 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1760 if (!empty($criteriaParams['newest'])) {
1761 $selectDate = " max(ca.activity_date_time) ";
1764 $selectDate = " min(ca.activity_date_time) ";
1768 $query = "SELECT ca.id, {$selectDate} as activity_date
1769 FROM civicrm_activity ca
1770 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1771 WHERE cc.id = %1 {$where} {$groupBy}";
1773 $params = array(1 => array($caseID, 'Integer'));
1774 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1776 while ($dao->fetch()) {
1777 $values[$dao->id
]['id'] = $dao->id
;
1778 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1784 * Create activities when Case or Other roles assigned/modified/deleted.
1786 * @param int $caseId
1787 * @param int $relationshipId
1789 * @param int $relContactId
1790 * Case role assignee contactId.
1791 * @param int $contactId
1793 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1794 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1798 $queryParam = array();
1799 if (is_array($relationshipId)) {
1800 $relationshipId = implode(',', $relationshipId);
1801 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1804 $relationshipClause = " civicrm_relationship.id = %1";
1805 $queryParam[1] = array($relationshipId, 'Positive');
1809 SELECT cc.display_name as clientName,
1810 cca.display_name as assigneeContactName,
1811 civicrm_relationship.case_id as caseId,
1812 civicrm_relationship_type.label_a_b as relation_a_b,
1813 civicrm_relationship_type.label_b_a as relation_b_a,
1814 civicrm_relationship.contact_id_b as rel_contact_id,
1815 civicrm_relationship.contact_id_a as assign_contact_id
1816 FROM civicrm_relationship_type, civicrm_relationship
1817 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1818 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1819 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1821 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1823 while ($dao->fetch()) {
1824 // The assignee is not the client.
1825 if ($dao->rel_contact_id
!= $contactId) {
1826 $caseRelationship = $dao->relation_a_b
;
1827 $assigneContactName = $dao->clientName
;
1828 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1831 $caseRelationship = $dao->relation_b_a
;
1832 $assigneContactName = $dao->assigneeContactName
;
1833 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1837 $session = CRM_Core_Session
::singleton();
1838 $activityParams = array(
1839 'source_contact_id' => $session->get('userID'),
1840 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1841 'activity_date_time' => date('YmdHis'),
1842 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1845 //if $relContactId is passed, role is added or modified.
1846 if (!empty($relContactId)) {
1847 $activityParams['assignee_contact_id'] = $assigneContactIds;
1848 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Assign Case Role');
1851 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Remove Case Role');
1854 $activityParams['activity_type_id'] = $activityTypeID;
1856 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1858 //create case_activity record.
1859 $caseParams = array(
1860 'activity_id' => $activity->id
,
1861 'case_id' => $caseId,
1864 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1869 * contact which is assigned a case role of case manager.
1871 * @param int $caseType
1873 * @param int $caseId
1877 * html hyperlink of manager contact view page
1880 public static function getCaseManagerContact($caseType, $caseId) {
1881 if (!$caseType ||
!$caseId) {
1885 $caseManagerName = '---';
1886 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1888 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1890 if (!empty($managerRoleId)) {
1891 if (substr($managerRoleId, -4) == '_a_b') {
1892 $managerRoleQuery = "
1893 SELECT civicrm_contact.id as casemanager_id,
1894 civicrm_contact.sort_name as casemanager
1895 FROM civicrm_contact
1896 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1) AND civicrm_relationship.is_active
1897 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1898 WHERE civicrm_case.id = %2 AND is_active = 1";
1900 if (substr($managerRoleId, -4) == '_b_a') {
1901 $managerRoleQuery = "
1902 SELECT civicrm_contact.id as casemanager_id,
1903 civicrm_contact.sort_name as casemanager
1904 FROM civicrm_contact
1905 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_a = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1) AND civicrm_relationship.is_active
1906 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1907 WHERE civicrm_case.id = %2 AND is_active = 1";
1910 $managerRoleParams = array(
1911 1 => array(substr($managerRoleId, 0, -4), 'Integer'),
1912 2 => array($caseId, 'Integer'),
1915 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1916 if ($dao->fetch()) {
1917 $caseManagerName = sprintf('<a href="%s">%s</a>',
1918 CRM_Utils_System
::url('civicrm/contact/view', array('cid' => $dao->casemanager_id
)),
1924 return $caseManagerName;
1928 * @param int $contactId
1929 * @param bool $excludeDeleted
1933 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1934 $params = array('check_permissions' => TRUE);
1935 if ($excludeDeleted) {
1936 $params['is_deleted'] = 0;
1939 $params['contact_id'] = $contactId;
1942 return civicrm_api3('Case', 'getcount', $params);
1944 catch (CiviCRM_API3_Exception
$e) {
1945 // Lack of permissions will throw an exception
1951 * Retrieve related case ids for given case.
1953 * @param int $caseId
1954 * @param bool $excludeDeleted
1955 * Do not include deleted cases.
1959 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1960 //FIXME : do check for permissions.
1966 $linkActType = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Link Cases');
1967 if (!$linkActType) {
1971 $whereClause = "mainCase.id = %2";
1972 if ($excludeDeleted) {
1973 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1977 SELECT relCaseAct.case_id
1978 FROM civicrm_case mainCase
1979 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1980 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1981 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1982 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1983 WHERE $whereClause";
1985 $dao = CRM_Core_DAO
::executeQuery($query, array(
1986 1 => array($linkActType, 'Integer'),
1987 2 => array($caseId, 'Integer'),
1989 $relatedCaseIds = array();
1990 while ($dao->fetch()) {
1991 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1994 return array_values($relatedCaseIds);
1998 * Retrieve related case details for given case.
2000 * @param int $caseId
2001 * @param bool $excludeDeleted
2002 * Do not include deleted cases.
2006 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
2007 $relatedCaseIds = self
::getRelatedCaseIds($caseId, $excludeDeleted);
2008 $relatedCases = array();
2010 if (!$relatedCaseIds) {
2014 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2015 if ($excludeDeleted) {
2016 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2019 //filter for permissioned cases.
2020 $filterCases = array();
2021 $doFilterCases = FALSE;
2022 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2023 $doFilterCases = TRUE;
2024 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE);
2027 //2. fetch the details of related cases.
2029 SELECT relCase.id as id,
2030 civicrm_case_type.title as case_type,
2031 client.display_name as client_name,
2032 client.id as client_id,
2034 FROM civicrm_case relCase
2035 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2036 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2037 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
2038 WHERE {$whereClause}";
2040 $dao = CRM_Core_DAO
::executeQuery($query);
2041 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2042 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2043 $statuses = CRM_Case_BAO_Case
::buildOptions('status_id');
2045 while ($dao->fetch()) {
2047 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2048 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2049 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2050 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2052 $clientView = $dao->client_name
;
2053 if ($hasViewContact) {
2054 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2057 $relatedCases[$dao->id
] = array(
2058 'case_id' => $dao->id
,
2059 'case_type' => $dao->case_type
,
2060 'client_name' => $clientView,
2061 'case_status' => $statuses[$dao->status_id
],
2062 'links' => $caseView,
2066 return $relatedCases;
2070 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2072 * @see CRM_Dedupe_Merger::cpTables()
2074 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2076 * @param int $mainContactId
2077 * @param int $otherContactId
2079 public static function mergeContacts($mainContactId, $otherContactId) {
2080 self
::mergeCases($mainContactId, NULL, $otherContactId);
2084 * Function perform two task.
2085 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2086 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2088 * @param int $mainContactId
2089 * Contact id of main contact record.
2090 * @param int $mainCaseId
2091 * Case id of main case record.
2092 * @param int $otherContactId
2093 * Contact id of record which is going to merge.
2094 * @param int $otherCaseId
2095 * Case id of record which is going to merge.
2097 * @param bool $changeClient
2100 * @throws \CRM_Core_Exception
2102 public static function mergeCases(
2103 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2104 $otherCaseId = NULL, $changeClient = FALSE) {
2105 $moveToTrash = TRUE;
2107 $duplicateContacts = FALSE;
2108 if ($mainContactId && $otherContactId &&
2109 $mainContactId != $otherContactId
2111 $duplicateContacts = TRUE;
2114 $duplicateCases = FALSE;
2115 if ($mainCaseId && $otherCaseId &&
2116 $mainCaseId != $otherCaseId
2118 $duplicateCases = TRUE;
2121 $mainCaseIds = array();
2122 if (!$duplicateContacts && !$duplicateCases) {
2123 return $mainCaseIds;
2126 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'validate');
2127 $completedActivityStatus = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
2128 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2129 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2130 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2131 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2133 $processCaseIds = array($otherCaseId);
2134 if ($duplicateContacts && !$duplicateCases) {
2135 if ($changeClient) {
2136 $processCaseIds = array($mainCaseId);
2139 //get all case ids for other contact.
2140 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2142 if (!is_array($processCaseIds)) {
2147 $session = CRM_Core_Session
::singleton();
2148 $currentUserId = $session->get('userID');
2150 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2152 // copy all cases and connect to main contact id.
2153 foreach ($processCaseIds as $otherCaseId) {
2154 if ($duplicateContacts) {
2155 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2156 $mainCaseId = $mainCase->id
;
2161 // CRM-11662 Copy Case custom data
2162 $extends = array('case');
2163 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2165 foreach ($groupTree as $groupID => $group) {
2166 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2167 foreach ($group['fields'] as $fieldID => $field) {
2168 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2172 foreach ($table as $tableName => $tableColumns) {
2173 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2174 $tableColumns[0] = $mainCaseId;
2175 $select = 'SELECT ' . implode(', ', $tableColumns);
2176 $from = ' FROM ' . $tableName;
2177 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2178 $query = $insert . $select . $from . $where;
2179 $dao = CRM_Core_DAO
::executeQuery($query);
2183 $mainCaseIds[] = $mainCaseId;
2184 //insert record for case contact.
2185 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2186 $otherCaseContact->case_id
= $otherCaseId;
2187 $otherCaseContact->find();
2188 while ($otherCaseContact->fetch()) {
2189 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2190 $mainCaseContact->case_id
= $mainCaseId;
2191 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2192 if ($mainCaseContact->contact_id
== $otherContactId) {
2193 $mainCaseContact->contact_id
= $mainContactId;
2195 //avoid duplicate object.
2196 if (!$mainCaseContact->find(TRUE)) {
2197 $mainCaseContact->save();
2201 elseif (!$otherContactId) {
2202 $otherContactId = $mainContactId;
2205 if (!$mainCaseId ||
!$otherCaseId ||
2206 !$mainContactId ||
!$otherContactId
2211 // get all activities for other case.
2212 $otherCaseActivities = array();
2213 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2215 //for duplicate cases do not process singleton activities.
2216 $otherActivityIds = $singletonActivityIds = array();
2217 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2218 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2219 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2222 $otherActivityIds[] = $otherActId;
2224 if ($duplicateCases) {
2225 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2228 FROM civicrm_activity
2229 WHERE activity_type_id = $openCaseType
2230 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2231 $dao = CRM_Core_DAO
::executeQuery($sql);
2232 while ($dao->fetch()) {
2233 $singletonActivityIds[] = $dao->id
;
2238 // migrate all activities and connect to main contact.
2239 $copiedActivityIds = $activityMappingIds = array();
2240 sort($otherActivityIds);
2241 foreach ($otherActivityIds as $otherActivityId) {
2243 //for duplicate cases -
2244 //do not migrate singleton activities.
2245 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2249 //migrate activity record.
2250 $otherActivity = new CRM_Activity_DAO_Activity();
2251 $otherActivity->id
= $otherActivityId;
2252 if (!$otherActivity->find(TRUE)) {
2256 $mainActVals = array();
2257 $mainActivity = new CRM_Activity_DAO_Activity();
2258 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2259 $mainActivity->copyValues($mainActVals);
2260 $mainActivity->id
= NULL;
2261 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2262 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2266 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2270 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2273 $mainActivity->save();
2274 $mainActivityId = $mainActivity->id
;
2275 if (!$mainActivityId) {
2279 $activityMappingIds[$otherActivityId] = $mainActivityId;
2280 // insert log of all activities
2281 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2283 $copiedActivityIds[] = $otherActivityId;
2285 //create case activity record.
2286 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2287 $mainCaseActivity->case_id
= $mainCaseId;
2288 $mainCaseActivity->activity_id
= $mainActivityId;
2289 $mainCaseActivity->save();
2291 //migrate source activity.
2292 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2293 $otherSourceActivity->activity_id
= $otherActivityId;
2294 $otherSourceActivity->record_type_id
= $sourceID;
2295 $otherSourceActivity->find();
2296 while ($otherSourceActivity->fetch()) {
2297 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2298 $mainActivitySource->record_type_id
= $sourceID;
2299 $mainActivitySource->activity_id
= $mainActivityId;
2300 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2301 if ($mainActivitySource->contact_id
== $otherContactId) {
2302 $mainActivitySource->contact_id
= $mainContactId;
2304 //avoid duplicate object.
2305 if (!$mainActivitySource->find(TRUE)) {
2306 $mainActivitySource->save();
2310 //migrate target activities.
2311 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2312 $otherTargetActivity->activity_id
= $otherActivityId;
2313 $otherTargetActivity->record_type_id
= $targetID;
2314 $otherTargetActivity->find();
2315 while ($otherTargetActivity->fetch()) {
2316 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2317 $mainActivityTarget->record_type_id
= $targetID;
2318 $mainActivityTarget->activity_id
= $mainActivityId;
2319 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2320 if ($mainActivityTarget->contact_id
== $otherContactId) {
2321 $mainActivityTarget->contact_id
= $mainContactId;
2323 //avoid duplicate object.
2324 if (!$mainActivityTarget->find(TRUE)) {
2325 $mainActivityTarget->save();
2329 //migrate assignee activities.
2330 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2331 $otherAssigneeActivity->activity_id
= $otherActivityId;
2332 $otherAssigneeActivity->record_type_id
= $assigneeID;
2333 $otherAssigneeActivity->find();
2334 while ($otherAssigneeActivity->fetch()) {
2335 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2336 $mainAssigneeActivity->activity_id
= $mainActivityId;
2337 $mainAssigneeActivity->record_type_id
= $assigneeID;
2338 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2339 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2340 $mainAssigneeActivity->contact_id
= $mainContactId;
2342 //avoid duplicate object.
2343 if (!$mainAssigneeActivity->find(TRUE)) {
2344 $mainAssigneeActivity->save();
2348 // copy custom fields and attachments
2350 'activityID' => $otherActivityId,
2351 'mainActivityId' => $mainActivityId,
2353 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2356 //copy case relationship.
2357 if ($duplicateContacts) {
2358 //migrate relationship records.
2359 $otherRelationship = new CRM_Contact_DAO_Relationship();
2360 $otherRelationship->case_id
= $otherCaseId;
2361 $otherRelationship->find();
2362 $otherRelationshipIds = array();
2363 while ($otherRelationship->fetch()) {
2364 $otherRelVals = array();
2365 $updateOtherRel = FALSE;
2366 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2368 $mainRelationship = new CRM_Contact_DAO_Relationship();
2369 $mainRelationship->copyValues($otherRelVals);
2370 $mainRelationship->id
= NULL;
2371 $mainRelationship->case_id
= $mainCaseId;
2372 if ($mainRelationship->contact_id_a
== $otherContactId) {
2373 $updateOtherRel = TRUE;
2374 $mainRelationship->contact_id_a
= $mainContactId;
2377 //case creator change only when we merge user contact.
2378 if ($mainRelationship->contact_id_b
== $otherContactId) {
2379 //do not change creator for change client.
2380 if (!$changeClient) {
2381 $updateOtherRel = TRUE;
2382 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2385 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2386 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2388 //avoid duplicate object.
2389 if (!$mainRelationship->find(TRUE)) {
2390 $mainRelationship->save();
2393 //get the other relationship ids to update end date.
2394 if ($updateOtherRel) {
2395 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2399 //update other relationships end dates
2400 if (!empty($otherRelationshipIds)) {
2401 $sql = 'UPDATE civicrm_relationship
2402 SET end_date = CURDATE()
2403 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2404 CRM_Core_DAO
::executeQuery($sql);
2408 //move other case to trash.
2409 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2414 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2415 if ($changeClient) {
2416 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2417 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2419 $mergeActType = array_search('Reassigned Case', $activityTypes);
2420 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2423 2 => $otherContactDisplayName,
2424 3 => $mainContactDisplayName,
2429 elseif ($duplicateContacts) {
2430 $mergeActType = array_search('Merge Case', $activityTypes);
2431 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2434 2 => $otherContactId,
2435 3 => $mainContactId,
2441 $mergeActType = array_search('Merge Case', $activityTypes);
2442 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2443 if (!empty($copiedActivityIds)) {
2445 SELECT id, subject, activity_date_time, activity_type_id
2446 FROM civicrm_activity
2447 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2448 $dao = CRM_Core_DAO
::executeQuery($sql);
2449 while ($dao->fetch()) {
2450 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2451 if ($dao->subject
) {
2452 $mergeActSubjectDetails .= " :: {$dao->subject}";
2454 $mergeActSubjectDetails .= "<br />";
2459 // Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2460 $activityParams = array(
2461 'subject' => $mergeActSubject,
2462 'details' => $mergeActSubjectDetails,
2463 'status_id' => $completedActivityStatus,
2464 'activity_type_id' => $mergeActType,
2465 'source_contact_id' => $currentUserId,
2466 'activity_date_time' => date('YmdHis'),
2469 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2470 $mergeActivityId = $mergeActivity->id
;
2471 if (!$mergeActivityId) {
2475 //connect merge activity to case.
2476 $mergeCaseAct = array(
2477 'case_id' => $mainCaseId,
2478 'activity_id' => $mergeActivityId,
2481 self
::processCaseActivity($mergeCaseAct);
2484 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2486 return $mainCaseIds;
2490 * Validate contact permission for
2491 * edit/view on activity record and build links.
2493 * @param array $tplParams
2494 * Params to be sent to template for sending email.
2495 * @param array $activityParams
2496 * Info of the activity.
2498 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2499 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2500 'activity_type_id', 'id'
2503 if (!empty($tplParams['isCaseActivity'])) {
2504 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2505 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2508 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2509 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2512 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2513 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2517 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2518 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2521 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2522 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2528 * Validate contact permission for
2529 * given operation on activity record.
2531 * @param int $activityId
2532 * Activity record id.
2533 * @param string $operation
2535 * @param int $actTypeId
2537 * @param int $contactId
2538 * Contact id/if not pass consider logged in.
2539 * @param bool $checkComponent
2540 * Do we need to check component enabled.
2544 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2546 if (!$actTypeId && $activityId) {
2547 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2550 if (!$activityId ||
!$operation ||
!$actTypeId) {
2554 //do check for civicase component enabled.
2555 if ($checkComponent && !self
::enabled()) {
2559 //do check for cases.
2560 $caseActOperations = array(
2567 if (in_array($operation, $caseActOperations)) {
2569 if (!isset($caseCount)) {
2571 $caseCount = civicrm_api3('Case', 'getcount', array(
2572 'check_permissions' => TRUE,
2573 'status_id' => array('!=' => 'Closed'),
2575 'end_date' => array('IS NULL' => 1),
2578 catch (CiviCRM_API3_Exception
$e) {
2579 // Lack of permissions will throw an exception
2583 if ($operation == 'File On Case') {
2584 $allow = !empty($caseCount);
2587 $allow = ($caseCount > 1);
2591 $actionOperations = array('view', 'edit', 'delete');
2592 if (in_array($operation, $actionOperations)) {
2594 //do cache when user has non/supper permission.
2595 static $allowOperations;
2597 if (!is_array($allowOperations) ||
2598 !array_key_exists($operation, $allowOperations)
2602 $session = CRM_Core_Session
::singleton();
2603 $contactId = $session->get('userID');
2606 //check for permissions.
2607 $permissions = array(
2609 'access my cases and activities',
2610 'access all cases and activities',
2613 'access my cases and activities',
2614 'access all cases and activities',
2616 'delete' => array('delete activities'),
2619 //check for core permission.
2620 $hasPermissions = array();
2621 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2622 if (is_array($checkPermissions)) {
2623 foreach ($checkPermissions as $per) {
2624 if (CRM_Core_Permission
::check($per)) {
2625 $hasPermissions[$operation][] = $per;
2631 if (!empty($hasPermissions)) {
2632 //need to check activity object specific.
2633 if (in_array($operation, array(
2638 //do we have supper permission.
2639 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2640 $allowOperations[$operation] = $allow = TRUE;
2643 //user has only access to my cases and activity.
2644 //here object specific permmions come in picture.
2646 //edit - contact must be source or assignee
2647 //view - contact must be source/assignee/target
2648 $isTarget = $isAssignee = $isSource = FALSE;
2649 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2650 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2651 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2652 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2654 $target = new CRM_Activity_DAO_ActivityContact();
2655 $target->record_type_id
= $targetID;
2656 $target->activity_id
= $activityId;
2657 $target->contact_id
= $contactId;
2658 if ($target->find(TRUE)) {
2662 $assignee = new CRM_Activity_DAO_ActivityContact();
2663 $assignee->activity_id
= $activityId;
2664 $assignee->record_type_id
= $assigneeID;
2665 $assignee->contact_id
= $contactId;
2666 if ($assignee->find(TRUE)) {
2670 $source = new CRM_Activity_DAO_ActivityContact();
2671 $source->activity_id
= $activityId;
2672 $source->record_type_id
= $sourceID;
2673 $source->contact_id
= $contactId;
2674 if ($source->find(TRUE)) {
2678 if ($operation == 'edit') {
2679 if ($isAssignee ||
$isSource) {
2683 if ($operation == 'view') {
2684 if ($isTarget ||
$isAssignee ||
$isSource) {
2690 elseif (is_array($hasPermissions[$operation])) {
2691 $allowOperations[$operation] = $allow = TRUE;
2695 //contact do not have permission.
2696 $allowOperations[$operation] = FALSE;
2701 //here contact might have supper/non permission.
2702 $allow = $allowOperations[$operation];
2706 //do further only when operation is granted.
2708 $actTypeName = CRM_Core_PseudoConstant
::getName('CRM_Activity_BAO_Activity', 'activity_type_id', $actTypeId);
2710 //do not allow multiple copy / edit action.
2711 $singletonNames = array(
2721 //do not allow to delete these activities, CRM-4543
2722 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2724 //allow edit operation.
2725 $allowEditNames = array('Open Case');
2727 if (CRM_Activity_BAO_Activity
::checkEditInboundEmailsPermissions()) {
2728 $allowEditNames[] = 'Inbound Email';
2731 // do not allow File on Case
2732 $doNotFileNames = array(
2735 'Change Case Status',
2736 'Change Case Start Date',
2743 if (in_array($actTypeName, $singletonNames)) {
2745 if ($operation == 'File On Case') {
2746 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2748 if (in_array($operation, $actionOperations)) {
2750 if ($operation == 'edit') {
2751 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2753 elseif ($operation == 'delete') {
2754 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2758 if ($allow && ($operation == 'delete') &&
2759 in_array($actTypeName, $doNotDeleteNames)
2764 if ($allow && ($operation == 'File On Case') &&
2765 in_array($actTypeName, $doNotFileNames)
2770 //check settings file for masking actions
2771 //on the basis the activity types
2772 //hide Edit link if activity type is NOT editable
2773 //(special case activities).CRM-5871
2774 if ($allow && in_array($operation, $actionOperations)) {
2775 static $actionFilter = array();
2776 if (!array_key_exists($operation, $actionFilter)) {
2777 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2778 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2780 if (array_key_exists($operation, $actionFilter[$operation]) &&
2781 in_array($actTypeId, $actionFilter[$operation][$operation])
2792 * Since we drop 'access CiviCase', allow access
2793 * if user has 'access my cases and activities'
2794 * or 'access all cases and activities'
2796 public static function accessCiviCase() {
2797 if (!self
::enabled()) {
2801 if (CRM_Core_Permission
::check('access my cases and activities') ||
2802 CRM_Core_Permission
::check('access all cases and activities')
2811 * Verify user has permission to access a case.
2813 * @param int $caseId
2814 * @param bool $denyClosed
2815 * Set TRUE if one wants closed cases to be treated as inaccessible.
2819 public static function accessCase($caseId, $denyClosed = TRUE) {
2820 if (!$caseId ||
!self
::enabled()) {
2824 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2825 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2826 $params['status_id'] = array('!=' => 'Closed');
2829 return (bool) civicrm_api3('Case', 'getcount', $params);
2831 catch (CiviCRM_API3_Exception
$e) {
2832 // Lack of permissions will throw an exception
2838 * Check whether activity is a case Activity.
2840 * @param int $activityID
2845 public static function isCaseActivity($activityID) {
2846 $isCaseActivity = FALSE;
2848 $params = array(1 => array($activityID, 'Integer'));
2849 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2850 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2851 $isCaseActivity = TRUE;
2855 return $isCaseActivity;
2859 * Get all the case type ids currently in use.
2863 public static function getUsedCaseType() {
2864 static $caseTypeIds;
2866 if (!is_array($caseTypeIds)) {
2867 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2869 $dao = CRM_Core_DAO
::executeQuery($query);
2870 $caseTypeIds = array();
2871 while ($dao->fetch()) {
2872 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2875 $caseTypeIds[] = $typeId[1];
2879 return $caseTypeIds;
2883 * Get all the case status ids currently in use.
2887 public static function getUsedCaseStatuses() {
2888 static $caseStatusIds;
2890 if (!is_array($caseStatusIds)) {
2891 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2893 $dao = CRM_Core_DAO
::executeQuery($query);
2894 $caseStatusIds = array();
2895 while ($dao->fetch()) {
2896 $caseStatusIds[] = $dao->status_id
;
2900 return $caseStatusIds;
2904 * Get all the encounter medium ids currently in use.
2908 public static function getUsedEncounterMediums() {
2911 if (!is_array($mediumIds)) {
2912 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2914 $dao = CRM_Core_DAO
::executeQuery($query);
2915 $mediumIds = array();
2916 while ($dao->fetch()) {
2917 $mediumIds[] = $dao->medium_id
;
2925 * Check case configuration.
2927 * @param int $contactId
2931 public static function isCaseConfigured($contactId = NULL) {
2932 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2934 //lets check for case configured.
2935 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2936 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2937 if (!$configured['configured']) {
2938 //do check for case type and case status.
2939 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2940 if (!empty($caseTypes)) {
2941 $configured['configured'] = TRUE;
2942 if (!$configured['configured']) {
2943 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2944 if (!empty($caseStatuses)) {
2945 $configured['configured'] = TRUE;
2950 if ($configured['configured']) {
2951 //do check for active case type and case status.
2952 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2953 if (!empty($caseTypes)) {
2954 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2955 if (!empty($caseStatuses)) {
2956 $configured['allowToAddNewCase'] = TRUE;
2960 //do we need to redirect user to case admin.
2961 if (!$configured['allowToAddNewCase'] && $contactId) {
2962 //check for current contact case count.
2963 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2964 //redirect user to case admin page.
2965 if (!$currentContatCasesCount) {
2966 $configured['redirectToCaseAdmin'] = TRUE;
2975 * Used during case component enablement and during ugprade.
2979 public static function createCaseViews() {
2980 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2981 $dao = new CRM_Core_DAO();
2983 $sql = self
::createCaseViewsQuery('upcoming');
2985 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2989 // Above error doesn't get caught?
2990 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2991 if (is_null($doublecheck)) {
2995 $sql = self
::createCaseViewsQuery('recent');
2997 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3001 // Above error doesn't get caught?
3002 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3003 if (is_null($doublecheck)) {
3011 * Helper function, also used by the upgrade in case of error
3013 * @param string $section
3017 public static function createCaseViewsQuery($section = 'upcoming') {
3019 $scheduled_id = CRM_Core_Pseudoconstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
3022 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3023 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3024 FROM civicrm_case_activity ca
3025 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3027 (SELECT b.id FROM civicrm_case_activity bca
3028 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3029 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3030 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
3031 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
3035 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3036 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3037 FROM civicrm_case_activity ca
3038 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3040 (SELECT b.id FROM civicrm_case_activity bca
3041 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3042 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3043 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
3044 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
3051 * Add/copy relationships, when new client is added for a case
3053 * @param int $caseId
3055 * @param int $contactId
3056 * Contact id / new client id.
3058 public static function addCaseRelationships($caseId, $contactId) {
3059 // get the case role / relationships for the case
3060 $caseRelationships = new CRM_Contact_DAO_Relationship();
3061 $caseRelationships->case_id
= $caseId;
3062 $caseRelationships->find();
3063 $relationshipTypes = array();
3065 // make sure we don't add duplicate relationships of same relationship type.
3066 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3068 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3070 // add relationship for new client.
3071 $newRelationship = new CRM_Contact_DAO_Relationship();
3072 $newRelationship->copyValues($values);
3073 $newRelationship->id
= NULL;
3074 $newRelationship->case_id
= $caseId;
3075 $newRelationship->contact_id_a
= $contactId;
3076 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3077 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3079 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3080 if (!$newRelationship->find(TRUE)) {
3081 $newRelationship->save();
3084 // store relationship type of newly created relationship
3085 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3090 * Get the list of clients for a case.
3092 * @param int $caseId
3095 * associated array with client ids
3097 public static function getCaseClients($caseId) {
3099 $caseContact = new CRM_Case_DAO_CaseContact();
3100 $caseContact->case_id
= $caseId;
3101 $caseContact->orderBy('id');
3102 $caseContact->find();
3104 while ($caseContact->fetch()) {
3105 $clients[] = $caseContact->contact_id
;
3112 * @param int $caseId
3113 * @param string $direction
3115 * @param int $relTypeId
3116 * @throws \CRM_Core_Exception
3117 * @throws \CiviCRM_API3_Exception
3119 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3121 if ($direction !== 'a' && $direction !== 'b') {
3122 throw new CRM_Core_Exception('Invalid relationship direction');
3125 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3126 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3127 $dao = CRM_Core_DAO
::executeQuery($sql, array(
3128 1 => array($caseId, 'Positive'),
3129 2 => array($cid, 'Positive'),
3130 3 => array($relTypeId, 'Positive'),
3132 while ($dao->fetch()) {
3133 civicrm_api3('relationship', 'create', array(
3136 'end_date' => 'now',
3142 * Get options for a given case field.
3143 * @see CRM_Core_DAO::buildOptions
3145 * @param string $fieldName
3146 * @param string $context
3147 * @see CRM_Core_DAO::buildOptionsContext
3148 * @param array $props
3149 * Whatever is known about this dao object.
3151 * @return array|bool
3153 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3154 $className = __CLASS__
;
3156 switch ($fieldName) {
3157 // This field is not part of this object but the api supports it
3159 $className = 'CRM_Activity_BAO_Activity';
3162 // Filter status id by case type id
3164 if (!empty($props['case_type_id'])) {
3165 $idField = is_numeric($props['case_type_id']) ?
'id' : 'name';
3166 $caseType = civicrm_api3('CaseType', 'getsingle', array($idField => $props['case_type_id'], 'return' => 'definition'));
3167 if (!empty($caseType['definition']['statuses'])) {
3168 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
3173 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3179 public function addSelectWhereClause() {
3180 // We always return an array with these keys, even if they are empty,
3181 // because this tells the query builder that we have considered these fields for acls
3184 // Only case admins can view deleted cases
3185 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
array() : array("= 0"),
3187 // Ensure the user has permission to view the case client
3188 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3189 if ($contactClause) {
3190 $contactClause = implode(' AND contact_id ', $contactClause);
3191 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3193 // The api gatekeeper ensures the user has at least "access my cases and activities"
3194 // so if they do not have permission to see all cases we'll assume they can only access their own
3195 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3196 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3197 $clauses['id'][] = "IN (
3198 SELECT r.case_id FROM civicrm_relationship r, civicrm_case_contact cc WHERE r.is_active = 1 AND cc.case_id = r.case_id AND (
3199 (r.contact_id_a = cc.contact_id AND r.contact_id_b = $user) OR (r.contact_id_b = cc.contact_id AND r.contact_id_a = $user)
3203 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3208 * CRM-20308: Method to get the contact id to use as from contact for email copy
3209 * 1. Activity Added by Contact's email address
3210 * 2. System Default From Address
3211 * 3. Default Organization Contact email address
3214 * @param int $activityID
3216 * @return mixed $emailFromContactId
3217 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3219 public static function getReceiptFrom($activityID) {
3220 $name = $address = NULL;
3222 if (!empty($activityID) && (Civi
::settings()->get('allow_mail_from_logged_in_contact'))) {
3223 // This breaks SPF/DMARC if email is sent from an email address that the server is not authorised to send from.
3224 // so we can disable this behaviour with the "allow_mail_from_logged_in_contact" setting.
3225 // There is always a 'Added by' contact for a activity,
3226 // so we can safely use ActivityContact.Getvalue API
3227 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', array(
3228 'activity_id' => $activityID,
3229 'record_type_id' => 'Activity Source',
3230 'return' => 'contact_id',
3232 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3235 // If 'From' email address not found for Source Activity Contact then
3236 // fetch the email from domain or logged in user.
3237 if (empty($address)) {
3238 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3241 return "$name <$address>";
3247 public static function getEntityRefFilters() {
3250 'key' => 'case_id.case_type_id',
3251 'value' => ts('Case Type'),
3255 'key' => 'case_id.status_id',
3256 'value' => ts('Case Status'),
3260 foreach (CRM_Contact_BAO_Contact
::getEntityRefFilters() as $filter) {
3261 $filter +
= ['entity' => 'Contact'];
3262 $filter['key'] = 'contact_id.' . $filter['key'];
3263 $filters[] = $filter;
3269 * Fetch Case Role direction from Case Type
3271 public static function getCaseRoleDirection($caseId, $roleTypeId = NULL) {
3273 $case = civicrm_api3('Case', 'getsingle', array('id' => $caseId));
3275 catch (CiviCRM_API3_Exception
$e) {
3276 // Lack of permissions will throw an exception
3279 if (!empty($case['case_type_id'])) {
3281 $caseType = civicrm_api3('CaseType', 'getsingle', array('id' => $case['case_type_id'], 'return' => array('definition')));
3283 catch (CiviCRM_API3_Exception
$e) {
3284 // Lack of permissions will throw an exception
3285 return 'no case type found';
3287 if (!empty($caseType['definition']['caseRoles'])) {
3288 $caseRoles = array();
3289 foreach ($caseType['definition']['caseRoles'] as $key => $roleDetails) {
3290 // Check if its an a_b label
3292 $relType = civicrm_api3('RelationshipType', 'getsingle', array('label_a_b' => $roleDetails['name']));
3294 catch (CiviCRM_API3_Exception
$e) {
3296 if (!empty($relType['id'])) {
3297 $roleDetails['id'] = $relType['id'];
3298 $roleDetails['direction'] = 'a_b';
3300 // Check if its a b_a label
3302 $relTypeBa = civicrm_api3('RelationshipType', 'getsingle', array('label_b_a' => $roleDetails['name']));
3304 catch (CiviCRM_API3_Exception
$e) {
3306 if (!empty($relTypeBa['id'])) {
3307 if (!empty($roleDetails['direction'])) {
3308 $roleDetails['direction'] = 'bidrectional';
3311 $roleDetails['id'] = $relTypeBa['id'];
3312 $roleDetails['direction'] = 'b_a';
3315 $caseRoles[$roleDetails['id']] = $roleDetails;