3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 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 $caseDAO->find(TRUE); // Get other case values (required by XML processor), this adds to $result array
84 * Takes an associative array and creates a case object.
86 * @param array $params
87 * (reference) an assoc array of name/value pairs.
89 * @return CRM_Case_BAO_Case
91 public static function &create(&$params) {
92 // CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps.
93 unset($params['created_date']);
94 unset($params['modified_date']);
95 $caseStatus = CRM_Case_PseudoConstant
::caseStatus('name');
96 // for resolved case the end date should set to now
97 if (!empty($params['status_id']) && $params['status_id'] == array_search('Closed', $caseStatus)) {
98 $params['end_date'] = date("Ymd");
101 $transaction = new CRM_Core_Transaction();
103 if (!empty($params['id'])) {
104 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
107 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
110 $case = self
::add($params);
112 if (!empty($params['custom']) &&
113 is_array($params['custom'])
115 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
118 if (is_a($case, 'CRM_Core_Error')) {
119 $transaction->rollback();
123 if (!empty($params['id'])) {
124 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
127 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
129 $transaction->commit();
131 //we are not creating log for case
132 //since case log can be tracked using log for activity.
137 * Process case activity add/delete
138 * takes an associative array and
140 * @param array $params
141 * (reference ) an assoc array of name/value pairs.
144 public static function processCaseActivity(&$params) {
145 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
146 $caseActivityDAO->activity_id
= $params['activity_id'];
147 $caseActivityDAO->case_id
= $params['case_id'];
149 $caseActivityDAO->find(TRUE);
150 $caseActivityDAO->save();
154 * Get the case subject for Activity.
156 * @param int $activityId
159 * @return string|null
161 public static function getCaseSubject($activityId) {
162 $caseActivity = new CRM_Case_DAO_CaseActivity();
163 $caseActivity->activity_id
= $activityId;
164 if ($caseActivity->find(TRUE)) {
165 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
174 * @param string $colName
179 public static function getCaseType($caseId, $colName = 'title') {
181 SELECT civicrm_case_type.{$colName} FROM civicrm_case
182 LEFT JOIN civicrm_case_type ON
183 civicrm_case.case_type_id = civicrm_case_type.id
184 WHERE civicrm_case.id = %1";
186 $queryParams = array(1 => array($caseId, 'Integer'));
188 return CRM_Core_DAO
::singleValueQuery($query, $queryParams);
192 * Delete the record that are associated with this case.
193 * record are deleted from case
196 * Id of the case to delete.
198 * @param bool $moveToTrash
203 public static function deleteCase($caseId, $moveToTrash = FALSE) {
204 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
207 $activities = self
::getCaseActivityDates($caseId);
209 foreach ($activities as $value) {
210 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
215 $transaction = new CRM_Core_Transaction();
217 $case = new CRM_Case_DAO_Case();
220 $result = $case->delete();
221 $transaction->commit();
224 $result = $case->is_deleted
= 1;
229 // CRM-7364, disable relationships
230 self
::enableDisableCaseRelationships($caseId, FALSE);
232 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
234 // remove case from recent items.
239 CRM_Utils_Recent
::del($caseRecent);
247 * Enable disable case related relationships.
251 * @param bool $enable
254 public static function enableDisableCaseRelationships($caseId, $enable) {
255 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
256 if (!empty($contactIds)) {
257 foreach ($contactIds as $cid) {
258 $roles = self
::getCaseRoles($cid, $caseId);
259 if (!empty($roles)) {
260 $relationshipIds = implode(',', array_keys($roles));
261 $enable = (int) $enable;
262 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
263 WHERE id IN ( {$relationshipIds} )";
264 CRM_Core_DAO
::executeQuery($query);
271 * Retrieve contact_id by case_id.
276 * @param int $contactID
277 * @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
281 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL, $startArrayAt = 0) {
282 $caseContact = new CRM_Case_DAO_CaseContact();
283 $caseContact->case_id
= $caseId;
284 $caseContact->find();
285 $contactArray = array();
286 $count = $startArrayAt;
287 while ($caseContact->fetch()) {
288 if ($contactID != $caseContact->contact_id
) {
289 $contactArray[$count] = $caseContact->contact_id
;
294 return $contactArray;
298 * Look up a case using an activity ID.
300 * @param int $activityId
302 * @return int, case ID
304 public static function getCaseIdByActivityId($activityId) {
305 $originalId = CRM_Core_DAO
::singleValueQuery(
306 'SELECT original_id FROM civicrm_activity WHERE id = %1',
307 array('1' => array($activityId, 'Integer'))
309 $caseId = CRM_Core_DAO
::singleValueQuery(
310 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
312 '1' => array($activityId, 'Integer'),
313 '2' => array($originalId ?
$originalId : $activityId, 'Integer'),
320 * Retrieve contact names by caseId.
327 public static function getContactNames($caseId) {
328 $contactNames = array();
330 return $contactNames;
334 SELECT contact_a.sort_name name,
335 contact_a.display_name as display_name,
337 contact_a.birth_date as birth_date,
340 FROM civicrm_contact contact_a
341 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
342 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
343 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
344 WHERE contact_a.is_deleted = 0 AND civicrm_case_contact.case_id = %1
345 ORDER BY civicrm_case_contact.id";
347 $dao = CRM_Core_DAO
::executeQuery($query,
348 array(1 => array($caseId, 'Integer'))
350 while ($dao->fetch()) {
351 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
352 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
353 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
354 $contactNames[$dao->cid
]['email'] = $dao->email
;
355 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
356 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
357 $contactNames[$dao->cid
]['role'] = ts('Client');
360 return $contactNames;
364 * Retrieve case_id by contact_id.
366 * @param int $contactID
367 * @param bool $includeDeleted
368 * Include the deleted cases in result.
369 * @param null $caseType
373 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
376 FROM civicrm_case_contact cc
377 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
379 if (isset($caseType)) {
381 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
382 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
384 if (!isset($caseType)) {
385 $query .= "WHERE cc.contact_id = %1";
387 if (!$includeDeleted) {
388 $query .= " AND ca.is_deleted = 0";
391 $params = array(1 => array($contactID, 'Integer'));
392 $dao = CRM_Core_DAO
::executeQuery($query, $params);
394 $caseArray = array();
395 while ($dao->fetch()) {
396 $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
422 public static function getCaseActivityQuery($type = 'upcoming', $userID, $condition = NULL, $limit = NULL, $order = NULL) {
423 $selectClauses = array(
424 'civicrm_case.id as case_id',
425 'civicrm_case.subject as case_subject',
426 'civicrm_contact.id as contact_id',
427 'civicrm_contact.sort_name as sort_name',
428 'civicrm_phone.phone as phone',
429 'civicrm_contact.contact_type as contact_type',
430 'civicrm_contact.contact_sub_type as contact_sub_type',
431 't_act.activity_type_id',
432 'c_type.title as case_type',
433 'civicrm_case.case_type_id as case_type_id',
434 'cov_status.label as case_status',
435 'cov_status.label as case_status_name',
437 'civicrm_case.start_date as case_start_date',
438 'case_relation_type.label_b_a as case_role',
441 if ($type == 'upcoming') {
442 $selectClauses = array_merge($selectClauses, array(
443 't_act.desired_date as case_scheduled_activity_date',
444 't_act.id as case_scheduled_activity_id',
445 't_act.act_type_name as case_scheduled_activity_type_name',
446 't_act.act_type AS case_scheduled_activity_type',
449 elseif ($type == 'recent') {
450 $selectClauses = array_merge($selectClauses, array(
451 't_act.desired_date as case_recent_activity_date',
452 't_act.id as case_recent_activity_id',
453 't_act.act_type_name as case_recent_activity_type_name',
454 't_act.act_type AS case_recent_activity_type',
457 elseif ($type == 'any') {
458 $selectClauses = array_merge($selectClauses, array(
459 't_act.desired_date as case_activity_date',
460 't_act.id as case_activity_id',
461 't_act.act_type_name as case_activity_type_name',
462 't_act.act_type AS case_activity_type',
466 $query = CRM_Contact_BAO_Query
::appendAnyValueToSelect($selectClauses, 'case_id');
468 $query .= " FROM civicrm_case
469 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
470 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
472 if ($type == 'upcoming') {
473 // This gets the earliest activity per case that's scheduled within 14 days from now.
474 // 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.
475 // In this case we don't really care which one, so min(id) works.
476 // optimized in CRM-11837
477 $query .= " INNER JOIN
479 SELECT case_id, act.id, activity_date_time AS desired_date, activity_type_id, status_id, aov.name AS act_type_name, aov.label AS act_type
484 FROM civicrm_view_case_activity_upcoming
485 ORDER BY activity_date_time ASC, id ASC
488 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
489 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
493 elseif ($type == 'recent') {
494 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
495 //improve query performance - CRM-10598
496 $query .= " INNER JOIN
498 SELECT case_id, act.id, activity_date_time AS desired_date, activity_type_id, status_id, aov.name AS act_type_name, aov.label AS act_type
503 FROM civicrm_view_case_activity_recent
504 ORDER BY activity_date_time DESC, id ASC
507 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
508 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
511 elseif ($type == 'any') {
512 $query .= " LEFT JOIN
514 SELECT ca4.case_id, act4.id AS id, act4.activity_date_time AS desired_date, act4.activity_type_id, act4.status_id, aov.name AS act_type_name, aov.label AS act_type
515 FROM civicrm_activity act4
516 LEFT JOIN civicrm_case_activity ca4
517 ON ca4.activity_id = act4.id
518 AND act4.is_current_revision = 1
519 LEFT JOIN civicrm_option_group aog
520 ON aog.name='activity_type'
521 LEFT JOIN civicrm_option_value aov
522 ON aov.option_group_id = aog.id
523 AND aov.value = act4.activity_type_id
528 ON t_act.case_id = civicrm_case.id
529 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
530 LEFT JOIN civicrm_relationship case_relationship
531 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
532 AND case_relationship.case_id = civicrm_case.id )
534 LEFT JOIN civicrm_relationship_type case_relation_type
535 ON ( case_relation_type.id = case_relationship.relationship_type_id
536 AND case_relation_type.id = case_relationship.relationship_type_id )
538 LEFT JOIN civicrm_case_type c_type
539 ON civicrm_case.case_type_id = c_type.id
541 LEFT JOIN civicrm_option_group cog_status
542 ON cog_status.name = 'case_status'
544 LEFT JOIN civicrm_option_value cov_status
545 ON ( civicrm_case.status_id = cov_status.value
546 AND cog_status.id = cov_status.option_group_id )
550 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
551 $query .= " WHERE (1) AND $condition ";
553 $query .= " GROUP BY case_id ";
559 if ($type == 'upcoming') {
560 $query .= " ORDER BY case_scheduled_activity_date ASC ";
562 elseif ($type == 'recent') {
563 $query .= " ORDER BY case_recent_activity_date ASC ";
565 elseif ($type == 'any') {
566 $query .= " ORDER BY case_activity_date ASC ";
578 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
580 * @param bool $allCases
581 * @param array $params
582 * @param string $context
583 * @param bool $getCount
588 public static function getCases($allCases = TRUE, $params = array(), $context = 'dashboard', $getCount = FALSE) {
590 $casesList = array();
592 //validate access for own cases.
593 if (!self
::accessCiviCase()) {
594 return $getCount ?
0 : $casesList;
597 $type = CRM_Utils_Array
::value('type', $params, 'upcoming');
598 $userID = CRM_Core_Session
::singleton()->get('userID');
600 $caseActivityTypeColumn = 'case_activity_type_name';
601 $caseActivityDateColumn = 'case_activity_date';
602 $caseActivityIDColumn = 'case_activity_id';
603 if ($type == 'upcoming') {
604 $caseActivityDateColumn = 'case_scheduled_activity_date';
605 $caseActivityTypeColumn = 'case_scheduled_activity_type';
606 $caseActivityIDColumn = 'case_scheduled_activity_id';
608 elseif ($type == 'recent') {
609 $caseActivityDateColumn = 'case_recent_activity_date';
610 $caseActivityTypeColumn = 'case_recent_activity_type';
611 $caseActivityIDColumn = 'case_recent_activity_id';
614 //validate access for all cases.
615 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
619 $whereClauses = array('civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1');
622 $whereClauses[] .= " case_relationship.contact_id_b = {$userID} ";
624 if (empty($params['status_id']) && ($type == 'upcoming' ||
$type == 'any')) {
625 $whereClauses[] = " civicrm_case.status_id != " . CRM_Core_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
628 foreach (array('case_type_id', 'status_id') as $column) {
629 if (!empty($params[$column])) {
630 $whereClauses[] = sprintf("civicrm_case.%s IN (%s)", $column, $params[$column]);
633 $condition = implode(' AND ', $whereClauses);
635 $totalCount = CRM_Core_DAO
::singleValueQuery(self
::getCaseActivityCountQuery($type, $userID, $condition));
639 $casesList['total'] = $totalCount;
642 if (!empty($params['rp'])) {
643 $params['offset'] = ($params['page'] - 1) * $params['rp'];
644 $params['rowCount'] = $params['rp'];
645 if (!empty($params['rowCount']) && $params['rowCount'] > 0) {
646 $limit = " LIMIT {$params['offset']}, {$params['rowCount']} ";
651 if (!empty($params['sortBy'])) {
652 if (strstr($params['sortBy'], 'date ')) {
653 $params['sortBy'] = str_replace('date', $caseActivityDateColumn, $params['sortBy']);
655 $order = "ORDER BY " . $params['sortBy'];
658 $query = self
::getCaseActivityQuery($type, $userID, $condition, $limit, $order);
659 $result = CRM_Core_DAO
::executeQuery($query);
661 $caseStatus = CRM_Core_OptionGroup
::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
663 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
664 $actions = CRM_Case_Selector_Search
::links();
666 // check is the user has view/edit signer permission
667 $permissions = array(CRM_Core_Permission
::VIEW
);
668 if (CRM_Core_Permission
::check('access all cases and activities') ||
669 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
671 $permissions[] = CRM_Core_Permission
::EDIT
;
673 if (CRM_Core_Permission
::check('delete in CiviCase')) {
674 $permissions[] = CRM_Core_Permission
::DELETE
;
676 $mask = CRM_Core_Action
::mask($permissions);
678 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
679 foreach ($result->fetchAll() as $key => $case) {
680 $casesList[$key] = array();
681 $casesList[$key]['DT_RowId'] = $case['case_id'];
682 $casesList[$key]['DT_RowAttr'] = array('data-entity' => 'case', 'data-id' => $case['case_id']);
683 $casesList[$key]['DT_RowClass'] = "crm-entity";
685 $casesList[$key]['activity_list'] = sprintf('<a title="%s" class="crm-expand-row" href="%s"></a>',
687 CRM_Utils_System
::url('civicrm/case/details', array('caseId' => $case['case_id'], 'cid' => $case['contact_id'], 'type' => $type))
690 $phone = empty($case['phone']) ?
'' : '<br /><span class="description">' . $case['phone'] . '</span>';
691 $casesList[$key]['contact_id'] = sprintf('<a href="%s">%s</a>%s<br /><span class="description">%s: %d</span>',
692 CRM_Utils_System
::url('civicrm/contact/view', array('cid' => $case['contact_id'])),
698 $casesList[$key]['subject'] = $case['case_subject'];
699 $casesList[$key]['case_status'] = in_array($case['case_status'], $caseStatus) ?
sprintf('<strong>%s</strong>', strtoupper($case['case_status'])) : $case['case_status'];
700 $casesList[$key]['case_type'] = $case['case_type'];
701 $casesList[$key]['case_role'] = CRM_Utils_Array
::value('case_role', $case, '---');
702 $casesList[$key]['manager'] = self
::getCaseManagerContact($caseTypes[$case['case_type_id']], $case['case_id']);
704 $casesList[$key]['date'] = $case[$caseActivityTypeColumn];
705 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $case)) ||
706 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $case))
708 if (self
::checkPermission($actId, 'view', $case['activity_type_id'], $userID)) {
709 if ($type == 'recent') {
710 $casesList[$key]['date'] = sprintf('<a class="action-item crm-hover-button" href="%s" title="%s">%s</a>',
711 CRM_Utils_System
::url('civicrm/case/activity/view', array('reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case[$caseActivityIDColumn])),
713 $case[$caseActivityTypeColumn]
717 $status = CRM_Utils_Date
::overdue($case[$caseActivityDateColumn]) ?
'status-overdue' : 'status-scheduled';
718 $casesList[$key]['date'] = sprintf('<a class="crm-popup %s" href="%s" title="%s">%s</a> ',
720 CRM_Utils_System
::url('civicrm/case/activity/view', array('reset' => 1, 'cid' => $case['contact_id'], 'aid' => $case[$caseActivityIDColumn])),
722 $case[$caseActivityTypeColumn]
726 if (self
::checkPermission($actId, 'edit', $case['activity_type_id'], $userID)) {
727 $casesList[$key]['date'] .= sprintf('<a class="action-item crm-hover-button" href="%s" title="%s"><i class="crm-i fa-pencil"></i></a>',
728 CRM_Utils_System
::url('civicrm/case/activity', array('reset' => 1, 'cid' => $case['contact_id'], 'caseid' => $case['case_id'], 'action' => 'update', 'id' => $actId)),
733 $casesList[$key]['date'] .= "<br/>" . CRM_Utils_Date
::customFormat($case[$caseActivityDateColumn]);
734 $casesList[$key]['links'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
736 'id' => $case['case_id'],
737 'cid' => $case['contact_id'],
742 'case.actions.primary',
752 * Get the summary of cases counts by type and status.
754 * @param bool $allCases
757 public static function getCasesSummary($allCases = TRUE) {
758 $caseSummary = array();
760 //validate access for civicase.
761 if (!self
::accessCiviCase()) {
765 $userID = CRM_Core_Session
::singleton()->get('userID');
767 //validate access for all cases.
768 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
772 $caseTypes = CRM_Case_PseudoConstant
::caseType();
773 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
774 $caseTypes = array_flip($caseTypes);
776 // get statuses as headers for the table
777 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
778 foreach ($caseStatuses as $key => $name) {
779 $caseSummary['headers'][$key]['status'] = $name;
780 $caseSummary['headers'][$key]['url'] = $url . $key;
783 // build rows with actual data
785 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
791 $myGroupByClause = ' GROUP BY civicrm_case.id';
796 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
797 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
799 $myGroupByClause .= ", case_status.label, status_id, case_type_id";
801 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
803 SELECT case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
804 case_type_id, case_relationship.contact_id_b
806 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
807 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
808 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
809 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
810 AND option_group_case_status.id = case_status.option_group_id )
811 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
812 AND case_relationship.contact_id_b = {$userID})
813 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
814 {$myCaseWhereClause} {$myGroupByClause}";
816 $res = CRM_Core_DAO
::executeQuery($query);
817 while ($res->fetch()) {
818 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
819 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
822 $rows[$res->case_type
][$res->case_status
] = array(
824 'url' => CRM_Utils_System
::url('civicrm/case/search',
825 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
830 $caseSummary['rows'] = array_merge($caseTypes, $rows);
838 * @param int $contactID
842 * @param int $relationshipID
843 * @param bool $activeOnly
846 * case role / relationships
849 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL, $activeOnly = TRUE) {
851 SELECT rel.id as civicrm_relationship_id,
852 con.sort_name as sort_name,
853 civicrm_email.email as email,
854 civicrm_phone.phone as phone,
855 con.id as civicrm_contact_id,
856 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
857 civicrm_relationship_type.id as relation_type,
858 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
859 FROM civicrm_relationship rel
860 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
861 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))
862 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
863 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
864 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
865 AND con.is_deleted = 0';
868 $query .= ' AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
872 1 => array($contactID, 'Positive'),
873 2 => array($caseID, 'Positive'),
876 if ($relationshipID) {
877 $query .= ' AND rel.id = %3 ';
878 $params[3] = array($relationshipID, 'Integer');
880 $dao = CRM_Core_DAO
::executeQuery($query, $params);
883 while ($dao->fetch()) {
884 $rid = $dao->civicrm_relationship_id
;
885 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
886 $values[$rid]['relation'] = $dao->relation
;
887 $values[$rid]['name'] = $dao->sort_name
;
888 $values[$rid]['email'] = $dao->email
;
889 $values[$rid]['phone'] = $dao->phone
;
890 $values[$rid]['relation_type'] = $dao->relation_type
;
891 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
892 $values[$rid]['client_id'] = $contactID;
893 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
901 * Get Case Activities.
905 * @param array $params
907 * @param int $contactID
910 * @param null $context
912 * @param null $type (deprecated)
915 * Array of case activities
918 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
919 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
920 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
921 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
922 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
924 // CRM-5081 - formatting the dates to omit seconds.
925 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
927 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
929 ca.activity_type_id AS type,
930 ca.activity_type_id AS activity_type_id,
931 tcc.sort_name AS target_contact_name,
932 tcc.id AS target_contact_id,
933 scc.sort_name AS source_contact_name,
934 scc.id AS source_contact_id,
935 acc.sort_name AS assignee_contact_name,
936 acc.id AS assignee_contact_id,
938 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
939 ca.activity_date_time,
940 DATE_ADD(NOW(), INTERVAL 1 YEAR)
941 ), '%Y%m%d%H%i00') AS overdue_date,
942 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
943 ca.status_id AS status,
944 ca.subject AS subject,
945 ca.is_deleted AS deleted,
946 ca.priority_id AS priority,
948 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
951 FROM civicrm_case_activity cca
952 INNER JOIN civicrm_activity ca
953 ON ca.id = cca.activity_id
954 INNER JOIN civicrm_activity_contact cas
955 ON cas.activity_id = ca.id
956 AND cas.record_type_id = {$sourceID}
957 INNER JOIN civicrm_contact scc
958 ON scc.id = cas.contact_id
959 LEFT JOIN civicrm_activity_contact caa
960 ON caa.activity_id = ca.id
961 AND caa.record_type_id = {$assigneeID}
962 LEFT JOIN civicrm_contact acc
963 ON acc.id = caa.contact_id
964 LEFT JOIN civicrm_activity_contact cat
965 ON cat.activity_id = ca.id
966 AND cat.record_type_id = {$targetID}
967 LEFT JOIN civicrm_contact tcc
968 ON tcc.id = cat.contact_id
969 INNER JOIN civicrm_option_group cog
970 ON cog.name = 'activity_type'
971 INNER JOIN civicrm_option_value cov
972 ON cov.option_group_id = cog.id
973 AND cov.value = ca.activity_type_id
974 AND cov.is_active = 1
975 LEFT JOIN civicrm_entity_file ef
976 ON ef.entity_table = 'civicrm_activity'
977 AND ef.entity_id = ca.id
978 LEFT OUTER JOIN civicrm_option_group og
979 ON og.name = 'activity_status'
980 LEFT OUTER JOIN civicrm_option_value ov
981 ON ov.option_group_id=og.id
982 AND ov.name = 'Scheduled'";
985 WHERE cca.case_id= %1
986 AND ca.is_current_revision = 1';
988 if (!empty($params['source_contact_id'])) {
990 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
993 if (!empty($params['status_id'])) {
995 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
998 if (!empty($params['activity_deleted'])) {
1000 AND ca.is_deleted = 1";
1004 AND ca.is_deleted = 0";
1007 if (!empty($params['activity_type_id'])) {
1009 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
1012 if (!empty($params['activity_date_low'])) {
1013 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
1015 if (!empty($fromActivityDate)) {
1017 AND ca.activity_date_time >= '{$fromActivityDate}'";
1020 if (!empty($params['activity_date_high'])) {
1021 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
1022 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
1024 if (!empty($toActivityDate)) {
1026 AND ca.activity_date_time <= '{$toActivityDate}'";
1030 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
1032 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
1034 // CRM-5081 - added id to act like creation date
1036 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
1039 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
1040 $orderBy = " ORDER BY $sortBy ";
1043 $page = CRM_Utils_Array
::value('page', $params);
1044 $rp = CRM_Utils_Array
::value('rp', $params);
1052 $start = (($page - 1) * $rp);
1053 $limit = " LIMIT $start, $rp";
1055 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
1056 $queryParams = array(1 => array($caseID, 'Integer'));
1058 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
1059 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
1061 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1062 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus();
1064 $url = CRM_Utils_System
::url("civicrm/case/activity",
1065 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1069 if ($context == 'fulltext') {
1070 $contextUrl = "&context={$context}";
1072 $editUrl = "{$url}&action=update{$contextUrl}";
1073 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1074 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1075 $viewTitle = ts('View activity');
1077 $emailActivityTypeIDs = array(
1078 'Email' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email'),
1079 'Inbound Email' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email'),
1082 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1084 $compStatusValues = array_keys(
1085 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::COMPLETED
) +
1086 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::CANCELLED
)
1090 $session = CRM_Core_Session
::singleton();
1091 $userID = $session->get('userID');
1094 $caseActivities = array();
1096 while ($dao->fetch()) {
1097 $caseActivity = array();
1098 $caseActivityId = $dao->id
;
1100 $allowView = self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID);
1101 $allowEdit = self
::checkPermission($caseActivityId, 'edit', $dao->activity_type_id
, $userID);
1102 $allowDelete = self
::checkPermission($caseActivityId, 'delete', $dao->activity_type_id
, $userID);
1104 //do not have sufficient permission
1105 //to access given case activity record.
1106 if (!$allowView && !$allowEdit && !$allowDelete) {
1110 $caseActivities[$caseActivityId]['DT_RowId'] = $caseActivityId;
1111 //Add classes to the row, via DataTables syntax
1112 $caseActivities[$caseActivityId]['DT_RowClass'] = "crm-entity status-id-$dao->status";
1114 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1115 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-completed";
1118 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1119 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-overdue";
1122 $caseActivities[$caseActivityId]['DT_RowClass'] .= " status-scheduled";
1126 if (!empty($dao->priority
)) {
1127 if ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Urgent')) {
1128 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-urgent ";
1130 elseif ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Low')) {
1131 $caseActivities[$caseActivityId]['DT_RowClass'] .= " priority-low ";
1135 //Add data to the row for inline editing, via DataTable syntax
1136 $caseActivities[$caseActivityId]['DT_RowAttr'] = array();
1137 $caseActivities[$caseActivityId]['DT_RowAttr']['data-entity'] = 'activity';
1138 $caseActivities[$caseActivityId]['DT_RowAttr']['data-id'] = $caseActivityId;
1140 //Activity Date and Time
1141 $caseActivities[$caseActivityId]['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1144 $caseActivities[$caseActivityId]['subject'] = $dao->subject
;
1147 $caseActivities[$caseActivityId]['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1148 . $activityTypes[$dao->type
]['label'];
1150 // Activity Target (With Contact) (There can be more than one)
1151 $targetContact = self
::formatContactLink($dao->target_contact_id
, $dao->target_contact_name
);
1152 if (empty($caseActivities[$caseActivityId]['target_contact_name'])) {
1153 $caseActivities[$caseActivityId]['target_contact_name'] = $targetContact;
1156 if (strpos($caseActivities[$caseActivityId]['target_contact_name'], $targetContact) === FALSE) {
1157 $caseActivities[$caseActivityId]['target_contact_name'] .= '; ' . $targetContact;
1161 // Activity Source Contact (Reporter) (There can only be one)
1162 $sourceContact = self
::formatContactLink($dao->source_contact_id
, $dao->source_contact_name
);
1163 $caseActivities[$caseActivityId]['source_contact_name'] = $sourceContact;
1165 // Activity Assignee (There can be more than one)
1166 $assigneeContact = self
::formatContactLink($dao->assignee_contact_id
, $dao->assignee_contact_name
);
1167 if (empty($caseActivities[$caseActivityId]['assignee_contact_name'])) {
1168 $caseActivities[$caseActivityId]['assignee_contact_name'] = $assigneeContact;
1171 if (strpos($caseActivities[$caseActivityId]['assignee_contact_name'], $assigneeContact) === FALSE) {
1172 $caseActivities[$caseActivityId]['assignee_contact_name'] .= '; ' . $assigneeContact;
1177 $caseActivities[$caseActivityId]['status_id'] = $activityStatuses[$dao->status
];
1179 // 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.
1181 $css = 'class="action-item crm-hover-button"';
1183 $viewUrl = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1184 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1186 $additionalUrl = "&id={$caseActivityId}";
1187 if (!$dao->deleted
) {
1188 //hide edit link of activity type email.CRM-4530.
1189 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1190 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1192 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1196 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1199 elseif (!$caseDeleted) {
1200 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1201 $caseActivities[$caseActivityId]['status_id'] = $caseActivities[$caseActivityId]['status_id'] . '<br /> (deleted)';
1204 //check for operations.
1205 if (self
::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id
)) {
1206 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1208 if (self
::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id
)) {
1209 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1211 // if there are file attachments we will return how many and, if only one, add a link to it
1212 if (!empty($dao->attachment_ids
)) {
1213 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1214 $caseActivities[$caseActivityId]['no_attachments'] = count($attachmentIDs);
1215 $url .= implode(' ', CRM_Core_BAO_File
::paperIconAttachment('civicrm_activity', $caseActivityId));
1218 $caseActivities[$caseActivityId]['links'] = $url;
1222 $caseActivitiesDT = array();
1223 $caseActivitiesDT['data'] = array_values($caseActivities);
1224 $caseActivitiesDT['recordsTotal'] = $caseCount;
1225 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1227 return $caseActivitiesDT;
1231 * Helper function to generate a formatted contact link/name for display in the Case activities tab
1234 * @param $contactName
1238 private static function formatContactLink($contactId, $contactName) {
1239 if (empty($contactId)) {
1243 $hasViewContact = CRM_Contact_BAO_Contact_Permission
::allow($contactId);
1245 if ($hasViewContact) {
1246 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid={$contactId}");
1247 return "<a href=\"{$contactViewUrl}\">" . $contactName . "</a>";
1250 return $contactName;
1255 * Get Case Related Contacts.
1257 * @param int $caseID
1259 * @param bool $includeDetails
1260 * If true include details of contacts.
1263 * array of return properties
1266 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1267 $caseRoles = array();
1268 if ($includeDetails) {
1269 $caseInfo = civicrm_api3('Case', 'getsingle', array(
1271 // 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
1272 'return' => array('case_type_id', 'case_type_id.name', 'case_type_id.definition'),
1274 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1275 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1280 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
1281 FROM civicrm_relationship cr
1282 LEFT JOIN civicrm_relationship_type crt
1283 ON crt.id = cr.relationship_type_id
1284 LEFT JOIN civicrm_contact cc
1285 ON cc.id = cr.contact_id_b
1286 LEFT JOIN civicrm_email ce
1287 ON ce.contact_id = cc.id
1288 AND ce.is_primary= 1
1289 LEFT JOIN civicrm_phone cp
1290 ON cp.contact_id = cc.id
1291 AND cp.is_primary= 1
1292 WHERE cr.case_id = %1 AND cr.is_active AND cc.is_deleted <> 1';
1294 $params = array(1 => array($caseID, 'Integer'));
1295 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1297 while ($dao->fetch()) {
1298 if (!$includeDetails) {
1299 $values[$dao->id
] = 1;
1303 'contact_id' => $dao->id
,
1304 'display_name' => $dao->name
,
1305 'sort_name' => $dao->sort_name
,
1306 'relationship_type_id' => $dao->relationship_type_id
,
1307 'role' => $dao->role
,
1308 'email' => $dao->email
,
1309 'phone' => $dao->phone
,
1311 // Add more info about the role (creator, manager)
1312 $role = CRM_Utils_Array
::value($dao->name_b_a
, $caseRoles);
1314 unset($role['name']);
1317 $values[] = $details;
1326 * Send e-mail copy of activity
1328 * @param int $clientId
1329 * @param int $activityId
1331 * @param array $contacts
1332 * Array of related contact.
1334 * @param null $attachments
1335 * @param int $caseId
1337 * @return bool |array
1339 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1344 $tplParams = $activityInfo = array();
1345 //if its a case activity
1347 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1348 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1349 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1350 $anyActivity = TRUE;
1353 $anyActivity = FALSE;
1355 $tplParams['isCaseActivity'] = 1;
1356 $tplParams['client_id'] = $clientId;
1359 $anyActivity = TRUE;
1362 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1363 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1365 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1367 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1369 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1371 $tplParams['activity'] = $activityInfo;
1372 foreach ($tplParams['activity']['fields'] as $k => $val) {
1373 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1374 $activitySubject = $val['value'];
1378 $session = CRM_Core_Session
::singleton();
1379 // CRM-8926 If user is not logged in, use the activity creator as userID
1380 if (!($userID = $session->get('userID'))) {
1381 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1384 //also create activities simultaneously of this copy.
1385 $activityParams = array();
1387 $activityParams['source_record_id'] = $activityId;
1388 $activityParams['source_contact_id'] = $userID;
1389 $activityParams['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', 'Email');
1390 $activityParams['activity_date_time'] = date('YmdHis');
1391 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
1392 $activityParams['medium_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'encounter_medium', 'email');
1393 $activityParams['case_id'] = $caseId;
1394 $activityParams['is_auto'] = 0;
1395 $activityParams['target_id'] = $clientId;
1397 $tplParams['activitySubject'] = $activitySubject;
1399 // if it’s a case activity, add hashed id to the template (CRM-5916)
1401 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1405 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1406 $receiptFrom = self
::getReceiptFrom($activityId);
1408 $recordedActivityParams = array();
1410 foreach ($contacts as $mail => $info) {
1411 $tplParams['contact'] = $info;
1412 self
::buildPermissionLinks($tplParams, $activityParams);
1414 $displayName = CRM_Utils_Array
::value('display_name', $info);
1416 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1418 'groupName' => 'msg_tpl_workflow_case',
1419 'valueName' => 'case_activity',
1420 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1421 'tplParams' => $tplParams,
1422 'from' => $receiptFrom,
1423 'toName' => $displayName,
1425 'attachments' => $attachments,
1429 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1430 $activityParams['details'] = $message;
1432 if (!empty($result[$info['contact_id']])) {
1434 * Really only need to record one activity with all the targets combined.
1435 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1436 * but it's always the same content at the moment.
1438 if (empty($recordedActivityParams)) {
1439 $recordedActivityParams = $activityParams;
1442 $recordedActivityParams['subject'] .= "; $displayName";
1444 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1447 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1451 if (!empty($recordedActivityParams)) {
1452 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1454 //create case_activity record if its case activity.
1456 $caseParams = array(
1457 'activity_id' => $activity->id
,
1458 'case_id' => $caseId,
1460 self
::processCaseActivity($caseParams);
1468 * Retrieve count of activities having a particular type, and
1469 * associated with a particular case.
1471 * @param int $caseId
1473 * @param int $activityTypeId
1474 * ID of the activity type.
1478 public static function getCaseActivityCount($caseId, $activityTypeId) {
1479 $queryParam = array(
1480 1 => array($caseId, 'Integer'),
1481 2 => array($activityTypeId, 'Integer'),
1483 $query = "SELECT count(ca.id) as countact
1484 FROM civicrm_activity ca
1485 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1486 WHERE ca.activity_type_id = %2
1487 AND cca.case_id = %1
1488 AND ca.is_deleted = 0";
1490 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1491 if ($dao->fetch()) {
1492 return $dao->countact
;
1499 * Create an activity for a case via email.
1504 * @return array|void
1505 * $activity object of newly creted activity via email
1507 public static function recordActivityViaEmail($file) {
1508 if (!file_exists($file) ||
1511 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1516 $result = CRM_Utils_Mail_Incoming
::parse($file);
1517 if ($result['is_error']) {
1521 foreach ($result['to'] as $to) {
1524 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1525 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1527 if ($replacement !== $to['email']) {
1528 $caseId = $replacement;
1529 //if caseId is invalid, return as error file
1530 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1531 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1540 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1541 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1542 $contactDetails = self
::getRelatedContacts($caseId, FALSE);
1544 if (!empty($contactDetails[$result['from']['id']])) {
1546 $params['subject'] = $result['subject'];
1547 $params['activity_date_time'] = $result['date'];
1548 $params['details'] = $result['body'];
1549 $params['source_contact_id'] = $result['from']['id'];
1550 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
1552 $details = CRM_Case_PseudoConstant
::caseActivityType();
1554 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1555 $result['body'], $matches
1558 if (!empty($matches) && isset($matches[1])) {
1559 $activityType = trim($matches[1]);
1560 if (isset($details[$activityType])) {
1561 $params['activity_type_id'] = $details[$activityType]['id'];
1564 if (!isset($params['activity_type_id'])) {
1565 $params['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email');
1569 $activity = CRM_Activity_BAO_Activity
::create($params);
1571 $caseParams = array(
1572 'activity_id' => $activity->id
,
1573 'case_id' => $caseId,
1575 self
::processCaseActivity($caseParams);
1578 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1579 array(1 => $result['from']['email'])
1586 * Retrieve the scheduled activity type and date.
1588 * @param array $cases
1589 * Array of contact and case id.
1591 * @param string $type
1594 * Array of scheduled activity type and date
1598 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1599 $session = CRM_Core_Session
::singleton();
1600 $userID = $session->get('userID');
1602 $caseID = implode(',', $cases['case_id']);
1603 $contactID = implode(',', $cases['contact_id']);
1605 $condition = " civicrm_case_contact.contact_id IN( {$contactID} )
1606 AND civicrm_case.id IN( {$caseID})
1607 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1609 $query = self
::getCaseActivityQuery($type, $userID, $condition);
1611 $res = CRM_Core_DAO
::executeQuery($query);
1613 $activityInfo = array();
1614 while ($res->fetch()) {
1615 if ($type == 'upcoming') {
1616 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1617 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1620 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1621 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1625 return $activityInfo;
1629 * Combine all the exportable fields from the lower levels object.
1632 * array of exportable Fields
1634 public static function &exportableFields() {
1635 if (!self
::$_exportableFields) {
1636 if (!self
::$_exportableFields) {
1637 self
::$_exportableFields = array();
1640 $fields = CRM_Case_DAO_Case
::export();
1641 $fields['case_role'] = array('title' => ts('Role in Case'));
1642 $fields['case_type'] = array(
1643 'title' => ts('Case Type'),
1644 'name' => 'case_type',
1646 $fields['case_status'] = array(
1647 'title' => ts('Case Status'),
1648 'name' => 'case_status',
1651 // add custom data for cases
1652 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1654 self
::$_exportableFields = $fields;
1656 return self
::$_exportableFields;
1660 * Restore the record that are associated with this case.
1662 * @param int $caseId
1663 * Id of the case to restore.
1667 public static function restoreCase($caseId) {
1668 //restore activities
1669 $activities = self
::getCaseActivityDates($caseId);
1671 foreach ($activities as $value) {
1672 CRM_Activity_BAO_Activity
::restoreActivity($value);
1676 $case = new CRM_Case_DAO_Case();
1677 $case->id
= $caseId;
1678 $case->is_deleted
= 0;
1681 //CRM-7364, enable relationships
1682 self
::enableDisableCaseRelationships($caseId, TRUE);
1689 * @param null $showLinks
1690 * @param bool $returnOnlyCount
1691 * @param int $offset
1692 * @param int $rowCount
1696 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1697 $globalContacts = array();
1699 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1700 $settings = $settingsProcessor->run();
1701 if (!empty($settings)) {
1702 $groupInfo['name'] = $settings['groupname'];
1703 if ($groupInfo['name']) {
1704 $searchParams = array('name' => $groupInfo['name']);
1706 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1708 $groupInfo['id'] = $results['id'];
1709 $groupInfo['title'] = $results['title'];
1710 $params = array(array('group', '=', $groupInfo['id'], 0, 0));
1711 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1712 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1714 if ($returnOnlyCount) {
1715 return $globalContacts;
1719 foreach ($globalContacts as $idx => $contact) {
1720 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1726 return $globalContacts;
1730 * Convenience function to get both case contacts and global in one array.
1731 * @param int $caseId
1735 public static function getRelatedAndGlobalContacts($caseId) {
1736 $relatedContacts = self
::getRelatedContacts($caseId);
1738 $groupInfo = array();
1739 $globalContacts = self
::getGlobalContacts($groupInfo);
1741 //unset values which are not required.
1742 foreach ($globalContacts as $k => & $v) {
1743 unset($v['email_id']);
1744 unset($v['group_contact_id']);
1745 unset($v['status']);
1747 $v['role'] = $groupInfo['title'];
1749 //include multiple listings for the same contact/different roles.
1750 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1751 return $relatedGlobalContacts;
1755 * Get Case ActivitiesDueDates with given criteria.
1757 * @param int $caseID
1759 * @param array $criteriaParams
1761 * @param bool $latestDate
1762 * If set newest or oldest date is selected.
1765 * case activities due dates
1768 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1770 $selectDate = " ca.activity_date_time";
1771 $where = $groupBy = ' ';
1778 if (!empty($criteriaParams['activity_type_id'])) {
1779 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1780 $where .= " AND ca.is_current_revision = 1";
1781 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1784 if (!empty($criteriaParams['newest'])) {
1785 $selectDate = " max(ca.activity_date_time) ";
1788 $selectDate = " min(ca.activity_date_time) ";
1792 $query = "SELECT ca.id, {$selectDate} as activity_date
1793 FROM civicrm_activity ca
1794 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1795 WHERE cc.id = %1 {$where} {$groupBy}";
1797 $params = array(1 => array($caseID, 'Integer'));
1798 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1800 while ($dao->fetch()) {
1801 $values[$dao->id
]['id'] = $dao->id
;
1802 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1809 * Create activities when Case or Other roles assigned/modified/deleted.
1811 * @param int $caseId
1812 * @param int $relationshipId
1814 * @param int $relContactId
1815 * Case role assignee contactId.
1816 * @param int $contactId
1818 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1819 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1823 $queryParam = array();
1824 if (is_array($relationshipId)) {
1825 $relationshipId = implode(',', $relationshipId);
1826 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1829 $relationshipClause = " civicrm_relationship.id = %1";
1830 $queryParam[1] = array($relationshipId, 'Positive');
1834 SELECT cc.display_name as clientName,
1835 cca.display_name as assigneeContactName,
1836 civicrm_relationship.case_id as caseId,
1837 civicrm_relationship_type.label_a_b as relation_a_b,
1838 civicrm_relationship_type.label_b_a as relation_b_a,
1839 civicrm_relationship.contact_id_b as rel_contact_id,
1840 civicrm_relationship.contact_id_a as assign_contact_id
1841 FROM civicrm_relationship_type, civicrm_relationship
1842 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1843 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1844 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1846 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1848 while ($dao->fetch()) {
1849 // The assignee is not the client.
1850 if ($dao->rel_contact_id
!= $contactId) {
1851 $caseRelationship = $dao->relation_a_b
;
1852 $assigneContactName = $dao->clientName
;
1853 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1856 $caseRelationship = $dao->relation_b_a
;
1857 $assigneContactName = $dao->assigneeContactName
;
1858 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1862 $session = CRM_Core_Session
::singleton();
1863 $activityParams = array(
1864 'source_contact_id' => $session->get('userID'),
1865 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1866 'activity_date_time' => date('YmdHis'),
1867 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1870 //if $relContactId is passed, role is added or modified.
1871 if (!empty($relContactId)) {
1872 $activityParams['assignee_contact_id'] = $assigneContactIds;
1873 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Assign Case Role');
1876 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Remove Case Role');
1879 $activityParams['activity_type_id'] = $activityTypeID;
1881 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1883 //create case_activity record.
1884 $caseParams = array(
1885 'activity_id' => $activity->id
,
1886 'case_id' => $caseId,
1889 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1894 * contact which is assigned a case role of case manager.
1896 * @param int $caseType
1898 * @param int $caseId
1902 * html hyperlink of manager contact view page
1905 public static function getCaseManagerContact($caseType, $caseId) {
1906 if (!$caseType ||
!$caseId) {
1910 $caseManagerName = '---';
1911 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1913 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1915 if (!empty($managerRoleId)) {
1916 $managerRoleQuery = "
1917 SELECT civicrm_contact.id as casemanager_id,
1918 civicrm_contact.sort_name as casemanager
1919 FROM civicrm_contact
1920 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1921 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1922 WHERE civicrm_case.id = %2 AND is_active = 1";
1924 $managerRoleParams = array(
1925 1 => array($managerRoleId, 'Integer'),
1926 2 => array($caseId, 'Integer'),
1929 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1930 if ($dao->fetch()) {
1931 $caseManagerName = sprintf('<a href="%s">%s</a>',
1932 CRM_Utils_System
::url('civicrm/contact/view', array('cid' => $dao->casemanager_id
)),
1938 return $caseManagerName;
1942 * @param int $contactId
1943 * @param bool $excludeDeleted
1947 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1948 $params = array('check_permissions' => TRUE);
1949 if ($excludeDeleted) {
1950 $params['is_deleted'] = 0;
1953 $params['contact_id'] = $contactId;
1956 return civicrm_api3('Case', 'getcount', $params);
1958 catch (CiviCRM_API3_Exception
$e) {
1959 // Lack of permissions will throw an exception
1965 * Retrieve related case ids for given case.
1967 * @param int $caseId
1968 * @param bool $excludeDeleted
1969 * Do not include deleted cases.
1973 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1974 //FIXME : do check for permissions.
1980 $linkActType = array_search('Link Cases',
1981 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
1983 if (!$linkActType) {
1987 $whereClause = "mainCase.id = %2";
1988 if ($excludeDeleted) {
1989 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1993 SELECT relCaseAct.case_id
1994 FROM civicrm_case mainCase
1995 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1996 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1997 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1998 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1999 WHERE $whereClause";
2001 $dao = CRM_Core_DAO
::executeQuery($query, array(
2002 1 => array($linkActType, 'Integer'),
2003 2 => array($caseId, 'Integer'),
2005 $relatedCaseIds = array();
2006 while ($dao->fetch()) {
2007 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
2011 return array_values($relatedCaseIds);
2015 * Retrieve related case details for given case.
2017 * @param int $caseId
2018 * @param bool $excludeDeleted
2019 * Do not include deleted cases.
2023 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
2024 $relatedCaseIds = self
::getRelatedCaseIds($caseId, $excludeDeleted);
2025 $relatedCases = array();
2027 if (!$relatedCaseIds) {
2031 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2032 if ($excludeDeleted) {
2033 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2036 //filter for permissioned cases.
2037 $filterCases = array();
2038 $doFilterCases = FALSE;
2039 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2040 $doFilterCases = TRUE;
2041 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE);
2044 //2. fetch the details of related cases.
2046 SELECT relCase.id as id,
2047 civicrm_case_type.title as case_type,
2048 client.display_name as client_name,
2049 client.id as client_id,
2051 FROM civicrm_case relCase
2052 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2053 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2054 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
2055 WHERE {$whereClause}";
2057 $dao = CRM_Core_DAO
::executeQuery($query);
2058 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2059 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2060 $statuses = CRM_Case_BAO_Case
::buildOptions('status_id');
2062 while ($dao->fetch()) {
2064 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2065 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2066 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2067 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2069 $clientView = $dao->client_name
;
2070 if ($hasViewContact) {
2071 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2074 $relatedCases[$dao->id
] = array(
2075 'case_id' => $dao->id
,
2076 'case_type' => $dao->case_type
,
2077 'client_name' => $clientView,
2078 'case_status' => $statuses[$dao->status_id
],
2079 'links' => $caseView,
2084 return $relatedCases;
2088 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2090 * @see CRM_Dedupe_Merger::cpTables()
2092 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2094 * @param int $mainContactId
2095 * @param int $otherContactId
2097 public static function mergeContacts($mainContactId, $otherContactId) {
2098 self
::mergeCases($mainContactId, NULL, $otherContactId);
2102 * Function perform two task.
2103 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2104 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2106 * @param int $mainContactId
2107 * Contact id of main contact record.
2108 * @param int $mainCaseId
2109 * Case id of main case record.
2110 * @param int $otherContactId
2111 * Contact id of record which is going to merge.
2112 * @param int $otherCaseId
2113 * Case id of record which is going to merge.
2115 * @param bool $changeClient
2119 public static function mergeCases(
2120 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2121 $otherCaseId = NULL, $changeClient = FALSE) {
2122 $moveToTrash = TRUE;
2124 $duplicateContacts = FALSE;
2125 if ($mainContactId && $otherContactId &&
2126 $mainContactId != $otherContactId
2128 $duplicateContacts = TRUE;
2131 $duplicateCases = FALSE;
2132 if ($mainCaseId && $otherCaseId &&
2133 $mainCaseId != $otherCaseId
2135 $duplicateCases = TRUE;
2138 $mainCaseIds = array();
2139 if (!$duplicateContacts && !$duplicateCases) {
2140 return $mainCaseIds;
2143 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2144 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2145 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2146 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2147 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2148 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2150 $processCaseIds = array($otherCaseId);
2151 if ($duplicateContacts && !$duplicateCases) {
2152 if ($changeClient) {
2153 $processCaseIds = array($mainCaseId);
2156 //get all case ids for other contact.
2157 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2159 if (!is_array($processCaseIds)) {
2164 $session = CRM_Core_Session
::singleton();
2165 $currentUserId = $session->get('userID');
2167 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2169 // copy all cases and connect to main contact id.
2170 foreach ($processCaseIds as $otherCaseId) {
2171 if ($duplicateContacts) {
2172 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2173 $mainCaseId = $mainCase->id
;
2178 // CRM-11662 Copy Case custom data
2179 $extends = array('case');
2180 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2182 foreach ($groupTree as $groupID => $group) {
2183 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2184 foreach ($group['fields'] as $fieldID => $field) {
2185 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2189 foreach ($table as $tableName => $tableColumns) {
2190 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2191 $tableColumns[0] = $mainCaseId;
2192 $select = 'SELECT ' . implode(', ', $tableColumns);
2193 $from = ' FROM ' . $tableName;
2194 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2195 $query = $insert . $select . $from . $where;
2196 $dao = CRM_Core_DAO
::executeQuery($query);
2202 $mainCaseIds[] = $mainCaseId;
2203 //insert record for case contact.
2204 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2205 $otherCaseContact->case_id
= $otherCaseId;
2206 $otherCaseContact->find();
2207 while ($otherCaseContact->fetch()) {
2208 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2209 $mainCaseContact->case_id
= $mainCaseId;
2210 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2211 if ($mainCaseContact->contact_id
== $otherContactId) {
2212 $mainCaseContact->contact_id
= $mainContactId;
2214 //avoid duplicate object.
2215 if (!$mainCaseContact->find(TRUE)) {
2216 $mainCaseContact->save();
2218 $mainCaseContact->free();
2220 $otherCaseContact->free();
2222 elseif (!$otherContactId) {
2223 $otherContactId = $mainContactId;
2226 if (!$mainCaseId ||
!$otherCaseId ||
2227 !$mainContactId ||
!$otherContactId
2232 // get all activities for other case.
2233 $otherCaseActivities = array();
2234 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2236 //for duplicate cases do not process singleton activities.
2237 $otherActivityIds = $singletonActivityIds = array();
2238 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2239 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2240 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2243 $otherActivityIds[] = $otherActId;
2245 if ($duplicateCases) {
2246 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2249 FROM civicrm_activity
2250 WHERE activity_type_id = $openCaseType
2251 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2252 $dao = CRM_Core_DAO
::executeQuery($sql);
2253 while ($dao->fetch()) {
2254 $singletonActivityIds[] = $dao->id
;
2260 // migrate all activities and connect to main contact.
2261 $copiedActivityIds = $activityMappingIds = array();
2262 sort($otherActivityIds);
2263 foreach ($otherActivityIds as $otherActivityId) {
2265 //for duplicate cases -
2266 //do not migrate singleton activities.
2267 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2271 //migrate activity record.
2272 $otherActivity = new CRM_Activity_DAO_Activity();
2273 $otherActivity->id
= $otherActivityId;
2274 if (!$otherActivity->find(TRUE)) {
2278 $mainActVals = array();
2279 $mainActivity = new CRM_Activity_DAO_Activity();
2280 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2281 $mainActivity->copyValues($mainActVals);
2282 $mainActivity->id
= NULL;
2283 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2284 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2288 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2292 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2295 $mainActivity->save();
2296 $mainActivityId = $mainActivity->id
;
2297 if (!$mainActivityId) {
2301 $activityMappingIds[$otherActivityId] = $mainActivityId;
2302 // insert log of all activities
2303 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2305 $otherActivity->free();
2306 $mainActivity->free();
2307 $copiedActivityIds[] = $otherActivityId;
2309 //create case activity record.
2310 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2311 $mainCaseActivity->case_id
= $mainCaseId;
2312 $mainCaseActivity->activity_id
= $mainActivityId;
2313 $mainCaseActivity->save();
2314 $mainCaseActivity->free();
2316 //migrate source activity.
2317 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2318 $otherSourceActivity->activity_id
= $otherActivityId;
2319 $otherSourceActivity->record_type_id
= $sourceID;
2320 $otherSourceActivity->find();
2321 while ($otherSourceActivity->fetch()) {
2322 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2323 $mainActivitySource->record_type_id
= $sourceID;
2324 $mainActivitySource->activity_id
= $mainActivityId;
2325 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2326 if ($mainActivitySource->contact_id
== $otherContactId) {
2327 $mainActivitySource->contact_id
= $mainContactId;
2329 //avoid duplicate object.
2330 if (!$mainActivitySource->find(TRUE)) {
2331 $mainActivitySource->save();
2333 $mainActivitySource->free();
2335 $otherSourceActivity->free();
2337 //migrate target activities.
2338 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2339 $otherTargetActivity->activity_id
= $otherActivityId;
2340 $otherTargetActivity->record_type_id
= $targetID;
2341 $otherTargetActivity->find();
2342 while ($otherTargetActivity->fetch()) {
2343 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2344 $mainActivityTarget->record_type_id
= $targetID;
2345 $mainActivityTarget->activity_id
= $mainActivityId;
2346 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2347 if ($mainActivityTarget->contact_id
== $otherContactId) {
2348 $mainActivityTarget->contact_id
= $mainContactId;
2350 //avoid duplicate object.
2351 if (!$mainActivityTarget->find(TRUE)) {
2352 $mainActivityTarget->save();
2354 $mainActivityTarget->free();
2356 $otherTargetActivity->free();
2358 //migrate assignee activities.
2359 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2360 $otherAssigneeActivity->activity_id
= $otherActivityId;
2361 $otherAssigneeActivity->record_type_id
= $assigneeID;
2362 $otherAssigneeActivity->find();
2363 while ($otherAssigneeActivity->fetch()) {
2364 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2365 $mainAssigneeActivity->activity_id
= $mainActivityId;
2366 $mainAssigneeActivity->record_type_id
= $assigneeID;
2367 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2368 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2369 $mainAssigneeActivity->contact_id
= $mainContactId;
2371 //avoid duplicate object.
2372 if (!$mainAssigneeActivity->find(TRUE)) {
2373 $mainAssigneeActivity->save();
2375 $mainAssigneeActivity->free();
2377 $otherAssigneeActivity->free();
2379 // copy custom fields and attachments
2381 'activityID' => $otherActivityId,
2382 'mainActivityId' => $mainActivityId,
2384 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2387 //copy case relationship.
2388 if ($duplicateContacts) {
2389 //migrate relationship records.
2390 $otherRelationship = new CRM_Contact_DAO_Relationship();
2391 $otherRelationship->case_id
= $otherCaseId;
2392 $otherRelationship->find();
2393 $otherRelationshipIds = array();
2394 while ($otherRelationship->fetch()) {
2395 $otherRelVals = array();
2396 $updateOtherRel = FALSE;
2397 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2399 $mainRelationship = new CRM_Contact_DAO_Relationship();
2400 $mainRelationship->copyValues($otherRelVals);
2401 $mainRelationship->id
= NULL;
2402 $mainRelationship->case_id
= $mainCaseId;
2403 if ($mainRelationship->contact_id_a
== $otherContactId) {
2404 $updateOtherRel = TRUE;
2405 $mainRelationship->contact_id_a
= $mainContactId;
2408 //case creator change only when we merge user contact.
2409 if ($mainRelationship->contact_id_b
== $otherContactId) {
2410 //do not change creator for change client.
2411 if (!$changeClient) {
2412 $updateOtherRel = TRUE;
2413 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2416 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2417 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2419 //avoid duplicate object.
2420 if (!$mainRelationship->find(TRUE)) {
2421 $mainRelationship->save();
2423 $mainRelationship->free();
2425 //get the other relationship ids to update end date.
2426 if ($updateOtherRel) {
2427 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2430 $otherRelationship->free();
2432 //update other relationships end dates
2433 if (!empty($otherRelationshipIds)) {
2434 $sql = 'UPDATE civicrm_relationship
2435 SET end_date = CURDATE()
2436 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2437 CRM_Core_DAO
::executeQuery($sql);
2441 //move other case to trash.
2442 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2447 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2448 if ($changeClient) {
2449 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2450 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2452 $mergeActType = array_search('Reassigned Case', $activityTypes);
2453 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2456 2 => $otherContactDisplayName,
2457 3 => $mainContactDisplayName,
2462 elseif ($duplicateContacts) {
2463 $mergeActType = array_search('Merge Case', $activityTypes);
2464 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2467 2 => $otherContactId,
2468 3 => $mainContactId,
2474 $mergeActType = array_search('Merge Case', $activityTypes);
2475 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2476 if (!empty($copiedActivityIds)) {
2478 SELECT id, subject, activity_date_time, activity_type_id
2479 FROM civicrm_activity
2480 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2481 $dao = CRM_Core_DAO
::executeQuery($sql);
2482 while ($dao->fetch()) {
2483 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2484 if ($dao->subject
) {
2485 $mergeActSubjectDetails .= " :: {$dao->subject}";
2487 $mergeActSubjectDetails .= "<br />";
2492 //Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2493 $activityParams = array(
2494 'subject' => $mergeActSubject,
2495 'details' => $mergeActSubjectDetails,
2496 'status_id' => array_search('Completed', $activityStatuses),
2497 'activity_type_id' => $mergeActType,
2498 'source_contact_id' => $currentUserId,
2499 'activity_date_time' => date('YmdHis'),
2502 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2503 $mergeActivityId = $mergeActivity->id
;
2504 if (!$mergeActivityId) {
2507 $mergeActivity->free();
2509 //connect merge activity to case.
2510 $mergeCaseAct = array(
2511 'case_id' => $mainCaseId,
2512 'activity_id' => $mergeActivityId,
2515 self
::processCaseActivity($mergeCaseAct);
2518 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2520 return $mainCaseIds;
2524 * Validate contact permission for
2525 * edit/view on activity record and build links.
2527 * @param array $tplParams
2528 * Params to be sent to template for sending email.
2529 * @param array $activityParams
2530 * Info of the activity.
2532 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2533 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2534 'activity_type_id', 'id'
2537 if (!empty($tplParams['isCaseActivity'])) {
2538 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2539 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2542 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2543 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2546 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2547 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2551 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2552 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2555 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2556 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2562 * Validate contact permission for
2563 * given operation on activity record.
2565 * @param int $activityId
2566 * Activity record id.
2567 * @param string $operation
2569 * @param int $actTypeId
2571 * @param int $contactId
2572 * Contact id/if not pass consider logged in.
2573 * @param bool $checkComponent
2574 * Do we need to check component enabled.
2578 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2580 if (!$actTypeId && $activityId) {
2581 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2584 if (!$activityId ||
!$operation ||
!$actTypeId) {
2588 //do check for civicase component enabled.
2589 if ($checkComponent && !self
::enabled()) {
2593 //do check for cases.
2594 $caseActOperations = array(
2601 if (in_array($operation, $caseActOperations)) {
2603 if (!isset($caseCount)) {
2605 $caseCount = civicrm_api3('Case', 'getcount', array(
2606 'check_permissions' => TRUE,
2607 'status_id' => array('!=' => 'Closed'),
2609 'end_date' => array('IS NULL' => 1),
2612 catch (CiviCRM_API3_Exception
$e) {
2613 // Lack of permissions will throw an exception
2617 if ($operation == 'File On Case') {
2618 $allow = !empty($caseCount);
2621 $allow = ($caseCount > 1);
2625 $actionOperations = array('view', 'edit', 'delete');
2626 if (in_array($operation, $actionOperations)) {
2628 //do cache when user has non/supper permission.
2629 static $allowOperations;
2631 if (!is_array($allowOperations) ||
2632 !array_key_exists($operation, $allowOperations)
2636 $session = CRM_Core_Session
::singleton();
2637 $contactId = $session->get('userID');
2640 //check for permissions.
2641 $permissions = array(
2643 'access my cases and activities',
2644 'access all cases and activities',
2647 'access my cases and activities',
2648 'access all cases and activities',
2650 'delete' => array('delete activities'),
2653 //check for core permission.
2654 $hasPermissions = array();
2655 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2656 if (is_array($checkPermissions)) {
2657 foreach ($checkPermissions as $per) {
2658 if (CRM_Core_Permission
::check($per)) {
2659 $hasPermissions[$operation][] = $per;
2665 if (!empty($hasPermissions)) {
2666 //need to check activity object specific.
2667 if (in_array($operation, array(
2672 //do we have supper permission.
2673 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2674 $allowOperations[$operation] = $allow = TRUE;
2677 //user has only access to my cases and activity.
2678 //here object specific permmions come in picture.
2680 //edit - contact must be source or assignee
2681 //view - contact must be source/assignee/target
2682 $isTarget = $isAssignee = $isSource = FALSE;
2683 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2684 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2685 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2686 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2688 $target = new CRM_Activity_DAO_ActivityContact();
2689 $target->record_type_id
= $targetID;
2690 $target->activity_id
= $activityId;
2691 $target->contact_id
= $contactId;
2692 if ($target->find(TRUE)) {
2696 $assignee = new CRM_Activity_DAO_ActivityContact();
2697 $assignee->activity_id
= $activityId;
2698 $assignee->record_type_id
= $assigneeID;
2699 $assignee->contact_id
= $contactId;
2700 if ($assignee->find(TRUE)) {
2704 $source = new CRM_Activity_DAO_ActivityContact();
2705 $source->activity_id
= $activityId;
2706 $source->record_type_id
= $sourceID;
2707 $source->contact_id
= $contactId;
2708 if ($source->find(TRUE)) {
2712 if ($operation == 'edit') {
2713 if ($isAssignee ||
$isSource) {
2717 if ($operation == 'view') {
2718 if ($isTarget ||
$isAssignee ||
$isSource) {
2724 elseif (is_array($hasPermissions[$operation])) {
2725 $allowOperations[$operation] = $allow = TRUE;
2729 //contact do not have permission.
2730 $allowOperations[$operation] = FALSE;
2735 //here contact might have supper/non permission.
2736 $allow = $allowOperations[$operation];
2740 //do further only when operation is granted.
2742 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2744 //get the activity type name.
2745 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2747 //do not allow multiple copy / edit action.
2748 $singletonNames = array(
2758 //do not allow to delete these activities, CRM-4543
2759 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2761 //allow edit operation.
2762 $allowEditNames = array('Open Case');
2764 if (CRM_Core_Permission
::check('edit inbound email basic information') ||
2765 CRM_Core_Permission
::check('edit inbound email basic information and content')
2767 $allowEditNames[] = 'Inbound Email';
2770 // do not allow File on Case
2771 $doNotFileNames = array(
2774 'Change Case Status',
2775 'Change Case Start Date',
2782 if (in_array($actTypeName, $singletonNames)) {
2784 if ($operation == 'File On Case') {
2785 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2787 if (in_array($operation, $actionOperations)) {
2789 if ($operation == 'edit') {
2790 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2792 elseif ($operation == 'delete') {
2793 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2797 if ($allow && ($operation == 'delete') &&
2798 in_array($actTypeName, $doNotDeleteNames)
2803 if ($allow && ($operation == 'File On Case') &&
2804 in_array($actTypeName, $doNotFileNames)
2809 //check settings file for masking actions
2810 //on the basis the activity types
2811 //hide Edit link if activity type is NOT editable
2812 //(special case activities).CRM-5871
2813 if ($allow && in_array($operation, $actionOperations)) {
2814 static $actionFilter = array();
2815 if (!array_key_exists($operation, $actionFilter)) {
2816 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2817 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2819 if (array_key_exists($operation, $actionFilter[$operation]) &&
2820 in_array($actTypeId, $actionFilter[$operation][$operation])
2831 * Since we drop 'access CiviCase', allow access
2832 * if user has 'access my cases and activities'
2833 * or 'access all cases and activities'
2835 public static function accessCiviCase() {
2836 if (!self
::enabled()) {
2840 if (CRM_Core_Permission
::check('access my cases and activities') ||
2841 CRM_Core_Permission
::check('access all cases and activities')
2850 * Verify user has permission to access a case.
2852 * @param int $caseId
2853 * @param bool $denyClosed
2854 * Set TRUE if one wants closed cases to be treated as inaccessible.
2858 public static function accessCase($caseId, $denyClosed = TRUE) {
2859 if (!$caseId ||
!self
::enabled()) {
2863 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2864 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2865 $params['status_id'] = array('!=' => 'Closed');
2868 return (bool) civicrm_api3('Case', 'getcount', $params);
2870 catch (CiviCRM_API3_Exception
$e) {
2871 // Lack of permissions will throw an exception
2877 * Check whether activity is a case Activity.
2879 * @param int $activityID
2884 public static function isCaseActivity($activityID) {
2885 $isCaseActivity = FALSE;
2887 $params = array(1 => array($activityID, 'Integer'));
2888 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2889 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2890 $isCaseActivity = TRUE;
2894 return $isCaseActivity;
2898 * Get all the case type ids currently in use.
2902 public static function getUsedCaseType() {
2903 static $caseTypeIds;
2905 if (!is_array($caseTypeIds)) {
2906 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2908 $dao = CRM_Core_DAO
::executeQuery($query);
2909 $caseTypeIds = array();
2910 while ($dao->fetch()) {
2911 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2914 $caseTypeIds[] = $typeId[1];
2918 return $caseTypeIds;
2922 * Get all the case status ids currently in use.
2926 public static function getUsedCaseStatuses() {
2927 static $caseStatusIds;
2929 if (!is_array($caseStatusIds)) {
2930 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2932 $dao = CRM_Core_DAO
::executeQuery($query);
2933 $caseStatusIds = array();
2934 while ($dao->fetch()) {
2935 $caseStatusIds[] = $dao->status_id
;
2939 return $caseStatusIds;
2943 * Get all the encounter medium ids currently in use.
2947 public static function getUsedEncounterMediums() {
2950 if (!is_array($mediumIds)) {
2951 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2953 $dao = CRM_Core_DAO
::executeQuery($query);
2954 $mediumIds = array();
2955 while ($dao->fetch()) {
2956 $mediumIds[] = $dao->medium_id
;
2964 * Check case configuration.
2966 * @param int $contactId
2970 public static function isCaseConfigured($contactId = NULL) {
2971 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2973 //lets check for case configured.
2974 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2975 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2976 if (!$configured['configured']) {
2977 //do check for case type and case status.
2978 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2979 if (!empty($caseTypes)) {
2980 $configured['configured'] = TRUE;
2981 if (!$configured['configured']) {
2982 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2983 if (!empty($caseStatuses)) {
2984 $configured['configured'] = TRUE;
2989 if ($configured['configured']) {
2990 //do check for active case type and case status.
2991 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2992 if (!empty($caseTypes)) {
2993 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2994 if (!empty($caseStatuses)) {
2995 $configured['allowToAddNewCase'] = TRUE;
2999 //do we need to redirect user to case admin.
3000 if (!$configured['allowToAddNewCase'] && $contactId) {
3001 //check for current contact case count.
3002 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
3003 //redirect user to case admin page.
3004 if (!$currentContatCasesCount) {
3005 $configured['redirectToCaseAdmin'] = TRUE;
3014 * Used during case component enablement and during ugprade.
3018 public static function createCaseViews() {
3019 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
3020 $dao = new CRM_Core_DAO();
3022 $sql = self
::createCaseViewsQuery('upcoming');
3024 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3028 // Above error doesn't get caught?
3029 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3030 if (is_null($doublecheck)) {
3034 $sql = self
::createCaseViewsQuery('recent');
3036 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3040 // Above error doesn't get caught?
3041 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3042 if (is_null($doublecheck)) {
3050 * Helper function, also used by the upgrade in case of error
3052 * @param string $section
3056 public static function createCaseViewsQuery($section = 'upcoming') {
3058 $scheduled_id = CRM_Core_Pseudoconstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
3061 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3062 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3063 FROM civicrm_case_activity ca
3064 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3065 WHERE a.activity_date_time =
3066 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3067 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3068 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3069 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
3070 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
3074 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3075 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3076 FROM civicrm_case_activity ca
3077 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3078 WHERE a.activity_date_time =
3079 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3080 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3081 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3082 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
3083 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
3090 * Add/copy relationships, when new client is added for a case
3092 * @param int $caseId
3094 * @param int $contactId
3095 * Contact id / new client id.
3097 public static function addCaseRelationships($caseId, $contactId) {
3098 // get the case role / relationships for the case
3099 $caseRelationships = new CRM_Contact_DAO_Relationship();
3100 $caseRelationships->case_id
= $caseId;
3101 $caseRelationships->find();
3102 $relationshipTypes = array();
3104 // make sure we don't add duplicate relationships of same relationship type.
3105 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3107 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3109 // add relationship for new client.
3110 $newRelationship = new CRM_Contact_DAO_Relationship();
3111 $newRelationship->copyValues($values);
3112 $newRelationship->id
= NULL;
3113 $newRelationship->case_id
= $caseId;
3114 $newRelationship->contact_id_a
= $contactId;
3115 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3116 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3118 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3119 if (!$newRelationship->find(TRUE)) {
3120 $newRelationship->save();
3122 $newRelationship->free();
3124 // store relationship type of newly created relationship
3125 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3130 * Get the list of clients for a case.
3132 * @param int $caseId
3135 * associated array with client ids
3137 public static function getCaseClients($caseId) {
3139 $caseContact = new CRM_Case_DAO_CaseContact();
3140 $caseContact->case_id
= $caseId;
3141 $caseContact->orderBy('id');
3142 $caseContact->find();
3144 while ($caseContact->fetch()) {
3145 $clients[] = $caseContact->contact_id
;
3152 * @param int $caseId
3153 * @param string $direction
3155 * @param int $relTypeId
3156 * @throws \CRM_Core_Exception
3157 * @throws \CiviCRM_API3_Exception
3159 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3161 if ($direction !== 'a' && $direction !== 'b') {
3162 throw new CRM_Core_Exception('Invalid relationship direction');
3165 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3166 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3167 $dao = CRM_Core_DAO
::executeQuery($sql, array(
3168 1 => array($caseId, 'Positive'),
3169 2 => array($cid, 'Positive'),
3170 3 => array($relTypeId, 'Positive'),
3172 while ($dao->fetch()) {
3173 civicrm_api3('relationship', 'create', array(
3176 'end_date' => 'now',
3182 * Get options for a given case field.
3183 * @see CRM_Core_DAO::buildOptions
3185 * @param string $fieldName
3186 * @param string $context
3187 * @see CRM_Core_DAO::buildOptionsContext
3188 * @param array $props
3189 * Whatever is known about this dao object.
3191 * @return array|bool
3193 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3194 $className = __CLASS__
;
3196 switch ($fieldName) {
3197 // This field is not part of this object but the api supports it
3199 $className = 'CRM_Activity_BAO_Activity';
3202 // Filter status id by case type id
3204 if (!empty($props['case_type_id'])) {
3205 $idField = is_numeric($props['case_type_id']) ?
'id' : 'name';
3206 $caseType = civicrm_api3('CaseType', 'getsingle', array($idField => $props['case_type_id'], 'return' => 'definition'));
3207 if (!empty($caseType['definition']['statuses'])) {
3208 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
3213 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3219 public function addSelectWhereClause() {
3220 // We always return an array with these keys, even if they are empty,
3221 // because this tells the query builder that we have considered these fields for acls
3224 // Only case admins can view deleted cases
3225 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
array() : array("= 0"),
3227 // Ensure the user has permission to view the case client
3228 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3229 if ($contactClause) {
3230 $contactClause = implode(' AND contact_id ', $contactClause);
3231 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3233 // The api gatekeeper ensures the user has at least "access my cases and activities"
3234 // so if they do not have permission to see all cases we'll assume they can only access their own
3235 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3236 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3237 $clauses['id'][] = "IN (
3238 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 (
3239 (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)
3243 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3248 * CRM-20308: Method to get the contact id to use as from contact for email copy
3249 * 1. Activity Added by Contact's email address
3250 * 2. System Default From Address
3251 * 3. Default Organization Contact email address
3254 * @param int $activityID
3256 * @return mixed $emailFromContactId
3257 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3259 public static function getReceiptFrom($activityID) {
3260 $name = $address = NULL;
3262 if (!empty($activityID) && (Civi
::settings()->get('allow_mail_from_logged_in_contact'))) {
3263 // This breaks SPF/DMARC if email is sent from an email address that the server is not authorised to send from.
3264 // so we can disable this behaviour with the "allow_mail_from_logged_in_contact" setting.
3265 // There is always a 'Added by' contact for a activity,
3266 // so we can safely use ActivityContact.Getvalue API
3267 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', array(
3268 'activity_id' => $activityID,
3269 'record_type_id' => 'Activity Source',
3270 'return' => 'contact_id',
3272 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3275 // If 'From' email address not found for Source Activity Contact then
3276 // fetch the email from domain or logged in user.
3277 if (empty($address)) {
3278 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3281 return "$name <$address>";