3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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 return $caseDAO->save();
82 * Takes an associative array and creates a case object.
84 * @param array $params
85 * (reference) an assoc array of name/value pairs.
87 * @return CRM_Case_BAO_Case
89 public static function &create(&$params) {
90 $transaction = new CRM_Core_Transaction();
92 if (!empty($params['id'])) {
93 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
96 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
99 $case = self
::add($params);
101 if (!empty($params['custom']) &&
102 is_array($params['custom'])
104 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
107 if (is_a($case, 'CRM_Core_Error')) {
108 $transaction->rollback();
112 if (!empty($params['id'])) {
113 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
116 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
118 $transaction->commit();
120 //we are not creating log for case
121 //since case log can be tracked using log for activity.
126 * Process case activity add/delete
127 * takes an associative array and
129 * @param array $params
130 * (reference ) an assoc array of name/value pairs.
133 public static function processCaseActivity(&$params) {
134 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
135 $caseActivityDAO->activity_id
= $params['activity_id'];
136 $caseActivityDAO->case_id
= $params['case_id'];
138 $caseActivityDAO->find(TRUE);
139 $caseActivityDAO->save();
143 * Get the case subject for Activity.
145 * @param int $activityId
148 * @return string|null
150 public static function getCaseSubject($activityId) {
151 $caseActivity = new CRM_Case_DAO_CaseActivity();
152 $caseActivity->activity_id
= $activityId;
153 if ($caseActivity->find(TRUE)) {
154 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
163 * @param string $colName
168 public static function getCaseType($caseId, $colName = 'title') {
170 SELECT civicrm_case_type.{$colName} FROM civicrm_case
171 LEFT JOIN civicrm_case_type ON
172 civicrm_case.case_type_id = civicrm_case_type.id
173 WHERE civicrm_case.id = %1";
175 $queryParams = array(1 => array($caseId, 'Integer'));
177 return CRM_Core_DAO
::singleValueQuery($query, $queryParams);
181 * Delete the record that are associated with this case.
182 * record are deleted from case
185 * Id of the case to delete.
187 * @param bool $moveToTrash
192 public static function deleteCase($caseId, $moveToTrash = FALSE) {
193 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
196 $activities = self
::getCaseActivityDates($caseId);
198 foreach ($activities as $value) {
199 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
204 $transaction = new CRM_Core_Transaction();
206 $case = new CRM_Case_DAO_Case();
209 $result = $case->delete();
210 $transaction->commit();
213 $result = $case->is_deleted
= 1;
218 // CRM-7364, disable relationships
219 self
::enableDisableCaseRelationships($caseId, FALSE);
221 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
223 // remove case from recent items.
228 CRM_Utils_Recent
::del($caseRecent);
236 * Enable disable case related relationships.
240 * @param bool $enable
243 public static function enableDisableCaseRelationships($caseId, $enable) {
244 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
245 if (!empty($contactIds)) {
246 foreach ($contactIds as $cid) {
247 $roles = self
::getCaseRoles($cid, $caseId);
248 if (!empty($roles)) {
249 $relationshipIds = implode(',', array_keys($roles));
250 $enable = (int) $enable;
251 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
252 WHERE id IN ( {$relationshipIds} )";
253 CRM_Core_DAO
::executeQuery($query);
260 * Retrieve contact_id by case_id.
265 * @param int $contactID
269 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL) {
270 $caseContact = new CRM_Case_DAO_CaseContact();
271 $caseContact->case_id
= $caseId;
272 $caseContact->find();
273 $contactArray = array();
275 while ($caseContact->fetch()) {
276 if ($contactID != $caseContact->contact_id
) {
277 $contactArray[$count] = $caseContact->contact_id
;
282 return $contactArray;
286 * Look up a case using an activity ID.
288 * @param int $activityId
290 * @return int, case ID
292 public static function getCaseIdByActivityId($activityId) {
293 $originalId = CRM_Core_DAO
::singleValueQuery(
294 'SELECT original_id FROM civicrm_activity WHERE id = %1',
295 array('1' => array($activityId, 'Integer'))
297 $caseId = CRM_Core_DAO
::singleValueQuery(
298 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
300 '1' => array($activityId, 'Integer'),
301 '2' => array($originalId ?
$originalId : $activityId, 'Integer'),
308 * Retrieve contact names by caseId.
315 public static function getContactNames($caseId) {
316 $contactNames = array();
318 return $contactNames;
322 SELECT contact_a.sort_name name,
323 contact_a.display_name as display_name,
325 contact_a.birth_date as birth_date,
328 FROM civicrm_contact contact_a
329 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
330 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
331 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
332 WHERE civicrm_case_contact.case_id = %1";
334 $dao = CRM_Core_DAO
::executeQuery($query,
335 array(1 => array($caseId, 'Integer'))
337 while ($dao->fetch()) {
338 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
339 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
340 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
341 $contactNames[$dao->cid
]['email'] = $dao->email
;
342 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
343 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
344 $contactNames[$dao->cid
]['role'] = ts('Client');
347 return $contactNames;
351 * Retrieve case_id by contact_id.
353 * @param int $contactID
354 * @param bool $includeDeleted
355 * Include the deleted cases in result.
356 * @param null $caseType
360 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
363 FROM civicrm_case_contact cc
364 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
366 if (isset($caseType)) {
368 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
369 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
371 if (!isset($caseType)) {
372 $query .= "WHERE cc.contact_id = %1";
374 if (!$includeDeleted) {
375 $query .= " AND ca.is_deleted = 0";
378 $params = array(1 => array($contactID, 'Integer'));
379 $dao = CRM_Core_DAO
::executeQuery($query, $params);
381 $caseArray = array();
382 while ($dao->fetch()) {
383 $caseArray[] = $dao->id
;
391 * @param string $type
393 * @param string $condition
397 public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL) {
399 $session = CRM_Core_Session
::singleton();
400 $userID = $session->get('userID');
404 civicrm_case.id as case_id,
405 civicrm_case.subject as case_subject,
406 civicrm_contact.id as contact_id,
407 civicrm_contact.sort_name as sort_name,
408 civicrm_phone.phone as phone,
409 civicrm_contact.contact_type as contact_type,
410 civicrm_contact.contact_sub_type as contact_sub_type,
411 t_act.activity_type_id,
412 c_type.title as case_type,
413 civicrm_case.case_type_id as case_type_id,
414 cov_status.label as case_status,
415 cov_status.label as case_status_name,
417 civicrm_case.start_date as case_start_date,
418 case_relation_type.label_b_a as case_role, ";
420 if ($type == 'upcoming') {
422 t_act.desired_date as case_scheduled_activity_date,
423 t_act.id as case_scheduled_activity_id,
424 t_act.act_type_name as case_scheduled_activity_type_name,
425 t_act.act_type AS case_scheduled_activity_type ";
427 elseif ($type == 'recent') {
429 t_act.desired_date as case_recent_activity_date,
430 t_act.id as case_recent_activity_id,
431 t_act.act_type_name as case_recent_activity_type_name,
432 t_act.act_type AS case_recent_activity_type ";
434 elseif ($type == 'any') {
436 t_act.desired_date as case_activity_date,
437 t_act.id as case_activity_id,
438 t_act.act_type_name as case_activity_type_name,
439 t_act.act_type AS case_activity_type ";
442 $query .= " FROM civicrm_case
443 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
444 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
446 if ($type == 'upcoming') {
447 // This gets the earliest activity per case that's scheduled within 14 days from now.
448 // 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.
449 // In this case we don't really care which one, so min(id) works.
450 // optimized in CRM-11837
451 $query .= " INNER JOIN
453 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
458 FROM civicrm_view_case_activity_upcoming
459 ORDER BY activity_date_time ASC, id ASC
462 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
463 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
467 elseif ($type == 'recent') {
468 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
469 //improve query performance - CRM-10598
470 $query .= " INNER JOIN
472 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
477 FROM civicrm_view_case_activity_recent
478 ORDER BY activity_date_time DESC, id ASC
481 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
482 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
485 elseif ($type == 'any') {
486 $query .= " LEFT JOIN
488 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
489 FROM civicrm_activity act4
490 LEFT JOIN civicrm_case_activity ca4
491 ON ca4.activity_id = act4.id
492 AND act4.is_current_revision = 1
493 LEFT JOIN civicrm_option_group aog
494 ON aog.name='activity_type'
495 LEFT JOIN civicrm_option_value aov
496 ON aov.option_group_id = aog.id
497 AND aov.value = act4.activity_type_id
502 ON t_act.case_id = civicrm_case.id
503 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
504 LEFT JOIN civicrm_relationship case_relationship
505 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
506 AND case_relationship.case_id = civicrm_case.id )
508 LEFT JOIN civicrm_relationship_type case_relation_type
509 ON ( case_relation_type.id = case_relationship.relationship_type_id
510 AND case_relation_type.id = case_relationship.relationship_type_id )
512 LEFT JOIN civicrm_case_type c_type
513 ON civicrm_case.case_type_id = c_type.id
515 LEFT JOIN civicrm_option_group cog_status
516 ON cog_status.name = 'case_status'
518 LEFT JOIN civicrm_option_value cov_status
519 ON ( civicrm_case.status_id = cov_status.value
520 AND cog_status.id = cov_status.option_group_id )
524 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
525 $query .= " WHERE (1) $condition ";
528 if ($type == 'upcoming') {
529 $query .= " ORDER BY case_scheduled_activity_date ASC ";
531 elseif ($type == 'recent') {
532 $query .= " ORDER BY case_recent_activity_date ASC ";
534 elseif ($type == 'any') {
535 $query .= " ORDER BY case_activity_date ASC ";
542 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
544 * @param bool $allCases
548 * @param string $type
549 * /upcoming,recent,all/.
551 * @param string $context
556 public static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') {
558 $casesList = array();
560 //validate access for own cases.
561 if (!self
::accessCiviCase()) {
566 $session = CRM_Core_Session
::singleton();
567 $userID = $session->get('userID');
570 //validate access for all cases.
571 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
575 $condition = " AND civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1";
578 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
580 if ($type == 'upcoming' ||
$type == 'any') {
581 $closedId = CRM_Core_OptionGroup
::getValue('case_status', 'Closed', 'name');
583 AND civicrm_case.status_id != $closedId";
586 $query = self
::getCaseActivityQuery($type, $userID, $condition);
588 $queryParams = array();
589 $result = CRM_Core_DAO
::executeQuery($query,
593 $caseStatus = CRM_Core_OptionGroup
::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
595 $resultFields = array(
612 if ($type == 'upcoming') {
613 $resultFields[] = 'case_scheduled_activity_date';
614 $resultFields[] = 'case_scheduled_activity_type_name';
615 $resultFields[] = 'case_scheduled_activity_type';
616 $resultFields[] = 'case_scheduled_activity_id';
618 elseif ($type == 'recent') {
619 $resultFields[] = 'case_recent_activity_date';
620 $resultFields[] = 'case_recent_activity_type_name';
621 $resultFields[] = 'case_recent_activity_type';
622 $resultFields[] = 'case_recent_activity_id';
624 elseif ($type == 'any') {
625 $resultFields[] = 'case_activity_date';
626 $resultFields[] = 'case_activity_type_name';
627 $resultFields[] = 'case_activity_type';
628 $resultFields[] = 'case_activity_id';
631 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
632 $actions = CRM_Case_Selector_Search
::links();
634 // check is the user has view/edit signer permission
635 $permissions = array(CRM_Core_Permission
::VIEW
);
636 if (CRM_Core_Permission
::check('access all cases and activities') ||
637 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
639 $permissions[] = CRM_Core_Permission
::EDIT
;
641 if (CRM_Core_Permission
::check('delete in CiviCase')) {
642 $permissions[] = CRM_Core_Permission
::DELETE
;
644 $mask = CRM_Core_Action
::mask($permissions);
646 while ($result->fetch()) {
647 foreach ($resultFields as $donCare => $field) {
648 $casesList[$result->case_id
][$field] = $result->$field;
649 if ($field == 'contact_type') {
650 $casesList[$result->case_id
]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
652 $casesList[$result->case_id
]['action'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
654 'id' => $result->case_id
,
655 'cid' => $result->contact_id
,
660 'case.actions.primary',
664 $casesList[$result->case_id
]['moreActions'] = CRM_Core_Action
::formLink($actions['moreActions'],
667 'id' => $result->case_id
,
668 'cid' => $result->contact_id
,
678 elseif ($field == 'case_status') {
679 if (in_array($result->$field, $caseStatus)) {
680 $casesList[$result->case_id
]['class'] = "status-urgent";
683 $casesList[$result->case_id
]['class'] = "status-normal";
688 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
689 $caseManagerContact = self
::getCaseManagerContact($caseTypes[$result->case_type_id
], $result->case_id
);
690 if (!empty($caseManagerContact)) {
691 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
692 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
695 //do check user permissions for edit/view activity.
696 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
697 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
699 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
701 $casesList[$result->case_id
]['activity_type_id'], $userID
703 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
705 $casesList[$result->case_id
]['activity_type_id'], $userID
714 * Get the summary of cases counts by type and status.
716 * @param bool $allCases
720 public static function getCasesSummary($allCases = TRUE, $userID) {
721 $caseSummary = array();
723 //validate access for civicase.
724 if (!self
::accessCiviCase()) {
728 //validate access for all cases.
729 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
733 $caseTypes = CRM_Case_PseudoConstant
::caseType();
734 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
735 $caseTypes = array_flip($caseTypes);
737 // get statuses as headers for the table
738 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
739 foreach ($caseStatuses as $key => $name) {
740 $caseSummary['headers'][$key]['status'] = $name;
741 $caseSummary['headers'][$key]['url'] = $url . $key;
744 // build rows with actual data
746 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
752 $myGroupByClause = ' GROUP BY civicrm_case.id';
757 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
758 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
760 $myGroupByClause .= ", case_status.label, status_id, case_type_id";
762 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
764 SELECT case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
765 case_type_id, case_relationship.contact_id_b
767 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
768 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
769 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
770 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
771 AND option_group_case_status.id = case_status.option_group_id )
772 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
773 AND case_relationship.contact_id_b = {$userID})
774 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
775 {$myCaseWhereClause} {$myGroupByClause}";
777 $res = CRM_Core_DAO
::executeQuery($query);
778 while ($res->fetch()) {
779 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
780 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
783 $rows[$res->case_type
][$res->case_status
] = array(
785 'url' => CRM_Utils_System
::url('civicrm/case/search',
786 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
791 $caseSummary['rows'] = array_merge($caseTypes, $rows);
799 * @param int $contactID
803 * @param int $relationshipID
806 * case role / relationships
809 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
811 SELECT rel.id as civicrm_relationship_id,
812 con.sort_name as sort_name,
813 civicrm_email.email as email,
814 civicrm_phone.phone as phone,
815 con.id as civicrm_contact_id,
816 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
817 civicrm_relationship_type.id as relation_type,
818 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
819 FROM civicrm_relationship rel
820 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
821 INNER JOIN civicrm_contact con ON ((con.id <> %1 AND con.id IN (rel.contact_id_a, rel.contact_id_b)) OR (con.id = %1 AND rel.contact_id_b = rel.contact_id_a AND rel.contact_id_a = %1))
822 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
823 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
824 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
825 AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
828 1 => array($contactID, 'Positive'),
829 2 => array($caseID, 'Positive'),
832 if ($relationshipID) {
833 $query .= ' AND civicrm_relationship.id = %3 ';
834 $params[3] = array($relationshipID, 'Integer');
836 $dao = CRM_Core_DAO
::executeQuery($query, $params);
839 while ($dao->fetch()) {
840 $rid = $dao->civicrm_relationship_id
;
841 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
842 $values[$rid]['relation'] = $dao->relation
;
843 $values[$rid]['name'] = $dao->sort_name
;
844 $values[$rid]['email'] = $dao->email
;
845 $values[$rid]['phone'] = $dao->phone
;
846 $values[$rid]['relation_type'] = $dao->relation_type
;
847 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
848 $values[$rid]['client_id'] = $contactID;
849 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
857 * Get Case Activities.
861 * @param array $params
863 * @param int $contactID
866 * @param null $context
871 * Array of case activities
874 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
877 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
878 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
879 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
880 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
882 // CRM-5081 - formatting the dates to omit seconds.
883 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
885 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
887 ca.activity_type_id AS type,
888 ca.activity_type_id AS activity_type_id,
889 tcc.sort_name AS target_contact_name,
890 tcc.id AS target_contact_id,
891 scc.sort_name AS source_contact_name,
892 scc.id AS source_contact_id,
893 acc.sort_name AS assignee_contact_name,
894 acc.id AS assignee_contact_id,
896 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
897 ca.activity_date_time,
898 DATE_ADD(NOW(), INTERVAL 1 YEAR)
899 ), '%Y%m%d%H%i00') AS overdue_date,
900 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
901 ca.status_id AS status,
902 ca.subject AS subject,
903 ca.is_deleted AS deleted,
904 ca.priority_id AS priority,
906 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
909 FROM civicrm_case_activity cca
910 INNER JOIN civicrm_activity ca
911 ON ca.id = cca.activity_id
912 INNER JOIN civicrm_activity_contact cas
913 ON cas.activity_id = ca.id
914 AND cas.record_type_id = {$sourceID}
915 INNER JOIN civicrm_contact scc
916 ON scc.id = cas.contact_id
917 LEFT JOIN civicrm_activity_contact caa
918 ON caa.activity_id = ca.id
919 AND caa.record_type_id = {$assigneeID}
920 LEFT JOIN civicrm_contact acc
921 ON acc.id = caa.contact_id
922 LEFT JOIN civicrm_activity_contact cat
923 ON cat.activity_id = ca.id
924 AND cat.record_type_id = {$targetID}
925 LEFT JOIN civicrm_contact tcc
926 ON tcc.id = cat.contact_id
927 INNER JOIN civicrm_option_group cog
928 ON cog.name = 'activity_type'
929 INNER JOIN civicrm_option_value cov
930 ON cov.option_group_id = cog.id
931 AND cov.value = ca.activity_type_id
932 AND cov.is_active = 1
933 LEFT JOIN civicrm_entity_file ef
934 ON ef.entity_table = 'civicrm_activity'
935 AND ef.entity_id = ca.id
936 LEFT OUTER JOIN civicrm_option_group og
937 ON og.name = 'activity_status'
938 LEFT OUTER JOIN civicrm_option_value ov
939 ON ov.option_group_id=og.id
940 AND ov.name = 'Scheduled'";
943 WHERE cca.case_id= %1
944 AND ca.is_current_revision = 1';
946 if (!empty($params['source_contact_id'])) {
948 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
951 if (!empty($params['status_id'])) {
953 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
956 if (!empty($params['activity_deleted'])) {
958 AND ca.is_deleted = 1";
962 AND ca.is_deleted = 0";
965 if (!empty($params['activity_type_id'])) {
967 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
970 if (!empty($params['activity_date_low'])) {
971 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
973 if (!empty($fromActivityDate)) {
975 AND ca.activity_date_time >= '{$fromActivityDate}'";
978 if (!empty($params['activity_date_high'])) {
979 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
980 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
982 if (!empty($toActivityDate)) {
984 AND ca.activity_date_time <= '{$toActivityDate}'";
988 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
990 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
992 // CRM-5081 - added id to act like creation date
994 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
997 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
998 $orderBy = " ORDER BY $sortBy ";
1001 $page = CRM_Utils_Array
::value('page', $params);
1002 $rp = CRM_Utils_Array
::value('rp', $params);
1010 $start = (($page - 1) * $rp);
1011 $limit = " LIMIT $start, $rp";
1013 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
1014 $queryParams = array(1 => array($caseID, 'Integer'));
1016 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
1017 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
1019 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1020 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus();
1022 $url = CRM_Utils_System
::url("civicrm/case/activity",
1023 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1027 if ($context == 'fulltext') {
1028 $contextUrl = "&context={$context}";
1030 $editUrl = "{$url}&action=update{$contextUrl}";
1031 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1032 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1033 $viewTitle = ts('View activity');
1034 $statusTitle = ts('Edit Status');
1036 $emailActivityTypeIDs = array(
1037 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1041 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1047 $emailActivityTypeIDs = array(
1048 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1052 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1058 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1060 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1061 $compStatusValues = array();
1062 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1063 foreach ($compStatusNames as $name) {
1064 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1067 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=", FALSE, NULL, FALSE);
1068 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1069 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1072 $session = CRM_Core_Session
::singleton();
1073 $userID = $session->get('userID');
1076 $caseActivities = array();
1078 while ($dao->fetch()) {
1079 $caseActivity = array();
1080 $caseActivityId = $dao->id
;
1082 $allowView = self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID);
1083 $allowEdit = self
::checkPermission($caseActivityId, 'edit', $dao->activity_type_id
, $userID);
1084 $allowDelete = self
::checkPermission($caseActivityId, 'delete', $dao->activity_type_id
, $userID);
1086 //do not have sufficient permission
1087 //to access given case activity record.
1088 if (!$allowView && !$allowEdit && !$allowDelete) {
1092 $caseActivity['DT_RowId'] = $caseActivityId;
1093 //Add classes to the row, via DataTables syntax
1094 $caseActivity['DT_RowClass'] = "crm-entity";
1096 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1097 $caseActivity['DT_RowClass'] .= " status-completed";
1100 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1101 $caseActivity['DT_RowClass'] .= " status-overdue";
1104 $caseActivity['DT_RowClass'] .= " status-scheduled";
1108 if (!empty($dao->priority
)) {
1109 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1110 $caseActivity['DT_RowClass'] .= " priority-urgent ";
1112 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1113 $caseActivity['DT_RowClass'] .= " priority-low ";
1117 //Add data to the row for inline editing, via DataTable syntax
1118 $caseActivity['DT_RowAttr'] = array();
1119 $caseActivity['DT_RowAttr']['data-entity'] = 'activity';
1120 $caseActivity['DT_RowAttr']['data-id'] = $caseActivityId;
1122 //Activity Date and Time
1123 $caseActivity['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1126 $caseActivity['subject'] = $dao->subject
;
1129 $caseActivity['type'] = $activityTypes[$dao->type
]['label'];
1131 //Activity Target (With)
1132 $targetContact = '';
1133 if (isset($dao->target_contact_id
)) {
1134 $targetContact = $dao->target_contact_name
;
1135 if ($hasViewContact) {
1136 $targetContact = '<a href="' . $contactViewUrl . $dao->target_contact_id
. '">' . $dao->target_contact_name
. '</a>';
1139 $caseActivity['target_contact_name'] = $targetContact;
1141 //Activity Source Contact (Reporter)
1142 $sourceContact = $dao->source_contact_name
;
1143 if ($hasViewContact) {
1144 $sourceContact = '<a href="' . $contactViewUrl . $dao->source_contact_id
. '">' . $dao->source_contact_name
. '</a>';
1146 $caseActivity['source_contact_name'] = $sourceContact;
1148 //Activity Assignee. CRM-4485.
1149 $assigneeContact = '';
1150 if (isset($dao->assignee_contact_id
)) {
1151 $assigneeContact = $dao->assignee_contact_name
;
1152 if ($hasViewContact) {
1153 $assigneeContact = '<a href="' . $contactViewUrl . $dao->assignee_contact_id
. '">' . $dao->assignee_contact_name
. '</a>';
1156 $caseActivity['assignee_contact_name'] = $assigneeContact;
1159 $caseActivity['status_id'] = $activityStatuses[$dao->status
];
1161 // 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.
1163 $css = 'class="action-item crm-hover-button"';
1165 $viewUrl = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1166 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1168 $additionalUrl = "&id={$caseActivityId}";
1169 if (!$dao->deleted
) {
1170 //hide edit link of activity type email.CRM-4530.
1171 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1172 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1174 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1178 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1181 elseif (!$caseDeleted) {
1182 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1183 $caseActivity['status_id'] = $caseActivity['status_id'] . '<br /> (deleted)';
1186 //check for operations.
1187 if (self
::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id
)) {
1188 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1190 if (self
::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id
)) {
1191 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1193 // if there are file attachments we will return how many and, if only one, add a link to it
1194 if (!empty($dao->attachment_ids
)) {
1195 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1196 $caseActivity['no_attachments'] = count($attachmentIDs);
1197 $url .= implode(' ', CRM_Core_BAO_File
::paperIconAttachment('civicrm_activity', $caseActivityId));
1200 $caseActivity['links'] = $url;
1202 array_push($caseActivities, $caseActivity);
1206 $caseActivitiesDT = array();
1207 $caseActivitiesDT['data'] = $caseActivities;
1208 $caseActivitiesDT['recordsTotal'] = $caseCount;
1209 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1211 return $caseActivitiesDT;
1215 * Get Case Related Contacts.
1217 * @param int $caseID
1219 * @param bool $skipDetails
1220 * If true include details of contacts.
1223 * array of return properties
1226 public static function getRelatedContacts($caseID, $skipDetails = FALSE) {
1229 SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, crt.label_b_a as role, ce.email
1230 FROM civicrm_relationship cr
1231 LEFT JOIN civicrm_relationship_type crt
1232 ON crt.id = cr.relationship_type_id
1233 LEFT JOIN civicrm_contact cc
1234 ON cc.id = cr.contact_id_b
1235 LEFT JOIN civicrm_email ce
1236 ON ce.contact_id = cc.id
1237 AND ce.is_primary= 1
1238 WHERE cr.case_id = %1';
1240 $params = array(1 => array($caseID, 'Integer'));
1241 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1243 while ($dao->fetch()) {
1245 $values[$dao->id
] = 1;
1249 'contact_id' => $dao->id
,
1250 'display_name' => $dao->name
,
1251 'sort_name' => $dao->sort_name
,
1252 'role' => $dao->role
,
1253 'email' => $dao->email
,
1263 * Send e-mail copy of activity
1265 * @param int $clientId
1266 * @param int $activityId
1268 * @param array $contacts
1269 * Array of related contact.
1271 * @param null $attachments
1272 * @param int $caseId
1274 * @return bool |array
1276 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1281 $tplParams = $activityInfo = array();
1282 //if its a case activity
1284 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1285 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1286 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1287 $anyActivity = TRUE;
1290 $anyActivity = FALSE;
1292 $tplParams['isCaseActivity'] = 1;
1293 $tplParams['client_id'] = $clientId;
1296 $anyActivity = TRUE;
1299 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1300 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1302 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1304 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1306 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1308 $tplParams['activity'] = $activityInfo;
1309 foreach ($tplParams['activity']['fields'] as $k => $val) {
1310 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1311 $activitySubject = $val['value'];
1315 $session = CRM_Core_Session
::singleton();
1316 // CRM-8926 If user is not logged in, use the activity creator as userID
1317 if (!($userID = $session->get('userID'))) {
1318 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1321 //also create activities simultaneously of this copy.
1322 $activityParams = array();
1324 $activityParams['source_record_id'] = $activityId;
1325 $activityParams['source_contact_id'] = $userID;
1326 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1327 $activityParams['activity_date_time'] = date('YmdHis');
1328 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1329 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1330 $activityParams['case_id'] = $caseId;
1331 $activityParams['is_auto'] = 0;
1332 $activityParams['target_id'] = $clientId;
1334 $tplParams['activitySubject'] = $activitySubject;
1336 // if it’s a case activity, add hashed id to the template (CRM-5916)
1338 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1342 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($userID);
1344 $receiptFrom = "$name <$address>";
1346 $recordedActivityParams = array();
1348 foreach ($contacts as $mail => $info) {
1349 $tplParams['contact'] = $info;
1350 self
::buildPermissionLinks($tplParams, $activityParams);
1352 $displayName = CRM_Utils_Array
::value('display_name', $info);
1354 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1356 'groupName' => 'msg_tpl_workflow_case',
1357 'valueName' => 'case_activity',
1358 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1359 'tplParams' => $tplParams,
1360 'from' => $receiptFrom,
1361 'toName' => $displayName,
1363 'attachments' => $attachments,
1367 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1368 $activityParams['details'] = $message;
1370 if (!empty($result[$info['contact_id']])) {
1372 * Really only need to record one activity with all the targets combined.
1373 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1374 * but it's always the same content at the moment.
1376 if (empty($recordedActivityParams)) {
1377 $recordedActivityParams = $activityParams;
1380 $recordedActivityParams['subject'] .= "; $displayName";
1382 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1385 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1389 if (!empty($recordedActivityParams)) {
1390 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1392 //create case_activity record if its case activity.
1394 $caseParams = array(
1395 'activity_id' => $activity->id
,
1396 'case_id' => $caseId,
1398 self
::processCaseActivity($caseParams);
1406 * Retrieve count of activities having a particular type, and
1407 * associated with a particular case.
1409 * @param int $caseId
1411 * @param int $activityTypeId
1412 * ID of the activity type.
1416 public static function getCaseActivityCount($caseId, $activityTypeId) {
1417 $queryParam = array(
1418 1 => array($caseId, 'Integer'),
1419 2 => array($activityTypeId, 'Integer'),
1421 $query = "SELECT count(ca.id) as countact
1422 FROM civicrm_activity ca
1423 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1424 WHERE ca.activity_type_id = %2
1425 AND cca.case_id = %1
1426 AND ca.is_deleted = 0";
1428 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1429 if ($dao->fetch()) {
1430 return $dao->countact
;
1437 * Create an activity for a case via email.
1442 * @return array|void
1443 * $activity object of newly creted activity via email
1445 public static function recordActivityViaEmail($file) {
1446 if (!file_exists($file) ||
1449 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1454 $result = CRM_Utils_Mail_Incoming
::parse($file);
1455 if ($result['is_error']) {
1459 foreach ($result['to'] as $to) {
1462 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1463 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1465 if ($replacement !== $to['email']) {
1466 $caseId = $replacement;
1467 //if caseId is invalid, return as error file
1468 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1469 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1478 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1479 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1480 $contactDetails = self
::getRelatedContacts($caseId, TRUE);
1482 if (!empty($contactDetails[$result['from']['id']])) {
1484 $params['subject'] = $result['subject'];
1485 $params['activity_date_time'] = $result['date'];
1486 $params['details'] = $result['body'];
1487 $params['source_contact_id'] = $result['from']['id'];
1488 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1493 $details = CRM_Case_PseudoConstant
::caseActivityType();
1495 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1496 $result['body'], $matches
1499 if (!empty($matches) && isset($matches[1])) {
1500 $activityType = trim($matches[1]);
1501 if (isset($details[$activityType])) {
1502 $params['activity_type_id'] = $details[$activityType]['id'];
1505 if (!isset($params['activity_type_id'])) {
1506 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1510 $activity = CRM_Activity_BAO_Activity
::create($params);
1512 $caseParams = array(
1513 'activity_id' => $activity->id
,
1514 'case_id' => $caseId,
1516 self
::processCaseActivity($caseParams);
1519 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1520 array(1 => $result['from']['email'])
1527 * Retrieve the scheduled activity type and date.
1529 * @param array $cases
1530 * Array of contact and case id.
1532 * @param string $type
1535 * Array of scheduled activity type and date
1539 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1540 $session = CRM_Core_Session
::singleton();
1541 $userID = $session->get('userID');
1543 $caseID = implode(',', $cases['case_id']);
1544 $contactID = implode(',', $cases['contact_id']);
1547 AND civicrm_case_contact.contact_id IN( {$contactID} )
1548 AND civicrm_case.id IN( {$caseID})
1549 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1551 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1553 $res = CRM_Core_DAO
::executeQuery($query);
1555 $activityInfo = array();
1556 while ($res->fetch()) {
1557 if ($type == 'upcoming') {
1558 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1559 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1562 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1563 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1567 return $activityInfo;
1571 * Combine all the exportable fields from the lower levels object.
1574 * array of exportable Fields
1576 public static function &exportableFields() {
1577 if (!self
::$_exportableFields) {
1578 if (!self
::$_exportableFields) {
1579 self
::$_exportableFields = array();
1582 $fields = CRM_Case_DAO_Case
::export();
1583 $fields['case_role'] = array('title' => ts('Role in Case'));
1584 $fields['case_type'] = array(
1585 'title' => ts('Case Type'),
1586 'name' => 'case_type',
1588 $fields['case_status'] = array(
1589 'title' => ts('Case Status'),
1590 'name' => 'case_status',
1593 // add custom data for cases
1594 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1596 self
::$_exportableFields = $fields;
1598 return self
::$_exportableFields;
1602 * Restore the record that are associated with this case.
1604 * @param int $caseId
1605 * Id of the case to restore.
1609 public static function restoreCase($caseId) {
1610 //restore activities
1611 $activities = self
::getCaseActivityDates($caseId);
1613 foreach ($activities as $value) {
1614 CRM_Activity_BAO_Activity
::restoreActivity($value);
1618 $case = new CRM_Case_DAO_Case();
1619 $case->id
= $caseId;
1620 $case->is_deleted
= 0;
1623 //CRM-7364, enable relationships
1624 self
::enableDisableCaseRelationships($caseId, TRUE);
1631 * @param null $showLinks
1632 * @param bool $returnOnlyCount
1633 * @param int $offset
1634 * @param int $rowCount
1638 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1639 $globalContacts = array();
1641 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1642 $settings = $settingsProcessor->run();
1643 if (!empty($settings)) {
1644 $groupInfo['name'] = $settings['groupname'];
1645 if ($groupInfo['name']) {
1646 $searchParams = array('name' => $groupInfo['name']);
1648 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1650 $groupInfo['id'] = $results['id'];
1651 $groupInfo['title'] = $results['title'];
1652 $params = array(array('group', '=', $groupInfo['id'], 0, 0));
1653 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1654 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1656 if ($returnOnlyCount) {
1657 return $globalContacts;
1661 foreach ($globalContacts as $idx => $contact) {
1662 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1668 return $globalContacts;
1672 * Convenience function to get both case contacts and global in one array.
1673 * @param int $caseId
1677 public static function getRelatedAndGlobalContacts($caseId) {
1678 $relatedContacts = self
::getRelatedContacts($caseId);
1680 $groupInfo = array();
1681 $globalContacts = self
::getGlobalContacts($groupInfo);
1683 //unset values which are not required.
1684 foreach ($globalContacts as $k => & $v) {
1685 unset($v['email_id']);
1686 unset($v['group_contact_id']);
1687 unset($v['status']);
1689 $v['role'] = $groupInfo['title'];
1691 //include multiple listings for the same contact/different roles.
1692 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1693 return $relatedGlobalContacts;
1697 * Get Case ActivitiesDueDates with given criteria.
1699 * @param int $caseID
1701 * @param array $criteriaParams
1703 * @param bool $latestDate
1704 * If set newest or oldest date is selected.
1707 * case activities due dates
1710 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1712 $selectDate = " ca.activity_date_time";
1713 $where = $groupBy = ' ';
1720 if (!empty($criteriaParams['activity_type_id'])) {
1721 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1722 $where .= " AND ca.is_current_revision = 1";
1723 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1726 if (!empty($criteriaParams['newest'])) {
1727 $selectDate = " max(ca.activity_date_time) ";
1730 $selectDate = " min(ca.activity_date_time) ";
1734 $query = "SELECT ca.id, {$selectDate} as activity_date
1735 FROM civicrm_activity ca
1736 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1737 WHERE cc.id = %1 {$where} {$groupBy}";
1739 $params = array(1 => array($caseID, 'Integer'));
1740 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1742 while ($dao->fetch()) {
1743 $values[$dao->id
]['id'] = $dao->id
;
1744 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1751 * Create activities when Case or Other roles assigned/modified/deleted.
1753 * @param int $caseId
1754 * @param int $relationshipId
1756 * @param int $relContactId
1757 * Case role assignee contactId.
1758 * @param int $contactId
1760 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1761 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1765 $queryParam = array();
1766 if (is_array($relationshipId)) {
1767 $relationshipId = implode(',', $relationshipId);
1768 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1771 $relationshipClause = " civicrm_relationship.id = %1";
1772 $queryParam[1] = array($relationshipId, 'Positive');
1776 SELECT cc.display_name as clientName,
1777 cca.display_name as assigneeContactName,
1778 civicrm_relationship.case_id as caseId,
1779 civicrm_relationship_type.label_a_b as relation_a_b,
1780 civicrm_relationship_type.label_b_a as relation_b_a,
1781 civicrm_relationship.contact_id_b as rel_contact_id,
1782 civicrm_relationship.contact_id_a as assign_contact_id
1783 FROM civicrm_relationship_type, civicrm_relationship
1784 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1785 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1786 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1788 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1790 while ($dao->fetch()) {
1791 // The assignee is not the client.
1792 if ($dao->rel_contact_id
!= $contactId) {
1793 $caseRelationship = $dao->relation_a_b
;
1794 $assigneContactName = $dao->clientName
;
1795 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1798 $caseRelationship = $dao->relation_b_a
;
1799 $assigneContactName = $dao->assigneeContactName
;
1800 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1804 $session = CRM_Core_Session
::singleton();
1805 $activityParams = array(
1806 'source_contact_id' => $session->get('userID'),
1807 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1808 'activity_date_time' => date('YmdHis'),
1809 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1812 //if $relContactId is passed, role is added or modified.
1813 if (!empty($relContactId)) {
1814 $activityParams['assignee_contact_id'] = $assigneContactIds;
1816 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1822 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1828 $activityParams['activity_type_id'] = $activityTypeID;
1830 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1832 //create case_activity record.
1833 $caseParams = array(
1834 'activity_id' => $activity->id
,
1835 'case_id' => $caseId,
1838 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1843 * contact which is assigned a case role of case manager.
1845 * @param int $caseType
1847 * @param int $caseId
1851 * array of contact on success otherwise empty
1854 public static function getCaseManagerContact($caseType, $caseId) {
1855 if (!$caseType ||
!$caseId) {
1859 $caseManagerContact = array();
1860 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1862 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1864 if (!empty($managerRoleId)) {
1865 $managerRoleQuery = "
1866 SELECT civicrm_contact.id as casemanager_id,
1867 civicrm_contact.sort_name as casemanager
1868 FROM civicrm_contact
1869 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1870 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1871 WHERE civicrm_case.id = %2";
1873 $managerRoleParams = array(
1874 1 => array($managerRoleId, 'Integer'),
1875 2 => array($caseId, 'Integer'),
1878 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1879 if ($dao->fetch()) {
1880 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1881 $caseManagerContact['casemanager'] = $dao->casemanager
;
1885 return $caseManagerContact;
1889 * @param int $contactId
1890 * @param bool $excludeDeleted
1894 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1895 $params = array('check_permissions' => TRUE);
1896 if ($excludeDeleted) {
1897 $params['is_deleted'] = 0;
1900 $params['contact_id'] = $contactId;
1903 return civicrm_api3('Case', 'getcount', $params);
1905 catch (CiviCRM_API3_Exception
$e) {
1906 // Lack of permissions will throw an exception
1912 * Retrieve related cases for give case.
1914 * @param int $mainCaseId
1916 * @param int $contactId
1918 * @param bool $excludeDeleted
1919 * Do not include deleted cases.
1923 public static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
1924 //FIXME : do check for permissions.
1926 $relatedCases = array();
1927 if (!$mainCaseId ||
!$contactId) {
1928 return $relatedCases;
1931 $linkActType = array_search('Link Cases',
1932 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
1934 if (!$linkActType) {
1935 return $relatedCases;
1938 $whereClause = "mainCase.id = %2";
1939 if ($excludeDeleted) {
1940 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1943 //1. first fetch related case ids.
1945 SELECT relCaseAct.case_id
1946 FROM civicrm_case mainCase
1947 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1948 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1949 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1950 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1951 WHERE $whereClause";
1953 $dao = CRM_Core_DAO
::executeQuery($query, array(
1954 1 => array($linkActType, 'Integer'),
1955 2 => array($mainCaseId, 'Integer'),
1957 $relatedCaseIds = array();
1958 while ($dao->fetch()) {
1959 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1963 // there are no related cases.
1964 if (empty($relatedCaseIds)) {
1965 return $relatedCases;
1968 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1969 if ($excludeDeleted) {
1970 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1973 //filter for permissioned cases.
1974 $filterCases = array();
1975 $doFilterCases = FALSE;
1976 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1977 $doFilterCases = TRUE;
1978 $session = CRM_Core_Session
::singleton();
1979 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
1982 //2. fetch the details of related cases.
1984 SELECT relCase.id as id,
1985 civicrm_case_type.title as case_type,
1986 client.display_name as client_name,
1987 client.id as client_id
1988 FROM civicrm_case relCase
1989 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
1990 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
1991 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
1992 WHERE {$whereClause}";
1994 $dao = CRM_Core_DAO
::executeQuery($query);
1995 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
1996 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1998 while ($dao->fetch()) {
2000 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2001 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2002 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2003 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2005 $clientView = $dao->client_name
;
2006 if ($hasViewContact) {
2007 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2010 $relatedCases[$dao->id
] = array(
2011 'case_id' => $dao->id
,
2012 'case_type' => $dao->case_type
,
2013 'client_name' => $clientView,
2014 'links' => $caseView,
2019 return $relatedCases;
2023 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2025 * @see CRM_Dedupe_Merger::cpTables()
2027 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2029 * @param int $mainContactId
2030 * @param int $otherContactId
2032 public static function mergeContacts($mainContactId, $otherContactId) {
2033 self
::mergeCases($mainContactId, NULL, $otherContactId);
2037 * Function perform two task.
2038 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2039 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2041 * @param int $mainContactId
2042 * Contact id of main contact record.
2043 * @param int $mainCaseId
2044 * Case id of main case record.
2045 * @param int $otherContactId
2046 * Contact id of record which is going to merge.
2047 * @param int $otherCaseId
2048 * Case id of record which is going to merge.
2050 * @param bool $changeClient
2054 public static function mergeCases(
2055 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2056 $otherCaseId = NULL, $changeClient = FALSE) {
2057 $moveToTrash = TRUE;
2059 $duplicateContacts = FALSE;
2060 if ($mainContactId && $otherContactId &&
2061 $mainContactId != $otherContactId
2063 $duplicateContacts = TRUE;
2066 $duplicateCases = FALSE;
2067 if ($mainCaseId && $otherCaseId &&
2068 $mainCaseId != $otherCaseId
2070 $duplicateCases = TRUE;
2073 $mainCaseIds = array();
2074 if (!$duplicateContacts && !$duplicateCases) {
2075 return $mainCaseIds;
2078 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2079 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2080 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2081 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2082 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2083 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2085 $processCaseIds = array($otherCaseId);
2086 if ($duplicateContacts && !$duplicateCases) {
2087 if ($changeClient) {
2088 $processCaseIds = array($mainCaseId);
2091 //get all case ids for other contact.
2092 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2094 if (!is_array($processCaseIds)) {
2099 $session = CRM_Core_Session
::singleton();
2100 $currentUserId = $session->get('userID');
2102 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2104 // copy all cases and connect to main contact id.
2105 foreach ($processCaseIds as $otherCaseId) {
2106 if ($duplicateContacts) {
2107 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2108 $mainCaseId = $mainCase->id
;
2113 // CRM-11662 Copy Case custom data
2114 $extends = array('case');
2115 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2117 foreach ($groupTree as $groupID => $group) {
2118 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2119 foreach ($group['fields'] as $fieldID => $field) {
2120 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2124 foreach ($table as $tableName => $tableColumns) {
2125 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2126 $tableColumns[0] = $mainCaseId;
2127 $select = 'SELECT ' . implode(', ', $tableColumns);
2128 $from = ' FROM ' . $tableName;
2129 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2130 $query = $insert . $select . $from . $where;
2131 $dao = CRM_Core_DAO
::executeQuery($query);
2137 $mainCaseIds[] = $mainCaseId;
2138 //insert record for case contact.
2139 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2140 $otherCaseContact->case_id
= $otherCaseId;
2141 $otherCaseContact->find();
2142 while ($otherCaseContact->fetch()) {
2143 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2144 $mainCaseContact->case_id
= $mainCaseId;
2145 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2146 if ($mainCaseContact->contact_id
== $otherContactId) {
2147 $mainCaseContact->contact_id
= $mainContactId;
2149 //avoid duplicate object.
2150 if (!$mainCaseContact->find(TRUE)) {
2151 $mainCaseContact->save();
2153 $mainCaseContact->free();
2155 $otherCaseContact->free();
2157 elseif (!$otherContactId) {
2158 $otherContactId = $mainContactId;
2161 if (!$mainCaseId ||
!$otherCaseId ||
2162 !$mainContactId ||
!$otherContactId
2167 // get all activities for other case.
2168 $otherCaseActivities = array();
2169 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2171 //for duplicate cases do not process singleton activities.
2172 $otherActivityIds = $singletonActivityIds = array();
2173 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2174 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2175 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2178 $otherActivityIds[] = $otherActId;
2180 if ($duplicateCases) {
2181 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2184 FROM civicrm_activity
2185 WHERE activity_type_id = $openCaseType
2186 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2187 $dao = CRM_Core_DAO
::executeQuery($sql);
2188 while ($dao->fetch()) {
2189 $singletonActivityIds[] = $dao->id
;
2195 // migrate all activities and connect to main contact.
2196 $copiedActivityIds = $activityMappingIds = array();
2197 sort($otherActivityIds);
2198 foreach ($otherActivityIds as $otherActivityId) {
2200 //for duplicate cases -
2201 //do not migrate singleton activities.
2202 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2206 //migrate activity record.
2207 $otherActivity = new CRM_Activity_DAO_Activity();
2208 $otherActivity->id
= $otherActivityId;
2209 if (!$otherActivity->find(TRUE)) {
2213 $mainActVals = array();
2214 $mainActivity = new CRM_Activity_DAO_Activity();
2215 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2216 $mainActivity->copyValues($mainActVals);
2217 $mainActivity->id
= NULL;
2218 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2219 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2223 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2227 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2230 $mainActivity->save();
2231 $mainActivityId = $mainActivity->id
;
2232 if (!$mainActivityId) {
2236 $activityMappingIds[$otherActivityId] = $mainActivityId;
2237 // insert log of all activities
2238 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2240 $otherActivity->free();
2241 $mainActivity->free();
2242 $copiedActivityIds[] = $otherActivityId;
2244 //create case activity record.
2245 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2246 $mainCaseActivity->case_id
= $mainCaseId;
2247 $mainCaseActivity->activity_id
= $mainActivityId;
2248 $mainCaseActivity->save();
2249 $mainCaseActivity->free();
2251 //migrate source activity.
2252 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2253 $otherSourceActivity->activity_id
= $otherActivityId;
2254 $otherSourceActivity->record_type_id
= $sourceID;
2255 $otherSourceActivity->find();
2256 while ($otherSourceActivity->fetch()) {
2257 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2258 $mainActivitySource->record_type_id
= $sourceID;
2259 $mainActivitySource->activity_id
= $mainActivityId;
2260 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2261 if ($mainActivitySource->contact_id
== $otherContactId) {
2262 $mainActivitySource->contact_id
= $mainContactId;
2264 //avoid duplicate object.
2265 if (!$mainActivitySource->find(TRUE)) {
2266 $mainActivitySource->save();
2268 $mainActivitySource->free();
2270 $otherSourceActivity->free();
2272 //migrate target activities.
2273 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2274 $otherTargetActivity->activity_id
= $otherActivityId;
2275 $otherTargetActivity->record_type_id
= $targetID;
2276 $otherTargetActivity->find();
2277 while ($otherTargetActivity->fetch()) {
2278 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2279 $mainActivityTarget->record_type_id
= $targetID;
2280 $mainActivityTarget->activity_id
= $mainActivityId;
2281 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2282 if ($mainActivityTarget->contact_id
== $otherContactId) {
2283 $mainActivityTarget->contact_id
= $mainContactId;
2285 //avoid duplicate object.
2286 if (!$mainActivityTarget->find(TRUE)) {
2287 $mainActivityTarget->save();
2289 $mainActivityTarget->free();
2291 $otherTargetActivity->free();
2293 //migrate assignee activities.
2294 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2295 $otherAssigneeActivity->activity_id
= $otherActivityId;
2296 $otherAssigneeActivity->record_type_id
= $assigneeID;
2297 $otherAssigneeActivity->find();
2298 while ($otherAssigneeActivity->fetch()) {
2299 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2300 $mainAssigneeActivity->activity_id
= $mainActivityId;
2301 $mainAssigneeActivity->record_type_id
= $assigneeID;
2302 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2303 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2304 $mainAssigneeActivity->contact_id
= $mainContactId;
2306 //avoid duplicate object.
2307 if (!$mainAssigneeActivity->find(TRUE)) {
2308 $mainAssigneeActivity->save();
2310 $mainAssigneeActivity->free();
2312 $otherAssigneeActivity->free();
2314 // copy custom fields and attachments
2316 'activityID' => $otherActivityId,
2317 'mainActivityId' => $mainActivityId,
2319 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2322 //copy case relationship.
2323 if ($duplicateContacts) {
2324 //migrate relationship records.
2325 $otherRelationship = new CRM_Contact_DAO_Relationship();
2326 $otherRelationship->case_id
= $otherCaseId;
2327 $otherRelationship->find();
2328 $otherRelationshipIds = array();
2329 while ($otherRelationship->fetch()) {
2330 $otherRelVals = array();
2331 $updateOtherRel = FALSE;
2332 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2334 $mainRelationship = new CRM_Contact_DAO_Relationship();
2335 $mainRelationship->copyValues($otherRelVals);
2336 $mainRelationship->id
= NULL;
2337 $mainRelationship->case_id
= $mainCaseId;
2338 if ($mainRelationship->contact_id_a
== $otherContactId) {
2339 $updateOtherRel = TRUE;
2340 $mainRelationship->contact_id_a
= $mainContactId;
2343 //case creator change only when we merge user contact.
2344 if ($mainRelationship->contact_id_b
== $otherContactId) {
2345 //do not change creator for change client.
2346 if (!$changeClient) {
2347 $updateOtherRel = TRUE;
2348 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2351 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2352 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2354 //avoid duplicate object.
2355 if (!$mainRelationship->find(TRUE)) {
2356 $mainRelationship->save();
2358 $mainRelationship->free();
2360 //get the other relationship ids to update end date.
2361 if ($updateOtherRel) {
2362 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2365 $otherRelationship->free();
2367 //update other relationships end dates
2368 if (!empty($otherRelationshipIds)) {
2369 $sql = 'UPDATE civicrm_relationship
2370 SET end_date = CURDATE()
2371 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2372 CRM_Core_DAO
::executeQuery($sql);
2376 //move other case to trash.
2377 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2382 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2383 if ($changeClient) {
2384 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2385 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2387 $mergeActType = array_search('Reassigned Case', $activityTypes);
2388 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2391 2 => $otherContactDisplayName,
2392 3 => $mainContactDisplayName,
2397 elseif ($duplicateContacts) {
2398 $mergeActType = array_search('Merge Case', $activityTypes);
2399 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2402 2 => $otherContactId,
2403 3 => $mainContactId,
2409 $mergeActType = array_search('Merge Case', $activityTypes);
2410 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2411 if (!empty($copiedActivityIds)) {
2413 SELECT id, subject, activity_date_time, activity_type_id
2414 FROM civicrm_activity
2415 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2416 $dao = CRM_Core_DAO
::executeQuery($sql);
2417 while ($dao->fetch()) {
2418 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2419 if ($dao->subject
) {
2420 $mergeActSubjectDetails .= " :: {$dao->subject}";
2422 $mergeActSubjectDetails .= "<br />";
2427 //Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2428 $activityParams = array(
2429 'subject' => $mergeActSubject,
2430 'details' => $mergeActSubjectDetails,
2431 'status_id' => array_search('Completed', $activityStatuses),
2432 'activity_type_id' => $mergeActType,
2433 'source_contact_id' => $currentUserId,
2434 'activity_date_time' => date('YmdHis'),
2437 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2438 $mergeActivityId = $mergeActivity->id
;
2439 if (!$mergeActivityId) {
2442 $mergeActivity->free();
2444 //connect merge activity to case.
2445 $mergeCaseAct = array(
2446 'case_id' => $mainCaseId,
2447 'activity_id' => $mergeActivityId,
2450 self
::processCaseActivity($mergeCaseAct);
2453 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2455 return $mainCaseIds;
2459 * Validate contact permission for
2460 * edit/view on activity record and build links.
2462 * @param array $tplParams
2463 * Params to be sent to template for sending email.
2464 * @param array $activityParams
2465 * Info of the activity.
2467 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2468 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2469 'activity_type_id', 'id'
2472 if (!empty($tplParams['isCaseActivity'])) {
2473 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2474 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2477 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2478 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2481 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2482 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2486 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2487 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2490 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2491 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2497 * Validate contact permission for
2498 * given operation on activity record.
2500 * @param int $activityId
2501 * Activity record id.
2502 * @param string $operation
2504 * @param int $actTypeId
2506 * @param int $contactId
2507 * Contact id/if not pass consider logged in.
2508 * @param bool $checkComponent
2509 * Do we need to check component enabled.
2513 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2515 if (!$actTypeId && $activityId) {
2516 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2519 if (!$activityId ||
!$operation ||
!$actTypeId) {
2523 //do check for civicase component enabled.
2524 if ($checkComponent && !self
::enabled()) {
2528 //do check for cases.
2529 $caseActOperations = array(
2536 if (in_array($operation, $caseActOperations)) {
2538 if (!isset($caseCount)) {
2540 $caseCount = civicrm_api3('Case', 'getcount', array(
2541 'check_permissions' => TRUE,
2542 'status_id' => array('!=' => 'Closed'),
2544 'end_date' => array('IS NULL' => 1),
2547 catch (CiviCRM_API3_Exception
$e) {
2548 // Lack of permissions will throw an exception
2552 if ($operation == 'File On Case') {
2553 $allow = !empty($caseCount);
2556 $allow = ($caseCount > 1);
2560 $actionOperations = array('view', 'edit', 'delete');
2561 if (in_array($operation, $actionOperations)) {
2563 //do cache when user has non/supper permission.
2564 static $allowOperations;
2566 if (!is_array($allowOperations) ||
2567 !array_key_exists($operation, $allowOperations)
2571 $session = CRM_Core_Session
::singleton();
2572 $contactId = $session->get('userID');
2575 //check for permissions.
2576 $permissions = array(
2578 'access my cases and activities',
2579 'access all cases and activities',
2582 'access my cases and activities',
2583 'access all cases and activities',
2585 'delete' => array('delete activities'),
2588 //check for core permission.
2589 $hasPermissions = array();
2590 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2591 if (is_array($checkPermissions)) {
2592 foreach ($checkPermissions as $per) {
2593 if (CRM_Core_Permission
::check($per)) {
2594 $hasPermissions[$operation][] = $per;
2600 if (!empty($hasPermissions)) {
2601 //need to check activity object specific.
2602 if (in_array($operation, array(
2607 //do we have supper permission.
2608 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2609 $allowOperations[$operation] = $allow = TRUE;
2612 //user has only access to my cases and activity.
2613 //here object specific permmions come in picture.
2615 //edit - contact must be source or assignee
2616 //view - contact must be source/assignee/target
2617 $isTarget = $isAssignee = $isSource = FALSE;
2618 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2619 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2620 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2621 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2623 $target = new CRM_Activity_DAO_ActivityContact();
2624 $target->record_type_id
= $targetID;
2625 $target->activity_id
= $activityId;
2626 $target->contact_id
= $contactId;
2627 if ($target->find(TRUE)) {
2631 $assignee = new CRM_Activity_DAO_ActivityContact();
2632 $assignee->activity_id
= $activityId;
2633 $assignee->record_type_id
= $assigneeID;
2634 $assignee->contact_id
= $contactId;
2635 if ($assignee->find(TRUE)) {
2639 $source = new CRM_Activity_DAO_ActivityContact();
2640 $source->activity_id
= $activityId;
2641 $source->record_type_id
= $sourceID;
2642 $source->contact_id
= $contactId;
2643 if ($source->find(TRUE)) {
2647 if ($operation == 'edit') {
2648 if ($isAssignee ||
$isSource) {
2652 if ($operation == 'view') {
2653 if ($isTarget ||
$isAssignee ||
$isSource) {
2659 elseif (is_array($hasPermissions[$operation])) {
2660 $allowOperations[$operation] = $allow = TRUE;
2664 //contact do not have permission.
2665 $allowOperations[$operation] = FALSE;
2670 //here contact might have supper/non permission.
2671 $allow = $allowOperations[$operation];
2675 //do further only when operation is granted.
2677 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2679 //get the activity type name.
2680 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2682 //do not allow multiple copy / edit action.
2683 $singletonNames = array(
2693 //do not allow to delete these activities, CRM-4543
2694 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2696 //allow edit operation.
2697 $allowEditNames = array('Open Case');
2699 // do not allow File on Case
2700 $doNotFileNames = array(
2703 'Change Case Status',
2704 'Change Case Start Date',
2711 if (in_array($actTypeName, $singletonNames)) {
2713 if ($operation == 'File On Case') {
2714 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2716 if (in_array($operation, $actionOperations)) {
2718 if ($operation == 'edit') {
2719 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2721 elseif ($operation == 'delete') {
2722 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2726 if ($allow && ($operation == 'delete') &&
2727 in_array($actTypeName, $doNotDeleteNames)
2732 if ($allow && ($operation == 'File On Case') &&
2733 in_array($actTypeName, $doNotFileNames)
2738 //check settings file for masking actions
2739 //on the basis the activity types
2740 //hide Edit link if activity type is NOT editable
2741 //(special case activities).CRM-5871
2742 if ($allow && in_array($operation, $actionOperations)) {
2743 static $actionFilter = array();
2744 if (!array_key_exists($operation, $actionFilter)) {
2745 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2746 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2748 if (array_key_exists($operation, $actionFilter[$operation]) &&
2749 in_array($actTypeId, $actionFilter[$operation][$operation])
2760 * Since we drop 'access CiviCase', allow access
2761 * if user has 'access my cases and activities'
2762 * or 'access all cases and activities'
2764 public static function accessCiviCase() {
2765 if (!self
::enabled()) {
2769 if (CRM_Core_Permission
::check('access my cases and activities') ||
2770 CRM_Core_Permission
::check('access all cases and activities')
2779 * Verify user has permission to access a case.
2781 * @param int $caseId
2782 * @param bool $denyClosed
2783 * Set TRUE if one wants closed cases to be treated as inaccessible.
2787 public static function accessCase($caseId, $denyClosed = TRUE) {
2788 if (!$caseId ||
!self
::enabled()) {
2792 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2793 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2794 $params['status_id'] = array('!=' => 'Closed');
2797 return (bool) civicrm_api3('Case', 'getcount', $params);
2799 catch (CiviCRM_API3_Exception
$e) {
2800 // Lack of permissions will throw an exception
2806 * Check whether activity is a case Activity.
2808 * @param int $activityID
2813 public static function isCaseActivity($activityID) {
2814 $isCaseActivity = FALSE;
2816 $params = array(1 => array($activityID, 'Integer'));
2817 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2818 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2819 $isCaseActivity = TRUE;
2823 return $isCaseActivity;
2827 * Get all the case type ids currently in use.
2831 public static function getUsedCaseType() {
2832 static $caseTypeIds;
2834 if (!is_array($caseTypeIds)) {
2835 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2837 $dao = CRM_Core_DAO
::executeQuery($query);
2838 $caseTypeIds = array();
2839 while ($dao->fetch()) {
2840 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2843 $caseTypeIds[] = $typeId[1];
2847 return $caseTypeIds;
2851 * Get all the case status ids currently in use.
2855 public static function getUsedCaseStatuses() {
2856 static $caseStatusIds;
2858 if (!is_array($caseStatusIds)) {
2859 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2861 $dao = CRM_Core_DAO
::executeQuery($query);
2862 $caseStatusIds = array();
2863 while ($dao->fetch()) {
2864 $caseStatusIds[] = $dao->status_id
;
2868 return $caseStatusIds;
2872 * Get all the encounter medium ids currently in use.
2876 public static function getUsedEncounterMediums() {
2879 if (!is_array($mediumIds)) {
2880 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2882 $dao = CRM_Core_DAO
::executeQuery($query);
2883 $mediumIds = array();
2884 while ($dao->fetch()) {
2885 $mediumIds[] = $dao->medium_id
;
2893 * Check case configuration.
2895 * @param int $contactId
2899 public static function isCaseConfigured($contactId = NULL) {
2900 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2902 //lets check for case configured.
2903 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2904 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2905 if (!$configured['configured']) {
2906 //do check for case type and case status.
2907 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2908 if (!empty($caseTypes)) {
2909 $configured['configured'] = TRUE;
2910 if (!$configured['configured']) {
2911 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2912 if (!empty($caseStatuses)) {
2913 $configured['configured'] = TRUE;
2918 if ($configured['configured']) {
2919 //do check for active case type and case status.
2920 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2921 if (!empty($caseTypes)) {
2922 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2923 if (!empty($caseStatuses)) {
2924 $configured['allowToAddNewCase'] = TRUE;
2928 //do we need to redirect user to case admin.
2929 if (!$configured['allowToAddNewCase'] && $contactId) {
2930 //check for current contact case count.
2931 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2932 //redirect user to case admin page.
2933 if (!$currentContatCasesCount) {
2934 $configured['redirectToCaseAdmin'] = TRUE;
2943 * Used during case component enablement and during ugprade.
2947 public static function createCaseViews() {
2948 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2949 $dao = new CRM_Core_DAO();
2951 $sql = self
::createCaseViewsQuery('upcoming');
2953 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2957 // Above error doesn't get caught?
2958 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2959 if (is_null($doublecheck)) {
2963 $sql = self
::createCaseViewsQuery('recent');
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_recent");
2971 if (is_null($doublecheck)) {
2979 * Helper function, also used by the upgrade in case of error
2981 * @param string $section
2985 public static function createCaseViewsQuery($section = 'upcoming') {
2987 $scheduled_id = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
2990 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
2991 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
2992 FROM civicrm_case_activity ca
2993 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
2994 WHERE a.activity_date_time =
2995 (SELECT b.activity_date_time FROM civicrm_case_activity bca
2996 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
2997 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
2998 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
2999 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
3003 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3004 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3005 FROM civicrm_case_activity ca
3006 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3007 WHERE a.activity_date_time =
3008 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3009 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3010 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3011 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
3012 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
3019 * Add/copy relationships, when new client is added for a case
3021 * @param int $caseId
3023 * @param int $contactId
3024 * Contact id / new client id.
3026 public static function addCaseRelationships($caseId, $contactId) {
3027 // get the case role / relationships for the case
3028 $caseRelationships = new CRM_Contact_DAO_Relationship();
3029 $caseRelationships->case_id
= $caseId;
3030 $caseRelationships->find();
3031 $relationshipTypes = array();
3033 // make sure we don't add duplicate relationships of same relationship type.
3034 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3036 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3038 // add relationship for new client.
3039 $newRelationship = new CRM_Contact_DAO_Relationship();
3040 $newRelationship->copyValues($values);
3041 $newRelationship->id
= NULL;
3042 $newRelationship->case_id
= $caseId;
3043 $newRelationship->contact_id_a
= $contactId;
3044 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3045 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3047 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3048 if (!$newRelationship->find(TRUE)) {
3049 $newRelationship->save();
3051 $newRelationship->free();
3053 // store relationship type of newly created relationship
3054 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3059 * Get the list of clients for a case.
3061 * @param int $caseId
3064 * associated array with client ids
3066 public static function getCaseClients($caseId) {
3068 $caseContact = new CRM_Case_DAO_CaseContact();
3069 $caseContact->case_id
= $caseId;
3070 $caseContact->find();
3072 while ($caseContact->fetch()) {
3073 $clients[] = $caseContact->contact_id
;
3080 * @param int $caseId
3081 * @param string $direction
3083 * @param int $relTypeId
3084 * @throws \CRM_Core_Exception
3085 * @throws \CiviCRM_API3_Exception
3087 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3089 if ($direction !== 'a' && $direction !== 'b') {
3090 throw new CRM_Core_Exception('Invalid relationship direction');
3093 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3094 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3095 $dao = CRM_Core_DAO
::executeQuery($sql, array(
3096 1 => array($caseId, 'Positive'),
3097 2 => array($cid, 'Positive'),
3098 3 => array($relTypeId, 'Positive'),
3100 while ($dao->fetch()) {
3101 civicrm_api3('relationship', 'create', array(
3104 'end_date' => 'now',
3110 * Get options for a given case field.
3111 * @see CRM_Core_DAO::buildOptions
3113 * @param string $fieldName
3114 * @param string $context
3115 * @see CRM_Core_DAO::buildOptionsContext
3116 * @param array $props
3117 * Whatever is known about this dao object.
3119 * @return array|bool
3121 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3122 $className = __CLASS__
;
3124 switch ($fieldName) {
3125 // This field is not part of this object but the api supports it
3127 $className = 'CRM_Activity_BAO_Activity';
3130 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3136 public function addSelectWhereClause() {
3137 // We always return an array with these keys, even if they are empty,
3138 // because this tells the query builder that we have considered these fields for acls
3141 // Only case admins can view deleted cases
3142 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
array() : array("= 0"),
3144 // Ensure the user has permission to view the case client
3145 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3146 if ($contactClause) {
3147 $contactClause = implode(' AND contact_id ', $contactClause);
3148 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3150 // The api gatekeeper ensures the user has at least "access my cases and activities"
3151 // so if they do not have permission to see all cases we'll assume they can only access their own
3152 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3153 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3154 $clauses['id'][] = "IN (
3155 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 (
3156 (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)
3160 CRM_Utils_Hook
::selectWhereClause($this, $clauses);