3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
35 * This class contains the functions for Case Management.
37 class CRM_Case_BAO_Case
extends CRM_Case_DAO_Case
{
40 * Static field for all the case information that we can potentially export.
44 static $_exportableFields = NULL;
49 public function __construct() {
50 parent
::__construct();
54 * Is CiviCase enabled?
58 public static function enabled() {
59 $config = CRM_Core_Config
::singleton();
60 return in_array('CiviCase', $config->enableComponents
);
64 * Create a case object.
66 * The function extracts all the params it needs to initialize the create a
67 * case object. the params array could contain additional unused name/value
70 * @param array $params
71 * (reference ) an assoc array of name/value pairs.
73 * @return CRM_Case_BAO_Case
75 public static function add(&$params) {
76 $caseDAO = new CRM_Case_DAO_Case();
77 $caseDAO->copyValues($params);
78 $result = $caseDAO->save();
79 $caseDAO->find(TRUE); // Get other case values (required by XML processor), this adds to $result array
84 * Takes an associative array and creates a case object.
86 * @param array $params
87 * (reference) an assoc array of name/value pairs.
89 * @return CRM_Case_BAO_Case
91 public static function &create(&$params) {
92 // CRM-20958 - These fields are managed by MySQL triggers. Watch out for clients resaving stale timestamps.
93 unset($params['created_date']);
94 unset($params['modified_date']);
96 $transaction = new CRM_Core_Transaction();
98 if (!empty($params['id'])) {
99 CRM_Utils_Hook
::pre('edit', 'Case', $params['id'], $params);
102 CRM_Utils_Hook
::pre('create', 'Case', NULL, $params);
105 $case = self
::add($params);
107 if (!empty($params['custom']) &&
108 is_array($params['custom'])
110 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_case', $case->id
);
113 if (is_a($case, 'CRM_Core_Error')) {
114 $transaction->rollback();
118 if (!empty($params['id'])) {
119 CRM_Utils_Hook
::post('edit', 'Case', $case->id
, $case);
122 CRM_Utils_Hook
::post('create', 'Case', $case->id
, $case);
124 $transaction->commit();
126 //we are not creating log for case
127 //since case log can be tracked using log for activity.
132 * Process case activity add/delete
133 * takes an associative array and
135 * @param array $params
136 * (reference ) an assoc array of name/value pairs.
139 public static function processCaseActivity(&$params) {
140 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
141 $caseActivityDAO->activity_id
= $params['activity_id'];
142 $caseActivityDAO->case_id
= $params['case_id'];
144 $caseActivityDAO->find(TRUE);
145 $caseActivityDAO->save();
149 * Get the case subject for Activity.
151 * @param int $activityId
154 * @return string|null
156 public static function getCaseSubject($activityId) {
157 $caseActivity = new CRM_Case_DAO_CaseActivity();
158 $caseActivity->activity_id
= $activityId;
159 if ($caseActivity->find(TRUE)) {
160 return CRM_Core_DAO
::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id
, 'subject');
169 * @param string $colName
174 public static function getCaseType($caseId, $colName = 'title') {
176 SELECT civicrm_case_type.{$colName} FROM civicrm_case
177 LEFT JOIN civicrm_case_type ON
178 civicrm_case.case_type_id = civicrm_case_type.id
179 WHERE civicrm_case.id = %1";
181 $queryParams = array(1 => array($caseId, 'Integer'));
183 return CRM_Core_DAO
::singleValueQuery($query, $queryParams);
187 * Delete the record that are associated with this case.
188 * record are deleted from case
191 * Id of the case to delete.
193 * @param bool $moveToTrash
198 public static function deleteCase($caseId, $moveToTrash = FALSE) {
199 CRM_Utils_Hook
::pre('delete', 'Case', $caseId, CRM_Core_DAO
::$_nullArray);
202 $activities = self
::getCaseActivityDates($caseId);
204 foreach ($activities as $value) {
205 CRM_Activity_BAO_Activity
::deleteActivity($value, $moveToTrash);
210 $transaction = new CRM_Core_Transaction();
212 $case = new CRM_Case_DAO_Case();
215 $result = $case->delete();
216 $transaction->commit();
219 $result = $case->is_deleted
= 1;
224 // CRM-7364, disable relationships
225 self
::enableDisableCaseRelationships($caseId, FALSE);
227 CRM_Utils_Hook
::post('delete', 'Case', $caseId, $case);
229 // remove case from recent items.
234 CRM_Utils_Recent
::del($caseRecent);
242 * Enable disable case related relationships.
246 * @param bool $enable
249 public static function enableDisableCaseRelationships($caseId, $enable) {
250 $contactIds = self
::retrieveContactIdsByCaseId($caseId);
251 if (!empty($contactIds)) {
252 foreach ($contactIds as $cid) {
253 $roles = self
::getCaseRoles($cid, $caseId);
254 if (!empty($roles)) {
255 $relationshipIds = implode(',', array_keys($roles));
256 $enable = (int) $enable;
257 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
258 WHERE id IN ( {$relationshipIds} )";
259 CRM_Core_DAO
::executeQuery($query);
266 * Retrieve contact_id by case_id.
271 * @param int $contactID
275 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL) {
276 $caseContact = new CRM_Case_DAO_CaseContact();
277 $caseContact->case_id
= $caseId;
278 $caseContact->find();
279 $contactArray = array();
280 // FIXME: Why does this return a 1-based array?
282 while ($caseContact->fetch()) {
283 if ($contactID != $caseContact->contact_id
) {
284 $contactArray[$count] = $caseContact->contact_id
;
289 return $contactArray;
293 * Look up a case using an activity ID.
295 * @param int $activityId
297 * @return int, case ID
299 public static function getCaseIdByActivityId($activityId) {
300 $originalId = CRM_Core_DAO
::singleValueQuery(
301 'SELECT original_id FROM civicrm_activity WHERE id = %1',
302 array('1' => array($activityId, 'Integer'))
304 $caseId = CRM_Core_DAO
::singleValueQuery(
305 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
307 '1' => array($activityId, 'Integer'),
308 '2' => array($originalId ?
$originalId : $activityId, 'Integer'),
315 * Retrieve contact names by caseId.
322 public static function getContactNames($caseId) {
323 $contactNames = array();
325 return $contactNames;
329 SELECT contact_a.sort_name name,
330 contact_a.display_name as display_name,
332 contact_a.birth_date as birth_date,
335 FROM civicrm_contact contact_a
336 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
337 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
338 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
339 WHERE contact_a.is_deleted = 0 AND civicrm_case_contact.case_id = %1
340 ORDER BY civicrm_case_contact.id";
342 $dao = CRM_Core_DAO
::executeQuery($query,
343 array(1 => array($caseId, 'Integer'))
345 while ($dao->fetch()) {
346 $contactNames[$dao->cid
]['contact_id'] = $dao->cid
;
347 $contactNames[$dao->cid
]['sort_name'] = $dao->name
;
348 $contactNames[$dao->cid
]['display_name'] = $dao->display_name
;
349 $contactNames[$dao->cid
]['email'] = $dao->email
;
350 $contactNames[$dao->cid
]['phone'] = $dao->phone
;
351 $contactNames[$dao->cid
]['birth_date'] = $dao->birth_date
;
352 $contactNames[$dao->cid
]['role'] = ts('Client');
355 return $contactNames;
359 * Retrieve case_id by contact_id.
361 * @param int $contactID
362 * @param bool $includeDeleted
363 * Include the deleted cases in result.
364 * @param null $caseType
368 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
371 FROM civicrm_case_contact cc
372 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
374 if (isset($caseType)) {
376 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
377 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
379 if (!isset($caseType)) {
380 $query .= "WHERE cc.contact_id = %1";
382 if (!$includeDeleted) {
383 $query .= " AND ca.is_deleted = 0";
386 $params = array(1 => array($contactID, 'Integer'));
387 $dao = CRM_Core_DAO
::executeQuery($query, $params);
389 $caseArray = array();
390 while ($dao->fetch()) {
391 $caseArray[] = $dao->id
;
399 * @param string $type
401 * @param string $condition
405 public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL) {
407 $session = CRM_Core_Session
::singleton();
408 $userID = $session->get('userID');
412 civicrm_case.id as case_id,
413 civicrm_case.subject as case_subject,
414 civicrm_contact.id as contact_id,
415 civicrm_contact.sort_name as sort_name,
416 civicrm_phone.phone as phone,
417 civicrm_contact.contact_type as contact_type,
418 civicrm_contact.contact_sub_type as contact_sub_type,
419 t_act.activity_type_id,
420 c_type.title as case_type,
421 civicrm_case.case_type_id as case_type_id,
422 cov_status.label as case_status,
423 cov_status.label as case_status_name,
425 civicrm_case.start_date as case_start_date,
426 case_relation_type.label_b_a as case_role, ";
428 if ($type == 'upcoming') {
430 t_act.desired_date as case_scheduled_activity_date,
431 t_act.id as case_scheduled_activity_id,
432 t_act.act_type_name as case_scheduled_activity_type_name,
433 t_act.act_type AS case_scheduled_activity_type ";
435 elseif ($type == 'recent') {
437 t_act.desired_date as case_recent_activity_date,
438 t_act.id as case_recent_activity_id,
439 t_act.act_type_name as case_recent_activity_type_name,
440 t_act.act_type AS case_recent_activity_type ";
442 elseif ($type == 'any') {
444 t_act.desired_date as case_activity_date,
445 t_act.id as case_activity_id,
446 t_act.act_type_name as case_activity_type_name,
447 t_act.act_type AS case_activity_type ";
450 $query .= " FROM civicrm_case
451 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
452 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
454 if ($type == 'upcoming') {
455 // This gets the earliest activity per case that's scheduled within 14 days from now.
456 // 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.
457 // In this case we don't really care which one, so min(id) works.
458 // optimized in CRM-11837
459 $query .= " INNER JOIN
461 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
466 FROM civicrm_view_case_activity_upcoming
467 ORDER BY activity_date_time ASC, id ASC
470 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
471 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
475 elseif ($type == 'recent') {
476 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
477 //improve query performance - CRM-10598
478 $query .= " INNER JOIN
480 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
485 FROM civicrm_view_case_activity_recent
486 ORDER BY activity_date_time DESC, id ASC
489 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
490 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
493 elseif ($type == 'any') {
494 $query .= " LEFT JOIN
496 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
497 FROM civicrm_activity act4
498 LEFT JOIN civicrm_case_activity ca4
499 ON ca4.activity_id = act4.id
500 AND act4.is_current_revision = 1
501 LEFT JOIN civicrm_option_group aog
502 ON aog.name='activity_type'
503 LEFT JOIN civicrm_option_value aov
504 ON aov.option_group_id = aog.id
505 AND aov.value = act4.activity_type_id
510 ON t_act.case_id = civicrm_case.id
511 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
512 LEFT JOIN civicrm_relationship case_relationship
513 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
514 AND case_relationship.case_id = civicrm_case.id )
516 LEFT JOIN civicrm_relationship_type case_relation_type
517 ON ( case_relation_type.id = case_relationship.relationship_type_id
518 AND case_relation_type.id = case_relationship.relationship_type_id )
520 LEFT JOIN civicrm_case_type c_type
521 ON civicrm_case.case_type_id = c_type.id
523 LEFT JOIN civicrm_option_group cog_status
524 ON cog_status.name = 'case_status'
526 LEFT JOIN civicrm_option_value cov_status
527 ON ( civicrm_case.status_id = cov_status.value
528 AND cog_status.id = cov_status.option_group_id )
532 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
533 $query .= " WHERE (1) $condition ";
536 if ($type == 'upcoming') {
537 $query .= " ORDER BY case_scheduled_activity_date ASC ";
539 elseif ($type == 'recent') {
540 $query .= " ORDER BY case_recent_activity_date ASC ";
542 elseif ($type == 'any') {
543 $query .= " ORDER BY case_activity_date ASC ";
550 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
552 * @param bool $allCases
556 * @param string $type
557 * /upcoming,recent,all/.
559 * @param string $context
564 public static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') {
566 $casesList = array();
568 //validate access for own cases.
569 if (!self
::accessCiviCase()) {
574 $session = CRM_Core_Session
::singleton();
575 $userID = $session->get('userID');
578 //validate access for all cases.
579 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
583 $condition = " AND civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1";
586 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
588 if ($type == 'upcoming' ||
$type == 'any') {
589 $closedId = CRM_Core_PseudoConstant
::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
591 AND civicrm_case.status_id != $closedId";
594 $query = self
::getCaseActivityQuery($type, $userID, $condition);
596 $queryParams = array();
597 $result = CRM_Core_DAO
::executeQuery($query,
601 $caseStatus = CRM_Core_OptionGroup
::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
603 $resultFields = array(
620 if ($type == 'upcoming') {
621 $resultFields[] = 'case_scheduled_activity_date';
622 $resultFields[] = 'case_scheduled_activity_type_name';
623 $resultFields[] = 'case_scheduled_activity_type';
624 $resultFields[] = 'case_scheduled_activity_id';
626 elseif ($type == 'recent') {
627 $resultFields[] = 'case_recent_activity_date';
628 $resultFields[] = 'case_recent_activity_type_name';
629 $resultFields[] = 'case_recent_activity_type';
630 $resultFields[] = 'case_recent_activity_id';
632 elseif ($type == 'any') {
633 $resultFields[] = 'case_activity_date';
634 $resultFields[] = 'case_activity_type_name';
635 $resultFields[] = 'case_activity_type';
636 $resultFields[] = 'case_activity_id';
639 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
640 $actions = CRM_Case_Selector_Search
::links();
642 // check is the user has view/edit signer permission
643 $permissions = array(CRM_Core_Permission
::VIEW
);
644 if (CRM_Core_Permission
::check('access all cases and activities') ||
645 (!$allCases && CRM_Core_Permission
::check('access my cases and activities'))
647 $permissions[] = CRM_Core_Permission
::EDIT
;
649 if (CRM_Core_Permission
::check('delete in CiviCase')) {
650 $permissions[] = CRM_Core_Permission
::DELETE
;
652 $mask = CRM_Core_Action
::mask($permissions);
654 while ($result->fetch()) {
655 foreach ($resultFields as $donCare => $field) {
656 $casesList[$result->case_id
][$field] = $result->$field;
657 if ($field == 'contact_type') {
658 $casesList[$result->case_id
]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils
::getImage($result->contact_sub_type ?
$result->contact_sub_type
: $result->contact_type
660 $casesList[$result->case_id
]['action'] = CRM_Core_Action
::formLink($actions['primaryActions'], $mask,
662 'id' => $result->case_id
,
663 'cid' => $result->contact_id
,
668 'case.actions.primary',
673 elseif ($field == 'case_status') {
674 if (in_array($result->$field, $caseStatus)) {
675 $casesList[$result->case_id
]['class'] = "status-urgent";
678 $casesList[$result->case_id
]['class'] = "status-normal";
683 $caseTypes = CRM_Case_PseudoConstant
::caseType('name');
684 $caseManagerContact = self
::getCaseManagerContact($caseTypes[$result->case_type_id
], $result->case_id
);
685 if (!empty($caseManagerContact)) {
686 $casesList[$result->case_id
]['casemanager_id'] = CRM_Utils_Array
::value('casemanager_id', $caseManagerContact);
687 $casesList[$result->case_id
]['casemanager'] = CRM_Utils_Array
::value('casemanager', $caseManagerContact);
690 //do check user permissions for edit/view activity.
691 if (($actId = CRM_Utils_Array
::value('case_scheduled_activity_id', $casesList[$result->case_id
])) ||
692 ($actId = CRM_Utils_Array
::value('case_recent_activity_id', $casesList[$result->case_id
]))
694 $casesList[$result->case_id
]["case_{$type}_activity_editable"] = self
::checkPermission($actId,
696 $casesList[$result->case_id
]['activity_type_id'], $userID
698 $casesList[$result->case_id
]["case_{$type}_activity_viewable"] = self
::checkPermission($actId,
700 $casesList[$result->case_id
]['activity_type_id'], $userID
709 * Get the summary of cases counts by type and status.
711 * @param bool $allCases
715 public static function getCasesSummary($allCases = TRUE, $userID) {
716 $caseSummary = array();
718 //validate access for civicase.
719 if (!self
::accessCiviCase()) {
723 //validate access for all cases.
724 if ($allCases && !CRM_Core_Permission
::check('access all cases and activities')) {
728 $caseTypes = CRM_Case_PseudoConstant
::caseType();
729 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
730 $caseTypes = array_flip($caseTypes);
732 // get statuses as headers for the table
733 $url = CRM_Utils_System
::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
734 foreach ($caseStatuses as $key => $name) {
735 $caseSummary['headers'][$key]['status'] = $name;
736 $caseSummary['headers'][$key]['url'] = $url . $key;
739 // build rows with actual data
741 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
747 $myGroupByClause = ' GROUP BY civicrm_case.id';
752 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
753 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
755 $myGroupByClause .= ", case_status.label, status_id, case_type_id";
757 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
759 SELECT case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
760 case_type_id, case_relationship.contact_id_b
762 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
763 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
764 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
765 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
766 AND option_group_case_status.id = case_status.option_group_id )
767 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
768 AND case_relationship.contact_id_b = {$userID})
769 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
770 {$myCaseWhereClause} {$myGroupByClause}";
772 $res = CRM_Core_DAO
::executeQuery($query);
773 while ($res->fetch()) {
774 if (!empty($rows[$res->case_type
]) && !empty($rows[$res->case_type
][$res->case_status
])) {
775 $rows[$res->case_type
][$res->case_status
]['count'] = $rows[$res->case_type
][$res->case_status
]['count'] +
1;
778 $rows[$res->case_type
][$res->case_status
] = array(
780 'url' => CRM_Utils_System
::url('civicrm/case/search',
781 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
786 $caseSummary['rows'] = array_merge($caseTypes, $rows);
794 * @param int $contactID
798 * @param int $relationshipID
801 * case role / relationships
804 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
806 SELECT rel.id as civicrm_relationship_id,
807 con.sort_name as sort_name,
808 civicrm_email.email as email,
809 civicrm_phone.phone as phone,
810 con.id as civicrm_contact_id,
811 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
812 civicrm_relationship_type.id as relation_type,
813 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
814 FROM civicrm_relationship rel
815 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
816 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))
817 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
818 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
819 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
820 AND rel.is_active = 1 AND con.is_deleted = 0 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
823 1 => array($contactID, 'Positive'),
824 2 => array($caseID, 'Positive'),
827 if ($relationshipID) {
828 $query .= ' AND civicrm_relationship.id = %3 ';
829 $params[3] = array($relationshipID, 'Integer');
831 $dao = CRM_Core_DAO
::executeQuery($query, $params);
834 while ($dao->fetch()) {
835 $rid = $dao->civicrm_relationship_id
;
836 $values[$rid]['cid'] = $dao->civicrm_contact_id
;
837 $values[$rid]['relation'] = $dao->relation
;
838 $values[$rid]['name'] = $dao->sort_name
;
839 $values[$rid]['email'] = $dao->email
;
840 $values[$rid]['phone'] = $dao->phone
;
841 $values[$rid]['relation_type'] = $dao->relation_type
;
842 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id
;
843 $values[$rid]['client_id'] = $contactID;
844 $values[$rid]['relationship_direction'] = $dao->relationship_direction
;
852 * Get Case Activities.
856 * @param array $params
858 * @param int $contactID
861 * @param null $context
866 * Array of case activities
869 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
872 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
873 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
874 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
875 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
877 // CRM-5081 - formatting the dates to omit seconds.
878 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
880 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
882 ca.activity_type_id AS type,
883 ca.activity_type_id AS activity_type_id,
884 tcc.sort_name AS target_contact_name,
885 tcc.id AS target_contact_id,
886 scc.sort_name AS source_contact_name,
887 scc.id AS source_contact_id,
888 acc.sort_name AS assignee_contact_name,
889 acc.id AS assignee_contact_id,
891 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
892 ca.activity_date_time,
893 DATE_ADD(NOW(), INTERVAL 1 YEAR)
894 ), '%Y%m%d%H%i00') AS overdue_date,
895 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
896 ca.status_id AS status,
897 ca.subject AS subject,
898 ca.is_deleted AS deleted,
899 ca.priority_id AS priority,
901 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
904 FROM civicrm_case_activity cca
905 INNER JOIN civicrm_activity ca
906 ON ca.id = cca.activity_id
907 INNER JOIN civicrm_activity_contact cas
908 ON cas.activity_id = ca.id
909 AND cas.record_type_id = {$sourceID}
910 INNER JOIN civicrm_contact scc
911 ON scc.id = cas.contact_id
912 LEFT JOIN civicrm_activity_contact caa
913 ON caa.activity_id = ca.id
914 AND caa.record_type_id = {$assigneeID}
915 LEFT JOIN civicrm_contact acc
916 ON acc.id = caa.contact_id
917 LEFT JOIN civicrm_activity_contact cat
918 ON cat.activity_id = ca.id
919 AND cat.record_type_id = {$targetID}
920 LEFT JOIN civicrm_contact tcc
921 ON tcc.id = cat.contact_id
922 INNER JOIN civicrm_option_group cog
923 ON cog.name = 'activity_type'
924 INNER JOIN civicrm_option_value cov
925 ON cov.option_group_id = cog.id
926 AND cov.value = ca.activity_type_id
927 AND cov.is_active = 1
928 LEFT JOIN civicrm_entity_file ef
929 ON ef.entity_table = 'civicrm_activity'
930 AND ef.entity_id = ca.id
931 LEFT OUTER JOIN civicrm_option_group og
932 ON og.name = 'activity_status'
933 LEFT OUTER JOIN civicrm_option_value ov
934 ON ov.option_group_id=og.id
935 AND ov.name = 'Scheduled'";
938 WHERE cca.case_id= %1
939 AND ca.is_current_revision = 1';
941 if (!empty($params['source_contact_id'])) {
943 AND cas.contact_id = " . CRM_Utils_Type
::escape($params['source_contact_id'], 'Integer');
946 if (!empty($params['status_id'])) {
948 AND ca.status_id = " . CRM_Utils_Type
::escape($params['status_id'], 'Integer');
951 if (!empty($params['activity_deleted'])) {
953 AND ca.is_deleted = 1";
957 AND ca.is_deleted = 0";
960 if (!empty($params['activity_type_id'])) {
962 AND ca.activity_type_id = " . CRM_Utils_Type
::escape($params['activity_type_id'], 'Integer');
965 if (!empty($params['activity_date_low'])) {
966 $fromActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_low']), 'Date');
968 if (!empty($fromActivityDate)) {
970 AND ca.activity_date_time >= '{$fromActivityDate}'";
973 if (!empty($params['activity_date_high'])) {
974 $toActivityDate = CRM_Utils_Type
::escape(CRM_Utils_Date
::processDate($params['activity_date_high']), 'Date');
975 $toActivityDate = $toActivityDate ?
$toActivityDate +
235959 : NULL;
977 if (!empty($toActivityDate)) {
979 AND ca.activity_date_time <= '{$toActivityDate}'";
983 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
985 $sortBy = CRM_Utils_Array
::value('sortBy', $params);
987 // CRM-5081 - added id to act like creation date
989 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
992 $sortBy = CRM_Utils_Type
::escape($sortBy, 'String');
993 $orderBy = " ORDER BY $sortBy ";
996 $page = CRM_Utils_Array
::value('page', $params);
997 $rp = CRM_Utils_Array
::value('rp', $params);
1005 $start = (($page - 1) * $rp);
1006 $limit = " LIMIT $start, $rp";
1008 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
1009 $queryParams = array(1 => array($caseID, 'Integer'));
1011 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
1012 $caseCount = CRM_Core_DAO
::singleValueQuery('SELECT FOUND_ROWS()');
1014 $activityTypes = CRM_Case_PseudoConstant
::caseActivityType(FALSE, TRUE);
1015 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus();
1017 $url = CRM_Utils_System
::url("civicrm/case/activity",
1018 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1022 if ($context == 'fulltext') {
1023 $contextUrl = "&context={$context}";
1025 $editUrl = "{$url}&action=update{$contextUrl}";
1026 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1027 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1028 $viewTitle = ts('View activity');
1030 $emailActivityTypeIDs = array(
1031 'Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1035 'Inbound Email' => CRM_Core_OptionGroup
::getValue('activity_type',
1041 $caseDeleted = CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1043 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1044 $compStatusValues = array();
1045 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1046 foreach ($compStatusNames as $name) {
1047 $compStatusValues[] = CRM_Core_OptionGroup
::getValue('activity_status', $name, 'name');
1050 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=", FALSE, NULL, FALSE);
1051 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
1052 $clientIds = self
::retrieveContactIdsByCaseId($caseID);
1055 $session = CRM_Core_Session
::singleton();
1056 $userID = $session->get('userID');
1059 $caseActivities = array();
1061 while ($dao->fetch()) {
1062 $caseActivity = array();
1063 $caseActivityId = $dao->id
;
1065 $allowView = self
::checkPermission($caseActivityId, 'view', $dao->activity_type_id
, $userID);
1066 $allowEdit = self
::checkPermission($caseActivityId, 'edit', $dao->activity_type_id
, $userID);
1067 $allowDelete = self
::checkPermission($caseActivityId, 'delete', $dao->activity_type_id
, $userID);
1069 //do not have sufficient permission
1070 //to access given case activity record.
1071 if (!$allowView && !$allowEdit && !$allowDelete) {
1075 $caseActivity['DT_RowId'] = $caseActivityId;
1076 //Add classes to the row, via DataTables syntax
1077 $caseActivity['DT_RowClass'] = "crm-entity status-id-$dao->status";
1079 if (CRM_Utils_Array
::crmInArray($dao->status
, $compStatusValues)) {
1080 $caseActivity['DT_RowClass'] .= " status-completed";
1083 if (CRM_Utils_Date
::overdue($dao->display_date
)) {
1084 $caseActivity['DT_RowClass'] .= " status-overdue";
1087 $caseActivity['DT_RowClass'] .= " status-scheduled";
1091 if (!empty($dao->priority
)) {
1092 if ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Urgent', 'name')) {
1093 $caseActivity['DT_RowClass'] .= " priority-urgent ";
1095 elseif ($dao->priority
== CRM_Core_OptionGroup
::getValue('priority', 'Low', 'name')) {
1096 $caseActivity['DT_RowClass'] .= " priority-low ";
1100 //Add data to the row for inline editing, via DataTable syntax
1101 $caseActivity['DT_RowAttr'] = array();
1102 $caseActivity['DT_RowAttr']['data-entity'] = 'activity';
1103 $caseActivity['DT_RowAttr']['data-id'] = $caseActivityId;
1105 //Activity Date and Time
1106 $caseActivity['activity_date_time'] = CRM_Utils_Date
::customFormat($dao->display_date
);
1109 $caseActivity['subject'] = $dao->subject
;
1112 $caseActivity['type'] = (!empty($activityTypes[$dao->type
]['icon']) ?
'<span class="crm-i ' . $activityTypes[$dao->type
]['icon'] . '"></span> ' : '')
1113 . $activityTypes[$dao->type
]['label'];
1115 //Activity Target (With)
1116 $targetContact = '';
1117 if (isset($dao->target_contact_id
)) {
1118 $targetContact = $dao->target_contact_name
;
1119 if ($hasViewContact) {
1120 $targetContact = '<a href="' . $contactViewUrl . $dao->target_contact_id
. '">' . $dao->target_contact_name
. '</a>';
1123 $caseActivity['target_contact_name'] = $targetContact;
1125 //Activity Source Contact (Reporter)
1126 $sourceContact = $dao->source_contact_name
;
1127 if ($hasViewContact) {
1128 $sourceContact = '<a href="' . $contactViewUrl . $dao->source_contact_id
. '">' . $dao->source_contact_name
. '</a>';
1130 $caseActivity['source_contact_name'] = $sourceContact;
1132 //Activity Assignee. CRM-4485.
1133 $assigneeContact = '';
1134 if (isset($dao->assignee_contact_id
)) {
1135 $assigneeContact = $dao->assignee_contact_name
;
1136 if ($hasViewContact) {
1137 $assigneeContact = '<a href="' . $contactViewUrl . $dao->assignee_contact_id
. '">' . $dao->assignee_contact_name
. '</a>';
1140 $caseActivity['assignee_contact_name'] = $assigneeContact;
1143 $caseActivity['status_id'] = $activityStatuses[$dao->status
];
1145 // 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.
1147 $css = 'class="action-item crm-hover-button"';
1149 $viewUrl = CRM_Utils_System
::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1150 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1152 $additionalUrl = "&id={$caseActivityId}";
1153 if (!$dao->deleted
) {
1154 //hide edit link of activity type email.CRM-4530.
1155 if (!in_array($dao->type
, $emailActivityTypeIDs)) {
1156 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1158 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1162 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1165 elseif (!$caseDeleted) {
1166 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1167 $caseActivity['status_id'] = $caseActivity['status_id'] . '<br /> (deleted)';
1170 //check for operations.
1171 if (self
::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id
)) {
1172 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1174 if (self
::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id
)) {
1175 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1177 // if there are file attachments we will return how many and, if only one, add a link to it
1178 if (!empty($dao->attachment_ids
)) {
1179 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids
));
1180 $caseActivity['no_attachments'] = count($attachmentIDs);
1181 $url .= implode(' ', CRM_Core_BAO_File
::paperIconAttachment('civicrm_activity', $caseActivityId));
1184 $caseActivity['links'] = $url;
1186 array_push($caseActivities, $caseActivity);
1190 $caseActivitiesDT = array();
1191 $caseActivitiesDT['data'] = $caseActivities;
1192 $caseActivitiesDT['recordsTotal'] = $caseCount;
1193 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1195 return $caseActivitiesDT;
1199 * Get Case Related Contacts.
1201 * @param int $caseID
1203 * @param bool $includeDetails
1204 * If true include details of contacts.
1207 * array of return properties
1210 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1211 $caseRoles = array();
1212 if ($includeDetails) {
1213 $caseInfo = civicrm_api3('Case', 'getsingle', array(
1215 // 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
1216 'return' => array('case_type_id', 'case_type_id.name', 'case_type_id.definition'),
1218 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1219 $caseRoles = CRM_Utils_Array
::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1224 SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, cr.relationship_type_id, crt.label_b_a as role, crt.name_b_a, ce.email, cp.phone
1225 FROM civicrm_relationship cr
1226 LEFT JOIN civicrm_relationship_type crt
1227 ON crt.id = cr.relationship_type_id
1228 LEFT JOIN civicrm_contact cc
1229 ON cc.id = cr.contact_id_b
1230 LEFT JOIN civicrm_email ce
1231 ON ce.contact_id = cc.id
1232 AND ce.is_primary= 1
1233 LEFT JOIN civicrm_phone cp
1234 ON cp.contact_id = cc.id
1235 AND cp.is_primary= 1
1236 WHERE cr.case_id = %1 AND cr.is_active AND cc.is_deleted <> 1';
1238 $params = array(1 => array($caseID, 'Integer'));
1239 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1241 while ($dao->fetch()) {
1242 if (!$includeDetails) {
1243 $values[$dao->id
] = 1;
1247 'contact_id' => $dao->id
,
1248 'display_name' => $dao->name
,
1249 'sort_name' => $dao->sort_name
,
1250 'relationship_type_id' => $dao->relationship_type_id
,
1251 'role' => $dao->role
,
1252 'email' => $dao->email
,
1253 'phone' => $dao->phone
,
1255 // Add more info about the role (creator, manager)
1256 $role = CRM_Utils_Array
::value($dao->name_b_a
, $caseRoles);
1258 unset($role['name']);
1261 $values[] = $details;
1270 * Send e-mail copy of activity
1272 * @param int $clientId
1273 * @param int $activityId
1275 * @param array $contacts
1276 * Array of related contact.
1278 * @param null $attachments
1279 * @param int $caseId
1281 * @return bool |array
1283 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1288 $tplParams = $activityInfo = array();
1289 //if its a case activity
1291 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1292 $nonCaseActivityTypes = CRM_Core_PseudoConstant
::activityType();
1293 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1294 $anyActivity = TRUE;
1297 $anyActivity = FALSE;
1299 $tplParams['isCaseActivity'] = 1;
1300 $tplParams['client_id'] = $clientId;
1303 $anyActivity = TRUE;
1306 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1307 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1309 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1311 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1313 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1315 $tplParams['activity'] = $activityInfo;
1316 foreach ($tplParams['activity']['fields'] as $k => $val) {
1317 if (CRM_Utils_Array
::value('label', $val) == ts('Subject')) {
1318 $activitySubject = $val['value'];
1322 $session = CRM_Core_Session
::singleton();
1323 // CRM-8926 If user is not logged in, use the activity creator as userID
1324 if (!($userID = $session->get('userID'))) {
1325 $userID = CRM_Activity_BAO_Activity
::getSourceContactID($activityId);
1328 //also create activities simultaneously of this copy.
1329 $activityParams = array();
1331 $activityParams['source_record_id'] = $activityId;
1332 $activityParams['source_contact_id'] = $userID;
1333 $activityParams['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Email', 'name');
1334 $activityParams['activity_date_time'] = date('YmdHis');
1335 $activityParams['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name');
1336 $activityParams['medium_id'] = CRM_Core_OptionGroup
::getValue('encounter_medium', 'email', 'name');
1337 $activityParams['case_id'] = $caseId;
1338 $activityParams['is_auto'] = 0;
1339 $activityParams['target_id'] = $clientId;
1341 $tplParams['activitySubject'] = $activitySubject;
1343 // if it’s a case activity, add hashed id to the template (CRM-5916)
1345 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY
. $caseId), 0, 7);
1349 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1350 $receiptFrom = self
::getReceiptFrom($activityId);
1352 $recordedActivityParams = array();
1354 foreach ($contacts as $mail => $info) {
1355 $tplParams['contact'] = $info;
1356 self
::buildPermissionLinks($tplParams, $activityParams);
1358 $displayName = CRM_Utils_Array
::value('display_name', $info);
1360 list($result[CRM_Utils_Array
::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1362 'groupName' => 'msg_tpl_workflow_case',
1363 'valueName' => 'case_activity',
1364 'contactId' => CRM_Utils_Array
::value('contact_id', $info),
1365 'tplParams' => $tplParams,
1366 'from' => $receiptFrom,
1367 'toName' => $displayName,
1369 'attachments' => $attachments,
1373 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1374 $activityParams['details'] = $message;
1376 if (!empty($result[$info['contact_id']])) {
1378 * Really only need to record one activity with all the targets combined.
1379 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1380 * but it's always the same content at the moment.
1382 if (empty($recordedActivityParams)) {
1383 $recordedActivityParams = $activityParams;
1386 $recordedActivityParams['subject'] .= "; $displayName";
1388 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1391 unset($result[CRM_Utils_Array
::value('contact_id', $info)]);
1395 if (!empty($recordedActivityParams)) {
1396 $activity = CRM_Activity_BAO_Activity
::create($recordedActivityParams);
1398 //create case_activity record if its case activity.
1400 $caseParams = array(
1401 'activity_id' => $activity->id
,
1402 'case_id' => $caseId,
1404 self
::processCaseActivity($caseParams);
1412 * Retrieve count of activities having a particular type, and
1413 * associated with a particular case.
1415 * @param int $caseId
1417 * @param int $activityTypeId
1418 * ID of the activity type.
1422 public static function getCaseActivityCount($caseId, $activityTypeId) {
1423 $queryParam = array(
1424 1 => array($caseId, 'Integer'),
1425 2 => array($activityTypeId, 'Integer'),
1427 $query = "SELECT count(ca.id) as countact
1428 FROM civicrm_activity ca
1429 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1430 WHERE ca.activity_type_id = %2
1431 AND cca.case_id = %1
1432 AND ca.is_deleted = 0";
1434 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1435 if ($dao->fetch()) {
1436 return $dao->countact
;
1443 * Create an activity for a case via email.
1448 * @return array|void
1449 * $activity object of newly creted activity via email
1451 public static function recordActivityViaEmail($file) {
1452 if (!file_exists($file) ||
1455 return CRM_Core_Error
::fatal(ts('File %1 does not exist or is not readable',
1460 $result = CRM_Utils_Mail_Incoming
::parse($file);
1461 if ($result['is_error']) {
1465 foreach ($result['to'] as $to) {
1468 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1469 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1471 if ($replacement !== $to['email']) {
1472 $caseId = $replacement;
1473 //if caseId is invalid, return as error file
1474 if (!CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1475 return CRM_Core_Error
::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1484 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1485 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1486 $contactDetails = self
::getRelatedContacts($caseId, FALSE);
1488 if (!empty($contactDetails[$result['from']['id']])) {
1490 $params['subject'] = $result['subject'];
1491 $params['activity_date_time'] = $result['date'];
1492 $params['details'] = $result['body'];
1493 $params['source_contact_id'] = $result['from']['id'];
1494 $params['status_id'] = CRM_Core_OptionGroup
::getValue('activity_status',
1499 $details = CRM_Case_PseudoConstant
::caseActivityType();
1501 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1502 $result['body'], $matches
1505 if (!empty($matches) && isset($matches[1])) {
1506 $activityType = trim($matches[1]);
1507 if (isset($details[$activityType])) {
1508 $params['activity_type_id'] = $details[$activityType]['id'];
1511 if (!isset($params['activity_type_id'])) {
1512 $params['activity_type_id'] = CRM_Core_OptionGroup
::getValue('activity_type', 'Inbound Email', 'name');
1516 $activity = CRM_Activity_BAO_Activity
::create($params);
1518 $caseParams = array(
1519 'activity_id' => $activity->id
,
1520 'case_id' => $caseId,
1522 self
::processCaseActivity($caseParams);
1525 return CRM_Core_Error
::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1526 array(1 => $result['from']['email'])
1533 * Retrieve the scheduled activity type and date.
1535 * @param array $cases
1536 * Array of contact and case id.
1538 * @param string $type
1541 * Array of scheduled activity type and date
1545 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1546 $session = CRM_Core_Session
::singleton();
1547 $userID = $session->get('userID');
1549 $caseID = implode(',', $cases['case_id']);
1550 $contactID = implode(',', $cases['contact_id']);
1553 AND civicrm_case_contact.contact_id IN( {$contactID} )
1554 AND civicrm_case.id IN( {$caseID})
1555 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1557 $query = self
::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1559 $res = CRM_Core_DAO
::executeQuery($query);
1561 $activityInfo = array();
1562 while ($res->fetch()) {
1563 if ($type == 'upcoming') {
1564 $activityInfo[$res->case_id
]['date'] = $res->case_scheduled_activity_date
;
1565 $activityInfo[$res->case_id
]['type'] = $res->case_scheduled_activity_type
;
1568 $activityInfo[$res->case_id
]['date'] = $res->case_recent_activity_date
;
1569 $activityInfo[$res->case_id
]['type'] = $res->case_recent_activity_type
;
1573 return $activityInfo;
1577 * Combine all the exportable fields from the lower levels object.
1580 * array of exportable Fields
1582 public static function &exportableFields() {
1583 if (!self
::$_exportableFields) {
1584 if (!self
::$_exportableFields) {
1585 self
::$_exportableFields = array();
1588 $fields = CRM_Case_DAO_Case
::export();
1589 $fields['case_role'] = array('title' => ts('Role in Case'));
1590 $fields['case_type'] = array(
1591 'title' => ts('Case Type'),
1592 'name' => 'case_type',
1594 $fields['case_status'] = array(
1595 'title' => ts('Case Status'),
1596 'name' => 'case_status',
1599 // add custom data for cases
1600 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Case'));
1602 self
::$_exportableFields = $fields;
1604 return self
::$_exportableFields;
1608 * Restore the record that are associated with this case.
1610 * @param int $caseId
1611 * Id of the case to restore.
1615 public static function restoreCase($caseId) {
1616 //restore activities
1617 $activities = self
::getCaseActivityDates($caseId);
1619 foreach ($activities as $value) {
1620 CRM_Activity_BAO_Activity
::restoreActivity($value);
1624 $case = new CRM_Case_DAO_Case();
1625 $case->id
= $caseId;
1626 $case->is_deleted
= 0;
1629 //CRM-7364, enable relationships
1630 self
::enableDisableCaseRelationships($caseId, TRUE);
1637 * @param null $showLinks
1638 * @param bool $returnOnlyCount
1639 * @param int $offset
1640 * @param int $rowCount
1644 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1645 $globalContacts = array();
1647 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1648 $settings = $settingsProcessor->run();
1649 if (!empty($settings)) {
1650 $groupInfo['name'] = $settings['groupname'];
1651 if ($groupInfo['name']) {
1652 $searchParams = array('name' => $groupInfo['name']);
1654 CRM_Contact_BAO_Group
::retrieve($searchParams, $results);
1656 $groupInfo['id'] = $results['id'];
1657 $groupInfo['title'] = $results['title'];
1658 $params = array(array('group', '=', $groupInfo['id'], 0, 0));
1659 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1660 list($globalContacts) = CRM_Contact_BAO_Query
::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1662 if ($returnOnlyCount) {
1663 return $globalContacts;
1667 foreach ($globalContacts as $idx => $contact) {
1668 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System
::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1674 return $globalContacts;
1678 * Convenience function to get both case contacts and global in one array.
1679 * @param int $caseId
1683 public static function getRelatedAndGlobalContacts($caseId) {
1684 $relatedContacts = self
::getRelatedContacts($caseId);
1686 $groupInfo = array();
1687 $globalContacts = self
::getGlobalContacts($groupInfo);
1689 //unset values which are not required.
1690 foreach ($globalContacts as $k => & $v) {
1691 unset($v['email_id']);
1692 unset($v['group_contact_id']);
1693 unset($v['status']);
1695 $v['role'] = $groupInfo['title'];
1697 //include multiple listings for the same contact/different roles.
1698 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1699 return $relatedGlobalContacts;
1703 * Get Case ActivitiesDueDates with given criteria.
1705 * @param int $caseID
1707 * @param array $criteriaParams
1709 * @param bool $latestDate
1710 * If set newest or oldest date is selected.
1713 * case activities due dates
1716 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1718 $selectDate = " ca.activity_date_time";
1719 $where = $groupBy = ' ';
1726 if (!empty($criteriaParams['activity_type_id'])) {
1727 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type
::escape($criteriaParams['activity_type_id'], 'Integer');
1728 $where .= " AND ca.is_current_revision = 1";
1729 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1732 if (!empty($criteriaParams['newest'])) {
1733 $selectDate = " max(ca.activity_date_time) ";
1736 $selectDate = " min(ca.activity_date_time) ";
1740 $query = "SELECT ca.id, {$selectDate} as activity_date
1741 FROM civicrm_activity ca
1742 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1743 WHERE cc.id = %1 {$where} {$groupBy}";
1745 $params = array(1 => array($caseID, 'Integer'));
1746 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1748 while ($dao->fetch()) {
1749 $values[$dao->id
]['id'] = $dao->id
;
1750 $values[$dao->id
]['activity_date'] = $dao->activity_date
;
1757 * Create activities when Case or Other roles assigned/modified/deleted.
1759 * @param int $caseId
1760 * @param int $relationshipId
1762 * @param int $relContactId
1763 * Case role assignee contactId.
1764 * @param int $contactId
1766 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1767 if (!$caseId ||
!$relationshipId ||
empty($relationshipId)) {
1771 $queryParam = array();
1772 if (is_array($relationshipId)) {
1773 $relationshipId = implode(',', $relationshipId);
1774 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1777 $relationshipClause = " civicrm_relationship.id = %1";
1778 $queryParam[1] = array($relationshipId, 'Positive');
1782 SELECT cc.display_name as clientName,
1783 cca.display_name as assigneeContactName,
1784 civicrm_relationship.case_id as caseId,
1785 civicrm_relationship_type.label_a_b as relation_a_b,
1786 civicrm_relationship_type.label_b_a as relation_b_a,
1787 civicrm_relationship.contact_id_b as rel_contact_id,
1788 civicrm_relationship.contact_id_a as assign_contact_id
1789 FROM civicrm_relationship_type, civicrm_relationship
1790 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1791 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1792 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1794 $dao = CRM_Core_DAO
::executeQuery($query, $queryParam);
1796 while ($dao->fetch()) {
1797 // The assignee is not the client.
1798 if ($dao->rel_contact_id
!= $contactId) {
1799 $caseRelationship = $dao->relation_a_b
;
1800 $assigneContactName = $dao->clientName
;
1801 $assigneContactIds[$dao->rel_contact_id
] = $dao->rel_contact_id
;
1804 $caseRelationship = $dao->relation_b_a
;
1805 $assigneContactName = $dao->assigneeContactName
;
1806 $assigneContactIds[$dao->assign_contact_id
] = $dao->assign_contact_id
;
1810 $session = CRM_Core_Session
::singleton();
1811 $activityParams = array(
1812 'source_contact_id' => $session->get('userID'),
1813 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1814 'activity_date_time' => date('YmdHis'),
1815 'status_id' => CRM_Core_OptionGroup
::getValue('activity_status', 'Completed', 'name'),
1818 //if $relContactId is passed, role is added or modified.
1819 if (!empty($relContactId)) {
1820 $activityParams['assignee_contact_id'] = $assigneContactIds;
1822 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1828 $activityTypeID = CRM_Core_OptionGroup
::getValue('activity_type',
1834 $activityParams['activity_type_id'] = $activityTypeID;
1836 $activity = CRM_Activity_BAO_Activity
::create($activityParams);
1838 //create case_activity record.
1839 $caseParams = array(
1840 'activity_id' => $activity->id
,
1841 'case_id' => $caseId,
1844 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
1849 * contact which is assigned a case role of case manager.
1851 * @param int $caseType
1853 * @param int $caseId
1857 * array of contact on success otherwise empty
1860 public static function getCaseManagerContact($caseType, $caseId) {
1861 if (!$caseType ||
!$caseId) {
1865 $caseManagerContact = array();
1866 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1868 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1870 if (!empty($managerRoleId)) {
1871 $managerRoleQuery = "
1872 SELECT civicrm_contact.id as casemanager_id,
1873 civicrm_contact.sort_name as casemanager
1874 FROM civicrm_contact
1875 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1876 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1877 WHERE civicrm_case.id = %2 AND is_active = 1";
1879 $managerRoleParams = array(
1880 1 => array($managerRoleId, 'Integer'),
1881 2 => array($caseId, 'Integer'),
1884 $dao = CRM_Core_DAO
::executeQuery($managerRoleQuery, $managerRoleParams);
1885 if ($dao->fetch()) {
1886 $caseManagerContact['casemanager_id'] = $dao->casemanager_id
;
1887 $caseManagerContact['casemanager'] = $dao->casemanager
;
1891 return $caseManagerContact;
1895 * @param int $contactId
1896 * @param bool $excludeDeleted
1900 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1901 $params = array('check_permissions' => TRUE);
1902 if ($excludeDeleted) {
1903 $params['is_deleted'] = 0;
1906 $params['contact_id'] = $contactId;
1909 return civicrm_api3('Case', 'getcount', $params);
1911 catch (CiviCRM_API3_Exception
$e) {
1912 // Lack of permissions will throw an exception
1918 * Retrieve related case ids for given case.
1920 * @param int $caseId
1921 * @param bool $excludeDeleted
1922 * Do not include deleted cases.
1926 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1927 //FIXME : do check for permissions.
1933 $linkActType = array_search('Link Cases',
1934 CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name')
1936 if (!$linkActType) {
1940 $whereClause = "mainCase.id = %2";
1941 if ($excludeDeleted) {
1942 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1946 SELECT relCaseAct.case_id
1947 FROM civicrm_case mainCase
1948 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1949 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1950 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1951 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1952 WHERE $whereClause";
1954 $dao = CRM_Core_DAO
::executeQuery($query, array(
1955 1 => array($linkActType, 'Integer'),
1956 2 => array($caseId, 'Integer'),
1958 $relatedCaseIds = array();
1959 while ($dao->fetch()) {
1960 $relatedCaseIds[$dao->case_id
] = $dao->case_id
;
1964 return array_values($relatedCaseIds);
1968 * Retrieve related case details for given case.
1970 * @param int $caseId
1971 * @param bool $excludeDeleted
1972 * Do not include deleted cases.
1976 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
1977 $relatedCaseIds = self
::getRelatedCaseIds($caseId, $excludeDeleted);
1978 $relatedCases = array();
1980 if (!$relatedCaseIds) {
1984 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1985 if ($excludeDeleted) {
1986 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1989 //filter for permissioned cases.
1990 $filterCases = array();
1991 $doFilterCases = FALSE;
1992 if (!CRM_Core_Permission
::check('access all cases and activities')) {
1993 $doFilterCases = TRUE;
1994 $session = CRM_Core_Session
::singleton();
1995 $filterCases = CRM_Case_BAO_Case
::getCases(FALSE, $session->get('userID'));
1998 //2. fetch the details of related cases.
2000 SELECT relCase.id as id,
2001 civicrm_case_type.title as case_type,
2002 client.display_name as client_name,
2003 client.id as client_id
2004 FROM civicrm_case relCase
2005 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2006 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2007 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
2008 WHERE {$whereClause}";
2010 $dao = CRM_Core_DAO
::executeQuery($query);
2011 $contactViewUrl = CRM_Utils_System
::url("civicrm/contact/view", "reset=1&cid=");
2012 $hasViewContact = CRM_Core_Permission
::giveMeAllACLs();
2014 while ($dao->fetch()) {
2016 if (!$doFilterCases ||
array_key_exists($dao->id
, $filterCases)) {
2017 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2018 $caseViewUrl = CRM_Utils_System
::url("civicrm/contact/view/case", $caseViewStr);
2019 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2021 $clientView = $dao->client_name
;
2022 if ($hasViewContact) {
2023 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2026 $relatedCases[$dao->id
] = array(
2027 'case_id' => $dao->id
,
2028 'case_type' => $dao->case_type
,
2029 'client_name' => $clientView,
2030 'links' => $caseView,
2035 return $relatedCases;
2039 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2041 * @see CRM_Dedupe_Merger::cpTables()
2043 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2045 * @param int $mainContactId
2046 * @param int $otherContactId
2048 public static function mergeContacts($mainContactId, $otherContactId) {
2049 self
::mergeCases($mainContactId, NULL, $otherContactId);
2053 * Function perform two task.
2054 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2055 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2057 * @param int $mainContactId
2058 * Contact id of main contact record.
2059 * @param int $mainCaseId
2060 * Case id of main case record.
2061 * @param int $otherContactId
2062 * Contact id of record which is going to merge.
2063 * @param int $otherCaseId
2064 * Case id of record which is going to merge.
2066 * @param bool $changeClient
2070 public static function mergeCases(
2071 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2072 $otherCaseId = NULL, $changeClient = FALSE) {
2073 $moveToTrash = TRUE;
2075 $duplicateContacts = FALSE;
2076 if ($mainContactId && $otherContactId &&
2077 $mainContactId != $otherContactId
2079 $duplicateContacts = TRUE;
2082 $duplicateCases = FALSE;
2083 if ($mainCaseId && $otherCaseId &&
2084 $mainCaseId != $otherCaseId
2086 $duplicateCases = TRUE;
2089 $mainCaseIds = array();
2090 if (!$duplicateContacts && !$duplicateCases) {
2091 return $mainCaseIds;
2094 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2095 $activityStatuses = CRM_Core_PseudoConstant
::activityStatus('name');
2096 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2097 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2098 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2099 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2101 $processCaseIds = array($otherCaseId);
2102 if ($duplicateContacts && !$duplicateCases) {
2103 if ($changeClient) {
2104 $processCaseIds = array($mainCaseId);
2107 //get all case ids for other contact.
2108 $processCaseIds = self
::retrieveCaseIdsByContactId($otherContactId, TRUE);
2110 if (!is_array($processCaseIds)) {
2115 $session = CRM_Core_Session
::singleton();
2116 $currentUserId = $session->get('userID');
2118 CRM_Utils_Hook
::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2120 // copy all cases and connect to main contact id.
2121 foreach ($processCaseIds as $otherCaseId) {
2122 if ($duplicateContacts) {
2123 $mainCase = CRM_Core_DAO
::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2124 $mainCaseId = $mainCase->id
;
2129 // CRM-11662 Copy Case custom data
2130 $extends = array('case');
2131 $groupTree = CRM_Core_BAO_CustomGroup
::getGroupDetail(NULL, NULL, $extends);
2133 foreach ($groupTree as $groupID => $group) {
2134 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2135 foreach ($group['fields'] as $fieldID => $field) {
2136 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2140 foreach ($table as $tableName => $tableColumns) {
2141 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2142 $tableColumns[0] = $mainCaseId;
2143 $select = 'SELECT ' . implode(', ', $tableColumns);
2144 $from = ' FROM ' . $tableName;
2145 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2146 $query = $insert . $select . $from . $where;
2147 $dao = CRM_Core_DAO
::executeQuery($query);
2153 $mainCaseIds[] = $mainCaseId;
2154 //insert record for case contact.
2155 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2156 $otherCaseContact->case_id
= $otherCaseId;
2157 $otherCaseContact->find();
2158 while ($otherCaseContact->fetch()) {
2159 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2160 $mainCaseContact->case_id
= $mainCaseId;
2161 $mainCaseContact->contact_id
= $otherCaseContact->contact_id
;
2162 if ($mainCaseContact->contact_id
== $otherContactId) {
2163 $mainCaseContact->contact_id
= $mainContactId;
2165 //avoid duplicate object.
2166 if (!$mainCaseContact->find(TRUE)) {
2167 $mainCaseContact->save();
2169 $mainCaseContact->free();
2171 $otherCaseContact->free();
2173 elseif (!$otherContactId) {
2174 $otherContactId = $mainContactId;
2177 if (!$mainCaseId ||
!$otherCaseId ||
2178 !$mainContactId ||
!$otherContactId
2183 // get all activities for other case.
2184 $otherCaseActivities = array();
2185 CRM_Core_DAO
::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2187 //for duplicate cases do not process singleton activities.
2188 $otherActivityIds = $singletonActivityIds = array();
2189 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2190 $otherActId = CRM_Utils_Array
::value('activity_id', $otherIds);
2191 if (!$otherActId ||
in_array($otherActId, $otherActivityIds)) {
2194 $otherActivityIds[] = $otherActId;
2196 if ($duplicateCases) {
2197 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2200 FROM civicrm_activity
2201 WHERE activity_type_id = $openCaseType
2202 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2203 $dao = CRM_Core_DAO
::executeQuery($sql);
2204 while ($dao->fetch()) {
2205 $singletonActivityIds[] = $dao->id
;
2211 // migrate all activities and connect to main contact.
2212 $copiedActivityIds = $activityMappingIds = array();
2213 sort($otherActivityIds);
2214 foreach ($otherActivityIds as $otherActivityId) {
2216 //for duplicate cases -
2217 //do not migrate singleton activities.
2218 if (!$otherActivityId ||
in_array($otherActivityId, $singletonActivityIds)) {
2222 //migrate activity record.
2223 $otherActivity = new CRM_Activity_DAO_Activity();
2224 $otherActivity->id
= $otherActivityId;
2225 if (!$otherActivity->find(TRUE)) {
2229 $mainActVals = array();
2230 $mainActivity = new CRM_Activity_DAO_Activity();
2231 CRM_Core_DAO
::storeValues($otherActivity, $mainActVals);
2232 $mainActivity->copyValues($mainActVals);
2233 $mainActivity->id
= NULL;
2234 $mainActivity->activity_date_time
= CRM_Utils_Date
::isoToMysql($otherActivity->activity_date_time
);
2235 $mainActivity->source_record_id
= CRM_Utils_Array
::value($mainActivity->source_record_id
,
2239 $mainActivity->original_id
= CRM_Utils_Array
::value($mainActivity->original_id
,
2243 $mainActivity->parent_id
= CRM_Utils_Array
::value($mainActivity->parent_id
,
2246 $mainActivity->save();
2247 $mainActivityId = $mainActivity->id
;
2248 if (!$mainActivityId) {
2252 $activityMappingIds[$otherActivityId] = $mainActivityId;
2253 // insert log of all activities
2254 CRM_Activity_BAO_Activity
::logActivityAction($mainActivity);
2256 $otherActivity->free();
2257 $mainActivity->free();
2258 $copiedActivityIds[] = $otherActivityId;
2260 //create case activity record.
2261 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2262 $mainCaseActivity->case_id
= $mainCaseId;
2263 $mainCaseActivity->activity_id
= $mainActivityId;
2264 $mainCaseActivity->save();
2265 $mainCaseActivity->free();
2267 //migrate source activity.
2268 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2269 $otherSourceActivity->activity_id
= $otherActivityId;
2270 $otherSourceActivity->record_type_id
= $sourceID;
2271 $otherSourceActivity->find();
2272 while ($otherSourceActivity->fetch()) {
2273 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2274 $mainActivitySource->record_type_id
= $sourceID;
2275 $mainActivitySource->activity_id
= $mainActivityId;
2276 $mainActivitySource->contact_id
= $otherSourceActivity->contact_id
;
2277 if ($mainActivitySource->contact_id
== $otherContactId) {
2278 $mainActivitySource->contact_id
= $mainContactId;
2280 //avoid duplicate object.
2281 if (!$mainActivitySource->find(TRUE)) {
2282 $mainActivitySource->save();
2284 $mainActivitySource->free();
2286 $otherSourceActivity->free();
2288 //migrate target activities.
2289 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2290 $otherTargetActivity->activity_id
= $otherActivityId;
2291 $otherTargetActivity->record_type_id
= $targetID;
2292 $otherTargetActivity->find();
2293 while ($otherTargetActivity->fetch()) {
2294 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2295 $mainActivityTarget->record_type_id
= $targetID;
2296 $mainActivityTarget->activity_id
= $mainActivityId;
2297 $mainActivityTarget->contact_id
= $otherTargetActivity->contact_id
;
2298 if ($mainActivityTarget->contact_id
== $otherContactId) {
2299 $mainActivityTarget->contact_id
= $mainContactId;
2301 //avoid duplicate object.
2302 if (!$mainActivityTarget->find(TRUE)) {
2303 $mainActivityTarget->save();
2305 $mainActivityTarget->free();
2307 $otherTargetActivity->free();
2309 //migrate assignee activities.
2310 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2311 $otherAssigneeActivity->activity_id
= $otherActivityId;
2312 $otherAssigneeActivity->record_type_id
= $assigneeID;
2313 $otherAssigneeActivity->find();
2314 while ($otherAssigneeActivity->fetch()) {
2315 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2316 $mainAssigneeActivity->activity_id
= $mainActivityId;
2317 $mainAssigneeActivity->record_type_id
= $assigneeID;
2318 $mainAssigneeActivity->contact_id
= $otherAssigneeActivity->contact_id
;
2319 if ($mainAssigneeActivity->contact_id
== $otherContactId) {
2320 $mainAssigneeActivity->contact_id
= $mainContactId;
2322 //avoid duplicate object.
2323 if (!$mainAssigneeActivity->find(TRUE)) {
2324 $mainAssigneeActivity->save();
2326 $mainAssigneeActivity->free();
2328 $otherAssigneeActivity->free();
2330 // copy custom fields and attachments
2332 'activityID' => $otherActivityId,
2333 'mainActivityId' => $mainActivityId,
2335 CRM_Activity_BAO_Activity
::copyExtendedActivityData($aparams);
2338 //copy case relationship.
2339 if ($duplicateContacts) {
2340 //migrate relationship records.
2341 $otherRelationship = new CRM_Contact_DAO_Relationship();
2342 $otherRelationship->case_id
= $otherCaseId;
2343 $otherRelationship->find();
2344 $otherRelationshipIds = array();
2345 while ($otherRelationship->fetch()) {
2346 $otherRelVals = array();
2347 $updateOtherRel = FALSE;
2348 CRM_Core_DAO
::storeValues($otherRelationship, $otherRelVals);
2350 $mainRelationship = new CRM_Contact_DAO_Relationship();
2351 $mainRelationship->copyValues($otherRelVals);
2352 $mainRelationship->id
= NULL;
2353 $mainRelationship->case_id
= $mainCaseId;
2354 if ($mainRelationship->contact_id_a
== $otherContactId) {
2355 $updateOtherRel = TRUE;
2356 $mainRelationship->contact_id_a
= $mainContactId;
2359 //case creator change only when we merge user contact.
2360 if ($mainRelationship->contact_id_b
== $otherContactId) {
2361 //do not change creator for change client.
2362 if (!$changeClient) {
2363 $updateOtherRel = TRUE;
2364 $mainRelationship->contact_id_b
= ($currentUserId) ?
$currentUserId : $mainContactId;
2367 $mainRelationship->end_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->end_date
);
2368 $mainRelationship->start_date
= CRM_Utils_Date
::isoToMysql($otherRelationship->start_date
);
2370 //avoid duplicate object.
2371 if (!$mainRelationship->find(TRUE)) {
2372 $mainRelationship->save();
2374 $mainRelationship->free();
2376 //get the other relationship ids to update end date.
2377 if ($updateOtherRel) {
2378 $otherRelationshipIds[$otherRelationship->id
] = $otherRelationship->id
;
2381 $otherRelationship->free();
2383 //update other relationships end dates
2384 if (!empty($otherRelationshipIds)) {
2385 $sql = 'UPDATE civicrm_relationship
2386 SET end_date = CURDATE()
2387 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2388 CRM_Core_DAO
::executeQuery($sql);
2392 //move other case to trash.
2393 $mergeCase = self
::deleteCase($otherCaseId, $moveToTrash);
2398 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2399 if ($changeClient) {
2400 $mainContactDisplayName = CRM_Contact_BAO_Contact
::displayName($mainContactId);
2401 $otherContactDisplayName = CRM_Contact_BAO_Contact
::displayName($otherContactId);
2403 $mergeActType = array_search('Reassigned Case', $activityTypes);
2404 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2407 2 => $otherContactDisplayName,
2408 3 => $mainContactDisplayName,
2413 elseif ($duplicateContacts) {
2414 $mergeActType = array_search('Merge Case', $activityTypes);
2415 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2418 2 => $otherContactId,
2419 3 => $mainContactId,
2425 $mergeActType = array_search('Merge Case', $activityTypes);
2426 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2427 if (!empty($copiedActivityIds)) {
2429 SELECT id, subject, activity_date_time, activity_type_id
2430 FROM civicrm_activity
2431 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2432 $dao = CRM_Core_DAO
::executeQuery($sql);
2433 while ($dao->fetch()) {
2434 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2435 if ($dao->subject
) {
2436 $mergeActSubjectDetails .= " :: {$dao->subject}";
2438 $mergeActSubjectDetails .= "<br />";
2443 //Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2444 $activityParams = array(
2445 'subject' => $mergeActSubject,
2446 'details' => $mergeActSubjectDetails,
2447 'status_id' => array_search('Completed', $activityStatuses),
2448 'activity_type_id' => $mergeActType,
2449 'source_contact_id' => $currentUserId,
2450 'activity_date_time' => date('YmdHis'),
2453 $mergeActivity = CRM_Activity_BAO_Activity
::create($activityParams);
2454 $mergeActivityId = $mergeActivity->id
;
2455 if (!$mergeActivityId) {
2458 $mergeActivity->free();
2460 //connect merge activity to case.
2461 $mergeCaseAct = array(
2462 'case_id' => $mainCaseId,
2463 'activity_id' => $mergeActivityId,
2466 self
::processCaseActivity($mergeCaseAct);
2469 CRM_Utils_Hook
::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2471 return $mainCaseIds;
2475 * Validate contact permission for
2476 * edit/view on activity record and build links.
2478 * @param array $tplParams
2479 * Params to be sent to template for sending email.
2480 * @param array $activityParams
2481 * Info of the activity.
2483 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2484 $activityTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2485 'activity_type_id', 'id'
2488 if (!empty($tplParams['isCaseActivity'])) {
2489 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/case/activity',
2490 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2493 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/case/activity/view',
2494 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2497 $tplParams['manageCaseURL'] = CRM_Utils_System
::url('civicrm/contact/view/case',
2498 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2502 $tplParams['editActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2503 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2506 $tplParams['viewActURL'] = CRM_Utils_System
::url('civicrm/contact/view/activity',
2507 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2513 * Validate contact permission for
2514 * given operation on activity record.
2516 * @param int $activityId
2517 * Activity record id.
2518 * @param string $operation
2520 * @param int $actTypeId
2522 * @param int $contactId
2523 * Contact id/if not pass consider logged in.
2524 * @param bool $checkComponent
2525 * Do we need to check component enabled.
2529 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2531 if (!$actTypeId && $activityId) {
2532 $actTypeId = CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2535 if (!$activityId ||
!$operation ||
!$actTypeId) {
2539 //do check for civicase component enabled.
2540 if ($checkComponent && !self
::enabled()) {
2544 //do check for cases.
2545 $caseActOperations = array(
2552 if (in_array($operation, $caseActOperations)) {
2554 if (!isset($caseCount)) {
2556 $caseCount = civicrm_api3('Case', 'getcount', array(
2557 'check_permissions' => TRUE,
2558 'status_id' => array('!=' => 'Closed'),
2560 'end_date' => array('IS NULL' => 1),
2563 catch (CiviCRM_API3_Exception
$e) {
2564 // Lack of permissions will throw an exception
2568 if ($operation == 'File On Case') {
2569 $allow = !empty($caseCount);
2572 $allow = ($caseCount > 1);
2576 $actionOperations = array('view', 'edit', 'delete');
2577 if (in_array($operation, $actionOperations)) {
2579 //do cache when user has non/supper permission.
2580 static $allowOperations;
2582 if (!is_array($allowOperations) ||
2583 !array_key_exists($operation, $allowOperations)
2587 $session = CRM_Core_Session
::singleton();
2588 $contactId = $session->get('userID');
2591 //check for permissions.
2592 $permissions = array(
2594 'access my cases and activities',
2595 'access all cases and activities',
2598 'access my cases and activities',
2599 'access all cases and activities',
2601 'delete' => array('delete activities'),
2604 //check for core permission.
2605 $hasPermissions = array();
2606 $checkPermissions = CRM_Utils_Array
::value($operation, $permissions);
2607 if (is_array($checkPermissions)) {
2608 foreach ($checkPermissions as $per) {
2609 if (CRM_Core_Permission
::check($per)) {
2610 $hasPermissions[$operation][] = $per;
2616 if (!empty($hasPermissions)) {
2617 //need to check activity object specific.
2618 if (in_array($operation, array(
2623 //do we have supper permission.
2624 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2625 $allowOperations[$operation] = $allow = TRUE;
2628 //user has only access to my cases and activity.
2629 //here object specific permmions come in picture.
2631 //edit - contact must be source or assignee
2632 //view - contact must be source/assignee/target
2633 $isTarget = $isAssignee = $isSource = FALSE;
2634 $activityContacts = CRM_Activity_BAO_ActivityContact
::buildOptions('record_type_id', 'validate');
2635 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
2636 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
2637 $targetID = CRM_Utils_Array
::key('Activity Targets', $activityContacts);
2639 $target = new CRM_Activity_DAO_ActivityContact();
2640 $target->record_type_id
= $targetID;
2641 $target->activity_id
= $activityId;
2642 $target->contact_id
= $contactId;
2643 if ($target->find(TRUE)) {
2647 $assignee = new CRM_Activity_DAO_ActivityContact();
2648 $assignee->activity_id
= $activityId;
2649 $assignee->record_type_id
= $assigneeID;
2650 $assignee->contact_id
= $contactId;
2651 if ($assignee->find(TRUE)) {
2655 $source = new CRM_Activity_DAO_ActivityContact();
2656 $source->activity_id
= $activityId;
2657 $source->record_type_id
= $sourceID;
2658 $source->contact_id
= $contactId;
2659 if ($source->find(TRUE)) {
2663 if ($operation == 'edit') {
2664 if ($isAssignee ||
$isSource) {
2668 if ($operation == 'view') {
2669 if ($isTarget ||
$isAssignee ||
$isSource) {
2675 elseif (is_array($hasPermissions[$operation])) {
2676 $allowOperations[$operation] = $allow = TRUE;
2680 //contact do not have permission.
2681 $allowOperations[$operation] = FALSE;
2686 //here contact might have supper/non permission.
2687 $allow = $allowOperations[$operation];
2691 //do further only when operation is granted.
2693 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, TRUE, FALSE, 'name');
2695 //get the activity type name.
2696 $actTypeName = CRM_Utils_Array
::value($actTypeId, $activityTypes);
2698 //do not allow multiple copy / edit action.
2699 $singletonNames = array(
2709 //do not allow to delete these activities, CRM-4543
2710 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2712 //allow edit operation.
2713 $allowEditNames = array('Open Case');
2715 // do not allow File on Case
2716 $doNotFileNames = array(
2719 'Change Case Status',
2720 'Change Case Start Date',
2727 if (in_array($actTypeName, $singletonNames)) {
2729 if ($operation == 'File On Case') {
2730 $allow = (in_array($actTypeName, $doNotFileNames)) ?
FALSE : TRUE;
2732 if (in_array($operation, $actionOperations)) {
2734 if ($operation == 'edit') {
2735 $allow = (in_array($actTypeName, $allowEditNames)) ?
TRUE : FALSE;
2737 elseif ($operation == 'delete') {
2738 $allow = (in_array($actTypeName, $doNotDeleteNames)) ?
FALSE : TRUE;
2742 if ($allow && ($operation == 'delete') &&
2743 in_array($actTypeName, $doNotDeleteNames)
2748 if ($allow && ($operation == 'File On Case') &&
2749 in_array($actTypeName, $doNotFileNames)
2754 //check settings file for masking actions
2755 //on the basis the activity types
2756 //hide Edit link if activity type is NOT editable
2757 //(special case activities).CRM-5871
2758 if ($allow && in_array($operation, $actionOperations)) {
2759 static $actionFilter = array();
2760 if (!array_key_exists($operation, $actionFilter)) {
2761 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2762 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2764 if (array_key_exists($operation, $actionFilter[$operation]) &&
2765 in_array($actTypeId, $actionFilter[$operation][$operation])
2776 * Since we drop 'access CiviCase', allow access
2777 * if user has 'access my cases and activities'
2778 * or 'access all cases and activities'
2780 public static function accessCiviCase() {
2781 if (!self
::enabled()) {
2785 if (CRM_Core_Permission
::check('access my cases and activities') ||
2786 CRM_Core_Permission
::check('access all cases and activities')
2795 * Verify user has permission to access a case.
2797 * @param int $caseId
2798 * @param bool $denyClosed
2799 * Set TRUE if one wants closed cases to be treated as inaccessible.
2803 public static function accessCase($caseId, $denyClosed = TRUE) {
2804 if (!$caseId ||
!self
::enabled()) {
2808 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2809 if ($denyClosed && !CRM_Core_Permission
::check('access all cases and activities')) {
2810 $params['status_id'] = array('!=' => 'Closed');
2813 return (bool) civicrm_api3('Case', 'getcount', $params);
2815 catch (CiviCRM_API3_Exception
$e) {
2816 // Lack of permissions will throw an exception
2822 * Check whether activity is a case Activity.
2824 * @param int $activityID
2829 public static function isCaseActivity($activityID) {
2830 $isCaseActivity = FALSE;
2832 $params = array(1 => array($activityID, 'Integer'));
2833 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2834 if (CRM_Core_DAO
::singleValueQuery($query, $params)) {
2835 $isCaseActivity = TRUE;
2839 return $isCaseActivity;
2843 * Get all the case type ids currently in use.
2847 public static function getUsedCaseType() {
2848 static $caseTypeIds;
2850 if (!is_array($caseTypeIds)) {
2851 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2853 $dao = CRM_Core_DAO
::executeQuery($query);
2854 $caseTypeIds = array();
2855 while ($dao->fetch()) {
2856 $typeId = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2859 $caseTypeIds[] = $typeId[1];
2863 return $caseTypeIds;
2867 * Get all the case status ids currently in use.
2871 public static function getUsedCaseStatuses() {
2872 static $caseStatusIds;
2874 if (!is_array($caseStatusIds)) {
2875 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2877 $dao = CRM_Core_DAO
::executeQuery($query);
2878 $caseStatusIds = array();
2879 while ($dao->fetch()) {
2880 $caseStatusIds[] = $dao->status_id
;
2884 return $caseStatusIds;
2888 * Get all the encounter medium ids currently in use.
2892 public static function getUsedEncounterMediums() {
2895 if (!is_array($mediumIds)) {
2896 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2898 $dao = CRM_Core_DAO
::executeQuery($query);
2899 $mediumIds = array();
2900 while ($dao->fetch()) {
2901 $mediumIds[] = $dao->medium_id
;
2909 * Check case configuration.
2911 * @param int $contactId
2915 public static function isCaseConfigured($contactId = NULL) {
2916 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2918 //lets check for case configured.
2919 $allCasesCount = CRM_Case_BAO_Case
::caseCount(NULL, FALSE);
2920 $configured['configured'] = ($allCasesCount) ?
TRUE : FALSE;
2921 if (!$configured['configured']) {
2922 //do check for case type and case status.
2923 $caseTypes = CRM_Case_PseudoConstant
::caseType('title', FALSE);
2924 if (!empty($caseTypes)) {
2925 $configured['configured'] = TRUE;
2926 if (!$configured['configured']) {
2927 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus('label', FALSE);
2928 if (!empty($caseStatuses)) {
2929 $configured['configured'] = TRUE;
2934 if ($configured['configured']) {
2935 //do check for active case type and case status.
2936 $caseTypes = CRM_Case_PseudoConstant
::caseType();
2937 if (!empty($caseTypes)) {
2938 $caseStatuses = CRM_Case_PseudoConstant
::caseStatus();
2939 if (!empty($caseStatuses)) {
2940 $configured['allowToAddNewCase'] = TRUE;
2944 //do we need to redirect user to case admin.
2945 if (!$configured['allowToAddNewCase'] && $contactId) {
2946 //check for current contact case count.
2947 $currentContatCasesCount = CRM_Case_BAO_Case
::caseCount($contactId);
2948 //redirect user to case admin page.
2949 if (!$currentContatCasesCount) {
2950 $configured['redirectToCaseAdmin'] = TRUE;
2959 * Used during case component enablement and during ugprade.
2963 public static function createCaseViews() {
2964 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
2965 $dao = new CRM_Core_DAO();
2967 $sql = self
::createCaseViewsQuery('upcoming');
2969 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2973 // Above error doesn't get caught?
2974 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2975 if (is_null($doublecheck)) {
2979 $sql = self
::createCaseViewsQuery('recent');
2981 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2985 // Above error doesn't get caught?
2986 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
2987 if (is_null($doublecheck)) {
2995 * Helper function, also used by the upgrade in case of error
2997 * @param string $section
3001 public static function createCaseViewsQuery($section = 'upcoming') {
3003 $scheduled_id = CRM_Core_Pseudoconstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
3006 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3007 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3008 FROM civicrm_case_activity ca
3009 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3010 WHERE a.activity_date_time =
3011 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3012 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3013 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3014 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
3015 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
3019 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3020 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3021 FROM civicrm_case_activity ca
3022 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3023 WHERE a.activity_date_time =
3024 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3025 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3026 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3027 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
3028 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
3035 * Add/copy relationships, when new client is added for a case
3037 * @param int $caseId
3039 * @param int $contactId
3040 * Contact id / new client id.
3042 public static function addCaseRelationships($caseId, $contactId) {
3043 // get the case role / relationships for the case
3044 $caseRelationships = new CRM_Contact_DAO_Relationship();
3045 $caseRelationships->case_id
= $caseId;
3046 $caseRelationships->find();
3047 $relationshipTypes = array();
3049 // make sure we don't add duplicate relationships of same relationship type.
3050 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id
, $relationshipTypes)) {
3052 CRM_Core_DAO
::storeValues($caseRelationships, $values);
3054 // add relationship for new client.
3055 $newRelationship = new CRM_Contact_DAO_Relationship();
3056 $newRelationship->copyValues($values);
3057 $newRelationship->id
= NULL;
3058 $newRelationship->case_id
= $caseId;
3059 $newRelationship->contact_id_a
= $contactId;
3060 $newRelationship->end_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->end_date
);
3061 $newRelationship->start_date
= CRM_Utils_Date
::isoToMysql($caseRelationships->start_date
);
3063 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3064 if (!$newRelationship->find(TRUE)) {
3065 $newRelationship->save();
3067 $newRelationship->free();
3069 // store relationship type of newly created relationship
3070 $relationshipTypes[] = $caseRelationships->relationship_type_id
;
3075 * Get the list of clients for a case.
3077 * @param int $caseId
3080 * associated array with client ids
3082 public static function getCaseClients($caseId) {
3084 $caseContact = new CRM_Case_DAO_CaseContact();
3085 $caseContact->case_id
= $caseId;
3086 $caseContact->orderBy('id');
3087 $caseContact->find();
3089 while ($caseContact->fetch()) {
3090 $clients[] = $caseContact->contact_id
;
3097 * @param int $caseId
3098 * @param string $direction
3100 * @param int $relTypeId
3101 * @throws \CRM_Core_Exception
3102 * @throws \CiviCRM_API3_Exception
3104 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3106 if ($direction !== 'a' && $direction !== 'b') {
3107 throw new CRM_Core_Exception('Invalid relationship direction');
3110 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3111 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3112 $dao = CRM_Core_DAO
::executeQuery($sql, array(
3113 1 => array($caseId, 'Positive'),
3114 2 => array($cid, 'Positive'),
3115 3 => array($relTypeId, 'Positive'),
3117 while ($dao->fetch()) {
3118 civicrm_api3('relationship', 'create', array(
3121 'end_date' => 'now',
3127 * Get options for a given case field.
3128 * @see CRM_Core_DAO::buildOptions
3130 * @param string $fieldName
3131 * @param string $context
3132 * @see CRM_Core_DAO::buildOptionsContext
3133 * @param array $props
3134 * Whatever is known about this dao object.
3136 * @return array|bool
3138 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3139 $className = __CLASS__
;
3141 switch ($fieldName) {
3142 // This field is not part of this object but the api supports it
3144 $className = 'CRM_Activity_BAO_Activity';
3147 // Filter status id by case type id
3149 if (!empty($props['case_type_id'])) {
3150 $idField = is_numeric($props['case_type_id']) ?
'id' : 'name';
3151 $caseType = civicrm_api3('CaseType', 'getsingle', array($idField => $props['case_type_id'], 'return' => 'definition'));
3152 if (!empty($caseType['definition']['statuses'])) {
3153 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
3158 return CRM_Core_PseudoConstant
::get($className, $fieldName, $params, $context);
3164 public function addSelectWhereClause() {
3165 // We always return an array with these keys, even if they are empty,
3166 // because this tells the query builder that we have considered these fields for acls
3169 // Only case admins can view deleted cases
3170 'is_deleted' => CRM_Core_Permission
::check('administer CiviCase') ?
array() : array("= 0"),
3172 // Ensure the user has permission to view the case client
3173 $contactClause = CRM_Utils_SQL
::mergeSubquery('Contact');
3174 if ($contactClause) {
3175 $contactClause = implode(' AND contact_id ', $contactClause);
3176 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3178 // The api gatekeeper ensures the user has at least "access my cases and activities"
3179 // so if they do not have permission to see all cases we'll assume they can only access their own
3180 if (!CRM_Core_Permission
::check('access all cases and activities')) {
3181 $user = (int) CRM_Core_Session
::getLoggedInContactID();
3182 $clauses['id'][] = "IN (
3183 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 (
3184 (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)
3188 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3193 * CRM-20308: Method to get the contact id to use as from contact for email copy
3194 * 1. Activity Added by Contact's email address
3195 * 2. System Default From Address
3196 * 3. Default Organization Contact email address
3199 * @param int $activityID
3201 * @return mixed $emailFromContactId
3202 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3204 public static function getReceiptFrom($activityID) {
3205 $name = $address = NULL;
3207 if (!empty($activityID)) {
3208 // There is always a 'Added by' contact for a activity,
3209 // so we can safely use ActivityContact.Getvalue API
3210 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', array(
3211 'activity_id' => $activityID,
3212 'record_type_id' => 'Activity Source',
3213 'return' => 'contact_id',
3215 list($name, $address) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($sourceContactId);
3218 // If 'From' email address not found for Source Activity Contact then
3219 // fetch the email from domain or logged in user.
3220 if (empty($address)) {
3221 list($name, $address) = CRM_Core_BAO_Domain
::getDefaultReceiptFrom();
3224 return "$name <$address>";