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 // CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps.
93 unset($params['created_date']);
94 unset($params['modified_date']);
95 $caseStatus = CRM_Case_PseudoConstant
::caseStatus('name');
96 // for resolved case the end date should set to now
97 if (!empty($params['status_id']) && $params['status_id'] == array_search('Closed', $caseStatus)) {
98 $params['end_date'] = date("Ymd");
101 $transaction = new CRM_Core_Transaction();
103 if (!empty($params['id'])) {
104 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
107 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
110 $case = self
::add($params);
112 if (!empty($params['custom']) &&
113 is_array($params['custom'])
115 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
118 if (is_a($case, 'CRM_Core_Error')) {
119 $transaction->rollback();
123 if (!empty($params['id'])) {
124 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
127 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
129 $transaction->commit();
131 //we are not creating log for case
132 //since case log can be tracked using log for activity.
137 * Process case activity add/delete
138 * takes an associative array and
140 * @param array $params
141 * (reference ) an assoc array of name/value pairs.
144 public static function processCaseActivity(&$params) {
145 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
146 $caseActivityDAO->activity_id
= $params['activity_id'];
147 $caseActivityDAO->case_id
= $params['case_id'];
149 $caseActivityDAO->find(TRUE);
150 $caseActivityDAO->save();
154 * Get the case subject for Activity.
156 * @param int $activityId
159 * @return string|null
161 public static function getCaseSubject($activityId) {
162 $caseActivity = new CRM_Case_DAO_CaseActivity();
163 $caseActivity->activity_id
= $activityId;
164 if ($caseActivity->find(TRUE)) {
165 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
174 * @param string $colName
179 public static function getCaseType($caseId, $colName = 'title') {
181 SELECT civicrm_case_type.{$colName} FROM civicrm_case
182 LEFT JOIN civicrm_case_type ON
183 civicrm_case.case_type_id = civicrm_case_type.id
184 WHERE civicrm_case.id = %1";
186 $queryParams = array(1 => array($caseId, 'Integer'));
188 return CRM_Core_DAO
::singleValueQuery($query, $queryParams);
192 * Delete the record that are associated with this case.
193 * record are deleted from case
196 * Id of the case to delete.
198 * @param bool $moveToTrash
203 public static function deleteCase($caseId, $moveToTrash = FALSE) {
204 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
207 $activities = self
::getCaseActivityDates($caseId);
209 foreach ($activities as $value) {
210 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
215 $transaction = new CRM_Core_Transaction();
217 $case = new CRM_Case_DAO_Case();
220 $result = $case->delete();
221 $transaction->commit();
224 $result = $case->is_deleted
= 1;
229 // CRM-7364, disable relationships
230 self
::enableDisableCaseRelationships($caseId, FALSE);
232 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
234 // remove case from recent items.
239 CRM_Utils_Recent
::del($caseRecent);
247 * Enable disable case related relationships.
251 * @param bool $enable
254 public static function enableDisableCaseRelationships($caseId, $enable) {
255 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
256 if (!empty($contactIds)) {
257 foreach ($contactIds as $cid) {
258 $roles = self
::getCaseRoles($cid, $caseId);
259 if (!empty($roles)) {
260 $relationshipIds = implode(',', array_keys($roles));
261 $enable = (int) $enable;
262 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
263 WHERE id IN ( {$relationshipIds} )";
264 CRM_Core_DAO
::executeQuery($query);
271 * Retrieve contact_id by case_id.
276 * @param int $contactID
280 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL) {
281 $caseContact = new CRM_Case_DAO_CaseContact();
282 $caseContact->case_id
= $caseId;
283 $caseContact->find();
284 $contactArray = array();
285 // FIXME: Why does this return a 1-based array?
287 while ($caseContact->fetch()) {
288 if ($contactID != $caseContact->contact_id
) {
289 $contactArray[$count] = $caseContact->contact_id
;
294 return $contactArray;
298 * Look up a case using an activity ID.
300 * @param int $activityId
302 * @return int, case ID
304 public static function getCaseIdByActivityId($activityId) {
305 $originalId = CRM_Core_DAO
::singleValueQuery(
306 'SELECT original_id FROM civicrm_activity WHERE id = %1',
307 array('1' => array($activityId, 'Integer'))
309 $caseId = CRM_Core_DAO
::singleValueQuery(
310 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
312 '1' => array($activityId, 'Integer'),
313 '2' => array($originalId ?
$originalId : $activityId, 'Integer'),
320 * Retrieve contact names by caseId.
327 public static function getContactNames($caseId) {
328 $contactNames = array();
330 return $contactNames;
334 SELECT contact_a.sort_name name,
335 contact_a.display_name as display_name,
337 contact_a.birth_date as birth_date,
340 FROM civicrm_contact contact_a
341 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
342 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
343 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
344 WHERE contact_a.is_deleted = 0 AND civicrm_case_contact.case_id = %1
345 ORDER BY civicrm_case_contact.id";
347 $dao = CRM_Core_DAO
::executeQuery($query,
348 array(1 => array($caseId, 'Integer'))
350 while ($dao->fetch()) {
351 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
352 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
353 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
354 $contactNames[$dao->cid
]['email'] = $dao->email
;
355 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
356 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
357 $contactNames[$dao->cid
]['role'] = ts('Client');
360 return $contactNames;
364 * Retrieve case_id by contact_id.
366 * @param int $contactID
367 * @param bool $includeDeleted
368 * Include the deleted cases in result.
369 * @param null $caseType
373 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
376 FROM civicrm_case_contact cc
377 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
379 if (isset($caseType)) {
381 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
382 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
384 if (!isset($caseType)) {
385 $query .= "WHERE cc.contact_id = %1";
387 if (!$includeDeleted) {
388 $query .= " AND ca.is_deleted = 0";
391 $params = array(1 => array($contactID, 'Integer'));
392 $dao = CRM_Core_DAO
::executeQuery($query, $params);
394 $caseArray = array();
395 while ($dao->fetch()) {
396 $caseArray[] = $dao->id
;
404 * @param string $type
406 * @param string $condition
410 public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL) {
412 $session = CRM_Core_Session
::singleton();
413 $userID = $session->get('userID');
417 civicrm_case.id as case_id,
418 civicrm_case.subject as case_subject,
419 civicrm_contact.id as contact_id,
420 civicrm_contact.sort_name as sort_name,
421 civicrm_phone.phone as phone,
422 civicrm_contact.contact_type as contact_type,
423 civicrm_contact.contact_sub_type as contact_sub_type,
424 t_act.activity_type_id,
425 c_type.title as case_type,
426 civicrm_case.case_type_id as case_type_id,
427 cov_status.label as case_status,
428 cov_status.label as case_status_name,
430 civicrm_case.start_date as case_start_date,
431 case_relation_type.label_b_a as case_role, ";
433 if ($type == 'upcoming') {
435 t_act.desired_date as case_scheduled_activity_date,
436 t_act.id as case_scheduled_activity_id,
437 t_act.act_type_name as case_scheduled_activity_type_name,
438 t_act.act_type AS case_scheduled_activity_type ";
440 elseif ($type == 'recent') {
442 t_act.desired_date as case_recent_activity_date,
443 t_act.id as case_recent_activity_id,
444 t_act.act_type_name as case_recent_activity_type_name,
445 t_act.act_type AS case_recent_activity_type ";
447 elseif ($type == 'any') {
449 t_act.desired_date as case_activity_date,
450 t_act.id as case_activity_id,
451 t_act.act_type_name as case_activity_type_name,
452 t_act.act_type AS case_activity_type ";
455 $query .= " FROM civicrm_case
456 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
457 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
459 if ($type == 'upcoming') {
460 // This gets the earliest activity per case that's scheduled within 14 days from now.
461 // 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.
462 // In this case we don't really care which one, so min(id) works.
463 // optimized in CRM-11837
464 $query .= " INNER JOIN
466 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
471 FROM civicrm_view_case_activity_upcoming
472 ORDER BY activity_date_time ASC, id ASC
475 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
476 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
480 elseif ($type == 'recent') {
481 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
482 //improve query performance - CRM-10598
483 $query .= " INNER JOIN
485 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
490 FROM civicrm_view_case_activity_recent
491 ORDER BY activity_date_time DESC, id ASC
494 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
495 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
498 elseif ($type == 'any') {
499 $query .= " LEFT JOIN
501 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
502 FROM civicrm_activity act4
503 LEFT JOIN civicrm_case_activity ca4
504 ON ca4.activity_id = act4.id
505 AND act4.is_current_revision = 1
506 LEFT JOIN civicrm_option_group aog
507 ON aog.name='activity_type'
508 LEFT JOIN civicrm_option_value aov
509 ON aov.option_group_id = aog.id
510 AND aov.value = act4.activity_type_id
515 ON t_act.case_id = civicrm_case.id
516 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
517 LEFT JOIN civicrm_relationship case_relationship
518 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
519 AND case_relationship.case_id = civicrm_case.id )
521 LEFT JOIN civicrm_relationship_type case_relation_type
522 ON ( case_relation_type.id = case_relationship.relationship_type_id
523 AND case_relation_type.id = case_relationship.relationship_type_id )
525 LEFT JOIN civicrm_case_type c_type
526 ON civicrm_case.case_type_id = c_type.id
528 LEFT JOIN civicrm_option_group cog_status
529 ON cog_status.name = 'case_status'
531 LEFT JOIN civicrm_option_value cov_status
532 ON ( civicrm_case.status_id = cov_status.value
533 AND cog_status.id = cov_status.option_group_id )
537 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
538 $query .= " WHERE (1) $condition ";
541 if ($type == 'upcoming') {
542 $query .= " ORDER BY case_scheduled_activity_date ASC ";
544 elseif ($type == 'recent') {
545 $query .= " ORDER BY case_recent_activity_date ASC ";
547 elseif ($type == 'any') {
548 $query .= " ORDER BY case_activity_date ASC ";
555 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
557 * @param bool $allCases
561 * @param string $type
562 * /upcoming,recent,all/.
564 * @param string $context
569 public static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') {
571 $casesList = array();
573 //validate access for own cases.
574 if (!self
::accessCiviCase()) {
579 $session = CRM_Core_Session
::singleton();
580 $userID = $session->get('userID');
583 //validate access for all cases.
584 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
588 $condition = " AND civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1";
591 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
593 if ($type == 'upcoming' ||
$type == 'any') {
594 $closedId = CRM_Core_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
596 AND civicrm_case.status_id != $closedId";
599 $query = self
::getCaseActivityQuery($type, $userID, $condition);
601 $queryParams = array();
602 $result = CRM_Core_DAO
::executeQuery($query,
606 $caseStatus = CRM_Core_OptionGroup
::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
608 $resultFields = array(
625 if ($type == 'upcoming') {
626 $resultFields[] = 'case_scheduled_activity_date';
627 $resultFields[] = 'case_scheduled_activity_type_name';
628 $resultFields[] = 'case_scheduled_activity_type';
629 $resultFields[] = 'case_scheduled_activity_id';
631 elseif ($type == 'recent') {
632 $resultFields[] = 'case_recent_activity_date';
633 $resultFields[] = 'case_recent_activity_type_name';
634 $resultFields[] = 'case_recent_activity_type';
635 $resultFields[] = 'case_recent_activity_id';
637 elseif ($type == 'any') {
638 $resultFields[] = 'case_activity_date';
639 $resultFields[] = 'case_activity_type_name';
640 $resultFields[] = 'case_activity_type';
641 $resultFields[] = 'case_activity_id';
644 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
645 $actions = CRM_Case_Selector_Search
::links();
647 // check is the user has view/edit signer permission
648 $permissions = array(CRM_Core_Permission
::VIEW
);
649 if (CRM_Core_Permission
::check('access all cases and activities') ||
650 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
652 $permissions[] = CRM_Core_Permission
::EDIT
;
654 if (CRM_Core_Permission
::check('delete in CiviCase')) {
655 $permissions[] = CRM_Core_Permission
::DELETE
;
657 $mask = CRM_Core_Action
::mask($permissions);
659 while ($result->fetch()) {
660 foreach ($resultFields as $donCare => $field) {
661 $casesList[$result->case_id
][$field] = $result->$field;
662 if ($field == 'contact_type') {
663 $casesList[$result->case_id
]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
665 $casesList[$result->case_id
]['action'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
667 'id' => $result->case_id
,
668 'cid' => $result->contact_id
,
673 'case.actions.primary',
678 elseif ($field == 'case_status') {
679 if (in_array($result->$field, $caseStatus)) {
680 $casesList[$result->case_id
]['class'] = "status-urgent";
683 $casesList[$result->case_id
]['class'] = "status-normal";
688 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
689 $caseManagerContact = self
::getCaseManagerContact($caseTypes[$result->case_type_id
], $result->case_id
);
690 if (!empty($caseManagerContact)) {
691 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
692 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
695 //do check user permissions for edit/view activity.
696 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
697 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
699 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
701 $casesList[$result->case_id
]['activity_type_id'], $userID
703 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
705 $casesList[$result->case_id
]['activity_type_id'], $userID
714 * Get the summary of cases counts by type and status.
716 * @param bool $allCases
720 public static function getCasesSummary($allCases = TRUE, $userID) {
721 $caseSummary = array();
723 //validate access for civicase.
724 if (!self
::accessCiviCase()) {
728 //validate access for all cases.
729 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
733 $caseTypes = CRM_Case_PseudoConstant
::caseType();
734 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
735 $caseTypes = array_flip($caseTypes);
737 // get statuses as headers for the table
738 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
739 foreach ($caseStatuses as $key => $name) {
740 $caseSummary['headers'][$key]['status'] = $name;
741 $caseSummary['headers'][$key]['url'] = $url . $key;
744 // build rows with actual data
746 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
752 $myGroupByClause = ' GROUP BY civicrm_case.id';
757 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
758 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
760 $myGroupByClause .= ", case_status.label, status_id, case_type_id";
762 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
764 SELECT case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
765 case_type_id, case_relationship.contact_id_b
767 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
768 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
769 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
770 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
771 AND option_group_case_status.id = case_status.option_group_id )
772 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
773 AND case_relationship.contact_id_b = {$userID})
774 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
775 {$myCaseWhereClause} {$myGroupByClause}";
777 $res = CRM_Core_DAO
::executeQuery($query);
778 while ($res->fetch()) {
779 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
780 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
783 $rows[$res->case_type
][$res->case_status
] = array(
785 'url' => CRM_Utils_System
::url('civicrm/case/search',
786 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
791 $caseSummary['rows'] = array_merge($caseTypes, $rows);
799 * @param int $contactID
803 * @param int $relationshipID
806 * case role / relationships
809 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
811 SELECT rel.id as civicrm_relationship_id,
812 con.sort_name as sort_name,
813 civicrm_email.email as email,
814 civicrm_phone.phone as phone,
815 con.id as civicrm_contact_id,
816 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
817 civicrm_relationship_type.id as relation_type,
818 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
819 FROM civicrm_relationship rel
820 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
821 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))
822 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
823 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
824 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
825 AND rel.is_active = 1 AND con.is_deleted = 0 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
828 1 => array($contactID, 'Positive'),
829 2 => array($caseID, 'Positive'),
832 if ($relationshipID) {
833 $query .= ' AND civicrm_relationship.id = %3 ';
834 $params[3] = array($relationshipID, 'Integer');
836 $dao = CRM_Core_DAO
::executeQuery($query, $params);
839 while ($dao->fetch()) {
840 $rid = $dao->civicrm_relationship_id
;
841 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
842 $values[$rid]['relation'] = $dao->relation
;
843 $values[$rid]['name'] = $dao->sort_name
;
844 $values[$rid]['email'] = $dao->email
;
845 $values[$rid]['phone'] = $dao->phone
;
846 $values[$rid]['relation_type'] = $dao->relation_type
;
847 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
848 $values[$rid]['client_id'] = $contactID;
849 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
857 * Get Case Activities.
861 * @param array $params
863 * @param int $contactID
866 * @param null $context
871 * Array of case activities
874 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
877 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
878 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
879 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
880 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
882 // CRM-5081 - formatting the dates to omit seconds.
883 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
885 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
887 ca.activity_type_id AS type,
888 ca.activity_type_id AS activity_type_id,
889 tcc.sort_name AS target_contact_name,
890 tcc.id AS target_contact_id,
891 scc.sort_name AS source_contact_name,
892 scc.id AS source_contact_id,
893 acc.sort_name AS assignee_contact_name,
894 acc.id AS assignee_contact_id,
896 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
897 ca.activity_date_time,
898 DATE_ADD(NOW(), INTERVAL 1 YEAR)
899 ), '%Y%m%d%H%i00') AS overdue_date,
900 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
901 ca.status_id AS status,
902 ca.subject AS subject,
903 ca.is_deleted AS deleted,
904 ca.priority_id AS priority,
906 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
909 FROM civicrm_case_activity cca
910 INNER JOIN civicrm_activity ca
911 ON ca.id = cca.activity_id
912 INNER JOIN civicrm_activity_contact cas
913 ON cas.activity_id = ca.id
914 AND cas.record_type_id = {$sourceID}
915 INNER JOIN civicrm_contact scc
916 ON scc.id = cas.contact_id
917 LEFT JOIN civicrm_activity_contact caa
918 ON caa.activity_id = ca.id
919 AND caa.record_type_id = {$assigneeID}
920 LEFT JOIN civicrm_contact acc
921 ON acc.id = caa.contact_id
922 LEFT JOIN civicrm_activity_contact cat
923 ON cat.activity_id = ca.id
924 AND cat.record_type_id = {$targetID}
925 LEFT JOIN civicrm_contact tcc
926 ON tcc.id = cat.contact_id
927 INNER JOIN civicrm_option_group cog
928 ON cog.name = 'activity_type'
929 INNER JOIN civicrm_option_value cov
930 ON cov.option_group_id = cog.id
931 AND cov.value = ca.activity_type_id
932 AND cov.is_active = 1
933 LEFT JOIN civicrm_entity_file ef
934 ON ef.entity_table = 'civicrm_activity'
935 AND ef.entity_id = ca.id
936 LEFT OUTER JOIN civicrm_option_group og
937 ON og.name = 'activity_status'
938 LEFT OUTER JOIN civicrm_option_value ov
939 ON ov.option_group_id=og.id
940 AND ov.name = 'Scheduled'";
943 WHERE cca.case_id= %1
944 AND ca.is_current_revision = 1';
946 if (!empty($params['source_contact_id'])) {
948 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
951 if (!empty($params['status_id'])) {
953 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
956 if (!empty($params['activity_deleted'])) {
958 AND ca.is_deleted = 1";
962 AND ca.is_deleted = 0";
965 if (!empty($params['activity_type_id'])) {
967 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
970 if (!empty($params['activity_date_low'])) {
971 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
973 if (!empty($fromActivityDate)) {
975 AND ca.activity_date_time >= '{$fromActivityDate}'";
978 if (!empty($params['activity_date_high'])) {
979 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
980 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
982 if (!empty($toActivityDate)) {
984 AND ca.activity_date_time <= '{$toActivityDate}'";
988 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
990 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
992 // CRM-5081 - added id to act like creation date
994 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
997 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
998 $orderBy = " ORDER BY $sortBy ";
1001 $page = CRM_Utils_Array
::value('page', $params);
1002 $rp = CRM_Utils_Array
::value('rp', $params);
1010 $start = (($page - 1) * $rp);
1011 $limit = " LIMIT $start, $rp";
1013 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
1014 $queryParams = array(1 => array($caseID, 'Integer'));
1016 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
1017 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
1019 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1020 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus();
1022 $url = CRM_Utils_System
::url("civicrm/case/activity",
1023 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1027 if ($context == 'fulltext') {
1028 $contextUrl = "&context={$context}";
1030 $editUrl = "{$url}&action=update{$contextUrl}";
1031 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1032 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1033 $viewTitle = ts('View activity');
1035 $emailActivityTypeIDs = array(
1036 'Email' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Email'),
1037 'Inbound Email' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email'),
1040 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1042 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1043 $compStatusValues = array();
1044 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1045 foreach ($compStatusNames as $name) {
1046 $compStatusValues[] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $name);
1049 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=", FALSE, NULL, FALSE);
1050 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1051 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1054 $session = CRM_Core_Session
::singleton();
1055 $userID = $session->get('userID');
1058 $caseActivities = array();
1060 while ($dao->fetch()) {
1061 $caseActivity = array();
1062 $caseActivityId = $dao->id
;
1064 $allowView = self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID);
1065 $allowEdit = self
::checkPermission($caseActivityId, 'edit', $dao->activity_type_id
, $userID);
1066 $allowDelete = self
::checkPermission($caseActivityId, 'delete', $dao->activity_type_id
, $userID);
1068 //do not have sufficient permission
1069 //to access given case activity record.
1070 if (!$allowView && !$allowEdit && !$allowDelete) {
1074 $caseActivity['DT_RowId'] = $caseActivityId;
1075 //Add classes to the row, via DataTables syntax
1076 $caseActivity['DT_RowClass'] = "crm-entity status-id-$dao->status";
1078 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1079 $caseActivity['DT_RowClass'] .= " status-completed";
1082 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1083 $caseActivity['DT_RowClass'] .= " status-overdue";
1086 $caseActivity['DT_RowClass'] .= " status-scheduled";
1090 if (!empty($dao->priority
)) {
1091 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1092 $caseActivity['DT_RowClass'] .= " priority-urgent ";
1094 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1095 $caseActivity['DT_RowClass'] .= " priority-low ";
1099 //Add data to the row for inline editing, via DataTable syntax
1100 $caseActivity['DT_RowAttr'] = array();
1101 $caseActivity['DT_RowAttr']['data-entity'] = 'activity';
1102 $caseActivity['DT_RowAttr']['data-id'] = $caseActivityId;
1104 //Activity Date and Time
1105 $caseActivity['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1108 $caseActivity['subject'] = $dao->subject
;
1111 $caseActivity['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1112 . $activityTypes[$dao->type
]['label'];
1114 //Activity Target (With)
1115 $targetContact = '';
1116 if (isset($dao->target_contact_id
)) {
1117 $targetContact = $dao->target_contact_name
;
1118 if ($hasViewContact) {
1119 $targetContact = '<a href="' . $contactViewUrl . $dao->target_contact_id
. '">' . $dao->target_contact_name
. '</a>';
1122 $caseActivity['target_contact_name'] = $targetContact;
1124 //Activity Source Contact (Reporter)
1125 $sourceContact = $dao->source_contact_name
;
1126 if ($hasViewContact) {
1127 $sourceContact = '<a href="' . $contactViewUrl . $dao->source_contact_id
. '">' . $dao->source_contact_name
. '</a>';
1129 $caseActivity['source_contact_name'] = $sourceContact;
1131 //Activity Assignee. CRM-4485.
1132 $assigneeContact = '';
1133 if (isset($dao->assignee_contact_id
)) {
1134 $assigneeContact = $dao->assignee_contact_name
;
1135 if ($hasViewContact) {
1136 $assigneeContact = '<a href="' . $contactViewUrl . $dao->assignee_contact_id
. '">' . $dao->assignee_contact_name
. '</a>';
1139 $caseActivity['assignee_contact_name'] = $assigneeContact;
1142 $caseActivity['status_id'] = $activityStatuses[$dao->status
];
1144 // 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.
1146 $css = 'class="action-item crm-hover-button"';
1148 $viewUrl = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1149 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1151 $additionalUrl = "&id={$caseActivityId}";
1152 if (!$dao->deleted
) {
1153 //hide edit link of activity type email.CRM-4530.
1154 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1155 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1157 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1161 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1164 elseif (!$caseDeleted) {
1165 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1166 $caseActivity['status_id'] = $caseActivity['status_id'] . '<br /> (deleted)';
1169 //check for operations.
1170 if (self
::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id
)) {
1171 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1173 if (self
::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id
)) {
1174 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1176 // if there are file attachments we will return how many and, if only one, add a link to it
1177 if (!empty($dao->attachment_ids
)) {
1178 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1179 $caseActivity['no_attachments'] = count($attachmentIDs);
1180 $url .= implode(' ', CRM_Core_BAO_File
::paperIconAttachment('civicrm_activity', $caseActivityId));
1183 $caseActivity['links'] = $url;
1185 array_push($caseActivities, $caseActivity);
1189 $caseActivitiesDT = array();
1190 $caseActivitiesDT['data'] = $caseActivities;
1191 $caseActivitiesDT['recordsTotal'] = $caseCount;
1192 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1194 return $caseActivitiesDT;
1198 * Get Case Related Contacts.
1200 * @param int $caseID
1202 * @param bool $includeDetails
1203 * If true include details of contacts.
1206 * array of return properties
1209 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1210 $caseRoles = array();
1211 if ($includeDetails) {
1212 $caseInfo = civicrm_api3('Case', 'getsingle', array(
1214 // 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
1215 'return' => array('case_type_id', 'case_type_id.name', 'case_type_id.definition'),
1217 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1218 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1223 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
1224 FROM civicrm_relationship cr
1225 LEFT JOIN civicrm_relationship_type crt
1226 ON crt.id = cr.relationship_type_id
1227 LEFT JOIN civicrm_contact cc
1228 ON cc.id = cr.contact_id_b
1229 LEFT JOIN civicrm_email ce
1230 ON ce.contact_id = cc.id
1231 AND ce.is_primary= 1
1232 LEFT JOIN civicrm_phone cp
1233 ON cp.contact_id = cc.id
1234 AND cp.is_primary= 1
1235 WHERE cr.case_id = %1 AND cr.is_active AND cc.is_deleted <> 1';
1237 $params = array(1 => array($caseID, 'Integer'));
1238 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1240 while ($dao->fetch()) {
1241 if (!$includeDetails) {
1242 $values[$dao->id
] = 1;
1246 'contact_id' => $dao->id
,
1247 'display_name' => $dao->name
,
1248 'sort_name' => $dao->sort_name
,
1249 'relationship_type_id' => $dao->relationship_type_id
,
1250 'role' => $dao->role
,
1251 'email' => $dao->email
,
1252 'phone' => $dao->phone
,
1254 // Add more info about the role (creator, manager)
1255 $role = CRM_Utils_Array
::value($dao->name_b_a
, $caseRoles);
1257 unset($role['name']);
1260 $values[] = $details;
1269 * Send e-mail copy of activity
1271 * @param int $clientId
1272 * @param int $activityId
1274 * @param array $contacts
1275 * Array of related contact.
1277 * @param null $attachments
1278 * @param int $caseId
1280 * @return bool |array
1282 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1287 $tplParams = $activityInfo = array();
1288 //if its a case activity
1290 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1291 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1292 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1293 $anyActivity = TRUE;
1296 $anyActivity = FALSE;
1298 $tplParams['isCaseActivity'] = 1;
1299 $tplParams['client_id'] = $clientId;
1302 $anyActivity = TRUE;
1305 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1306 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1308 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1310 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1312 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1314 $tplParams['activity'] = $activityInfo;
1315 foreach ($tplParams['activity']['fields'] as $k => $val) {
1316 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1317 $activitySubject = $val['value'];
1321 $session = CRM_Core_Session
::singleton();
1322 // CRM-8926 If user is not logged in, use the activity creator as userID
1323 if (!($userID = $session->get('userID'))) {
1324 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1327 //also create activities simultaneously of this copy.
1328 $activityParams = array();
1330 $activityParams['source_record_id'] = $activityId;
1331 $activityParams['source_contact_id'] = $userID;
1332 $activityParams['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_type_id', 'Email');
1333 $activityParams['activity_date_time'] = date('YmdHis');
1334 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'activity_status_id', 'Completed');
1335 $activityParams['medium_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_DAO_Activity', 'encounter_medium', 'email');
1336 $activityParams['case_id'] = $caseId;
1337 $activityParams['is_auto'] = 0;
1338 $activityParams['target_id'] = $clientId;
1340 $tplParams['activitySubject'] = $activitySubject;
1342 // if it’s a case activity, add hashed id to the template (CRM-5916)
1344 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1348 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1349 $receiptFrom = self
::getReceiptFrom($activityId);
1351 $recordedActivityParams = array();
1353 foreach ($contacts as $mail => $info) {
1354 $tplParams['contact'] = $info;
1355 self
::buildPermissionLinks($tplParams, $activityParams);
1357 $displayName = CRM_Utils_Array
::value('display_name', $info);
1359 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1361 'groupName' => 'msg_tpl_workflow_case',
1362 'valueName' => 'case_activity',
1363 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1364 'tplParams' => $tplParams,
1365 'from' => $receiptFrom,
1366 'toName' => $displayName,
1368 'attachments' => $attachments,
1372 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1373 $activityParams['details'] = $message;
1375 if (!empty($result[$info['contact_id']])) {
1377 * Really only need to record one activity with all the targets combined.
1378 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1379 * but it's always the same content at the moment.
1381 if (empty($recordedActivityParams)) {
1382 $recordedActivityParams = $activityParams;
1385 $recordedActivityParams['subject'] .= "; $displayName";
1387 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1390 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1394 if (!empty($recordedActivityParams)) {
1395 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1397 //create case_activity record if its case activity.
1399 $caseParams = array(
1400 'activity_id' => $activity->id
,
1401 'case_id' => $caseId,
1403 self
::processCaseActivity($caseParams);
1411 * Retrieve count of activities having a particular type, and
1412 * associated with a particular case.
1414 * @param int $caseId
1416 * @param int $activityTypeId
1417 * ID of the activity type.
1421 public static function getCaseActivityCount($caseId, $activityTypeId) {
1422 $queryParam = array(
1423 1 => array($caseId, 'Integer'),
1424 2 => array($activityTypeId, 'Integer'),
1426 $query = "SELECT count(ca.id) as countact
1427 FROM civicrm_activity ca
1428 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1429 WHERE ca.activity_type_id = %2
1430 AND cca.case_id = %1
1431 AND ca.is_deleted = 0";
1433 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1434 if ($dao->fetch()) {
1435 return $dao->countact
;
1442 * Create an activity for a case via email.
1447 * @return array|void
1448 * $activity object of newly creted activity via email
1450 public static function recordActivityViaEmail($file) {
1451 if (!file_exists($file) ||
1454 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1459 $result = CRM_Utils_Mail_Incoming
::parse($file);
1460 if ($result['is_error']) {
1464 foreach ($result['to'] as $to) {
1467 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1468 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1470 if ($replacement !== $to['email']) {
1471 $caseId = $replacement;
1472 //if caseId is invalid, return as error file
1473 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1474 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1483 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1484 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1485 $contactDetails = self
::getRelatedContacts($caseId, FALSE);
1487 if (!empty($contactDetails[$result['from']['id']])) {
1489 $params['subject'] = $result['subject'];
1490 $params['activity_date_time'] = $result['date'];
1491 $params['details'] = $result['body'];
1492 $params['source_contact_id'] = $result['from']['id'];
1493 $params['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed');
1495 $details = CRM_Case_PseudoConstant
::caseActivityType();
1497 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1498 $result['body'], $matches
1501 if (!empty($matches) && isset($matches[1])) {
1502 $activityType = trim($matches[1]);
1503 if (isset($details[$activityType])) {
1504 $params['activity_type_id'] = $details[$activityType]['id'];
1507 if (!isset($params['activity_type_id'])) {
1508 $params['activity_type_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Inbound Email');
1512 $activity = CRM_Activity_BAO_Activity
::create($params);
1514 $caseParams = array(
1515 'activity_id' => $activity->id
,
1516 'case_id' => $caseId,
1518 self
::processCaseActivity($caseParams);
1521 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1522 array(1 => $result['from']['email'])
1529 * Retrieve the scheduled activity type and date.
1531 * @param array $cases
1532 * Array of contact and case id.
1534 * @param string $type
1537 * Array of scheduled activity type and date
1541 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1542 $session = CRM_Core_Session
::singleton();
1543 $userID = $session->get('userID');
1545 $caseID = implode(',', $cases['case_id']);
1546 $contactID = implode(',', $cases['contact_id']);
1549 AND civicrm_case_contact.contact_id IN( {$contactID} )
1550 AND civicrm_case.id IN( {$caseID})
1551 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1553 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1555 $res = CRM_Core_DAO
::executeQuery($query);
1557 $activityInfo = array();
1558 while ($res->fetch()) {
1559 if ($type == 'upcoming') {
1560 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1561 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1564 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1565 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1569 return $activityInfo;
1573 * Combine all the exportable fields from the lower levels object.
1576 * array of exportable Fields
1578 public static function &exportableFields() {
1579 if (!self
::$_exportableFields) {
1580 if (!self
::$_exportableFields) {
1581 self
::$_exportableFields = array();
1584 $fields = CRM_Case_DAO_Case
::export();
1585 $fields['case_role'] = array('title' => ts('Role in Case'));
1586 $fields['case_type'] = array(
1587 'title' => ts('Case Type'),
1588 'name' => 'case_type',
1590 $fields['case_status'] = array(
1591 'title' => ts('Case Status'),
1592 'name' => 'case_status',
1595 // add custom data for cases
1596 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1598 self
::$_exportableFields = $fields;
1600 return self
::$_exportableFields;
1604 * Restore the record that are associated with this case.
1606 * @param int $caseId
1607 * Id of the case to restore.
1611 public static function restoreCase($caseId) {
1612 //restore activities
1613 $activities = self
::getCaseActivityDates($caseId);
1615 foreach ($activities as $value) {
1616 CRM_Activity_BAO_Activity
::restoreActivity($value);
1620 $case = new CRM_Case_DAO_Case();
1621 $case->id
= $caseId;
1622 $case->is_deleted
= 0;
1625 //CRM-7364, enable relationships
1626 self
::enableDisableCaseRelationships($caseId, TRUE);
1633 * @param null $showLinks
1634 * @param bool $returnOnlyCount
1635 * @param int $offset
1636 * @param int $rowCount
1640 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1641 $globalContacts = array();
1643 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1644 $settings = $settingsProcessor->run();
1645 if (!empty($settings)) {
1646 $groupInfo['name'] = $settings['groupname'];
1647 if ($groupInfo['name']) {
1648 $searchParams = array('name' => $groupInfo['name']);
1650 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1652 $groupInfo['id'] = $results['id'];
1653 $groupInfo['title'] = $results['title'];
1654 $params = array(array('group', '=', $groupInfo['id'], 0, 0));
1655 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1656 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1658 if ($returnOnlyCount) {
1659 return $globalContacts;
1663 foreach ($globalContacts as $idx => $contact) {
1664 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1670 return $globalContacts;
1674 * Convenience function to get both case contacts and global in one array.
1675 * @param int $caseId
1679 public static function getRelatedAndGlobalContacts($caseId) {
1680 $relatedContacts = self
::getRelatedContacts($caseId);
1682 $groupInfo = array();
1683 $globalContacts = self
::getGlobalContacts($groupInfo);
1685 //unset values which are not required.
1686 foreach ($globalContacts as $k => & $v) {
1687 unset($v['email_id']);
1688 unset($v['group_contact_id']);
1689 unset($v['status']);
1691 $v['role'] = $groupInfo['title'];
1693 //include multiple listings for the same contact/different roles.
1694 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1695 return $relatedGlobalContacts;
1699 * Get Case ActivitiesDueDates with given criteria.
1701 * @param int $caseID
1703 * @param array $criteriaParams
1705 * @param bool $latestDate
1706 * If set newest or oldest date is selected.
1709 * case activities due dates
1712 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1714 $selectDate = " ca.activity_date_time";
1715 $where = $groupBy = ' ';
1722 if (!empty($criteriaParams['activity_type_id'])) {
1723 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1724 $where .= " AND ca.is_current_revision = 1";
1725 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1728 if (!empty($criteriaParams['newest'])) {
1729 $selectDate = " max(ca.activity_date_time) ";
1732 $selectDate = " min(ca.activity_date_time) ";
1736 $query = "SELECT ca.id, {$selectDate} as activity_date
1737 FROM civicrm_activity ca
1738 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1739 WHERE cc.id = %1 {$where} {$groupBy}";
1741 $params = array(1 => array($caseID, 'Integer'));
1742 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1744 while ($dao->fetch()) {
1745 $values[$dao->id
]['id'] = $dao->id
;
1746 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1753 * Create activities when Case or Other roles assigned/modified/deleted.
1755 * @param int $caseId
1756 * @param int $relationshipId
1758 * @param int $relContactId
1759 * Case role assignee contactId.
1760 * @param int $contactId
1762 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1763 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1767 $queryParam = array();
1768 if (is_array($relationshipId)) {
1769 $relationshipId = implode(',', $relationshipId);
1770 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1773 $relationshipClause = " civicrm_relationship.id = %1";
1774 $queryParam[1] = array($relationshipId, 'Positive');
1778 SELECT cc.display_name as clientName,
1779 cca.display_name as assigneeContactName,
1780 civicrm_relationship.case_id as caseId,
1781 civicrm_relationship_type.label_a_b as relation_a_b,
1782 civicrm_relationship_type.label_b_a as relation_b_a,
1783 civicrm_relationship.contact_id_b as rel_contact_id,
1784 civicrm_relationship.contact_id_a as assign_contact_id
1785 FROM civicrm_relationship_type, civicrm_relationship
1786 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1787 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1788 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1790 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1792 while ($dao->fetch()) {
1793 // The assignee is not the client.
1794 if ($dao->rel_contact_id
!= $contactId) {
1795 $caseRelationship = $dao->relation_a_b
;
1796 $assigneContactName = $dao->clientName
;
1797 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1800 $caseRelationship = $dao->relation_b_a
;
1801 $assigneContactName = $dao->assigneeContactName
;
1802 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1806 $session = CRM_Core_Session
::singleton();
1807 $activityParams = array(
1808 'source_contact_id' => $session->get('userID'),
1809 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1810 'activity_date_time' => date('YmdHis'),
1811 'status_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
1814 //if $relContactId is passed, role is added or modified.
1815 if (!empty($relContactId)) {
1816 $activityParams['assignee_contact_id'] = $assigneContactIds;
1817 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Assign Case Role');
1820 $activityTypeID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Remove Case Role');
1823 $activityParams['activity_type_id'] = $activityTypeID;
1825 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1827 //create case_activity record.
1828 $caseParams = array(
1829 'activity_id' => $activity->id
,
1830 'case_id' => $caseId,
1833 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1838 * contact which is assigned a case role of case manager.
1840 * @param int $caseType
1842 * @param int $caseId
1846 * array of contact on success otherwise empty
1849 public static function getCaseManagerContact($caseType, $caseId) {
1850 if (!$caseType ||
!$caseId) {
1854 $caseManagerContact = array();
1855 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1857 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1859 if (!empty($managerRoleId)) {
1860 $managerRoleQuery = "
1861 SELECT civicrm_contact.id as casemanager_id,
1862 civicrm_contact.sort_name as casemanager
1863 FROM civicrm_contact
1864 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1865 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1866 WHERE civicrm_case.id = %2 AND is_active = 1";
1868 $managerRoleParams = array(
1869 1 => array($managerRoleId, 'Integer'),
1870 2 => array($caseId, 'Integer'),
1873 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1874 if ($dao->fetch()) {
1875 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1876 $caseManagerContact['casemanager'] = $dao->casemanager
;
1880 return $caseManagerContact;
1884 * @param int $contactId
1885 * @param bool $excludeDeleted
1889 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1890 $params = array('check_permissions' => TRUE);
1891 if ($excludeDeleted) {
1892 $params['is_deleted'] = 0;
1895 $params['contact_id'] = $contactId;
1898 return civicrm_api3('Case', 'getcount', $params);
1900 catch (CiviCRM_API3_Exception
$e) {
1901 // Lack of permissions will throw an exception
1907 * Retrieve related case ids for given case.
1909 * @param int $caseId
1910 * @param bool $excludeDeleted
1911 * Do not include deleted cases.
1915 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1916 //FIXME : do check for permissions.
1922 $linkActType = array_search('Link Cases',
1923 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
1925 if (!$linkActType) {
1929 $whereClause = "mainCase.id = %2";
1930 if ($excludeDeleted) {
1931 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1935 SELECT relCaseAct.case_id
1936 FROM civicrm_case mainCase
1937 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1938 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1939 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1940 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1941 WHERE $whereClause";
1943 $dao = CRM_Core_DAO
::executeQuery($query, array(
1944 1 => array($linkActType, 'Integer'),
1945 2 => array($caseId, 'Integer'),
1947 $relatedCaseIds = array();
1948 while ($dao->fetch()) {
1949 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1953 return array_values($relatedCaseIds);
1957 * Retrieve related case details for given case.
1959 * @param int $caseId
1960 * @param bool $excludeDeleted
1961 * Do not include deleted cases.
1965 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
1966 $relatedCaseIds = self
::getRelatedCaseIds($caseId, $excludeDeleted);
1967 $relatedCases = array();
1969 if (!$relatedCaseIds) {
1973 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1974 if ($excludeDeleted) {
1975 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1978 //filter for permissioned cases.
1979 $filterCases = array();
1980 $doFilterCases = FALSE;
1981 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1982 $doFilterCases = TRUE;
1983 $session = CRM_Core_Session
::singleton();
1984 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
1987 //2. fetch the details of related cases.
1989 SELECT relCase.id as id,
1990 civicrm_case_type.title as case_type,
1991 client.display_name as client_name,
1992 client.id as client_id,
1994 FROM civicrm_case relCase
1995 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
1996 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
1997 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
1998 WHERE {$whereClause}";
2000 $dao = CRM_Core_DAO
::executeQuery($query);
2001 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2002 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2003 $statuses = CRM_Case_BAO_Case
::buildOptions('status_id');
2005 while ($dao->fetch()) {
2007 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2008 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2009 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2010 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2012 $clientView = $dao->client_name
;
2013 if ($hasViewContact) {
2014 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2017 $relatedCases[$dao->id
] = array(
2018 'case_id' => $dao->id
,
2019 'case_type' => $dao->case_type
,
2020 'client_name' => $clientView,
2021 'case_status' => $statuses[$dao->status_id
],
2022 'links' => $caseView,
2027 return $relatedCases;
2031 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2033 * @see CRM_Dedupe_Merger::cpTables()
2035 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2037 * @param int $mainContactId
2038 * @param int $otherContactId
2040 public static function mergeContacts($mainContactId, $otherContactId) {
2041 self
::mergeCases($mainContactId, NULL, $otherContactId);
2045 * Function perform two task.
2046 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2047 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2049 * @param int $mainContactId
2050 * Contact id of main contact record.
2051 * @param int $mainCaseId
2052 * Case id of main case record.
2053 * @param int $otherContactId
2054 * Contact id of record which is going to merge.
2055 * @param int $otherCaseId
2056 * Case id of record which is going to merge.
2058 * @param bool $changeClient
2062 public static function mergeCases(
2063 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2064 $otherCaseId = NULL, $changeClient = FALSE) {
2065 $moveToTrash = TRUE;
2067 $duplicateContacts = FALSE;
2068 if ($mainContactId && $otherContactId &&
2069 $mainContactId != $otherContactId
2071 $duplicateContacts = TRUE;
2074 $duplicateCases = FALSE;
2075 if ($mainCaseId && $otherCaseId &&
2076 $mainCaseId != $otherCaseId
2078 $duplicateCases = TRUE;
2081 $mainCaseIds = array();
2082 if (!$duplicateContacts && !$duplicateCases) {
2083 return $mainCaseIds;
2086 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2087 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2088 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2089 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2090 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2091 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2093 $processCaseIds = array($otherCaseId);
2094 if ($duplicateContacts && !$duplicateCases) {
2095 if ($changeClient) {
2096 $processCaseIds = array($mainCaseId);
2099 //get all case ids for other contact.
2100 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2102 if (!is_array($processCaseIds)) {
2107 $session = CRM_Core_Session
::singleton();
2108 $currentUserId = $session->get('userID');
2110 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2112 // copy all cases and connect to main contact id.
2113 foreach ($processCaseIds as $otherCaseId) {
2114 if ($duplicateContacts) {
2115 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2116 $mainCaseId = $mainCase->id
;
2121 // CRM-11662 Copy Case custom data
2122 $extends = array('case');
2123 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2125 foreach ($groupTree as $groupID => $group) {
2126 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2127 foreach ($group['fields'] as $fieldID => $field) {
2128 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2132 foreach ($table as $tableName => $tableColumns) {
2133 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2134 $tableColumns[0] = $mainCaseId;
2135 $select = 'SELECT ' . implode(', ', $tableColumns);
2136 $from = ' FROM ' . $tableName;
2137 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2138 $query = $insert . $select . $from . $where;
2139 $dao = CRM_Core_DAO
::executeQuery($query);
2145 $mainCaseIds[] = $mainCaseId;
2146 //insert record for case contact.
2147 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2148 $otherCaseContact->case_id
= $otherCaseId;
2149 $otherCaseContact->find();
2150 while ($otherCaseContact->fetch()) {
2151 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2152 $mainCaseContact->case_id
= $mainCaseId;
2153 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2154 if ($mainCaseContact->contact_id
== $otherContactId) {
2155 $mainCaseContact->contact_id
= $mainContactId;
2157 //avoid duplicate object.
2158 if (!$mainCaseContact->find(TRUE)) {
2159 $mainCaseContact->save();
2161 $mainCaseContact->free();
2163 $otherCaseContact->free();
2165 elseif (!$otherContactId) {
2166 $otherContactId = $mainContactId;
2169 if (!$mainCaseId ||
!$otherCaseId ||
2170 !$mainContactId ||
!$otherContactId
2175 // get all activities for other case.
2176 $otherCaseActivities = array();
2177 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2179 //for duplicate cases do not process singleton activities.
2180 $otherActivityIds = $singletonActivityIds = array();
2181 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2182 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2183 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2186 $otherActivityIds[] = $otherActId;
2188 if ($duplicateCases) {
2189 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2192 FROM civicrm_activity
2193 WHERE activity_type_id = $openCaseType
2194 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2195 $dao = CRM_Core_DAO
::executeQuery($sql);
2196 while ($dao->fetch()) {
2197 $singletonActivityIds[] = $dao->id
;
2203 // migrate all activities and connect to main contact.
2204 $copiedActivityIds = $activityMappingIds = array();
2205 sort($otherActivityIds);
2206 foreach ($otherActivityIds as $otherActivityId) {
2208 //for duplicate cases -
2209 //do not migrate singleton activities.
2210 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2214 //migrate activity record.
2215 $otherActivity = new CRM_Activity_DAO_Activity();
2216 $otherActivity->id
= $otherActivityId;
2217 if (!$otherActivity->find(TRUE)) {
2221 $mainActVals = array();
2222 $mainActivity = new CRM_Activity_DAO_Activity();
2223 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2224 $mainActivity->copyValues($mainActVals);
2225 $mainActivity->id
= NULL;
2226 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2227 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2231 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2235 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2238 $mainActivity->save();
2239 $mainActivityId = $mainActivity->id
;
2240 if (!$mainActivityId) {
2244 $activityMappingIds[$otherActivityId] = $mainActivityId;
2245 // insert log of all activities
2246 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2248 $otherActivity->free();
2249 $mainActivity->free();
2250 $copiedActivityIds[] = $otherActivityId;
2252 //create case activity record.
2253 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2254 $mainCaseActivity->case_id
= $mainCaseId;
2255 $mainCaseActivity->activity_id
= $mainActivityId;
2256 $mainCaseActivity->save();
2257 $mainCaseActivity->free();
2259 //migrate source activity.
2260 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2261 $otherSourceActivity->activity_id
= $otherActivityId;
2262 $otherSourceActivity->record_type_id
= $sourceID;
2263 $otherSourceActivity->find();
2264 while ($otherSourceActivity->fetch()) {
2265 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2266 $mainActivitySource->record_type_id
= $sourceID;
2267 $mainActivitySource->activity_id
= $mainActivityId;
2268 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2269 if ($mainActivitySource->contact_id
== $otherContactId) {
2270 $mainActivitySource->contact_id
= $mainContactId;
2272 //avoid duplicate object.
2273 if (!$mainActivitySource->find(TRUE)) {
2274 $mainActivitySource->save();
2276 $mainActivitySource->free();
2278 $otherSourceActivity->free();
2280 //migrate target activities.
2281 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2282 $otherTargetActivity->activity_id
= $otherActivityId;
2283 $otherTargetActivity->record_type_id
= $targetID;
2284 $otherTargetActivity->find();
2285 while ($otherTargetActivity->fetch()) {
2286 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2287 $mainActivityTarget->record_type_id
= $targetID;
2288 $mainActivityTarget->activity_id
= $mainActivityId;
2289 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2290 if ($mainActivityTarget->contact_id
== $otherContactId) {
2291 $mainActivityTarget->contact_id
= $mainContactId;
2293 //avoid duplicate object.
2294 if (!$mainActivityTarget->find(TRUE)) {
2295 $mainActivityTarget->save();
2297 $mainActivityTarget->free();
2299 $otherTargetActivity->free();
2301 //migrate assignee activities.
2302 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2303 $otherAssigneeActivity->activity_id
= $otherActivityId;
2304 $otherAssigneeActivity->record_type_id
= $assigneeID;
2305 $otherAssigneeActivity->find();
2306 while ($otherAssigneeActivity->fetch()) {
2307 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2308 $mainAssigneeActivity->activity_id
= $mainActivityId;
2309 $mainAssigneeActivity->record_type_id
= $assigneeID;
2310 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2311 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2312 $mainAssigneeActivity->contact_id
= $mainContactId;
2314 //avoid duplicate object.
2315 if (!$mainAssigneeActivity->find(TRUE)) {
2316 $mainAssigneeActivity->save();
2318 $mainAssigneeActivity->free();
2320 $otherAssigneeActivity->free();
2322 // copy custom fields and attachments
2324 'activityID' => $otherActivityId,
2325 'mainActivityId' => $mainActivityId,
2327 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2330 //copy case relationship.
2331 if ($duplicateContacts) {
2332 //migrate relationship records.
2333 $otherRelationship = new CRM_Contact_DAO_Relationship();
2334 $otherRelationship->case_id
= $otherCaseId;
2335 $otherRelationship->find();
2336 $otherRelationshipIds = array();
2337 while ($otherRelationship->fetch()) {
2338 $otherRelVals = array();
2339 $updateOtherRel = FALSE;
2340 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2342 $mainRelationship = new CRM_Contact_DAO_Relationship();
2343 $mainRelationship->copyValues($otherRelVals);
2344 $mainRelationship->id
= NULL;
2345 $mainRelationship->case_id
= $mainCaseId;
2346 if ($mainRelationship->contact_id_a
== $otherContactId) {
2347 $updateOtherRel = TRUE;
2348 $mainRelationship->contact_id_a
= $mainContactId;
2351 //case creator change only when we merge user contact.
2352 if ($mainRelationship->contact_id_b
== $otherContactId) {
2353 //do not change creator for change client.
2354 if (!$changeClient) {
2355 $updateOtherRel = TRUE;
2356 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2359 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2360 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2362 //avoid duplicate object.
2363 if (!$mainRelationship->find(TRUE)) {
2364 $mainRelationship->save();
2366 $mainRelationship->free();
2368 //get the other relationship ids to update end date.
2369 if ($updateOtherRel) {
2370 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2373 $otherRelationship->free();
2375 //update other relationships end dates
2376 if (!empty($otherRelationshipIds)) {
2377 $sql = 'UPDATE civicrm_relationship
2378 SET end_date = CURDATE()
2379 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2380 CRM_Core_DAO
::executeQuery($sql);
2384 //move other case to trash.
2385 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2390 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2391 if ($changeClient) {
2392 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2393 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2395 $mergeActType = array_search('Reassigned Case', $activityTypes);
2396 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2399 2 => $otherContactDisplayName,
2400 3 => $mainContactDisplayName,
2405 elseif ($duplicateContacts) {
2406 $mergeActType = array_search('Merge Case', $activityTypes);
2407 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2410 2 => $otherContactId,
2411 3 => $mainContactId,
2417 $mergeActType = array_search('Merge Case', $activityTypes);
2418 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2419 if (!empty($copiedActivityIds)) {
2421 SELECT id, subject, activity_date_time, activity_type_id
2422 FROM civicrm_activity
2423 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2424 $dao = CRM_Core_DAO
::executeQuery($sql);
2425 while ($dao->fetch()) {
2426 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2427 if ($dao->subject
) {
2428 $mergeActSubjectDetails .= " :: {$dao->subject}";
2430 $mergeActSubjectDetails .= "<br />";
2435 //Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2436 $activityParams = array(
2437 'subject' => $mergeActSubject,
2438 'details' => $mergeActSubjectDetails,
2439 'status_id' => array_search('Completed', $activityStatuses),
2440 'activity_type_id' => $mergeActType,
2441 'source_contact_id' => $currentUserId,
2442 'activity_date_time' => date('YmdHis'),
2445 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2446 $mergeActivityId = $mergeActivity->id
;
2447 if (!$mergeActivityId) {
2450 $mergeActivity->free();
2452 //connect merge activity to case.
2453 $mergeCaseAct = array(
2454 'case_id' => $mainCaseId,
2455 'activity_id' => $mergeActivityId,
2458 self
::processCaseActivity($mergeCaseAct);
2461 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2463 return $mainCaseIds;
2467 * Validate contact permission for
2468 * edit/view on activity record and build links.
2470 * @param array $tplParams
2471 * Params to be sent to template for sending email.
2472 * @param array $activityParams
2473 * Info of the activity.
2475 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2476 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2477 'activity_type_id', 'id'
2480 if (!empty($tplParams['isCaseActivity'])) {
2481 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2482 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2485 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2486 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2489 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2490 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2494 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2495 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2498 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2499 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2505 * Validate contact permission for
2506 * given operation on activity record.
2508 * @param int $activityId
2509 * Activity record id.
2510 * @param string $operation
2512 * @param int $actTypeId
2514 * @param int $contactId
2515 * Contact id/if not pass consider logged in.
2516 * @param bool $checkComponent
2517 * Do we need to check component enabled.
2521 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2523 if (!$actTypeId && $activityId) {
2524 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2527 if (!$activityId ||
!$operation ||
!$actTypeId) {
2531 //do check for civicase component enabled.
2532 if ($checkComponent && !self
::enabled()) {
2536 //do check for cases.
2537 $caseActOperations = array(
2544 if (in_array($operation, $caseActOperations)) {
2546 if (!isset($caseCount)) {
2548 $caseCount = civicrm_api3('Case', 'getcount', array(
2549 'check_permissions' => TRUE,
2550 'status_id' => array('!=' => 'Closed'),
2552 'end_date' => array('IS NULL' => 1),
2555 catch (CiviCRM_API3_Exception
$e) {
2556 // Lack of permissions will throw an exception
2560 if ($operation == 'File On Case') {
2561 $allow = !empty($caseCount);
2564 $allow = ($caseCount > 1);
2568 $actionOperations = array('view', 'edit', 'delete');
2569 if (in_array($operation, $actionOperations)) {
2571 //do cache when user has non/supper permission.
2572 static $allowOperations;
2574 if (!is_array($allowOperations) ||
2575 !array_key_exists($operation, $allowOperations)
2579 $session = CRM_Core_Session
::singleton();
2580 $contactId = $session->get('userID');
2583 //check for permissions.
2584 $permissions = array(
2586 'access my cases and activities',
2587 'access all cases and activities',
2590 'access my cases and activities',
2591 'access all cases and activities',
2593 'delete' => array('delete activities'),
2596 //check for core permission.
2597 $hasPermissions = array();
2598 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2599 if (is_array($checkPermissions)) {
2600 foreach ($checkPermissions as $per) {
2601 if (CRM_Core_Permission
::check($per)) {
2602 $hasPermissions[$operation][] = $per;
2608 if (!empty($hasPermissions)) {
2609 //need to check activity object specific.
2610 if (in_array($operation, array(
2615 //do we have supper permission.
2616 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2617 $allowOperations[$operation] = $allow = TRUE;
2620 //user has only access to my cases and activity.
2621 //here object specific permmions come in picture.
2623 //edit - contact must be source or assignee
2624 //view - contact must be source/assignee/target
2625 $isTarget = $isAssignee = $isSource = FALSE;
2626 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2627 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2628 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2629 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2631 $target = new CRM_Activity_DAO_ActivityContact();
2632 $target->record_type_id
= $targetID;
2633 $target->activity_id
= $activityId;
2634 $target->contact_id
= $contactId;
2635 if ($target->find(TRUE)) {
2639 $assignee = new CRM_Activity_DAO_ActivityContact();
2640 $assignee->activity_id
= $activityId;
2641 $assignee->record_type_id
= $assigneeID;
2642 $assignee->contact_id
= $contactId;
2643 if ($assignee->find(TRUE)) {
2647 $source = new CRM_Activity_DAO_ActivityContact();
2648 $source->activity_id
= $activityId;
2649 $source->record_type_id
= $sourceID;
2650 $source->contact_id
= $contactId;
2651 if ($source->find(TRUE)) {
2655 if ($operation == 'edit') {
2656 if ($isAssignee ||
$isSource) {
2660 if ($operation == 'view') {
2661 if ($isTarget ||
$isAssignee ||
$isSource) {
2667 elseif (is_array($hasPermissions[$operation])) {
2668 $allowOperations[$operation] = $allow = TRUE;
2672 //contact do not have permission.
2673 $allowOperations[$operation] = FALSE;
2678 //here contact might have supper/non permission.
2679 $allow = $allowOperations[$operation];
2683 //do further only when operation is granted.
2685 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2687 //get the activity type name.
2688 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2690 //do not allow multiple copy / edit action.
2691 $singletonNames = array(
2701 //do not allow to delete these activities, CRM-4543
2702 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2704 //allow edit operation.
2705 $allowEditNames = array('Open Case');
2707 // do not allow File on Case
2708 $doNotFileNames = array(
2711 'Change Case Status',
2712 'Change Case Start Date',
2719 if (in_array($actTypeName, $singletonNames)) {
2721 if ($operation == 'File On Case') {
2722 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2724 if (in_array($operation, $actionOperations)) {
2726 if ($operation == 'edit') {
2727 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2729 elseif ($operation == 'delete') {
2730 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2734 if ($allow && ($operation == 'delete') &&
2735 in_array($actTypeName, $doNotDeleteNames)
2740 if ($allow && ($operation == 'File On Case') &&
2741 in_array($actTypeName, $doNotFileNames)
2746 //check settings file for masking actions
2747 //on the basis the activity types
2748 //hide Edit link if activity type is NOT editable
2749 //(special case activities).CRM-5871
2750 if ($allow && in_array($operation, $actionOperations)) {
2751 static $actionFilter = array();
2752 if (!array_key_exists($operation, $actionFilter)) {
2753 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2754 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2756 if (array_key_exists($operation, $actionFilter[$operation]) &&
2757 in_array($actTypeId, $actionFilter[$operation][$operation])
2768 * Since we drop 'access CiviCase', allow access
2769 * if user has 'access my cases and activities'
2770 * or 'access all cases and activities'
2772 public static function accessCiviCase() {
2773 if (!self
::enabled()) {
2777 if (CRM_Core_Permission
::check('access my cases and activities') ||
2778 CRM_Core_Permission
::check('access all cases and activities')
2787 * Verify user has permission to access a case.
2789 * @param int $caseId
2790 * @param bool $denyClosed
2791 * Set TRUE if one wants closed cases to be treated as inaccessible.
2795 public static function accessCase($caseId, $denyClosed = TRUE) {
2796 if (!$caseId ||
!self
::enabled()) {
2800 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2801 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2802 $params['status_id'] = array('!=' => 'Closed');
2805 return (bool) civicrm_api3('Case', 'getcount', $params);
2807 catch (CiviCRM_API3_Exception
$e) {
2808 // Lack of permissions will throw an exception
2814 * Check whether activity is a case Activity.
2816 * @param int $activityID
2821 public static function isCaseActivity($activityID) {
2822 $isCaseActivity = FALSE;
2824 $params = array(1 => array($activityID, 'Integer'));
2825 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2826 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2827 $isCaseActivity = TRUE;
2831 return $isCaseActivity;
2835 * Get all the case type ids currently in use.
2839 public static function getUsedCaseType() {
2840 static $caseTypeIds;
2842 if (!is_array($caseTypeIds)) {
2843 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2845 $dao = CRM_Core_DAO
::executeQuery($query);
2846 $caseTypeIds = array();
2847 while ($dao->fetch()) {
2848 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2851 $caseTypeIds[] = $typeId[1];
2855 return $caseTypeIds;
2859 * Get all the case status ids currently in use.
2863 public static function getUsedCaseStatuses() {
2864 static $caseStatusIds;
2866 if (!is_array($caseStatusIds)) {
2867 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2869 $dao = CRM_Core_DAO
::executeQuery($query);
2870 $caseStatusIds = array();
2871 while ($dao->fetch()) {
2872 $caseStatusIds[] = $dao->status_id
;
2876 return $caseStatusIds;
2880 * Get all the encounter medium ids currently in use.
2884 public static function getUsedEncounterMediums() {
2887 if (!is_array($mediumIds)) {
2888 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2890 $dao = CRM_Core_DAO
::executeQuery($query);
2891 $mediumIds = array();
2892 while ($dao->fetch()) {
2893 $mediumIds[] = $dao->medium_id
;
2901 * Check case configuration.
2903 * @param int $contactId
2907 public static function isCaseConfigured($contactId = NULL) {
2908 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2910 //lets check for case configured.
2911 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2912 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2913 if (!$configured['configured']) {
2914 //do check for case type and case status.
2915 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2916 if (!empty($caseTypes)) {
2917 $configured['configured'] = TRUE;
2918 if (!$configured['configured']) {
2919 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2920 if (!empty($caseStatuses)) {
2921 $configured['configured'] = TRUE;
2926 if ($configured['configured']) {
2927 //do check for active case type and case status.
2928 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2929 if (!empty($caseTypes)) {
2930 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2931 if (!empty($caseStatuses)) {
2932 $configured['allowToAddNewCase'] = TRUE;
2936 //do we need to redirect user to case admin.
2937 if (!$configured['allowToAddNewCase'] && $contactId) {
2938 //check for current contact case count.
2939 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2940 //redirect user to case admin page.
2941 if (!$currentContatCasesCount) {
2942 $configured['redirectToCaseAdmin'] = TRUE;
2951 * Used during case component enablement and during ugprade.
2955 public static function createCaseViews() {
2956 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2957 $dao = new CRM_Core_DAO();
2959 $sql = self
::createCaseViewsQuery('upcoming');
2961 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2965 // Above error doesn't get caught?
2966 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2967 if (is_null($doublecheck)) {
2971 $sql = self
::createCaseViewsQuery('recent');
2973 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2977 // Above error doesn't get caught?
2978 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
2979 if (is_null($doublecheck)) {
2987 * Helper function, also used by the upgrade in case of error
2989 * @param string $section
2993 public static function createCaseViewsQuery($section = 'upcoming') {
2995 $scheduled_id = CRM_Core_Pseudoconstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
2998 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
2999 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3000 FROM civicrm_case_activity ca
3001 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3002 WHERE a.activity_date_time =
3003 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3004 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3005 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3006 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
3007 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
3011 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3012 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3013 FROM civicrm_case_activity ca
3014 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3015 WHERE a.activity_date_time =
3016 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3017 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3018 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3019 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
3020 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
3027 * Add/copy relationships, when new client is added for a case
3029 * @param int $caseId
3031 * @param int $contactId
3032 * Contact id / new client id.
3034 public static function addCaseRelationships($caseId, $contactId) {
3035 // get the case role / relationships for the case
3036 $caseRelationships = new CRM_Contact_DAO_Relationship();
3037 $caseRelationships->case_id
= $caseId;
3038 $caseRelationships->find();
3039 $relationshipTypes = array();
3041 // make sure we don't add duplicate relationships of same relationship type.
3042 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3044 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3046 // add relationship for new client.
3047 $newRelationship = new CRM_Contact_DAO_Relationship();
3048 $newRelationship->copyValues($values);
3049 $newRelationship->id
= NULL;
3050 $newRelationship->case_id
= $caseId;
3051 $newRelationship->contact_id_a
= $contactId;
3052 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3053 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3055 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3056 if (!$newRelationship->find(TRUE)) {
3057 $newRelationship->save();
3059 $newRelationship->free();
3061 // store relationship type of newly created relationship
3062 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3067 * Get the list of clients for a case.
3069 * @param int $caseId
3072 * associated array with client ids
3074 public static function getCaseClients($caseId) {
3076 $caseContact = new CRM_Case_DAO_CaseContact();
3077 $caseContact->case_id
= $caseId;
3078 $caseContact->orderBy('id');
3079 $caseContact->find();
3081 while ($caseContact->fetch()) {
3082 $clients[] = $caseContact->contact_id
;
3089 * @param int $caseId
3090 * @param string $direction
3092 * @param int $relTypeId
3093 * @throws \CRM_Core_Exception
3094 * @throws \CiviCRM_API3_Exception
3096 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3098 if ($direction !== 'a' && $direction !== 'b') {
3099 throw new CRM_Core_Exception('Invalid relationship direction');
3102 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3103 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3104 $dao = CRM_Core_DAO
::executeQuery($sql, array(
3105 1 => array($caseId, 'Positive'),
3106 2 => array($cid, 'Positive'),
3107 3 => array($relTypeId, 'Positive'),
3109 while ($dao->fetch()) {
3110 civicrm_api3('relationship', 'create', array(
3113 'end_date' => 'now',
3119 * Get options for a given case field.
3120 * @see CRM_Core_DAO::buildOptions
3122 * @param string $fieldName
3123 * @param string $context
3124 * @see CRM_Core_DAO::buildOptionsContext
3125 * @param array $props
3126 * Whatever is known about this dao object.
3128 * @return array|bool
3130 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3131 $className = __CLASS__
;
3133 switch ($fieldName) {
3134 // This field is not part of this object but the api supports it
3136 $className = 'CRM_Activity_BAO_Activity';
3139 // Filter status id by case type id
3141 if (!empty($props['case_type_id'])) {
3142 $idField = is_numeric($props['case_type_id']) ?
'id' : 'name';
3143 $caseType = civicrm_api3('CaseType', 'getsingle', array($idField => $props['case_type_id'], 'return' => 'definition'));
3144 if (!empty($caseType['definition']['statuses'])) {
3145 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
3150 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3156 public function addSelectWhereClause() {
3157 // We always return an array with these keys, even if they are empty,
3158 // because this tells the query builder that we have considered these fields for acls
3161 // Only case admins can view deleted cases
3162 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
array() : array("= 0"),
3164 // Ensure the user has permission to view the case client
3165 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3166 if ($contactClause) {
3167 $contactClause = implode(' AND contact_id ', $contactClause);
3168 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3170 // The api gatekeeper ensures the user has at least "access my cases and activities"
3171 // so if they do not have permission to see all cases we'll assume they can only access their own
3172 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3173 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3174 $clauses['id'][] = "IN (
3175 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 (
3176 (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)
3180 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3185 * CRM-20308: Method to get the contact id to use as from contact for email copy
3186 * 1. Activity Added by Contact's email address
3187 * 2. System Default From Address
3188 * 3. Default Organization Contact email address
3191 * @param int $activityID
3193 * @return mixed $emailFromContactId
3194 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3196 public static function getReceiptFrom($activityID) {
3197 $name = $address = NULL;
3199 if (!empty($activityID)) {
3200 // There is always a 'Added by' contact for a activity,
3201 // so we can safely use ActivityContact.Getvalue API
3202 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', array(
3203 'activity_id' => $activityID,
3204 'record_type_id' => 'Activity Source',
3205 'return' => 'contact_id',
3207 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3210 // If 'From' email address not found for Source Activity Contact then
3211 // fetch the email from domain or logged in user.
3212 if (empty($address)) {
3213 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3216 return "$name <$address>";