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 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
333 ORDER BY civicrm_case_contact.id";
335 $dao = CRM_Core_DAO
::executeQuery($query,
336 array(1 => array($caseId, 'Integer'))
338 while ($dao->fetch()) {
339 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
340 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
341 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
342 $contactNames[$dao->cid
]['email'] = $dao->email
;
343 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
344 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
345 $contactNames[$dao->cid
]['role'] = ts('Client');
348 return $contactNames;
352 * Retrieve case_id by contact_id.
354 * @param int $contactID
355 * @param bool $includeDeleted
356 * Include the deleted cases in result.
357 * @param null $caseType
361 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
364 FROM civicrm_case_contact cc
365 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
367 if (isset($caseType)) {
369 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
370 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
372 if (!isset($caseType)) {
373 $query .= "WHERE cc.contact_id = %1";
375 if (!$includeDeleted) {
376 $query .= " AND ca.is_deleted = 0";
379 $params = array(1 => array($contactID, 'Integer'));
380 $dao = CRM_Core_DAO
::executeQuery($query, $params);
382 $caseArray = array();
383 while ($dao->fetch()) {
384 $caseArray[] = $dao->id
;
392 * @param string $type
394 * @param string $condition
398 public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL) {
400 $session = CRM_Core_Session
::singleton();
401 $userID = $session->get('userID');
405 civicrm_case.id as case_id,
406 civicrm_case.subject as case_subject,
407 civicrm_contact.id as contact_id,
408 civicrm_contact.sort_name as sort_name,
409 civicrm_phone.phone as phone,
410 civicrm_contact.contact_type as contact_type,
411 civicrm_contact.contact_sub_type as contact_sub_type,
412 t_act.activity_type_id,
413 c_type.title as case_type,
414 civicrm_case.case_type_id as case_type_id,
415 cov_status.label as case_status,
416 cov_status.label as case_status_name,
418 civicrm_case.start_date as case_start_date,
419 case_relation_type.label_b_a as case_role, ";
421 if ($type == 'upcoming') {
423 t_act.desired_date as case_scheduled_activity_date,
424 t_act.id as case_scheduled_activity_id,
425 t_act.act_type_name as case_scheduled_activity_type_name,
426 t_act.act_type AS case_scheduled_activity_type ";
428 elseif ($type == 'recent') {
430 t_act.desired_date as case_recent_activity_date,
431 t_act.id as case_recent_activity_id,
432 t_act.act_type_name as case_recent_activity_type_name,
433 t_act.act_type AS case_recent_activity_type ";
435 elseif ($type == 'any') {
437 t_act.desired_date as case_activity_date,
438 t_act.id as case_activity_id,
439 t_act.act_type_name as case_activity_type_name,
440 t_act.act_type AS case_activity_type ";
443 $query .= " FROM civicrm_case
444 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
445 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
447 if ($type == 'upcoming') {
448 // This gets the earliest activity per case that's scheduled within 14 days from now.
449 // 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.
450 // In this case we don't really care which one, so min(id) works.
451 // optimized in CRM-11837
452 $query .= " INNER JOIN
454 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
459 FROM civicrm_view_case_activity_upcoming
460 ORDER BY activity_date_time ASC, id ASC
463 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
464 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
468 elseif ($type == 'recent') {
469 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
470 //improve query performance - CRM-10598
471 $query .= " INNER JOIN
473 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
478 FROM civicrm_view_case_activity_recent
479 ORDER BY activity_date_time DESC, id ASC
482 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
483 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
486 elseif ($type == 'any') {
487 $query .= " LEFT JOIN
489 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
490 FROM civicrm_activity act4
491 LEFT JOIN civicrm_case_activity ca4
492 ON ca4.activity_id = act4.id
493 AND act4.is_current_revision = 1
494 LEFT JOIN civicrm_option_group aog
495 ON aog.name='activity_type'
496 LEFT JOIN civicrm_option_value aov
497 ON aov.option_group_id = aog.id
498 AND aov.value = act4.activity_type_id
503 ON t_act.case_id = civicrm_case.id
504 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
505 LEFT JOIN civicrm_relationship case_relationship
506 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
507 AND case_relationship.case_id = civicrm_case.id )
509 LEFT JOIN civicrm_relationship_type case_relation_type
510 ON ( case_relation_type.id = case_relationship.relationship_type_id
511 AND case_relation_type.id = case_relationship.relationship_type_id )
513 LEFT JOIN civicrm_case_type c_type
514 ON civicrm_case.case_type_id = c_type.id
516 LEFT JOIN civicrm_option_group cog_status
517 ON cog_status.name = 'case_status'
519 LEFT JOIN civicrm_option_value cov_status
520 ON ( civicrm_case.status_id = cov_status.value
521 AND cog_status.id = cov_status.option_group_id )
525 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
526 $query .= " WHERE (1) $condition ";
529 if ($type == 'upcoming') {
530 $query .= " ORDER BY case_scheduled_activity_date ASC ";
532 elseif ($type == 'recent') {
533 $query .= " ORDER BY case_recent_activity_date ASC ";
535 elseif ($type == 'any') {
536 $query .= " ORDER BY case_activity_date ASC ";
543 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
545 * @param bool $allCases
549 * @param string $type
550 * /upcoming,recent,all/.
552 * @param string $context
557 public static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') {
559 $casesList = array();
561 //validate access for own cases.
562 if (!self
::accessCiviCase()) {
567 $session = CRM_Core_Session
::singleton();
568 $userID = $session->get('userID');
571 //validate access for all cases.
572 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
576 $condition = " AND civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1";
579 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
581 if ($type == 'upcoming' ||
$type == 'any') {
582 $closedId = CRM_Core_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
584 AND civicrm_case.status_id != $closedId";
587 $query = self
::getCaseActivityQuery($type, $userID, $condition);
589 $queryParams = array();
590 $result = CRM_Core_DAO
::executeQuery($query,
594 $caseStatus = CRM_Core_OptionGroup
::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
596 $resultFields = array(
613 if ($type == 'upcoming') {
614 $resultFields[] = 'case_scheduled_activity_date';
615 $resultFields[] = 'case_scheduled_activity_type_name';
616 $resultFields[] = 'case_scheduled_activity_type';
617 $resultFields[] = 'case_scheduled_activity_id';
619 elseif ($type == 'recent') {
620 $resultFields[] = 'case_recent_activity_date';
621 $resultFields[] = 'case_recent_activity_type_name';
622 $resultFields[] = 'case_recent_activity_type';
623 $resultFields[] = 'case_recent_activity_id';
625 elseif ($type == 'any') {
626 $resultFields[] = 'case_activity_date';
627 $resultFields[] = 'case_activity_type_name';
628 $resultFields[] = 'case_activity_type';
629 $resultFields[] = 'case_activity_id';
632 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
633 $actions = CRM_Case_Selector_Search
::links();
635 // check is the user has view/edit signer permission
636 $permissions = array(CRM_Core_Permission
::VIEW
);
637 if (CRM_Core_Permission
::check('access all cases and activities') ||
638 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
640 $permissions[] = CRM_Core_Permission
::EDIT
;
642 if (CRM_Core_Permission
::check('delete in CiviCase')) {
643 $permissions[] = CRM_Core_Permission
::DELETE
;
645 $mask = CRM_Core_Action
::mask($permissions);
647 while ($result->fetch()) {
648 foreach ($resultFields as $donCare => $field) {
649 $casesList[$result->case_id
][$field] = $result->$field;
650 if ($field == 'contact_type') {
651 $casesList[$result->case_id
]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
653 $casesList[$result->case_id
]['action'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
655 'id' => $result->case_id
,
656 'cid' => $result->contact_id
,
661 'case.actions.primary',
666 elseif ($field == 'case_status') {
667 if (in_array($result->$field, $caseStatus)) {
668 $casesList[$result->case_id
]['class'] = "status-urgent";
671 $casesList[$result->case_id
]['class'] = "status-normal";
676 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
677 $caseManagerContact = self
::getCaseManagerContact($caseTypes[$result->case_type_id
], $result->case_id
);
678 if (!empty($caseManagerContact)) {
679 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
680 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
683 //do check user permissions for edit/view activity.
684 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
685 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
687 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
689 $casesList[$result->case_id
]['activity_type_id'], $userID
691 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
693 $casesList[$result->case_id
]['activity_type_id'], $userID
702 * Get the summary of cases counts by type and status.
704 * @param bool $allCases
708 public static function getCasesSummary($allCases = TRUE, $userID) {
709 $caseSummary = array();
711 //validate access for civicase.
712 if (!self
::accessCiviCase()) {
716 //validate access for all cases.
717 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
721 $caseTypes = CRM_Case_PseudoConstant
::caseType();
722 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
723 $caseTypes = array_flip($caseTypes);
725 // get statuses as headers for the table
726 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
727 foreach ($caseStatuses as $key => $name) {
728 $caseSummary['headers'][$key]['status'] = $name;
729 $caseSummary['headers'][$key]['url'] = $url . $key;
732 // build rows with actual data
734 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
740 $myGroupByClause = ' GROUP BY civicrm_case.id';
745 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
746 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
748 $myGroupByClause .= ", case_status.label, status_id, case_type_id";
750 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
752 SELECT case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
753 case_type_id, case_relationship.contact_id_b
755 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
756 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
757 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
758 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
759 AND option_group_case_status.id = case_status.option_group_id )
760 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
761 AND case_relationship.contact_id_b = {$userID})
762 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
763 {$myCaseWhereClause} {$myGroupByClause}";
765 $res = CRM_Core_DAO
::executeQuery($query);
766 while ($res->fetch()) {
767 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
768 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
771 $rows[$res->case_type
][$res->case_status
] = array(
773 'url' => CRM_Utils_System
::url('civicrm/case/search',
774 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
779 $caseSummary['rows'] = array_merge($caseTypes, $rows);
787 * @param int $contactID
791 * @param int $relationshipID
794 * case role / relationships
797 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
799 SELECT rel.id as civicrm_relationship_id,
800 con.sort_name as sort_name,
801 civicrm_email.email as email,
802 civicrm_phone.phone as phone,
803 con.id as civicrm_contact_id,
804 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
805 civicrm_relationship_type.id as relation_type,
806 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
807 FROM civicrm_relationship rel
808 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
809 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))
810 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
811 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
812 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
813 AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
816 1 => array($contactID, 'Positive'),
817 2 => array($caseID, 'Positive'),
820 if ($relationshipID) {
821 $query .= ' AND civicrm_relationship.id = %3 ';
822 $params[3] = array($relationshipID, 'Integer');
824 $dao = CRM_Core_DAO
::executeQuery($query, $params);
827 while ($dao->fetch()) {
828 $rid = $dao->civicrm_relationship_id
;
829 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
830 $values[$rid]['relation'] = $dao->relation
;
831 $values[$rid]['name'] = $dao->sort_name
;
832 $values[$rid]['email'] = $dao->email
;
833 $values[$rid]['phone'] = $dao->phone
;
834 $values[$rid]['relation_type'] = $dao->relation_type
;
835 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
836 $values[$rid]['client_id'] = $contactID;
837 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
845 * Get Case Activities.
849 * @param array $params
851 * @param int $contactID
854 * @param null $context
859 * Array of case activities
862 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
865 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
866 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
867 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
868 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
870 // CRM-5081 - formatting the dates to omit seconds.
871 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
873 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
875 ca.activity_type_id AS type,
876 ca.activity_type_id AS activity_type_id,
877 tcc.sort_name AS target_contact_name,
878 tcc.id AS target_contact_id,
879 scc.sort_name AS source_contact_name,
880 scc.id AS source_contact_id,
881 acc.sort_name AS assignee_contact_name,
882 acc.id AS assignee_contact_id,
884 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
885 ca.activity_date_time,
886 DATE_ADD(NOW(), INTERVAL 1 YEAR)
887 ), '%Y%m%d%H%i00') AS overdue_date,
888 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
889 ca.status_id AS status,
890 ca.subject AS subject,
891 ca.is_deleted AS deleted,
892 ca.priority_id AS priority,
894 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
897 FROM civicrm_case_activity cca
898 INNER JOIN civicrm_activity ca
899 ON ca.id = cca.activity_id
900 INNER JOIN civicrm_activity_contact cas
901 ON cas.activity_id = ca.id
902 AND cas.record_type_id = {$sourceID}
903 INNER JOIN civicrm_contact scc
904 ON scc.id = cas.contact_id
905 LEFT JOIN civicrm_activity_contact caa
906 ON caa.activity_id = ca.id
907 AND caa.record_type_id = {$assigneeID}
908 LEFT JOIN civicrm_contact acc
909 ON acc.id = caa.contact_id
910 LEFT JOIN civicrm_activity_contact cat
911 ON cat.activity_id = ca.id
912 AND cat.record_type_id = {$targetID}
913 LEFT JOIN civicrm_contact tcc
914 ON tcc.id = cat.contact_id
915 INNER JOIN civicrm_option_group cog
916 ON cog.name = 'activity_type'
917 INNER JOIN civicrm_option_value cov
918 ON cov.option_group_id = cog.id
919 AND cov.value = ca.activity_type_id
920 AND cov.is_active = 1
921 LEFT JOIN civicrm_entity_file ef
922 ON ef.entity_table = 'civicrm_activity'
923 AND ef.entity_id = ca.id
924 LEFT OUTER JOIN civicrm_option_group og
925 ON og.name = 'activity_status'
926 LEFT OUTER JOIN civicrm_option_value ov
927 ON ov.option_group_id=og.id
928 AND ov.name = 'Scheduled'";
931 WHERE cca.case_id= %1
932 AND ca.is_current_revision = 1';
934 if (!empty($params['source_contact_id'])) {
936 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
939 if (!empty($params['status_id'])) {
941 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
944 if (!empty($params['activity_deleted'])) {
946 AND ca.is_deleted = 1";
950 AND ca.is_deleted = 0";
953 if (!empty($params['activity_type_id'])) {
955 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
958 if (!empty($params['activity_date_low'])) {
959 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
961 if (!empty($fromActivityDate)) {
963 AND ca.activity_date_time >= '{$fromActivityDate}'";
966 if (!empty($params['activity_date_high'])) {
967 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
968 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
970 if (!empty($toActivityDate)) {
972 AND ca.activity_date_time <= '{$toActivityDate}'";
976 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
978 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
980 // CRM-5081 - added id to act like creation date
982 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
985 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
986 $orderBy = " ORDER BY $sortBy ";
989 $page = CRM_Utils_Array
::value('page', $params);
990 $rp = CRM_Utils_Array
::value('rp', $params);
998 $start = (($page - 1) * $rp);
999 $limit = " LIMIT $start, $rp";
1001 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
1002 $queryParams = array(1 => array($caseID, 'Integer'));
1004 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
1005 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
1007 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1008 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus();
1010 $url = CRM_Utils_System
::url("civicrm/case/activity",
1011 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1015 if ($context == 'fulltext') {
1016 $contextUrl = "&context={$context}";
1018 $editUrl = "{$url}&action=update{$contextUrl}";
1019 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1020 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1021 $viewTitle = ts('View activity');
1023 $emailActivityTypeIDs = array(
1024 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1028 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1034 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1036 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1037 $compStatusValues = array();
1038 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1039 foreach ($compStatusNames as $name) {
1040 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1043 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=", FALSE, NULL, FALSE);
1044 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1045 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1048 $session = CRM_Core_Session
::singleton();
1049 $userID = $session->get('userID');
1052 $caseActivities = array();
1054 while ($dao->fetch()) {
1055 $caseActivity = array();
1056 $caseActivityId = $dao->id
;
1058 $allowView = self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID);
1059 $allowEdit = self
::checkPermission($caseActivityId, 'edit', $dao->activity_type_id
, $userID);
1060 $allowDelete = self
::checkPermission($caseActivityId, 'delete', $dao->activity_type_id
, $userID);
1062 //do not have sufficient permission
1063 //to access given case activity record.
1064 if (!$allowView && !$allowEdit && !$allowDelete) {
1068 $caseActivity['DT_RowId'] = $caseActivityId;
1069 //Add classes to the row, via DataTables syntax
1070 $caseActivity['DT_RowClass'] = "crm-entity status-id-$dao->status";
1072 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1073 $caseActivity['DT_RowClass'] .= " status-completed";
1076 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1077 $caseActivity['DT_RowClass'] .= " status-overdue";
1080 $caseActivity['DT_RowClass'] .= " status-scheduled";
1084 if (!empty($dao->priority
)) {
1085 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1086 $caseActivity['DT_RowClass'] .= " priority-urgent ";
1088 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1089 $caseActivity['DT_RowClass'] .= " priority-low ";
1093 //Add data to the row for inline editing, via DataTable syntax
1094 $caseActivity['DT_RowAttr'] = array();
1095 $caseActivity['DT_RowAttr']['data-entity'] = 'activity';
1096 $caseActivity['DT_RowAttr']['data-id'] = $caseActivityId;
1098 //Activity Date and Time
1099 $caseActivity['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1102 $caseActivity['subject'] = $dao->subject
;
1105 $caseActivity['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1106 . $activityTypes[$dao->type
]['label'];
1108 //Activity Target (With)
1109 $targetContact = '';
1110 if (isset($dao->target_contact_id
)) {
1111 $targetContact = $dao->target_contact_name
;
1112 if ($hasViewContact) {
1113 $targetContact = '<a href="' . $contactViewUrl . $dao->target_contact_id
. '">' . $dao->target_contact_name
. '</a>';
1116 $caseActivity['target_contact_name'] = $targetContact;
1118 //Activity Source Contact (Reporter)
1119 $sourceContact = $dao->source_contact_name
;
1120 if ($hasViewContact) {
1121 $sourceContact = '<a href="' . $contactViewUrl . $dao->source_contact_id
. '">' . $dao->source_contact_name
. '</a>';
1123 $caseActivity['source_contact_name'] = $sourceContact;
1125 //Activity Assignee. CRM-4485.
1126 $assigneeContact = '';
1127 if (isset($dao->assignee_contact_id
)) {
1128 $assigneeContact = $dao->assignee_contact_name
;
1129 if ($hasViewContact) {
1130 $assigneeContact = '<a href="' . $contactViewUrl . $dao->assignee_contact_id
. '">' . $dao->assignee_contact_name
. '</a>';
1133 $caseActivity['assignee_contact_name'] = $assigneeContact;
1136 $caseActivity['status_id'] = $activityStatuses[$dao->status
];
1138 // 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.
1140 $css = 'class="action-item crm-hover-button"';
1142 $viewUrl = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1143 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1145 $additionalUrl = "&id={$caseActivityId}";
1146 if (!$dao->deleted
) {
1147 //hide edit link of activity type email.CRM-4530.
1148 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1149 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1151 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1155 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1158 elseif (!$caseDeleted) {
1159 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1160 $caseActivity['status_id'] = $caseActivity['status_id'] . '<br /> (deleted)';
1163 //check for operations.
1164 if (self
::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id
)) {
1165 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1167 if (self
::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id
)) {
1168 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1170 // if there are file attachments we will return how many and, if only one, add a link to it
1171 if (!empty($dao->attachment_ids
)) {
1172 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1173 $caseActivity['no_attachments'] = count($attachmentIDs);
1174 $url .= implode(' ', CRM_Core_BAO_File
::paperIconAttachment('civicrm_activity', $caseActivityId));
1177 $caseActivity['links'] = $url;
1179 array_push($caseActivities, $caseActivity);
1183 $caseActivitiesDT = array();
1184 $caseActivitiesDT['data'] = $caseActivities;
1185 $caseActivitiesDT['recordsTotal'] = $caseCount;
1186 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1188 return $caseActivitiesDT;
1192 * Get Case Related Contacts.
1194 * @param int $caseID
1196 * @param bool $includeDetails
1197 * If true include details of contacts.
1200 * array of return properties
1203 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1204 $caseRoles = array();
1205 if ($includeDetails) {
1206 $caseInfo = civicrm_api3('Case', 'getsingle', array(
1208 // 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
1209 'return' => array('case_type_id', 'case_type_id.name', 'case_type_id.definition'),
1211 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1212 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1217 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
1218 FROM civicrm_relationship cr
1219 LEFT JOIN civicrm_relationship_type crt
1220 ON crt.id = cr.relationship_type_id
1221 LEFT JOIN civicrm_contact cc
1222 ON cc.id = cr.contact_id_b
1223 LEFT JOIN civicrm_email ce
1224 ON ce.contact_id = cc.id
1225 AND ce.is_primary= 1
1226 LEFT JOIN civicrm_phone cp
1227 ON cp.contact_id = cc.id
1228 AND cp.is_primary= 1
1229 WHERE cr.case_id = %1 AND cr.is_active AND cc.is_deleted <> 1';
1231 $params = array(1 => array($caseID, 'Integer'));
1232 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1234 while ($dao->fetch()) {
1235 if (!$includeDetails) {
1236 $values[$dao->id
] = 1;
1240 'contact_id' => $dao->id
,
1241 'display_name' => $dao->name
,
1242 'sort_name' => $dao->sort_name
,
1243 'relationship_type_id' => $dao->relationship_type_id
,
1244 'role' => $dao->role
,
1245 'email' => $dao->email
,
1246 'phone' => $dao->phone
,
1248 // Add more info about the role (creator, manager)
1249 $role = CRM_Utils_Array
::value($dao->name_b_a
, $caseRoles);
1251 unset($role['name']);
1254 $values[] = $details;
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 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1343 $receiptFrom = self
::getReceiptFrom($activityId);
1345 $recordedActivityParams = array();
1347 foreach ($contacts as $mail => $info) {
1348 $tplParams['contact'] = $info;
1349 self
::buildPermissionLinks($tplParams, $activityParams);
1351 $displayName = CRM_Utils_Array
::value('display_name', $info);
1353 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1355 'groupName' => 'msg_tpl_workflow_case',
1356 'valueName' => 'case_activity',
1357 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1358 'tplParams' => $tplParams,
1359 'from' => $receiptFrom,
1360 'toName' => $displayName,
1362 'attachments' => $attachments,
1366 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1367 $activityParams['details'] = $message;
1369 if (!empty($result[$info['contact_id']])) {
1371 * Really only need to record one activity with all the targets combined.
1372 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1373 * but it's always the same content at the moment.
1375 if (empty($recordedActivityParams)) {
1376 $recordedActivityParams = $activityParams;
1379 $recordedActivityParams['subject'] .= "; $displayName";
1381 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1384 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1388 if (!empty($recordedActivityParams)) {
1389 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1391 //create case_activity record if its case activity.
1393 $caseParams = array(
1394 'activity_id' => $activity->id
,
1395 'case_id' => $caseId,
1397 self
::processCaseActivity($caseParams);
1405 * Retrieve count of activities having a particular type, and
1406 * associated with a particular case.
1408 * @param int $caseId
1410 * @param int $activityTypeId
1411 * ID of the activity type.
1415 public static function getCaseActivityCount($caseId, $activityTypeId) {
1416 $queryParam = array(
1417 1 => array($caseId, 'Integer'),
1418 2 => array($activityTypeId, 'Integer'),
1420 $query = "SELECT count(ca.id) as countact
1421 FROM civicrm_activity ca
1422 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1423 WHERE ca.activity_type_id = %2
1424 AND cca.case_id = %1
1425 AND ca.is_deleted = 0";
1427 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1428 if ($dao->fetch()) {
1429 return $dao->countact
;
1436 * Create an activity for a case via email.
1441 * @return array|void
1442 * $activity object of newly creted activity via email
1444 public static function recordActivityViaEmail($file) {
1445 if (!file_exists($file) ||
1448 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1453 $result = CRM_Utils_Mail_Incoming
::parse($file);
1454 if ($result['is_error']) {
1458 foreach ($result['to'] as $to) {
1461 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1462 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1464 if ($replacement !== $to['email']) {
1465 $caseId = $replacement;
1466 //if caseId is invalid, return as error file
1467 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1468 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1477 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1478 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1479 $contactDetails = self
::getRelatedContacts($caseId, FALSE);
1481 if (!empty($contactDetails[$result['from']['id']])) {
1483 $params['subject'] = $result['subject'];
1484 $params['activity_date_time'] = $result['date'];
1485 $params['details'] = $result['body'];
1486 $params['source_contact_id'] = $result['from']['id'];
1487 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1492 $details = CRM_Case_PseudoConstant
::caseActivityType();
1494 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1495 $result['body'], $matches
1498 if (!empty($matches) && isset($matches[1])) {
1499 $activityType = trim($matches[1]);
1500 if (isset($details[$activityType])) {
1501 $params['activity_type_id'] = $details[$activityType]['id'];
1504 if (!isset($params['activity_type_id'])) {
1505 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1509 $activity = CRM_Activity_BAO_Activity
::create($params);
1511 $caseParams = array(
1512 'activity_id' => $activity->id
,
1513 'case_id' => $caseId,
1515 self
::processCaseActivity($caseParams);
1518 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1519 array(1 => $result['from']['email'])
1526 * Retrieve the scheduled activity type and date.
1528 * @param array $cases
1529 * Array of contact and case id.
1531 * @param string $type
1534 * Array of scheduled activity type and date
1538 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1539 $session = CRM_Core_Session
::singleton();
1540 $userID = $session->get('userID');
1542 $caseID = implode(',', $cases['case_id']);
1543 $contactID = implode(',', $cases['contact_id']);
1546 AND civicrm_case_contact.contact_id IN( {$contactID} )
1547 AND civicrm_case.id IN( {$caseID})
1548 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1550 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1552 $res = CRM_Core_DAO
::executeQuery($query);
1554 $activityInfo = array();
1555 while ($res->fetch()) {
1556 if ($type == 'upcoming') {
1557 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1558 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1561 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1562 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1566 return $activityInfo;
1570 * Combine all the exportable fields from the lower levels object.
1573 * array of exportable Fields
1575 public static function &exportableFields() {
1576 if (!self
::$_exportableFields) {
1577 if (!self
::$_exportableFields) {
1578 self
::$_exportableFields = array();
1581 $fields = CRM_Case_DAO_Case
::export();
1582 $fields['case_role'] = array('title' => ts('Role in Case'));
1583 $fields['case_type'] = array(
1584 'title' => ts('Case Type'),
1585 'name' => 'case_type',
1587 $fields['case_status'] = array(
1588 'title' => ts('Case Status'),
1589 'name' => 'case_status',
1592 // add custom data for cases
1593 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1595 self
::$_exportableFields = $fields;
1597 return self
::$_exportableFields;
1601 * Restore the record that are associated with this case.
1603 * @param int $caseId
1604 * Id of the case to restore.
1608 public static function restoreCase($caseId) {
1609 //restore activities
1610 $activities = self
::getCaseActivityDates($caseId);
1612 foreach ($activities as $value) {
1613 CRM_Activity_BAO_Activity
::restoreActivity($value);
1617 $case = new CRM_Case_DAO_Case();
1618 $case->id
= $caseId;
1619 $case->is_deleted
= 0;
1622 //CRM-7364, enable relationships
1623 self
::enableDisableCaseRelationships($caseId, TRUE);
1630 * @param null $showLinks
1631 * @param bool $returnOnlyCount
1632 * @param int $offset
1633 * @param int $rowCount
1637 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1638 $globalContacts = array();
1640 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1641 $settings = $settingsProcessor->run();
1642 if (!empty($settings)) {
1643 $groupInfo['name'] = $settings['groupname'];
1644 if ($groupInfo['name']) {
1645 $searchParams = array('name' => $groupInfo['name']);
1647 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1649 $groupInfo['id'] = $results['id'];
1650 $groupInfo['title'] = $results['title'];
1651 $params = array(array('group', '=', $groupInfo['id'], 0, 0));
1652 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1653 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1655 if ($returnOnlyCount) {
1656 return $globalContacts;
1660 foreach ($globalContacts as $idx => $contact) {
1661 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1667 return $globalContacts;
1671 * Convenience function to get both case contacts and global in one array.
1672 * @param int $caseId
1676 public static function getRelatedAndGlobalContacts($caseId) {
1677 $relatedContacts = self
::getRelatedContacts($caseId);
1679 $groupInfo = array();
1680 $globalContacts = self
::getGlobalContacts($groupInfo);
1682 //unset values which are not required.
1683 foreach ($globalContacts as $k => & $v) {
1684 unset($v['email_id']);
1685 unset($v['group_contact_id']);
1686 unset($v['status']);
1688 $v['role'] = $groupInfo['title'];
1690 //include multiple listings for the same contact/different roles.
1691 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1692 return $relatedGlobalContacts;
1696 * Get Case ActivitiesDueDates with given criteria.
1698 * @param int $caseID
1700 * @param array $criteriaParams
1702 * @param bool $latestDate
1703 * If set newest or oldest date is selected.
1706 * case activities due dates
1709 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1711 $selectDate = " ca.activity_date_time";
1712 $where = $groupBy = ' ';
1719 if (!empty($criteriaParams['activity_type_id'])) {
1720 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1721 $where .= " AND ca.is_current_revision = 1";
1722 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1725 if (!empty($criteriaParams['newest'])) {
1726 $selectDate = " max(ca.activity_date_time) ";
1729 $selectDate = " min(ca.activity_date_time) ";
1733 $query = "SELECT ca.id, {$selectDate} as activity_date
1734 FROM civicrm_activity ca
1735 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1736 WHERE cc.id = %1 {$where} {$groupBy}";
1738 $params = array(1 => array($caseID, 'Integer'));
1739 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1741 while ($dao->fetch()) {
1742 $values[$dao->id
]['id'] = $dao->id
;
1743 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1750 * Create activities when Case or Other roles assigned/modified/deleted.
1752 * @param int $caseId
1753 * @param int $relationshipId
1755 * @param int $relContactId
1756 * Case role assignee contactId.
1757 * @param int $contactId
1759 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1760 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1764 $queryParam = array();
1765 if (is_array($relationshipId)) {
1766 $relationshipId = implode(',', $relationshipId);
1767 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1770 $relationshipClause = " civicrm_relationship.id = %1";
1771 $queryParam[1] = array($relationshipId, 'Positive');
1775 SELECT cc.display_name as clientName,
1776 cca.display_name as assigneeContactName,
1777 civicrm_relationship.case_id as caseId,
1778 civicrm_relationship_type.label_a_b as relation_a_b,
1779 civicrm_relationship_type.label_b_a as relation_b_a,
1780 civicrm_relationship.contact_id_b as rel_contact_id,
1781 civicrm_relationship.contact_id_a as assign_contact_id
1782 FROM civicrm_relationship_type, civicrm_relationship
1783 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1784 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1785 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1787 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1789 while ($dao->fetch()) {
1790 // The assignee is not the client.
1791 if ($dao->rel_contact_id
!= $contactId) {
1792 $caseRelationship = $dao->relation_a_b
;
1793 $assigneContactName = $dao->clientName
;
1794 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1797 $caseRelationship = $dao->relation_b_a
;
1798 $assigneContactName = $dao->assigneeContactName
;
1799 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1803 $session = CRM_Core_Session
::singleton();
1804 $activityParams = array(
1805 'source_contact_id' => $session->get('userID'),
1806 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1807 'activity_date_time' => date('YmdHis'),
1808 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1811 //if $relContactId is passed, role is added or modified.
1812 if (!empty($relContactId)) {
1813 $activityParams['assignee_contact_id'] = $assigneContactIds;
1815 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1821 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1827 $activityParams['activity_type_id'] = $activityTypeID;
1829 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1831 //create case_activity record.
1832 $caseParams = array(
1833 'activity_id' => $activity->id
,
1834 'case_id' => $caseId,
1837 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1842 * contact which is assigned a case role of case manager.
1844 * @param int $caseType
1846 * @param int $caseId
1850 * array of contact on success otherwise empty
1853 public static function getCaseManagerContact($caseType, $caseId) {
1854 if (!$caseType ||
!$caseId) {
1858 $caseManagerContact = array();
1859 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1861 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1863 if (!empty($managerRoleId)) {
1864 $managerRoleQuery = "
1865 SELECT civicrm_contact.id as casemanager_id,
1866 civicrm_contact.sort_name as casemanager
1867 FROM civicrm_contact
1868 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1869 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1870 WHERE civicrm_case.id = %2 AND is_active = 1";
1872 $managerRoleParams = array(
1873 1 => array($managerRoleId, 'Integer'),
1874 2 => array($caseId, 'Integer'),
1877 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1878 if ($dao->fetch()) {
1879 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1880 $caseManagerContact['casemanager'] = $dao->casemanager
;
1884 return $caseManagerContact;
1888 * @param int $contactId
1889 * @param bool $excludeDeleted
1893 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1894 $params = array('check_permissions' => TRUE);
1895 if ($excludeDeleted) {
1896 $params['is_deleted'] = 0;
1899 $params['contact_id'] = $contactId;
1902 return civicrm_api3('Case', 'getcount', $params);
1904 catch (CiviCRM_API3_Exception
$e) {
1905 // Lack of permissions will throw an exception
1911 * Retrieve related case ids for given case.
1913 * @param int $caseId
1914 * @param bool $excludeDeleted
1915 * Do not include deleted cases.
1919 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1920 //FIXME : do check for permissions.
1926 $linkActType = array_search('Link Cases',
1927 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
1929 if (!$linkActType) {
1933 $whereClause = "mainCase.id = %2";
1934 if ($excludeDeleted) {
1935 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1939 SELECT relCaseAct.case_id
1940 FROM civicrm_case mainCase
1941 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1942 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1943 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1944 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1945 WHERE $whereClause";
1947 $dao = CRM_Core_DAO
::executeQuery($query, array(
1948 1 => array($linkActType, 'Integer'),
1949 2 => array($caseId, 'Integer'),
1951 $relatedCaseIds = array();
1952 while ($dao->fetch()) {
1953 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1957 return array_values($relatedCaseIds);
1961 * Retrieve related case details for given case.
1963 * @param int $caseId
1964 * @param bool $excludeDeleted
1965 * Do not include deleted cases.
1969 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
1970 $relatedCaseIds = self
::getRelatedCaseIds($caseId, $excludeDeleted);
1971 $relatedCases = array();
1973 if (!$relatedCaseIds) {
1977 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1978 if ($excludeDeleted) {
1979 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1982 //filter for permissioned cases.
1983 $filterCases = array();
1984 $doFilterCases = FALSE;
1985 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1986 $doFilterCases = TRUE;
1987 $session = CRM_Core_Session
::singleton();
1988 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
1991 //2. fetch the details of related cases.
1993 SELECT relCase.id as id,
1994 civicrm_case_type.title as case_type,
1995 client.display_name as client_name,
1996 client.id as client_id
1997 FROM civicrm_case relCase
1998 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
1999 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2000 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
2001 WHERE {$whereClause}";
2003 $dao = CRM_Core_DAO
::executeQuery($query);
2004 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2005 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2007 while ($dao->fetch()) {
2009 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2010 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2011 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2012 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2014 $clientView = $dao->client_name
;
2015 if ($hasViewContact) {
2016 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2019 $relatedCases[$dao->id
] = array(
2020 'case_id' => $dao->id
,
2021 'case_type' => $dao->case_type
,
2022 'client_name' => $clientView,
2023 'links' => $caseView,
2028 return $relatedCases;
2032 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2034 * @see CRM_Dedupe_Merger::cpTables()
2036 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2038 * @param int $mainContactId
2039 * @param int $otherContactId
2041 public static function mergeContacts($mainContactId, $otherContactId) {
2042 self
::mergeCases($mainContactId, NULL, $otherContactId);
2046 * Function perform two task.
2047 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2048 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2050 * @param int $mainContactId
2051 * Contact id of main contact record.
2052 * @param int $mainCaseId
2053 * Case id of main case record.
2054 * @param int $otherContactId
2055 * Contact id of record which is going to merge.
2056 * @param int $otherCaseId
2057 * Case id of record which is going to merge.
2059 * @param bool $changeClient
2063 public static function mergeCases(
2064 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2065 $otherCaseId = NULL, $changeClient = FALSE) {
2066 $moveToTrash = TRUE;
2068 $duplicateContacts = FALSE;
2069 if ($mainContactId && $otherContactId &&
2070 $mainContactId != $otherContactId
2072 $duplicateContacts = TRUE;
2075 $duplicateCases = FALSE;
2076 if ($mainCaseId && $otherCaseId &&
2077 $mainCaseId != $otherCaseId
2079 $duplicateCases = TRUE;
2082 $mainCaseIds = array();
2083 if (!$duplicateContacts && !$duplicateCases) {
2084 return $mainCaseIds;
2087 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2088 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2089 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2090 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2091 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2092 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2094 $processCaseIds = array($otherCaseId);
2095 if ($duplicateContacts && !$duplicateCases) {
2096 if ($changeClient) {
2097 $processCaseIds = array($mainCaseId);
2100 //get all case ids for other contact.
2101 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2103 if (!is_array($processCaseIds)) {
2108 $session = CRM_Core_Session
::singleton();
2109 $currentUserId = $session->get('userID');
2111 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2113 // copy all cases and connect to main contact id.
2114 foreach ($processCaseIds as $otherCaseId) {
2115 if ($duplicateContacts) {
2116 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2117 $mainCaseId = $mainCase->id
;
2122 // CRM-11662 Copy Case custom data
2123 $extends = array('case');
2124 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2126 foreach ($groupTree as $groupID => $group) {
2127 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2128 foreach ($group['fields'] as $fieldID => $field) {
2129 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2133 foreach ($table as $tableName => $tableColumns) {
2134 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2135 $tableColumns[0] = $mainCaseId;
2136 $select = 'SELECT ' . implode(', ', $tableColumns);
2137 $from = ' FROM ' . $tableName;
2138 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2139 $query = $insert . $select . $from . $where;
2140 $dao = CRM_Core_DAO
::executeQuery($query);
2146 $mainCaseIds[] = $mainCaseId;
2147 //insert record for case contact.
2148 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2149 $otherCaseContact->case_id
= $otherCaseId;
2150 $otherCaseContact->find();
2151 while ($otherCaseContact->fetch()) {
2152 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2153 $mainCaseContact->case_id
= $mainCaseId;
2154 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2155 if ($mainCaseContact->contact_id
== $otherContactId) {
2156 $mainCaseContact->contact_id
= $mainContactId;
2158 //avoid duplicate object.
2159 if (!$mainCaseContact->find(TRUE)) {
2160 $mainCaseContact->save();
2162 $mainCaseContact->free();
2164 $otherCaseContact->free();
2166 elseif (!$otherContactId) {
2167 $otherContactId = $mainContactId;
2170 if (!$mainCaseId ||
!$otherCaseId ||
2171 !$mainContactId ||
!$otherContactId
2176 // get all activities for other case.
2177 $otherCaseActivities = array();
2178 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2180 //for duplicate cases do not process singleton activities.
2181 $otherActivityIds = $singletonActivityIds = array();
2182 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2183 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2184 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2187 $otherActivityIds[] = $otherActId;
2189 if ($duplicateCases) {
2190 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2193 FROM civicrm_activity
2194 WHERE activity_type_id = $openCaseType
2195 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2196 $dao = CRM_Core_DAO
::executeQuery($sql);
2197 while ($dao->fetch()) {
2198 $singletonActivityIds[] = $dao->id
;
2204 // migrate all activities and connect to main contact.
2205 $copiedActivityIds = $activityMappingIds = array();
2206 sort($otherActivityIds);
2207 foreach ($otherActivityIds as $otherActivityId) {
2209 //for duplicate cases -
2210 //do not migrate singleton activities.
2211 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2215 //migrate activity record.
2216 $otherActivity = new CRM_Activity_DAO_Activity();
2217 $otherActivity->id
= $otherActivityId;
2218 if (!$otherActivity->find(TRUE)) {
2222 $mainActVals = array();
2223 $mainActivity = new CRM_Activity_DAO_Activity();
2224 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2225 $mainActivity->copyValues($mainActVals);
2226 $mainActivity->id
= NULL;
2227 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2228 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2232 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2236 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2239 $mainActivity->save();
2240 $mainActivityId = $mainActivity->id
;
2241 if (!$mainActivityId) {
2245 $activityMappingIds[$otherActivityId] = $mainActivityId;
2246 // insert log of all activities
2247 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2249 $otherActivity->free();
2250 $mainActivity->free();
2251 $copiedActivityIds[] = $otherActivityId;
2253 //create case activity record.
2254 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2255 $mainCaseActivity->case_id
= $mainCaseId;
2256 $mainCaseActivity->activity_id
= $mainActivityId;
2257 $mainCaseActivity->save();
2258 $mainCaseActivity->free();
2260 //migrate source activity.
2261 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2262 $otherSourceActivity->activity_id
= $otherActivityId;
2263 $otherSourceActivity->record_type_id
= $sourceID;
2264 $otherSourceActivity->find();
2265 while ($otherSourceActivity->fetch()) {
2266 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2267 $mainActivitySource->record_type_id
= $sourceID;
2268 $mainActivitySource->activity_id
= $mainActivityId;
2269 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2270 if ($mainActivitySource->contact_id
== $otherContactId) {
2271 $mainActivitySource->contact_id
= $mainContactId;
2273 //avoid duplicate object.
2274 if (!$mainActivitySource->find(TRUE)) {
2275 $mainActivitySource->save();
2277 $mainActivitySource->free();
2279 $otherSourceActivity->free();
2281 //migrate target activities.
2282 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2283 $otherTargetActivity->activity_id
= $otherActivityId;
2284 $otherTargetActivity->record_type_id
= $targetID;
2285 $otherTargetActivity->find();
2286 while ($otherTargetActivity->fetch()) {
2287 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2288 $mainActivityTarget->record_type_id
= $targetID;
2289 $mainActivityTarget->activity_id
= $mainActivityId;
2290 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2291 if ($mainActivityTarget->contact_id
== $otherContactId) {
2292 $mainActivityTarget->contact_id
= $mainContactId;
2294 //avoid duplicate object.
2295 if (!$mainActivityTarget->find(TRUE)) {
2296 $mainActivityTarget->save();
2298 $mainActivityTarget->free();
2300 $otherTargetActivity->free();
2302 //migrate assignee activities.
2303 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2304 $otherAssigneeActivity->activity_id
= $otherActivityId;
2305 $otherAssigneeActivity->record_type_id
= $assigneeID;
2306 $otherAssigneeActivity->find();
2307 while ($otherAssigneeActivity->fetch()) {
2308 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2309 $mainAssigneeActivity->activity_id
= $mainActivityId;
2310 $mainAssigneeActivity->record_type_id
= $assigneeID;
2311 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2312 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2313 $mainAssigneeActivity->contact_id
= $mainContactId;
2315 //avoid duplicate object.
2316 if (!$mainAssigneeActivity->find(TRUE)) {
2317 $mainAssigneeActivity->save();
2319 $mainAssigneeActivity->free();
2321 $otherAssigneeActivity->free();
2323 // copy custom fields and attachments
2325 'activityID' => $otherActivityId,
2326 'mainActivityId' => $mainActivityId,
2328 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2331 //copy case relationship.
2332 if ($duplicateContacts) {
2333 //migrate relationship records.
2334 $otherRelationship = new CRM_Contact_DAO_Relationship();
2335 $otherRelationship->case_id
= $otherCaseId;
2336 $otherRelationship->find();
2337 $otherRelationshipIds = array();
2338 while ($otherRelationship->fetch()) {
2339 $otherRelVals = array();
2340 $updateOtherRel = FALSE;
2341 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2343 $mainRelationship = new CRM_Contact_DAO_Relationship();
2344 $mainRelationship->copyValues($otherRelVals);
2345 $mainRelationship->id
= NULL;
2346 $mainRelationship->case_id
= $mainCaseId;
2347 if ($mainRelationship->contact_id_a
== $otherContactId) {
2348 $updateOtherRel = TRUE;
2349 $mainRelationship->contact_id_a
= $mainContactId;
2352 //case creator change only when we merge user contact.
2353 if ($mainRelationship->contact_id_b
== $otherContactId) {
2354 //do not change creator for change client.
2355 if (!$changeClient) {
2356 $updateOtherRel = TRUE;
2357 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2360 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2361 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2363 //avoid duplicate object.
2364 if (!$mainRelationship->find(TRUE)) {
2365 $mainRelationship->save();
2367 $mainRelationship->free();
2369 //get the other relationship ids to update end date.
2370 if ($updateOtherRel) {
2371 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2374 $otherRelationship->free();
2376 //update other relationships end dates
2377 if (!empty($otherRelationshipIds)) {
2378 $sql = 'UPDATE civicrm_relationship
2379 SET end_date = CURDATE()
2380 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2381 CRM_Core_DAO
::executeQuery($sql);
2385 //move other case to trash.
2386 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2391 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2392 if ($changeClient) {
2393 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2394 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2396 $mergeActType = array_search('Reassigned Case', $activityTypes);
2397 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2400 2 => $otherContactDisplayName,
2401 3 => $mainContactDisplayName,
2406 elseif ($duplicateContacts) {
2407 $mergeActType = array_search('Merge Case', $activityTypes);
2408 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2411 2 => $otherContactId,
2412 3 => $mainContactId,
2418 $mergeActType = array_search('Merge Case', $activityTypes);
2419 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2420 if (!empty($copiedActivityIds)) {
2422 SELECT id, subject, activity_date_time, activity_type_id
2423 FROM civicrm_activity
2424 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2425 $dao = CRM_Core_DAO
::executeQuery($sql);
2426 while ($dao->fetch()) {
2427 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2428 if ($dao->subject
) {
2429 $mergeActSubjectDetails .= " :: {$dao->subject}";
2431 $mergeActSubjectDetails .= "<br />";
2436 //Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2437 $activityParams = array(
2438 'subject' => $mergeActSubject,
2439 'details' => $mergeActSubjectDetails,
2440 'status_id' => array_search('Completed', $activityStatuses),
2441 'activity_type_id' => $mergeActType,
2442 'source_contact_id' => $currentUserId,
2443 'activity_date_time' => date('YmdHis'),
2446 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2447 $mergeActivityId = $mergeActivity->id
;
2448 if (!$mergeActivityId) {
2451 $mergeActivity->free();
2453 //connect merge activity to case.
2454 $mergeCaseAct = array(
2455 'case_id' => $mainCaseId,
2456 'activity_id' => $mergeActivityId,
2459 self
::processCaseActivity($mergeCaseAct);
2462 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2464 return $mainCaseIds;
2468 * Validate contact permission for
2469 * edit/view on activity record and build links.
2471 * @param array $tplParams
2472 * Params to be sent to template for sending email.
2473 * @param array $activityParams
2474 * Info of the activity.
2476 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2477 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2478 'activity_type_id', 'id'
2481 if (!empty($tplParams['isCaseActivity'])) {
2482 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2483 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2486 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2487 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2490 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2491 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2495 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2496 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2499 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2500 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2506 * Validate contact permission for
2507 * given operation on activity record.
2509 * @param int $activityId
2510 * Activity record id.
2511 * @param string $operation
2513 * @param int $actTypeId
2515 * @param int $contactId
2516 * Contact id/if not pass consider logged in.
2517 * @param bool $checkComponent
2518 * Do we need to check component enabled.
2522 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2524 if (!$actTypeId && $activityId) {
2525 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2528 if (!$activityId ||
!$operation ||
!$actTypeId) {
2532 //do check for civicase component enabled.
2533 if ($checkComponent && !self
::enabled()) {
2537 //do check for cases.
2538 $caseActOperations = array(
2545 if (in_array($operation, $caseActOperations)) {
2547 if (!isset($caseCount)) {
2549 $caseCount = civicrm_api3('Case', 'getcount', array(
2550 'check_permissions' => TRUE,
2551 'status_id' => array('!=' => 'Closed'),
2553 'end_date' => array('IS NULL' => 1),
2556 catch (CiviCRM_API3_Exception
$e) {
2557 // Lack of permissions will throw an exception
2561 if ($operation == 'File On Case') {
2562 $allow = !empty($caseCount);
2565 $allow = ($caseCount > 1);
2569 $actionOperations = array('view', 'edit', 'delete');
2570 if (in_array($operation, $actionOperations)) {
2572 //do cache when user has non/supper permission.
2573 static $allowOperations;
2575 if (!is_array($allowOperations) ||
2576 !array_key_exists($operation, $allowOperations)
2580 $session = CRM_Core_Session
::singleton();
2581 $contactId = $session->get('userID');
2584 //check for permissions.
2585 $permissions = array(
2587 'access my cases and activities',
2588 'access all cases and activities',
2591 'access my cases and activities',
2592 'access all cases and activities',
2594 'delete' => array('delete activities'),
2597 //check for core permission.
2598 $hasPermissions = array();
2599 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2600 if (is_array($checkPermissions)) {
2601 foreach ($checkPermissions as $per) {
2602 if (CRM_Core_Permission
::check($per)) {
2603 $hasPermissions[$operation][] = $per;
2609 if (!empty($hasPermissions)) {
2610 //need to check activity object specific.
2611 if (in_array($operation, array(
2616 //do we have supper permission.
2617 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2618 $allowOperations[$operation] = $allow = TRUE;
2621 //user has only access to my cases and activity.
2622 //here object specific permmions come in picture.
2624 //edit - contact must be source or assignee
2625 //view - contact must be source/assignee/target
2626 $isTarget = $isAssignee = $isSource = FALSE;
2627 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2628 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2629 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2630 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2632 $target = new CRM_Activity_DAO_ActivityContact();
2633 $target->record_type_id
= $targetID;
2634 $target->activity_id
= $activityId;
2635 $target->contact_id
= $contactId;
2636 if ($target->find(TRUE)) {
2640 $assignee = new CRM_Activity_DAO_ActivityContact();
2641 $assignee->activity_id
= $activityId;
2642 $assignee->record_type_id
= $assigneeID;
2643 $assignee->contact_id
= $contactId;
2644 if ($assignee->find(TRUE)) {
2648 $source = new CRM_Activity_DAO_ActivityContact();
2649 $source->activity_id
= $activityId;
2650 $source->record_type_id
= $sourceID;
2651 $source->contact_id
= $contactId;
2652 if ($source->find(TRUE)) {
2656 if ($operation == 'edit') {
2657 if ($isAssignee ||
$isSource) {
2661 if ($operation == 'view') {
2662 if ($isTarget ||
$isAssignee ||
$isSource) {
2668 elseif (is_array($hasPermissions[$operation])) {
2669 $allowOperations[$operation] = $allow = TRUE;
2673 //contact do not have permission.
2674 $allowOperations[$operation] = FALSE;
2679 //here contact might have supper/non permission.
2680 $allow = $allowOperations[$operation];
2684 //do further only when operation is granted.
2686 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2688 //get the activity type name.
2689 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2691 //do not allow multiple copy / edit action.
2692 $singletonNames = array(
2702 //do not allow to delete these activities, CRM-4543
2703 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2705 //allow edit operation.
2706 $allowEditNames = array('Open Case');
2708 // do not allow File on Case
2709 $doNotFileNames = array(
2712 'Change Case Status',
2713 'Change Case Start Date',
2720 if (in_array($actTypeName, $singletonNames)) {
2722 if ($operation == 'File On Case') {
2723 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2725 if (in_array($operation, $actionOperations)) {
2727 if ($operation == 'edit') {
2728 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2730 elseif ($operation == 'delete') {
2731 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2735 if ($allow && ($operation == 'delete') &&
2736 in_array($actTypeName, $doNotDeleteNames)
2741 if ($allow && ($operation == 'File On Case') &&
2742 in_array($actTypeName, $doNotFileNames)
2747 //check settings file for masking actions
2748 //on the basis the activity types
2749 //hide Edit link if activity type is NOT editable
2750 //(special case activities).CRM-5871
2751 if ($allow && in_array($operation, $actionOperations)) {
2752 static $actionFilter = array();
2753 if (!array_key_exists($operation, $actionFilter)) {
2754 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2755 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2757 if (array_key_exists($operation, $actionFilter[$operation]) &&
2758 in_array($actTypeId, $actionFilter[$operation][$operation])
2769 * Since we drop 'access CiviCase', allow access
2770 * if user has 'access my cases and activities'
2771 * or 'access all cases and activities'
2773 public static function accessCiviCase() {
2774 if (!self
::enabled()) {
2778 if (CRM_Core_Permission
::check('access my cases and activities') ||
2779 CRM_Core_Permission
::check('access all cases and activities')
2788 * Verify user has permission to access a case.
2790 * @param int $caseId
2791 * @param bool $denyClosed
2792 * Set TRUE if one wants closed cases to be treated as inaccessible.
2796 public static function accessCase($caseId, $denyClosed = TRUE) {
2797 if (!$caseId ||
!self
::enabled()) {
2801 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2802 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2803 $params['status_id'] = array('!=' => 'Closed');
2806 return (bool) civicrm_api3('Case', 'getcount', $params);
2808 catch (CiviCRM_API3_Exception
$e) {
2809 // Lack of permissions will throw an exception
2815 * Check whether activity is a case Activity.
2817 * @param int $activityID
2822 public static function isCaseActivity($activityID) {
2823 $isCaseActivity = FALSE;
2825 $params = array(1 => array($activityID, 'Integer'));
2826 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2827 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2828 $isCaseActivity = TRUE;
2832 return $isCaseActivity;
2836 * Get all the case type ids currently in use.
2840 public static function getUsedCaseType() {
2841 static $caseTypeIds;
2843 if (!is_array($caseTypeIds)) {
2844 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2846 $dao = CRM_Core_DAO
::executeQuery($query);
2847 $caseTypeIds = array();
2848 while ($dao->fetch()) {
2849 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2852 $caseTypeIds[] = $typeId[1];
2856 return $caseTypeIds;
2860 * Get all the case status ids currently in use.
2864 public static function getUsedCaseStatuses() {
2865 static $caseStatusIds;
2867 if (!is_array($caseStatusIds)) {
2868 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2870 $dao = CRM_Core_DAO
::executeQuery($query);
2871 $caseStatusIds = array();
2872 while ($dao->fetch()) {
2873 $caseStatusIds[] = $dao->status_id
;
2877 return $caseStatusIds;
2881 * Get all the encounter medium ids currently in use.
2885 public static function getUsedEncounterMediums() {
2888 if (!is_array($mediumIds)) {
2889 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2891 $dao = CRM_Core_DAO
::executeQuery($query);
2892 $mediumIds = array();
2893 while ($dao->fetch()) {
2894 $mediumIds[] = $dao->medium_id
;
2902 * Check case configuration.
2904 * @param int $contactId
2908 public static function isCaseConfigured($contactId = NULL) {
2909 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2911 //lets check for case configured.
2912 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2913 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2914 if (!$configured['configured']) {
2915 //do check for case type and case status.
2916 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2917 if (!empty($caseTypes)) {
2918 $configured['configured'] = TRUE;
2919 if (!$configured['configured']) {
2920 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2921 if (!empty($caseStatuses)) {
2922 $configured['configured'] = TRUE;
2927 if ($configured['configured']) {
2928 //do check for active case type and case status.
2929 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2930 if (!empty($caseTypes)) {
2931 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2932 if (!empty($caseStatuses)) {
2933 $configured['allowToAddNewCase'] = TRUE;
2937 //do we need to redirect user to case admin.
2938 if (!$configured['allowToAddNewCase'] && $contactId) {
2939 //check for current contact case count.
2940 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2941 //redirect user to case admin page.
2942 if (!$currentContatCasesCount) {
2943 $configured['redirectToCaseAdmin'] = TRUE;
2952 * Used during case component enablement and during ugprade.
2956 public static function createCaseViews() {
2957 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2958 $dao = new CRM_Core_DAO();
2960 $sql = self
::createCaseViewsQuery('upcoming');
2962 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2966 // Above error doesn't get caught?
2967 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2968 if (is_null($doublecheck)) {
2972 $sql = self
::createCaseViewsQuery('recent');
2974 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2978 // Above error doesn't get caught?
2979 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
2980 if (is_null($doublecheck)) {
2988 * Helper function, also used by the upgrade in case of error
2990 * @param string $section
2994 public static function createCaseViewsQuery($section = 'upcoming') {
2996 $scheduled_id = CRM_Core_Pseudoconstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
2999 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3000 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3001 FROM civicrm_case_activity ca
3002 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3003 WHERE a.activity_date_time =
3004 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3005 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3006 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3007 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
3008 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
3012 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3013 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3014 FROM civicrm_case_activity ca
3015 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3016 WHERE a.activity_date_time =
3017 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3018 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3019 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3020 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
3021 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
3028 * Add/copy relationships, when new client is added for a case
3030 * @param int $caseId
3032 * @param int $contactId
3033 * Contact id / new client id.
3035 public static function addCaseRelationships($caseId, $contactId) {
3036 // get the case role / relationships for the case
3037 $caseRelationships = new CRM_Contact_DAO_Relationship();
3038 $caseRelationships->case_id
= $caseId;
3039 $caseRelationships->find();
3040 $relationshipTypes = array();
3042 // make sure we don't add duplicate relationships of same relationship type.
3043 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3045 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3047 // add relationship for new client.
3048 $newRelationship = new CRM_Contact_DAO_Relationship();
3049 $newRelationship->copyValues($values);
3050 $newRelationship->id
= NULL;
3051 $newRelationship->case_id
= $caseId;
3052 $newRelationship->contact_id_a
= $contactId;
3053 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3054 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3056 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3057 if (!$newRelationship->find(TRUE)) {
3058 $newRelationship->save();
3060 $newRelationship->free();
3062 // store relationship type of newly created relationship
3063 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3068 * Get the list of clients for a case.
3070 * @param int $caseId
3073 * associated array with client ids
3075 public static function getCaseClients($caseId) {
3077 $caseContact = new CRM_Case_DAO_CaseContact();
3078 $caseContact->case_id
= $caseId;
3079 $caseContact->orderBy('id');
3080 $caseContact->find();
3082 while ($caseContact->fetch()) {
3083 $clients[] = $caseContact->contact_id
;
3090 * @param int $caseId
3091 * @param string $direction
3093 * @param int $relTypeId
3094 * @throws \CRM_Core_Exception
3095 * @throws \CiviCRM_API3_Exception
3097 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3099 if ($direction !== 'a' && $direction !== 'b') {
3100 throw new CRM_Core_Exception('Invalid relationship direction');
3103 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3104 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3105 $dao = CRM_Core_DAO
::executeQuery($sql, array(
3106 1 => array($caseId, 'Positive'),
3107 2 => array($cid, 'Positive'),
3108 3 => array($relTypeId, 'Positive'),
3110 while ($dao->fetch()) {
3111 civicrm_api3('relationship', 'create', array(
3114 'end_date' => 'now',
3120 * Get options for a given case field.
3121 * @see CRM_Core_DAO::buildOptions
3123 * @param string $fieldName
3124 * @param string $context
3125 * @see CRM_Core_DAO::buildOptionsContext
3126 * @param array $props
3127 * Whatever is known about this dao object.
3129 * @return array|bool
3131 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3132 $className = __CLASS__
;
3134 switch ($fieldName) {
3135 // This field is not part of this object but the api supports it
3137 $className = 'CRM_Activity_BAO_Activity';
3140 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3146 public function addSelectWhereClause() {
3147 // We always return an array with these keys, even if they are empty,
3148 // because this tells the query builder that we have considered these fields for acls
3151 // Only case admins can view deleted cases
3152 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
array() : array("= 0"),
3154 // Ensure the user has permission to view the case client
3155 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3156 if ($contactClause) {
3157 $contactClause = implode(' AND contact_id ', $contactClause);
3158 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3160 // The api gatekeeper ensures the user has at least "access my cases and activities"
3161 // so if they do not have permission to see all cases we'll assume they can only access their own
3162 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3163 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3164 $clauses['id'][] = "IN (
3165 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 (
3166 (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)
3170 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3175 * CRM-20308: Method to get the contact id to use as from contact for email copy
3176 * 1. Activity Added by Contact's email address
3177 * 2. System Default From Address
3178 * 3. Default Organization Contact email address
3181 * @param int $activityID
3183 * @return mixed $emailFromContactId
3184 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3186 public static function getReceiptFrom($activityID) {
3187 $name = $address = NULL;
3189 if (!empty($activityID)) {
3190 // There is always a 'Added by' contact for a activity,
3191 // so we can safely use ActivityContact.Getvalue API
3192 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', array(
3193 'activity_id' => $activityID,
3194 'record_type_id' => 'Activity Source',
3195 'return' => 'contact_id',
3197 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3200 // If 'From' email address not found for Source Activity Contact then
3201 // fetch the email from domain or logged in user.
3202 if (empty($address)) {
3203 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3206 return "$name <$address>";