3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
35 * This class contains the functions for Case Management.
37 class CRM_Case_BAO_Case
extends CRM_Case_DAO_Case
{
40 * Static field for all the case information that we can potentially export.
44 static $_exportableFields = NULL;
49 public function __construct() {
50 parent
::__construct();
54 * Is CiviCase enabled?
58 public static function enabled() {
59 $config = CRM_Core_Config
::singleton();
60 return in_array('CiviCase', $config->enableComponents
);
64 * Create a case object.
66 * The function extracts all the params it needs to initialize the create a
67 * case object. the params array could contain additional unused name/value
70 * @param array $params
71 * (reference ) an assoc array of name/value pairs.
73 * @return CRM_Case_BAO_Case
75 public static function add(&$params) {
76 $caseDAO = new CRM_Case_DAO_Case();
77 $caseDAO->copyValues($params);
78 $result = $caseDAO->save();
79 $caseDAO->find(TRUE); // Get other case values (required by XML processor), this adds to $result array
84 * Takes an associative array and creates a case object.
86 * @param array $params
87 * (reference) an assoc array of name/value pairs.
89 * @return CRM_Case_BAO_Case
91 public static function &create(&$params) {
92 $transaction = new CRM_Core_Transaction();
94 if (!empty($params['id'])) {
95 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
98 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
101 $case = self
::add($params);
103 if (!empty($params['custom']) &&
104 is_array($params['custom'])
106 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
109 if (is_a($case, 'CRM_Core_Error')) {
110 $transaction->rollback();
114 if (!empty($params['id'])) {
115 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
118 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
120 $transaction->commit();
122 //we are not creating log for case
123 //since case log can be tracked using log for activity.
128 * Process case activity add/delete
129 * takes an associative array and
131 * @param array $params
132 * (reference ) an assoc array of name/value pairs.
135 public static function processCaseActivity(&$params) {
136 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
137 $caseActivityDAO->activity_id
= $params['activity_id'];
138 $caseActivityDAO->case_id
= $params['case_id'];
140 $caseActivityDAO->find(TRUE);
141 $caseActivityDAO->save();
145 * Get the case subject for Activity.
147 * @param int $activityId
150 * @return string|null
152 public static function getCaseSubject($activityId) {
153 $caseActivity = new CRM_Case_DAO_CaseActivity();
154 $caseActivity->activity_id
= $activityId;
155 if ($caseActivity->find(TRUE)) {
156 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
165 * @param string $colName
170 public static function getCaseType($caseId, $colName = 'title') {
172 SELECT civicrm_case_type.{$colName} FROM civicrm_case
173 LEFT JOIN civicrm_case_type ON
174 civicrm_case.case_type_id = civicrm_case_type.id
175 WHERE civicrm_case.id = %1";
177 $queryParams = array(1 => array($caseId, 'Integer'));
179 return CRM_Core_DAO
::singleValueQuery($query, $queryParams);
183 * Delete the record that are associated with this case.
184 * record are deleted from case
187 * Id of the case to delete.
189 * @param bool $moveToTrash
194 public static function deleteCase($caseId, $moveToTrash = FALSE) {
195 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
198 $activities = self
::getCaseActivityDates($caseId);
200 foreach ($activities as $value) {
201 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
206 $transaction = new CRM_Core_Transaction();
208 $case = new CRM_Case_DAO_Case();
211 $result = $case->delete();
212 $transaction->commit();
215 $result = $case->is_deleted
= 1;
220 // CRM-7364, disable relationships
221 self
::enableDisableCaseRelationships($caseId, FALSE);
223 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
225 // remove case from recent items.
230 CRM_Utils_Recent
::del($caseRecent);
238 * Enable disable case related relationships.
242 * @param bool $enable
245 public static function enableDisableCaseRelationships($caseId, $enable) {
246 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
247 if (!empty($contactIds)) {
248 foreach ($contactIds as $cid) {
249 $roles = self
::getCaseRoles($cid, $caseId);
250 if (!empty($roles)) {
251 $relationshipIds = implode(',', array_keys($roles));
252 $enable = (int) $enable;
253 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
254 WHERE id IN ( {$relationshipIds} )";
255 CRM_Core_DAO
::executeQuery($query);
262 * Retrieve contact_id by case_id.
267 * @param int $contactID
271 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL) {
272 $caseContact = new CRM_Case_DAO_CaseContact();
273 $caseContact->case_id
= $caseId;
274 $caseContact->find();
275 $contactArray = array();
276 // FIXME: Why does this return a 1-based array?
278 while ($caseContact->fetch()) {
279 if ($contactID != $caseContact->contact_id
) {
280 $contactArray[$count] = $caseContact->contact_id
;
285 return $contactArray;
289 * Look up a case using an activity ID.
291 * @param int $activityId
293 * @return int, case ID
295 public static function getCaseIdByActivityId($activityId) {
296 $originalId = CRM_Core_DAO
::singleValueQuery(
297 'SELECT original_id FROM civicrm_activity WHERE id = %1',
298 array('1' => array($activityId, 'Integer'))
300 $caseId = CRM_Core_DAO
::singleValueQuery(
301 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
303 '1' => array($activityId, 'Integer'),
304 '2' => array($originalId ?
$originalId : $activityId, 'Integer'),
311 * Retrieve contact names by caseId.
318 public static function getContactNames($caseId) {
319 $contactNames = array();
321 return $contactNames;
325 SELECT contact_a.sort_name name,
326 contact_a.display_name as display_name,
328 contact_a.birth_date as birth_date,
331 FROM civicrm_contact contact_a
332 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
333 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
334 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
335 WHERE civicrm_case_contact.case_id = %1
336 ORDER BY civicrm_case_contact.id";
338 $dao = CRM_Core_DAO
::executeQuery($query,
339 array(1 => array($caseId, 'Integer'))
341 while ($dao->fetch()) {
342 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
343 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
344 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
345 $contactNames[$dao->cid
]['email'] = $dao->email
;
346 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
347 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
348 $contactNames[$dao->cid
]['role'] = ts('Client');
351 return $contactNames;
355 * Retrieve case_id by contact_id.
357 * @param int $contactID
358 * @param bool $includeDeleted
359 * Include the deleted cases in result.
360 * @param null $caseType
364 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
367 FROM civicrm_case_contact cc
368 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
370 if (isset($caseType)) {
372 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
373 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
375 if (!isset($caseType)) {
376 $query .= "WHERE cc.contact_id = %1";
378 if (!$includeDeleted) {
379 $query .= " AND ca.is_deleted = 0";
382 $params = array(1 => array($contactID, 'Integer'));
383 $dao = CRM_Core_DAO
::executeQuery($query, $params);
385 $caseArray = array();
386 while ($dao->fetch()) {
387 $caseArray[] = $dao->id
;
395 * @param string $type
397 * @param string $condition
401 public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL) {
403 $session = CRM_Core_Session
::singleton();
404 $userID = $session->get('userID');
408 civicrm_case.id as case_id,
409 civicrm_case.subject as case_subject,
410 civicrm_contact.id as contact_id,
411 civicrm_contact.sort_name as sort_name,
412 civicrm_phone.phone as phone,
413 civicrm_contact.contact_type as contact_type,
414 civicrm_contact.contact_sub_type as contact_sub_type,
415 t_act.activity_type_id,
416 c_type.title as case_type,
417 civicrm_case.case_type_id as case_type_id,
418 cov_status.label as case_status,
419 cov_status.label as case_status_name,
421 civicrm_case.start_date as case_start_date,
422 case_relation_type.label_b_a as case_role, ";
424 if ($type == 'upcoming') {
426 t_act.desired_date as case_scheduled_activity_date,
427 t_act.id as case_scheduled_activity_id,
428 t_act.act_type_name as case_scheduled_activity_type_name,
429 t_act.act_type AS case_scheduled_activity_type ";
431 elseif ($type == 'recent') {
433 t_act.desired_date as case_recent_activity_date,
434 t_act.id as case_recent_activity_id,
435 t_act.act_type_name as case_recent_activity_type_name,
436 t_act.act_type AS case_recent_activity_type ";
438 elseif ($type == 'any') {
440 t_act.desired_date as case_activity_date,
441 t_act.id as case_activity_id,
442 t_act.act_type_name as case_activity_type_name,
443 t_act.act_type AS case_activity_type ";
446 $query .= " FROM civicrm_case
447 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
448 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
450 if ($type == 'upcoming') {
451 // This gets the earliest activity per case that's scheduled within 14 days from now.
452 // 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.
453 // In this case we don't really care which one, so min(id) works.
454 // optimized in CRM-11837
455 $query .= " INNER JOIN
457 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
462 FROM civicrm_view_case_activity_upcoming
463 ORDER BY activity_date_time ASC, id ASC
466 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
467 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
471 elseif ($type == 'recent') {
472 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
473 //improve query performance - CRM-10598
474 $query .= " INNER JOIN
476 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
481 FROM civicrm_view_case_activity_recent
482 ORDER BY activity_date_time DESC, id ASC
485 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
486 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
489 elseif ($type == 'any') {
490 $query .= " LEFT JOIN
492 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
493 FROM civicrm_activity act4
494 LEFT JOIN civicrm_case_activity ca4
495 ON ca4.activity_id = act4.id
496 AND act4.is_current_revision = 1
497 LEFT JOIN civicrm_option_group aog
498 ON aog.name='activity_type'
499 LEFT JOIN civicrm_option_value aov
500 ON aov.option_group_id = aog.id
501 AND aov.value = act4.activity_type_id
506 ON t_act.case_id = civicrm_case.id
507 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
508 LEFT JOIN civicrm_relationship case_relationship
509 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
510 AND case_relationship.case_id = civicrm_case.id )
512 LEFT JOIN civicrm_relationship_type case_relation_type
513 ON ( case_relation_type.id = case_relationship.relationship_type_id
514 AND case_relation_type.id = case_relationship.relationship_type_id )
516 LEFT JOIN civicrm_case_type c_type
517 ON civicrm_case.case_type_id = c_type.id
519 LEFT JOIN civicrm_option_group cog_status
520 ON cog_status.name = 'case_status'
522 LEFT JOIN civicrm_option_value cov_status
523 ON ( civicrm_case.status_id = cov_status.value
524 AND cog_status.id = cov_status.option_group_id )
528 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
529 $query .= " WHERE (1) $condition ";
532 if ($type == 'upcoming') {
533 $query .= " ORDER BY case_scheduled_activity_date ASC ";
535 elseif ($type == 'recent') {
536 $query .= " ORDER BY case_recent_activity_date ASC ";
538 elseif ($type == 'any') {
539 $query .= " ORDER BY case_activity_date ASC ";
546 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
548 * @param bool $allCases
552 * @param string $type
553 * /upcoming,recent,all/.
555 * @param string $context
560 public static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') {
562 $casesList = array();
564 //validate access for own cases.
565 if (!self
::accessCiviCase()) {
570 $session = CRM_Core_Session
::singleton();
571 $userID = $session->get('userID');
574 //validate access for all cases.
575 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
579 $condition = " AND civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1";
582 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
584 if ($type == 'upcoming' ||
$type == 'any') {
585 $closedId = CRM_Core_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
587 AND civicrm_case.status_id != $closedId";
590 $query = self
::getCaseActivityQuery($type, $userID, $condition);
592 $queryParams = array();
593 $result = CRM_Core_DAO
::executeQuery($query,
597 $caseStatus = CRM_Core_OptionGroup
::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
599 $resultFields = array(
616 if ($type == 'upcoming') {
617 $resultFields[] = 'case_scheduled_activity_date';
618 $resultFields[] = 'case_scheduled_activity_type_name';
619 $resultFields[] = 'case_scheduled_activity_type';
620 $resultFields[] = 'case_scheduled_activity_id';
622 elseif ($type == 'recent') {
623 $resultFields[] = 'case_recent_activity_date';
624 $resultFields[] = 'case_recent_activity_type_name';
625 $resultFields[] = 'case_recent_activity_type';
626 $resultFields[] = 'case_recent_activity_id';
628 elseif ($type == 'any') {
629 $resultFields[] = 'case_activity_date';
630 $resultFields[] = 'case_activity_type_name';
631 $resultFields[] = 'case_activity_type';
632 $resultFields[] = 'case_activity_id';
635 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
636 $actions = CRM_Case_Selector_Search
::links();
638 // check is the user has view/edit signer permission
639 $permissions = array(CRM_Core_Permission
::VIEW
);
640 if (CRM_Core_Permission
::check('access all cases and activities') ||
641 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
643 $permissions[] = CRM_Core_Permission
::EDIT
;
645 if (CRM_Core_Permission
::check('delete in CiviCase')) {
646 $permissions[] = CRM_Core_Permission
::DELETE
;
648 $mask = CRM_Core_Action
::mask($permissions);
650 while ($result->fetch()) {
651 foreach ($resultFields as $donCare => $field) {
652 $casesList[$result->case_id
][$field] = $result->$field;
653 if ($field == 'contact_type') {
654 $casesList[$result->case_id
]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
656 $casesList[$result->case_id
]['action'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
658 'id' => $result->case_id
,
659 'cid' => $result->contact_id
,
664 'case.actions.primary',
669 elseif ($field == 'case_status') {
670 if (in_array($result->$field, $caseStatus)) {
671 $casesList[$result->case_id
]['class'] = "status-urgent";
674 $casesList[$result->case_id
]['class'] = "status-normal";
679 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
680 $caseManagerContact = self
::getCaseManagerContact($caseTypes[$result->case_type_id
], $result->case_id
);
681 if (!empty($caseManagerContact)) {
682 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
683 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
686 //do check user permissions for edit/view activity.
687 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
688 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
690 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
692 $casesList[$result->case_id
]['activity_type_id'], $userID
694 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
696 $casesList[$result->case_id
]['activity_type_id'], $userID
705 * Get the summary of cases counts by type and status.
707 * @param bool $allCases
711 public static function getCasesSummary($allCases = TRUE, $userID) {
712 $caseSummary = array();
714 //validate access for civicase.
715 if (!self
::accessCiviCase()) {
719 //validate access for all cases.
720 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
724 $caseTypes = CRM_Case_PseudoConstant
::caseType();
725 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
726 $caseTypes = array_flip($caseTypes);
728 // get statuses as headers for the table
729 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
730 foreach ($caseStatuses as $key => $name) {
731 $caseSummary['headers'][$key]['status'] = $name;
732 $caseSummary['headers'][$key]['url'] = $url . $key;
735 // build rows with actual data
737 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
743 $myGroupByClause = ' GROUP BY civicrm_case.id';
748 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
749 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
751 $myGroupByClause .= ", case_status.label, status_id, case_type_id";
753 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
755 SELECT case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
756 case_type_id, case_relationship.contact_id_b
758 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
759 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
760 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
761 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
762 AND option_group_case_status.id = case_status.option_group_id )
763 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
764 AND case_relationship.contact_id_b = {$userID})
765 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
766 {$myCaseWhereClause} {$myGroupByClause}";
768 $res = CRM_Core_DAO
::executeQuery($query);
769 while ($res->fetch()) {
770 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
771 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
774 $rows[$res->case_type
][$res->case_status
] = array(
776 'url' => CRM_Utils_System
::url('civicrm/case/search',
777 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
782 $caseSummary['rows'] = array_merge($caseTypes, $rows);
790 * @param int $contactID
794 * @param int $relationshipID
797 * case role / relationships
800 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
802 SELECT rel.id as civicrm_relationship_id,
803 con.sort_name as sort_name,
804 civicrm_email.email as email,
805 civicrm_phone.phone as phone,
806 con.id as civicrm_contact_id,
807 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
808 civicrm_relationship_type.id as relation_type,
809 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
810 FROM civicrm_relationship rel
811 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
812 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))
813 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
814 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
815 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
816 AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
819 1 => array($contactID, 'Positive'),
820 2 => array($caseID, 'Positive'),
823 if ($relationshipID) {
824 $query .= ' AND civicrm_relationship.id = %3 ';
825 $params[3] = array($relationshipID, 'Integer');
827 $dao = CRM_Core_DAO
::executeQuery($query, $params);
830 while ($dao->fetch()) {
831 $rid = $dao->civicrm_relationship_id
;
832 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
833 $values[$rid]['relation'] = $dao->relation
;
834 $values[$rid]['name'] = $dao->sort_name
;
835 $values[$rid]['email'] = $dao->email
;
836 $values[$rid]['phone'] = $dao->phone
;
837 $values[$rid]['relation_type'] = $dao->relation_type
;
838 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
839 $values[$rid]['client_id'] = $contactID;
840 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
848 * Get Case Activities.
852 * @param array $params
854 * @param int $contactID
857 * @param null $context
862 * Array of case activities
865 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
868 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
869 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
870 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
871 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
873 // CRM-5081 - formatting the dates to omit seconds.
874 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
876 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
878 ca.activity_type_id AS type,
879 ca.activity_type_id AS activity_type_id,
880 tcc.sort_name AS target_contact_name,
881 tcc.id AS target_contact_id,
882 scc.sort_name AS source_contact_name,
883 scc.id AS source_contact_id,
884 acc.sort_name AS assignee_contact_name,
885 acc.id AS assignee_contact_id,
887 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
888 ca.activity_date_time,
889 DATE_ADD(NOW(), INTERVAL 1 YEAR)
890 ), '%Y%m%d%H%i00') AS overdue_date,
891 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
892 ca.status_id AS status,
893 ca.subject AS subject,
894 ca.is_deleted AS deleted,
895 ca.priority_id AS priority,
897 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
900 FROM civicrm_case_activity cca
901 INNER JOIN civicrm_activity ca
902 ON ca.id = cca.activity_id
903 INNER JOIN civicrm_activity_contact cas
904 ON cas.activity_id = ca.id
905 AND cas.record_type_id = {$sourceID}
906 INNER JOIN civicrm_contact scc
907 ON scc.id = cas.contact_id
908 LEFT JOIN civicrm_activity_contact caa
909 ON caa.activity_id = ca.id
910 AND caa.record_type_id = {$assigneeID}
911 LEFT JOIN civicrm_contact acc
912 ON acc.id = caa.contact_id
913 LEFT JOIN civicrm_activity_contact cat
914 ON cat.activity_id = ca.id
915 AND cat.record_type_id = {$targetID}
916 LEFT JOIN civicrm_contact tcc
917 ON tcc.id = cat.contact_id
918 INNER JOIN civicrm_option_group cog
919 ON cog.name = 'activity_type'
920 INNER JOIN civicrm_option_value cov
921 ON cov.option_group_id = cog.id
922 AND cov.value = ca.activity_type_id
923 AND cov.is_active = 1
924 LEFT JOIN civicrm_entity_file ef
925 ON ef.entity_table = 'civicrm_activity'
926 AND ef.entity_id = ca.id
927 LEFT OUTER JOIN civicrm_option_group og
928 ON og.name = 'activity_status'
929 LEFT OUTER JOIN civicrm_option_value ov
930 ON ov.option_group_id=og.id
931 AND ov.name = 'Scheduled'";
934 WHERE cca.case_id= %1
935 AND ca.is_current_revision = 1';
937 if (!empty($params['source_contact_id'])) {
939 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
942 if (!empty($params['status_id'])) {
944 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
947 if (!empty($params['activity_deleted'])) {
949 AND ca.is_deleted = 1";
953 AND ca.is_deleted = 0";
956 if (!empty($params['activity_type_id'])) {
958 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
961 if (!empty($params['activity_date_low'])) {
962 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
964 if (!empty($fromActivityDate)) {
966 AND ca.activity_date_time >= '{$fromActivityDate}'";
969 if (!empty($params['activity_date_high'])) {
970 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
971 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
973 if (!empty($toActivityDate)) {
975 AND ca.activity_date_time <= '{$toActivityDate}'";
979 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
981 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
983 // CRM-5081 - added id to act like creation date
985 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
988 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
989 $orderBy = " ORDER BY $sortBy ";
992 $page = CRM_Utils_Array
::value('page', $params);
993 $rp = CRM_Utils_Array
::value('rp', $params);
1001 $start = (($page - 1) * $rp);
1002 $limit = " LIMIT $start, $rp";
1004 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
1005 $queryParams = array(1 => array($caseID, 'Integer'));
1007 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
1008 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
1010 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1011 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus();
1013 $url = CRM_Utils_System
::url("civicrm/case/activity",
1014 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1018 if ($context == 'fulltext') {
1019 $contextUrl = "&context={$context}";
1021 $editUrl = "{$url}&action=update{$contextUrl}";
1022 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1023 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1024 $viewTitle = ts('View activity');
1026 $emailActivityTypeIDs = array(
1027 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1031 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1037 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1039 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1040 $compStatusValues = array();
1041 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1042 foreach ($compStatusNames as $name) {
1043 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1046 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=", FALSE, NULL, FALSE);
1047 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1048 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1051 $session = CRM_Core_Session
::singleton();
1052 $userID = $session->get('userID');
1055 $caseActivities = array();
1057 while ($dao->fetch()) {
1058 $caseActivity = array();
1059 $caseActivityId = $dao->id
;
1061 $allowView = self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID);
1062 $allowEdit = self
::checkPermission($caseActivityId, 'edit', $dao->activity_type_id
, $userID);
1063 $allowDelete = self
::checkPermission($caseActivityId, 'delete', $dao->activity_type_id
, $userID);
1065 //do not have sufficient permission
1066 //to access given case activity record.
1067 if (!$allowView && !$allowEdit && !$allowDelete) {
1071 $caseActivity['DT_RowId'] = $caseActivityId;
1072 //Add classes to the row, via DataTables syntax
1073 $caseActivity['DT_RowClass'] = "crm-entity status-id-$dao->status";
1075 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1076 $caseActivity['DT_RowClass'] .= " status-completed";
1079 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1080 $caseActivity['DT_RowClass'] .= " status-overdue";
1083 $caseActivity['DT_RowClass'] .= " status-scheduled";
1087 if (!empty($dao->priority
)) {
1088 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1089 $caseActivity['DT_RowClass'] .= " priority-urgent ";
1091 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1092 $caseActivity['DT_RowClass'] .= " priority-low ";
1096 //Add data to the row for inline editing, via DataTable syntax
1097 $caseActivity['DT_RowAttr'] = array();
1098 $caseActivity['DT_RowAttr']['data-entity'] = 'activity';
1099 $caseActivity['DT_RowAttr']['data-id'] = $caseActivityId;
1101 //Activity Date and Time
1102 $caseActivity['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1105 $caseActivity['subject'] = $dao->subject
;
1108 $caseActivity['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1109 . $activityTypes[$dao->type
]['label'];
1111 //Activity Target (With)
1112 $targetContact = '';
1113 if (isset($dao->target_contact_id
)) {
1114 $targetContact = $dao->target_contact_name
;
1115 if ($hasViewContact) {
1116 $targetContact = '<a href="' . $contactViewUrl . $dao->target_contact_id
. '">' . $dao->target_contact_name
. '</a>';
1119 $caseActivity['target_contact_name'] = $targetContact;
1121 //Activity Source Contact (Reporter)
1122 $sourceContact = $dao->source_contact_name
;
1123 if ($hasViewContact) {
1124 $sourceContact = '<a href="' . $contactViewUrl . $dao->source_contact_id
. '">' . $dao->source_contact_name
. '</a>';
1126 $caseActivity['source_contact_name'] = $sourceContact;
1128 //Activity Assignee. CRM-4485.
1129 $assigneeContact = '';
1130 if (isset($dao->assignee_contact_id
)) {
1131 $assigneeContact = $dao->assignee_contact_name
;
1132 if ($hasViewContact) {
1133 $assigneeContact = '<a href="' . $contactViewUrl . $dao->assignee_contact_id
. '">' . $dao->assignee_contact_name
. '</a>';
1136 $caseActivity['assignee_contact_name'] = $assigneeContact;
1139 $caseActivity['status_id'] = $activityStatuses[$dao->status
];
1141 // 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.
1143 $css = 'class="action-item crm-hover-button"';
1145 $viewUrl = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1146 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1148 $additionalUrl = "&id={$caseActivityId}";
1149 if (!$dao->deleted
) {
1150 //hide edit link of activity type email.CRM-4530.
1151 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1152 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1154 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1158 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1161 elseif (!$caseDeleted) {
1162 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1163 $caseActivity['status_id'] = $caseActivity['status_id'] . '<br /> (deleted)';
1166 //check for operations.
1167 if (self
::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id
)) {
1168 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1170 if (self
::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id
)) {
1171 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1173 // if there are file attachments we will return how many and, if only one, add a link to it
1174 if (!empty($dao->attachment_ids
)) {
1175 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1176 $caseActivity['no_attachments'] = count($attachmentIDs);
1177 $url .= implode(' ', CRM_Core_BAO_File
::paperIconAttachment('civicrm_activity', $caseActivityId));
1180 $caseActivity['links'] = $url;
1182 array_push($caseActivities, $caseActivity);
1186 $caseActivitiesDT = array();
1187 $caseActivitiesDT['data'] = $caseActivities;
1188 $caseActivitiesDT['recordsTotal'] = $caseCount;
1189 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1191 return $caseActivitiesDT;
1195 * Get Case Related Contacts.
1197 * @param int $caseID
1199 * @param bool $includeDetails
1200 * If true include details of contacts.
1203 * array of return properties
1206 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1207 $caseRoles = array();
1208 if ($includeDetails) {
1209 $caseInfo = civicrm_api3('Case', 'getsingle', array(
1211 // 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
1212 'return' => array('case_type_id', 'case_type_id.name', 'case_type_id.definition'),
1214 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1215 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1220 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
1221 FROM civicrm_relationship cr
1222 LEFT JOIN civicrm_relationship_type crt
1223 ON crt.id = cr.relationship_type_id
1224 LEFT JOIN civicrm_contact cc
1225 ON cc.id = cr.contact_id_b
1226 LEFT JOIN civicrm_email ce
1227 ON ce.contact_id = cc.id
1228 AND ce.is_primary= 1
1229 LEFT JOIN civicrm_phone cp
1230 ON cp.contact_id = cc.id
1231 AND cp.is_primary= 1
1232 WHERE cr.case_id = %1 AND cr.is_active AND cc.is_deleted <> 1';
1234 $params = array(1 => array($caseID, 'Integer'));
1235 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1237 while ($dao->fetch()) {
1238 if (!$includeDetails) {
1239 $values[$dao->id
] = 1;
1243 'contact_id' => $dao->id
,
1244 'display_name' => $dao->name
,
1245 'sort_name' => $dao->sort_name
,
1246 'relationship_type_id' => $dao->relationship_type_id
,
1247 'role' => $dao->role
,
1248 'email' => $dao->email
,
1249 'phone' => $dao->phone
,
1251 // Add more info about the role (creator, manager)
1252 $role = CRM_Utils_Array
::value($dao->name_b_a
, $caseRoles);
1254 unset($role['name']);
1257 $values[] = $details;
1266 * Send e-mail copy of activity
1268 * @param int $clientId
1269 * @param int $activityId
1271 * @param array $contacts
1272 * Array of related contact.
1274 * @param null $attachments
1275 * @param int $caseId
1277 * @return bool |array
1279 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1284 $tplParams = $activityInfo = array();
1285 //if its a case activity
1287 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1288 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1289 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1290 $anyActivity = TRUE;
1293 $anyActivity = FALSE;
1295 $tplParams['isCaseActivity'] = 1;
1296 $tplParams['client_id'] = $clientId;
1299 $anyActivity = TRUE;
1302 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1303 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1305 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1307 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1309 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1311 $tplParams['activity'] = $activityInfo;
1312 foreach ($tplParams['activity']['fields'] as $k => $val) {
1313 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1314 $activitySubject = $val['value'];
1318 $session = CRM_Core_Session
::singleton();
1319 // CRM-8926 If user is not logged in, use the activity creator as userID
1320 if (!($userID = $session->get('userID'))) {
1321 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1324 //also create activities simultaneously of this copy.
1325 $activityParams = array();
1327 $activityParams['source_record_id'] = $activityId;
1328 $activityParams['source_contact_id'] = $userID;
1329 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1330 $activityParams['activity_date_time'] = date('YmdHis');
1331 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1332 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1333 $activityParams['case_id'] = $caseId;
1334 $activityParams['is_auto'] = 0;
1335 $activityParams['target_id'] = $clientId;
1337 $tplParams['activitySubject'] = $activitySubject;
1339 // if it’s a case activity, add hashed id to the template (CRM-5916)
1341 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1345 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1346 $receiptFrom = self
::getReceiptFrom($activityId);
1348 $recordedActivityParams = array();
1350 foreach ($contacts as $mail => $info) {
1351 $tplParams['contact'] = $info;
1352 self
::buildPermissionLinks($tplParams, $activityParams);
1354 $displayName = CRM_Utils_Array
::value('display_name', $info);
1356 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1358 'groupName' => 'msg_tpl_workflow_case',
1359 'valueName' => 'case_activity',
1360 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1361 'tplParams' => $tplParams,
1362 'from' => $receiptFrom,
1363 'toName' => $displayName,
1365 'attachments' => $attachments,
1369 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1370 $activityParams['details'] = $message;
1372 if (!empty($result[$info['contact_id']])) {
1374 * Really only need to record one activity with all the targets combined.
1375 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1376 * but it's always the same content at the moment.
1378 if (empty($recordedActivityParams)) {
1379 $recordedActivityParams = $activityParams;
1382 $recordedActivityParams['subject'] .= "; $displayName";
1384 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1387 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1391 if (!empty($recordedActivityParams)) {
1392 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1394 //create case_activity record if its case activity.
1396 $caseParams = array(
1397 'activity_id' => $activity->id
,
1398 'case_id' => $caseId,
1400 self
::processCaseActivity($caseParams);
1408 * Retrieve count of activities having a particular type, and
1409 * associated with a particular case.
1411 * @param int $caseId
1413 * @param int $activityTypeId
1414 * ID of the activity type.
1418 public static function getCaseActivityCount($caseId, $activityTypeId) {
1419 $queryParam = array(
1420 1 => array($caseId, 'Integer'),
1421 2 => array($activityTypeId, 'Integer'),
1423 $query = "SELECT count(ca.id) as countact
1424 FROM civicrm_activity ca
1425 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1426 WHERE ca.activity_type_id = %2
1427 AND cca.case_id = %1
1428 AND ca.is_deleted = 0";
1430 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1431 if ($dao->fetch()) {
1432 return $dao->countact
;
1439 * Create an activity for a case via email.
1444 * @return array|void
1445 * $activity object of newly creted activity via email
1447 public static function recordActivityViaEmail($file) {
1448 if (!file_exists($file) ||
1451 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1456 $result = CRM_Utils_Mail_Incoming
::parse($file);
1457 if ($result['is_error']) {
1461 foreach ($result['to'] as $to) {
1464 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1465 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1467 if ($replacement !== $to['email']) {
1468 $caseId = $replacement;
1469 //if caseId is invalid, return as error file
1470 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1471 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1480 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1481 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1482 $contactDetails = self
::getRelatedContacts($caseId, FALSE);
1484 if (!empty($contactDetails[$result['from']['id']])) {
1486 $params['subject'] = $result['subject'];
1487 $params['activity_date_time'] = $result['date'];
1488 $params['details'] = $result['body'];
1489 $params['source_contact_id'] = $result['from']['id'];
1490 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
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_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
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_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1814 //if $relContactId is passed, role is added or modified.
1815 if (!empty($relContactId)) {
1816 $activityParams['assignee_contact_id'] = $assigneContactIds;
1818 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1824 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1830 $activityParams['activity_type_id'] = $activityTypeID;
1832 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1834 //create case_activity record.
1835 $caseParams = array(
1836 'activity_id' => $activity->id
,
1837 'case_id' => $caseId,
1840 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1845 * contact which is assigned a case role of case manager.
1847 * @param int $caseType
1849 * @param int $caseId
1853 * array of contact on success otherwise empty
1856 public static function getCaseManagerContact($caseType, $caseId) {
1857 if (!$caseType ||
!$caseId) {
1861 $caseManagerContact = array();
1862 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1864 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1866 if (!empty($managerRoleId)) {
1867 $managerRoleQuery = "
1868 SELECT civicrm_contact.id as casemanager_id,
1869 civicrm_contact.sort_name as casemanager
1870 FROM civicrm_contact
1871 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1872 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1873 WHERE civicrm_case.id = %2 AND is_active = 1";
1875 $managerRoleParams = array(
1876 1 => array($managerRoleId, 'Integer'),
1877 2 => array($caseId, 'Integer'),
1880 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1881 if ($dao->fetch()) {
1882 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1883 $caseManagerContact['casemanager'] = $dao->casemanager
;
1887 return $caseManagerContact;
1891 * @param int $contactId
1892 * @param bool $excludeDeleted
1896 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1897 $params = array('check_permissions' => TRUE);
1898 if ($excludeDeleted) {
1899 $params['is_deleted'] = 0;
1902 $params['contact_id'] = $contactId;
1905 return civicrm_api3('Case', 'getcount', $params);
1907 catch (CiviCRM_API3_Exception
$e) {
1908 // Lack of permissions will throw an exception
1914 * Retrieve related case ids for given case.
1916 * @param int $caseId
1917 * @param bool $excludeDeleted
1918 * Do not include deleted cases.
1922 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1923 //FIXME : do check for permissions.
1929 $linkActType = array_search('Link Cases',
1930 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
1932 if (!$linkActType) {
1936 $whereClause = "mainCase.id = %2";
1937 if ($excludeDeleted) {
1938 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1942 SELECT relCaseAct.case_id
1943 FROM civicrm_case mainCase
1944 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1945 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1946 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1947 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1948 WHERE $whereClause";
1950 $dao = CRM_Core_DAO
::executeQuery($query, array(
1951 1 => array($linkActType, 'Integer'),
1952 2 => array($caseId, 'Integer'),
1954 $relatedCaseIds = array();
1955 while ($dao->fetch()) {
1956 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1960 return array_values($relatedCaseIds);
1964 * Retrieve related case details for given case.
1966 * @param int $caseId
1967 * @param bool $excludeDeleted
1968 * Do not include deleted cases.
1972 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
1973 $relatedCaseIds = self
::getRelatedCaseIds($caseId, $excludeDeleted);
1974 $relatedCases = array();
1976 if (!$relatedCaseIds) {
1980 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1981 if ($excludeDeleted) {
1982 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1985 //filter for permissioned cases.
1986 $filterCases = array();
1987 $doFilterCases = FALSE;
1988 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1989 $doFilterCases = TRUE;
1990 $session = CRM_Core_Session
::singleton();
1991 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
1994 //2. fetch the details of related cases.
1996 SELECT relCase.id as id,
1997 civicrm_case_type.title as case_type,
1998 client.display_name as client_name,
1999 client.id as client_id
2000 FROM civicrm_case relCase
2001 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2002 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2003 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
2004 WHERE {$whereClause}";
2006 $dao = CRM_Core_DAO
::executeQuery($query);
2007 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2008 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2010 while ($dao->fetch()) {
2012 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2013 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2014 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2015 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2017 $clientView = $dao->client_name
;
2018 if ($hasViewContact) {
2019 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2022 $relatedCases[$dao->id
] = array(
2023 'case_id' => $dao->id
,
2024 'case_type' => $dao->case_type
,
2025 'client_name' => $clientView,
2026 'links' => $caseView,
2031 return $relatedCases;
2035 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2037 * @see CRM_Dedupe_Merger::cpTables()
2039 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2041 * @param int $mainContactId
2042 * @param int $otherContactId
2044 public static function mergeContacts($mainContactId, $otherContactId) {
2045 self
::mergeCases($mainContactId, NULL, $otherContactId);
2049 * Function perform two task.
2050 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2051 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2053 * @param int $mainContactId
2054 * Contact id of main contact record.
2055 * @param int $mainCaseId
2056 * Case id of main case record.
2057 * @param int $otherContactId
2058 * Contact id of record which is going to merge.
2059 * @param int $otherCaseId
2060 * Case id of record which is going to merge.
2062 * @param bool $changeClient
2066 public static function mergeCases(
2067 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2068 $otherCaseId = NULL, $changeClient = FALSE) {
2069 $moveToTrash = TRUE;
2071 $duplicateContacts = FALSE;
2072 if ($mainContactId && $otherContactId &&
2073 $mainContactId != $otherContactId
2075 $duplicateContacts = TRUE;
2078 $duplicateCases = FALSE;
2079 if ($mainCaseId && $otherCaseId &&
2080 $mainCaseId != $otherCaseId
2082 $duplicateCases = TRUE;
2085 $mainCaseIds = array();
2086 if (!$duplicateContacts && !$duplicateCases) {
2087 return $mainCaseIds;
2090 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2091 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2092 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2093 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2094 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2095 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2097 $processCaseIds = array($otherCaseId);
2098 if ($duplicateContacts && !$duplicateCases) {
2099 if ($changeClient) {
2100 $processCaseIds = array($mainCaseId);
2103 //get all case ids for other contact.
2104 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2106 if (!is_array($processCaseIds)) {
2111 $session = CRM_Core_Session
::singleton();
2112 $currentUserId = $session->get('userID');
2114 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2116 // copy all cases and connect to main contact id.
2117 foreach ($processCaseIds as $otherCaseId) {
2118 if ($duplicateContacts) {
2119 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2120 $mainCaseId = $mainCase->id
;
2125 // CRM-11662 Copy Case custom data
2126 $extends = array('case');
2127 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2129 foreach ($groupTree as $groupID => $group) {
2130 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2131 foreach ($group['fields'] as $fieldID => $field) {
2132 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2136 foreach ($table as $tableName => $tableColumns) {
2137 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2138 $tableColumns[0] = $mainCaseId;
2139 $select = 'SELECT ' . implode(', ', $tableColumns);
2140 $from = ' FROM ' . $tableName;
2141 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2142 $query = $insert . $select . $from . $where;
2143 $dao = CRM_Core_DAO
::executeQuery($query);
2149 $mainCaseIds[] = $mainCaseId;
2150 //insert record for case contact.
2151 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2152 $otherCaseContact->case_id
= $otherCaseId;
2153 $otherCaseContact->find();
2154 while ($otherCaseContact->fetch()) {
2155 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2156 $mainCaseContact->case_id
= $mainCaseId;
2157 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2158 if ($mainCaseContact->contact_id
== $otherContactId) {
2159 $mainCaseContact->contact_id
= $mainContactId;
2161 //avoid duplicate object.
2162 if (!$mainCaseContact->find(TRUE)) {
2163 $mainCaseContact->save();
2165 $mainCaseContact->free();
2167 $otherCaseContact->free();
2169 elseif (!$otherContactId) {
2170 $otherContactId = $mainContactId;
2173 if (!$mainCaseId ||
!$otherCaseId ||
2174 !$mainContactId ||
!$otherContactId
2179 // get all activities for other case.
2180 $otherCaseActivities = array();
2181 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2183 //for duplicate cases do not process singleton activities.
2184 $otherActivityIds = $singletonActivityIds = array();
2185 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2186 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2187 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2190 $otherActivityIds[] = $otherActId;
2192 if ($duplicateCases) {
2193 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2196 FROM civicrm_activity
2197 WHERE activity_type_id = $openCaseType
2198 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2199 $dao = CRM_Core_DAO
::executeQuery($sql);
2200 while ($dao->fetch()) {
2201 $singletonActivityIds[] = $dao->id
;
2207 // migrate all activities and connect to main contact.
2208 $copiedActivityIds = $activityMappingIds = array();
2209 sort($otherActivityIds);
2210 foreach ($otherActivityIds as $otherActivityId) {
2212 //for duplicate cases -
2213 //do not migrate singleton activities.
2214 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2218 //migrate activity record.
2219 $otherActivity = new CRM_Activity_DAO_Activity();
2220 $otherActivity->id
= $otherActivityId;
2221 if (!$otherActivity->find(TRUE)) {
2225 $mainActVals = array();
2226 $mainActivity = new CRM_Activity_DAO_Activity();
2227 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2228 $mainActivity->copyValues($mainActVals);
2229 $mainActivity->id
= NULL;
2230 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2231 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2235 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2239 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2242 $mainActivity->save();
2243 $mainActivityId = $mainActivity->id
;
2244 if (!$mainActivityId) {
2248 $activityMappingIds[$otherActivityId] = $mainActivityId;
2249 // insert log of all activities
2250 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2252 $otherActivity->free();
2253 $mainActivity->free();
2254 $copiedActivityIds[] = $otherActivityId;
2256 //create case activity record.
2257 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2258 $mainCaseActivity->case_id
= $mainCaseId;
2259 $mainCaseActivity->activity_id
= $mainActivityId;
2260 $mainCaseActivity->save();
2261 $mainCaseActivity->free();
2263 //migrate source activity.
2264 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2265 $otherSourceActivity->activity_id
= $otherActivityId;
2266 $otherSourceActivity->record_type_id
= $sourceID;
2267 $otherSourceActivity->find();
2268 while ($otherSourceActivity->fetch()) {
2269 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2270 $mainActivitySource->record_type_id
= $sourceID;
2271 $mainActivitySource->activity_id
= $mainActivityId;
2272 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2273 if ($mainActivitySource->contact_id
== $otherContactId) {
2274 $mainActivitySource->contact_id
= $mainContactId;
2276 //avoid duplicate object.
2277 if (!$mainActivitySource->find(TRUE)) {
2278 $mainActivitySource->save();
2280 $mainActivitySource->free();
2282 $otherSourceActivity->free();
2284 //migrate target activities.
2285 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2286 $otherTargetActivity->activity_id
= $otherActivityId;
2287 $otherTargetActivity->record_type_id
= $targetID;
2288 $otherTargetActivity->find();
2289 while ($otherTargetActivity->fetch()) {
2290 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2291 $mainActivityTarget->record_type_id
= $targetID;
2292 $mainActivityTarget->activity_id
= $mainActivityId;
2293 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2294 if ($mainActivityTarget->contact_id
== $otherContactId) {
2295 $mainActivityTarget->contact_id
= $mainContactId;
2297 //avoid duplicate object.
2298 if (!$mainActivityTarget->find(TRUE)) {
2299 $mainActivityTarget->save();
2301 $mainActivityTarget->free();
2303 $otherTargetActivity->free();
2305 //migrate assignee activities.
2306 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2307 $otherAssigneeActivity->activity_id
= $otherActivityId;
2308 $otherAssigneeActivity->record_type_id
= $assigneeID;
2309 $otherAssigneeActivity->find();
2310 while ($otherAssigneeActivity->fetch()) {
2311 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2312 $mainAssigneeActivity->activity_id
= $mainActivityId;
2313 $mainAssigneeActivity->record_type_id
= $assigneeID;
2314 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2315 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2316 $mainAssigneeActivity->contact_id
= $mainContactId;
2318 //avoid duplicate object.
2319 if (!$mainAssigneeActivity->find(TRUE)) {
2320 $mainAssigneeActivity->save();
2322 $mainAssigneeActivity->free();
2324 $otherAssigneeActivity->free();
2326 // copy custom fields and attachments
2328 'activityID' => $otherActivityId,
2329 'mainActivityId' => $mainActivityId,
2331 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2334 //copy case relationship.
2335 if ($duplicateContacts) {
2336 //migrate relationship records.
2337 $otherRelationship = new CRM_Contact_DAO_Relationship();
2338 $otherRelationship->case_id
= $otherCaseId;
2339 $otherRelationship->find();
2340 $otherRelationshipIds = array();
2341 while ($otherRelationship->fetch()) {
2342 $otherRelVals = array();
2343 $updateOtherRel = FALSE;
2344 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2346 $mainRelationship = new CRM_Contact_DAO_Relationship();
2347 $mainRelationship->copyValues($otherRelVals);
2348 $mainRelationship->id
= NULL;
2349 $mainRelationship->case_id
= $mainCaseId;
2350 if ($mainRelationship->contact_id_a
== $otherContactId) {
2351 $updateOtherRel = TRUE;
2352 $mainRelationship->contact_id_a
= $mainContactId;
2355 //case creator change only when we merge user contact.
2356 if ($mainRelationship->contact_id_b
== $otherContactId) {
2357 //do not change creator for change client.
2358 if (!$changeClient) {
2359 $updateOtherRel = TRUE;
2360 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2363 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2364 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2366 //avoid duplicate object.
2367 if (!$mainRelationship->find(TRUE)) {
2368 $mainRelationship->save();
2370 $mainRelationship->free();
2372 //get the other relationship ids to update end date.
2373 if ($updateOtherRel) {
2374 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2377 $otherRelationship->free();
2379 //update other relationships end dates
2380 if (!empty($otherRelationshipIds)) {
2381 $sql = 'UPDATE civicrm_relationship
2382 SET end_date = CURDATE()
2383 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2384 CRM_Core_DAO
::executeQuery($sql);
2388 //move other case to trash.
2389 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2394 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2395 if ($changeClient) {
2396 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2397 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2399 $mergeActType = array_search('Reassigned Case', $activityTypes);
2400 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2403 2 => $otherContactDisplayName,
2404 3 => $mainContactDisplayName,
2409 elseif ($duplicateContacts) {
2410 $mergeActType = array_search('Merge Case', $activityTypes);
2411 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2414 2 => $otherContactId,
2415 3 => $mainContactId,
2421 $mergeActType = array_search('Merge Case', $activityTypes);
2422 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2423 if (!empty($copiedActivityIds)) {
2425 SELECT id, subject, activity_date_time, activity_type_id
2426 FROM civicrm_activity
2427 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2428 $dao = CRM_Core_DAO
::executeQuery($sql);
2429 while ($dao->fetch()) {
2430 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2431 if ($dao->subject
) {
2432 $mergeActSubjectDetails .= " :: {$dao->subject}";
2434 $mergeActSubjectDetails .= "<br />";
2439 //Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2440 $activityParams = array(
2441 'subject' => $mergeActSubject,
2442 'details' => $mergeActSubjectDetails,
2443 'status_id' => array_search('Completed', $activityStatuses),
2444 'activity_type_id' => $mergeActType,
2445 'source_contact_id' => $currentUserId,
2446 'activity_date_time' => date('YmdHis'),
2449 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2450 $mergeActivityId = $mergeActivity->id
;
2451 if (!$mergeActivityId) {
2454 $mergeActivity->free();
2456 //connect merge activity to case.
2457 $mergeCaseAct = array(
2458 'case_id' => $mainCaseId,
2459 'activity_id' => $mergeActivityId,
2462 self
::processCaseActivity($mergeCaseAct);
2465 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2467 return $mainCaseIds;
2471 * Validate contact permission for
2472 * edit/view on activity record and build links.
2474 * @param array $tplParams
2475 * Params to be sent to template for sending email.
2476 * @param array $activityParams
2477 * Info of the activity.
2479 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2480 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2481 'activity_type_id', 'id'
2484 if (!empty($tplParams['isCaseActivity'])) {
2485 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2486 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2489 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2490 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2493 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2494 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2498 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2499 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2502 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2503 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2509 * Validate contact permission for
2510 * given operation on activity record.
2512 * @param int $activityId
2513 * Activity record id.
2514 * @param string $operation
2516 * @param int $actTypeId
2518 * @param int $contactId
2519 * Contact id/if not pass consider logged in.
2520 * @param bool $checkComponent
2521 * Do we need to check component enabled.
2525 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2527 if (!$actTypeId && $activityId) {
2528 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2531 if (!$activityId ||
!$operation ||
!$actTypeId) {
2535 //do check for civicase component enabled.
2536 if ($checkComponent && !self
::enabled()) {
2540 //do check for cases.
2541 $caseActOperations = array(
2548 if (in_array($operation, $caseActOperations)) {
2550 if (!isset($caseCount)) {
2552 $caseCount = civicrm_api3('Case', 'getcount', array(
2553 'check_permissions' => TRUE,
2554 'status_id' => array('!=' => 'Closed'),
2556 'end_date' => array('IS NULL' => 1),
2559 catch (CiviCRM_API3_Exception
$e) {
2560 // Lack of permissions will throw an exception
2564 if ($operation == 'File On Case') {
2565 $allow = !empty($caseCount);
2568 $allow = ($caseCount > 1);
2572 $actionOperations = array('view', 'edit', 'delete');
2573 if (in_array($operation, $actionOperations)) {
2575 //do cache when user has non/supper permission.
2576 static $allowOperations;
2578 if (!is_array($allowOperations) ||
2579 !array_key_exists($operation, $allowOperations)
2583 $session = CRM_Core_Session
::singleton();
2584 $contactId = $session->get('userID');
2587 //check for permissions.
2588 $permissions = array(
2590 'access my cases and activities',
2591 'access all cases and activities',
2594 'access my cases and activities',
2595 'access all cases and activities',
2597 'delete' => array('delete activities'),
2600 //check for core permission.
2601 $hasPermissions = array();
2602 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2603 if (is_array($checkPermissions)) {
2604 foreach ($checkPermissions as $per) {
2605 if (CRM_Core_Permission
::check($per)) {
2606 $hasPermissions[$operation][] = $per;
2612 if (!empty($hasPermissions)) {
2613 //need to check activity object specific.
2614 if (in_array($operation, array(
2619 //do we have supper permission.
2620 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2621 $allowOperations[$operation] = $allow = TRUE;
2624 //user has only access to my cases and activity.
2625 //here object specific permmions come in picture.
2627 //edit - contact must be source or assignee
2628 //view - contact must be source/assignee/target
2629 $isTarget = $isAssignee = $isSource = FALSE;
2630 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2631 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2632 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2633 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2635 $target = new CRM_Activity_DAO_ActivityContact();
2636 $target->record_type_id
= $targetID;
2637 $target->activity_id
= $activityId;
2638 $target->contact_id
= $contactId;
2639 if ($target->find(TRUE)) {
2643 $assignee = new CRM_Activity_DAO_ActivityContact();
2644 $assignee->activity_id
= $activityId;
2645 $assignee->record_type_id
= $assigneeID;
2646 $assignee->contact_id
= $contactId;
2647 if ($assignee->find(TRUE)) {
2651 $source = new CRM_Activity_DAO_ActivityContact();
2652 $source->activity_id
= $activityId;
2653 $source->record_type_id
= $sourceID;
2654 $source->contact_id
= $contactId;
2655 if ($source->find(TRUE)) {
2659 if ($operation == 'edit') {
2660 if ($isAssignee ||
$isSource) {
2664 if ($operation == 'view') {
2665 if ($isTarget ||
$isAssignee ||
$isSource) {
2671 elseif (is_array($hasPermissions[$operation])) {
2672 $allowOperations[$operation] = $allow = TRUE;
2676 //contact do not have permission.
2677 $allowOperations[$operation] = FALSE;
2682 //here contact might have supper/non permission.
2683 $allow = $allowOperations[$operation];
2687 //do further only when operation is granted.
2689 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2691 //get the activity type name.
2692 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2694 //do not allow multiple copy / edit action.
2695 $singletonNames = array(
2705 //do not allow to delete these activities, CRM-4543
2706 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2708 //allow edit operation.
2709 $allowEditNames = array('Open Case');
2711 // do not allow File on Case
2712 $doNotFileNames = array(
2715 'Change Case Status',
2716 'Change Case Start Date',
2723 if (in_array($actTypeName, $singletonNames)) {
2725 if ($operation == 'File On Case') {
2726 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2728 if (in_array($operation, $actionOperations)) {
2730 if ($operation == 'edit') {
2731 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2733 elseif ($operation == 'delete') {
2734 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2738 if ($allow && ($operation == 'delete') &&
2739 in_array($actTypeName, $doNotDeleteNames)
2744 if ($allow && ($operation == 'File On Case') &&
2745 in_array($actTypeName, $doNotFileNames)
2750 //check settings file for masking actions
2751 //on the basis the activity types
2752 //hide Edit link if activity type is NOT editable
2753 //(special case activities).CRM-5871
2754 if ($allow && in_array($operation, $actionOperations)) {
2755 static $actionFilter = array();
2756 if (!array_key_exists($operation, $actionFilter)) {
2757 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2758 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2760 if (array_key_exists($operation, $actionFilter[$operation]) &&
2761 in_array($actTypeId, $actionFilter[$operation][$operation])
2772 * Since we drop 'access CiviCase', allow access
2773 * if user has 'access my cases and activities'
2774 * or 'access all cases and activities'
2776 public static function accessCiviCase() {
2777 if (!self
::enabled()) {
2781 if (CRM_Core_Permission
::check('access my cases and activities') ||
2782 CRM_Core_Permission
::check('access all cases and activities')
2791 * Verify user has permission to access a case.
2793 * @param int $caseId
2794 * @param bool $denyClosed
2795 * Set TRUE if one wants closed cases to be treated as inaccessible.
2799 public static function accessCase($caseId, $denyClosed = TRUE) {
2800 if (!$caseId ||
!self
::enabled()) {
2804 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2805 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2806 $params['status_id'] = array('!=' => 'Closed');
2809 return (bool) civicrm_api3('Case', 'getcount', $params);
2811 catch (CiviCRM_API3_Exception
$e) {
2812 // Lack of permissions will throw an exception
2818 * Check whether activity is a case Activity.
2820 * @param int $activityID
2825 public static function isCaseActivity($activityID) {
2826 $isCaseActivity = FALSE;
2828 $params = array(1 => array($activityID, 'Integer'));
2829 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2830 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2831 $isCaseActivity = TRUE;
2835 return $isCaseActivity;
2839 * Get all the case type ids currently in use.
2843 public static function getUsedCaseType() {
2844 static $caseTypeIds;
2846 if (!is_array($caseTypeIds)) {
2847 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2849 $dao = CRM_Core_DAO
::executeQuery($query);
2850 $caseTypeIds = array();
2851 while ($dao->fetch()) {
2852 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2855 $caseTypeIds[] = $typeId[1];
2859 return $caseTypeIds;
2863 * Get all the case status ids currently in use.
2867 public static function getUsedCaseStatuses() {
2868 static $caseStatusIds;
2870 if (!is_array($caseStatusIds)) {
2871 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2873 $dao = CRM_Core_DAO
::executeQuery($query);
2874 $caseStatusIds = array();
2875 while ($dao->fetch()) {
2876 $caseStatusIds[] = $dao->status_id
;
2880 return $caseStatusIds;
2884 * Get all the encounter medium ids currently in use.
2888 public static function getUsedEncounterMediums() {
2891 if (!is_array($mediumIds)) {
2892 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2894 $dao = CRM_Core_DAO
::executeQuery($query);
2895 $mediumIds = array();
2896 while ($dao->fetch()) {
2897 $mediumIds[] = $dao->medium_id
;
2905 * Check case configuration.
2907 * @param int $contactId
2911 public static function isCaseConfigured($contactId = NULL) {
2912 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2914 //lets check for case configured.
2915 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2916 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2917 if (!$configured['configured']) {
2918 //do check for case type and case status.
2919 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2920 if (!empty($caseTypes)) {
2921 $configured['configured'] = TRUE;
2922 if (!$configured['configured']) {
2923 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2924 if (!empty($caseStatuses)) {
2925 $configured['configured'] = TRUE;
2930 if ($configured['configured']) {
2931 //do check for active case type and case status.
2932 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2933 if (!empty($caseTypes)) {
2934 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2935 if (!empty($caseStatuses)) {
2936 $configured['allowToAddNewCase'] = TRUE;
2940 //do we need to redirect user to case admin.
2941 if (!$configured['allowToAddNewCase'] && $contactId) {
2942 //check for current contact case count.
2943 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2944 //redirect user to case admin page.
2945 if (!$currentContatCasesCount) {
2946 $configured['redirectToCaseAdmin'] = TRUE;
2955 * Used during case component enablement and during ugprade.
2959 public static function createCaseViews() {
2960 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2961 $dao = new CRM_Core_DAO();
2963 $sql = self
::createCaseViewsQuery('upcoming');
2965 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2969 // Above error doesn't get caught?
2970 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2971 if (is_null($doublecheck)) {
2975 $sql = self
::createCaseViewsQuery('recent');
2977 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2981 // Above error doesn't get caught?
2982 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
2983 if (is_null($doublecheck)) {
2991 * Helper function, also used by the upgrade in case of error
2993 * @param string $section
2997 public static function createCaseViewsQuery($section = 'upcoming') {
2999 $scheduled_id = CRM_Core_Pseudoconstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
3002 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3003 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3004 FROM civicrm_case_activity ca
3005 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3006 WHERE a.activity_date_time =
3007 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3008 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3009 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3010 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
3011 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
3015 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3016 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3017 FROM civicrm_case_activity ca
3018 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3019 WHERE a.activity_date_time =
3020 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3021 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3022 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3023 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
3024 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
3031 * Add/copy relationships, when new client is added for a case
3033 * @param int $caseId
3035 * @param int $contactId
3036 * Contact id / new client id.
3038 public static function addCaseRelationships($caseId, $contactId) {
3039 // get the case role / relationships for the case
3040 $caseRelationships = new CRM_Contact_DAO_Relationship();
3041 $caseRelationships->case_id
= $caseId;
3042 $caseRelationships->find();
3043 $relationshipTypes = array();
3045 // make sure we don't add duplicate relationships of same relationship type.
3046 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3048 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3050 // add relationship for new client.
3051 $newRelationship = new CRM_Contact_DAO_Relationship();
3052 $newRelationship->copyValues($values);
3053 $newRelationship->id
= NULL;
3054 $newRelationship->case_id
= $caseId;
3055 $newRelationship->contact_id_a
= $contactId;
3056 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3057 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3059 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3060 if (!$newRelationship->find(TRUE)) {
3061 $newRelationship->save();
3063 $newRelationship->free();
3065 // store relationship type of newly created relationship
3066 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3071 * Get the list of clients for a case.
3073 * @param int $caseId
3076 * associated array with client ids
3078 public static function getCaseClients($caseId) {
3080 $caseContact = new CRM_Case_DAO_CaseContact();
3081 $caseContact->case_id
= $caseId;
3082 $caseContact->orderBy('id');
3083 $caseContact->find();
3085 while ($caseContact->fetch()) {
3086 $clients[] = $caseContact->contact_id
;
3093 * @param int $caseId
3094 * @param string $direction
3096 * @param int $relTypeId
3097 * @throws \CRM_Core_Exception
3098 * @throws \CiviCRM_API3_Exception
3100 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3102 if ($direction !== 'a' && $direction !== 'b') {
3103 throw new CRM_Core_Exception('Invalid relationship direction');
3106 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3107 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3108 $dao = CRM_Core_DAO
::executeQuery($sql, array(
3109 1 => array($caseId, 'Positive'),
3110 2 => array($cid, 'Positive'),
3111 3 => array($relTypeId, 'Positive'),
3113 while ($dao->fetch()) {
3114 civicrm_api3('relationship', 'create', array(
3117 'end_date' => 'now',
3123 * Get options for a given case field.
3124 * @see CRM_Core_DAO::buildOptions
3126 * @param string $fieldName
3127 * @param string $context
3128 * @see CRM_Core_DAO::buildOptionsContext
3129 * @param array $props
3130 * Whatever is known about this dao object.
3132 * @return array|bool
3134 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3135 $className = __CLASS__
;
3137 switch ($fieldName) {
3138 // This field is not part of this object but the api supports it
3140 $className = 'CRM_Activity_BAO_Activity';
3143 // Filter status id by case type id
3145 if (!empty($props['case_type_id'])) {
3146 $idField = is_numeric($props['case_type_id']) ?
'id' : 'name';
3147 $caseType = civicrm_api3('CaseType', 'getsingle', array($idField => $props['case_type_id'], 'return' => 'definition'));
3148 if (!empty($caseType['definition']['statuses'])) {
3149 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
3154 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3160 public function addSelectWhereClause() {
3161 // We always return an array with these keys, even if they are empty,
3162 // because this tells the query builder that we have considered these fields for acls
3165 // Only case admins can view deleted cases
3166 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
array() : array("= 0"),
3168 // Ensure the user has permission to view the case client
3169 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3170 if ($contactClause) {
3171 $contactClause = implode(' AND contact_id ', $contactClause);
3172 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3174 // The api gatekeeper ensures the user has at least "access my cases and activities"
3175 // so if they do not have permission to see all cases we'll assume they can only access their own
3176 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3177 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3178 $clauses['id'][] = "IN (
3179 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 (
3180 (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)
3184 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3189 * CRM-20308: Method to get the contact id to use as from contact for email copy
3190 * 1. Activity Added by Contact's email address
3191 * 2. System Default From Address
3192 * 3. Default Organization Contact email address
3195 * @param int $activityID
3197 * @return mixed $emailFromContactId
3198 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3200 public static function getReceiptFrom($activityID) {
3201 $name = $address = NULL;
3203 if (!empty($activityID)) {
3204 // There is always a 'Added by' contact for a activity,
3205 // so we can safely use ActivityContact.Getvalue API
3206 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', array(
3207 'activity_id' => $activityID,
3208 'record_type_id' => 'Activity Source',
3209 'return' => 'contact_id',
3211 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3214 // If 'From' email address not found for Source Activity Contact then
3215 // fetch the email from domain or logged in user.
3216 if (empty($address)) {
3217 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3220 return "$name <$address>";