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
280 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL) {
281 $caseContact = new CRM_Case_DAO_CaseContact();
282 $caseContact->case_id
= $caseId;
283 $caseContact->find();
284 $contactArray = array();
285 // FIXME: Why does this return a 1-based array?
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')),
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
845 * case role / relationships
848 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
850 SELECT rel.id as civicrm_relationship_id,
851 con.sort_name as sort_name,
852 civicrm_email.email as email,
853 civicrm_phone.phone as phone,
854 con.id as civicrm_contact_id,
855 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
856 civicrm_relationship_type.id as relation_type,
857 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
858 FROM civicrm_relationship rel
859 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
860 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))
861 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
862 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
863 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
864 AND rel.is_active = 1 AND con.is_deleted = 0 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
867 1 => array($contactID, 'Positive'),
868 2 => array($caseID, 'Positive'),
871 if ($relationshipID) {
872 $query .= ' AND rel.id = %3 ';
873 $params[3] = array($relationshipID, 'Integer');
875 $dao = CRM_Core_DAO
::executeQuery($query, $params);
878 while ($dao->fetch()) {
879 $rid = $dao->civicrm_relationship_id
;
880 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
881 $values[$rid]['relation'] = $dao->relation
;
882 $values[$rid]['name'] = $dao->sort_name
;
883 $values[$rid]['email'] = $dao->email
;
884 $values[$rid]['phone'] = $dao->phone
;
885 $values[$rid]['relation_type'] = $dao->relation_type
;
886 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
887 $values[$rid]['client_id'] = $contactID;
888 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
896 * Get Case Activities.
900 * @param array $params
902 * @param int $contactID
905 * @param null $context
910 * Array of case activities
913 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
916 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
917 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
918 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
919 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
921 // CRM-5081 - formatting the dates to omit seconds.
922 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
924 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
926 ca.activity_type_id AS type,
927 ca.activity_type_id AS activity_type_id,
928 tcc.sort_name AS target_contact_name,
929 tcc.id AS target_contact_id,
930 scc.sort_name AS source_contact_name,
931 scc.id AS source_contact_id,
932 acc.sort_name AS assignee_contact_name,
933 acc.id AS assignee_contact_id,
935 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
936 ca.activity_date_time,
937 DATE_ADD(NOW(), INTERVAL 1 YEAR)
938 ), '%Y%m%d%H%i00') AS overdue_date,
939 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
940 ca.status_id AS status,
941 ca.subject AS subject,
942 ca.is_deleted AS deleted,
943 ca.priority_id AS priority,
945 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
948 FROM civicrm_case_activity cca
949 INNER JOIN civicrm_activity ca
950 ON ca.id = cca.activity_id
951 INNER JOIN civicrm_activity_contact cas
952 ON cas.activity_id = ca.id
953 AND cas.record_type_id = {$sourceID}
954 INNER JOIN civicrm_contact scc
955 ON scc.id = cas.contact_id
956 LEFT JOIN civicrm_activity_contact caa
957 ON caa.activity_id = ca.id
958 AND caa.record_type_id = {$assigneeID}
959 LEFT JOIN civicrm_contact acc
960 ON acc.id = caa.contact_id
961 LEFT JOIN civicrm_activity_contact cat
962 ON cat.activity_id = ca.id
963 AND cat.record_type_id = {$targetID}
964 LEFT JOIN civicrm_contact tcc
965 ON tcc.id = cat.contact_id
966 INNER JOIN civicrm_option_group cog
967 ON cog.name = 'activity_type'
968 INNER JOIN civicrm_option_value cov
969 ON cov.option_group_id = cog.id
970 AND cov.value = ca.activity_type_id
971 AND cov.is_active = 1
972 LEFT JOIN civicrm_entity_file ef
973 ON ef.entity_table = 'civicrm_activity'
974 AND ef.entity_id = ca.id
975 LEFT OUTER JOIN civicrm_option_group og
976 ON og.name = 'activity_status'
977 LEFT OUTER JOIN civicrm_option_value ov
978 ON ov.option_group_id=og.id
979 AND ov.name = 'Scheduled'";
982 WHERE cca.case_id= %1
983 AND ca.is_current_revision = 1';
985 if (!empty($params['source_contact_id'])) {
987 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
990 if (!empty($params['status_id'])) {
992 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
995 if (!empty($params['activity_deleted'])) {
997 AND ca.is_deleted = 1";
1001 AND ca.is_deleted = 0";
1004 if (!empty($params['activity_type_id'])) {
1006 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
1009 if (!empty($params['activity_date_low'])) {
1010 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
1012 if (!empty($fromActivityDate)) {
1014 AND ca.activity_date_time >= '{$fromActivityDate}'";
1017 if (!empty($params['activity_date_high'])) {
1018 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
1019 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
1021 if (!empty($toActivityDate)) {
1023 AND ca.activity_date_time <= '{$toActivityDate}'";
1027 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
1029 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
1031 // CRM-5081 - added id to act like creation date
1033 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
1036 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
1037 $orderBy = " ORDER BY $sortBy ";
1040 $page = CRM_Utils_Array
::value('page', $params);
1041 $rp = CRM_Utils_Array
::value('rp', $params);
1049 $start = (($page - 1) * $rp);
1050 $limit = " LIMIT $start, $rp";
1052 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
1053 $queryParams = array(1 => array($caseID, 'Integer'));
1055 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
1056 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
1058 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1059 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus();
1061 $url = CRM_Utils_System
::url("civicrm/case/activity",
1062 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1066 if ($context == 'fulltext') {
1067 $contextUrl = "&context={$context}";
1069 $editUrl = "{$url}&action=update{$contextUrl}";
1070 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1071 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1072 $viewTitle = ts('View activity');
1074 $emailActivityTypeIDs = array(
1075 'Email' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email'),
1076 'Inbound Email' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email'),
1079 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1081 $compStatusValues = array_keys(
1082 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::COMPLETED
) +
1083 CRM_Activity_BAO_Activity
::getStatusesByType(CRM_Activity_BAO_Activity
::CANCELLED
)
1086 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=", FALSE, NULL, FALSE);
1087 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1088 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1091 $session = CRM_Core_Session
::singleton();
1092 $userID = $session->get('userID');
1095 $caseActivities = array();
1097 while ($dao->fetch()) {
1098 $caseActivity = array();
1099 $caseActivityId = $dao->id
;
1101 $allowView = self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID);
1102 $allowEdit = self
::checkPermission($caseActivityId, 'edit', $dao->activity_type_id
, $userID);
1103 $allowDelete = self
::checkPermission($caseActivityId, 'delete', $dao->activity_type_id
, $userID);
1105 //do not have sufficient permission
1106 //to access given case activity record.
1107 if (!$allowView && !$allowEdit && !$allowDelete) {
1111 $caseActivity['DT_RowId'] = $caseActivityId;
1112 //Add classes to the row, via DataTables syntax
1113 $caseActivity['DT_RowClass'] = "crm-entity status-id-$dao->status";
1115 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1116 $caseActivity['DT_RowClass'] .= " status-completed";
1119 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1120 $caseActivity['DT_RowClass'] .= " status-overdue";
1123 $caseActivity['DT_RowClass'] .= " status-scheduled";
1127 if (!empty($dao->priority
)) {
1128 if ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Urgent')) {
1129 $caseActivity['DT_RowClass'] .= " priority-urgent ";
1131 elseif ($dao->priority
== CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'priority_id', 'Low')) {
1132 $caseActivity['DT_RowClass'] .= " priority-low ";
1136 //Add data to the row for inline editing, via DataTable syntax
1137 $caseActivity['DT_RowAttr'] = array();
1138 $caseActivity['DT_RowAttr']['data-entity'] = 'activity';
1139 $caseActivity['DT_RowAttr']['data-id'] = $caseActivityId;
1141 //Activity Date and Time
1142 $caseActivity['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1145 $caseActivity['subject'] = $dao->subject
;
1148 $caseActivity['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1149 . $activityTypes[$dao->type
]['label'];
1151 //Activity Target (With)
1152 $targetContact = '';
1153 if (isset($dao->target_contact_id
)) {
1154 $targetContact = $dao->target_contact_name
;
1155 if ($hasViewContact) {
1156 $targetContact = '<a href="' . $contactViewUrl . $dao->target_contact_id
. '">' . $dao->target_contact_name
. '</a>';
1159 $caseActivity['target_contact_name'] = $targetContact;
1161 //Activity Source Contact (Reporter)
1162 $sourceContact = $dao->source_contact_name
;
1163 if ($hasViewContact) {
1164 $sourceContact = '<a href="' . $contactViewUrl . $dao->source_contact_id
. '">' . $dao->source_contact_name
. '</a>';
1166 $caseActivity['source_contact_name'] = $sourceContact;
1168 //Activity Assignee. CRM-4485.
1169 $assigneeContact = '';
1170 if (isset($dao->assignee_contact_id
)) {
1171 $assigneeContact = $dao->assignee_contact_name
;
1172 if ($hasViewContact) {
1173 $assigneeContact = '<a href="' . $contactViewUrl . $dao->assignee_contact_id
. '">' . $dao->assignee_contact_name
. '</a>';
1176 $caseActivity['assignee_contact_name'] = $assigneeContact;
1179 $caseActivity['status_id'] = $activityStatuses[$dao->status
];
1181 // 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.
1183 $css = 'class="action-item crm-hover-button"';
1185 $viewUrl = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1186 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1188 $additionalUrl = "&id={$caseActivityId}";
1189 if (!$dao->deleted
) {
1190 //hide edit link of activity type email.CRM-4530.
1191 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1192 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1194 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1198 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1201 elseif (!$caseDeleted) {
1202 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1203 $caseActivity['status_id'] = $caseActivity['status_id'] . '<br /> (deleted)';
1206 //check for operations.
1207 if (self
::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id
)) {
1208 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1210 if (self
::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id
)) {
1211 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1213 // if there are file attachments we will return how many and, if only one, add a link to it
1214 if (!empty($dao->attachment_ids
)) {
1215 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1216 $caseActivity['no_attachments'] = count($attachmentIDs);
1217 $url .= implode(' ', CRM_Core_BAO_File
::paperIconAttachment('civicrm_activity', $caseActivityId));
1220 $caseActivity['links'] = $url;
1222 array_push($caseActivities, $caseActivity);
1226 $caseActivitiesDT = array();
1227 $caseActivitiesDT['data'] = $caseActivities;
1228 $caseActivitiesDT['recordsTotal'] = $caseCount;
1229 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1231 return $caseActivitiesDT;
1235 * Get Case Related Contacts.
1237 * @param int $caseID
1239 * @param bool $includeDetails
1240 * If true include details of contacts.
1243 * array of return properties
1246 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1247 $caseRoles = array();
1248 if ($includeDetails) {
1249 $caseInfo = civicrm_api3('Case', 'getsingle', array(
1251 // 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
1252 'return' => array('case_type_id', 'case_type_id.name', 'case_type_id.definition'),
1254 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1255 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1260 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
1261 FROM civicrm_relationship cr
1262 LEFT JOIN civicrm_relationship_type crt
1263 ON crt.id = cr.relationship_type_id
1264 LEFT JOIN civicrm_contact cc
1265 ON cc.id = cr.contact_id_b
1266 LEFT JOIN civicrm_email ce
1267 ON ce.contact_id = cc.id
1268 AND ce.is_primary= 1
1269 LEFT JOIN civicrm_phone cp
1270 ON cp.contact_id = cc.id
1271 AND cp.is_primary= 1
1272 WHERE cr.case_id = %1 AND cr.is_active AND cc.is_deleted <> 1';
1274 $params = array(1 => array($caseID, 'Integer'));
1275 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1277 while ($dao->fetch()) {
1278 if (!$includeDetails) {
1279 $values[$dao->id
] = 1;
1283 'contact_id' => $dao->id
,
1284 'display_name' => $dao->name
,
1285 'sort_name' => $dao->sort_name
,
1286 'relationship_type_id' => $dao->relationship_type_id
,
1287 'role' => $dao->role
,
1288 'email' => $dao->email
,
1289 'phone' => $dao->phone
,
1291 // Add more info about the role (creator, manager)
1292 $role = CRM_Utils_Array
::value($dao->name_b_a
, $caseRoles);
1294 unset($role['name']);
1297 $values[] = $details;
1306 * Send e-mail copy of activity
1308 * @param int $clientId
1309 * @param int $activityId
1311 * @param array $contacts
1312 * Array of related contact.
1314 * @param null $attachments
1315 * @param int $caseId
1317 * @return bool |array
1319 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1324 $tplParams = $activityInfo = array();
1325 //if its a case activity
1327 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1328 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1329 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1330 $anyActivity = TRUE;
1333 $anyActivity = FALSE;
1335 $tplParams['isCaseActivity'] = 1;
1336 $tplParams['client_id'] = $clientId;
1339 $anyActivity = TRUE;
1342 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1343 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1345 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1347 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1349 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1351 $tplParams['activity'] = $activityInfo;
1352 foreach ($tplParams['activity']['fields'] as $k => $val) {
1353 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1354 $activitySubject = $val['value'];
1358 $session = CRM_Core_Session
::singleton();
1359 // CRM-8926 If user is not logged in, use the activity creator as userID
1360 if (!($userID = $session->get('userID'))) {
1361 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1364 //also create activities simultaneously of this copy.
1365 $activityParams = array();
1367 $activityParams['source_record_id'] = $activityId;
1368 $activityParams['source_contact_id'] = $userID;
1369 $activityParams['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', 'Email');
1370 $activityParams['activity_date_time'] = date('YmdHis');
1371 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
1372 $activityParams['medium_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'encounter_medium', 'email');
1373 $activityParams['case_id'] = $caseId;
1374 $activityParams['is_auto'] = 0;
1375 $activityParams['target_id'] = $clientId;
1377 $tplParams['activitySubject'] = $activitySubject;
1379 // if it’s a case activity, add hashed id to the template (CRM-5916)
1381 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1385 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1386 $receiptFrom = self
::getReceiptFrom($activityId);
1388 $recordedActivityParams = array();
1390 foreach ($contacts as $mail => $info) {
1391 $tplParams['contact'] = $info;
1392 self
::buildPermissionLinks($tplParams, $activityParams);
1394 $displayName = CRM_Utils_Array
::value('display_name', $info);
1396 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1398 'groupName' => 'msg_tpl_workflow_case',
1399 'valueName' => 'case_activity',
1400 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1401 'tplParams' => $tplParams,
1402 'from' => $receiptFrom,
1403 'toName' => $displayName,
1405 'attachments' => $attachments,
1409 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1410 $activityParams['details'] = $message;
1412 if (!empty($result[$info['contact_id']])) {
1414 * Really only need to record one activity with all the targets combined.
1415 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1416 * but it's always the same content at the moment.
1418 if (empty($recordedActivityParams)) {
1419 $recordedActivityParams = $activityParams;
1422 $recordedActivityParams['subject'] .= "; $displayName";
1424 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1427 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1431 if (!empty($recordedActivityParams)) {
1432 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1434 //create case_activity record if its case activity.
1436 $caseParams = array(
1437 'activity_id' => $activity->id
,
1438 'case_id' => $caseId,
1440 self
::processCaseActivity($caseParams);
1448 * Retrieve count of activities having a particular type, and
1449 * associated with a particular case.
1451 * @param int $caseId
1453 * @param int $activityTypeId
1454 * ID of the activity type.
1458 public static function getCaseActivityCount($caseId, $activityTypeId) {
1459 $queryParam = array(
1460 1 => array($caseId, 'Integer'),
1461 2 => array($activityTypeId, 'Integer'),
1463 $query = "SELECT count(ca.id) as countact
1464 FROM civicrm_activity ca
1465 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1466 WHERE ca.activity_type_id = %2
1467 AND cca.case_id = %1
1468 AND ca.is_deleted = 0";
1470 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1471 if ($dao->fetch()) {
1472 return $dao->countact
;
1479 * Create an activity for a case via email.
1484 * @return array|void
1485 * $activity object of newly creted activity via email
1487 public static function recordActivityViaEmail($file) {
1488 if (!file_exists($file) ||
1491 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1496 $result = CRM_Utils_Mail_Incoming
::parse($file);
1497 if ($result['is_error']) {
1501 foreach ($result['to'] as $to) {
1504 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1505 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1507 if ($replacement !== $to['email']) {
1508 $caseId = $replacement;
1509 //if caseId is invalid, return as error file
1510 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1511 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1520 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1521 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1522 $contactDetails = self
::getRelatedContacts($caseId, FALSE);
1524 if (!empty($contactDetails[$result['from']['id']])) {
1526 $params['subject'] = $result['subject'];
1527 $params['activity_date_time'] = $result['date'];
1528 $params['details'] = $result['body'];
1529 $params['source_contact_id'] = $result['from']['id'];
1530 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
1532 $details = CRM_Case_PseudoConstant
::caseActivityType();
1534 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1535 $result['body'], $matches
1538 if (!empty($matches) && isset($matches[1])) {
1539 $activityType = trim($matches[1]);
1540 if (isset($details[$activityType])) {
1541 $params['activity_type_id'] = $details[$activityType]['id'];
1544 if (!isset($params['activity_type_id'])) {
1545 $params['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email');
1549 $activity = CRM_Activity_BAO_Activity
::create($params);
1551 $caseParams = array(
1552 'activity_id' => $activity->id
,
1553 'case_id' => $caseId,
1555 self
::processCaseActivity($caseParams);
1558 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1559 array(1 => $result['from']['email'])
1566 * Retrieve the scheduled activity type and date.
1568 * @param array $cases
1569 * Array of contact and case id.
1571 * @param string $type
1574 * Array of scheduled activity type and date
1578 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1579 $session = CRM_Core_Session
::singleton();
1580 $userID = $session->get('userID');
1582 $caseID = implode(',', $cases['case_id']);
1583 $contactID = implode(',', $cases['contact_id']);
1585 $condition = " civicrm_case_contact.contact_id IN( {$contactID} )
1586 AND civicrm_case.id IN( {$caseID})
1587 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1589 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1591 $res = CRM_Core_DAO
::executeQuery($query);
1593 $activityInfo = array();
1594 while ($res->fetch()) {
1595 if ($type == 'upcoming') {
1596 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1597 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1600 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1601 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1605 return $activityInfo;
1609 * Combine all the exportable fields from the lower levels object.
1612 * array of exportable Fields
1614 public static function &exportableFields() {
1615 if (!self
::$_exportableFields) {
1616 if (!self
::$_exportableFields) {
1617 self
::$_exportableFields = array();
1620 $fields = CRM_Case_DAO_Case
::export();
1621 $fields['case_role'] = array('title' => ts('Role in Case'));
1622 $fields['case_type'] = array(
1623 'title' => ts('Case Type'),
1624 'name' => 'case_type',
1626 $fields['case_status'] = array(
1627 'title' => ts('Case Status'),
1628 'name' => 'case_status',
1631 // add custom data for cases
1632 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1634 self
::$_exportableFields = $fields;
1636 return self
::$_exportableFields;
1640 * Restore the record that are associated with this case.
1642 * @param int $caseId
1643 * Id of the case to restore.
1647 public static function restoreCase($caseId) {
1648 //restore activities
1649 $activities = self
::getCaseActivityDates($caseId);
1651 foreach ($activities as $value) {
1652 CRM_Activity_BAO_Activity
::restoreActivity($value);
1656 $case = new CRM_Case_DAO_Case();
1657 $case->id
= $caseId;
1658 $case->is_deleted
= 0;
1661 //CRM-7364, enable relationships
1662 self
::enableDisableCaseRelationships($caseId, TRUE);
1669 * @param null $showLinks
1670 * @param bool $returnOnlyCount
1671 * @param int $offset
1672 * @param int $rowCount
1676 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1677 $globalContacts = array();
1679 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1680 $settings = $settingsProcessor->run();
1681 if (!empty($settings)) {
1682 $groupInfo['name'] = $settings['groupname'];
1683 if ($groupInfo['name']) {
1684 $searchParams = array('name' => $groupInfo['name']);
1686 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1688 $groupInfo['id'] = $results['id'];
1689 $groupInfo['title'] = $results['title'];
1690 $params = array(array('group', '=', $groupInfo['id'], 0, 0));
1691 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1692 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1694 if ($returnOnlyCount) {
1695 return $globalContacts;
1699 foreach ($globalContacts as $idx => $contact) {
1700 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1706 return $globalContacts;
1710 * Convenience function to get both case contacts and global in one array.
1711 * @param int $caseId
1715 public static function getRelatedAndGlobalContacts($caseId) {
1716 $relatedContacts = self
::getRelatedContacts($caseId);
1718 $groupInfo = array();
1719 $globalContacts = self
::getGlobalContacts($groupInfo);
1721 //unset values which are not required.
1722 foreach ($globalContacts as $k => & $v) {
1723 unset($v['email_id']);
1724 unset($v['group_contact_id']);
1725 unset($v['status']);
1727 $v['role'] = $groupInfo['title'];
1729 //include multiple listings for the same contact/different roles.
1730 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1731 return $relatedGlobalContacts;
1735 * Get Case ActivitiesDueDates with given criteria.
1737 * @param int $caseID
1739 * @param array $criteriaParams
1741 * @param bool $latestDate
1742 * If set newest or oldest date is selected.
1745 * case activities due dates
1748 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1750 $selectDate = " ca.activity_date_time";
1751 $where = $groupBy = ' ';
1758 if (!empty($criteriaParams['activity_type_id'])) {
1759 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1760 $where .= " AND ca.is_current_revision = 1";
1761 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1764 if (!empty($criteriaParams['newest'])) {
1765 $selectDate = " max(ca.activity_date_time) ";
1768 $selectDate = " min(ca.activity_date_time) ";
1772 $query = "SELECT ca.id, {$selectDate} as activity_date
1773 FROM civicrm_activity ca
1774 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1775 WHERE cc.id = %1 {$where} {$groupBy}";
1777 $params = array(1 => array($caseID, 'Integer'));
1778 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1780 while ($dao->fetch()) {
1781 $values[$dao->id
]['id'] = $dao->id
;
1782 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1789 * Create activities when Case or Other roles assigned/modified/deleted.
1791 * @param int $caseId
1792 * @param int $relationshipId
1794 * @param int $relContactId
1795 * Case role assignee contactId.
1796 * @param int $contactId
1798 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1799 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1803 $queryParam = array();
1804 if (is_array($relationshipId)) {
1805 $relationshipId = implode(',', $relationshipId);
1806 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1809 $relationshipClause = " civicrm_relationship.id = %1";
1810 $queryParam[1] = array($relationshipId, 'Positive');
1814 SELECT cc.display_name as clientName,
1815 cca.display_name as assigneeContactName,
1816 civicrm_relationship.case_id as caseId,
1817 civicrm_relationship_type.label_a_b as relation_a_b,
1818 civicrm_relationship_type.label_b_a as relation_b_a,
1819 civicrm_relationship.contact_id_b as rel_contact_id,
1820 civicrm_relationship.contact_id_a as assign_contact_id
1821 FROM civicrm_relationship_type, civicrm_relationship
1822 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1823 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1824 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1826 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1828 while ($dao->fetch()) {
1829 // The assignee is not the client.
1830 if ($dao->rel_contact_id
!= $contactId) {
1831 $caseRelationship = $dao->relation_a_b
;
1832 $assigneContactName = $dao->clientName
;
1833 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1836 $caseRelationship = $dao->relation_b_a
;
1837 $assigneContactName = $dao->assigneeContactName
;
1838 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1842 $session = CRM_Core_Session
::singleton();
1843 $activityParams = array(
1844 'source_contact_id' => $session->get('userID'),
1845 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1846 'activity_date_time' => date('YmdHis'),
1847 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1850 //if $relContactId is passed, role is added or modified.
1851 if (!empty($relContactId)) {
1852 $activityParams['assignee_contact_id'] = $assigneContactIds;
1853 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Assign Case Role');
1856 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Remove Case Role');
1859 $activityParams['activity_type_id'] = $activityTypeID;
1861 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1863 //create case_activity record.
1864 $caseParams = array(
1865 'activity_id' => $activity->id
,
1866 'case_id' => $caseId,
1869 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1874 * contact which is assigned a case role of case manager.
1876 * @param int $caseType
1878 * @param int $caseId
1882 * html hyperlink of manager contact view page
1885 public static function getCaseManagerContact($caseType, $caseId) {
1886 if (!$caseType ||
!$caseId) {
1890 $caseManagerName = '---';
1891 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1893 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1895 if (!empty($managerRoleId)) {
1896 $managerRoleQuery = "
1897 SELECT civicrm_contact.id as casemanager_id,
1898 civicrm_contact.sort_name as casemanager
1899 FROM civicrm_contact
1900 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1901 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1902 WHERE civicrm_case.id = %2 AND is_active = 1";
1904 $managerRoleParams = array(
1905 1 => array($managerRoleId, 'Integer'),
1906 2 => array($caseId, 'Integer'),
1909 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1910 if ($dao->fetch()) {
1911 $caseManagerName = sprintf('<a href="%s">%s</a>',
1912 CRM_Utils_System
::url('civicrm/contact/view', array('cid' => $dao->casemanager_id
)),
1918 return $caseManagerName;
1922 * @param int $contactId
1923 * @param bool $excludeDeleted
1927 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1928 $params = array('check_permissions' => TRUE);
1929 if ($excludeDeleted) {
1930 $params['is_deleted'] = 0;
1933 $params['contact_id'] = $contactId;
1936 return civicrm_api3('Case', 'getcount', $params);
1938 catch (CiviCRM_API3_Exception
$e) {
1939 // Lack of permissions will throw an exception
1945 * Retrieve related case ids for given case.
1947 * @param int $caseId
1948 * @param bool $excludeDeleted
1949 * Do not include deleted cases.
1953 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1954 //FIXME : do check for permissions.
1960 $linkActType = array_search('Link Cases',
1961 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
1963 if (!$linkActType) {
1967 $whereClause = "mainCase.id = %2";
1968 if ($excludeDeleted) {
1969 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1973 SELECT relCaseAct.case_id
1974 FROM civicrm_case mainCase
1975 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1976 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1977 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1978 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1979 WHERE $whereClause";
1981 $dao = CRM_Core_DAO
::executeQuery($query, array(
1982 1 => array($linkActType, 'Integer'),
1983 2 => array($caseId, 'Integer'),
1985 $relatedCaseIds = array();
1986 while ($dao->fetch()) {
1987 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1991 return array_values($relatedCaseIds);
1995 * Retrieve related case details for given case.
1997 * @param int $caseId
1998 * @param bool $excludeDeleted
1999 * Do not include deleted cases.
2003 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
2004 $relatedCaseIds = self
::getRelatedCaseIds($caseId, $excludeDeleted);
2005 $relatedCases = array();
2007 if (!$relatedCaseIds) {
2011 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2012 if ($excludeDeleted) {
2013 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2016 //filter for permissioned cases.
2017 $filterCases = array();
2018 $doFilterCases = FALSE;
2019 if (!CRM_Core_Permission
::check('access all cases and activities')) {
2020 $doFilterCases = TRUE;
2021 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE);
2024 //2. fetch the details of related cases.
2026 SELECT relCase.id as id,
2027 civicrm_case_type.title as case_type,
2028 client.display_name as client_name,
2029 client.id as client_id,
2031 FROM civicrm_case relCase
2032 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2033 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2034 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
2035 WHERE {$whereClause}";
2037 $dao = CRM_Core_DAO
::executeQuery($query);
2038 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2039 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2040 $statuses = CRM_Case_BAO_Case
::buildOptions('status_id');
2042 while ($dao->fetch()) {
2044 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2045 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2046 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2047 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2049 $clientView = $dao->client_name
;
2050 if ($hasViewContact) {
2051 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2054 $relatedCases[$dao->id
] = array(
2055 'case_id' => $dao->id
,
2056 'case_type' => $dao->case_type
,
2057 'client_name' => $clientView,
2058 'case_status' => $statuses[$dao->status_id
],
2059 'links' => $caseView,
2064 return $relatedCases;
2068 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2070 * @see CRM_Dedupe_Merger::cpTables()
2072 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2074 * @param int $mainContactId
2075 * @param int $otherContactId
2077 public static function mergeContacts($mainContactId, $otherContactId) {
2078 self
::mergeCases($mainContactId, NULL, $otherContactId);
2082 * Function perform two task.
2083 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2084 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2086 * @param int $mainContactId
2087 * Contact id of main contact record.
2088 * @param int $mainCaseId
2089 * Case id of main case record.
2090 * @param int $otherContactId
2091 * Contact id of record which is going to merge.
2092 * @param int $otherCaseId
2093 * Case id of record which is going to merge.
2095 * @param bool $changeClient
2099 public static function mergeCases(
2100 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2101 $otherCaseId = NULL, $changeClient = FALSE) {
2102 $moveToTrash = TRUE;
2104 $duplicateContacts = FALSE;
2105 if ($mainContactId && $otherContactId &&
2106 $mainContactId != $otherContactId
2108 $duplicateContacts = TRUE;
2111 $duplicateCases = FALSE;
2112 if ($mainCaseId && $otherCaseId &&
2113 $mainCaseId != $otherCaseId
2115 $duplicateCases = TRUE;
2118 $mainCaseIds = array();
2119 if (!$duplicateContacts && !$duplicateCases) {
2120 return $mainCaseIds;
2123 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2124 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2125 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2126 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2127 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2128 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2130 $processCaseIds = array($otherCaseId);
2131 if ($duplicateContacts && !$duplicateCases) {
2132 if ($changeClient) {
2133 $processCaseIds = array($mainCaseId);
2136 //get all case ids for other contact.
2137 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2139 if (!is_array($processCaseIds)) {
2144 $session = CRM_Core_Session
::singleton();
2145 $currentUserId = $session->get('userID');
2147 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2149 // copy all cases and connect to main contact id.
2150 foreach ($processCaseIds as $otherCaseId) {
2151 if ($duplicateContacts) {
2152 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2153 $mainCaseId = $mainCase->id
;
2158 // CRM-11662 Copy Case custom data
2159 $extends = array('case');
2160 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2162 foreach ($groupTree as $groupID => $group) {
2163 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2164 foreach ($group['fields'] as $fieldID => $field) {
2165 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2169 foreach ($table as $tableName => $tableColumns) {
2170 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2171 $tableColumns[0] = $mainCaseId;
2172 $select = 'SELECT ' . implode(', ', $tableColumns);
2173 $from = ' FROM ' . $tableName;
2174 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2175 $query = $insert . $select . $from . $where;
2176 $dao = CRM_Core_DAO
::executeQuery($query);
2182 $mainCaseIds[] = $mainCaseId;
2183 //insert record for case contact.
2184 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2185 $otherCaseContact->case_id
= $otherCaseId;
2186 $otherCaseContact->find();
2187 while ($otherCaseContact->fetch()) {
2188 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2189 $mainCaseContact->case_id
= $mainCaseId;
2190 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2191 if ($mainCaseContact->contact_id
== $otherContactId) {
2192 $mainCaseContact->contact_id
= $mainContactId;
2194 //avoid duplicate object.
2195 if (!$mainCaseContact->find(TRUE)) {
2196 $mainCaseContact->save();
2198 $mainCaseContact->free();
2200 $otherCaseContact->free();
2202 elseif (!$otherContactId) {
2203 $otherContactId = $mainContactId;
2206 if (!$mainCaseId ||
!$otherCaseId ||
2207 !$mainContactId ||
!$otherContactId
2212 // get all activities for other case.
2213 $otherCaseActivities = array();
2214 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2216 //for duplicate cases do not process singleton activities.
2217 $otherActivityIds = $singletonActivityIds = array();
2218 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2219 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2220 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2223 $otherActivityIds[] = $otherActId;
2225 if ($duplicateCases) {
2226 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2229 FROM civicrm_activity
2230 WHERE activity_type_id = $openCaseType
2231 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2232 $dao = CRM_Core_DAO
::executeQuery($sql);
2233 while ($dao->fetch()) {
2234 $singletonActivityIds[] = $dao->id
;
2240 // migrate all activities and connect to main contact.
2241 $copiedActivityIds = $activityMappingIds = array();
2242 sort($otherActivityIds);
2243 foreach ($otherActivityIds as $otherActivityId) {
2245 //for duplicate cases -
2246 //do not migrate singleton activities.
2247 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2251 //migrate activity record.
2252 $otherActivity = new CRM_Activity_DAO_Activity();
2253 $otherActivity->id
= $otherActivityId;
2254 if (!$otherActivity->find(TRUE)) {
2258 $mainActVals = array();
2259 $mainActivity = new CRM_Activity_DAO_Activity();
2260 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2261 $mainActivity->copyValues($mainActVals);
2262 $mainActivity->id
= NULL;
2263 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2264 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2268 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2272 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2275 $mainActivity->save();
2276 $mainActivityId = $mainActivity->id
;
2277 if (!$mainActivityId) {
2281 $activityMappingIds[$otherActivityId] = $mainActivityId;
2282 // insert log of all activities
2283 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2285 $otherActivity->free();
2286 $mainActivity->free();
2287 $copiedActivityIds[] = $otherActivityId;
2289 //create case activity record.
2290 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2291 $mainCaseActivity->case_id
= $mainCaseId;
2292 $mainCaseActivity->activity_id
= $mainActivityId;
2293 $mainCaseActivity->save();
2294 $mainCaseActivity->free();
2296 //migrate source activity.
2297 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2298 $otherSourceActivity->activity_id
= $otherActivityId;
2299 $otherSourceActivity->record_type_id
= $sourceID;
2300 $otherSourceActivity->find();
2301 while ($otherSourceActivity->fetch()) {
2302 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2303 $mainActivitySource->record_type_id
= $sourceID;
2304 $mainActivitySource->activity_id
= $mainActivityId;
2305 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2306 if ($mainActivitySource->contact_id
== $otherContactId) {
2307 $mainActivitySource->contact_id
= $mainContactId;
2309 //avoid duplicate object.
2310 if (!$mainActivitySource->find(TRUE)) {
2311 $mainActivitySource->save();
2313 $mainActivitySource->free();
2315 $otherSourceActivity->free();
2317 //migrate target activities.
2318 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2319 $otherTargetActivity->activity_id
= $otherActivityId;
2320 $otherTargetActivity->record_type_id
= $targetID;
2321 $otherTargetActivity->find();
2322 while ($otherTargetActivity->fetch()) {
2323 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2324 $mainActivityTarget->record_type_id
= $targetID;
2325 $mainActivityTarget->activity_id
= $mainActivityId;
2326 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2327 if ($mainActivityTarget->contact_id
== $otherContactId) {
2328 $mainActivityTarget->contact_id
= $mainContactId;
2330 //avoid duplicate object.
2331 if (!$mainActivityTarget->find(TRUE)) {
2332 $mainActivityTarget->save();
2334 $mainActivityTarget->free();
2336 $otherTargetActivity->free();
2338 //migrate assignee activities.
2339 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2340 $otherAssigneeActivity->activity_id
= $otherActivityId;
2341 $otherAssigneeActivity->record_type_id
= $assigneeID;
2342 $otherAssigneeActivity->find();
2343 while ($otherAssigneeActivity->fetch()) {
2344 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2345 $mainAssigneeActivity->activity_id
= $mainActivityId;
2346 $mainAssigneeActivity->record_type_id
= $assigneeID;
2347 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2348 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2349 $mainAssigneeActivity->contact_id
= $mainContactId;
2351 //avoid duplicate object.
2352 if (!$mainAssigneeActivity->find(TRUE)) {
2353 $mainAssigneeActivity->save();
2355 $mainAssigneeActivity->free();
2357 $otherAssigneeActivity->free();
2359 // copy custom fields and attachments
2361 'activityID' => $otherActivityId,
2362 'mainActivityId' => $mainActivityId,
2364 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2367 //copy case relationship.
2368 if ($duplicateContacts) {
2369 //migrate relationship records.
2370 $otherRelationship = new CRM_Contact_DAO_Relationship();
2371 $otherRelationship->case_id
= $otherCaseId;
2372 $otherRelationship->find();
2373 $otherRelationshipIds = array();
2374 while ($otherRelationship->fetch()) {
2375 $otherRelVals = array();
2376 $updateOtherRel = FALSE;
2377 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2379 $mainRelationship = new CRM_Contact_DAO_Relationship();
2380 $mainRelationship->copyValues($otherRelVals);
2381 $mainRelationship->id
= NULL;
2382 $mainRelationship->case_id
= $mainCaseId;
2383 if ($mainRelationship->contact_id_a
== $otherContactId) {
2384 $updateOtherRel = TRUE;
2385 $mainRelationship->contact_id_a
= $mainContactId;
2388 //case creator change only when we merge user contact.
2389 if ($mainRelationship->contact_id_b
== $otherContactId) {
2390 //do not change creator for change client.
2391 if (!$changeClient) {
2392 $updateOtherRel = TRUE;
2393 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2396 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2397 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2399 //avoid duplicate object.
2400 if (!$mainRelationship->find(TRUE)) {
2401 $mainRelationship->save();
2403 $mainRelationship->free();
2405 //get the other relationship ids to update end date.
2406 if ($updateOtherRel) {
2407 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2410 $otherRelationship->free();
2412 //update other relationships end dates
2413 if (!empty($otherRelationshipIds)) {
2414 $sql = 'UPDATE civicrm_relationship
2415 SET end_date = CURDATE()
2416 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2417 CRM_Core_DAO
::executeQuery($sql);
2421 //move other case to trash.
2422 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2427 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2428 if ($changeClient) {
2429 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2430 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2432 $mergeActType = array_search('Reassigned Case', $activityTypes);
2433 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2436 2 => $otherContactDisplayName,
2437 3 => $mainContactDisplayName,
2442 elseif ($duplicateContacts) {
2443 $mergeActType = array_search('Merge Case', $activityTypes);
2444 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2447 2 => $otherContactId,
2448 3 => $mainContactId,
2454 $mergeActType = array_search('Merge Case', $activityTypes);
2455 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2456 if (!empty($copiedActivityIds)) {
2458 SELECT id, subject, activity_date_time, activity_type_id
2459 FROM civicrm_activity
2460 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2461 $dao = CRM_Core_DAO
::executeQuery($sql);
2462 while ($dao->fetch()) {
2463 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2464 if ($dao->subject
) {
2465 $mergeActSubjectDetails .= " :: {$dao->subject}";
2467 $mergeActSubjectDetails .= "<br />";
2472 //Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2473 $activityParams = array(
2474 'subject' => $mergeActSubject,
2475 'details' => $mergeActSubjectDetails,
2476 'status_id' => array_search('Completed', $activityStatuses),
2477 'activity_type_id' => $mergeActType,
2478 'source_contact_id' => $currentUserId,
2479 'activity_date_time' => date('YmdHis'),
2482 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2483 $mergeActivityId = $mergeActivity->id
;
2484 if (!$mergeActivityId) {
2487 $mergeActivity->free();
2489 //connect merge activity to case.
2490 $mergeCaseAct = array(
2491 'case_id' => $mainCaseId,
2492 'activity_id' => $mergeActivityId,
2495 self
::processCaseActivity($mergeCaseAct);
2498 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2500 return $mainCaseIds;
2504 * Validate contact permission for
2505 * edit/view on activity record and build links.
2507 * @param array $tplParams
2508 * Params to be sent to template for sending email.
2509 * @param array $activityParams
2510 * Info of the activity.
2512 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2513 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2514 'activity_type_id', 'id'
2517 if (!empty($tplParams['isCaseActivity'])) {
2518 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2519 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2522 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2523 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2526 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2527 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2531 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2532 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2535 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2536 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2542 * Validate contact permission for
2543 * given operation on activity record.
2545 * @param int $activityId
2546 * Activity record id.
2547 * @param string $operation
2549 * @param int $actTypeId
2551 * @param int $contactId
2552 * Contact id/if not pass consider logged in.
2553 * @param bool $checkComponent
2554 * Do we need to check component enabled.
2558 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2560 if (!$actTypeId && $activityId) {
2561 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2564 if (!$activityId ||
!$operation ||
!$actTypeId) {
2568 //do check for civicase component enabled.
2569 if ($checkComponent && !self
::enabled()) {
2573 //do check for cases.
2574 $caseActOperations = array(
2581 if (in_array($operation, $caseActOperations)) {
2583 if (!isset($caseCount)) {
2585 $caseCount = civicrm_api3('Case', 'getcount', array(
2586 'check_permissions' => TRUE,
2587 'status_id' => array('!=' => 'Closed'),
2589 'end_date' => array('IS NULL' => 1),
2592 catch (CiviCRM_API3_Exception
$e) {
2593 // Lack of permissions will throw an exception
2597 if ($operation == 'File On Case') {
2598 $allow = !empty($caseCount);
2601 $allow = ($caseCount > 1);
2605 $actionOperations = array('view', 'edit', 'delete');
2606 if (in_array($operation, $actionOperations)) {
2608 //do cache when user has non/supper permission.
2609 static $allowOperations;
2611 if (!is_array($allowOperations) ||
2612 !array_key_exists($operation, $allowOperations)
2616 $session = CRM_Core_Session
::singleton();
2617 $contactId = $session->get('userID');
2620 //check for permissions.
2621 $permissions = array(
2623 'access my cases and activities',
2624 'access all cases and activities',
2627 'access my cases and activities',
2628 'access all cases and activities',
2630 'delete' => array('delete activities'),
2633 //check for core permission.
2634 $hasPermissions = array();
2635 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2636 if (is_array($checkPermissions)) {
2637 foreach ($checkPermissions as $per) {
2638 if (CRM_Core_Permission
::check($per)) {
2639 $hasPermissions[$operation][] = $per;
2645 if (!empty($hasPermissions)) {
2646 //need to check activity object specific.
2647 if (in_array($operation, array(
2652 //do we have supper permission.
2653 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2654 $allowOperations[$operation] = $allow = TRUE;
2657 //user has only access to my cases and activity.
2658 //here object specific permmions come in picture.
2660 //edit - contact must be source or assignee
2661 //view - contact must be source/assignee/target
2662 $isTarget = $isAssignee = $isSource = FALSE;
2663 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2664 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2665 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2666 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2668 $target = new CRM_Activity_DAO_ActivityContact();
2669 $target->record_type_id
= $targetID;
2670 $target->activity_id
= $activityId;
2671 $target->contact_id
= $contactId;
2672 if ($target->find(TRUE)) {
2676 $assignee = new CRM_Activity_DAO_ActivityContact();
2677 $assignee->activity_id
= $activityId;
2678 $assignee->record_type_id
= $assigneeID;
2679 $assignee->contact_id
= $contactId;
2680 if ($assignee->find(TRUE)) {
2684 $source = new CRM_Activity_DAO_ActivityContact();
2685 $source->activity_id
= $activityId;
2686 $source->record_type_id
= $sourceID;
2687 $source->contact_id
= $contactId;
2688 if ($source->find(TRUE)) {
2692 if ($operation == 'edit') {
2693 if ($isAssignee ||
$isSource) {
2697 if ($operation == 'view') {
2698 if ($isTarget ||
$isAssignee ||
$isSource) {
2704 elseif (is_array($hasPermissions[$operation])) {
2705 $allowOperations[$operation] = $allow = TRUE;
2709 //contact do not have permission.
2710 $allowOperations[$operation] = FALSE;
2715 //here contact might have supper/non permission.
2716 $allow = $allowOperations[$operation];
2720 //do further only when operation is granted.
2722 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2724 //get the activity type name.
2725 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2727 //do not allow multiple copy / edit action.
2728 $singletonNames = array(
2738 //do not allow to delete these activities, CRM-4543
2739 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2741 //allow edit operation.
2742 $allowEditNames = array('Open Case');
2744 // do not allow File on Case
2745 $doNotFileNames = array(
2748 'Change Case Status',
2749 'Change Case Start Date',
2756 if (in_array($actTypeName, $singletonNames)) {
2758 if ($operation == 'File On Case') {
2759 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2761 if (in_array($operation, $actionOperations)) {
2763 if ($operation == 'edit') {
2764 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2766 elseif ($operation == 'delete') {
2767 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2771 if ($allow && ($operation == 'delete') &&
2772 in_array($actTypeName, $doNotDeleteNames)
2777 if ($allow && ($operation == 'File On Case') &&
2778 in_array($actTypeName, $doNotFileNames)
2783 //check settings file for masking actions
2784 //on the basis the activity types
2785 //hide Edit link if activity type is NOT editable
2786 //(special case activities).CRM-5871
2787 if ($allow && in_array($operation, $actionOperations)) {
2788 static $actionFilter = array();
2789 if (!array_key_exists($operation, $actionFilter)) {
2790 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2791 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2793 if (array_key_exists($operation, $actionFilter[$operation]) &&
2794 in_array($actTypeId, $actionFilter[$operation][$operation])
2805 * Since we drop 'access CiviCase', allow access
2806 * if user has 'access my cases and activities'
2807 * or 'access all cases and activities'
2809 public static function accessCiviCase() {
2810 if (!self
::enabled()) {
2814 if (CRM_Core_Permission
::check('access my cases and activities') ||
2815 CRM_Core_Permission
::check('access all cases and activities')
2824 * Verify user has permission to access a case.
2826 * @param int $caseId
2827 * @param bool $denyClosed
2828 * Set TRUE if one wants closed cases to be treated as inaccessible.
2832 public static function accessCase($caseId, $denyClosed = TRUE) {
2833 if (!$caseId ||
!self
::enabled()) {
2837 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2838 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2839 $params['status_id'] = array('!=' => 'Closed');
2842 return (bool) civicrm_api3('Case', 'getcount', $params);
2844 catch (CiviCRM_API3_Exception
$e) {
2845 // Lack of permissions will throw an exception
2851 * Check whether activity is a case Activity.
2853 * @param int $activityID
2858 public static function isCaseActivity($activityID) {
2859 $isCaseActivity = FALSE;
2861 $params = array(1 => array($activityID, 'Integer'));
2862 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2863 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2864 $isCaseActivity = TRUE;
2868 return $isCaseActivity;
2872 * Get all the case type ids currently in use.
2876 public static function getUsedCaseType() {
2877 static $caseTypeIds;
2879 if (!is_array($caseTypeIds)) {
2880 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2882 $dao = CRM_Core_DAO
::executeQuery($query);
2883 $caseTypeIds = array();
2884 while ($dao->fetch()) {
2885 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2888 $caseTypeIds[] = $typeId[1];
2892 return $caseTypeIds;
2896 * Get all the case status ids currently in use.
2900 public static function getUsedCaseStatuses() {
2901 static $caseStatusIds;
2903 if (!is_array($caseStatusIds)) {
2904 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2906 $dao = CRM_Core_DAO
::executeQuery($query);
2907 $caseStatusIds = array();
2908 while ($dao->fetch()) {
2909 $caseStatusIds[] = $dao->status_id
;
2913 return $caseStatusIds;
2917 * Get all the encounter medium ids currently in use.
2921 public static function getUsedEncounterMediums() {
2924 if (!is_array($mediumIds)) {
2925 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2927 $dao = CRM_Core_DAO
::executeQuery($query);
2928 $mediumIds = array();
2929 while ($dao->fetch()) {
2930 $mediumIds[] = $dao->medium_id
;
2938 * Check case configuration.
2940 * @param int $contactId
2944 public static function isCaseConfigured($contactId = NULL) {
2945 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2947 //lets check for case configured.
2948 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2949 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2950 if (!$configured['configured']) {
2951 //do check for case type and case status.
2952 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2953 if (!empty($caseTypes)) {
2954 $configured['configured'] = TRUE;
2955 if (!$configured['configured']) {
2956 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2957 if (!empty($caseStatuses)) {
2958 $configured['configured'] = TRUE;
2963 if ($configured['configured']) {
2964 //do check for active case type and case status.
2965 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2966 if (!empty($caseTypes)) {
2967 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2968 if (!empty($caseStatuses)) {
2969 $configured['allowToAddNewCase'] = TRUE;
2973 //do we need to redirect user to case admin.
2974 if (!$configured['allowToAddNewCase'] && $contactId) {
2975 //check for current contact case count.
2976 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2977 //redirect user to case admin page.
2978 if (!$currentContatCasesCount) {
2979 $configured['redirectToCaseAdmin'] = TRUE;
2988 * Used during case component enablement and during ugprade.
2992 public static function createCaseViews() {
2993 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2994 $dao = new CRM_Core_DAO();
2996 $sql = self
::createCaseViewsQuery('upcoming');
2998 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3002 // Above error doesn't get caught?
3003 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3004 if (is_null($doublecheck)) {
3008 $sql = self
::createCaseViewsQuery('recent');
3010 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
3014 // Above error doesn't get caught?
3015 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3016 if (is_null($doublecheck)) {
3024 * Helper function, also used by the upgrade in case of error
3026 * @param string $section
3030 public static function createCaseViewsQuery($section = 'upcoming') {
3032 $scheduled_id = CRM_Core_Pseudoconstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
3035 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3036 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3037 FROM civicrm_case_activity ca
3038 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3039 WHERE a.activity_date_time =
3040 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3041 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3042 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3043 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
3044 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
3048 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3049 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3050 FROM civicrm_case_activity ca
3051 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3052 WHERE a.activity_date_time =
3053 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3054 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3055 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3056 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
3057 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
3064 * Add/copy relationships, when new client is added for a case
3066 * @param int $caseId
3068 * @param int $contactId
3069 * Contact id / new client id.
3071 public static function addCaseRelationships($caseId, $contactId) {
3072 // get the case role / relationships for the case
3073 $caseRelationships = new CRM_Contact_DAO_Relationship();
3074 $caseRelationships->case_id
= $caseId;
3075 $caseRelationships->find();
3076 $relationshipTypes = array();
3078 // make sure we don't add duplicate relationships of same relationship type.
3079 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3081 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3083 // add relationship for new client.
3084 $newRelationship = new CRM_Contact_DAO_Relationship();
3085 $newRelationship->copyValues($values);
3086 $newRelationship->id
= NULL;
3087 $newRelationship->case_id
= $caseId;
3088 $newRelationship->contact_id_a
= $contactId;
3089 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3090 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3092 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3093 if (!$newRelationship->find(TRUE)) {
3094 $newRelationship->save();
3096 $newRelationship->free();
3098 // store relationship type of newly created relationship
3099 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3104 * Get the list of clients for a case.
3106 * @param int $caseId
3109 * associated array with client ids
3111 public static function getCaseClients($caseId) {
3113 $caseContact = new CRM_Case_DAO_CaseContact();
3114 $caseContact->case_id
= $caseId;
3115 $caseContact->orderBy('id');
3116 $caseContact->find();
3118 while ($caseContact->fetch()) {
3119 $clients[] = $caseContact->contact_id
;
3126 * @param int $caseId
3127 * @param string $direction
3129 * @param int $relTypeId
3130 * @throws \CRM_Core_Exception
3131 * @throws \CiviCRM_API3_Exception
3133 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3135 if ($direction !== 'a' && $direction !== 'b') {
3136 throw new CRM_Core_Exception('Invalid relationship direction');
3139 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3140 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3141 $dao = CRM_Core_DAO
::executeQuery($sql, array(
3142 1 => array($caseId, 'Positive'),
3143 2 => array($cid, 'Positive'),
3144 3 => array($relTypeId, 'Positive'),
3146 while ($dao->fetch()) {
3147 civicrm_api3('relationship', 'create', array(
3150 'end_date' => 'now',
3156 * Get options for a given case field.
3157 * @see CRM_Core_DAO::buildOptions
3159 * @param string $fieldName
3160 * @param string $context
3161 * @see CRM_Core_DAO::buildOptionsContext
3162 * @param array $props
3163 * Whatever is known about this dao object.
3165 * @return array|bool
3167 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3168 $className = __CLASS__
;
3170 switch ($fieldName) {
3171 // This field is not part of this object but the api supports it
3173 $className = 'CRM_Activity_BAO_Activity';
3176 // Filter status id by case type id
3178 if (!empty($props['case_type_id'])) {
3179 $idField = is_numeric($props['case_type_id']) ?
'id' : 'name';
3180 $caseType = civicrm_api3('CaseType', 'getsingle', array($idField => $props['case_type_id'], 'return' => 'definition'));
3181 if (!empty($caseType['definition']['statuses'])) {
3182 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
3187 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3193 public function addSelectWhereClause() {
3194 // We always return an array with these keys, even if they are empty,
3195 // because this tells the query builder that we have considered these fields for acls
3198 // Only case admins can view deleted cases
3199 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
array() : array("= 0"),
3201 // Ensure the user has permission to view the case client
3202 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3203 if ($contactClause) {
3204 $contactClause = implode(' AND contact_id ', $contactClause);
3205 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3207 // The api gatekeeper ensures the user has at least "access my cases and activities"
3208 // so if they do not have permission to see all cases we'll assume they can only access their own
3209 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3210 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3211 $clauses['id'][] = "IN (
3212 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 (
3213 (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)
3217 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3222 * CRM-20308: Method to get the contact id to use as from contact for email copy
3223 * 1. Activity Added by Contact's email address
3224 * 2. System Default From Address
3225 * 3. Default Organization Contact email address
3228 * @param int $activityID
3230 * @return mixed $emailFromContactId
3231 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3233 public static function getReceiptFrom($activityID) {
3234 $name = $address = NULL;
3236 if (!empty($activityID) && (Civi
::settings()->get('allow_mail_from_logged_in_contact'))) {
3237 // This breaks SPF/DMARC if email is sent from an email address that the server is not authorised to send from.
3238 // so we can disable this behaviour with the "allow_mail_from_logged_in_contact" setting.
3239 // There is always a 'Added by' contact for a activity,
3240 // so we can safely use ActivityContact.Getvalue API
3241 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', array(
3242 'activity_id' => $activityID,
3243 'record_type_id' => 'Activity Source',
3244 'return' => 'contact_id',
3246 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3249 // If 'From' email address not found for Source Activity Contact then
3250 // fetch the email from domain or logged in user.
3251 if (empty($address)) {
3252 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3255 return "$name <$address>";