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');
1022 $statusTitle = ts('Edit Status');
1024 $emailActivityTypeIDs = array(
1025 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1029 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1035 $emailActivityTypeIDs = array(
1036 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1040 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1046 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1048 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1049 $compStatusValues = array();
1050 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1051 foreach ($compStatusNames as $name) {
1052 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1055 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=", FALSE, NULL, FALSE);
1056 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1057 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1060 $session = CRM_Core_Session
::singleton();
1061 $userID = $session->get('userID');
1064 $caseActivities = array();
1066 while ($dao->fetch()) {
1067 $caseActivity = array();
1068 $caseActivityId = $dao->id
;
1070 $allowView = self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID);
1071 $allowEdit = self
::checkPermission($caseActivityId, 'edit', $dao->activity_type_id
, $userID);
1072 $allowDelete = self
::checkPermission($caseActivityId, 'delete', $dao->activity_type_id
, $userID);
1074 //do not have sufficient permission
1075 //to access given case activity record.
1076 if (!$allowView && !$allowEdit && !$allowDelete) {
1080 $caseActivity['DT_RowId'] = $caseActivityId;
1081 //Add classes to the row, via DataTables syntax
1082 $caseActivity['DT_RowClass'] = "crm-entity status-id-$dao->status";
1084 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1085 $caseActivity['DT_RowClass'] .= " status-completed";
1088 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1089 $caseActivity['DT_RowClass'] .= " status-overdue";
1092 $caseActivity['DT_RowClass'] .= " status-scheduled";
1096 if (!empty($dao->priority
)) {
1097 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1098 $caseActivity['DT_RowClass'] .= " priority-urgent ";
1100 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1101 $caseActivity['DT_RowClass'] .= " priority-low ";
1105 //Add data to the row for inline editing, via DataTable syntax
1106 $caseActivity['DT_RowAttr'] = array();
1107 $caseActivity['DT_RowAttr']['data-entity'] = 'activity';
1108 $caseActivity['DT_RowAttr']['data-id'] = $caseActivityId;
1110 //Activity Date and Time
1111 $caseActivity['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1114 $caseActivity['subject'] = $dao->subject
;
1117 $caseActivity['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1118 . $activityTypes[$dao->type
]['label'];
1120 //Activity Target (With)
1121 $targetContact = '';
1122 if (isset($dao->target_contact_id
)) {
1123 $targetContact = $dao->target_contact_name
;
1124 if ($hasViewContact) {
1125 $targetContact = '<a href="' . $contactViewUrl . $dao->target_contact_id
. '">' . $dao->target_contact_name
. '</a>';
1128 $caseActivity['target_contact_name'] = $targetContact;
1130 //Activity Source Contact (Reporter)
1131 $sourceContact = $dao->source_contact_name
;
1132 if ($hasViewContact) {
1133 $sourceContact = '<a href="' . $contactViewUrl . $dao->source_contact_id
. '">' . $dao->source_contact_name
. '</a>';
1135 $caseActivity['source_contact_name'] = $sourceContact;
1137 //Activity Assignee. CRM-4485.
1138 $assigneeContact = '';
1139 if (isset($dao->assignee_contact_id
)) {
1140 $assigneeContact = $dao->assignee_contact_name
;
1141 if ($hasViewContact) {
1142 $assigneeContact = '<a href="' . $contactViewUrl . $dao->assignee_contact_id
. '">' . $dao->assignee_contact_name
. '</a>';
1145 $caseActivity['assignee_contact_name'] = $assigneeContact;
1148 $caseActivity['status_id'] = $activityStatuses[$dao->status
];
1150 // 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.
1152 $css = 'class="action-item crm-hover-button"';
1154 $viewUrl = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1155 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1157 $additionalUrl = "&id={$caseActivityId}";
1158 if (!$dao->deleted
) {
1159 //hide edit link of activity type email.CRM-4530.
1160 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1161 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1163 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1167 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1170 elseif (!$caseDeleted) {
1171 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1172 $caseActivity['status_id'] = $caseActivity['status_id'] . '<br /> (deleted)';
1175 //check for operations.
1176 if (self
::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id
)) {
1177 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1179 if (self
::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id
)) {
1180 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1182 // if there are file attachments we will return how many and, if only one, add a link to it
1183 if (!empty($dao->attachment_ids
)) {
1184 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1185 $caseActivity['no_attachments'] = count($attachmentIDs);
1186 $url .= implode(' ', CRM_Core_BAO_File
::paperIconAttachment('civicrm_activity', $caseActivityId));
1189 $caseActivity['links'] = $url;
1191 array_push($caseActivities, $caseActivity);
1195 $caseActivitiesDT = array();
1196 $caseActivitiesDT['data'] = $caseActivities;
1197 $caseActivitiesDT['recordsTotal'] = $caseCount;
1198 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1200 return $caseActivitiesDT;
1204 * Get Case Related Contacts.
1206 * @param int $caseID
1208 * @param bool $includeDetails
1209 * If true include details of contacts.
1212 * array of return properties
1215 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1216 $caseRoles = array();
1217 if ($includeDetails) {
1218 $caseInfo = civicrm_api3('Case', 'getsingle', array(
1220 // 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
1221 'return' => array('case_type_id', 'case_type_id.name', 'case_type_id.definition'),
1223 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1224 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1229 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
1230 FROM civicrm_relationship cr
1231 LEFT JOIN civicrm_relationship_type crt
1232 ON crt.id = cr.relationship_type_id
1233 LEFT JOIN civicrm_contact cc
1234 ON cc.id = cr.contact_id_b
1235 LEFT JOIN civicrm_email ce
1236 ON ce.contact_id = cc.id
1237 AND ce.is_primary= 1
1238 WHERE cr.case_id = %1 AND cr.is_active AND cc.is_deleted <> 1';
1240 $params = array(1 => array($caseID, 'Integer'));
1241 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1243 while ($dao->fetch()) {
1244 if (!$includeDetails) {
1245 $values[$dao->id
] = 1;
1249 'contact_id' => $dao->id
,
1250 'display_name' => $dao->name
,
1251 'sort_name' => $dao->sort_name
,
1252 'relationship_type_id' => $dao->relationship_type_id
,
1253 'role' => $dao->role
,
1254 'email' => $dao->email
,
1256 // Add more info about the role (creator, manager)
1257 $role = CRM_Utils_Array
::value($dao->name_b_a
, $caseRoles);
1259 unset($role['name']);
1262 $values[] = $details;
1271 * Send e-mail copy of activity
1273 * @param int $clientId
1274 * @param int $activityId
1276 * @param array $contacts
1277 * Array of related contact.
1279 * @param null $attachments
1280 * @param int $caseId
1282 * @return bool |array
1284 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1289 $tplParams = $activityInfo = array();
1290 //if its a case activity
1292 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1293 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1294 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1295 $anyActivity = TRUE;
1298 $anyActivity = FALSE;
1300 $tplParams['isCaseActivity'] = 1;
1301 $tplParams['client_id'] = $clientId;
1304 $anyActivity = TRUE;
1307 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1308 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1310 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1312 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1314 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1316 $tplParams['activity'] = $activityInfo;
1317 foreach ($tplParams['activity']['fields'] as $k => $val) {
1318 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1319 $activitySubject = $val['value'];
1323 $session = CRM_Core_Session
::singleton();
1324 // CRM-8926 If user is not logged in, use the activity creator as userID
1325 if (!($userID = $session->get('userID'))) {
1326 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1329 //also create activities simultaneously of this copy.
1330 $activityParams = array();
1332 $activityParams['source_record_id'] = $activityId;
1333 $activityParams['source_contact_id'] = $userID;
1334 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1335 $activityParams['activity_date_time'] = date('YmdHis');
1336 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1337 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1338 $activityParams['case_id'] = $caseId;
1339 $activityParams['is_auto'] = 0;
1340 $activityParams['target_id'] = $clientId;
1342 $tplParams['activitySubject'] = $activitySubject;
1344 // if it’s a case activity, add hashed id to the template (CRM-5916)
1346 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1350 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1351 $receiptFrom = self
::getReceiptFrom($activityId);
1353 $recordedActivityParams = array();
1355 foreach ($contacts as $mail => $info) {
1356 $tplParams['contact'] = $info;
1357 self
::buildPermissionLinks($tplParams, $activityParams);
1359 $displayName = CRM_Utils_Array
::value('display_name', $info);
1361 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1363 'groupName' => 'msg_tpl_workflow_case',
1364 'valueName' => 'case_activity',
1365 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1366 'tplParams' => $tplParams,
1367 'from' => $receiptFrom,
1368 'toName' => $displayName,
1370 'attachments' => $attachments,
1374 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1375 $activityParams['details'] = $message;
1377 if (!empty($result[$info['contact_id']])) {
1379 * Really only need to record one activity with all the targets combined.
1380 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1381 * but it's always the same content at the moment.
1383 if (empty($recordedActivityParams)) {
1384 $recordedActivityParams = $activityParams;
1387 $recordedActivityParams['subject'] .= "; $displayName";
1389 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1392 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1396 if (!empty($recordedActivityParams)) {
1397 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1399 //create case_activity record if its case activity.
1401 $caseParams = array(
1402 'activity_id' => $activity->id
,
1403 'case_id' => $caseId,
1405 self
::processCaseActivity($caseParams);
1413 * Retrieve count of activities having a particular type, and
1414 * associated with a particular case.
1416 * @param int $caseId
1418 * @param int $activityTypeId
1419 * ID of the activity type.
1423 public static function getCaseActivityCount($caseId, $activityTypeId) {
1424 $queryParam = array(
1425 1 => array($caseId, 'Integer'),
1426 2 => array($activityTypeId, 'Integer'),
1428 $query = "SELECT count(ca.id) as countact
1429 FROM civicrm_activity ca
1430 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1431 WHERE ca.activity_type_id = %2
1432 AND cca.case_id = %1
1433 AND ca.is_deleted = 0";
1435 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1436 if ($dao->fetch()) {
1437 return $dao->countact
;
1444 * Create an activity for a case via email.
1449 * @return array|void
1450 * $activity object of newly creted activity via email
1452 public static function recordActivityViaEmail($file) {
1453 if (!file_exists($file) ||
1456 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1461 $result = CRM_Utils_Mail_Incoming
::parse($file);
1462 if ($result['is_error']) {
1466 foreach ($result['to'] as $to) {
1469 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1470 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1472 if ($replacement !== $to['email']) {
1473 $caseId = $replacement;
1474 //if caseId is invalid, return as error file
1475 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1476 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1485 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1486 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1487 $contactDetails = self
::getRelatedContacts($caseId, FALSE);
1489 if (!empty($contactDetails[$result['from']['id']])) {
1491 $params['subject'] = $result['subject'];
1492 $params['activity_date_time'] = $result['date'];
1493 $params['details'] = $result['body'];
1494 $params['source_contact_id'] = $result['from']['id'];
1495 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1500 $details = CRM_Case_PseudoConstant
::caseActivityType();
1502 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1503 $result['body'], $matches
1506 if (!empty($matches) && isset($matches[1])) {
1507 $activityType = trim($matches[1]);
1508 if (isset($details[$activityType])) {
1509 $params['activity_type_id'] = $details[$activityType]['id'];
1512 if (!isset($params['activity_type_id'])) {
1513 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1517 $activity = CRM_Activity_BAO_Activity
::create($params);
1519 $caseParams = array(
1520 'activity_id' => $activity->id
,
1521 'case_id' => $caseId,
1523 self
::processCaseActivity($caseParams);
1526 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1527 array(1 => $result['from']['email'])
1534 * Retrieve the scheduled activity type and date.
1536 * @param array $cases
1537 * Array of contact and case id.
1539 * @param string $type
1542 * Array of scheduled activity type and date
1546 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1547 $session = CRM_Core_Session
::singleton();
1548 $userID = $session->get('userID');
1550 $caseID = implode(',', $cases['case_id']);
1551 $contactID = implode(',', $cases['contact_id']);
1554 AND civicrm_case_contact.contact_id IN( {$contactID} )
1555 AND civicrm_case.id IN( {$caseID})
1556 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1558 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1560 $res = CRM_Core_DAO
::executeQuery($query);
1562 $activityInfo = array();
1563 while ($res->fetch()) {
1564 if ($type == 'upcoming') {
1565 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1566 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1569 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1570 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1574 return $activityInfo;
1578 * Combine all the exportable fields from the lower levels object.
1581 * array of exportable Fields
1583 public static function &exportableFields() {
1584 if (!self
::$_exportableFields) {
1585 if (!self
::$_exportableFields) {
1586 self
::$_exportableFields = array();
1589 $fields = CRM_Case_DAO_Case
::export();
1590 $fields['case_role'] = array('title' => ts('Role in Case'));
1591 $fields['case_type'] = array(
1592 'title' => ts('Case Type'),
1593 'name' => 'case_type',
1595 $fields['case_status'] = array(
1596 'title' => ts('Case Status'),
1597 'name' => 'case_status',
1600 // add custom data for cases
1601 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1603 self
::$_exportableFields = $fields;
1605 return self
::$_exportableFields;
1609 * Restore the record that are associated with this case.
1611 * @param int $caseId
1612 * Id of the case to restore.
1616 public static function restoreCase($caseId) {
1617 //restore activities
1618 $activities = self
::getCaseActivityDates($caseId);
1620 foreach ($activities as $value) {
1621 CRM_Activity_BAO_Activity
::restoreActivity($value);
1625 $case = new CRM_Case_DAO_Case();
1626 $case->id
= $caseId;
1627 $case->is_deleted
= 0;
1630 //CRM-7364, enable relationships
1631 self
::enableDisableCaseRelationships($caseId, TRUE);
1638 * @param null $showLinks
1639 * @param bool $returnOnlyCount
1640 * @param int $offset
1641 * @param int $rowCount
1645 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1646 $globalContacts = array();
1648 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1649 $settings = $settingsProcessor->run();
1650 if (!empty($settings)) {
1651 $groupInfo['name'] = $settings['groupname'];
1652 if ($groupInfo['name']) {
1653 $searchParams = array('name' => $groupInfo['name']);
1655 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1657 $groupInfo['id'] = $results['id'];
1658 $groupInfo['title'] = $results['title'];
1659 $params = array(array('group', '=', $groupInfo['id'], 0, 0));
1660 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1661 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1663 if ($returnOnlyCount) {
1664 return $globalContacts;
1668 foreach ($globalContacts as $idx => $contact) {
1669 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1675 return $globalContacts;
1679 * Convenience function to get both case contacts and global in one array.
1680 * @param int $caseId
1684 public static function getRelatedAndGlobalContacts($caseId) {
1685 $relatedContacts = self
::getRelatedContacts($caseId);
1687 $groupInfo = array();
1688 $globalContacts = self
::getGlobalContacts($groupInfo);
1690 //unset values which are not required.
1691 foreach ($globalContacts as $k => & $v) {
1692 unset($v['email_id']);
1693 unset($v['group_contact_id']);
1694 unset($v['status']);
1696 $v['role'] = $groupInfo['title'];
1698 //include multiple listings for the same contact/different roles.
1699 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1700 return $relatedGlobalContacts;
1704 * Get Case ActivitiesDueDates with given criteria.
1706 * @param int $caseID
1708 * @param array $criteriaParams
1710 * @param bool $latestDate
1711 * If set newest or oldest date is selected.
1714 * case activities due dates
1717 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1719 $selectDate = " ca.activity_date_time";
1720 $where = $groupBy = ' ';
1727 if (!empty($criteriaParams['activity_type_id'])) {
1728 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1729 $where .= " AND ca.is_current_revision = 1";
1730 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1733 if (!empty($criteriaParams['newest'])) {
1734 $selectDate = " max(ca.activity_date_time) ";
1737 $selectDate = " min(ca.activity_date_time) ";
1741 $query = "SELECT ca.id, {$selectDate} as activity_date
1742 FROM civicrm_activity ca
1743 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1744 WHERE cc.id = %1 {$where} {$groupBy}";
1746 $params = array(1 => array($caseID, 'Integer'));
1747 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1749 while ($dao->fetch()) {
1750 $values[$dao->id
]['id'] = $dao->id
;
1751 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1758 * Create activities when Case or Other roles assigned/modified/deleted.
1760 * @param int $caseId
1761 * @param int $relationshipId
1763 * @param int $relContactId
1764 * Case role assignee contactId.
1765 * @param int $contactId
1767 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1768 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1772 $queryParam = array();
1773 if (is_array($relationshipId)) {
1774 $relationshipId = implode(',', $relationshipId);
1775 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1778 $relationshipClause = " civicrm_relationship.id = %1";
1779 $queryParam[1] = array($relationshipId, 'Positive');
1783 SELECT cc.display_name as clientName,
1784 cca.display_name as assigneeContactName,
1785 civicrm_relationship.case_id as caseId,
1786 civicrm_relationship_type.label_a_b as relation_a_b,
1787 civicrm_relationship_type.label_b_a as relation_b_a,
1788 civicrm_relationship.contact_id_b as rel_contact_id,
1789 civicrm_relationship.contact_id_a as assign_contact_id
1790 FROM civicrm_relationship_type, civicrm_relationship
1791 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1792 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1793 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1795 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1797 while ($dao->fetch()) {
1798 // The assignee is not the client.
1799 if ($dao->rel_contact_id
!= $contactId) {
1800 $caseRelationship = $dao->relation_a_b
;
1801 $assigneContactName = $dao->clientName
;
1802 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1805 $caseRelationship = $dao->relation_b_a
;
1806 $assigneContactName = $dao->assigneeContactName
;
1807 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1811 $session = CRM_Core_Session
::singleton();
1812 $activityParams = array(
1813 'source_contact_id' => $session->get('userID'),
1814 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1815 'activity_date_time' => date('YmdHis'),
1816 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1819 //if $relContactId is passed, role is added or modified.
1820 if (!empty($relContactId)) {
1821 $activityParams['assignee_contact_id'] = $assigneContactIds;
1823 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1829 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1835 $activityParams['activity_type_id'] = $activityTypeID;
1837 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1839 //create case_activity record.
1840 $caseParams = array(
1841 'activity_id' => $activity->id
,
1842 'case_id' => $caseId,
1845 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1850 * contact which is assigned a case role of case manager.
1852 * @param int $caseType
1854 * @param int $caseId
1858 * array of contact on success otherwise empty
1861 public static function getCaseManagerContact($caseType, $caseId) {
1862 if (!$caseType ||
!$caseId) {
1866 $caseManagerContact = array();
1867 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1869 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1871 if (!empty($managerRoleId)) {
1872 $managerRoleQuery = "
1873 SELECT civicrm_contact.id as casemanager_id,
1874 civicrm_contact.sort_name as casemanager
1875 FROM civicrm_contact
1876 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1877 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1878 WHERE civicrm_case.id = %2 AND is_active = 1";
1880 $managerRoleParams = array(
1881 1 => array($managerRoleId, 'Integer'),
1882 2 => array($caseId, 'Integer'),
1885 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1886 if ($dao->fetch()) {
1887 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1888 $caseManagerContact['casemanager'] = $dao->casemanager
;
1892 return $caseManagerContact;
1896 * @param int $contactId
1897 * @param bool $excludeDeleted
1901 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1902 $params = array('check_permissions' => TRUE);
1903 if ($excludeDeleted) {
1904 $params['is_deleted'] = 0;
1907 $params['contact_id'] = $contactId;
1910 return civicrm_api3('Case', 'getcount', $params);
1912 catch (CiviCRM_API3_Exception
$e) {
1913 // Lack of permissions will throw an exception
1919 * Retrieve related cases for give case.
1921 * @param int $mainCaseId
1923 * @param int $contactId
1925 * @param bool $excludeDeleted
1926 * Do not include deleted cases.
1930 public static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
1931 //FIXME : do check for permissions.
1933 $relatedCases = array();
1934 if (!$mainCaseId ||
!$contactId) {
1935 return $relatedCases;
1938 $linkActType = array_search('Link Cases',
1939 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
1941 if (!$linkActType) {
1942 return $relatedCases;
1945 $whereClause = "mainCase.id = %2";
1946 if ($excludeDeleted) {
1947 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1950 //1. first fetch related case ids.
1952 SELECT relCaseAct.case_id
1953 FROM civicrm_case mainCase
1954 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1955 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1956 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1957 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1958 WHERE $whereClause";
1960 $dao = CRM_Core_DAO
::executeQuery($query, array(
1961 1 => array($linkActType, 'Integer'),
1962 2 => array($mainCaseId, 'Integer'),
1964 $relatedCaseIds = array();
1965 while ($dao->fetch()) {
1966 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1970 // there are no related cases.
1971 if (empty($relatedCaseIds)) {
1972 return $relatedCases;
1975 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1976 if ($excludeDeleted) {
1977 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1980 //filter for permissioned cases.
1981 $filterCases = array();
1982 $doFilterCases = FALSE;
1983 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1984 $doFilterCases = TRUE;
1985 $session = CRM_Core_Session
::singleton();
1986 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
1989 //2. fetch the details of related cases.
1991 SELECT relCase.id as id,
1992 civicrm_case_type.title as case_type,
1993 client.display_name as client_name,
1994 client.id as client_id
1995 FROM civicrm_case relCase
1996 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
1997 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
1998 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
1999 WHERE {$whereClause}";
2001 $dao = CRM_Core_DAO
::executeQuery($query);
2002 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2003 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2005 while ($dao->fetch()) {
2007 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2008 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2009 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2010 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2012 $clientView = $dao->client_name
;
2013 if ($hasViewContact) {
2014 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2017 $relatedCases[$dao->id
] = array(
2018 'case_id' => $dao->id
,
2019 'case_type' => $dao->case_type
,
2020 'client_name' => $clientView,
2021 'links' => $caseView,
2026 return $relatedCases;
2030 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2032 * @see CRM_Dedupe_Merger::cpTables()
2034 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2036 * @param int $mainContactId
2037 * @param int $otherContactId
2039 public static function mergeContacts($mainContactId, $otherContactId) {
2040 self
::mergeCases($mainContactId, NULL, $otherContactId);
2044 * Function perform two task.
2045 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2046 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2048 * @param int $mainContactId
2049 * Contact id of main contact record.
2050 * @param int $mainCaseId
2051 * Case id of main case record.
2052 * @param int $otherContactId
2053 * Contact id of record which is going to merge.
2054 * @param int $otherCaseId
2055 * Case id of record which is going to merge.
2057 * @param bool $changeClient
2061 public static function mergeCases(
2062 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2063 $otherCaseId = NULL, $changeClient = FALSE) {
2064 $moveToTrash = TRUE;
2066 $duplicateContacts = FALSE;
2067 if ($mainContactId && $otherContactId &&
2068 $mainContactId != $otherContactId
2070 $duplicateContacts = TRUE;
2073 $duplicateCases = FALSE;
2074 if ($mainCaseId && $otherCaseId &&
2075 $mainCaseId != $otherCaseId
2077 $duplicateCases = TRUE;
2080 $mainCaseIds = array();
2081 if (!$duplicateContacts && !$duplicateCases) {
2082 return $mainCaseIds;
2085 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2086 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2087 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2088 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2089 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2090 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2092 $processCaseIds = array($otherCaseId);
2093 if ($duplicateContacts && !$duplicateCases) {
2094 if ($changeClient) {
2095 $processCaseIds = array($mainCaseId);
2098 //get all case ids for other contact.
2099 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2101 if (!is_array($processCaseIds)) {
2106 $session = CRM_Core_Session
::singleton();
2107 $currentUserId = $session->get('userID');
2109 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2111 // copy all cases and connect to main contact id.
2112 foreach ($processCaseIds as $otherCaseId) {
2113 if ($duplicateContacts) {
2114 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2115 $mainCaseId = $mainCase->id
;
2120 // CRM-11662 Copy Case custom data
2121 $extends = array('case');
2122 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2124 foreach ($groupTree as $groupID => $group) {
2125 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2126 foreach ($group['fields'] as $fieldID => $field) {
2127 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2131 foreach ($table as $tableName => $tableColumns) {
2132 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2133 $tableColumns[0] = $mainCaseId;
2134 $select = 'SELECT ' . implode(', ', $tableColumns);
2135 $from = ' FROM ' . $tableName;
2136 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2137 $query = $insert . $select . $from . $where;
2138 $dao = CRM_Core_DAO
::executeQuery($query);
2144 $mainCaseIds[] = $mainCaseId;
2145 //insert record for case contact.
2146 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2147 $otherCaseContact->case_id
= $otherCaseId;
2148 $otherCaseContact->find();
2149 while ($otherCaseContact->fetch()) {
2150 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2151 $mainCaseContact->case_id
= $mainCaseId;
2152 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2153 if ($mainCaseContact->contact_id
== $otherContactId) {
2154 $mainCaseContact->contact_id
= $mainContactId;
2156 //avoid duplicate object.
2157 if (!$mainCaseContact->find(TRUE)) {
2158 $mainCaseContact->save();
2160 $mainCaseContact->free();
2162 $otherCaseContact->free();
2164 elseif (!$otherContactId) {
2165 $otherContactId = $mainContactId;
2168 if (!$mainCaseId ||
!$otherCaseId ||
2169 !$mainContactId ||
!$otherContactId
2174 // get all activities for other case.
2175 $otherCaseActivities = array();
2176 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2178 //for duplicate cases do not process singleton activities.
2179 $otherActivityIds = $singletonActivityIds = array();
2180 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2181 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2182 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2185 $otherActivityIds[] = $otherActId;
2187 if ($duplicateCases) {
2188 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2191 FROM civicrm_activity
2192 WHERE activity_type_id = $openCaseType
2193 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2194 $dao = CRM_Core_DAO
::executeQuery($sql);
2195 while ($dao->fetch()) {
2196 $singletonActivityIds[] = $dao->id
;
2202 // migrate all activities and connect to main contact.
2203 $copiedActivityIds = $activityMappingIds = array();
2204 sort($otherActivityIds);
2205 foreach ($otherActivityIds as $otherActivityId) {
2207 //for duplicate cases -
2208 //do not migrate singleton activities.
2209 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2213 //migrate activity record.
2214 $otherActivity = new CRM_Activity_DAO_Activity();
2215 $otherActivity->id
= $otherActivityId;
2216 if (!$otherActivity->find(TRUE)) {
2220 $mainActVals = array();
2221 $mainActivity = new CRM_Activity_DAO_Activity();
2222 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2223 $mainActivity->copyValues($mainActVals);
2224 $mainActivity->id
= NULL;
2225 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2226 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2230 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2234 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2237 $mainActivity->save();
2238 $mainActivityId = $mainActivity->id
;
2239 if (!$mainActivityId) {
2243 $activityMappingIds[$otherActivityId] = $mainActivityId;
2244 // insert log of all activities
2245 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2247 $otherActivity->free();
2248 $mainActivity->free();
2249 $copiedActivityIds[] = $otherActivityId;
2251 //create case activity record.
2252 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2253 $mainCaseActivity->case_id
= $mainCaseId;
2254 $mainCaseActivity->activity_id
= $mainActivityId;
2255 $mainCaseActivity->save();
2256 $mainCaseActivity->free();
2258 //migrate source activity.
2259 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2260 $otherSourceActivity->activity_id
= $otherActivityId;
2261 $otherSourceActivity->record_type_id
= $sourceID;
2262 $otherSourceActivity->find();
2263 while ($otherSourceActivity->fetch()) {
2264 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2265 $mainActivitySource->record_type_id
= $sourceID;
2266 $mainActivitySource->activity_id
= $mainActivityId;
2267 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2268 if ($mainActivitySource->contact_id
== $otherContactId) {
2269 $mainActivitySource->contact_id
= $mainContactId;
2271 //avoid duplicate object.
2272 if (!$mainActivitySource->find(TRUE)) {
2273 $mainActivitySource->save();
2275 $mainActivitySource->free();
2277 $otherSourceActivity->free();
2279 //migrate target activities.
2280 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2281 $otherTargetActivity->activity_id
= $otherActivityId;
2282 $otherTargetActivity->record_type_id
= $targetID;
2283 $otherTargetActivity->find();
2284 while ($otherTargetActivity->fetch()) {
2285 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2286 $mainActivityTarget->record_type_id
= $targetID;
2287 $mainActivityTarget->activity_id
= $mainActivityId;
2288 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2289 if ($mainActivityTarget->contact_id
== $otherContactId) {
2290 $mainActivityTarget->contact_id
= $mainContactId;
2292 //avoid duplicate object.
2293 if (!$mainActivityTarget->find(TRUE)) {
2294 $mainActivityTarget->save();
2296 $mainActivityTarget->free();
2298 $otherTargetActivity->free();
2300 //migrate assignee activities.
2301 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2302 $otherAssigneeActivity->activity_id
= $otherActivityId;
2303 $otherAssigneeActivity->record_type_id
= $assigneeID;
2304 $otherAssigneeActivity->find();
2305 while ($otherAssigneeActivity->fetch()) {
2306 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2307 $mainAssigneeActivity->activity_id
= $mainActivityId;
2308 $mainAssigneeActivity->record_type_id
= $assigneeID;
2309 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2310 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2311 $mainAssigneeActivity->contact_id
= $mainContactId;
2313 //avoid duplicate object.
2314 if (!$mainAssigneeActivity->find(TRUE)) {
2315 $mainAssigneeActivity->save();
2317 $mainAssigneeActivity->free();
2319 $otherAssigneeActivity->free();
2321 // copy custom fields and attachments
2323 'activityID' => $otherActivityId,
2324 'mainActivityId' => $mainActivityId,
2326 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2329 //copy case relationship.
2330 if ($duplicateContacts) {
2331 //migrate relationship records.
2332 $otherRelationship = new CRM_Contact_DAO_Relationship();
2333 $otherRelationship->case_id
= $otherCaseId;
2334 $otherRelationship->find();
2335 $otherRelationshipIds = array();
2336 while ($otherRelationship->fetch()) {
2337 $otherRelVals = array();
2338 $updateOtherRel = FALSE;
2339 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2341 $mainRelationship = new CRM_Contact_DAO_Relationship();
2342 $mainRelationship->copyValues($otherRelVals);
2343 $mainRelationship->id
= NULL;
2344 $mainRelationship->case_id
= $mainCaseId;
2345 if ($mainRelationship->contact_id_a
== $otherContactId) {
2346 $updateOtherRel = TRUE;
2347 $mainRelationship->contact_id_a
= $mainContactId;
2350 //case creator change only when we merge user contact.
2351 if ($mainRelationship->contact_id_b
== $otherContactId) {
2352 //do not change creator for change client.
2353 if (!$changeClient) {
2354 $updateOtherRel = TRUE;
2355 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2358 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2359 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2361 //avoid duplicate object.
2362 if (!$mainRelationship->find(TRUE)) {
2363 $mainRelationship->save();
2365 $mainRelationship->free();
2367 //get the other relationship ids to update end date.
2368 if ($updateOtherRel) {
2369 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2372 $otherRelationship->free();
2374 //update other relationships end dates
2375 if (!empty($otherRelationshipIds)) {
2376 $sql = 'UPDATE civicrm_relationship
2377 SET end_date = CURDATE()
2378 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2379 CRM_Core_DAO
::executeQuery($sql);
2383 //move other case to trash.
2384 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2389 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2390 if ($changeClient) {
2391 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2392 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2394 $mergeActType = array_search('Reassigned Case', $activityTypes);
2395 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2398 2 => $otherContactDisplayName,
2399 3 => $mainContactDisplayName,
2404 elseif ($duplicateContacts) {
2405 $mergeActType = array_search('Merge Case', $activityTypes);
2406 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2409 2 => $otherContactId,
2410 3 => $mainContactId,
2416 $mergeActType = array_search('Merge Case', $activityTypes);
2417 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2418 if (!empty($copiedActivityIds)) {
2420 SELECT id, subject, activity_date_time, activity_type_id
2421 FROM civicrm_activity
2422 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2423 $dao = CRM_Core_DAO
::executeQuery($sql);
2424 while ($dao->fetch()) {
2425 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2426 if ($dao->subject
) {
2427 $mergeActSubjectDetails .= " :: {$dao->subject}";
2429 $mergeActSubjectDetails .= "<br />";
2434 //Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2435 $activityParams = array(
2436 'subject' => $mergeActSubject,
2437 'details' => $mergeActSubjectDetails,
2438 'status_id' => array_search('Completed', $activityStatuses),
2439 'activity_type_id' => $mergeActType,
2440 'source_contact_id' => $currentUserId,
2441 'activity_date_time' => date('YmdHis'),
2444 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2445 $mergeActivityId = $mergeActivity->id
;
2446 if (!$mergeActivityId) {
2449 $mergeActivity->free();
2451 //connect merge activity to case.
2452 $mergeCaseAct = array(
2453 'case_id' => $mainCaseId,
2454 'activity_id' => $mergeActivityId,
2457 self
::processCaseActivity($mergeCaseAct);
2460 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2462 return $mainCaseIds;
2466 * Validate contact permission for
2467 * edit/view on activity record and build links.
2469 * @param array $tplParams
2470 * Params to be sent to template for sending email.
2471 * @param array $activityParams
2472 * Info of the activity.
2474 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2475 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2476 'activity_type_id', 'id'
2479 if (!empty($tplParams['isCaseActivity'])) {
2480 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2481 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2484 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2485 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2488 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2489 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2493 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2494 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2497 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2498 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2504 * Validate contact permission for
2505 * given operation on activity record.
2507 * @param int $activityId
2508 * Activity record id.
2509 * @param string $operation
2511 * @param int $actTypeId
2513 * @param int $contactId
2514 * Contact id/if not pass consider logged in.
2515 * @param bool $checkComponent
2516 * Do we need to check component enabled.
2520 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2522 if (!$actTypeId && $activityId) {
2523 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2526 if (!$activityId ||
!$operation ||
!$actTypeId) {
2530 //do check for civicase component enabled.
2531 if ($checkComponent && !self
::enabled()) {
2535 //do check for cases.
2536 $caseActOperations = array(
2543 if (in_array($operation, $caseActOperations)) {
2545 if (!isset($caseCount)) {
2547 $caseCount = civicrm_api3('Case', 'getcount', array(
2548 'check_permissions' => TRUE,
2549 'status_id' => array('!=' => 'Closed'),
2551 'end_date' => array('IS NULL' => 1),
2554 catch (CiviCRM_API3_Exception
$e) {
2555 // Lack of permissions will throw an exception
2559 if ($operation == 'File On Case') {
2560 $allow = !empty($caseCount);
2563 $allow = ($caseCount > 1);
2567 $actionOperations = array('view', 'edit', 'delete');
2568 if (in_array($operation, $actionOperations)) {
2570 //do cache when user has non/supper permission.
2571 static $allowOperations;
2573 if (!is_array($allowOperations) ||
2574 !array_key_exists($operation, $allowOperations)
2578 $session = CRM_Core_Session
::singleton();
2579 $contactId = $session->get('userID');
2582 //check for permissions.
2583 $permissions = array(
2585 'access my cases and activities',
2586 'access all cases and activities',
2589 'access my cases and activities',
2590 'access all cases and activities',
2592 'delete' => array('delete activities'),
2595 //check for core permission.
2596 $hasPermissions = array();
2597 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2598 if (is_array($checkPermissions)) {
2599 foreach ($checkPermissions as $per) {
2600 if (CRM_Core_Permission
::check($per)) {
2601 $hasPermissions[$operation][] = $per;
2607 if (!empty($hasPermissions)) {
2608 //need to check activity object specific.
2609 if (in_array($operation, array(
2614 //do we have supper permission.
2615 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2616 $allowOperations[$operation] = $allow = TRUE;
2619 //user has only access to my cases and activity.
2620 //here object specific permmions come in picture.
2622 //edit - contact must be source or assignee
2623 //view - contact must be source/assignee/target
2624 $isTarget = $isAssignee = $isSource = FALSE;
2625 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2626 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2627 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2628 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2630 $target = new CRM_Activity_DAO_ActivityContact();
2631 $target->record_type_id
= $targetID;
2632 $target->activity_id
= $activityId;
2633 $target->contact_id
= $contactId;
2634 if ($target->find(TRUE)) {
2638 $assignee = new CRM_Activity_DAO_ActivityContact();
2639 $assignee->activity_id
= $activityId;
2640 $assignee->record_type_id
= $assigneeID;
2641 $assignee->contact_id
= $contactId;
2642 if ($assignee->find(TRUE)) {
2646 $source = new CRM_Activity_DAO_ActivityContact();
2647 $source->activity_id
= $activityId;
2648 $source->record_type_id
= $sourceID;
2649 $source->contact_id
= $contactId;
2650 if ($source->find(TRUE)) {
2654 if ($operation == 'edit') {
2655 if ($isAssignee ||
$isSource) {
2659 if ($operation == 'view') {
2660 if ($isTarget ||
$isAssignee ||
$isSource) {
2666 elseif (is_array($hasPermissions[$operation])) {
2667 $allowOperations[$operation] = $allow = TRUE;
2671 //contact do not have permission.
2672 $allowOperations[$operation] = FALSE;
2677 //here contact might have supper/non permission.
2678 $allow = $allowOperations[$operation];
2682 //do further only when operation is granted.
2684 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2686 //get the activity type name.
2687 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2689 //do not allow multiple copy / edit action.
2690 $singletonNames = array(
2700 //do not allow to delete these activities, CRM-4543
2701 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2703 //allow edit operation.
2704 $allowEditNames = array('Open Case');
2706 // do not allow File on Case
2707 $doNotFileNames = array(
2710 'Change Case Status',
2711 'Change Case Start Date',
2718 if (in_array($actTypeName, $singletonNames)) {
2720 if ($operation == 'File On Case') {
2721 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2723 if (in_array($operation, $actionOperations)) {
2725 if ($operation == 'edit') {
2726 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2728 elseif ($operation == 'delete') {
2729 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2733 if ($allow && ($operation == 'delete') &&
2734 in_array($actTypeName, $doNotDeleteNames)
2739 if ($allow && ($operation == 'File On Case') &&
2740 in_array($actTypeName, $doNotFileNames)
2745 //check settings file for masking actions
2746 //on the basis the activity types
2747 //hide Edit link if activity type is NOT editable
2748 //(special case activities).CRM-5871
2749 if ($allow && in_array($operation, $actionOperations)) {
2750 static $actionFilter = array();
2751 if (!array_key_exists($operation, $actionFilter)) {
2752 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2753 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2755 if (array_key_exists($operation, $actionFilter[$operation]) &&
2756 in_array($actTypeId, $actionFilter[$operation][$operation])
2767 * Since we drop 'access CiviCase', allow access
2768 * if user has 'access my cases and activities'
2769 * or 'access all cases and activities'
2771 public static function accessCiviCase() {
2772 if (!self
::enabled()) {
2776 if (CRM_Core_Permission
::check('access my cases and activities') ||
2777 CRM_Core_Permission
::check('access all cases and activities')
2786 * Verify user has permission to access a case.
2788 * @param int $caseId
2789 * @param bool $denyClosed
2790 * Set TRUE if one wants closed cases to be treated as inaccessible.
2794 public static function accessCase($caseId, $denyClosed = TRUE) {
2795 if (!$caseId ||
!self
::enabled()) {
2799 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2800 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2801 $params['status_id'] = array('!=' => 'Closed');
2804 return (bool) civicrm_api3('Case', 'getcount', $params);
2806 catch (CiviCRM_API3_Exception
$e) {
2807 // Lack of permissions will throw an exception
2813 * Check whether activity is a case Activity.
2815 * @param int $activityID
2820 public static function isCaseActivity($activityID) {
2821 $isCaseActivity = FALSE;
2823 $params = array(1 => array($activityID, 'Integer'));
2824 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2825 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2826 $isCaseActivity = TRUE;
2830 return $isCaseActivity;
2834 * Get all the case type ids currently in use.
2838 public static function getUsedCaseType() {
2839 static $caseTypeIds;
2841 if (!is_array($caseTypeIds)) {
2842 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2844 $dao = CRM_Core_DAO
::executeQuery($query);
2845 $caseTypeIds = array();
2846 while ($dao->fetch()) {
2847 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2850 $caseTypeIds[] = $typeId[1];
2854 return $caseTypeIds;
2858 * Get all the case status ids currently in use.
2862 public static function getUsedCaseStatuses() {
2863 static $caseStatusIds;
2865 if (!is_array($caseStatusIds)) {
2866 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2868 $dao = CRM_Core_DAO
::executeQuery($query);
2869 $caseStatusIds = array();
2870 while ($dao->fetch()) {
2871 $caseStatusIds[] = $dao->status_id
;
2875 return $caseStatusIds;
2879 * Get all the encounter medium ids currently in use.
2883 public static function getUsedEncounterMediums() {
2886 if (!is_array($mediumIds)) {
2887 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2889 $dao = CRM_Core_DAO
::executeQuery($query);
2890 $mediumIds = array();
2891 while ($dao->fetch()) {
2892 $mediumIds[] = $dao->medium_id
;
2900 * Check case configuration.
2902 * @param int $contactId
2906 public static function isCaseConfigured($contactId = NULL) {
2907 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2909 //lets check for case configured.
2910 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2911 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2912 if (!$configured['configured']) {
2913 //do check for case type and case status.
2914 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2915 if (!empty($caseTypes)) {
2916 $configured['configured'] = TRUE;
2917 if (!$configured['configured']) {
2918 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2919 if (!empty($caseStatuses)) {
2920 $configured['configured'] = TRUE;
2925 if ($configured['configured']) {
2926 //do check for active case type and case status.
2927 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2928 if (!empty($caseTypes)) {
2929 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2930 if (!empty($caseStatuses)) {
2931 $configured['allowToAddNewCase'] = TRUE;
2935 //do we need to redirect user to case admin.
2936 if (!$configured['allowToAddNewCase'] && $contactId) {
2937 //check for current contact case count.
2938 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2939 //redirect user to case admin page.
2940 if (!$currentContatCasesCount) {
2941 $configured['redirectToCaseAdmin'] = TRUE;
2950 * Used during case component enablement and during ugprade.
2954 public static function createCaseViews() {
2955 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2956 $dao = new CRM_Core_DAO();
2958 $sql = self
::createCaseViewsQuery('upcoming');
2960 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2964 // Above error doesn't get caught?
2965 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2966 if (is_null($doublecheck)) {
2970 $sql = self
::createCaseViewsQuery('recent');
2972 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2976 // Above error doesn't get caught?
2977 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
2978 if (is_null($doublecheck)) {
2986 * Helper function, also used by the upgrade in case of error
2988 * @param string $section
2992 public static function createCaseViewsQuery($section = 'upcoming') {
2994 $scheduled_id = CRM_Core_Pseudoconstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
2997 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
2998 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
2999 FROM civicrm_case_activity ca
3000 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3001 WHERE a.activity_date_time =
3002 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3003 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3004 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3005 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
3006 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
3010 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3011 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3012 FROM civicrm_case_activity ca
3013 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3014 WHERE a.activity_date_time =
3015 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3016 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3017 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3018 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
3019 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
3026 * Add/copy relationships, when new client is added for a case
3028 * @param int $caseId
3030 * @param int $contactId
3031 * Contact id / new client id.
3033 public static function addCaseRelationships($caseId, $contactId) {
3034 // get the case role / relationships for the case
3035 $caseRelationships = new CRM_Contact_DAO_Relationship();
3036 $caseRelationships->case_id
= $caseId;
3037 $caseRelationships->find();
3038 $relationshipTypes = array();
3040 // make sure we don't add duplicate relationships of same relationship type.
3041 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3043 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3045 // add relationship for new client.
3046 $newRelationship = new CRM_Contact_DAO_Relationship();
3047 $newRelationship->copyValues($values);
3048 $newRelationship->id
= NULL;
3049 $newRelationship->case_id
= $caseId;
3050 $newRelationship->contact_id_a
= $contactId;
3051 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3052 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3054 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3055 if (!$newRelationship->find(TRUE)) {
3056 $newRelationship->save();
3058 $newRelationship->free();
3060 // store relationship type of newly created relationship
3061 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3066 * Get the list of clients for a case.
3068 * @param int $caseId
3071 * associated array with client ids
3073 public static function getCaseClients($caseId) {
3075 $caseContact = new CRM_Case_DAO_CaseContact();
3076 $caseContact->case_id
= $caseId;
3077 $caseContact->orderBy('id');
3078 $caseContact->find();
3080 while ($caseContact->fetch()) {
3081 $clients[] = $caseContact->contact_id
;
3088 * @param int $caseId
3089 * @param string $direction
3091 * @param int $relTypeId
3092 * @throws \CRM_Core_Exception
3093 * @throws \CiviCRM_API3_Exception
3095 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3097 if ($direction !== 'a' && $direction !== 'b') {
3098 throw new CRM_Core_Exception('Invalid relationship direction');
3101 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3102 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3103 $dao = CRM_Core_DAO
::executeQuery($sql, array(
3104 1 => array($caseId, 'Positive'),
3105 2 => array($cid, 'Positive'),
3106 3 => array($relTypeId, 'Positive'),
3108 while ($dao->fetch()) {
3109 civicrm_api3('relationship', 'create', array(
3112 'end_date' => 'now',
3118 * Get options for a given case field.
3119 * @see CRM_Core_DAO::buildOptions
3121 * @param string $fieldName
3122 * @param string $context
3123 * @see CRM_Core_DAO::buildOptionsContext
3124 * @param array $props
3125 * Whatever is known about this dao object.
3127 * @return array|bool
3129 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3130 $className = __CLASS__
;
3132 switch ($fieldName) {
3133 // This field is not part of this object but the api supports it
3135 $className = 'CRM_Activity_BAO_Activity';
3138 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3144 public function addSelectWhereClause() {
3145 // We always return an array with these keys, even if they are empty,
3146 // because this tells the query builder that we have considered these fields for acls
3149 // Only case admins can view deleted cases
3150 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
array() : array("= 0"),
3152 // Ensure the user has permission to view the case client
3153 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3154 if ($contactClause) {
3155 $contactClause = implode(' AND contact_id ', $contactClause);
3156 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3158 // The api gatekeeper ensures the user has at least "access my cases and activities"
3159 // so if they do not have permission to see all cases we'll assume they can only access their own
3160 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3161 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3162 $clauses['id'][] = "IN (
3163 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 (
3164 (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)
3168 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3173 * CRM-20308: Method to get the contact id to use as from contact for email copy
3174 * 1. Activity Added by Contact's email address
3175 * 2. System Default From Address
3176 * 3. Default Organization Contact email address
3179 * @param int $activityID
3181 * @return mixed $emailFromContactId
3182 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3184 public static function getReceiptFrom($activityID) {
3185 $name = $address = NULL;
3187 if (!empty($activityID)) {
3188 // There is always a 'Added by' contact for a activity,
3189 // so we can safely use ActivityContact.Getvalue API
3190 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', array(
3191 'activity_id' => $activityID,
3192 'record_type_id' => 'Activity Source',
3193 'return' => 'contact_id',
3195 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3198 // If 'From' email address not found for Source Activity Contact then
3199 // fetch the email from domain or logged in user.
3200 if (empty($address)) {
3201 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3204 return "$name <$address>";