3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 $transaction = new CRM_Core_Transaction();
94 if (!empty($params['id'])) {
95 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
98 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
101 $case = self
::add($params);
103 if (!empty($params['custom']) &&
104 is_array($params['custom'])
106 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
109 if (is_a($case, 'CRM_Core_Error')) {
110 $transaction->rollback();
114 if (!empty($params['id'])) {
115 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
118 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
120 $transaction->commit();
122 //we are not creating log for case
123 //since case log can be tracked using log for activity.
128 * Process case activity add/delete
129 * takes an associative array and
131 * @param array $params
132 * (reference ) an assoc array of name/value pairs.
135 public static function processCaseActivity(&$params) {
136 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
137 $caseActivityDAO->activity_id
= $params['activity_id'];
138 $caseActivityDAO->case_id
= $params['case_id'];
140 $caseActivityDAO->find(TRUE);
141 $caseActivityDAO->save();
145 * Get the case subject for Activity.
147 * @param int $activityId
150 * @return string|null
152 public static function getCaseSubject($activityId) {
153 $caseActivity = new CRM_Case_DAO_CaseActivity();
154 $caseActivity->activity_id
= $activityId;
155 if ($caseActivity->find(TRUE)) {
156 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
165 * @param string $colName
170 public static function getCaseType($caseId, $colName = 'title') {
172 SELECT civicrm_case_type.{$colName} FROM civicrm_case
173 LEFT JOIN civicrm_case_type ON
174 civicrm_case.case_type_id = civicrm_case_type.id
175 WHERE civicrm_case.id = %1";
177 $queryParams = array(1 => array($caseId, 'Integer'));
179 return CRM_Core_DAO
::singleValueQuery($query, $queryParams);
183 * Delete the record that are associated with this case.
184 * record are deleted from case
187 * Id of the case to delete.
189 * @param bool $moveToTrash
194 public static function deleteCase($caseId, $moveToTrash = FALSE) {
195 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
198 $activities = self
::getCaseActivityDates($caseId);
200 foreach ($activities as $value) {
201 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
206 $transaction = new CRM_Core_Transaction();
208 $case = new CRM_Case_DAO_Case();
211 $result = $case->delete();
212 $transaction->commit();
215 $result = $case->is_deleted
= 1;
220 // CRM-7364, disable relationships
221 self
::enableDisableCaseRelationships($caseId, FALSE);
223 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
225 // remove case from recent items.
230 CRM_Utils_Recent
::del($caseRecent);
238 * Enable disable case related relationships.
242 * @param bool $enable
245 public static function enableDisableCaseRelationships($caseId, $enable) {
246 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
247 if (!empty($contactIds)) {
248 foreach ($contactIds as $cid) {
249 $roles = self
::getCaseRoles($cid, $caseId);
250 if (!empty($roles)) {
251 $relationshipIds = implode(',', array_keys($roles));
252 $enable = (int) $enable;
253 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
254 WHERE id IN ( {$relationshipIds} )";
255 CRM_Core_DAO
::executeQuery($query);
262 * Retrieve contact_id by case_id.
267 * @param int $contactID
271 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL) {
272 $caseContact = new CRM_Case_DAO_CaseContact();
273 $caseContact->case_id
= $caseId;
274 $caseContact->find();
275 $contactArray = array();
277 while ($caseContact->fetch()) {
278 if ($contactID != $caseContact->contact_id
) {
279 $contactArray[$count] = $caseContact->contact_id
;
284 return $contactArray;
288 * Look up a case using an activity ID.
290 * @param int $activityId
292 * @return int, case ID
294 public static function getCaseIdByActivityId($activityId) {
295 $originalId = CRM_Core_DAO
::singleValueQuery(
296 'SELECT original_id FROM civicrm_activity WHERE id = %1',
297 array('1' => array($activityId, 'Integer'))
299 $caseId = CRM_Core_DAO
::singleValueQuery(
300 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
302 '1' => array($activityId, 'Integer'),
303 '2' => array($originalId ?
$originalId : $activityId, 'Integer'),
310 * Retrieve contact names by caseId.
317 public static function getContactNames($caseId) {
318 $contactNames = array();
320 return $contactNames;
324 SELECT contact_a.sort_name name,
325 contact_a.display_name as display_name,
327 contact_a.birth_date as birth_date,
330 FROM civicrm_contact contact_a
331 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
332 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
333 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
334 WHERE civicrm_case_contact.case_id = %1
335 ORDER BY civicrm_case_contact.id";
337 $dao = CRM_Core_DAO
::executeQuery($query,
338 array(1 => array($caseId, 'Integer'))
340 while ($dao->fetch()) {
341 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
342 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
343 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
344 $contactNames[$dao->cid
]['email'] = $dao->email
;
345 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
346 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
347 $contactNames[$dao->cid
]['role'] = ts('Client');
350 return $contactNames;
354 * Retrieve case_id by contact_id.
356 * @param int $contactID
357 * @param bool $includeDeleted
358 * Include the deleted cases in result.
359 * @param null $caseType
363 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
366 FROM civicrm_case_contact cc
367 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
369 if (isset($caseType)) {
371 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
372 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
374 if (!isset($caseType)) {
375 $query .= "WHERE cc.contact_id = %1";
377 if (!$includeDeleted) {
378 $query .= " AND ca.is_deleted = 0";
381 $params = array(1 => array($contactID, 'Integer'));
382 $dao = CRM_Core_DAO
::executeQuery($query, $params);
384 $caseArray = array();
385 while ($dao->fetch()) {
386 $caseArray[] = $dao->id
;
394 * @param string $type
396 * @param string $condition
400 public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL) {
402 $session = CRM_Core_Session
::singleton();
403 $userID = $session->get('userID');
407 civicrm_case.id as case_id,
408 civicrm_case.subject as case_subject,
409 civicrm_contact.id as contact_id,
410 civicrm_contact.sort_name as sort_name,
411 civicrm_phone.phone as phone,
412 civicrm_contact.contact_type as contact_type,
413 civicrm_contact.contact_sub_type as contact_sub_type,
414 t_act.activity_type_id,
415 c_type.title as case_type,
416 civicrm_case.case_type_id as case_type_id,
417 cov_status.label as case_status,
418 cov_status.label as case_status_name,
420 civicrm_case.start_date as case_start_date,
421 case_relation_type.label_b_a as case_role, ";
423 if ($type == 'upcoming') {
425 t_act.desired_date as case_scheduled_activity_date,
426 t_act.id as case_scheduled_activity_id,
427 t_act.act_type_name as case_scheduled_activity_type_name,
428 t_act.act_type AS case_scheduled_activity_type ";
430 elseif ($type == 'recent') {
432 t_act.desired_date as case_recent_activity_date,
433 t_act.id as case_recent_activity_id,
434 t_act.act_type_name as case_recent_activity_type_name,
435 t_act.act_type AS case_recent_activity_type ";
437 elseif ($type == 'any') {
439 t_act.desired_date as case_activity_date,
440 t_act.id as case_activity_id,
441 t_act.act_type_name as case_activity_type_name,
442 t_act.act_type AS case_activity_type ";
445 $query .= " FROM civicrm_case
446 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
447 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
449 if ($type == 'upcoming') {
450 // This gets the earliest activity per case that's scheduled within 14 days from now.
451 // 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.
452 // In this case we don't really care which one, so min(id) works.
453 // optimized in CRM-11837
454 $query .= " INNER JOIN
456 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
461 FROM civicrm_view_case_activity_upcoming
462 ORDER BY activity_date_time ASC, id ASC
465 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
466 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
470 elseif ($type == 'recent') {
471 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
472 //improve query performance - CRM-10598
473 $query .= " INNER JOIN
475 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
480 FROM civicrm_view_case_activity_recent
481 ORDER BY activity_date_time DESC, id ASC
484 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
485 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
488 elseif ($type == 'any') {
489 $query .= " LEFT JOIN
491 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
492 FROM civicrm_activity act4
493 LEFT JOIN civicrm_case_activity ca4
494 ON ca4.activity_id = act4.id
495 AND act4.is_current_revision = 1
496 LEFT JOIN civicrm_option_group aog
497 ON aog.name='activity_type'
498 LEFT JOIN civicrm_option_value aov
499 ON aov.option_group_id = aog.id
500 AND aov.value = act4.activity_type_id
505 ON t_act.case_id = civicrm_case.id
506 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
507 LEFT JOIN civicrm_relationship case_relationship
508 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
509 AND case_relationship.case_id = civicrm_case.id )
511 LEFT JOIN civicrm_relationship_type case_relation_type
512 ON ( case_relation_type.id = case_relationship.relationship_type_id
513 AND case_relation_type.id = case_relationship.relationship_type_id )
515 LEFT JOIN civicrm_case_type c_type
516 ON civicrm_case.case_type_id = c_type.id
518 LEFT JOIN civicrm_option_group cog_status
519 ON cog_status.name = 'case_status'
521 LEFT JOIN civicrm_option_value cov_status
522 ON ( civicrm_case.status_id = cov_status.value
523 AND cog_status.id = cov_status.option_group_id )
527 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
528 $query .= " WHERE (1) $condition ";
531 if ($type == 'upcoming') {
532 $query .= " ORDER BY case_scheduled_activity_date ASC ";
534 elseif ($type == 'recent') {
535 $query .= " ORDER BY case_recent_activity_date ASC ";
537 elseif ($type == 'any') {
538 $query .= " ORDER BY case_activity_date ASC ";
545 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
547 * @param bool $allCases
551 * @param string $type
552 * /upcoming,recent,all/.
554 * @param string $context
559 public static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') {
561 $casesList = array();
563 //validate access for own cases.
564 if (!self
::accessCiviCase()) {
569 $session = CRM_Core_Session
::singleton();
570 $userID = $session->get('userID');
573 //validate access for all cases.
574 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
578 $condition = " AND civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1";
581 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
583 if ($type == 'upcoming' ||
$type == 'any') {
584 $closedId = CRM_Core_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
586 AND civicrm_case.status_id != $closedId";
589 $query = self
::getCaseActivityQuery($type, $userID, $condition);
591 $queryParams = array();
592 $result = CRM_Core_DAO
::executeQuery($query,
596 $caseStatus = CRM_Core_OptionGroup
::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
598 $resultFields = array(
615 if ($type == 'upcoming') {
616 $resultFields[] = 'case_scheduled_activity_date';
617 $resultFields[] = 'case_scheduled_activity_type_name';
618 $resultFields[] = 'case_scheduled_activity_type';
619 $resultFields[] = 'case_scheduled_activity_id';
621 elseif ($type == 'recent') {
622 $resultFields[] = 'case_recent_activity_date';
623 $resultFields[] = 'case_recent_activity_type_name';
624 $resultFields[] = 'case_recent_activity_type';
625 $resultFields[] = 'case_recent_activity_id';
627 elseif ($type == 'any') {
628 $resultFields[] = 'case_activity_date';
629 $resultFields[] = 'case_activity_type_name';
630 $resultFields[] = 'case_activity_type';
631 $resultFields[] = 'case_activity_id';
634 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
635 $actions = CRM_Case_Selector_Search
::links();
637 // check is the user has view/edit signer permission
638 $permissions = array(CRM_Core_Permission
::VIEW
);
639 if (CRM_Core_Permission
::check('access all cases and activities') ||
640 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
642 $permissions[] = CRM_Core_Permission
::EDIT
;
644 if (CRM_Core_Permission
::check('delete in CiviCase')) {
645 $permissions[] = CRM_Core_Permission
::DELETE
;
647 $mask = CRM_Core_Action
::mask($permissions);
649 while ($result->fetch()) {
650 foreach ($resultFields as $donCare => $field) {
651 $casesList[$result->case_id
][$field] = $result->$field;
652 if ($field == 'contact_type') {
653 $casesList[$result->case_id
]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
655 $casesList[$result->case_id
]['action'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
657 'id' => $result->case_id
,
658 'cid' => $result->contact_id
,
663 'case.actions.primary',
668 elseif ($field == 'case_status') {
669 if (in_array($result->$field, $caseStatus)) {
670 $casesList[$result->case_id
]['class'] = "status-urgent";
673 $casesList[$result->case_id
]['class'] = "status-normal";
678 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
679 $caseManagerContact = self
::getCaseManagerContact($caseTypes[$result->case_type_id
], $result->case_id
);
680 if (!empty($caseManagerContact)) {
681 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
682 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
685 //do check user permissions for edit/view activity.
686 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
687 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
689 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
691 $casesList[$result->case_id
]['activity_type_id'], $userID
693 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
695 $casesList[$result->case_id
]['activity_type_id'], $userID
704 * Get the summary of cases counts by type and status.
706 * @param bool $allCases
710 public static function getCasesSummary($allCases = TRUE, $userID) {
711 $caseSummary = array();
713 //validate access for civicase.
714 if (!self
::accessCiviCase()) {
718 //validate access for all cases.
719 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
723 $caseTypes = CRM_Case_PseudoConstant
::caseType();
724 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
725 $caseTypes = array_flip($caseTypes);
727 // get statuses as headers for the table
728 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
729 foreach ($caseStatuses as $key => $name) {
730 $caseSummary['headers'][$key]['status'] = $name;
731 $caseSummary['headers'][$key]['url'] = $url . $key;
734 // build rows with actual data
736 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
742 $myGroupByClause = ' GROUP BY civicrm_case.id';
747 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
748 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
750 $myGroupByClause .= ", case_status.label, status_id, case_type_id";
752 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
754 SELECT case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
755 case_type_id, case_relationship.contact_id_b
757 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
758 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
759 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
760 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
761 AND option_group_case_status.id = case_status.option_group_id )
762 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
763 AND case_relationship.contact_id_b = {$userID})
764 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
765 {$myCaseWhereClause} {$myGroupByClause}";
767 $res = CRM_Core_DAO
::executeQuery($query);
768 while ($res->fetch()) {
769 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
770 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
773 $rows[$res->case_type
][$res->case_status
] = array(
775 'url' => CRM_Utils_System
::url('civicrm/case/search',
776 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
781 $caseSummary['rows'] = array_merge($caseTypes, $rows);
789 * @param int $contactID
793 * @param int $relationshipID
796 * case role / relationships
799 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
801 SELECT rel.id as civicrm_relationship_id,
802 con.sort_name as sort_name,
803 civicrm_email.email as email,
804 civicrm_phone.phone as phone,
805 con.id as civicrm_contact_id,
806 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
807 civicrm_relationship_type.id as relation_type,
808 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
809 FROM civicrm_relationship rel
810 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
811 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))
812 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
813 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
814 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
815 AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
818 1 => array($contactID, 'Positive'),
819 2 => array($caseID, 'Positive'),
822 if ($relationshipID) {
823 $query .= ' AND civicrm_relationship.id = %3 ';
824 $params[3] = array($relationshipID, 'Integer');
826 $dao = CRM_Core_DAO
::executeQuery($query, $params);
829 while ($dao->fetch()) {
830 $rid = $dao->civicrm_relationship_id
;
831 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
832 $values[$rid]['relation'] = $dao->relation
;
833 $values[$rid]['name'] = $dao->sort_name
;
834 $values[$rid]['email'] = $dao->email
;
835 $values[$rid]['phone'] = $dao->phone
;
836 $values[$rid]['relation_type'] = $dao->relation_type
;
837 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
838 $values[$rid]['client_id'] = $contactID;
839 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
847 * Get Case Activities.
851 * @param array $params
853 * @param int $contactID
856 * @param null $context
861 * Array of case activities
864 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
867 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
868 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
869 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
870 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
872 // CRM-5081 - formatting the dates to omit seconds.
873 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
875 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
877 ca.activity_type_id AS type,
878 ca.activity_type_id AS activity_type_id,
879 tcc.sort_name AS target_contact_name,
880 tcc.id AS target_contact_id,
881 scc.sort_name AS source_contact_name,
882 scc.id AS source_contact_id,
883 acc.sort_name AS assignee_contact_name,
884 acc.id AS assignee_contact_id,
886 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
887 ca.activity_date_time,
888 DATE_ADD(NOW(), INTERVAL 1 YEAR)
889 ), '%Y%m%d%H%i00') AS overdue_date,
890 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
891 ca.status_id AS status,
892 ca.subject AS subject,
893 ca.is_deleted AS deleted,
894 ca.priority_id AS priority,
896 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
899 FROM civicrm_case_activity cca
900 INNER JOIN civicrm_activity ca
901 ON ca.id = cca.activity_id
902 INNER JOIN civicrm_activity_contact cas
903 ON cas.activity_id = ca.id
904 AND cas.record_type_id = {$sourceID}
905 INNER JOIN civicrm_contact scc
906 ON scc.id = cas.contact_id
907 LEFT JOIN civicrm_activity_contact caa
908 ON caa.activity_id = ca.id
909 AND caa.record_type_id = {$assigneeID}
910 LEFT JOIN civicrm_contact acc
911 ON acc.id = caa.contact_id
912 LEFT JOIN civicrm_activity_contact cat
913 ON cat.activity_id = ca.id
914 AND cat.record_type_id = {$targetID}
915 LEFT JOIN civicrm_contact tcc
916 ON tcc.id = cat.contact_id
917 INNER JOIN civicrm_option_group cog
918 ON cog.name = 'activity_type'
919 INNER JOIN civicrm_option_value cov
920 ON cov.option_group_id = cog.id
921 AND cov.value = ca.activity_type_id
922 AND cov.is_active = 1
923 LEFT JOIN civicrm_entity_file ef
924 ON ef.entity_table = 'civicrm_activity'
925 AND ef.entity_id = ca.id
926 LEFT OUTER JOIN civicrm_option_group og
927 ON og.name = 'activity_status'
928 LEFT OUTER JOIN civicrm_option_value ov
929 ON ov.option_group_id=og.id
930 AND ov.name = 'Scheduled'";
933 WHERE cca.case_id= %1
934 AND ca.is_current_revision = 1';
936 if (!empty($params['source_contact_id'])) {
938 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
941 if (!empty($params['status_id'])) {
943 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
946 if (!empty($params['activity_deleted'])) {
948 AND ca.is_deleted = 1";
952 AND ca.is_deleted = 0";
955 if (!empty($params['activity_type_id'])) {
957 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
960 if (!empty($params['activity_date_low'])) {
961 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
963 if (!empty($fromActivityDate)) {
965 AND ca.activity_date_time >= '{$fromActivityDate}'";
968 if (!empty($params['activity_date_high'])) {
969 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
970 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
972 if (!empty($toActivityDate)) {
974 AND ca.activity_date_time <= '{$toActivityDate}'";
978 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
980 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
982 // CRM-5081 - added id to act like creation date
984 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
987 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
988 $orderBy = " ORDER BY $sortBy ";
991 $page = CRM_Utils_Array
::value('page', $params);
992 $rp = CRM_Utils_Array
::value('rp', $params);
1000 $start = (($page - 1) * $rp);
1001 $limit = " LIMIT $start, $rp";
1003 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
1004 $queryParams = array(1 => array($caseID, 'Integer'));
1006 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
1007 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
1009 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1010 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus();
1012 $url = CRM_Utils_System
::url("civicrm/case/activity",
1013 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1017 if ($context == 'fulltext') {
1018 $contextUrl = "&context={$context}";
1020 $editUrl = "{$url}&action=update{$contextUrl}";
1021 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1022 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1023 $viewTitle = ts('View activity');
1025 $emailActivityTypeIDs = array(
1026 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1030 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1036 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1038 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1039 $compStatusValues = array();
1040 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1041 foreach ($compStatusNames as $name) {
1042 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1045 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=", FALSE, NULL, FALSE);
1046 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1047 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1050 $session = CRM_Core_Session
::singleton();
1051 $userID = $session->get('userID');
1054 $caseActivities = array();
1056 while ($dao->fetch()) {
1057 $caseActivity = array();
1058 $caseActivityId = $dao->id
;
1060 $allowView = self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID);
1061 $allowEdit = self
::checkPermission($caseActivityId, 'edit', $dao->activity_type_id
, $userID);
1062 $allowDelete = self
::checkPermission($caseActivityId, 'delete', $dao->activity_type_id
, $userID);
1064 //do not have sufficient permission
1065 //to access given case activity record.
1066 if (!$allowView && !$allowEdit && !$allowDelete) {
1070 $caseActivity['DT_RowId'] = $caseActivityId;
1071 //Add classes to the row, via DataTables syntax
1072 $caseActivity['DT_RowClass'] = "crm-entity status-id-$dao->status";
1074 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1075 $caseActivity['DT_RowClass'] .= " status-completed";
1078 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1079 $caseActivity['DT_RowClass'] .= " status-overdue";
1082 $caseActivity['DT_RowClass'] .= " status-scheduled";
1086 if (!empty($dao->priority
)) {
1087 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1088 $caseActivity['DT_RowClass'] .= " priority-urgent ";
1090 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1091 $caseActivity['DT_RowClass'] .= " priority-low ";
1095 //Add data to the row for inline editing, via DataTable syntax
1096 $caseActivity['DT_RowAttr'] = array();
1097 $caseActivity['DT_RowAttr']['data-entity'] = 'activity';
1098 $caseActivity['DT_RowAttr']['data-id'] = $caseActivityId;
1100 //Activity Date and Time
1101 $caseActivity['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1104 $caseActivity['subject'] = $dao->subject
;
1107 $caseActivity['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1108 . $activityTypes[$dao->type
]['label'];
1110 //Activity Target (With)
1111 $targetContact = '';
1112 if (isset($dao->target_contact_id
)) {
1113 $targetContact = $dao->target_contact_name
;
1114 if ($hasViewContact) {
1115 $targetContact = '<a href="' . $contactViewUrl . $dao->target_contact_id
. '">' . $dao->target_contact_name
. '</a>';
1118 $caseActivity['target_contact_name'] = $targetContact;
1120 //Activity Source Contact (Reporter)
1121 $sourceContact = $dao->source_contact_name
;
1122 if ($hasViewContact) {
1123 $sourceContact = '<a href="' . $contactViewUrl . $dao->source_contact_id
. '">' . $dao->source_contact_name
. '</a>';
1125 $caseActivity['source_contact_name'] = $sourceContact;
1127 //Activity Assignee. CRM-4485.
1128 $assigneeContact = '';
1129 if (isset($dao->assignee_contact_id
)) {
1130 $assigneeContact = $dao->assignee_contact_name
;
1131 if ($hasViewContact) {
1132 $assigneeContact = '<a href="' . $contactViewUrl . $dao->assignee_contact_id
. '">' . $dao->assignee_contact_name
. '</a>';
1135 $caseActivity['assignee_contact_name'] = $assigneeContact;
1138 $caseActivity['status_id'] = $activityStatuses[$dao->status
];
1140 // 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.
1142 $css = 'class="action-item crm-hover-button"';
1144 $viewUrl = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1145 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1147 $additionalUrl = "&id={$caseActivityId}";
1148 if (!$dao->deleted
) {
1149 //hide edit link of activity type email.CRM-4530.
1150 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1151 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1153 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1157 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1160 elseif (!$caseDeleted) {
1161 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1162 $caseActivity['status_id'] = $caseActivity['status_id'] . '<br /> (deleted)';
1165 //check for operations.
1166 if (self
::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id
)) {
1167 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1169 if (self
::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id
)) {
1170 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1172 // if there are file attachments we will return how many and, if only one, add a link to it
1173 if (!empty($dao->attachment_ids
)) {
1174 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1175 $caseActivity['no_attachments'] = count($attachmentIDs);
1176 $url .= implode(' ', CRM_Core_BAO_File
::paperIconAttachment('civicrm_activity', $caseActivityId));
1179 $caseActivity['links'] = $url;
1181 array_push($caseActivities, $caseActivity);
1185 $caseActivitiesDT = array();
1186 $caseActivitiesDT['data'] = $caseActivities;
1187 $caseActivitiesDT['recordsTotal'] = $caseCount;
1188 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1190 return $caseActivitiesDT;
1194 * Get Case Related Contacts.
1196 * @param int $caseID
1198 * @param bool $includeDetails
1199 * If true include details of contacts.
1202 * array of return properties
1205 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1206 $caseRoles = array();
1207 if ($includeDetails) {
1208 $caseInfo = civicrm_api3('Case', 'getsingle', array(
1210 // 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
1211 'return' => array('case_type_id', 'case_type_id.name', 'case_type_id.definition'),
1213 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1214 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1219 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
1220 FROM civicrm_relationship cr
1221 LEFT JOIN civicrm_relationship_type crt
1222 ON crt.id = cr.relationship_type_id
1223 LEFT JOIN civicrm_contact cc
1224 ON cc.id = cr.contact_id_b
1225 LEFT JOIN civicrm_email ce
1226 ON ce.contact_id = cc.id
1227 AND ce.is_primary= 1
1228 LEFT JOIN civicrm_phone cp
1229 ON cp.contact_id = cc.id
1230 AND cp.is_primary= 1
1231 WHERE cr.case_id = %1 AND cr.is_active AND cc.is_deleted <> 1';
1233 $params = array(1 => array($caseID, 'Integer'));
1234 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1236 while ($dao->fetch()) {
1237 if (!$includeDetails) {
1238 $values[$dao->id
] = 1;
1242 'contact_id' => $dao->id
,
1243 'display_name' => $dao->name
,
1244 'sort_name' => $dao->sort_name
,
1245 'relationship_type_id' => $dao->relationship_type_id
,
1246 'role' => $dao->role
,
1247 'email' => $dao->email
,
1248 'phone' => $dao->phone
,
1250 // Add more info about the role (creator, manager)
1251 $role = CRM_Utils_Array
::value($dao->name_b_a
, $caseRoles);
1253 unset($role['name']);
1256 $values[] = $details;
1265 * Send e-mail copy of activity
1267 * @param int $clientId
1268 * @param int $activityId
1270 * @param array $contacts
1271 * Array of related contact.
1273 * @param null $attachments
1274 * @param int $caseId
1276 * @return bool |array
1278 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1283 $tplParams = $activityInfo = array();
1284 //if its a case activity
1286 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1287 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1288 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1289 $anyActivity = TRUE;
1292 $anyActivity = FALSE;
1294 $tplParams['isCaseActivity'] = 1;
1295 $tplParams['client_id'] = $clientId;
1298 $anyActivity = TRUE;
1301 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1302 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1304 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1306 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1308 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1310 $tplParams['activity'] = $activityInfo;
1311 foreach ($tplParams['activity']['fields'] as $k => $val) {
1312 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1313 $activitySubject = $val['value'];
1317 $session = CRM_Core_Session
::singleton();
1318 // CRM-8926 If user is not logged in, use the activity creator as userID
1319 if (!($userID = $session->get('userID'))) {
1320 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1323 //also create activities simultaneously of this copy.
1324 $activityParams = array();
1326 $activityParams['source_record_id'] = $activityId;
1327 $activityParams['source_contact_id'] = $userID;
1328 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1329 $activityParams['activity_date_time'] = date('YmdHis');
1330 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1331 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1332 $activityParams['case_id'] = $caseId;
1333 $activityParams['is_auto'] = 0;
1334 $activityParams['target_id'] = $clientId;
1336 $tplParams['activitySubject'] = $activitySubject;
1338 // if it’s a case activity, add hashed id to the template (CRM-5916)
1340 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1344 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1345 $receiptFrom = self
::getReceiptFrom($activityId);
1347 $recordedActivityParams = array();
1349 foreach ($contacts as $mail => $info) {
1350 $tplParams['contact'] = $info;
1351 self
::buildPermissionLinks($tplParams, $activityParams);
1353 $displayName = CRM_Utils_Array
::value('display_name', $info);
1355 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1357 'groupName' => 'msg_tpl_workflow_case',
1358 'valueName' => 'case_activity',
1359 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1360 'tplParams' => $tplParams,
1361 'from' => $receiptFrom,
1362 'toName' => $displayName,
1364 'attachments' => $attachments,
1368 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1369 $activityParams['details'] = $message;
1371 if (!empty($result[$info['contact_id']])) {
1373 * Really only need to record one activity with all the targets combined.
1374 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1375 * but it's always the same content at the moment.
1377 if (empty($recordedActivityParams)) {
1378 $recordedActivityParams = $activityParams;
1381 $recordedActivityParams['subject'] .= "; $displayName";
1383 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1386 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1390 if (!empty($recordedActivityParams)) {
1391 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1393 //create case_activity record if its case activity.
1395 $caseParams = array(
1396 'activity_id' => $activity->id
,
1397 'case_id' => $caseId,
1399 self
::processCaseActivity($caseParams);
1407 * Retrieve count of activities having a particular type, and
1408 * associated with a particular case.
1410 * @param int $caseId
1412 * @param int $activityTypeId
1413 * ID of the activity type.
1417 public static function getCaseActivityCount($caseId, $activityTypeId) {
1418 $queryParam = array(
1419 1 => array($caseId, 'Integer'),
1420 2 => array($activityTypeId, 'Integer'),
1422 $query = "SELECT count(ca.id) as countact
1423 FROM civicrm_activity ca
1424 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1425 WHERE ca.activity_type_id = %2
1426 AND cca.case_id = %1
1427 AND ca.is_deleted = 0";
1429 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1430 if ($dao->fetch()) {
1431 return $dao->countact
;
1438 * Create an activity for a case via email.
1443 * @return array|void
1444 * $activity object of newly creted activity via email
1446 public static function recordActivityViaEmail($file) {
1447 if (!file_exists($file) ||
1450 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1455 $result = CRM_Utils_Mail_Incoming
::parse($file);
1456 if ($result['is_error']) {
1460 foreach ($result['to'] as $to) {
1463 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1464 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1466 if ($replacement !== $to['email']) {
1467 $caseId = $replacement;
1468 //if caseId is invalid, return as error file
1469 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1470 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1479 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1480 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1481 $contactDetails = self
::getRelatedContacts($caseId, FALSE);
1483 if (!empty($contactDetails[$result['from']['id']])) {
1485 $params['subject'] = $result['subject'];
1486 $params['activity_date_time'] = $result['date'];
1487 $params['details'] = $result['body'];
1488 $params['source_contact_id'] = $result['from']['id'];
1489 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1494 $details = CRM_Case_PseudoConstant
::caseActivityType();
1496 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1497 $result['body'], $matches
1500 if (!empty($matches) && isset($matches[1])) {
1501 $activityType = trim($matches[1]);
1502 if (isset($details[$activityType])) {
1503 $params['activity_type_id'] = $details[$activityType]['id'];
1506 if (!isset($params['activity_type_id'])) {
1507 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1511 $activity = CRM_Activity_BAO_Activity
::create($params);
1513 $caseParams = array(
1514 'activity_id' => $activity->id
,
1515 'case_id' => $caseId,
1517 self
::processCaseActivity($caseParams);
1520 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1521 array(1 => $result['from']['email'])
1528 * Retrieve the scheduled activity type and date.
1530 * @param array $cases
1531 * Array of contact and case id.
1533 * @param string $type
1536 * Array of scheduled activity type and date
1540 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1541 $session = CRM_Core_Session
::singleton();
1542 $userID = $session->get('userID');
1544 $caseID = implode(',', $cases['case_id']);
1545 $contactID = implode(',', $cases['contact_id']);
1548 AND civicrm_case_contact.contact_id IN( {$contactID} )
1549 AND civicrm_case.id IN( {$caseID})
1550 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1552 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1554 $res = CRM_Core_DAO
::executeQuery($query);
1556 $activityInfo = array();
1557 while ($res->fetch()) {
1558 if ($type == 'upcoming') {
1559 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1560 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1563 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1564 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1568 return $activityInfo;
1572 * Combine all the exportable fields from the lower levels object.
1575 * array of exportable Fields
1577 public static function &exportableFields() {
1578 if (!self
::$_exportableFields) {
1579 if (!self
::$_exportableFields) {
1580 self
::$_exportableFields = array();
1583 $fields = CRM_Case_DAO_Case
::export();
1584 $fields['case_role'] = array('title' => ts('Role in Case'));
1585 $fields['case_type'] = array(
1586 'title' => ts('Case Type'),
1587 'name' => 'case_type',
1589 $fields['case_status'] = array(
1590 'title' => ts('Case Status'),
1591 'name' => 'case_status',
1594 // add custom data for cases
1595 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1597 self
::$_exportableFields = $fields;
1599 return self
::$_exportableFields;
1603 * Restore the record that are associated with this case.
1605 * @param int $caseId
1606 * Id of the case to restore.
1610 public static function restoreCase($caseId) {
1611 //restore activities
1612 $activities = self
::getCaseActivityDates($caseId);
1614 foreach ($activities as $value) {
1615 CRM_Activity_BAO_Activity
::restoreActivity($value);
1619 $case = new CRM_Case_DAO_Case();
1620 $case->id
= $caseId;
1621 $case->is_deleted
= 0;
1624 //CRM-7364, enable relationships
1625 self
::enableDisableCaseRelationships($caseId, TRUE);
1632 * @param null $showLinks
1633 * @param bool $returnOnlyCount
1634 * @param int $offset
1635 * @param int $rowCount
1639 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1640 $globalContacts = array();
1642 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1643 $settings = $settingsProcessor->run();
1644 if (!empty($settings)) {
1645 $groupInfo['name'] = $settings['groupname'];
1646 if ($groupInfo['name']) {
1647 $searchParams = array('name' => $groupInfo['name']);
1649 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1651 $groupInfo['id'] = $results['id'];
1652 $groupInfo['title'] = $results['title'];
1653 $params = array(array('group', '=', $groupInfo['id'], 0, 0));
1654 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1655 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1657 if ($returnOnlyCount) {
1658 return $globalContacts;
1662 foreach ($globalContacts as $idx => $contact) {
1663 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1669 return $globalContacts;
1673 * Convenience function to get both case contacts and global in one array.
1674 * @param int $caseId
1678 public static function getRelatedAndGlobalContacts($caseId) {
1679 $relatedContacts = self
::getRelatedContacts($caseId);
1681 $groupInfo = array();
1682 $globalContacts = self
::getGlobalContacts($groupInfo);
1684 //unset values which are not required.
1685 foreach ($globalContacts as $k => & $v) {
1686 unset($v['email_id']);
1687 unset($v['group_contact_id']);
1688 unset($v['status']);
1690 $v['role'] = $groupInfo['title'];
1692 //include multiple listings for the same contact/different roles.
1693 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1694 return $relatedGlobalContacts;
1698 * Get Case ActivitiesDueDates with given criteria.
1700 * @param int $caseID
1702 * @param array $criteriaParams
1704 * @param bool $latestDate
1705 * If set newest or oldest date is selected.
1708 * case activities due dates
1711 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1713 $selectDate = " ca.activity_date_time";
1714 $where = $groupBy = ' ';
1721 if (!empty($criteriaParams['activity_type_id'])) {
1722 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1723 $where .= " AND ca.is_current_revision = 1";
1724 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1727 if (!empty($criteriaParams['newest'])) {
1728 $selectDate = " max(ca.activity_date_time) ";
1731 $selectDate = " min(ca.activity_date_time) ";
1735 $query = "SELECT ca.id, {$selectDate} as activity_date
1736 FROM civicrm_activity ca
1737 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1738 WHERE cc.id = %1 {$where} {$groupBy}";
1740 $params = array(1 => array($caseID, 'Integer'));
1741 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1743 while ($dao->fetch()) {
1744 $values[$dao->id
]['id'] = $dao->id
;
1745 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1752 * Create activities when Case or Other roles assigned/modified/deleted.
1754 * @param int $caseId
1755 * @param int $relationshipId
1757 * @param int $relContactId
1758 * Case role assignee contactId.
1759 * @param int $contactId
1761 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1762 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1766 $queryParam = array();
1767 if (is_array($relationshipId)) {
1768 $relationshipId = implode(',', $relationshipId);
1769 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1772 $relationshipClause = " civicrm_relationship.id = %1";
1773 $queryParam[1] = array($relationshipId, 'Positive');
1777 SELECT cc.display_name as clientName,
1778 cca.display_name as assigneeContactName,
1779 civicrm_relationship.case_id as caseId,
1780 civicrm_relationship_type.label_a_b as relation_a_b,
1781 civicrm_relationship_type.label_b_a as relation_b_a,
1782 civicrm_relationship.contact_id_b as rel_contact_id,
1783 civicrm_relationship.contact_id_a as assign_contact_id
1784 FROM civicrm_relationship_type, civicrm_relationship
1785 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1786 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1787 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1789 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1791 while ($dao->fetch()) {
1792 // The assignee is not the client.
1793 if ($dao->rel_contact_id
!= $contactId) {
1794 $caseRelationship = $dao->relation_a_b
;
1795 $assigneContactName = $dao->clientName
;
1796 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1799 $caseRelationship = $dao->relation_b_a
;
1800 $assigneContactName = $dao->assigneeContactName
;
1801 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1805 $session = CRM_Core_Session
::singleton();
1806 $activityParams = array(
1807 'source_contact_id' => $session->get('userID'),
1808 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1809 'activity_date_time' => date('YmdHis'),
1810 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1813 //if $relContactId is passed, role is added or modified.
1814 if (!empty($relContactId)) {
1815 $activityParams['assignee_contact_id'] = $assigneContactIds;
1817 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1823 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1829 $activityParams['activity_type_id'] = $activityTypeID;
1831 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1833 //create case_activity record.
1834 $caseParams = array(
1835 'activity_id' => $activity->id
,
1836 'case_id' => $caseId,
1839 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1844 * contact which is assigned a case role of case manager.
1846 * @param int $caseType
1848 * @param int $caseId
1852 * array of contact on success otherwise empty
1855 public static function getCaseManagerContact($caseType, $caseId) {
1856 if (!$caseType ||
!$caseId) {
1860 $caseManagerContact = array();
1861 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1863 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1865 if (!empty($managerRoleId)) {
1866 $managerRoleQuery = "
1867 SELECT civicrm_contact.id as casemanager_id,
1868 civicrm_contact.sort_name as casemanager
1869 FROM civicrm_contact
1870 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1871 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1872 WHERE civicrm_case.id = %2 AND is_active = 1";
1874 $managerRoleParams = array(
1875 1 => array($managerRoleId, 'Integer'),
1876 2 => array($caseId, 'Integer'),
1879 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1880 if ($dao->fetch()) {
1881 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1882 $caseManagerContact['casemanager'] = $dao->casemanager
;
1886 return $caseManagerContact;
1890 * @param int $contactId
1891 * @param bool $excludeDeleted
1895 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1896 $params = array('check_permissions' => TRUE);
1897 if ($excludeDeleted) {
1898 $params['is_deleted'] = 0;
1901 $params['contact_id'] = $contactId;
1904 return civicrm_api3('Case', 'getcount', $params);
1906 catch (CiviCRM_API3_Exception
$e) {
1907 // Lack of permissions will throw an exception
1913 * Retrieve related case ids for given case.
1915 * @param int $caseId
1916 * @param bool $excludeDeleted
1917 * Do not include deleted cases.
1921 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1922 //FIXME : do check for permissions.
1928 $linkActType = array_search('Link Cases',
1929 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
1931 if (!$linkActType) {
1935 $whereClause = "mainCase.id = %2";
1936 if ($excludeDeleted) {
1937 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1941 SELECT relCaseAct.case_id
1942 FROM civicrm_case mainCase
1943 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1944 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1945 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1946 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1947 WHERE $whereClause";
1949 $dao = CRM_Core_DAO
::executeQuery($query, array(
1950 1 => array($linkActType, 'Integer'),
1951 2 => array($caseId, 'Integer'),
1953 $relatedCaseIds = array();
1954 while ($dao->fetch()) {
1955 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1959 return array_values($relatedCaseIds);
1963 * Retrieve related case details for given case.
1965 * @param int $caseId
1966 * @param bool $excludeDeleted
1967 * Do not include deleted cases.
1971 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
1972 $relatedCaseIds = self
::getRelatedCaseIds($caseId, $excludeDeleted);
1973 $relatedCases = array();
1975 if (!$relatedCaseIds) {
1979 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1980 if ($excludeDeleted) {
1981 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1984 //filter for permissioned cases.
1985 $filterCases = array();
1986 $doFilterCases = FALSE;
1987 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1988 $doFilterCases = TRUE;
1989 $session = CRM_Core_Session
::singleton();
1990 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
1993 //2. fetch the details of related cases.
1995 SELECT relCase.id as id,
1996 civicrm_case_type.title as case_type,
1997 client.display_name as client_name,
1998 client.id as client_id
1999 FROM civicrm_case relCase
2000 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2001 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2002 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
2003 WHERE {$whereClause}";
2005 $dao = CRM_Core_DAO
::executeQuery($query);
2006 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2007 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2009 while ($dao->fetch()) {
2011 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2012 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2013 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2014 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2016 $clientView = $dao->client_name
;
2017 if ($hasViewContact) {
2018 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2021 $relatedCases[$dao->id
] = array(
2022 'case_id' => $dao->id
,
2023 'case_type' => $dao->case_type
,
2024 'client_name' => $clientView,
2025 'links' => $caseView,
2030 return $relatedCases;
2034 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2036 * @see CRM_Dedupe_Merger::cpTables()
2038 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2040 * @param int $mainContactId
2041 * @param int $otherContactId
2043 public static function mergeContacts($mainContactId, $otherContactId) {
2044 self
::mergeCases($mainContactId, NULL, $otherContactId);
2048 * Function perform two task.
2049 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2050 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2052 * @param int $mainContactId
2053 * Contact id of main contact record.
2054 * @param int $mainCaseId
2055 * Case id of main case record.
2056 * @param int $otherContactId
2057 * Contact id of record which is going to merge.
2058 * @param int $otherCaseId
2059 * Case id of record which is going to merge.
2061 * @param bool $changeClient
2065 public static function mergeCases(
2066 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2067 $otherCaseId = NULL, $changeClient = FALSE) {
2068 $moveToTrash = TRUE;
2070 $duplicateContacts = FALSE;
2071 if ($mainContactId && $otherContactId &&
2072 $mainContactId != $otherContactId
2074 $duplicateContacts = TRUE;
2077 $duplicateCases = FALSE;
2078 if ($mainCaseId && $otherCaseId &&
2079 $mainCaseId != $otherCaseId
2081 $duplicateCases = TRUE;
2084 $mainCaseIds = array();
2085 if (!$duplicateContacts && !$duplicateCases) {
2086 return $mainCaseIds;
2089 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2090 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2091 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2092 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2093 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2094 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2096 $processCaseIds = array($otherCaseId);
2097 if ($duplicateContacts && !$duplicateCases) {
2098 if ($changeClient) {
2099 $processCaseIds = array($mainCaseId);
2102 //get all case ids for other contact.
2103 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2105 if (!is_array($processCaseIds)) {
2110 $session = CRM_Core_Session
::singleton();
2111 $currentUserId = $session->get('userID');
2113 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2115 // copy all cases and connect to main contact id.
2116 foreach ($processCaseIds as $otherCaseId) {
2117 if ($duplicateContacts) {
2118 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2119 $mainCaseId = $mainCase->id
;
2124 // CRM-11662 Copy Case custom data
2125 $extends = array('case');
2126 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2128 foreach ($groupTree as $groupID => $group) {
2129 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2130 foreach ($group['fields'] as $fieldID => $field) {
2131 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2135 foreach ($table as $tableName => $tableColumns) {
2136 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2137 $tableColumns[0] = $mainCaseId;
2138 $select = 'SELECT ' . implode(', ', $tableColumns);
2139 $from = ' FROM ' . $tableName;
2140 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2141 $query = $insert . $select . $from . $where;
2142 $dao = CRM_Core_DAO
::executeQuery($query);
2148 $mainCaseIds[] = $mainCaseId;
2149 //insert record for case contact.
2150 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2151 $otherCaseContact->case_id
= $otherCaseId;
2152 $otherCaseContact->find();
2153 while ($otherCaseContact->fetch()) {
2154 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2155 $mainCaseContact->case_id
= $mainCaseId;
2156 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2157 if ($mainCaseContact->contact_id
== $otherContactId) {
2158 $mainCaseContact->contact_id
= $mainContactId;
2160 //avoid duplicate object.
2161 if (!$mainCaseContact->find(TRUE)) {
2162 $mainCaseContact->save();
2164 $mainCaseContact->free();
2166 $otherCaseContact->free();
2168 elseif (!$otherContactId) {
2169 $otherContactId = $mainContactId;
2172 if (!$mainCaseId ||
!$otherCaseId ||
2173 !$mainContactId ||
!$otherContactId
2178 // get all activities for other case.
2179 $otherCaseActivities = array();
2180 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2182 //for duplicate cases do not process singleton activities.
2183 $otherActivityIds = $singletonActivityIds = array();
2184 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2185 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2186 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2189 $otherActivityIds[] = $otherActId;
2191 if ($duplicateCases) {
2192 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2195 FROM civicrm_activity
2196 WHERE activity_type_id = $openCaseType
2197 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2198 $dao = CRM_Core_DAO
::executeQuery($sql);
2199 while ($dao->fetch()) {
2200 $singletonActivityIds[] = $dao->id
;
2206 // migrate all activities and connect to main contact.
2207 $copiedActivityIds = $activityMappingIds = array();
2208 sort($otherActivityIds);
2209 foreach ($otherActivityIds as $otherActivityId) {
2211 //for duplicate cases -
2212 //do not migrate singleton activities.
2213 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2217 //migrate activity record.
2218 $otherActivity = new CRM_Activity_DAO_Activity();
2219 $otherActivity->id
= $otherActivityId;
2220 if (!$otherActivity->find(TRUE)) {
2224 $mainActVals = array();
2225 $mainActivity = new CRM_Activity_DAO_Activity();
2226 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2227 $mainActivity->copyValues($mainActVals);
2228 $mainActivity->id
= NULL;
2229 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2230 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2234 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2238 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2241 $mainActivity->save();
2242 $mainActivityId = $mainActivity->id
;
2243 if (!$mainActivityId) {
2247 $activityMappingIds[$otherActivityId] = $mainActivityId;
2248 // insert log of all activities
2249 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2251 $otherActivity->free();
2252 $mainActivity->free();
2253 $copiedActivityIds[] = $otherActivityId;
2255 //create case activity record.
2256 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2257 $mainCaseActivity->case_id
= $mainCaseId;
2258 $mainCaseActivity->activity_id
= $mainActivityId;
2259 $mainCaseActivity->save();
2260 $mainCaseActivity->free();
2262 //migrate source activity.
2263 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2264 $otherSourceActivity->activity_id
= $otherActivityId;
2265 $otherSourceActivity->record_type_id
= $sourceID;
2266 $otherSourceActivity->find();
2267 while ($otherSourceActivity->fetch()) {
2268 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2269 $mainActivitySource->record_type_id
= $sourceID;
2270 $mainActivitySource->activity_id
= $mainActivityId;
2271 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2272 if ($mainActivitySource->contact_id
== $otherContactId) {
2273 $mainActivitySource->contact_id
= $mainContactId;
2275 //avoid duplicate object.
2276 if (!$mainActivitySource->find(TRUE)) {
2277 $mainActivitySource->save();
2279 $mainActivitySource->free();
2281 $otherSourceActivity->free();
2283 //migrate target activities.
2284 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2285 $otherTargetActivity->activity_id
= $otherActivityId;
2286 $otherTargetActivity->record_type_id
= $targetID;
2287 $otherTargetActivity->find();
2288 while ($otherTargetActivity->fetch()) {
2289 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2290 $mainActivityTarget->record_type_id
= $targetID;
2291 $mainActivityTarget->activity_id
= $mainActivityId;
2292 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2293 if ($mainActivityTarget->contact_id
== $otherContactId) {
2294 $mainActivityTarget->contact_id
= $mainContactId;
2296 //avoid duplicate object.
2297 if (!$mainActivityTarget->find(TRUE)) {
2298 $mainActivityTarget->save();
2300 $mainActivityTarget->free();
2302 $otherTargetActivity->free();
2304 //migrate assignee activities.
2305 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2306 $otherAssigneeActivity->activity_id
= $otherActivityId;
2307 $otherAssigneeActivity->record_type_id
= $assigneeID;
2308 $otherAssigneeActivity->find();
2309 while ($otherAssigneeActivity->fetch()) {
2310 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2311 $mainAssigneeActivity->activity_id
= $mainActivityId;
2312 $mainAssigneeActivity->record_type_id
= $assigneeID;
2313 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2314 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2315 $mainAssigneeActivity->contact_id
= $mainContactId;
2317 //avoid duplicate object.
2318 if (!$mainAssigneeActivity->find(TRUE)) {
2319 $mainAssigneeActivity->save();
2321 $mainAssigneeActivity->free();
2323 $otherAssigneeActivity->free();
2325 // copy custom fields and attachments
2327 'activityID' => $otherActivityId,
2328 'mainActivityId' => $mainActivityId,
2330 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2333 //copy case relationship.
2334 if ($duplicateContacts) {
2335 //migrate relationship records.
2336 $otherRelationship = new CRM_Contact_DAO_Relationship();
2337 $otherRelationship->case_id
= $otherCaseId;
2338 $otherRelationship->find();
2339 $otherRelationshipIds = array();
2340 while ($otherRelationship->fetch()) {
2341 $otherRelVals = array();
2342 $updateOtherRel = FALSE;
2343 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2345 $mainRelationship = new CRM_Contact_DAO_Relationship();
2346 $mainRelationship->copyValues($otherRelVals);
2347 $mainRelationship->id
= NULL;
2348 $mainRelationship->case_id
= $mainCaseId;
2349 if ($mainRelationship->contact_id_a
== $otherContactId) {
2350 $updateOtherRel = TRUE;
2351 $mainRelationship->contact_id_a
= $mainContactId;
2354 //case creator change only when we merge user contact.
2355 if ($mainRelationship->contact_id_b
== $otherContactId) {
2356 //do not change creator for change client.
2357 if (!$changeClient) {
2358 $updateOtherRel = TRUE;
2359 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2362 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2363 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2365 //avoid duplicate object.
2366 if (!$mainRelationship->find(TRUE)) {
2367 $mainRelationship->save();
2369 $mainRelationship->free();
2371 //get the other relationship ids to update end date.
2372 if ($updateOtherRel) {
2373 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2376 $otherRelationship->free();
2378 //update other relationships end dates
2379 if (!empty($otherRelationshipIds)) {
2380 $sql = 'UPDATE civicrm_relationship
2381 SET end_date = CURDATE()
2382 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2383 CRM_Core_DAO
::executeQuery($sql);
2387 //move other case to trash.
2388 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2393 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2394 if ($changeClient) {
2395 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2396 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2398 $mergeActType = array_search('Reassigned Case', $activityTypes);
2399 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2402 2 => $otherContactDisplayName,
2403 3 => $mainContactDisplayName,
2408 elseif ($duplicateContacts) {
2409 $mergeActType = array_search('Merge Case', $activityTypes);
2410 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2413 2 => $otherContactId,
2414 3 => $mainContactId,
2420 $mergeActType = array_search('Merge Case', $activityTypes);
2421 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2422 if (!empty($copiedActivityIds)) {
2424 SELECT id, subject, activity_date_time, activity_type_id
2425 FROM civicrm_activity
2426 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2427 $dao = CRM_Core_DAO
::executeQuery($sql);
2428 while ($dao->fetch()) {
2429 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2430 if ($dao->subject
) {
2431 $mergeActSubjectDetails .= " :: {$dao->subject}";
2433 $mergeActSubjectDetails .= "<br />";
2438 //Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2439 $activityParams = array(
2440 'subject' => $mergeActSubject,
2441 'details' => $mergeActSubjectDetails,
2442 'status_id' => array_search('Completed', $activityStatuses),
2443 'activity_type_id' => $mergeActType,
2444 'source_contact_id' => $currentUserId,
2445 'activity_date_time' => date('YmdHis'),
2448 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2449 $mergeActivityId = $mergeActivity->id
;
2450 if (!$mergeActivityId) {
2453 $mergeActivity->free();
2455 //connect merge activity to case.
2456 $mergeCaseAct = array(
2457 'case_id' => $mainCaseId,
2458 'activity_id' => $mergeActivityId,
2461 self
::processCaseActivity($mergeCaseAct);
2464 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2466 return $mainCaseIds;
2470 * Validate contact permission for
2471 * edit/view on activity record and build links.
2473 * @param array $tplParams
2474 * Params to be sent to template for sending email.
2475 * @param array $activityParams
2476 * Info of the activity.
2478 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2479 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2480 'activity_type_id', 'id'
2483 if (!empty($tplParams['isCaseActivity'])) {
2484 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2485 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2488 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2489 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2492 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2493 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2497 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2498 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2501 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2502 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2508 * Validate contact permission for
2509 * given operation on activity record.
2511 * @param int $activityId
2512 * Activity record id.
2513 * @param string $operation
2515 * @param int $actTypeId
2517 * @param int $contactId
2518 * Contact id/if not pass consider logged in.
2519 * @param bool $checkComponent
2520 * Do we need to check component enabled.
2524 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2526 if (!$actTypeId && $activityId) {
2527 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2530 if (!$activityId ||
!$operation ||
!$actTypeId) {
2534 //do check for civicase component enabled.
2535 if ($checkComponent && !self
::enabled()) {
2539 //do check for cases.
2540 $caseActOperations = array(
2547 if (in_array($operation, $caseActOperations)) {
2549 if (!isset($caseCount)) {
2551 $caseCount = civicrm_api3('Case', 'getcount', array(
2552 'check_permissions' => TRUE,
2553 'status_id' => array('!=' => 'Closed'),
2555 'end_date' => array('IS NULL' => 1),
2558 catch (CiviCRM_API3_Exception
$e) {
2559 // Lack of permissions will throw an exception
2563 if ($operation == 'File On Case') {
2564 $allow = !empty($caseCount);
2567 $allow = ($caseCount > 1);
2571 $actionOperations = array('view', 'edit', 'delete');
2572 if (in_array($operation, $actionOperations)) {
2574 //do cache when user has non/supper permission.
2575 static $allowOperations;
2577 if (!is_array($allowOperations) ||
2578 !array_key_exists($operation, $allowOperations)
2582 $session = CRM_Core_Session
::singleton();
2583 $contactId = $session->get('userID');
2586 //check for permissions.
2587 $permissions = array(
2589 'access my cases and activities',
2590 'access all cases and activities',
2593 'access my cases and activities',
2594 'access all cases and activities',
2596 'delete' => array('delete activities'),
2599 //check for core permission.
2600 $hasPermissions = array();
2601 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2602 if (is_array($checkPermissions)) {
2603 foreach ($checkPermissions as $per) {
2604 if (CRM_Core_Permission
::check($per)) {
2605 $hasPermissions[$operation][] = $per;
2611 if (!empty($hasPermissions)) {
2612 //need to check activity object specific.
2613 if (in_array($operation, array(
2618 //do we have supper permission.
2619 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2620 $allowOperations[$operation] = $allow = TRUE;
2623 //user has only access to my cases and activity.
2624 //here object specific permmions come in picture.
2626 //edit - contact must be source or assignee
2627 //view - contact must be source/assignee/target
2628 $isTarget = $isAssignee = $isSource = FALSE;
2629 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2630 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2631 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2632 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2634 $target = new CRM_Activity_DAO_ActivityContact();
2635 $target->record_type_id
= $targetID;
2636 $target->activity_id
= $activityId;
2637 $target->contact_id
= $contactId;
2638 if ($target->find(TRUE)) {
2642 $assignee = new CRM_Activity_DAO_ActivityContact();
2643 $assignee->activity_id
= $activityId;
2644 $assignee->record_type_id
= $assigneeID;
2645 $assignee->contact_id
= $contactId;
2646 if ($assignee->find(TRUE)) {
2650 $source = new CRM_Activity_DAO_ActivityContact();
2651 $source->activity_id
= $activityId;
2652 $source->record_type_id
= $sourceID;
2653 $source->contact_id
= $contactId;
2654 if ($source->find(TRUE)) {
2658 if ($operation == 'edit') {
2659 if ($isAssignee ||
$isSource) {
2663 if ($operation == 'view') {
2664 if ($isTarget ||
$isAssignee ||
$isSource) {
2670 elseif (is_array($hasPermissions[$operation])) {
2671 $allowOperations[$operation] = $allow = TRUE;
2675 //contact do not have permission.
2676 $allowOperations[$operation] = FALSE;
2681 //here contact might have supper/non permission.
2682 $allow = $allowOperations[$operation];
2686 //do further only when operation is granted.
2688 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2690 //get the activity type name.
2691 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2693 //do not allow multiple copy / edit action.
2694 $singletonNames = array(
2704 //do not allow to delete these activities, CRM-4543
2705 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2707 //allow edit operation.
2708 $allowEditNames = array('Open Case');
2710 // do not allow File on Case
2711 $doNotFileNames = array(
2714 'Change Case Status',
2715 'Change Case Start Date',
2722 if (in_array($actTypeName, $singletonNames)) {
2724 if ($operation == 'File On Case') {
2725 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2727 if (in_array($operation, $actionOperations)) {
2729 if ($operation == 'edit') {
2730 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2732 elseif ($operation == 'delete') {
2733 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2737 if ($allow && ($operation == 'delete') &&
2738 in_array($actTypeName, $doNotDeleteNames)
2743 if ($allow && ($operation == 'File On Case') &&
2744 in_array($actTypeName, $doNotFileNames)
2749 //check settings file for masking actions
2750 //on the basis the activity types
2751 //hide Edit link if activity type is NOT editable
2752 //(special case activities).CRM-5871
2753 if ($allow && in_array($operation, $actionOperations)) {
2754 static $actionFilter = array();
2755 if (!array_key_exists($operation, $actionFilter)) {
2756 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2757 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2759 if (array_key_exists($operation, $actionFilter[$operation]) &&
2760 in_array($actTypeId, $actionFilter[$operation][$operation])
2771 * Since we drop 'access CiviCase', allow access
2772 * if user has 'access my cases and activities'
2773 * or 'access all cases and activities'
2775 public static function accessCiviCase() {
2776 if (!self
::enabled()) {
2780 if (CRM_Core_Permission
::check('access my cases and activities') ||
2781 CRM_Core_Permission
::check('access all cases and activities')
2790 * Verify user has permission to access a case.
2792 * @param int $caseId
2793 * @param bool $denyClosed
2794 * Set TRUE if one wants closed cases to be treated as inaccessible.
2798 public static function accessCase($caseId, $denyClosed = TRUE) {
2799 if (!$caseId ||
!self
::enabled()) {
2803 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2804 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2805 $params['status_id'] = array('!=' => 'Closed');
2808 return (bool) civicrm_api3('Case', 'getcount', $params);
2810 catch (CiviCRM_API3_Exception
$e) {
2811 // Lack of permissions will throw an exception
2817 * Check whether activity is a case Activity.
2819 * @param int $activityID
2824 public static function isCaseActivity($activityID) {
2825 $isCaseActivity = FALSE;
2827 $params = array(1 => array($activityID, 'Integer'));
2828 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2829 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2830 $isCaseActivity = TRUE;
2834 return $isCaseActivity;
2838 * Get all the case type ids currently in use.
2842 public static function getUsedCaseType() {
2843 static $caseTypeIds;
2845 if (!is_array($caseTypeIds)) {
2846 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2848 $dao = CRM_Core_DAO
::executeQuery($query);
2849 $caseTypeIds = array();
2850 while ($dao->fetch()) {
2851 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2854 $caseTypeIds[] = $typeId[1];
2858 return $caseTypeIds;
2862 * Get all the case status ids currently in use.
2866 public static function getUsedCaseStatuses() {
2867 static $caseStatusIds;
2869 if (!is_array($caseStatusIds)) {
2870 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2872 $dao = CRM_Core_DAO
::executeQuery($query);
2873 $caseStatusIds = array();
2874 while ($dao->fetch()) {
2875 $caseStatusIds[] = $dao->status_id
;
2879 return $caseStatusIds;
2883 * Get all the encounter medium ids currently in use.
2887 public static function getUsedEncounterMediums() {
2890 if (!is_array($mediumIds)) {
2891 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2893 $dao = CRM_Core_DAO
::executeQuery($query);
2894 $mediumIds = array();
2895 while ($dao->fetch()) {
2896 $mediumIds[] = $dao->medium_id
;
2904 * Check case configuration.
2906 * @param int $contactId
2910 public static function isCaseConfigured($contactId = NULL) {
2911 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2913 //lets check for case configured.
2914 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2915 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2916 if (!$configured['configured']) {
2917 //do check for case type and case status.
2918 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2919 if (!empty($caseTypes)) {
2920 $configured['configured'] = TRUE;
2921 if (!$configured['configured']) {
2922 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2923 if (!empty($caseStatuses)) {
2924 $configured['configured'] = TRUE;
2929 if ($configured['configured']) {
2930 //do check for active case type and case status.
2931 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2932 if (!empty($caseTypes)) {
2933 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2934 if (!empty($caseStatuses)) {
2935 $configured['allowToAddNewCase'] = TRUE;
2939 //do we need to redirect user to case admin.
2940 if (!$configured['allowToAddNewCase'] && $contactId) {
2941 //check for current contact case count.
2942 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2943 //redirect user to case admin page.
2944 if (!$currentContatCasesCount) {
2945 $configured['redirectToCaseAdmin'] = TRUE;
2954 * Used during case component enablement and during ugprade.
2958 public static function createCaseViews() {
2959 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2960 $dao = new CRM_Core_DAO();
2962 $sql = self
::createCaseViewsQuery('upcoming');
2964 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2968 // Above error doesn't get caught?
2969 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2970 if (is_null($doublecheck)) {
2974 $sql = self
::createCaseViewsQuery('recent');
2976 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2980 // Above error doesn't get caught?
2981 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
2982 if (is_null($doublecheck)) {
2990 * Helper function, also used by the upgrade in case of error
2992 * @param string $section
2996 public static function createCaseViewsQuery($section = 'upcoming') {
2998 $scheduled_id = CRM_Core_Pseudoconstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
3001 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3002 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3003 FROM civicrm_case_activity ca
3004 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3005 WHERE a.activity_date_time =
3006 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3007 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3008 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3009 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
3010 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
3014 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3015 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3016 FROM civicrm_case_activity ca
3017 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3018 WHERE a.activity_date_time =
3019 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3020 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3021 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3022 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
3023 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
3030 * Add/copy relationships, when new client is added for a case
3032 * @param int $caseId
3034 * @param int $contactId
3035 * Contact id / new client id.
3037 public static function addCaseRelationships($caseId, $contactId) {
3038 // get the case role / relationships for the case
3039 $caseRelationships = new CRM_Contact_DAO_Relationship();
3040 $caseRelationships->case_id
= $caseId;
3041 $caseRelationships->find();
3042 $relationshipTypes = array();
3044 // make sure we don't add duplicate relationships of same relationship type.
3045 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3047 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3049 // add relationship for new client.
3050 $newRelationship = new CRM_Contact_DAO_Relationship();
3051 $newRelationship->copyValues($values);
3052 $newRelationship->id
= NULL;
3053 $newRelationship->case_id
= $caseId;
3054 $newRelationship->contact_id_a
= $contactId;
3055 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3056 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3058 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3059 if (!$newRelationship->find(TRUE)) {
3060 $newRelationship->save();
3062 $newRelationship->free();
3064 // store relationship type of newly created relationship
3065 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3070 * Get the list of clients for a case.
3072 * @param int $caseId
3075 * associated array with client ids
3077 public static function getCaseClients($caseId) {
3079 $caseContact = new CRM_Case_DAO_CaseContact();
3080 $caseContact->case_id
= $caseId;
3081 $caseContact->orderBy('id');
3082 $caseContact->find();
3084 while ($caseContact->fetch()) {
3085 $clients[] = $caseContact->contact_id
;
3092 * @param int $caseId
3093 * @param string $direction
3095 * @param int $relTypeId
3096 * @throws \CRM_Core_Exception
3097 * @throws \CiviCRM_API3_Exception
3099 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3101 if ($direction !== 'a' && $direction !== 'b') {
3102 throw new CRM_Core_Exception('Invalid relationship direction');
3105 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3106 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3107 $dao = CRM_Core_DAO
::executeQuery($sql, array(
3108 1 => array($caseId, 'Positive'),
3109 2 => array($cid, 'Positive'),
3110 3 => array($relTypeId, 'Positive'),
3112 while ($dao->fetch()) {
3113 civicrm_api3('relationship', 'create', array(
3116 'end_date' => 'now',
3122 * Get options for a given case field.
3123 * @see CRM_Core_DAO::buildOptions
3125 * @param string $fieldName
3126 * @param string $context
3127 * @see CRM_Core_DAO::buildOptionsContext
3128 * @param array $props
3129 * Whatever is known about this dao object.
3131 * @return array|bool
3133 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3134 $className = __CLASS__
;
3136 switch ($fieldName) {
3137 // This field is not part of this object but the api supports it
3139 $className = 'CRM_Activity_BAO_Activity';
3142 // Filter status id by case type id
3144 if (!empty($props['case_type_id'])) {
3145 $idField = is_numeric($props['case_type_id']) ?
'id' : 'name';
3146 $caseType = civicrm_api3('CaseType', 'getsingle', array($idField => $props['case_type_id'], 'return' => 'definition'));
3147 if (!empty($caseType['definition']['statuses'])) {
3148 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
3153 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3159 public function addSelectWhereClause() {
3160 // We always return an array with these keys, even if they are empty,
3161 // because this tells the query builder that we have considered these fields for acls
3164 // Only case admins can view deleted cases
3165 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
array() : array("= 0"),
3167 // Ensure the user has permission to view the case client
3168 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3169 if ($contactClause) {
3170 $contactClause = implode(' AND contact_id ', $contactClause);
3171 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3173 // The api gatekeeper ensures the user has at least "access my cases and activities"
3174 // so if they do not have permission to see all cases we'll assume they can only access their own
3175 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3176 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3177 $clauses['id'][] = "IN (
3178 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 (
3179 (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)
3183 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3188 * CRM-20308: Method to get the contact id to use as from contact for email copy
3189 * 1. Activity Added by Contact's email address
3190 * 2. System Default From Address
3191 * 3. Default Organization Contact email address
3194 * @param int $activityID
3196 * @return mixed $emailFromContactId
3197 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3199 public static function getReceiptFrom($activityID) {
3200 $name = $address = NULL;
3202 if (!empty($activityID)) {
3203 // There is always a 'Added by' contact for a activity,
3204 // so we can safely use ActivityContact.Getvalue API
3205 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', array(
3206 'activity_id' => $activityID,
3207 'record_type_id' => 'Activity Source',
3208 'return' => 'contact_id',
3210 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3213 // If 'From' email address not found for Source Activity Contact then
3214 // fetch the email from domain or logged in user.
3215 if (empty($address)) {
3216 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3219 return "$name <$address>";