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',
433 'civicrm_case.case_type_id as case_type_id',
434 'civicrm_case.status_id as case_status_id',
436 'civicrm_case.start_date as case_start_date',
437 'case_relation_type.label_b_a 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');
444 $query .= " FROM civicrm_case
445 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
446 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
448 if ($type == 'upcoming') {
449 // This gets the earliest activity per case that's scheduled within 14 days from now.
450 // Note we have an inner select to get the min activity id in order to remove duplicates in case there are two with the same datetime.
451 // In this case we don't really care which one, so min(id) works.
452 // optimized in CRM-11837
453 $query .= " INNER JOIN
455 SELECT case_id, act.id, activity_date_time, activity_type_id, status_id
460 FROM civicrm_view_case_activity_upcoming
461 ORDER BY activity_date_time ASC, id ASC
465 ON t_act.case_id = civicrm_case.id
468 elseif ($type == 'recent') {
469 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
470 //improve query performance - CRM-10598
471 $query .= " INNER JOIN
473 SELECT case_id, act.id, activity_date_time, activity_type_id, status_id
478 FROM civicrm_view_case_activity_recent
479 ORDER BY activity_date_time DESC, id ASC
483 ON t_act.case_id = civicrm_case.id ";
485 elseif ($type == 'any') {
486 $query .= " LEFT JOIN civicrm_case_activity ca4
487 ON civicrm_case.id = ca4.case_id
488 LEFT JOIN civicrm_activity t_act
489 ON t_act.id = ca4.activity_id
490 AND t_act.is_current_revision = 1";
494 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
495 LEFT JOIN civicrm_relationship case_relationship
496 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active AND case_relationship.case_id = civicrm_case.id )
497 LEFT JOIN civicrm_relationship_type case_relation_type
498 ON ( case_relation_type.id = case_relationship.relationship_type_id
499 AND case_relation_type.id = case_relationship.relationship_type_id )
503 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
504 $query .= " WHERE (1) AND $condition ";
506 $query .= " GROUP BY case_id ";
508 $query .= ($order) ?
: ' ORDER BY activity_date_time ASC';
518 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
520 * @param bool $allCases
521 * @param array $params
522 * @param string $context
523 * @param bool $getCount
528 public static function getCases($allCases = TRUE, $params = array(), $context = 'dashboard', $getCount = FALSE) {
530 $casesList = array();
532 // validate access for own cases.
533 if (!self
::accessCiviCase()) {
534 return $getCount ?
0 : $casesList;
537 // Return cached value instead of re-running query
538 if (isset(Civi
::$statics[__CLASS__
]['totalCount']) && $getCount) {
539 return Civi
::$statics[__CLASS__
]['totalCount'];
542 $type = CRM_Utils_Array
::value('type', $params, 'upcoming');
543 $userID = CRM_Core_Session
::singleton()->get('userID');
545 // validate access for all cases.
546 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
550 $whereClauses = array('civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1');
553 $whereClauses[] .= " case_relationship.contact_id_b = {$userID} AND case_relationship.is_active ";
555 if (empty($params['status_id']) && ($type == 'upcoming' ||
$type == 'any')) {
556 $whereClauses[] = " civicrm_case.status_id != " . CRM_Core_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
559 foreach (array('case_type_id', 'status_id') as $column) {
560 if (!empty($params[$column])) {
561 $whereClauses[] = sprintf("civicrm_case.%s IN (%s)", $column, $params[$column]);
564 $condition = implode(' AND ', $whereClauses);
566 Civi
::$statics[__CLASS__
]['totalCount'] = $totalCount = CRM_Core_DAO
::singleValueQuery(self
::getCaseActivityCountQuery($type, $userID, $condition));
570 $casesList['total'] = $totalCount;
573 if (!empty($params['rp'])) {
574 $params['offset'] = ($params['page'] - 1) * $params['rp'];
575 $params['rowCount'] = $params['rp'];
576 if (!empty($params['rowCount']) && $params['rowCount'] > 0) {
577 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
582 if (!empty($params['sortBy'])) {
583 if (strstr($params['sortBy'], 'date ')) {
584 $params['sortBy'] = str_replace('date', 'activity_date_time', $params['sortBy']);
586 $order = "ORDER BY " . $params['sortBy'];
589 $query = self
::getCaseActivityQuery($type, $userID, $condition, $limit, $order);
590 $result = CRM_Core_DAO
::executeQuery($query);
592 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
593 $actions = CRM_Case_Selector_Search
::links();
595 // check is the user has view/edit signer permission
596 $permissions = array(CRM_Core_Permission
::VIEW
);
597 if (CRM_Core_Permission
::check('access all cases and activities') ||
598 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
600 $permissions[] = CRM_Core_Permission
::EDIT
;
602 if (CRM_Core_Permission
::check('delete in CiviCase')) {
603 $permissions[] = CRM_Core_Permission
::DELETE
;
605 $mask = CRM_Core_Action
::mask($permissions);
607 // Pseudoconstants to populate labels
608 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
609 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
610 $caseTypeTitles = CRM_Case_PseudoConstant
::caseType('title', FALSE);
611 $activityTypeLabels = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id');
613 foreach ($result->fetchAll() as $case) {
614 $key = $case['case_id'];
615 $casesList[$key] = array();
616 $casesList[$key]['DT_RowId'] = $case['case_id'];
617 $casesList[$key]['DT_RowAttr'] = array('data-entity' => 'case', 'data-id' => $case['case_id']);
618 $casesList[$key]['DT_RowClass'] = "crm-entity";
620 $casesList[$key]['activity_list'] = sprintf('<a title="%s" class="crm-expand-row" href="%s"></a>',
622 CRM_Utils_System
::url('civicrm/case/details', array('caseId' => $case['case_id'], 'cid' => $case['contact_id'], 'type' => $type))
625 $phone = empty($case['phone']) ?
'' : '<br /><span class="description">' . $case['phone'] . '</span>';
626 $casesList[$key]['contact_id'] = sprintf('<a href="%s">%s</a>%s<br /><span class="description">%s: %d</span>',
627 CRM_Utils_System
::url('civicrm/contact/view', array('cid' => $case['contact_id'])),
633 $casesList[$key]['subject'] = $case['case_subject'];
634 $casesList[$key]['case_status'] = CRM_Utils_Array
::value($case['case_status_id'], $caseStatuses);
635 if ($case['case_status_id'] == CRM_Case_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Urgent')) {
636 $casesList[$key]['case_status'] = sprintf('<strong>%s</strong>', strtoupper($casesList[$key]['case_status']));
638 $casesList[$key]['case_type'] = CRM_Utils_Array
::value($case['case_type_id'], $caseTypeTitles);
639 $casesList[$key]['case_role'] = CRM_Utils_Array
::value('case_role', $case, '---');
640 $casesList[$key]['manager'] = self
::getCaseManagerContact($caseTypes[$case['case_type_id']], $case['case_id']);
642 $casesList[$key]['date'] = CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels);
643 if ($actId = CRM_Utils_Array
::value('activity_id', $case)) {
644 if (self
::checkPermission($actId, 'view', $case['activity_type_id'], $userID)) {
645 if ($type == 'recent') {
646 $casesList[$key]['date'] = sprintf('<a class="action-item crm-hover-button" href="%s" title="%s">%s</a>',
647 CRM_Utils_System
::url('civicrm/case/activity/view', array('reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id'])),
649 CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels)
653 $status = CRM_Utils_Date
::overdue($case['activity_date_time']) ?
'status-overdue' : 'status-scheduled';
654 $casesList[$key]['date'] = sprintf('<a class="crm-popup %s" href="%s" title="%s">%s</a> ',
656 CRM_Utils_System
::url('civicrm/case/activity/view', array('reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case['activity_id'])),
658 CRM_Utils_Array
::value($case['activity_type_id'], $activityTypeLabels)
662 if (isset($case['activity_type_id']) && self
::checkPermission($actId, 'edit', $case['activity_type_id'], $userID)) {
663 $casesList[$key]['date'] .= sprintf('<a class="action-item crm-hover-button" href="%s" title="%s"><i class="crm-i fa-pencil"></i></a>',
664 CRM_Utils_System
::url('civicrm/case/activity', array('reset' => 1, 'cid' => $case['contact_id'], 'caseid' => $case['case_id'], 'action' => 'update', 'id' => $actId)),
669 $casesList[$key]['date'] .= "<br/>" . CRM_Utils_Date
::customFormat($case['activity_date_time']);
670 $casesList[$key]['links'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
672 'id' => $case['case_id'],
673 'cid' => $case['contact_id'],
678 'case.actions.primary',
688 * Get the summary of cases counts by type and status.
690 * @param bool $allCases
693 public static function getCasesSummary($allCases = TRUE) {
694 $caseSummary = array();
696 //validate access for civicase.
697 if (!self
::accessCiviCase()) {
701 $userID = CRM_Core_Session
::singleton()->get('userID');
703 //validate access for all cases.
704 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
708 $caseTypes = CRM_Case_PseudoConstant
::caseType();
709 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
710 $caseTypes = array_flip($caseTypes);
712 // get statuses as headers for the table
713 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
714 foreach ($caseStatuses as $key => $name) {
715 $caseSummary['headers'][$key]['status'] = $name;
716 $caseSummary['headers'][$key]['url'] = $url . $key;
719 // build rows with actual data
721 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
727 $myGroupByClause = ' GROUP BY civicrm_case.id';
732 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active ";
733 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
735 $myGroupByClause .= ", case_status.label, status_id, case_type_id";
737 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
739 SELECT case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
740 case_type_id, case_relationship.contact_id_b
742 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
743 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
744 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
745 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
746 AND option_group_case_status.id = case_status.option_group_id )
747 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
748 AND case_relationship.contact_id_b = {$userID} AND case_relationship.is_active )
749 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
750 {$myCaseWhereClause} {$myGroupByClause}";
752 $res = CRM_Core_DAO
::executeQuery($query);
753 while ($res->fetch()) {
754 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
755 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
758 $rows[$res->case_type
][$res->case_status
] = array(
760 'url' => CRM_Utils_System
::url('civicrm/case/search',
761 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
766 $caseSummary['rows'] = array_merge($caseTypes, $rows);
774 * @param int $contactID
778 * @param int $relationshipID
779 * @param bool $activeOnly
782 * case role / relationships
785 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL, $activeOnly = TRUE) {
787 SELECT rel.id as civicrm_relationship_id,
788 con.sort_name as sort_name,
789 civicrm_email.email as email,
790 civicrm_phone.phone as phone,
791 con.id as civicrm_contact_id,
792 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
793 civicrm_relationship_type.id as relation_type,
794 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
795 FROM civicrm_relationship rel
796 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
797 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))
798 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
799 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
800 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
801 AND con.is_deleted = 0';
804 $query .= ' AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
808 1 => array($contactID, 'Positive'),
809 2 => array($caseID, 'Positive'),
812 if ($relationshipID) {
813 $query .= ' AND rel.id = %3 ';
814 $params[3] = array($relationshipID, 'Integer');
816 $dao = CRM_Core_DAO
::executeQuery($query, $params);
819 while ($dao->fetch()) {
820 $rid = $dao->civicrm_relationship_id
;
821 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
822 $values[$rid]['relation'] = $dao->relation
;
823 $values[$rid]['name'] = $dao->sort_name
;
824 $values[$rid]['email'] = $dao->email
;
825 $values[$rid]['phone'] = $dao->phone
;
826 $values[$rid]['relation_type'] = $dao->relation_type
;
827 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
828 $values[$rid]['client_id'] = $contactID;
829 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
836 * Get Case Activities.
840 * @param array $params
842 * @param int $contactID
845 * @param null $context
847 * @param null $type (deprecated)
850 * Array of case activities
853 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
854 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
855 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
856 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
857 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
859 // CRM-5081 - formatting the dates to omit seconds.
860 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
862 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
864 ca.activity_type_id AS type,
865 ca.activity_type_id AS activity_type_id,
866 tcc.sort_name AS target_contact_name,
867 tcc.id AS target_contact_id,
868 scc.sort_name AS source_contact_name,
869 scc.id AS source_contact_id,
870 acc.sort_name AS assignee_contact_name,
871 acc.id AS assignee_contact_id,
873 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
874 ca.activity_date_time,
875 DATE_ADD(NOW(), INTERVAL 1 YEAR)
876 ), '%Y%m%d%H%i00') AS overdue_date,
877 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
878 ca.status_id AS status,
879 ca.subject AS subject,
880 ca.is_deleted AS deleted,
881 ca.priority_id AS priority,
883 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
886 FROM civicrm_case_activity cca
887 INNER JOIN civicrm_activity ca
888 ON ca.id = cca.activity_id
889 INNER JOIN civicrm_activity_contact cas
890 ON cas.activity_id = ca.id
891 AND cas.record_type_id = {$sourceID}
892 INNER JOIN civicrm_contact scc
893 ON scc.id = cas.contact_id
894 LEFT JOIN civicrm_activity_contact caa
895 ON caa.activity_id = ca.id
896 AND caa.record_type_id = {$assigneeID}
897 LEFT JOIN civicrm_contact acc
898 ON acc.id = caa.contact_id
899 LEFT JOIN civicrm_activity_contact cat
900 ON cat.activity_id = ca.id
901 AND cat.record_type_id = {$targetID}
902 LEFT JOIN civicrm_contact tcc
903 ON tcc.id = cat.contact_id
904 INNER JOIN civicrm_option_group cog
905 ON cog.name = 'activity_type'
906 INNER JOIN civicrm_option_value cov
907 ON cov.option_group_id = cog.id
908 AND cov.value = ca.activity_type_id
909 AND cov.is_active = 1
910 LEFT JOIN civicrm_entity_file ef
911 ON ef.entity_table = 'civicrm_activity'
912 AND ef.entity_id = ca.id
913 LEFT OUTER JOIN civicrm_option_group og
914 ON og.name = 'activity_status'
915 LEFT OUTER JOIN civicrm_option_value ov
916 ON ov.option_group_id=og.id
917 AND ov.name = 'Scheduled'";
920 WHERE cca.case_id= %1
921 AND ca.is_current_revision = 1';
923 if (!empty($params['source_contact_id'])) {
925 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
928 if (!empty($params['status_id'])) {
930 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
933 if (!empty($params['activity_deleted'])) {
935 AND ca.is_deleted = 1";
939 AND ca.is_deleted = 0";
942 if (!empty($params['activity_type_id'])) {
944 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
947 if (!empty($params['activity_date_low'])) {
948 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
950 if (!empty($fromActivityDate)) {
952 AND ca.activity_date_time >= '{$fromActivityDate}'";
955 if (!empty($params['activity_date_high'])) {
956 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
957 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
959 if (!empty($toActivityDate)) {
961 AND ca.activity_date_time <= '{$toActivityDate}'";
965 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
967 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
969 // CRM-5081 - added id to act like creation date
971 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
974 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
975 $orderBy = " ORDER BY $sortBy ";
978 $page = CRM_Utils_Array
::value('page', $params);
979 $rp = CRM_Utils_Array
::value('rp', $params);
987 $start = (($page - 1) * $rp);
988 $limit = " LIMIT $start, $rp";
990 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
991 $queryParams = array(1 => array($caseID, 'Integer'));
993 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
994 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
996 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
998 $compStatusValues = array_keys(
999 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::COMPLETED
) +
1000 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::CANCELLED
)
1004 $userID = CRM_Core_Session
::getLoggedInContactID();
1007 $caseActivities = [];
1009 while ($dao->fetch()) {
1010 $caseActivityId = $dao->id
;
1012 //Do we have permission to access given case activity record.
1013 if (!self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID)) {
1017 $caseActivities[$caseActivityId]['DT_RowId'] = $caseActivityId;
1018 //Add classes to the row, via DataTables syntax
1019 $caseActivities[$caseActivityId]['DT_RowClass'] = "crm-entity status-id-$dao->status";
1021 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1022 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-completed";
1025 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1026 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-overdue";
1029 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-scheduled";
1033 if (!empty($dao->priority
)) {
1034 if ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Urgent')) {
1035 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-urgent ";
1037 elseif ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Low')) {
1038 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-low ";
1042 //Add data to the row for inline editing, via DataTable syntax
1043 $caseActivities[$caseActivityId]['DT_RowAttr'] = array();
1044 $caseActivities[$caseActivityId]['DT_RowAttr']['data-entity'] = 'activity';
1045 $caseActivities[$caseActivityId]['DT_RowAttr']['data-id'] = $caseActivityId;
1047 //Activity Date and Time
1048 $caseActivities[$caseActivityId]['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1051 $caseActivities[$caseActivityId]['subject'] = $dao->subject
;
1054 $caseActivities[$caseActivityId]['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1055 . $activityTypes[$dao->type
]['label'];
1057 // Activity Target (With Contact) (There can be more than one)
1058 $targetContact = self
::formatContactLink($dao->target_contact_id
, $dao->target_contact_name
);
1059 if (empty($caseActivities[$caseActivityId]['target_contact_name'])) {
1060 $caseActivities[$caseActivityId]['target_contact_name'] = $targetContact;
1063 if (strpos($caseActivities[$caseActivityId]['target_contact_name'], $targetContact) === FALSE) {
1064 $caseActivities[$caseActivityId]['target_contact_name'] .= '; ' . $targetContact;
1068 // Activity Source Contact (Reporter) (There can only be one)
1069 $sourceContact = self
::formatContactLink($dao->source_contact_id
, $dao->source_contact_name
);
1070 $caseActivities[$caseActivityId]['source_contact_name'] = $sourceContact;
1072 // Activity Assignee (There can be more than one)
1073 $assigneeContact = self
::formatContactLink($dao->assignee_contact_id
, $dao->assignee_contact_name
);
1074 if (empty($caseActivities[$caseActivityId]['assignee_contact_name'])) {
1075 $caseActivities[$caseActivityId]['assignee_contact_name'] = $assigneeContact;
1078 if (strpos($caseActivities[$caseActivityId]['assignee_contact_name'], $assigneeContact) === FALSE) {
1079 $caseActivities[$caseActivityId]['assignee_contact_name'] .= '; ' . $assigneeContact;
1083 // Activity Status Label for Case activities list
1084 $caseActivities[$caseActivityId]['status_id'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'activity_status_id', $dao->status
);
1086 $caseActivities[$caseActivityId]
1087 = self
::addCaseActivityLinks($caseID, $contactID, $userID, $context, $dao, $caseActivities[$caseActivityId]);
1090 $caseActivitiesDT = array();
1091 $caseActivitiesDT['data'] = array_values($caseActivities);
1092 $caseActivitiesDT['recordsTotal'] = $caseCount;
1093 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1095 return $caseActivitiesDT;
1099 * FIXME: This is a transitional function to facilitate a refactor of this to use CRM_Core_Action and actionLinks
1100 * Add the set of "actionLinks" to the case activity
1102 * @param int $caseID
1103 * @param int $contactID
1104 * @param int $userID
1105 * @param string $context
1106 * @param \CRM_Core_DAO $dao
1107 * @param array $caseActivity
1109 * @return array caseActivity
1111 public static function addCaseActivityLinks($caseID, $contactID, $userID, $context, $dao, $caseActivity) {
1112 // 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.
1113 $caseActivityId = $dao->id
;
1114 $allowView = self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID);
1115 $allowEdit = self
::checkPermission($caseActivityId, 'edit', $dao->activity_type_id
, $userID);
1116 $allowDelete = self
::checkPermission($caseActivityId, 'delete', $dao->activity_type_id
, $userID);
1117 $emailActivityTypeIDs = [
1118 'Email' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email'),
1119 'Inbound Email' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email'),
1121 $url = CRM_Utils_System
::url("civicrm/case/activity",
1122 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1125 if ($context == 'fulltext') {
1126 $contextUrl = "&context={$context}";
1128 $editUrl = "{$url}&action=update{$contextUrl}";
1129 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1130 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1131 $viewTitle = ts('View activity');
1132 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1135 $css = 'class="action-item crm-hover-button"';
1137 $viewUrl = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1138 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1140 $additionalUrl = "&id={$caseActivityId}";
1141 if (!$dao->deleted
) {
1142 //hide edit link of activity type email.CRM-4530.
1143 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1144 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1146 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1150 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1153 elseif (!$caseDeleted) {
1154 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1155 $caseActivity['status_id'] = $caseActivity['status_id'] . '<br /> (deleted)';
1158 //check for operations.
1159 if (self
::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id
)) {
1160 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1162 if (self
::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id
)) {
1163 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1165 // if there are file attachments we will return how many and, if only one, add a link to it
1166 if (!empty($dao->attachment_ids
)) {
1167 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1168 $caseActivity['no_attachments'] = count($attachmentIDs);
1169 $url .= implode(' ', CRM_Core_BAO_File
::paperIconAttachment('civicrm_activity', $caseActivityId));
1171 $caseActivity['links'] = $url;
1172 return $caseActivity;
1176 * Helper function to generate a formatted contact link/name for display in the Case activities tab
1179 * @param $contactName
1183 private static function formatContactLink($contactId, $contactName) {
1184 if (empty($contactId)) {
1188 $hasViewContact = CRM_Contact_BAO_Contact_Permission
::allow($contactId);
1190 if ($hasViewContact) {
1191 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid={$contactId}");
1192 return "<a href=\"{$contactViewUrl}\">" . $contactName . "</a>";
1195 return $contactName;
1200 * Get Case Related Contacts.
1202 * @param int $caseID
1204 * @param bool $includeDetails
1205 * If true include details of contacts.
1208 * array of return properties
1211 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1212 $caseRoles = array();
1213 if ($includeDetails) {
1214 $caseInfo = civicrm_api3('Case', 'getsingle', array(
1216 // 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
1217 'return' => array('case_type_id', 'case_type_id.name', 'case_type_id.definition'),
1219 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1220 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1225 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, ce.email, cp.phone
1226 FROM civicrm_relationship cr
1227 LEFT JOIN civicrm_relationship_type crt
1228 ON crt.id = cr.relationship_type_id
1229 LEFT JOIN civicrm_contact cc
1230 ON cc.id = cr.contact_id_b
1231 LEFT JOIN civicrm_email ce
1232 ON ce.contact_id = cc.id
1233 AND ce.is_primary= 1
1234 LEFT JOIN civicrm_phone cp
1235 ON cp.contact_id = cc.id
1236 AND cp.is_primary= 1
1237 WHERE cr.case_id = %1 AND cr.is_active AND cc.is_deleted <> 1';
1239 $params = array(1 => array($caseID, 'Integer'));
1240 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1242 while ($dao->fetch()) {
1243 if (!$includeDetails) {
1244 $values[$dao->id
] = 1;
1248 'contact_id' => $dao->id
,
1249 'display_name' => $dao->name
,
1250 'sort_name' => $dao->sort_name
,
1251 'relationship_type_id' => $dao->relationship_type_id
,
1252 'role' => $dao->role
,
1253 'email' => $dao->email
,
1254 'phone' => $dao->phone
,
1256 // Add more info about the role (creator, manager)
1257 $role = CRM_Utils_Array
::value($dao->name_b_a
, $caseRoles);
1259 unset($role['name']);
1262 $values[] = $details;
1270 * Send e-mail copy of activity
1272 * @param int $clientId
1273 * @param int $activityId
1275 * @param array $contacts
1276 * Array of related contact.
1278 * @param null $attachments
1279 * @param int $caseId
1281 * @return bool |array
1283 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1288 $tplParams = $activityInfo = array();
1289 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1290 // If it's a case activity
1292 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1293 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1294 $anyActivity = TRUE;
1297 $anyActivity = FALSE;
1299 $tplParams['isCaseActivity'] = 1;
1300 $tplParams['client_id'] = $clientId;
1303 $anyActivity = TRUE;
1306 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1307 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1309 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1311 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1313 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1315 $tplParams['activityTypeName'] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_DAO_Activity', 'activity_type_id', $activityTypeId);
1316 $tplParams['activity'] = $activityInfo;
1317 foreach ($tplParams['activity']['fields'] as $k => $val) {
1318 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1319 $activitySubject = $val['value'];
1323 $session = CRM_Core_Session
::singleton();
1324 // CRM-8926 If user is not logged in, use the activity creator as userID
1325 if (!($userID = $session->get('userID'))) {
1326 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1329 //also create activities simultaneously of this copy.
1330 $activityParams = array();
1332 $activityParams['source_record_id'] = $activityId;
1333 $activityParams['source_contact_id'] = $userID;
1334 $activityParams['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', 'Email');
1335 $activityParams['activity_date_time'] = date('YmdHis');
1336 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
1337 $activityParams['medium_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'encounter_medium', 'email');
1338 $activityParams['case_id'] = $caseId;
1339 $activityParams['is_auto'] = 0;
1340 $activityParams['target_id'] = $clientId;
1342 $tplParams['activitySubject'] = $activitySubject;
1344 // if it’s a case activity, add hashed id to the template (CRM-5916)
1346 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1350 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1351 $receiptFrom = self
::getReceiptFrom($activityId);
1353 $recordedActivityParams = array();
1355 foreach ($contacts as $mail => $info) {
1356 $tplParams['contact'] = $info;
1357 self
::buildPermissionLinks($tplParams, $activityParams);
1359 $displayName = CRM_Utils_Array
::value('display_name', $info);
1361 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1363 'groupName' => 'msg_tpl_workflow_case',
1364 'valueName' => 'case_activity',
1365 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1366 'tplParams' => $tplParams,
1367 'from' => $receiptFrom,
1368 'toName' => $displayName,
1370 'attachments' => $attachments,
1374 $activityParams['subject'] = ts('%1 - copy sent to %2', [1 => $activitySubject, 2 => $displayName]);
1375 $activityParams['details'] = $message;
1377 if (!empty($result[$info['contact_id']])) {
1379 * Really only need to record one activity with all the targets combined.
1380 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1381 * but it's always the same content at the moment.
1383 if (empty($recordedActivityParams)) {
1384 $recordedActivityParams = $activityParams;
1387 $recordedActivityParams['subject'] .= "; $displayName";
1389 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1392 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1396 if (!empty($recordedActivityParams)) {
1397 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1399 //create case_activity record if its case activity.
1401 $caseParams = array(
1402 'activity_id' => $activity->id
,
1403 'case_id' => $caseId,
1405 self
::processCaseActivity($caseParams);
1413 * Retrieve count of activities having a particular type, and
1414 * associated with a particular case.
1416 * @param int $caseId
1418 * @param int $activityTypeId
1419 * ID of the activity type.
1423 public static function getCaseActivityCount($caseId, $activityTypeId) {
1424 $queryParam = array(
1425 1 => array($caseId, 'Integer'),
1426 2 => array($activityTypeId, 'Integer'),
1428 $query = "SELECT count(ca.id) as countact
1429 FROM civicrm_activity ca
1430 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1431 WHERE ca.activity_type_id = %2
1432 AND cca.case_id = %1
1433 AND ca.is_deleted = 0";
1435 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1436 if ($dao->fetch()) {
1437 return $dao->countact
;
1444 * Create an activity for a case via email.
1449 * @return array|void
1450 * $activity object of newly creted activity via email
1452 public static function recordActivityViaEmail($file) {
1453 if (!file_exists($file) ||
1456 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1461 $result = CRM_Utils_Mail_Incoming
::parse($file);
1462 if ($result['is_error']) {
1466 foreach ($result['to'] as $to) {
1469 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1470 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1472 if ($replacement !== $to['email']) {
1473 $caseId = $replacement;
1474 //if caseId is invalid, return as error file
1475 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1476 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1485 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1486 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1487 $contactDetails = self
::getRelatedContacts($caseId, FALSE);
1489 if (!empty($contactDetails[$result['from']['id']])) {
1491 $params['subject'] = $result['subject'];
1492 $params['activity_date_time'] = $result['date'];
1493 $params['details'] = $result['body'];
1494 $params['source_contact_id'] = $result['from']['id'];
1495 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
1497 $details = CRM_Case_PseudoConstant
::caseActivityType();
1499 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1500 $result['body'], $matches
1503 if (!empty($matches) && isset($matches[1])) {
1504 $activityType = trim($matches[1]);
1505 if (isset($details[$activityType])) {
1506 $params['activity_type_id'] = $details[$activityType]['id'];
1509 if (!isset($params['activity_type_id'])) {
1510 $params['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email');
1514 $activity = CRM_Activity_BAO_Activity
::create($params);
1516 $caseParams = array(
1517 'activity_id' => $activity->id
,
1518 'case_id' => $caseId,
1520 self
::processCaseActivity($caseParams);
1523 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1524 array(1 => $result['from']['email'])
1531 * Retrieve the scheduled activity type and date.
1533 * @param array $cases
1534 * Array of contact and case id.
1536 * @param string $type
1539 * Array of scheduled activity type and date
1543 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1544 $session = CRM_Core_Session
::singleton();
1545 $userID = $session->get('userID');
1547 $caseID = implode(',', $cases['case_id']);
1548 $contactID = implode(',', $cases['contact_id']);
1550 $condition = " civicrm_case_contact.contact_id IN( {$contactID} )
1551 AND civicrm_case.id IN( {$caseID})
1552 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1554 $query = self
::getCaseActivityQuery($type, $userID, $condition);
1555 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id');
1557 $res = CRM_Core_DAO
::executeQuery($query);
1559 $activityInfo = array();
1560 while ($res->fetch()) {
1561 if ($type == 'upcoming') {
1562 $activityInfo[$res->case_id
]['date'] = $res->activity_date_time
;
1563 $activityInfo[$res->case_id
]['type'] = CRM_Utils_Array
::value($res->activity_type_id
, $activityTypes);
1566 $activityInfo[$res->case_id
]['date'] = $res->activity_date_time
;
1567 $activityInfo[$res->case_id
]['type'] = CRM_Utils_Array
::value($res->activity_type_id
, $activityTypes);
1571 return $activityInfo;
1575 * Combine all the exportable fields from the lower levels object.
1578 * array of exportable Fields
1580 public static function &exportableFields() {
1581 if (!self
::$_exportableFields) {
1582 if (!self
::$_exportableFields) {
1583 self
::$_exportableFields = array();
1586 $fields = CRM_Case_DAO_Case
::export();
1587 $fields['case_role'] = array('title' => ts('Role in Case'));
1588 $fields['case_type'] = array(
1589 'title' => ts('Case Type'),
1590 'name' => 'case_type',
1592 $fields['case_status'] = array(
1593 'title' => ts('Case Status'),
1594 'name' => 'case_status',
1597 // add custom data for cases
1598 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1600 self
::$_exportableFields = $fields;
1602 return self
::$_exportableFields;
1606 * Restore the record that are associated with this case.
1608 * @param int $caseId
1609 * Id of the case to restore.
1613 public static function restoreCase($caseId) {
1614 //restore activities
1615 $activities = self
::getCaseActivityDates($caseId);
1617 foreach ($activities as $value) {
1618 CRM_Activity_BAO_Activity
::restoreActivity($value);
1622 $case = new CRM_Case_DAO_Case();
1623 $case->id
= $caseId;
1624 $case->is_deleted
= 0;
1627 //CRM-7364, enable relationships
1628 self
::enableDisableCaseRelationships($caseId, TRUE);
1635 * @param null $showLinks
1636 * @param bool $returnOnlyCount
1637 * @param int $offset
1638 * @param int $rowCount
1642 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1643 $globalContacts = array();
1645 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1646 $settings = $settingsProcessor->run();
1647 if (!empty($settings)) {
1648 $groupInfo['name'] = $settings['groupname'];
1649 if ($groupInfo['name']) {
1650 $searchParams = array('name' => $groupInfo['name']);
1652 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1654 $groupInfo['id'] = $results['id'];
1655 $groupInfo['title'] = $results['title'];
1656 $params = array(array('group', '=', $groupInfo['id'], 0, 0));
1657 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1658 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1660 if ($returnOnlyCount) {
1661 return $globalContacts;
1665 foreach ($globalContacts as $idx => $contact) {
1666 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1672 return $globalContacts;
1676 * Convenience function to get both case contacts and global in one array.
1677 * @param int $caseId
1681 public static function getRelatedAndGlobalContacts($caseId) {
1682 $relatedContacts = self
::getRelatedContacts($caseId);
1684 $groupInfo = array();
1685 $globalContacts = self
::getGlobalContacts($groupInfo);
1687 //unset values which are not required.
1688 foreach ($globalContacts as $k => & $v) {
1689 unset($v['email_id']);
1690 unset($v['group_contact_id']);
1691 unset($v['status']);
1693 $v['role'] = $groupInfo['title'];
1695 //include multiple listings for the same contact/different roles.
1696 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1697 return $relatedGlobalContacts;
1701 * Get Case ActivitiesDueDates with given criteria.
1703 * @param int $caseID
1705 * @param array $criteriaParams
1707 * @param bool $latestDate
1708 * If set newest or oldest date is selected.
1711 * case activities due dates
1714 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1716 $selectDate = " ca.activity_date_time";
1717 $where = $groupBy = ' ';
1724 if (!empty($criteriaParams['activity_type_id'])) {
1725 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1726 $where .= " AND ca.is_current_revision = 1";
1727 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1730 if (!empty($criteriaParams['newest'])) {
1731 $selectDate = " max(ca.activity_date_time) ";
1734 $selectDate = " min(ca.activity_date_time) ";
1738 $query = "SELECT ca.id, {$selectDate} as activity_date
1739 FROM civicrm_activity ca
1740 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1741 WHERE cc.id = %1 {$where} {$groupBy}";
1743 $params = array(1 => array($caseID, 'Integer'));
1744 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1746 while ($dao->fetch()) {
1747 $values[$dao->id
]['id'] = $dao->id
;
1748 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1754 * Create activities when Case or Other roles assigned/modified/deleted.
1756 * @param int $caseId
1757 * @param int $relationshipId
1759 * @param int $relContactId
1760 * Case role assignee contactId.
1761 * @param int $contactId
1763 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1764 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1768 $queryParam = array();
1769 if (is_array($relationshipId)) {
1770 $relationshipId = implode(',', $relationshipId);
1771 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1774 $relationshipClause = " civicrm_relationship.id = %1";
1775 $queryParam[1] = array($relationshipId, 'Positive');
1779 SELECT cc.display_name as clientName,
1780 cca.display_name as assigneeContactName,
1781 civicrm_relationship.case_id as caseId,
1782 civicrm_relationship_type.label_a_b as relation_a_b,
1783 civicrm_relationship_type.label_b_a as relation_b_a,
1784 civicrm_relationship.contact_id_b as rel_contact_id,
1785 civicrm_relationship.contact_id_a as assign_contact_id
1786 FROM civicrm_relationship_type, civicrm_relationship
1787 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1788 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1789 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1791 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1793 while ($dao->fetch()) {
1794 // The assignee is not the client.
1795 if ($dao->rel_contact_id
!= $contactId) {
1796 $caseRelationship = $dao->relation_a_b
;
1797 $assigneContactName = $dao->clientName
;
1798 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1801 $caseRelationship = $dao->relation_b_a
;
1802 $assigneContactName = $dao->assigneeContactName
;
1803 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1807 $session = CRM_Core_Session
::singleton();
1808 $activityParams = array(
1809 'source_contact_id' => $session->get('userID'),
1810 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1811 'activity_date_time' => date('YmdHis'),
1812 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1815 //if $relContactId is passed, role is added or modified.
1816 if (!empty($relContactId)) {
1817 $activityParams['assignee_contact_id'] = $assigneContactIds;
1818 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Assign Case Role');
1821 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Remove Case Role');
1824 $activityParams['activity_type_id'] = $activityTypeID;
1826 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1828 //create case_activity record.
1829 $caseParams = array(
1830 'activity_id' => $activity->id
,
1831 'case_id' => $caseId,
1834 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1839 * contact which is assigned a case role of case manager.
1841 * @param int $caseType
1843 * @param int $caseId
1847 * html hyperlink of manager contact view page
1850 public static function getCaseManagerContact($caseType, $caseId) {
1851 if (!$caseType ||
!$caseId) {
1855 $caseManagerName = '---';
1856 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1858 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1860 if (!empty($managerRoleId)) {
1861 $managerRoleQuery = "
1862 SELECT civicrm_contact.id as casemanager_id,
1863 civicrm_contact.sort_name as casemanager
1864 FROM civicrm_contact
1865 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
1866 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1867 WHERE civicrm_case.id = %2 AND is_active = 1";
1869 $managerRoleParams = array(
1870 1 => array($managerRoleId, 'Integer'),
1871 2 => array($caseId, 'Integer'),
1874 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1875 if ($dao->fetch()) {
1876 $caseManagerName = sprintf('<a href="%s">%s</a>',
1877 CRM_Utils_System
::url('civicrm/contact/view', array('cid' => $dao->casemanager_id
)),
1883 return $caseManagerName;
1887 * @param int $contactId
1888 * @param bool $excludeDeleted
1892 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1893 $params = array('check_permissions' => TRUE);
1894 if ($excludeDeleted) {
1895 $params['is_deleted'] = 0;
1898 $params['contact_id'] = $contactId;
1901 return civicrm_api3('Case', 'getcount', $params);
1903 catch (CiviCRM_API3_Exception
$e) {
1904 // Lack of permissions will throw an exception
1910 * Retrieve related case ids for given case.
1912 * @param int $caseId
1913 * @param bool $excludeDeleted
1914 * Do not include deleted cases.
1918 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1919 //FIXME : do check for permissions.
1925 $linkActType = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Link Cases');
1926 if (!$linkActType) {
1930 $whereClause = "mainCase.id = %2";
1931 if ($excludeDeleted) {
1932 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1936 SELECT relCaseAct.case_id
1937 FROM civicrm_case mainCase
1938 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1939 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1940 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1941 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1942 WHERE $whereClause";
1944 $dao = CRM_Core_DAO
::executeQuery($query, array(
1945 1 => array($linkActType, 'Integer'),
1946 2 => array($caseId, 'Integer'),
1948 $relatedCaseIds = array();
1949 while ($dao->fetch()) {
1950 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1953 return array_values($relatedCaseIds);
1957 * Retrieve related case details for given case.
1959 * @param int $caseId
1960 * @param bool $excludeDeleted
1961 * Do not include deleted cases.
1965 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
1966 $relatedCaseIds = self
::getRelatedCaseIds($caseId, $excludeDeleted);
1967 $relatedCases = array();
1969 if (!$relatedCaseIds) {
1973 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1974 if ($excludeDeleted) {
1975 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1978 //filter for permissioned cases.
1979 $filterCases = array();
1980 $doFilterCases = FALSE;
1981 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1982 $doFilterCases = TRUE;
1983 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE);
1986 //2. fetch the details of related cases.
1988 SELECT relCase.id as id,
1989 civicrm_case_type.title as case_type,
1990 client.display_name as client_name,
1991 client.id as client_id,
1993 FROM civicrm_case relCase
1994 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
1995 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
1996 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
1997 WHERE {$whereClause}";
1999 $dao = CRM_Core_DAO
::executeQuery($query);
2000 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2001 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2002 $statuses = CRM_Case_BAO_Case
::buildOptions('status_id');
2004 while ($dao->fetch()) {
2006 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2007 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2008 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2009 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2011 $clientView = $dao->client_name
;
2012 if ($hasViewContact) {
2013 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2016 $relatedCases[$dao->id
] = array(
2017 'case_id' => $dao->id
,
2018 'case_type' => $dao->case_type
,
2019 'client_name' => $clientView,
2020 'case_status' => $statuses[$dao->status_id
],
2021 'links' => $caseView,
2025 return $relatedCases;
2029 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2031 * @see CRM_Dedupe_Merger::cpTables()
2033 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2035 * @param int $mainContactId
2036 * @param int $otherContactId
2038 public static function mergeContacts($mainContactId, $otherContactId) {
2039 self
::mergeCases($mainContactId, NULL, $otherContactId);
2043 * Function perform two task.
2044 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2045 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2047 * @param int $mainContactId
2048 * Contact id of main contact record.
2049 * @param int $mainCaseId
2050 * Case id of main case record.
2051 * @param int $otherContactId
2052 * Contact id of record which is going to merge.
2053 * @param int $otherCaseId
2054 * Case id of record which is going to merge.
2056 * @param bool $changeClient
2060 public static function mergeCases(
2061 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2062 $otherCaseId = NULL, $changeClient = FALSE) {
2063 $moveToTrash = TRUE;
2065 $duplicateContacts = FALSE;
2066 if ($mainContactId && $otherContactId &&
2067 $mainContactId != $otherContactId
2069 $duplicateContacts = TRUE;
2072 $duplicateCases = FALSE;
2073 if ($mainCaseId && $otherCaseId &&
2074 $mainCaseId != $otherCaseId
2076 $duplicateCases = TRUE;
2079 $mainCaseIds = array();
2080 if (!$duplicateContacts && !$duplicateCases) {
2081 return $mainCaseIds;
2084 $activityTypes = CRM_Activity_BAO_Activity
::buildOptions('activity_type_id', 'validate');
2085 $completedActivityStatus = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
2086 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2087 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2088 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2089 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2091 $processCaseIds = array($otherCaseId);
2092 if ($duplicateContacts && !$duplicateCases) {
2093 if ($changeClient) {
2094 $processCaseIds = array($mainCaseId);
2097 //get all case ids for other contact.
2098 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2100 if (!is_array($processCaseIds)) {
2105 $session = CRM_Core_Session
::singleton();
2106 $currentUserId = $session->get('userID');
2108 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2110 // copy all cases and connect to main contact id.
2111 foreach ($processCaseIds as $otherCaseId) {
2112 if ($duplicateContacts) {
2113 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2114 $mainCaseId = $mainCase->id
;
2119 // CRM-11662 Copy Case custom data
2120 $extends = array('case');
2121 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2123 foreach ($groupTree as $groupID => $group) {
2124 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2125 foreach ($group['fields'] as $fieldID => $field) {
2126 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2130 foreach ($table as $tableName => $tableColumns) {
2131 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2132 $tableColumns[0] = $mainCaseId;
2133 $select = 'SELECT ' . implode(', ', $tableColumns);
2134 $from = ' FROM ' . $tableName;
2135 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2136 $query = $insert . $select . $from . $where;
2137 $dao = CRM_Core_DAO
::executeQuery($query);
2141 $mainCaseIds[] = $mainCaseId;
2142 //insert record for case contact.
2143 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2144 $otherCaseContact->case_id
= $otherCaseId;
2145 $otherCaseContact->find();
2146 while ($otherCaseContact->fetch()) {
2147 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2148 $mainCaseContact->case_id
= $mainCaseId;
2149 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2150 if ($mainCaseContact->contact_id
== $otherContactId) {
2151 $mainCaseContact->contact_id
= $mainContactId;
2153 //avoid duplicate object.
2154 if (!$mainCaseContact->find(TRUE)) {
2155 $mainCaseContact->save();
2159 elseif (!$otherContactId) {
2160 $otherContactId = $mainContactId;
2163 if (!$mainCaseId ||
!$otherCaseId ||
2164 !$mainContactId ||
!$otherContactId
2169 // get all activities for other case.
2170 $otherCaseActivities = array();
2171 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2173 //for duplicate cases do not process singleton activities.
2174 $otherActivityIds = $singletonActivityIds = array();
2175 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2176 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2177 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2180 $otherActivityIds[] = $otherActId;
2182 if ($duplicateCases) {
2183 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2186 FROM civicrm_activity
2187 WHERE activity_type_id = $openCaseType
2188 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2189 $dao = CRM_Core_DAO
::executeQuery($sql);
2190 while ($dao->fetch()) {
2191 $singletonActivityIds[] = $dao->id
;
2196 // migrate all activities and connect to main contact.
2197 $copiedActivityIds = $activityMappingIds = array();
2198 sort($otherActivityIds);
2199 foreach ($otherActivityIds as $otherActivityId) {
2201 //for duplicate cases -
2202 //do not migrate singleton activities.
2203 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2207 //migrate activity record.
2208 $otherActivity = new CRM_Activity_DAO_Activity();
2209 $otherActivity->id
= $otherActivityId;
2210 if (!$otherActivity->find(TRUE)) {
2214 $mainActVals = array();
2215 $mainActivity = new CRM_Activity_DAO_Activity();
2216 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2217 $mainActivity->copyValues($mainActVals);
2218 $mainActivity->id
= NULL;
2219 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2220 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2224 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2228 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2231 $mainActivity->save();
2232 $mainActivityId = $mainActivity->id
;
2233 if (!$mainActivityId) {
2237 $activityMappingIds[$otherActivityId] = $mainActivityId;
2238 // insert log of all activities
2239 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2241 $copiedActivityIds[] = $otherActivityId;
2243 //create case activity record.
2244 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2245 $mainCaseActivity->case_id
= $mainCaseId;
2246 $mainCaseActivity->activity_id
= $mainActivityId;
2247 $mainCaseActivity->save();
2249 //migrate source activity.
2250 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2251 $otherSourceActivity->activity_id
= $otherActivityId;
2252 $otherSourceActivity->record_type_id
= $sourceID;
2253 $otherSourceActivity->find();
2254 while ($otherSourceActivity->fetch()) {
2255 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2256 $mainActivitySource->record_type_id
= $sourceID;
2257 $mainActivitySource->activity_id
= $mainActivityId;
2258 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2259 if ($mainActivitySource->contact_id
== $otherContactId) {
2260 $mainActivitySource->contact_id
= $mainContactId;
2262 //avoid duplicate object.
2263 if (!$mainActivitySource->find(TRUE)) {
2264 $mainActivitySource->save();
2268 //migrate target activities.
2269 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2270 $otherTargetActivity->activity_id
= $otherActivityId;
2271 $otherTargetActivity->record_type_id
= $targetID;
2272 $otherTargetActivity->find();
2273 while ($otherTargetActivity->fetch()) {
2274 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2275 $mainActivityTarget->record_type_id
= $targetID;
2276 $mainActivityTarget->activity_id
= $mainActivityId;
2277 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2278 if ($mainActivityTarget->contact_id
== $otherContactId) {
2279 $mainActivityTarget->contact_id
= $mainContactId;
2281 //avoid duplicate object.
2282 if (!$mainActivityTarget->find(TRUE)) {
2283 $mainActivityTarget->save();
2287 //migrate assignee activities.
2288 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2289 $otherAssigneeActivity->activity_id
= $otherActivityId;
2290 $otherAssigneeActivity->record_type_id
= $assigneeID;
2291 $otherAssigneeActivity->find();
2292 while ($otherAssigneeActivity->fetch()) {
2293 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2294 $mainAssigneeActivity->activity_id
= $mainActivityId;
2295 $mainAssigneeActivity->record_type_id
= $assigneeID;
2296 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2297 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2298 $mainAssigneeActivity->contact_id
= $mainContactId;
2300 //avoid duplicate object.
2301 if (!$mainAssigneeActivity->find(TRUE)) {
2302 $mainAssigneeActivity->save();
2306 // copy custom fields and attachments
2308 'activityID' => $otherActivityId,
2309 'mainActivityId' => $mainActivityId,
2311 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2314 //copy case relationship.
2315 if ($duplicateContacts) {
2316 //migrate relationship records.
2317 $otherRelationship = new CRM_Contact_DAO_Relationship();
2318 $otherRelationship->case_id
= $otherCaseId;
2319 $otherRelationship->find();
2320 $otherRelationshipIds = array();
2321 while ($otherRelationship->fetch()) {
2322 $otherRelVals = array();
2323 $updateOtherRel = FALSE;
2324 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2326 $mainRelationship = new CRM_Contact_DAO_Relationship();
2327 $mainRelationship->copyValues($otherRelVals);
2328 $mainRelationship->id
= NULL;
2329 $mainRelationship->case_id
= $mainCaseId;
2330 if ($mainRelationship->contact_id_a
== $otherContactId) {
2331 $updateOtherRel = TRUE;
2332 $mainRelationship->contact_id_a
= $mainContactId;
2335 //case creator change only when we merge user contact.
2336 if ($mainRelationship->contact_id_b
== $otherContactId) {
2337 //do not change creator for change client.
2338 if (!$changeClient) {
2339 $updateOtherRel = TRUE;
2340 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2343 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2344 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2346 //avoid duplicate object.
2347 if (!$mainRelationship->find(TRUE)) {
2348 $mainRelationship->save();
2351 //get the other relationship ids to update end date.
2352 if ($updateOtherRel) {
2353 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2357 //update other relationships end dates
2358 if (!empty($otherRelationshipIds)) {
2359 $sql = 'UPDATE civicrm_relationship
2360 SET end_date = CURDATE()
2361 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2362 CRM_Core_DAO
::executeQuery($sql);
2366 //move other case to trash.
2367 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2372 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2373 if ($changeClient) {
2374 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2375 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2377 $mergeActType = array_search('Reassigned Case', $activityTypes);
2378 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2381 2 => $otherContactDisplayName,
2382 3 => $mainContactDisplayName,
2387 elseif ($duplicateContacts) {
2388 $mergeActType = array_search('Merge Case', $activityTypes);
2389 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2392 2 => $otherContactId,
2393 3 => $mainContactId,
2399 $mergeActType = array_search('Merge Case', $activityTypes);
2400 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2401 if (!empty($copiedActivityIds)) {
2403 SELECT id, subject, activity_date_time, activity_type_id
2404 FROM civicrm_activity
2405 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2406 $dao = CRM_Core_DAO
::executeQuery($sql);
2407 while ($dao->fetch()) {
2408 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2409 if ($dao->subject
) {
2410 $mergeActSubjectDetails .= " :: {$dao->subject}";
2412 $mergeActSubjectDetails .= "<br />";
2417 // Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2418 $activityParams = array(
2419 'subject' => $mergeActSubject,
2420 'details' => $mergeActSubjectDetails,
2421 'status_id' => $completedActivityStatus,
2422 'activity_type_id' => $mergeActType,
2423 'source_contact_id' => $currentUserId,
2424 'activity_date_time' => date('YmdHis'),
2427 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2428 $mergeActivityId = $mergeActivity->id
;
2429 if (!$mergeActivityId) {
2433 //connect merge activity to case.
2434 $mergeCaseAct = array(
2435 'case_id' => $mainCaseId,
2436 'activity_id' => $mergeActivityId,
2439 self
::processCaseActivity($mergeCaseAct);
2442 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2444 return $mainCaseIds;
2448 * Validate contact permission for
2449 * edit/view on activity record and build links.
2451 * @param array $tplParams
2452 * Params to be sent to template for sending email.
2453 * @param array $activityParams
2454 * Info of the activity.
2456 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2457 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2458 'activity_type_id', 'id'
2461 if (!empty($tplParams['isCaseActivity'])) {
2462 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2463 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2466 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2467 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2470 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2471 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2475 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2476 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2479 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2480 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2486 * Validate contact permission for
2487 * given operation on activity record.
2489 * @param int $activityId
2490 * Activity record id.
2491 * @param string $operation
2493 * @param int $actTypeId
2495 * @param int $contactId
2496 * Contact id/if not pass consider logged in.
2497 * @param bool $checkComponent
2498 * Do we need to check component enabled.
2502 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2504 if (!$actTypeId && $activityId) {
2505 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2508 if (!$activityId ||
!$operation ||
!$actTypeId) {
2512 //do check for civicase component enabled.
2513 if ($checkComponent && !self
::enabled()) {
2517 //do check for cases.
2518 $caseActOperations = array(
2525 if (in_array($operation, $caseActOperations)) {
2527 if (!isset($caseCount)) {
2529 $caseCount = civicrm_api3('Case', 'getcount', array(
2530 'check_permissions' => TRUE,
2531 'status_id' => array('!=' => 'Closed'),
2533 'end_date' => array('IS NULL' => 1),
2536 catch (CiviCRM_API3_Exception
$e) {
2537 // Lack of permissions will throw an exception
2541 if ($operation == 'File On Case') {
2542 $allow = !empty($caseCount);
2545 $allow = ($caseCount > 1);
2549 $actionOperations = array('view', 'edit', 'delete');
2550 if (in_array($operation, $actionOperations)) {
2552 //do cache when user has non/supper permission.
2553 static $allowOperations;
2555 if (!is_array($allowOperations) ||
2556 !array_key_exists($operation, $allowOperations)
2560 $session = CRM_Core_Session
::singleton();
2561 $contactId = $session->get('userID');
2564 //check for permissions.
2565 $permissions = array(
2567 'access my cases and activities',
2568 'access all cases and activities',
2571 'access my cases and activities',
2572 'access all cases and activities',
2574 'delete' => array('delete activities'),
2577 //check for core permission.
2578 $hasPermissions = array();
2579 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2580 if (is_array($checkPermissions)) {
2581 foreach ($checkPermissions as $per) {
2582 if (CRM_Core_Permission
::check($per)) {
2583 $hasPermissions[$operation][] = $per;
2589 if (!empty($hasPermissions)) {
2590 //need to check activity object specific.
2591 if (in_array($operation, array(
2596 //do we have supper permission.
2597 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2598 $allowOperations[$operation] = $allow = TRUE;
2601 //user has only access to my cases and activity.
2602 //here object specific permmions come in picture.
2604 //edit - contact must be source or assignee
2605 //view - contact must be source/assignee/target
2606 $isTarget = $isAssignee = $isSource = FALSE;
2607 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2608 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2609 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2610 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2612 $target = new CRM_Activity_DAO_ActivityContact();
2613 $target->record_type_id
= $targetID;
2614 $target->activity_id
= $activityId;
2615 $target->contact_id
= $contactId;
2616 if ($target->find(TRUE)) {
2620 $assignee = new CRM_Activity_DAO_ActivityContact();
2621 $assignee->activity_id
= $activityId;
2622 $assignee->record_type_id
= $assigneeID;
2623 $assignee->contact_id
= $contactId;
2624 if ($assignee->find(TRUE)) {
2628 $source = new CRM_Activity_DAO_ActivityContact();
2629 $source->activity_id
= $activityId;
2630 $source->record_type_id
= $sourceID;
2631 $source->contact_id
= $contactId;
2632 if ($source->find(TRUE)) {
2636 if ($operation == 'edit') {
2637 if ($isAssignee ||
$isSource) {
2641 if ($operation == 'view') {
2642 if ($isTarget ||
$isAssignee ||
$isSource) {
2648 elseif (is_array($hasPermissions[$operation])) {
2649 $allowOperations[$operation] = $allow = TRUE;
2653 //contact do not have permission.
2654 $allowOperations[$operation] = FALSE;
2659 //here contact might have supper/non permission.
2660 $allow = $allowOperations[$operation];
2664 //do further only when operation is granted.
2666 $actTypeName = CRM_Core_PseudoConstant
::getName('CRM_Activity_BAO_Activity', 'activity_type_id', $actTypeId);
2668 //do not allow multiple copy / edit action.
2669 $singletonNames = array(
2679 //do not allow to delete these activities, CRM-4543
2680 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2682 //allow edit operation.
2683 $allowEditNames = array('Open Case');
2685 if (CRM_Core_Permission
::check('edit inbound email basic information') ||
2686 CRM_Core_Permission
::check('edit inbound email basic information and content')
2688 $allowEditNames[] = 'Inbound Email';
2691 // do not allow File on Case
2692 $doNotFileNames = array(
2695 'Change Case Status',
2696 'Change Case Start Date',
2703 if (in_array($actTypeName, $singletonNames)) {
2705 if ($operation == 'File On Case') {
2706 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2708 if (in_array($operation, $actionOperations)) {
2710 if ($operation == 'edit') {
2711 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2713 elseif ($operation == 'delete') {
2714 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2718 if ($allow && ($operation == 'delete') &&
2719 in_array($actTypeName, $doNotDeleteNames)
2724 if ($allow && ($operation == 'File On Case') &&
2725 in_array($actTypeName, $doNotFileNames)
2730 //check settings file for masking actions
2731 //on the basis the activity types
2732 //hide Edit link if activity type is NOT editable
2733 //(special case activities).CRM-5871
2734 if ($allow && in_array($operation, $actionOperations)) {
2735 static $actionFilter = array();
2736 if (!array_key_exists($operation, $actionFilter)) {
2737 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2738 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2740 if (array_key_exists($operation, $actionFilter[$operation]) &&
2741 in_array($actTypeId, $actionFilter[$operation][$operation])
2752 * Since we drop 'access CiviCase', allow access
2753 * if user has 'access my cases and activities'
2754 * or 'access all cases and activities'
2756 public static function accessCiviCase() {
2757 if (!self
::enabled()) {
2761 if (CRM_Core_Permission
::check('access my cases and activities') ||
2762 CRM_Core_Permission
::check('access all cases and activities')
2771 * Verify user has permission to access a case.
2773 * @param int $caseId
2774 * @param bool $denyClosed
2775 * Set TRUE if one wants closed cases to be treated as inaccessible.
2779 public static function accessCase($caseId, $denyClosed = TRUE) {
2780 if (!$caseId ||
!self
::enabled()) {
2784 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2785 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2786 $params['status_id'] = array('!=' => 'Closed');
2789 return (bool) civicrm_api3('Case', 'getcount', $params);
2791 catch (CiviCRM_API3_Exception
$e) {
2792 // Lack of permissions will throw an exception
2798 * Check whether activity is a case Activity.
2800 * @param int $activityID
2805 public static function isCaseActivity($activityID) {
2806 $isCaseActivity = FALSE;
2808 $params = array(1 => array($activityID, 'Integer'));
2809 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2810 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2811 $isCaseActivity = TRUE;
2815 return $isCaseActivity;
2819 * Get all the case type ids currently in use.
2823 public static function getUsedCaseType() {
2824 static $caseTypeIds;
2826 if (!is_array($caseTypeIds)) {
2827 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2829 $dao = CRM_Core_DAO
::executeQuery($query);
2830 $caseTypeIds = array();
2831 while ($dao->fetch()) {
2832 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2835 $caseTypeIds[] = $typeId[1];
2839 return $caseTypeIds;
2843 * Get all the case status ids currently in use.
2847 public static function getUsedCaseStatuses() {
2848 static $caseStatusIds;
2850 if (!is_array($caseStatusIds)) {
2851 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2853 $dao = CRM_Core_DAO
::executeQuery($query);
2854 $caseStatusIds = array();
2855 while ($dao->fetch()) {
2856 $caseStatusIds[] = $dao->status_id
;
2860 return $caseStatusIds;
2864 * Get all the encounter medium ids currently in use.
2868 public static function getUsedEncounterMediums() {
2871 if (!is_array($mediumIds)) {
2872 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2874 $dao = CRM_Core_DAO
::executeQuery($query);
2875 $mediumIds = array();
2876 while ($dao->fetch()) {
2877 $mediumIds[] = $dao->medium_id
;
2885 * Check case configuration.
2887 * @param int $contactId
2891 public static function isCaseConfigured($contactId = NULL) {
2892 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2894 //lets check for case configured.
2895 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2896 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2897 if (!$configured['configured']) {
2898 //do check for case type and case status.
2899 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2900 if (!empty($caseTypes)) {
2901 $configured['configured'] = TRUE;
2902 if (!$configured['configured']) {
2903 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2904 if (!empty($caseStatuses)) {
2905 $configured['configured'] = TRUE;
2910 if ($configured['configured']) {
2911 //do check for active case type and case status.
2912 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2913 if (!empty($caseTypes)) {
2914 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2915 if (!empty($caseStatuses)) {
2916 $configured['allowToAddNewCase'] = TRUE;
2920 //do we need to redirect user to case admin.
2921 if (!$configured['allowToAddNewCase'] && $contactId) {
2922 //check for current contact case count.
2923 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2924 //redirect user to case admin page.
2925 if (!$currentContatCasesCount) {
2926 $configured['redirectToCaseAdmin'] = TRUE;
2935 * Used during case component enablement and during ugprade.
2939 public static function createCaseViews() {
2940 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2941 $dao = new CRM_Core_DAO();
2943 $sql = self
::createCaseViewsQuery('upcoming');
2945 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2949 // Above error doesn't get caught?
2950 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2951 if (is_null($doublecheck)) {
2955 $sql = self
::createCaseViewsQuery('recent');
2957 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2961 // Above error doesn't get caught?
2962 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
2963 if (is_null($doublecheck)) {
2971 * Helper function, also used by the upgrade in case of error
2973 * @param string $section
2977 public static function createCaseViewsQuery($section = 'upcoming') {
2979 $scheduled_id = CRM_Core_Pseudoconstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
2982 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
2983 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
2984 FROM civicrm_case_activity ca
2985 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
2987 (SELECT b.id FROM civicrm_case_activity bca
2988 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
2989 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
2990 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
2991 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
2995 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
2996 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
2997 FROM civicrm_case_activity ca
2998 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3000 (SELECT b.id FROM civicrm_case_activity bca
3001 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3002 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3003 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
3004 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
3011 * Add/copy relationships, when new client is added for a case
3013 * @param int $caseId
3015 * @param int $contactId
3016 * Contact id / new client id.
3018 public static function addCaseRelationships($caseId, $contactId) {
3019 // get the case role / relationships for the case
3020 $caseRelationships = new CRM_Contact_DAO_Relationship();
3021 $caseRelationships->case_id
= $caseId;
3022 $caseRelationships->find();
3023 $relationshipTypes = array();
3025 // make sure we don't add duplicate relationships of same relationship type.
3026 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3028 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3030 // add relationship for new client.
3031 $newRelationship = new CRM_Contact_DAO_Relationship();
3032 $newRelationship->copyValues($values);
3033 $newRelationship->id
= NULL;
3034 $newRelationship->case_id
= $caseId;
3035 $newRelationship->contact_id_a
= $contactId;
3036 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3037 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3039 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3040 if (!$newRelationship->find(TRUE)) {
3041 $newRelationship->save();
3044 // store relationship type of newly created relationship
3045 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3050 * Get the list of clients for a case.
3052 * @param int $caseId
3055 * associated array with client ids
3057 public static function getCaseClients($caseId) {
3059 $caseContact = new CRM_Case_DAO_CaseContact();
3060 $caseContact->case_id
= $caseId;
3061 $caseContact->orderBy('id');
3062 $caseContact->find();
3064 while ($caseContact->fetch()) {
3065 $clients[] = $caseContact->contact_id
;
3072 * @param int $caseId
3073 * @param string $direction
3075 * @param int $relTypeId
3076 * @throws \CRM_Core_Exception
3077 * @throws \CiviCRM_API3_Exception
3079 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3081 if ($direction !== 'a' && $direction !== 'b') {
3082 throw new CRM_Core_Exception('Invalid relationship direction');
3085 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3086 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3087 $dao = CRM_Core_DAO
::executeQuery($sql, array(
3088 1 => array($caseId, 'Positive'),
3089 2 => array($cid, 'Positive'),
3090 3 => array($relTypeId, 'Positive'),
3092 while ($dao->fetch()) {
3093 civicrm_api3('relationship', 'create', array(
3096 'end_date' => 'now',
3102 * Get options for a given case field.
3103 * @see CRM_Core_DAO::buildOptions
3105 * @param string $fieldName
3106 * @param string $context
3107 * @see CRM_Core_DAO::buildOptionsContext
3108 * @param array $props
3109 * Whatever is known about this dao object.
3111 * @return array|bool
3113 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3114 $className = __CLASS__
;
3116 switch ($fieldName) {
3117 // This field is not part of this object but the api supports it
3119 $className = 'CRM_Activity_BAO_Activity';
3122 // Filter status id by case type id
3124 if (!empty($props['case_type_id'])) {
3125 $idField = is_numeric($props['case_type_id']) ?
'id' : 'name';
3126 $caseType = civicrm_api3('CaseType', 'getsingle', array($idField => $props['case_type_id'], 'return' => 'definition'));
3127 if (!empty($caseType['definition']['statuses'])) {
3128 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
3133 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3139 public function addSelectWhereClause() {
3140 // We always return an array with these keys, even if they are empty,
3141 // because this tells the query builder that we have considered these fields for acls
3144 // Only case admins can view deleted cases
3145 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
array() : array("= 0"),
3147 // Ensure the user has permission to view the case client
3148 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3149 if ($contactClause) {
3150 $contactClause = implode(' AND contact_id ', $contactClause);
3151 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3153 // The api gatekeeper ensures the user has at least "access my cases and activities"
3154 // so if they do not have permission to see all cases we'll assume they can only access their own
3155 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3156 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3157 $clauses['id'][] = "IN (
3158 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 (
3159 (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)
3163 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3168 * CRM-20308: Method to get the contact id to use as from contact for email copy
3169 * 1. Activity Added by Contact's email address
3170 * 2. System Default From Address
3171 * 3. Default Organization Contact email address
3174 * @param int $activityID
3176 * @return mixed $emailFromContactId
3177 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3179 public static function getReceiptFrom($activityID) {
3180 $name = $address = NULL;
3182 if (!empty($activityID) && (Civi
::settings()->get('allow_mail_from_logged_in_contact'))) {
3183 // This breaks SPF/DMARC if email is sent from an email address that the server is not authorised to send from.
3184 // so we can disable this behaviour with the "allow_mail_from_logged_in_contact" setting.
3185 // There is always a 'Added by' contact for a activity,
3186 // so we can safely use ActivityContact.Getvalue API
3187 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', array(
3188 'activity_id' => $activityID,
3189 'record_type_id' => 'Activity Source',
3190 'return' => 'contact_id',
3192 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3195 // If 'From' email address not found for Source Activity Contact then
3196 // fetch the email from domain or logged in user.
3197 if (empty($address)) {
3198 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3201 return "$name <$address>";
3207 public static function getEntityRefFilters() {
3210 'key' => 'case_id.case_type_id',
3211 'value' => ts('Case Type'),
3215 'key' => 'case_id.status_id',
3216 'value' => ts('Case Status'),
3220 foreach (CRM_Contact_BAO_Contact
::getEntityRefFilters() as $filter) {
3221 $filter +
= ['entity' => 'Contact'];
3222 $filter['key'] = 'contact_id.' . $filter['key'];
3223 $filters[] = $filter;