Merge pull request #10734 from jitendrapurohit/CRM-20949
[civicrm-core.git] / CRM / Case / BAO / Case.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2017
32 */
33
34 /**
35 * This class contains the functions for Case Management.
36 */
37 class CRM_Case_BAO_Case extends CRM_Case_DAO_Case {
38
39 /**
40 * Static field for all the case information that we can potentially export.
41 *
42 * @var array
43 */
44 static $_exportableFields = NULL;
45
46 /**
47 * Class constructor.
48 */
49 public function __construct() {
50 parent::__construct();
51 }
52
53 /**
54 * Is CiviCase enabled?
55 *
56 * @return bool
57 */
58 public static function enabled() {
59 $config = CRM_Core_Config::singleton();
60 return in_array('CiviCase', $config->enableComponents);
61 }
62
63 /**
64 * Create a case object.
65 *
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
68 * pairs
69 *
70 * @param array $params
71 * (reference ) an assoc array of name/value pairs.
72 *
73 * @return CRM_Case_BAO_Case
74 */
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
80 return $result;
81 }
82
83 /**
84 * Takes an associative array and creates a case object.
85 *
86 * @param array $params
87 * (reference) an assoc array of name/value pairs.
88 *
89 * @return CRM_Case_BAO_Case
90 */
91 public static function &create(&$params) {
92 $transaction = new CRM_Core_Transaction();
93
94 if (!empty($params['id'])) {
95 CRM_Utils_Hook::pre('edit', 'Case', $params['id'], $params);
96 }
97 else {
98 CRM_Utils_Hook::pre('create', 'Case', NULL, $params);
99 }
100
101 $case = self::add($params);
102
103 if (!empty($params['custom']) &&
104 is_array($params['custom'])
105 ) {
106 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_case', $case->id);
107 }
108
109 if (is_a($case, 'CRM_Core_Error')) {
110 $transaction->rollback();
111 return $case;
112 }
113
114 if (!empty($params['id'])) {
115 CRM_Utils_Hook::post('edit', 'Case', $case->id, $case);
116 }
117 else {
118 CRM_Utils_Hook::post('create', 'Case', $case->id, $case);
119 }
120 $transaction->commit();
121
122 //we are not creating log for case
123 //since case log can be tracked using log for activity.
124 return $case;
125 }
126
127 /**
128 * Process case activity add/delete
129 * takes an associative array and
130 *
131 * @param array $params
132 * (reference ) an assoc array of name/value pairs.
133 *
134 */
135 public static function processCaseActivity(&$params) {
136 $caseActivityDAO = new CRM_Case_DAO_CaseActivity();
137 $caseActivityDAO->activity_id = $params['activity_id'];
138 $caseActivityDAO->case_id = $params['case_id'];
139
140 $caseActivityDAO->find(TRUE);
141 $caseActivityDAO->save();
142 }
143
144 /**
145 * Get the case subject for Activity.
146 *
147 * @param int $activityId
148 * Activity id.
149 *
150 * @return string|null
151 */
152 public static function getCaseSubject($activityId) {
153 $caseActivity = new CRM_Case_DAO_CaseActivity();
154 $caseActivity->activity_id = $activityId;
155 if ($caseActivity->find(TRUE)) {
156 return CRM_Core_DAO::getFieldValue('CRM_Case_BAO_Case', $caseActivity->case_id, 'subject');
157 }
158 return NULL;
159 }
160
161 /**
162 * Get the case type.
163 *
164 * @param int $caseId
165 * @param string $colName
166 *
167 * @return string
168 * case type
169 */
170 public static function getCaseType($caseId, $colName = 'title') {
171 $query = "
172 SELECT civicrm_case_type.{$colName} FROM civicrm_case
173 LEFT JOIN civicrm_case_type ON
174 civicrm_case.case_type_id = civicrm_case_type.id
175 WHERE civicrm_case.id = %1";
176
177 $queryParams = array(1 => array($caseId, 'Integer'));
178
179 return CRM_Core_DAO::singleValueQuery($query, $queryParams);
180 }
181
182 /**
183 * Delete the record that are associated with this case.
184 * record are deleted from case
185 *
186 * @param int $caseId
187 * Id of the case to delete.
188 *
189 * @param bool $moveToTrash
190 *
191 * @return bool
192 * is successful
193 */
194 public static function deleteCase($caseId, $moveToTrash = FALSE) {
195 CRM_Utils_Hook::pre('delete', 'Case', $caseId, CRM_Core_DAO::$_nullArray);
196
197 //delete activities
198 $activities = self::getCaseActivityDates($caseId);
199 if ($activities) {
200 foreach ($activities as $value) {
201 CRM_Activity_BAO_Activity::deleteActivity($value, $moveToTrash);
202 }
203 }
204
205 if (!$moveToTrash) {
206 $transaction = new CRM_Core_Transaction();
207 }
208 $case = new CRM_Case_DAO_Case();
209 $case->id = $caseId;
210 if (!$moveToTrash) {
211 $result = $case->delete();
212 $transaction->commit();
213 }
214 else {
215 $result = $case->is_deleted = 1;
216 $case->save();
217 }
218
219 if ($result) {
220 // CRM-7364, disable relationships
221 self::enableDisableCaseRelationships($caseId, FALSE);
222
223 CRM_Utils_Hook::post('delete', 'Case', $caseId, $case);
224
225 // remove case from recent items.
226 $caseRecent = array(
227 'id' => $caseId,
228 'type' => 'Case',
229 );
230 CRM_Utils_Recent::del($caseRecent);
231 return TRUE;
232 }
233
234 return FALSE;
235 }
236
237 /**
238 * Enable disable case related relationships.
239 *
240 * @param int $caseId
241 * Case id.
242 * @param bool $enable
243 * Action.
244 */
245 public static function enableDisableCaseRelationships($caseId, $enable) {
246 $contactIds = self::retrieveContactIdsByCaseId($caseId);
247 if (!empty($contactIds)) {
248 foreach ($contactIds as $cid) {
249 $roles = self::getCaseRoles($cid, $caseId);
250 if (!empty($roles)) {
251 $relationshipIds = implode(',', array_keys($roles));
252 $enable = (int) $enable;
253 $query = "UPDATE civicrm_relationship SET is_active = {$enable}
254 WHERE id IN ( {$relationshipIds} )";
255 CRM_Core_DAO::executeQuery($query);
256 }
257 }
258 }
259 }
260
261 /**
262 * Retrieve contact_id by case_id.
263 *
264 * @param int $caseId
265 * ID of the case.
266 *
267 * @param int $contactID
268 *
269 * @return array
270 */
271 public static function retrieveContactIdsByCaseId($caseId, $contactID = NULL) {
272 $caseContact = new CRM_Case_DAO_CaseContact();
273 $caseContact->case_id = $caseId;
274 $caseContact->find();
275 $contactArray = array();
276 // FIXME: Why does this return a 1-based array?
277 $count = 1;
278 while ($caseContact->fetch()) {
279 if ($contactID != $caseContact->contact_id) {
280 $contactArray[$count] = $caseContact->contact_id;
281 $count++;
282 }
283 }
284
285 return $contactArray;
286 }
287
288 /**
289 * Look up a case using an activity ID.
290 *
291 * @param int $activityId
292 *
293 * @return int, case ID
294 */
295 public static function getCaseIdByActivityId($activityId) {
296 $originalId = CRM_Core_DAO::singleValueQuery(
297 'SELECT original_id FROM civicrm_activity WHERE id = %1',
298 array('1' => array($activityId, 'Integer'))
299 );
300 $caseId = CRM_Core_DAO::singleValueQuery(
301 'SELECT case_id FROM civicrm_case_activity WHERE activity_id in (%1,%2)',
302 array(
303 '1' => array($activityId, 'Integer'),
304 '2' => array($originalId ? $originalId : $activityId, 'Integer'),
305 )
306 );
307 return $caseId;
308 }
309
310 /**
311 * Retrieve contact names by caseId.
312 *
313 * @param int $caseId
314 * ID of the case.
315 *
316 * @return array
317 */
318 public static function getContactNames($caseId) {
319 $contactNames = array();
320 if (!$caseId) {
321 return $contactNames;
322 }
323
324 $query = "
325 SELECT contact_a.sort_name name,
326 contact_a.display_name as display_name,
327 contact_a.id cid,
328 contact_a.birth_date as birth_date,
329 ce.email as email,
330 cp.phone as phone
331 FROM civicrm_contact contact_a
332 LEFT JOIN civicrm_case_contact ON civicrm_case_contact.contact_id = contact_a.id
333 LEFT JOIN civicrm_email ce ON ( ce.contact_id = contact_a.id AND ce.is_primary = 1)
334 LEFT JOIN civicrm_phone cp ON ( cp.contact_id = contact_a.id AND cp.is_primary = 1)
335 WHERE civicrm_case_contact.case_id = %1
336 ORDER BY civicrm_case_contact.id";
337
338 $dao = CRM_Core_DAO::executeQuery($query,
339 array(1 => array($caseId, 'Integer'))
340 );
341 while ($dao->fetch()) {
342 $contactNames[$dao->cid]['contact_id'] = $dao->cid;
343 $contactNames[$dao->cid]['sort_name'] = $dao->name;
344 $contactNames[$dao->cid]['display_name'] = $dao->display_name;
345 $contactNames[$dao->cid]['email'] = $dao->email;
346 $contactNames[$dao->cid]['phone'] = $dao->phone;
347 $contactNames[$dao->cid]['birth_date'] = $dao->birth_date;
348 $contactNames[$dao->cid]['role'] = ts('Client');
349 }
350
351 return $contactNames;
352 }
353
354 /**
355 * Retrieve case_id by contact_id.
356 *
357 * @param int $contactID
358 * @param bool $includeDeleted
359 * Include the deleted cases in result.
360 * @param null $caseType
361 *
362 * @return array
363 */
364 public static function retrieveCaseIdsByContactId($contactID, $includeDeleted = FALSE, $caseType = NULL) {
365 $query = "
366 SELECT ca.id as id
367 FROM civicrm_case_contact cc
368 INNER JOIN civicrm_case ca ON cc.case_id = ca.id
369 ";
370 if (isset($caseType)) {
371 $query .=
372 "INNER JOIN civicrm_case_type ON civicrm_case_type.id = ca.case_type_id
373 WHERE cc.contact_id = %1 AND civicrm_case_type.name = '{$caseType}'";
374 }
375 if (!isset($caseType)) {
376 $query .= "WHERE cc.contact_id = %1";
377 }
378 if (!$includeDeleted) {
379 $query .= " AND ca.is_deleted = 0";
380 }
381
382 $params = array(1 => array($contactID, 'Integer'));
383 $dao = CRM_Core_DAO::executeQuery($query, $params);
384
385 $caseArray = array();
386 while ($dao->fetch()) {
387 $caseArray[] = $dao->id;
388 }
389
390 $dao->free();
391 return $caseArray;
392 }
393
394 /**
395 * @param string $type
396 * @param int $userID
397 * @param string $condition
398 *
399 * @return string
400 */
401 public static function getCaseActivityQuery($type = 'upcoming', $userID = NULL, $condition = NULL) {
402 if (!$userID) {
403 $session = CRM_Core_Session::singleton();
404 $userID = $session->get('userID');
405 }
406
407 $query = "SELECT
408 civicrm_case.id as case_id,
409 civicrm_case.subject as case_subject,
410 civicrm_contact.id as contact_id,
411 civicrm_contact.sort_name as sort_name,
412 civicrm_phone.phone as phone,
413 civicrm_contact.contact_type as contact_type,
414 civicrm_contact.contact_sub_type as contact_sub_type,
415 t_act.activity_type_id,
416 c_type.title as case_type,
417 civicrm_case.case_type_id as case_type_id,
418 cov_status.label as case_status,
419 cov_status.label as case_status_name,
420 t_act.status_id,
421 civicrm_case.start_date as case_start_date,
422 case_relation_type.label_b_a as case_role, ";
423
424 if ($type == 'upcoming') {
425 $query .= "
426 t_act.desired_date as case_scheduled_activity_date,
427 t_act.id as case_scheduled_activity_id,
428 t_act.act_type_name as case_scheduled_activity_type_name,
429 t_act.act_type AS case_scheduled_activity_type ";
430 }
431 elseif ($type == 'recent') {
432 $query .= "
433 t_act.desired_date as case_recent_activity_date,
434 t_act.id as case_recent_activity_id,
435 t_act.act_type_name as case_recent_activity_type_name,
436 t_act.act_type AS case_recent_activity_type ";
437 }
438 elseif ($type == 'any') {
439 $query .= "
440 t_act.desired_date as case_activity_date,
441 t_act.id as case_activity_id,
442 t_act.act_type_name as case_activity_type_name,
443 t_act.act_type AS case_activity_type ";
444 }
445
446 $query .= " FROM civicrm_case
447 INNER JOIN civicrm_case_contact ON civicrm_case.id = civicrm_case_contact.case_id
448 INNER JOIN civicrm_contact ON civicrm_case_contact.contact_id = civicrm_contact.id ";
449
450 if ($type == 'upcoming') {
451 // This gets the earliest activity per case that's scheduled within 14 days from now.
452 // Note we have an inner select to get the min activity id in order to remove duplicates in case there are two with the same datetime.
453 // In this case we don't really care which one, so min(id) works.
454 // optimized in CRM-11837
455 $query .= " INNER JOIN
456 (
457 SELECT case_id, act.id, activity_date_time AS desired_date, activity_type_id, status_id, aov.name AS act_type_name, aov.label AS act_type
458 FROM (
459 SELECT *
460 FROM (
461 SELECT *
462 FROM civicrm_view_case_activity_upcoming
463 ORDER BY activity_date_time ASC, id ASC
464 ) AS upcomingOrdered
465 ) AS act
466 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
467 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
468 ) AS t_act
469 ";
470 }
471 elseif ($type == 'recent') {
472 // Similarly, the most recent activity in the past 14 days, and exclude scheduled.
473 //improve query performance - CRM-10598
474 $query .= " INNER JOIN
475 (
476 SELECT case_id, act.id, activity_date_time AS desired_date, activity_type_id, status_id, aov.name AS act_type_name, aov.label AS act_type
477 FROM (
478 SELECT *
479 FROM (
480 SELECT *
481 FROM civicrm_view_case_activity_recent
482 ORDER BY activity_date_time DESC, id ASC
483 ) AS recentOrdered
484 ) AS act
485 LEFT JOIN civicrm_option_group aog ON aog.name='activity_type'
486 LEFT JOIN civicrm_option_value aov ON ( aov.option_group_id = aog.id AND aov.value = act.activity_type_id )
487 ) AS t_act ";
488 }
489 elseif ($type == 'any') {
490 $query .= " LEFT JOIN
491 (
492 SELECT ca4.case_id, act4.id AS id, act4.activity_date_time AS desired_date, act4.activity_type_id, act4.status_id, aov.name AS act_type_name, aov.label AS act_type
493 FROM civicrm_activity act4
494 LEFT JOIN civicrm_case_activity ca4
495 ON ca4.activity_id = act4.id
496 AND act4.is_current_revision = 1
497 LEFT JOIN civicrm_option_group aog
498 ON aog.name='activity_type'
499 LEFT JOIN civicrm_option_value aov
500 ON aov.option_group_id = aog.id
501 AND aov.value = act4.activity_type_id
502 ) AS t_act";
503 }
504
505 $query .= "
506 ON t_act.case_id = civicrm_case.id
507 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary=1)
508 LEFT JOIN civicrm_relationship case_relationship
509 ON ( case_relationship.contact_id_a = civicrm_case_contact.contact_id AND case_relationship.contact_id_b = {$userID}
510 AND case_relationship.case_id = civicrm_case.id )
511
512 LEFT JOIN civicrm_relationship_type case_relation_type
513 ON ( case_relation_type.id = case_relationship.relationship_type_id
514 AND case_relation_type.id = case_relationship.relationship_type_id )
515
516 LEFT JOIN civicrm_case_type c_type
517 ON civicrm_case.case_type_id = c_type.id
518
519 LEFT JOIN civicrm_option_group cog_status
520 ON cog_status.name = 'case_status'
521
522 LEFT JOIN civicrm_option_value cov_status
523 ON ( civicrm_case.status_id = cov_status.value
524 AND cog_status.id = cov_status.option_group_id )
525 ";
526
527 if ($condition) {
528 // CRM-8749 backwards compatibility - callers of this function expect to start $condition with "AND"
529 $query .= " WHERE (1) $condition ";
530 }
531
532 if ($type == 'upcoming') {
533 $query .= " ORDER BY case_scheduled_activity_date ASC ";
534 }
535 elseif ($type == 'recent') {
536 $query .= " ORDER BY case_recent_activity_date ASC ";
537 }
538 elseif ($type == 'any') {
539 $query .= " ORDER BY case_activity_date ASC ";
540 }
541
542 return $query;
543 }
544
545 /**
546 * Retrieve cases related to particular contact or whole contact used in Dashboard and Tab.
547 *
548 * @param bool $allCases
549 *
550 * @param int $userID
551 *
552 * @param string $type
553 * /upcoming,recent,all/.
554 *
555 * @param string $context
556 *
557 * @return array
558 * Array of Cases
559 */
560 public static function getCases($allCases = TRUE, $userID = NULL, $type = 'upcoming', $context = 'dashboard') {
561 $condition = NULL;
562 $casesList = array();
563
564 //validate access for own cases.
565 if (!self::accessCiviCase()) {
566 return $casesList;
567 }
568
569 if (!$userID) {
570 $session = CRM_Core_Session::singleton();
571 $userID = $session->get('userID');
572 }
573
574 //validate access for all cases.
575 if ($allCases && !CRM_Core_Permission::check('access all cases and activities')) {
576 $allCases = FALSE;
577 }
578
579 $condition = " AND civicrm_case.is_deleted = 0 AND civicrm_contact.is_deleted <> 1";
580
581 if (!$allCases) {
582 $condition .= " AND case_relationship.contact_id_b = {$userID} ";
583 }
584 if ($type == 'upcoming' || $type == 'any') {
585 $closedId = CRM_Core_PseudoConstant::getKey('CRM_Case_BAO_Case', 'case_status_id', 'Closed');
586 $condition .= "
587 AND civicrm_case.status_id != $closedId";
588 }
589
590 $query = self::getCaseActivityQuery($type, $userID, $condition);
591
592 $queryParams = array();
593 $result = CRM_Core_DAO::executeQuery($query,
594 $queryParams
595 );
596
597 $caseStatus = CRM_Core_OptionGroup::values('case_status', FALSE, FALSE, FALSE, " AND v.name = 'Urgent' ");
598
599 $resultFields = array(
600 'contact_id',
601 'contact_type',
602 'sort_name',
603 'phone',
604 'case_id',
605 'case_subject',
606 'case_type',
607 'case_type_id',
608 'status_id',
609 'case_status',
610 'case_status_name',
611 'activity_type_id',
612 'case_start_date',
613 'case_role',
614 );
615
616 if ($type == 'upcoming') {
617 $resultFields[] = 'case_scheduled_activity_date';
618 $resultFields[] = 'case_scheduled_activity_type_name';
619 $resultFields[] = 'case_scheduled_activity_type';
620 $resultFields[] = 'case_scheduled_activity_id';
621 }
622 elseif ($type == 'recent') {
623 $resultFields[] = 'case_recent_activity_date';
624 $resultFields[] = 'case_recent_activity_type_name';
625 $resultFields[] = 'case_recent_activity_type';
626 $resultFields[] = 'case_recent_activity_id';
627 }
628 elseif ($type == 'any') {
629 $resultFields[] = 'case_activity_date';
630 $resultFields[] = 'case_activity_type_name';
631 $resultFields[] = 'case_activity_type';
632 $resultFields[] = 'case_activity_id';
633 }
634
635 // we're going to use the usual actions, so doesn't make sense to duplicate definitions
636 $actions = CRM_Case_Selector_Search::links();
637
638 // check is the user has view/edit signer permission
639 $permissions = array(CRM_Core_Permission::VIEW);
640 if (CRM_Core_Permission::check('access all cases and activities') ||
641 (!$allCases && CRM_Core_Permission::check('access my cases and activities'))
642 ) {
643 $permissions[] = CRM_Core_Permission::EDIT;
644 }
645 if (CRM_Core_Permission::check('delete in CiviCase')) {
646 $permissions[] = CRM_Core_Permission::DELETE;
647 }
648 $mask = CRM_Core_Action::mask($permissions);
649
650 while ($result->fetch()) {
651 foreach ($resultFields as $donCare => $field) {
652 $casesList[$result->case_id][$field] = $result->$field;
653 if ($field == 'contact_type') {
654 $casesList[$result->case_id]['contact_type_icon'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type
655 );
656 $casesList[$result->case_id]['action'] = CRM_Core_Action::formLink($actions['primaryActions'], $mask,
657 array(
658 'id' => $result->case_id,
659 'cid' => $result->contact_id,
660 'cxt' => $context,
661 ),
662 ts('more'),
663 FALSE,
664 'case.actions.primary',
665 'Case',
666 $result->case_id
667 );
668 }
669 elseif ($field == 'case_status') {
670 if (in_array($result->$field, $caseStatus)) {
671 $casesList[$result->case_id]['class'] = "status-urgent";
672 }
673 else {
674 $casesList[$result->case_id]['class'] = "status-normal";
675 }
676 }
677 }
678 //CRM-4510.
679 $caseTypes = CRM_Case_PseudoConstant::caseType('name');
680 $caseManagerContact = self::getCaseManagerContact($caseTypes[$result->case_type_id], $result->case_id);
681 if (!empty($caseManagerContact)) {
682 $casesList[$result->case_id]['casemanager_id'] = CRM_Utils_Array::value('casemanager_id', $caseManagerContact);
683 $casesList[$result->case_id]['casemanager'] = CRM_Utils_Array::value('casemanager', $caseManagerContact);
684 }
685
686 //do check user permissions for edit/view activity.
687 if (($actId = CRM_Utils_Array::value('case_scheduled_activity_id', $casesList[$result->case_id])) ||
688 ($actId = CRM_Utils_Array::value('case_recent_activity_id', $casesList[$result->case_id]))
689 ) {
690 $casesList[$result->case_id]["case_{$type}_activity_editable"] = self::checkPermission($actId,
691 'edit',
692 $casesList[$result->case_id]['activity_type_id'], $userID
693 );
694 $casesList[$result->case_id]["case_{$type}_activity_viewable"] = self::checkPermission($actId,
695 'view',
696 $casesList[$result->case_id]['activity_type_id'], $userID
697 );
698 }
699 }
700
701 return $casesList;
702 }
703
704 /**
705 * Get the summary of cases counts by type and status.
706 *
707 * @param bool $allCases
708 * @param int $userID
709 * @return array
710 */
711 public static function getCasesSummary($allCases = TRUE, $userID) {
712 $caseSummary = array();
713
714 //validate access for civicase.
715 if (!self::accessCiviCase()) {
716 return $caseSummary;
717 }
718
719 //validate access for all cases.
720 if ($allCases && !CRM_Core_Permission::check('access all cases and activities')) {
721 $allCases = FALSE;
722 }
723
724 $caseTypes = CRM_Case_PseudoConstant::caseType();
725 $caseStatuses = CRM_Case_PseudoConstant::caseStatus();
726 $caseTypes = array_flip($caseTypes);
727
728 // get statuses as headers for the table
729 $url = CRM_Utils_System::url('civicrm/case/search', "reset=1&force=1&all=1&status=");
730 foreach ($caseStatuses as $key => $name) {
731 $caseSummary['headers'][$key]['status'] = $name;
732 $caseSummary['headers'][$key]['url'] = $url . $key;
733 }
734
735 // build rows with actual data
736 $rows = array();
737 $myGroupByClause = $mySelectClause = $myCaseFromClause = $myCaseWhereClause = '';
738
739 if ($allCases) {
740 $userID = 'null';
741 $all = 1;
742 $case_owner = 1;
743 $myGroupByClause = ' GROUP BY civicrm_case.id';
744 }
745 else {
746 $all = 0;
747 $case_owner = 2;
748 $myCaseWhereClause = " AND case_relationship.contact_id_b = {$userID}";
749 $myGroupByClause = " GROUP BY CONCAT(case_relationship.case_id,'-',case_relationship.contact_id_b)";
750 }
751 $myGroupByClause .= ", case_status.label, status_id, case_type_id";
752
753 // FIXME: This query could be a lot more efficient if it used COUNT() instead of returning all rows and then counting them with php
754 $query = "
755 SELECT case_status.label AS case_status, status_id, civicrm_case_type.title AS case_type,
756 case_type_id, case_relationship.contact_id_b
757 FROM civicrm_case
758 INNER JOIN civicrm_case_contact cc on cc.case_id = civicrm_case.id
759 LEFT JOIN civicrm_case_type ON civicrm_case.case_type_id = civicrm_case_type.id
760 LEFT JOIN civicrm_option_group option_group_case_status ON ( option_group_case_status.name = 'case_status' )
761 LEFT JOIN civicrm_option_value case_status ON ( civicrm_case.status_id = case_status.value
762 AND option_group_case_status.id = case_status.option_group_id )
763 LEFT JOIN civicrm_relationship case_relationship ON ( case_relationship.case_id = civicrm_case.id
764 AND case_relationship.contact_id_b = {$userID})
765 WHERE is_deleted = 0 AND cc.contact_id IN (SELECT id FROM civicrm_contact WHERE is_deleted <> 1)
766 {$myCaseWhereClause} {$myGroupByClause}";
767
768 $res = CRM_Core_DAO::executeQuery($query);
769 while ($res->fetch()) {
770 if (!empty($rows[$res->case_type]) && !empty($rows[$res->case_type][$res->case_status])) {
771 $rows[$res->case_type][$res->case_status]['count'] = $rows[$res->case_type][$res->case_status]['count'] + 1;
772 }
773 else {
774 $rows[$res->case_type][$res->case_status] = array(
775 'count' => 1,
776 'url' => CRM_Utils_System::url('civicrm/case/search',
777 "reset=1&force=1&status={$res->status_id}&type={$res->case_type_id}&case_owner={$case_owner}"
778 ),
779 );
780 }
781 }
782 $caseSummary['rows'] = array_merge($caseTypes, $rows);
783
784 return $caseSummary;
785 }
786
787 /**
788 * Get Case roles.
789 *
790 * @param int $contactID
791 * Contact id.
792 * @param int $caseID
793 * Case id.
794 * @param int $relationshipID
795 *
796 * @return array
797 * case role / relationships
798 *
799 */
800 public static function getCaseRoles($contactID, $caseID, $relationshipID = NULL) {
801 $query = '
802 SELECT rel.id as civicrm_relationship_id,
803 con.sort_name as sort_name,
804 civicrm_email.email as email,
805 civicrm_phone.phone as phone,
806 con.id as civicrm_contact_id,
807 IF(rel.contact_id_a = %1, civicrm_relationship_type.label_a_b, civicrm_relationship_type.label_b_a) as relation,
808 civicrm_relationship_type.id as relation_type,
809 IF(rel.contact_id_a = %1, "a_b", "b_a") as relationship_direction
810 FROM civicrm_relationship rel
811 INNER JOIN civicrm_relationship_type ON rel.relationship_type_id = civicrm_relationship_type.id
812 INNER JOIN civicrm_contact con ON ((con.id <> %1 AND con.id IN (rel.contact_id_a, rel.contact_id_b)) OR (con.id = %1 AND rel.contact_id_b = rel.contact_id_a AND rel.contact_id_a = %1))
813 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = con.id AND civicrm_phone.is_primary = 1)
814 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = con.id AND civicrm_email.is_primary = 1)
815 WHERE (rel.contact_id_a = %1 OR rel.contact_id_b = %1) AND rel.case_id = %2
816 AND rel.is_active = 1 AND (rel.end_date IS NULL OR rel.end_date > NOW())';
817
818 $params = array(
819 1 => array($contactID, 'Positive'),
820 2 => array($caseID, 'Positive'),
821 );
822
823 if ($relationshipID) {
824 $query .= ' AND civicrm_relationship.id = %3 ';
825 $params[3] = array($relationshipID, 'Integer');
826 }
827 $dao = CRM_Core_DAO::executeQuery($query, $params);
828
829 $values = array();
830 while ($dao->fetch()) {
831 $rid = $dao->civicrm_relationship_id;
832 $values[$rid]['cid'] = $dao->civicrm_contact_id;
833 $values[$rid]['relation'] = $dao->relation;
834 $values[$rid]['name'] = $dao->sort_name;
835 $values[$rid]['email'] = $dao->email;
836 $values[$rid]['phone'] = $dao->phone;
837 $values[$rid]['relation_type'] = $dao->relation_type;
838 $values[$rid]['rel_id'] = $dao->civicrm_relationship_id;
839 $values[$rid]['client_id'] = $contactID;
840 $values[$rid]['relationship_direction'] = $dao->relationship_direction;
841 }
842
843 $dao->free();
844 return $values;
845 }
846
847 /**
848 * Get Case Activities.
849 *
850 * @param int $caseID
851 * Case id.
852 * @param array $params
853 * Posted params.
854 * @param int $contactID
855 * Contact id.
856 *
857 * @param null $context
858 * @param int $userID
859 * @param null $type
860 *
861 * @return array
862 * Array of case activities
863 *
864 */
865 public static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL) {
866 $values = array();
867
868 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
869 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
870 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
871 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
872
873 // CRM-5081 - formatting the dates to omit seconds.
874 // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
875 $select = "
876 SELECT SQL_CALC_FOUND_ROWS COUNT(ca.id) AS ismultiple,
877 ca.id AS id,
878 ca.activity_type_id AS type,
879 ca.activity_type_id AS activity_type_id,
880 tcc.sort_name AS target_contact_name,
881 tcc.id AS target_contact_id,
882 scc.sort_name AS source_contact_name,
883 scc.id AS source_contact_id,
884 acc.sort_name AS assignee_contact_name,
885 acc.id AS assignee_contact_id,
886 DATE_FORMAT(
887 IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,
888 ca.activity_date_time,
889 DATE_ADD(NOW(), INTERVAL 1 YEAR)
890 ), '%Y%m%d%H%i00') AS overdue_date,
891 DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') AS display_date,
892 ca.status_id AS status,
893 ca.subject AS subject,
894 ca.is_deleted AS deleted,
895 ca.priority_id AS priority,
896 ca.weight AS weight,
897 GROUP_CONCAT(ef.file_id) AS attachment_ids ";
898
899 $from = "
900 FROM civicrm_case_activity cca
901 INNER JOIN civicrm_activity ca
902 ON ca.id = cca.activity_id
903 INNER JOIN civicrm_activity_contact cas
904 ON cas.activity_id = ca.id
905 AND cas.record_type_id = {$sourceID}
906 INNER JOIN civicrm_contact scc
907 ON scc.id = cas.contact_id
908 LEFT JOIN civicrm_activity_contact caa
909 ON caa.activity_id = ca.id
910 AND caa.record_type_id = {$assigneeID}
911 LEFT JOIN civicrm_contact acc
912 ON acc.id = caa.contact_id
913 LEFT JOIN civicrm_activity_contact cat
914 ON cat.activity_id = ca.id
915 AND cat.record_type_id = {$targetID}
916 LEFT JOIN civicrm_contact tcc
917 ON tcc.id = cat.contact_id
918 INNER JOIN civicrm_option_group cog
919 ON cog.name = 'activity_type'
920 INNER JOIN civicrm_option_value cov
921 ON cov.option_group_id = cog.id
922 AND cov.value = ca.activity_type_id
923 AND cov.is_active = 1
924 LEFT JOIN civicrm_entity_file ef
925 ON ef.entity_table = 'civicrm_activity'
926 AND ef.entity_id = ca.id
927 LEFT OUTER JOIN civicrm_option_group og
928 ON og.name = 'activity_status'
929 LEFT OUTER JOIN civicrm_option_value ov
930 ON ov.option_group_id=og.id
931 AND ov.name = 'Scheduled'";
932
933 $where = '
934 WHERE cca.case_id= %1
935 AND ca.is_current_revision = 1';
936
937 if (!empty($params['source_contact_id'])) {
938 $where .= "
939 AND cas.contact_id = " . CRM_Utils_Type::escape($params['source_contact_id'], 'Integer');
940 }
941
942 if (!empty($params['status_id'])) {
943 $where .= "
944 AND ca.status_id = " . CRM_Utils_Type::escape($params['status_id'], 'Integer');
945 }
946
947 if (!empty($params['activity_deleted'])) {
948 $where .= "
949 AND ca.is_deleted = 1";
950 }
951 else {
952 $where .= "
953 AND ca.is_deleted = 0";
954 }
955
956 if (!empty($params['activity_type_id'])) {
957 $where .= "
958 AND ca.activity_type_id = " . CRM_Utils_Type::escape($params['activity_type_id'], 'Integer');
959 }
960
961 if (!empty($params['activity_date_low'])) {
962 $fromActivityDate = CRM_Utils_Type::escape(CRM_Utils_Date::processDate($params['activity_date_low']), 'Date');
963 }
964 if (!empty($fromActivityDate)) {
965 $where .= "
966 AND ca.activity_date_time >= '{$fromActivityDate}'";
967 }
968
969 if (!empty($params['activity_date_high'])) {
970 $toActivityDate = CRM_Utils_Type::escape(CRM_Utils_Date::processDate($params['activity_date_high']), 'Date');
971 $toActivityDate = $toActivityDate ? $toActivityDate + 235959 : NULL;
972 }
973 if (!empty($toActivityDate)) {
974 $where .= "
975 AND ca.activity_date_time <= '{$toActivityDate}'";
976 }
977
978 $groupBy = "
979 GROUP BY ca.id, tcc.id, scc.id, acc.id, ov.value";
980
981 $sortBy = CRM_Utils_Array::value('sortBy', $params);
982 if (!$sortBy) {
983 // CRM-5081 - added id to act like creation date
984 $orderBy = "
985 ORDER BY overdue_date ASC, display_date DESC, weight DESC";
986 }
987 else {
988 $sortBy = CRM_Utils_Type::escape($sortBy, 'String');
989 $orderBy = " ORDER BY $sortBy ";
990 }
991
992 $page = CRM_Utils_Array::value('page', $params);
993 $rp = CRM_Utils_Array::value('rp', $params);
994
995 if (!$page) {
996 $page = 1;
997 }
998 if (!$rp) {
999 $rp = 10;
1000 }
1001 $start = (($page - 1) * $rp);
1002 $limit = " LIMIT $start, $rp";
1003
1004 $query = $select . $from . $where . $groupBy . $orderBy . $limit;
1005 $queryParams = array(1 => array($caseID, 'Integer'));
1006
1007 $dao = CRM_Core_DAO::executeQuery($query, $queryParams);
1008 $caseCount = CRM_Core_DAO::singleValueQuery('SELECT FOUND_ROWS()');
1009
1010 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
1011 $activityStatuses = CRM_Core_PseudoConstant::activityStatus();
1012
1013 $url = CRM_Utils_System::url("civicrm/case/activity",
1014 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1015 );
1016
1017 $contextUrl = '';
1018 if ($context == 'fulltext') {
1019 $contextUrl = "&context={$context}";
1020 }
1021 $editUrl = "{$url}&action=update{$contextUrl}";
1022 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1023 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1024 $viewTitle = ts('View activity');
1025
1026 $emailActivityTypeIDs = array(
1027 'Email' => CRM_Core_OptionGroup::getValue('activity_type',
1028 'Email',
1029 'name'
1030 ),
1031 'Inbound Email' => CRM_Core_OptionGroup::getValue('activity_type',
1032 'Inbound Email',
1033 'name'
1034 ),
1035 );
1036
1037 $caseDeleted = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1038
1039 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1040 $compStatusValues = array();
1041 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1042 foreach ($compStatusNames as $name) {
1043 $compStatusValues[] = CRM_Core_OptionGroup::getValue('activity_status', $name, 'name');
1044 }
1045
1046 $contactViewUrl = CRM_Utils_System::url("civicrm/contact/view", "reset=1&cid=", FALSE, NULL, FALSE);
1047 $hasViewContact = CRM_Core_Permission::giveMeAllACLs();
1048 $clientIds = self::retrieveContactIdsByCaseId($caseID);
1049
1050 if (!$userID) {
1051 $session = CRM_Core_Session::singleton();
1052 $userID = $session->get('userID');
1053 }
1054
1055 $caseActivities = array();
1056
1057 while ($dao->fetch()) {
1058 $caseActivity = array();
1059 $caseActivityId = $dao->id;
1060
1061 $allowView = self::checkPermission($caseActivityId, 'view', $dao->activity_type_id, $userID);
1062 $allowEdit = self::checkPermission($caseActivityId, 'edit', $dao->activity_type_id, $userID);
1063 $allowDelete = self::checkPermission($caseActivityId, 'delete', $dao->activity_type_id, $userID);
1064
1065 //do not have sufficient permission
1066 //to access given case activity record.
1067 if (!$allowView && !$allowEdit && !$allowDelete) {
1068 continue;
1069 }
1070
1071 $caseActivity['DT_RowId'] = $caseActivityId;
1072 //Add classes to the row, via DataTables syntax
1073 $caseActivity['DT_RowClass'] = "crm-entity status-id-$dao->status";
1074
1075 if (CRM_Utils_Array::crmInArray($dao->status, $compStatusValues)) {
1076 $caseActivity['DT_RowClass'] .= " status-completed";
1077 }
1078 else {
1079 if (CRM_Utils_Date::overdue($dao->display_date)) {
1080 $caseActivity['DT_RowClass'] .= " status-overdue";
1081 }
1082 else {
1083 $caseActivity['DT_RowClass'] .= " status-scheduled";
1084 }
1085 }
1086
1087 if (!empty($dao->priority)) {
1088 if ($dao->priority == CRM_Core_OptionGroup::getValue('priority', 'Urgent', 'name')) {
1089 $caseActivity['DT_RowClass'] .= " priority-urgent ";
1090 }
1091 elseif ($dao->priority == CRM_Core_OptionGroup::getValue('priority', 'Low', 'name')) {
1092 $caseActivity['DT_RowClass'] .= " priority-low ";
1093 }
1094 }
1095
1096 //Add data to the row for inline editing, via DataTable syntax
1097 $caseActivity['DT_RowAttr'] = array();
1098 $caseActivity['DT_RowAttr']['data-entity'] = 'activity';
1099 $caseActivity['DT_RowAttr']['data-id'] = $caseActivityId;
1100
1101 //Activity Date and Time
1102 $caseActivity['activity_date_time'] = CRM_Utils_Date::customFormat($dao->display_date);
1103
1104 //Activity Subject
1105 $caseActivity['subject'] = $dao->subject;
1106
1107 //Activity Type
1108 $caseActivity['type'] = (!empty($activityTypes[$dao->type]['icon']) ? '<span class="crm-i ' . $activityTypes[$dao->type]['icon'] . '"></span> ' : '')
1109 . $activityTypes[$dao->type]['label'];
1110
1111 //Activity Target (With)
1112 $targetContact = '';
1113 if (isset($dao->target_contact_id)) {
1114 $targetContact = $dao->target_contact_name;
1115 if ($hasViewContact) {
1116 $targetContact = '<a href="' . $contactViewUrl . $dao->target_contact_id . '">' . $dao->target_contact_name . '</a>';
1117 }
1118 }
1119 $caseActivity['target_contact_name'] = $targetContact;
1120
1121 //Activity Source Contact (Reporter)
1122 $sourceContact = $dao->source_contact_name;
1123 if ($hasViewContact) {
1124 $sourceContact = '<a href="' . $contactViewUrl . $dao->source_contact_id . '">' . $dao->source_contact_name . '</a>';
1125 }
1126 $caseActivity['source_contact_name'] = $sourceContact;
1127
1128 //Activity Assignee. CRM-4485.
1129 $assigneeContact = '';
1130 if (isset($dao->assignee_contact_id)) {
1131 $assigneeContact = $dao->assignee_contact_name;
1132 if ($hasViewContact) {
1133 $assigneeContact = '<a href="' . $contactViewUrl . $dao->assignee_contact_id . '">' . $dao->assignee_contact_name . '</a>';
1134 }
1135 }
1136 $caseActivity['assignee_contact_name'] = $assigneeContact;
1137
1138 //Activity Status
1139 $caseActivity['status_id'] = $activityStatuses[$dao->status];
1140
1141 // FIXME: Why are we not using CRM_Core_Action for these links? This is too much manual work and likely to get out-of-sync with core markup.
1142 $url = "";
1143 $css = 'class="action-item crm-hover-button"';
1144 if ($allowView) {
1145 $viewUrl = CRM_Utils_System::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $caseActivityId));
1146 $url = '<a ' . str_replace('action-item', 'action-item medium-pop-up', $css) . 'href="' . $viewUrl . '" title="' . $viewTitle . '">' . ts('View') . '</a>';
1147 }
1148 $additionalUrl = "&id={$caseActivityId}";
1149 if (!$dao->deleted) {
1150 //hide edit link of activity type email.CRM-4530.
1151 if (!in_array($dao->type, $emailActivityTypeIDs)) {
1152 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1153 if ($allowEdit) {
1154 $url .= '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1155 }
1156 }
1157 if ($allowDelete) {
1158 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1159 }
1160 }
1161 elseif (!$caseDeleted) {
1162 $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1163 $caseActivity['status_id'] = $caseActivity['status_id'] . '<br /> (deleted)';
1164 }
1165
1166 //check for operations.
1167 if (self::checkPermission($caseActivityId, 'Move To Case', $dao->activity_type_id)) {
1168 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $caseActivityId . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
1169 }
1170 if (self::checkPermission($caseActivityId, 'Copy To Case', $dao->activity_type_id)) {
1171 $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $caseActivityId . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
1172 }
1173 // if there are file attachments we will return how many and, if only one, add a link to it
1174 if (!empty($dao->attachment_ids)) {
1175 $attachmentIDs = array_unique(explode(',', $dao->attachment_ids));
1176 $caseActivity['no_attachments'] = count($attachmentIDs);
1177 $url .= implode(' ', CRM_Core_BAO_File::paperIconAttachment('civicrm_activity', $caseActivityId));
1178 }
1179
1180 $caseActivity['links'] = $url;
1181
1182 array_push($caseActivities, $caseActivity);
1183 }
1184 $dao->free();
1185
1186 $caseActivitiesDT = array();
1187 $caseActivitiesDT['data'] = $caseActivities;
1188 $caseActivitiesDT['recordsTotal'] = $caseCount;
1189 $caseActivitiesDT['recordsFiltered'] = $caseCount;
1190
1191 return $caseActivitiesDT;
1192 }
1193
1194 /**
1195 * Get Case Related Contacts.
1196 *
1197 * @param int $caseID
1198 * Case id.
1199 * @param bool $includeDetails
1200 * If true include details of contacts.
1201 *
1202 * @return array
1203 * array of return properties
1204 *
1205 */
1206 public static function getRelatedContacts($caseID, $includeDetails = TRUE) {
1207 $caseRoles = array();
1208 if ($includeDetails) {
1209 $caseInfo = civicrm_api3('Case', 'getsingle', array(
1210 'id' => $caseID,
1211 // Most efficient way of retrieving definition is to also include case type id and name so the api doesn't have to look it up separately
1212 'return' => array('case_type_id', 'case_type_id.name', 'case_type_id.definition'),
1213 ));
1214 if (!empty($caseInfo['case_type_id.definition']['caseRoles'])) {
1215 $caseRoles = CRM_Utils_Array::rekey($caseInfo['case_type_id.definition']['caseRoles'], 'name');
1216 }
1217 }
1218 $values = array();
1219 $query = '
1220 SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, cr.relationship_type_id, crt.label_b_a as role, crt.name_b_a, ce.email, cp.phone
1221 FROM civicrm_relationship cr
1222 LEFT JOIN civicrm_relationship_type crt
1223 ON crt.id = cr.relationship_type_id
1224 LEFT JOIN civicrm_contact cc
1225 ON cc.id = cr.contact_id_b
1226 LEFT JOIN civicrm_email ce
1227 ON ce.contact_id = cc.id
1228 AND ce.is_primary= 1
1229 LEFT JOIN civicrm_phone cp
1230 ON cp.contact_id = cc.id
1231 AND cp.is_primary= 1
1232 WHERE cr.case_id = %1 AND cr.is_active AND cc.is_deleted <> 1';
1233
1234 $params = array(1 => array($caseID, 'Integer'));
1235 $dao = CRM_Core_DAO::executeQuery($query, $params);
1236
1237 while ($dao->fetch()) {
1238 if (!$includeDetails) {
1239 $values[$dao->id] = 1;
1240 }
1241 else {
1242 $details = array(
1243 'contact_id' => $dao->id,
1244 'display_name' => $dao->name,
1245 'sort_name' => $dao->sort_name,
1246 'relationship_type_id' => $dao->relationship_type_id,
1247 'role' => $dao->role,
1248 'email' => $dao->email,
1249 'phone' => $dao->phone,
1250 );
1251 // Add more info about the role (creator, manager)
1252 $role = CRM_Utils_Array::value($dao->name_b_a, $caseRoles);
1253 if ($role) {
1254 unset($role['name']);
1255 $details += $role;
1256 }
1257 $values[] = $details;
1258 }
1259 }
1260 $dao->free();
1261
1262 return $values;
1263 }
1264
1265 /**
1266 * Send e-mail copy of activity
1267 *
1268 * @param int $clientId
1269 * @param int $activityId
1270 * Activity Id.
1271 * @param array $contacts
1272 * Array of related contact.
1273 *
1274 * @param null $attachments
1275 * @param int $caseId
1276 *
1277 * @return bool |array
1278 */
1279 public static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1280 if (!$activityId) {
1281 return FALSE;
1282 }
1283
1284 $tplParams = $activityInfo = array();
1285 //if its a case activity
1286 if ($caseId) {
1287 $activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1288 $nonCaseActivityTypes = CRM_Core_PseudoConstant::activityType();
1289 if (!empty($nonCaseActivityTypes[$activityTypeId])) {
1290 $anyActivity = TRUE;
1291 }
1292 else {
1293 $anyActivity = FALSE;
1294 }
1295 $tplParams['isCaseActivity'] = 1;
1296 $tplParams['client_id'] = $clientId;
1297 }
1298 else {
1299 $anyActivity = TRUE;
1300 }
1301
1302 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1303 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1304
1305 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1306
1307 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1308 if ($caseId) {
1309 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1310 }
1311 $tplParams['activity'] = $activityInfo;
1312 foreach ($tplParams['activity']['fields'] as $k => $val) {
1313 if (CRM_Utils_Array::value('label', $val) == ts('Subject')) {
1314 $activitySubject = $val['value'];
1315 break;
1316 }
1317 }
1318 $session = CRM_Core_Session::singleton();
1319 // CRM-8926 If user is not logged in, use the activity creator as userID
1320 if (!($userID = $session->get('userID'))) {
1321 $userID = CRM_Activity_BAO_Activity::getSourceContactID($activityId);
1322 }
1323
1324 //also create activities simultaneously of this copy.
1325 $activityParams = array();
1326
1327 $activityParams['source_record_id'] = $activityId;
1328 $activityParams['source_contact_id'] = $userID;
1329 $activityParams['activity_type_id'] = CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name');
1330 $activityParams['activity_date_time'] = date('YmdHis');
1331 $activityParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
1332 $activityParams['medium_id'] = CRM_Core_OptionGroup::getValue('encounter_medium', 'email', 'name');
1333 $activityParams['case_id'] = $caseId;
1334 $activityParams['is_auto'] = 0;
1335 $activityParams['target_id'] = $clientId;
1336
1337 $tplParams['activitySubject'] = $activitySubject;
1338
1339 // if it’s a case activity, add hashed id to the template (CRM-5916)
1340 if ($caseId) {
1341 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY . $caseId), 0, 7);
1342 }
1343
1344 $result = array();
1345 // CRM-20308 get receiptFrom defaults see https://issues.civicrm.org/jira/browse/CRM-20308
1346 $receiptFrom = self::getReceiptFrom($activityId);
1347
1348 $recordedActivityParams = array();
1349
1350 foreach ($contacts as $mail => $info) {
1351 $tplParams['contact'] = $info;
1352 self::buildPermissionLinks($tplParams, $activityParams);
1353
1354 $displayName = CRM_Utils_Array::value('display_name', $info);
1355
1356 list($result[CRM_Utils_Array::value('contact_id', $info)], $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
1357 array(
1358 'groupName' => 'msg_tpl_workflow_case',
1359 'valueName' => 'case_activity',
1360 'contactId' => CRM_Utils_Array::value('contact_id', $info),
1361 'tplParams' => $tplParams,
1362 'from' => $receiptFrom,
1363 'toName' => $displayName,
1364 'toEmail' => $mail,
1365 'attachments' => $attachments,
1366 )
1367 );
1368
1369 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1370 $activityParams['details'] = $message;
1371
1372 if (!empty($result[$info['contact_id']])) {
1373 /*
1374 * Really only need to record one activity with all the targets combined.
1375 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1376 * but it's always the same content at the moment.
1377 */
1378 if (empty($recordedActivityParams)) {
1379 $recordedActivityParams = $activityParams;
1380 }
1381 else {
1382 $recordedActivityParams['subject'] .= "; $displayName";
1383 }
1384 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1385 }
1386 else {
1387 unset($result[CRM_Utils_Array::value('contact_id', $info)]);
1388 }
1389 }
1390
1391 if (!empty($recordedActivityParams)) {
1392 $activity = CRM_Activity_BAO_Activity::create($recordedActivityParams);
1393
1394 //create case_activity record if its case activity.
1395 if ($caseId) {
1396 $caseParams = array(
1397 'activity_id' => $activity->id,
1398 'case_id' => $caseId,
1399 );
1400 self::processCaseActivity($caseParams);
1401 }
1402 }
1403
1404 return $result;
1405 }
1406
1407 /**
1408 * Retrieve count of activities having a particular type, and
1409 * associated with a particular case.
1410 *
1411 * @param int $caseId
1412 * ID of the case.
1413 * @param int $activityTypeId
1414 * ID of the activity type.
1415 *
1416 * @return array
1417 */
1418 public static function getCaseActivityCount($caseId, $activityTypeId) {
1419 $queryParam = array(
1420 1 => array($caseId, 'Integer'),
1421 2 => array($activityTypeId, 'Integer'),
1422 );
1423 $query = "SELECT count(ca.id) as countact
1424 FROM civicrm_activity ca
1425 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1426 WHERE ca.activity_type_id = %2
1427 AND cca.case_id = %1
1428 AND ca.is_deleted = 0";
1429
1430 $dao = CRM_Core_DAO::executeQuery($query, $queryParam);
1431 if ($dao->fetch()) {
1432 return $dao->countact;
1433 }
1434
1435 return FALSE;
1436 }
1437
1438 /**
1439 * Create an activity for a case via email.
1440 *
1441 * @param int $file
1442 * Email sent.
1443 *
1444 * @return array|void
1445 * $activity object of newly creted activity via email
1446 */
1447 public static function recordActivityViaEmail($file) {
1448 if (!file_exists($file) ||
1449 !is_readable($file)
1450 ) {
1451 return CRM_Core_Error::fatal(ts('File %1 does not exist or is not readable',
1452 array(1 => $file)
1453 ));
1454 }
1455
1456 $result = CRM_Utils_Mail_Incoming::parse($file);
1457 if ($result['is_error']) {
1458 return $result;
1459 }
1460
1461 foreach ($result['to'] as $to) {
1462 $caseId = NULL;
1463
1464 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1465 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1466
1467 if ($replacement !== $to['email']) {
1468 $caseId = $replacement;
1469 //if caseId is invalid, return as error file
1470 if (!CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1471 return CRM_Core_Error::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1472 array(1 => $caseId)
1473 ));
1474 }
1475 }
1476 else {
1477 continue;
1478 }
1479
1480 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1481 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1482 $contactDetails = self::getRelatedContacts($caseId, FALSE);
1483
1484 if (!empty($contactDetails[$result['from']['id']])) {
1485 $params = array();
1486 $params['subject'] = $result['subject'];
1487 $params['activity_date_time'] = $result['date'];
1488 $params['details'] = $result['body'];
1489 $params['source_contact_id'] = $result['from']['id'];
1490 $params['status_id'] = CRM_Core_OptionGroup::getValue('activity_status',
1491 'Completed',
1492 'name'
1493 );
1494
1495 $details = CRM_Case_PseudoConstant::caseActivityType();
1496 $matches = array();
1497 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1498 $result['body'], $matches
1499 );
1500
1501 if (!empty($matches) && isset($matches[1])) {
1502 $activityType = trim($matches[1]);
1503 if (isset($details[$activityType])) {
1504 $params['activity_type_id'] = $details[$activityType]['id'];
1505 }
1506 }
1507 if (!isset($params['activity_type_id'])) {
1508 $params['activity_type_id'] = CRM_Core_OptionGroup::getValue('activity_type', 'Inbound Email', 'name');
1509 }
1510
1511 // create activity
1512 $activity = CRM_Activity_BAO_Activity::create($params);
1513
1514 $caseParams = array(
1515 'activity_id' => $activity->id,
1516 'case_id' => $caseId,
1517 );
1518 self::processCaseActivity($caseParams);
1519 }
1520 else {
1521 return CRM_Core_Error::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1522 array(1 => $result['from']['email'])
1523 ));
1524 }
1525 }
1526 }
1527
1528 /**
1529 * Retrieve the scheduled activity type and date.
1530 *
1531 * @param array $cases
1532 * Array of contact and case id.
1533 *
1534 * @param string $type
1535 *
1536 * @return array
1537 * Array of scheduled activity type and date
1538 *
1539 *
1540 */
1541 public static function getNextScheduledActivity($cases, $type = 'upcoming') {
1542 $session = CRM_Core_Session::singleton();
1543 $userID = $session->get('userID');
1544
1545 $caseID = implode(',', $cases['case_id']);
1546 $contactID = implode(',', $cases['contact_id']);
1547
1548 $condition = "
1549 AND civicrm_case_contact.contact_id IN( {$contactID} )
1550 AND civicrm_case.id IN( {$caseID})
1551 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1552
1553 $query = self::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1554
1555 $res = CRM_Core_DAO::executeQuery($query);
1556
1557 $activityInfo = array();
1558 while ($res->fetch()) {
1559 if ($type == 'upcoming') {
1560 $activityInfo[$res->case_id]['date'] = $res->case_scheduled_activity_date;
1561 $activityInfo[$res->case_id]['type'] = $res->case_scheduled_activity_type;
1562 }
1563 else {
1564 $activityInfo[$res->case_id]['date'] = $res->case_recent_activity_date;
1565 $activityInfo[$res->case_id]['type'] = $res->case_recent_activity_type;
1566 }
1567 }
1568
1569 return $activityInfo;
1570 }
1571
1572 /**
1573 * Combine all the exportable fields from the lower levels object.
1574 *
1575 * @return array
1576 * array of exportable Fields
1577 */
1578 public static function &exportableFields() {
1579 if (!self::$_exportableFields) {
1580 if (!self::$_exportableFields) {
1581 self::$_exportableFields = array();
1582 }
1583
1584 $fields = CRM_Case_DAO_Case::export();
1585 $fields['case_role'] = array('title' => ts('Role in Case'));
1586 $fields['case_type'] = array(
1587 'title' => ts('Case Type'),
1588 'name' => 'case_type',
1589 );
1590 $fields['case_status'] = array(
1591 'title' => ts('Case Status'),
1592 'name' => 'case_status',
1593 );
1594
1595 // add custom data for cases
1596 $fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Case'));
1597
1598 self::$_exportableFields = $fields;
1599 }
1600 return self::$_exportableFields;
1601 }
1602
1603 /**
1604 * Restore the record that are associated with this case.
1605 *
1606 * @param int $caseId
1607 * Id of the case to restore.
1608 *
1609 * @return bool
1610 */
1611 public static function restoreCase($caseId) {
1612 //restore activities
1613 $activities = self::getCaseActivityDates($caseId);
1614 if ($activities) {
1615 foreach ($activities as $value) {
1616 CRM_Activity_BAO_Activity::restoreActivity($value);
1617 }
1618 }
1619 //restore case
1620 $case = new CRM_Case_DAO_Case();
1621 $case->id = $caseId;
1622 $case->is_deleted = 0;
1623 $case->save();
1624
1625 //CRM-7364, enable relationships
1626 self::enableDisableCaseRelationships($caseId, TRUE);
1627 return TRUE;
1628 }
1629
1630 /**
1631 * @param $groupInfo
1632 * @param null $sort
1633 * @param null $showLinks
1634 * @param bool $returnOnlyCount
1635 * @param int $offset
1636 * @param int $rowCount
1637 *
1638 * @return array
1639 */
1640 public static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1641 $globalContacts = array();
1642
1643 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1644 $settings = $settingsProcessor->run();
1645 if (!empty($settings)) {
1646 $groupInfo['name'] = $settings['groupname'];
1647 if ($groupInfo['name']) {
1648 $searchParams = array('name' => $groupInfo['name']);
1649 $results = array();
1650 CRM_Contact_BAO_Group::retrieve($searchParams, $results);
1651 if ($results) {
1652 $groupInfo['id'] = $results['id'];
1653 $groupInfo['title'] = $results['title'];
1654 $params = array(array('group', '=', $groupInfo['id'], 0, 0));
1655 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1656 list($globalContacts) = CRM_Contact_BAO_Query::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1657
1658 if ($returnOnlyCount) {
1659 return $globalContacts;
1660 }
1661
1662 if ($showLinks) {
1663 foreach ($globalContacts as $idx => $contact) {
1664 $globalContacts[$idx]['sort_name'] = '<a href="' . CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$contact['contact_id']}") . '">' . $contact['sort_name'] . '</a>';
1665 }
1666 }
1667 }
1668 }
1669 }
1670 return $globalContacts;
1671 }
1672
1673 /**
1674 * Convenience function to get both case contacts and global in one array.
1675 * @param int $caseId
1676 *
1677 * @return array
1678 */
1679 public static function getRelatedAndGlobalContacts($caseId) {
1680 $relatedContacts = self::getRelatedContacts($caseId);
1681
1682 $groupInfo = array();
1683 $globalContacts = self::getGlobalContacts($groupInfo);
1684
1685 //unset values which are not required.
1686 foreach ($globalContacts as $k => & $v) {
1687 unset($v['email_id']);
1688 unset($v['group_contact_id']);
1689 unset($v['status']);
1690 unset($v['phone']);
1691 $v['role'] = $groupInfo['title'];
1692 }
1693 //include multiple listings for the same contact/different roles.
1694 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1695 return $relatedGlobalContacts;
1696 }
1697
1698 /**
1699 * Get Case ActivitiesDueDates with given criteria.
1700 *
1701 * @param int $caseID
1702 * Case id.
1703 * @param array $criteriaParams
1704 * Given criteria.
1705 * @param bool $latestDate
1706 * If set newest or oldest date is selected.
1707 *
1708 * @return array
1709 * case activities due dates
1710 *
1711 */
1712 public static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1713 $values = array();
1714 $selectDate = " ca.activity_date_time";
1715 $where = $groupBy = ' ';
1716
1717 if (!$caseID) {
1718 return NULL;
1719 }
1720
1721 if ($latestDate) {
1722 if (!empty($criteriaParams['activity_type_id'])) {
1723 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type::escape($criteriaParams['activity_type_id'], 'Integer');
1724 $where .= " AND ca.is_current_revision = 1";
1725 $groupBy .= " GROUP BY ca.activity_type_id, ca.id";
1726 }
1727
1728 if (!empty($criteriaParams['newest'])) {
1729 $selectDate = " max(ca.activity_date_time) ";
1730 }
1731 else {
1732 $selectDate = " min(ca.activity_date_time) ";
1733 }
1734 }
1735
1736 $query = "SELECT ca.id, {$selectDate} as activity_date
1737 FROM civicrm_activity ca
1738 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1739 WHERE cc.id = %1 {$where} {$groupBy}";
1740
1741 $params = array(1 => array($caseID, 'Integer'));
1742 $dao = CRM_Core_DAO::executeQuery($query, $params);
1743
1744 while ($dao->fetch()) {
1745 $values[$dao->id]['id'] = $dao->id;
1746 $values[$dao->id]['activity_date'] = $dao->activity_date;
1747 }
1748 $dao->free();
1749 return $values;
1750 }
1751
1752 /**
1753 * Create activities when Case or Other roles assigned/modified/deleted.
1754 *
1755 * @param int $caseId
1756 * @param int $relationshipId
1757 * Relationship id.
1758 * @param int $relContactId
1759 * Case role assignee contactId.
1760 * @param int $contactId
1761 */
1762 public static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1763 if (!$caseId || !$relationshipId || empty($relationshipId)) {
1764 return;
1765 }
1766
1767 $queryParam = array();
1768 if (is_array($relationshipId)) {
1769 $relationshipId = implode(',', $relationshipId);
1770 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1771 }
1772 else {
1773 $relationshipClause = " civicrm_relationship.id = %1";
1774 $queryParam[1] = array($relationshipId, 'Positive');
1775 }
1776
1777 $query = "
1778 SELECT cc.display_name as clientName,
1779 cca.display_name as assigneeContactName,
1780 civicrm_relationship.case_id as caseId,
1781 civicrm_relationship_type.label_a_b as relation_a_b,
1782 civicrm_relationship_type.label_b_a as relation_b_a,
1783 civicrm_relationship.contact_id_b as rel_contact_id,
1784 civicrm_relationship.contact_id_a as assign_contact_id
1785 FROM civicrm_relationship_type, civicrm_relationship
1786 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1787 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1788 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1789
1790 $dao = CRM_Core_DAO::executeQuery($query, $queryParam);
1791
1792 while ($dao->fetch()) {
1793 // The assignee is not the client.
1794 if ($dao->rel_contact_id != $contactId) {
1795 $caseRelationship = $dao->relation_a_b;
1796 $assigneContactName = $dao->clientName;
1797 $assigneContactIds[$dao->rel_contact_id] = $dao->rel_contact_id;
1798 }
1799 else {
1800 $caseRelationship = $dao->relation_b_a;
1801 $assigneContactName = $dao->assigneeContactName;
1802 $assigneContactIds[$dao->assign_contact_id] = $dao->assign_contact_id;
1803 }
1804 }
1805
1806 $session = CRM_Core_Session::singleton();
1807 $activityParams = array(
1808 'source_contact_id' => $session->get('userID'),
1809 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1810 'activity_date_time' => date('YmdHis'),
1811 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'),
1812 );
1813
1814 //if $relContactId is passed, role is added or modified.
1815 if (!empty($relContactId)) {
1816 $activityParams['assignee_contact_id'] = $assigneContactIds;
1817
1818 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1819 'Assign Case Role',
1820 'name'
1821 );
1822 }
1823 else {
1824 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1825 'Remove Case Role',
1826 'name'
1827 );
1828 }
1829
1830 $activityParams['activity_type_id'] = $activityTypeID;
1831
1832 $activity = CRM_Activity_BAO_Activity::create($activityParams);
1833
1834 //create case_activity record.
1835 $caseParams = array(
1836 'activity_id' => $activity->id,
1837 'case_id' => $caseId,
1838 );
1839
1840 CRM_Case_BAO_Case::processCaseActivity($caseParams);
1841 }
1842
1843 /**
1844 * Get case manger
1845 * contact which is assigned a case role of case manager.
1846 *
1847 * @param int $caseType
1848 * Case type.
1849 * @param int $caseId
1850 * Case id.
1851 *
1852 * @return array
1853 * array of contact on success otherwise empty
1854 *
1855 */
1856 public static function getCaseManagerContact($caseType, $caseId) {
1857 if (!$caseType || !$caseId) {
1858 return NULL;
1859 }
1860
1861 $caseManagerContact = array();
1862 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1863
1864 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1865
1866 if (!empty($managerRoleId)) {
1867 $managerRoleQuery = "
1868 SELECT civicrm_contact.id as casemanager_id,
1869 civicrm_contact.sort_name as casemanager
1870 FROM civicrm_contact
1871 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1872 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1873 WHERE civicrm_case.id = %2 AND is_active = 1";
1874
1875 $managerRoleParams = array(
1876 1 => array($managerRoleId, 'Integer'),
1877 2 => array($caseId, 'Integer'),
1878 );
1879
1880 $dao = CRM_Core_DAO::executeQuery($managerRoleQuery, $managerRoleParams);
1881 if ($dao->fetch()) {
1882 $caseManagerContact['casemanager_id'] = $dao->casemanager_id;
1883 $caseManagerContact['casemanager'] = $dao->casemanager;
1884 }
1885 }
1886
1887 return $caseManagerContact;
1888 }
1889
1890 /**
1891 * @param int $contactId
1892 * @param bool $excludeDeleted
1893 *
1894 * @return int
1895 */
1896 public static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
1897 $params = array('check_permissions' => TRUE);
1898 if ($excludeDeleted) {
1899 $params['is_deleted'] = 0;
1900 }
1901 if ($contactId) {
1902 $params['contact_id'] = $contactId;
1903 }
1904 try {
1905 return civicrm_api3('Case', 'getcount', $params);
1906 }
1907 catch (CiviCRM_API3_Exception $e) {
1908 // Lack of permissions will throw an exception
1909 return 0;
1910 }
1911 }
1912
1913 /**
1914 * Retrieve related case ids for given case.
1915 *
1916 * @param int $caseId
1917 * @param bool $excludeDeleted
1918 * Do not include deleted cases.
1919 *
1920 * @return array
1921 */
1922 public static function getRelatedCaseIds($caseId, $excludeDeleted = TRUE) {
1923 //FIXME : do check for permissions.
1924
1925 if (!$caseId) {
1926 return array();
1927 }
1928
1929 $linkActType = array_search('Link Cases',
1930 CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name')
1931 );
1932 if (!$linkActType) {
1933 return array();
1934 }
1935
1936 $whereClause = "mainCase.id = %2";
1937 if ($excludeDeleted) {
1938 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
1939 }
1940
1941 $query = "
1942 SELECT relCaseAct.case_id
1943 FROM civicrm_case mainCase
1944 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
1945 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
1946 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
1947 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
1948 WHERE $whereClause";
1949
1950 $dao = CRM_Core_DAO::executeQuery($query, array(
1951 1 => array($linkActType, 'Integer'),
1952 2 => array($caseId, 'Integer'),
1953 ));
1954 $relatedCaseIds = array();
1955 while ($dao->fetch()) {
1956 $relatedCaseIds[$dao->case_id] = $dao->case_id;
1957 }
1958 $dao->free();
1959
1960 return array_values($relatedCaseIds);
1961 }
1962
1963 /**
1964 * Retrieve related case details for given case.
1965 *
1966 * @param int $caseId
1967 * @param bool $excludeDeleted
1968 * Do not include deleted cases.
1969 *
1970 * @return array
1971 */
1972 public static function getRelatedCases($caseId, $excludeDeleted = TRUE) {
1973 $relatedCaseIds = self::getRelatedCaseIds($caseId, $excludeDeleted);
1974 $relatedCases = array();
1975
1976 if (!$relatedCaseIds) {
1977 return array();
1978 }
1979
1980 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
1981 if ($excludeDeleted) {
1982 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
1983 }
1984
1985 //filter for permissioned cases.
1986 $filterCases = array();
1987 $doFilterCases = FALSE;
1988 if (!CRM_Core_Permission::check('access all cases and activities')) {
1989 $doFilterCases = TRUE;
1990 $session = CRM_Core_Session::singleton();
1991 $filterCases = CRM_Case_BAO_Case::getCases(FALSE, $session->get('userID'));
1992 }
1993
1994 //2. fetch the details of related cases.
1995 $query = "
1996 SELECT relCase.id as id,
1997 civicrm_case_type.title as case_type,
1998 client.display_name as client_name,
1999 client.id as client_id
2000 FROM civicrm_case relCase
2001 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2002 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2003 LEFT JOIN civicrm_case_type ON relCase.case_type_id = civicrm_case_type.id
2004 WHERE {$whereClause}";
2005
2006 $dao = CRM_Core_DAO::executeQuery($query);
2007 $contactViewUrl = CRM_Utils_System::url("civicrm/contact/view", "reset=1&cid=");
2008 $hasViewContact = CRM_Core_Permission::giveMeAllACLs();
2009
2010 while ($dao->fetch()) {
2011 $caseView = NULL;
2012 if (!$doFilterCases || array_key_exists($dao->id, $filterCases)) {
2013 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2014 $caseViewUrl = CRM_Utils_System::url("civicrm/contact/view/case", $caseViewStr);
2015 $caseView = "<a class='action-item no-popup crm-hover-button' href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2016 }
2017 $clientView = $dao->client_name;
2018 if ($hasViewContact) {
2019 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2020 }
2021
2022 $relatedCases[$dao->id] = array(
2023 'case_id' => $dao->id,
2024 'case_type' => $dao->case_type,
2025 'client_name' => $clientView,
2026 'links' => $caseView,
2027 );
2028 }
2029 $dao->free();
2030
2031 return $relatedCases;
2032 }
2033
2034 /**
2035 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2036 *
2037 * @see CRM_Dedupe_Merger::cpTables()
2038 *
2039 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2040 *
2041 * @param int $mainContactId
2042 * @param int $otherContactId
2043 */
2044 public static function mergeContacts($mainContactId, $otherContactId) {
2045 self::mergeCases($mainContactId, NULL, $otherContactId);
2046 }
2047
2048 /**
2049 * Function perform two task.
2050 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2051 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2052 *
2053 * @param int $mainContactId
2054 * Contact id of main contact record.
2055 * @param int $mainCaseId
2056 * Case id of main case record.
2057 * @param int $otherContactId
2058 * Contact id of record which is going to merge.
2059 * @param int $otherCaseId
2060 * Case id of record which is going to merge.
2061 *
2062 * @param bool $changeClient
2063 *
2064 * @return int|NULL
2065 */
2066 public static function mergeCases(
2067 $mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2068 $otherCaseId = NULL, $changeClient = FALSE) {
2069 $moveToTrash = TRUE;
2070
2071 $duplicateContacts = FALSE;
2072 if ($mainContactId && $otherContactId &&
2073 $mainContactId != $otherContactId
2074 ) {
2075 $duplicateContacts = TRUE;
2076 }
2077
2078 $duplicateCases = FALSE;
2079 if ($mainCaseId && $otherCaseId &&
2080 $mainCaseId != $otherCaseId
2081 ) {
2082 $duplicateCases = TRUE;
2083 }
2084
2085 $mainCaseIds = array();
2086 if (!$duplicateContacts && !$duplicateCases) {
2087 return $mainCaseIds;
2088 }
2089
2090 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name');
2091 $activityStatuses = CRM_Core_PseudoConstant::activityStatus('name');
2092 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2093 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2094 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2095 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2096
2097 $processCaseIds = array($otherCaseId);
2098 if ($duplicateContacts && !$duplicateCases) {
2099 if ($changeClient) {
2100 $processCaseIds = array($mainCaseId);
2101 }
2102 else {
2103 //get all case ids for other contact.
2104 $processCaseIds = self::retrieveCaseIdsByContactId($otherContactId, TRUE);
2105 }
2106 if (!is_array($processCaseIds)) {
2107 return;
2108 }
2109 }
2110
2111 $session = CRM_Core_Session::singleton();
2112 $currentUserId = $session->get('userID');
2113
2114 CRM_Utils_Hook::pre_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2115
2116 // copy all cases and connect to main contact id.
2117 foreach ($processCaseIds as $otherCaseId) {
2118 if ($duplicateContacts) {
2119 $mainCase = CRM_Core_DAO::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2120 $mainCaseId = $mainCase->id;
2121 if (!$mainCaseId) {
2122 continue;
2123 }
2124
2125 // CRM-11662 Copy Case custom data
2126 $extends = array('case');
2127 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
2128 if ($groupTree) {
2129 foreach ($groupTree as $groupID => $group) {
2130 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2131 foreach ($group['fields'] as $fieldID => $field) {
2132 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2133 }
2134 }
2135
2136 foreach ($table as $tableName => $tableColumns) {
2137 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2138 $tableColumns[0] = $mainCaseId;
2139 $select = 'SELECT ' . implode(', ', $tableColumns);
2140 $from = ' FROM ' . $tableName;
2141 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2142 $query = $insert . $select . $from . $where;
2143 $dao = CRM_Core_DAO::executeQuery($query);
2144 }
2145 }
2146
2147 $mainCase->free();
2148
2149 $mainCaseIds[] = $mainCaseId;
2150 //insert record for case contact.
2151 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2152 $otherCaseContact->case_id = $otherCaseId;
2153 $otherCaseContact->find();
2154 while ($otherCaseContact->fetch()) {
2155 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2156 $mainCaseContact->case_id = $mainCaseId;
2157 $mainCaseContact->contact_id = $otherCaseContact->contact_id;
2158 if ($mainCaseContact->contact_id == $otherContactId) {
2159 $mainCaseContact->contact_id = $mainContactId;
2160 }
2161 //avoid duplicate object.
2162 if (!$mainCaseContact->find(TRUE)) {
2163 $mainCaseContact->save();
2164 }
2165 $mainCaseContact->free();
2166 }
2167 $otherCaseContact->free();
2168 }
2169 elseif (!$otherContactId) {
2170 $otherContactId = $mainContactId;
2171 }
2172
2173 if (!$mainCaseId || !$otherCaseId ||
2174 !$mainContactId || !$otherContactId
2175 ) {
2176 continue;
2177 }
2178
2179 // get all activities for other case.
2180 $otherCaseActivities = array();
2181 CRM_Core_DAO::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2182
2183 //for duplicate cases do not process singleton activities.
2184 $otherActivityIds = $singletonActivityIds = array();
2185 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2186 $otherActId = CRM_Utils_Array::value('activity_id', $otherIds);
2187 if (!$otherActId || in_array($otherActId, $otherActivityIds)) {
2188 continue;
2189 }
2190 $otherActivityIds[] = $otherActId;
2191 }
2192 if ($duplicateCases) {
2193 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2194 $sql = "
2195 SELECT id
2196 FROM civicrm_activity
2197 WHERE activity_type_id = $openCaseType
2198 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2199 $dao = CRM_Core_DAO::executeQuery($sql);
2200 while ($dao->fetch()) {
2201 $singletonActivityIds[] = $dao->id;
2202 }
2203 $dao->free();
2204 }
2205 }
2206
2207 // migrate all activities and connect to main contact.
2208 $copiedActivityIds = $activityMappingIds = array();
2209 sort($otherActivityIds);
2210 foreach ($otherActivityIds as $otherActivityId) {
2211
2212 //for duplicate cases -
2213 //do not migrate singleton activities.
2214 if (!$otherActivityId || in_array($otherActivityId, $singletonActivityIds)) {
2215 continue;
2216 }
2217
2218 //migrate activity record.
2219 $otherActivity = new CRM_Activity_DAO_Activity();
2220 $otherActivity->id = $otherActivityId;
2221 if (!$otherActivity->find(TRUE)) {
2222 continue;
2223 }
2224
2225 $mainActVals = array();
2226 $mainActivity = new CRM_Activity_DAO_Activity();
2227 CRM_Core_DAO::storeValues($otherActivity, $mainActVals);
2228 $mainActivity->copyValues($mainActVals);
2229 $mainActivity->id = NULL;
2230 $mainActivity->activity_date_time = CRM_Utils_Date::isoToMysql($otherActivity->activity_date_time);
2231 $mainActivity->source_record_id = CRM_Utils_Array::value($mainActivity->source_record_id,
2232 $activityMappingIds
2233 );
2234
2235 $mainActivity->original_id = CRM_Utils_Array::value($mainActivity->original_id,
2236 $activityMappingIds
2237 );
2238
2239 $mainActivity->parent_id = CRM_Utils_Array::value($mainActivity->parent_id,
2240 $activityMappingIds
2241 );
2242 $mainActivity->save();
2243 $mainActivityId = $mainActivity->id;
2244 if (!$mainActivityId) {
2245 continue;
2246 }
2247
2248 $activityMappingIds[$otherActivityId] = $mainActivityId;
2249 // insert log of all activities
2250 CRM_Activity_BAO_Activity::logActivityAction($mainActivity);
2251
2252 $otherActivity->free();
2253 $mainActivity->free();
2254 $copiedActivityIds[] = $otherActivityId;
2255
2256 //create case activity record.
2257 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2258 $mainCaseActivity->case_id = $mainCaseId;
2259 $mainCaseActivity->activity_id = $mainActivityId;
2260 $mainCaseActivity->save();
2261 $mainCaseActivity->free();
2262
2263 //migrate source activity.
2264 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2265 $otherSourceActivity->activity_id = $otherActivityId;
2266 $otherSourceActivity->record_type_id = $sourceID;
2267 $otherSourceActivity->find();
2268 while ($otherSourceActivity->fetch()) {
2269 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2270 $mainActivitySource->record_type_id = $sourceID;
2271 $mainActivitySource->activity_id = $mainActivityId;
2272 $mainActivitySource->contact_id = $otherSourceActivity->contact_id;
2273 if ($mainActivitySource->contact_id == $otherContactId) {
2274 $mainActivitySource->contact_id = $mainContactId;
2275 }
2276 //avoid duplicate object.
2277 if (!$mainActivitySource->find(TRUE)) {
2278 $mainActivitySource->save();
2279 }
2280 $mainActivitySource->free();
2281 }
2282 $otherSourceActivity->free();
2283
2284 //migrate target activities.
2285 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2286 $otherTargetActivity->activity_id = $otherActivityId;
2287 $otherTargetActivity->record_type_id = $targetID;
2288 $otherTargetActivity->find();
2289 while ($otherTargetActivity->fetch()) {
2290 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2291 $mainActivityTarget->record_type_id = $targetID;
2292 $mainActivityTarget->activity_id = $mainActivityId;
2293 $mainActivityTarget->contact_id = $otherTargetActivity->contact_id;
2294 if ($mainActivityTarget->contact_id == $otherContactId) {
2295 $mainActivityTarget->contact_id = $mainContactId;
2296 }
2297 //avoid duplicate object.
2298 if (!$mainActivityTarget->find(TRUE)) {
2299 $mainActivityTarget->save();
2300 }
2301 $mainActivityTarget->free();
2302 }
2303 $otherTargetActivity->free();
2304
2305 //migrate assignee activities.
2306 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2307 $otherAssigneeActivity->activity_id = $otherActivityId;
2308 $otherAssigneeActivity->record_type_id = $assigneeID;
2309 $otherAssigneeActivity->find();
2310 while ($otherAssigneeActivity->fetch()) {
2311 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2312 $mainAssigneeActivity->activity_id = $mainActivityId;
2313 $mainAssigneeActivity->record_type_id = $assigneeID;
2314 $mainAssigneeActivity->contact_id = $otherAssigneeActivity->contact_id;
2315 if ($mainAssigneeActivity->contact_id == $otherContactId) {
2316 $mainAssigneeActivity->contact_id = $mainContactId;
2317 }
2318 //avoid duplicate object.
2319 if (!$mainAssigneeActivity->find(TRUE)) {
2320 $mainAssigneeActivity->save();
2321 }
2322 $mainAssigneeActivity->free();
2323 }
2324 $otherAssigneeActivity->free();
2325
2326 // copy custom fields and attachments
2327 $aparams = array(
2328 'activityID' => $otherActivityId,
2329 'mainActivityId' => $mainActivityId,
2330 );
2331 CRM_Activity_BAO_Activity::copyExtendedActivityData($aparams);
2332 }
2333
2334 //copy case relationship.
2335 if ($duplicateContacts) {
2336 //migrate relationship records.
2337 $otherRelationship = new CRM_Contact_DAO_Relationship();
2338 $otherRelationship->case_id = $otherCaseId;
2339 $otherRelationship->find();
2340 $otherRelationshipIds = array();
2341 while ($otherRelationship->fetch()) {
2342 $otherRelVals = array();
2343 $updateOtherRel = FALSE;
2344 CRM_Core_DAO::storeValues($otherRelationship, $otherRelVals);
2345
2346 $mainRelationship = new CRM_Contact_DAO_Relationship();
2347 $mainRelationship->copyValues($otherRelVals);
2348 $mainRelationship->id = NULL;
2349 $mainRelationship->case_id = $mainCaseId;
2350 if ($mainRelationship->contact_id_a == $otherContactId) {
2351 $updateOtherRel = TRUE;
2352 $mainRelationship->contact_id_a = $mainContactId;
2353 }
2354
2355 //case creator change only when we merge user contact.
2356 if ($mainRelationship->contact_id_b == $otherContactId) {
2357 //do not change creator for change client.
2358 if (!$changeClient) {
2359 $updateOtherRel = TRUE;
2360 $mainRelationship->contact_id_b = ($currentUserId) ? $currentUserId : $mainContactId;
2361 }
2362 }
2363 $mainRelationship->end_date = CRM_Utils_Date::isoToMysql($otherRelationship->end_date);
2364 $mainRelationship->start_date = CRM_Utils_Date::isoToMysql($otherRelationship->start_date);
2365
2366 //avoid duplicate object.
2367 if (!$mainRelationship->find(TRUE)) {
2368 $mainRelationship->save();
2369 }
2370 $mainRelationship->free();
2371
2372 //get the other relationship ids to update end date.
2373 if ($updateOtherRel) {
2374 $otherRelationshipIds[$otherRelationship->id] = $otherRelationship->id;
2375 }
2376 }
2377 $otherRelationship->free();
2378
2379 //update other relationships end dates
2380 if (!empty($otherRelationshipIds)) {
2381 $sql = 'UPDATE civicrm_relationship
2382 SET end_date = CURDATE()
2383 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2384 CRM_Core_DAO::executeQuery($sql);
2385 }
2386 }
2387
2388 //move other case to trash.
2389 $mergeCase = self::deleteCase($otherCaseId, $moveToTrash);
2390 if (!$mergeCase) {
2391 continue;
2392 }
2393
2394 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2395 if ($changeClient) {
2396 $mainContactDisplayName = CRM_Contact_BAO_Contact::displayName($mainContactId);
2397 $otherContactDisplayName = CRM_Contact_BAO_Contact::displayName($otherContactId);
2398
2399 $mergeActType = array_search('Reassigned Case', $activityTypes);
2400 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2401 array(
2402 1 => $otherCaseId,
2403 2 => $otherContactDisplayName,
2404 3 => $mainContactDisplayName,
2405 4 => $mainCaseId,
2406 )
2407 );
2408 }
2409 elseif ($duplicateContacts) {
2410 $mergeActType = array_search('Merge Case', $activityTypes);
2411 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2412 array(
2413 1 => $otherCaseId,
2414 2 => $otherContactId,
2415 3 => $mainContactId,
2416 4 => $mainCaseId,
2417 )
2418 );
2419 }
2420 else {
2421 $mergeActType = array_search('Merge Case', $activityTypes);
2422 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2423 if (!empty($copiedActivityIds)) {
2424 $sql = '
2425 SELECT id, subject, activity_date_time, activity_type_id
2426 FROM civicrm_activity
2427 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2428 $dao = CRM_Core_DAO::executeQuery($sql);
2429 while ($dao->fetch()) {
2430 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2431 if ($dao->subject) {
2432 $mergeActSubjectDetails .= " :: {$dao->subject}";
2433 }
2434 $mergeActSubjectDetails .= "<br />";
2435 }
2436 }
2437 }
2438
2439 //Create merge activity record. Source for merge activity is the logged in user's contact ID ($currentUserId).
2440 $activityParams = array(
2441 'subject' => $mergeActSubject,
2442 'details' => $mergeActSubjectDetails,
2443 'status_id' => array_search('Completed', $activityStatuses),
2444 'activity_type_id' => $mergeActType,
2445 'source_contact_id' => $currentUserId,
2446 'activity_date_time' => date('YmdHis'),
2447 );
2448
2449 $mergeActivity = CRM_Activity_BAO_Activity::create($activityParams);
2450 $mergeActivityId = $mergeActivity->id;
2451 if (!$mergeActivityId) {
2452 continue;
2453 }
2454 $mergeActivity->free();
2455
2456 //connect merge activity to case.
2457 $mergeCaseAct = array(
2458 'case_id' => $mainCaseId,
2459 'activity_id' => $mergeActivityId,
2460 );
2461
2462 self::processCaseActivity($mergeCaseAct);
2463 }
2464
2465 CRM_Utils_Hook::post_case_merge($mainContactId, $mainCaseId, $otherContactId, $otherCaseId, $changeClient);
2466
2467 return $mainCaseIds;
2468 }
2469
2470 /**
2471 * Validate contact permission for
2472 * edit/view on activity record and build links.
2473 *
2474 * @param array $tplParams
2475 * Params to be sent to template for sending email.
2476 * @param array $activityParams
2477 * Info of the activity.
2478 */
2479 public static function buildPermissionLinks(&$tplParams, $activityParams) {
2480 $activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2481 'activity_type_id', 'id'
2482 );
2483
2484 if (!empty($tplParams['isCaseActivity'])) {
2485 $tplParams['editActURL'] = CRM_Utils_System::url('civicrm/case/activity',
2486 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2487 );
2488
2489 $tplParams['viewActURL'] = CRM_Utils_System::url('civicrm/case/activity/view',
2490 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2491 );
2492
2493 $tplParams['manageCaseURL'] = CRM_Utils_System::url('civicrm/contact/view/case',
2494 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2495 );
2496 }
2497 else {
2498 $tplParams['editActURL'] = CRM_Utils_System::url('civicrm/contact/view/activity',
2499 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2500 );
2501
2502 $tplParams['viewActURL'] = CRM_Utils_System::url('civicrm/contact/view/activity',
2503 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2504 );
2505 }
2506 }
2507
2508 /**
2509 * Validate contact permission for
2510 * given operation on activity record.
2511 *
2512 * @param int $activityId
2513 * Activity record id.
2514 * @param string $operation
2515 * User operation.
2516 * @param int $actTypeId
2517 * Activity type id.
2518 * @param int $contactId
2519 * Contact id/if not pass consider logged in.
2520 * @param bool $checkComponent
2521 * Do we need to check component enabled.
2522 *
2523 * @return bool
2524 */
2525 public static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2526 $allow = FALSE;
2527 if (!$actTypeId && $activityId) {
2528 $actTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2529 }
2530
2531 if (!$activityId || !$operation || !$actTypeId) {
2532 return $allow;
2533 }
2534
2535 //do check for civicase component enabled.
2536 if ($checkComponent && !self::enabled()) {
2537 return $allow;
2538 }
2539
2540 //do check for cases.
2541 $caseActOperations = array(
2542 'File On Case',
2543 'Link Cases',
2544 'Move To Case',
2545 'Copy To Case',
2546 );
2547
2548 if (in_array($operation, $caseActOperations)) {
2549 static $caseCount;
2550 if (!isset($caseCount)) {
2551 try {
2552 $caseCount = civicrm_api3('Case', 'getcount', array(
2553 'check_permissions' => TRUE,
2554 'status_id' => array('!=' => 'Closed'),
2555 'is_deleted' => 0,
2556 'end_date' => array('IS NULL' => 1),
2557 ));
2558 }
2559 catch (CiviCRM_API3_Exception $e) {
2560 // Lack of permissions will throw an exception
2561 $caseCount = 0;
2562 }
2563 }
2564 if ($operation == 'File On Case') {
2565 $allow = !empty($caseCount);
2566 }
2567 else {
2568 $allow = ($caseCount > 1);
2569 }
2570 }
2571
2572 $actionOperations = array('view', 'edit', 'delete');
2573 if (in_array($operation, $actionOperations)) {
2574
2575 //do cache when user has non/supper permission.
2576 static $allowOperations;
2577
2578 if (!is_array($allowOperations) ||
2579 !array_key_exists($operation, $allowOperations)
2580 ) {
2581
2582 if (!$contactId) {
2583 $session = CRM_Core_Session::singleton();
2584 $contactId = $session->get('userID');
2585 }
2586
2587 //check for permissions.
2588 $permissions = array(
2589 'view' => array(
2590 'access my cases and activities',
2591 'access all cases and activities',
2592 ),
2593 'edit' => array(
2594 'access my cases and activities',
2595 'access all cases and activities',
2596 ),
2597 'delete' => array('delete activities'),
2598 );
2599
2600 //check for core permission.
2601 $hasPermissions = array();
2602 $checkPermissions = CRM_Utils_Array::value($operation, $permissions);
2603 if (is_array($checkPermissions)) {
2604 foreach ($checkPermissions as $per) {
2605 if (CRM_Core_Permission::check($per)) {
2606 $hasPermissions[$operation][] = $per;
2607 }
2608 }
2609 }
2610
2611 //has permissions.
2612 if (!empty($hasPermissions)) {
2613 //need to check activity object specific.
2614 if (in_array($operation, array(
2615 'view',
2616 'edit',
2617 ))
2618 ) {
2619 //do we have supper permission.
2620 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2621 $allowOperations[$operation] = $allow = TRUE;
2622 }
2623 else {
2624 //user has only access to my cases and activity.
2625 //here object specific permmions come in picture.
2626
2627 //edit - contact must be source or assignee
2628 //view - contact must be source/assignee/target
2629 $isTarget = $isAssignee = $isSource = FALSE;
2630 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
2631 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2632 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2633 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2634
2635 $target = new CRM_Activity_DAO_ActivityContact();
2636 $target->record_type_id = $targetID;
2637 $target->activity_id = $activityId;
2638 $target->contact_id = $contactId;
2639 if ($target->find(TRUE)) {
2640 $isTarget = TRUE;
2641 }
2642
2643 $assignee = new CRM_Activity_DAO_ActivityContact();
2644 $assignee->activity_id = $activityId;
2645 $assignee->record_type_id = $assigneeID;
2646 $assignee->contact_id = $contactId;
2647 if ($assignee->find(TRUE)) {
2648 $isAssignee = TRUE;
2649 }
2650
2651 $source = new CRM_Activity_DAO_ActivityContact();
2652 $source->activity_id = $activityId;
2653 $source->record_type_id = $sourceID;
2654 $source->contact_id = $contactId;
2655 if ($source->find(TRUE)) {
2656 $isSource = TRUE;
2657 }
2658
2659 if ($operation == 'edit') {
2660 if ($isAssignee || $isSource) {
2661 $allow = TRUE;
2662 }
2663 }
2664 if ($operation == 'view') {
2665 if ($isTarget || $isAssignee || $isSource) {
2666 $allow = TRUE;
2667 }
2668 }
2669 }
2670 }
2671 elseif (is_array($hasPermissions[$operation])) {
2672 $allowOperations[$operation] = $allow = TRUE;
2673 }
2674 }
2675 else {
2676 //contact do not have permission.
2677 $allowOperations[$operation] = FALSE;
2678 }
2679 }
2680 else {
2681 //use cache.
2682 //here contact might have supper/non permission.
2683 $allow = $allowOperations[$operation];
2684 }
2685 }
2686
2687 //do further only when operation is granted.
2688 if ($allow) {
2689 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name');
2690
2691 //get the activity type name.
2692 $actTypeName = CRM_Utils_Array::value($actTypeId, $activityTypes);
2693
2694 //do not allow multiple copy / edit action.
2695 $singletonNames = array(
2696 'Open Case',
2697 'Reassigned Case',
2698 'Merge Case',
2699 'Link Cases',
2700 'Assign Case Role',
2701 'Email',
2702 'Inbound Email',
2703 );
2704
2705 //do not allow to delete these activities, CRM-4543
2706 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2707
2708 //allow edit operation.
2709 $allowEditNames = array('Open Case');
2710
2711 // do not allow File on Case
2712 $doNotFileNames = array(
2713 'Open Case',
2714 'Change Case Type',
2715 'Change Case Status',
2716 'Change Case Start Date',
2717 'Reassigned Case',
2718 'Merge Case',
2719 'Link Cases',
2720 'Assign Case Role',
2721 );
2722
2723 if (in_array($actTypeName, $singletonNames)) {
2724 $allow = FALSE;
2725 if ($operation == 'File On Case') {
2726 $allow = (in_array($actTypeName, $doNotFileNames)) ? FALSE : TRUE;
2727 }
2728 if (in_array($operation, $actionOperations)) {
2729 $allow = TRUE;
2730 if ($operation == 'edit') {
2731 $allow = (in_array($actTypeName, $allowEditNames)) ? TRUE : FALSE;
2732 }
2733 elseif ($operation == 'delete') {
2734 $allow = (in_array($actTypeName, $doNotDeleteNames)) ? FALSE : TRUE;
2735 }
2736 }
2737 }
2738 if ($allow && ($operation == 'delete') &&
2739 in_array($actTypeName, $doNotDeleteNames)
2740 ) {
2741 $allow = FALSE;
2742 }
2743
2744 if ($allow && ($operation == 'File On Case') &&
2745 in_array($actTypeName, $doNotFileNames)
2746 ) {
2747 $allow = FALSE;
2748 }
2749
2750 //check settings file for masking actions
2751 //on the basis the activity types
2752 //hide Edit link if activity type is NOT editable
2753 //(special case activities).CRM-5871
2754 if ($allow && in_array($operation, $actionOperations)) {
2755 static $actionFilter = array();
2756 if (!array_key_exists($operation, $actionFilter)) {
2757 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2758 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2759 }
2760 if (array_key_exists($operation, $actionFilter[$operation]) &&
2761 in_array($actTypeId, $actionFilter[$operation][$operation])
2762 ) {
2763 $allow = FALSE;
2764 }
2765 }
2766 }
2767
2768 return $allow;
2769 }
2770
2771 /**
2772 * Since we drop 'access CiviCase', allow access
2773 * if user has 'access my cases and activities'
2774 * or 'access all cases and activities'
2775 */
2776 public static function accessCiviCase() {
2777 if (!self::enabled()) {
2778 return FALSE;
2779 }
2780
2781 if (CRM_Core_Permission::check('access my cases and activities') ||
2782 CRM_Core_Permission::check('access all cases and activities')
2783 ) {
2784 return TRUE;
2785 }
2786
2787 return FALSE;
2788 }
2789
2790 /**
2791 * Verify user has permission to access a case.
2792 *
2793 * @param int $caseId
2794 * @param bool $denyClosed
2795 * Set TRUE if one wants closed cases to be treated as inaccessible.
2796 *
2797 * @return bool
2798 */
2799 public static function accessCase($caseId, $denyClosed = TRUE) {
2800 if (!$caseId || !self::enabled()) {
2801 return FALSE;
2802 }
2803
2804 $params = array('id' => $caseId, 'check_permissions' => TRUE);
2805 if ($denyClosed && !CRM_Core_Permission::check('access all cases and activities')) {
2806 $params['status_id'] = array('!=' => 'Closed');
2807 }
2808 try {
2809 return (bool) civicrm_api3('Case', 'getcount', $params);
2810 }
2811 catch (CiviCRM_API3_Exception $e) {
2812 // Lack of permissions will throw an exception
2813 return FALSE;
2814 }
2815 }
2816
2817 /**
2818 * Check whether activity is a case Activity.
2819 *
2820 * @param int $activityID
2821 * Activity id.
2822 *
2823 * @return bool
2824 */
2825 public static function isCaseActivity($activityID) {
2826 $isCaseActivity = FALSE;
2827 if ($activityID) {
2828 $params = array(1 => array($activityID, 'Integer'));
2829 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2830 if (CRM_Core_DAO::singleValueQuery($query, $params)) {
2831 $isCaseActivity = TRUE;
2832 }
2833 }
2834
2835 return $isCaseActivity;
2836 }
2837
2838 /**
2839 * Get all the case type ids currently in use.
2840 *
2841 * @return array
2842 */
2843 public static function getUsedCaseType() {
2844 static $caseTypeIds;
2845
2846 if (!is_array($caseTypeIds)) {
2847 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2848
2849 $dao = CRM_Core_DAO::executeQuery($query);
2850 $caseTypeIds = array();
2851 while ($dao->fetch()) {
2852 $typeId = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2853 $dao->case_type_id
2854 );
2855 $caseTypeIds[] = $typeId[1];
2856 }
2857 }
2858
2859 return $caseTypeIds;
2860 }
2861
2862 /**
2863 * Get all the case status ids currently in use.
2864 *
2865 * @return array
2866 */
2867 public static function getUsedCaseStatuses() {
2868 static $caseStatusIds;
2869
2870 if (!is_array($caseStatusIds)) {
2871 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2872
2873 $dao = CRM_Core_DAO::executeQuery($query);
2874 $caseStatusIds = array();
2875 while ($dao->fetch()) {
2876 $caseStatusIds[] = $dao->status_id;
2877 }
2878 }
2879
2880 return $caseStatusIds;
2881 }
2882
2883 /**
2884 * Get all the encounter medium ids currently in use.
2885 *
2886 * @return array
2887 */
2888 public static function getUsedEncounterMediums() {
2889 static $mediumIds;
2890
2891 if (!is_array($mediumIds)) {
2892 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2893
2894 $dao = CRM_Core_DAO::executeQuery($query);
2895 $mediumIds = array();
2896 while ($dao->fetch()) {
2897 $mediumIds[] = $dao->medium_id;
2898 }
2899 }
2900
2901 return $mediumIds;
2902 }
2903
2904 /**
2905 * Check case configuration.
2906 *
2907 * @param int $contactId
2908 *
2909 * @return array
2910 */
2911 public static function isCaseConfigured($contactId = NULL) {
2912 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2913
2914 //lets check for case configured.
2915 $allCasesCount = CRM_Case_BAO_Case::caseCount(NULL, FALSE);
2916 $configured['configured'] = ($allCasesCount) ? TRUE : FALSE;
2917 if (!$configured['configured']) {
2918 //do check for case type and case status.
2919 $caseTypes = CRM_Case_PseudoConstant::caseType('title', FALSE);
2920 if (!empty($caseTypes)) {
2921 $configured['configured'] = TRUE;
2922 if (!$configured['configured']) {
2923 $caseStatuses = CRM_Case_PseudoConstant::caseStatus('label', FALSE);
2924 if (!empty($caseStatuses)) {
2925 $configured['configured'] = TRUE;
2926 }
2927 }
2928 }
2929 }
2930 if ($configured['configured']) {
2931 //do check for active case type and case status.
2932 $caseTypes = CRM_Case_PseudoConstant::caseType();
2933 if (!empty($caseTypes)) {
2934 $caseStatuses = CRM_Case_PseudoConstant::caseStatus();
2935 if (!empty($caseStatuses)) {
2936 $configured['allowToAddNewCase'] = TRUE;
2937 }
2938 }
2939
2940 //do we need to redirect user to case admin.
2941 if (!$configured['allowToAddNewCase'] && $contactId) {
2942 //check for current contact case count.
2943 $currentContatCasesCount = CRM_Case_BAO_Case::caseCount($contactId);
2944 //redirect user to case admin page.
2945 if (!$currentContatCasesCount) {
2946 $configured['redirectToCaseAdmin'] = TRUE;
2947 }
2948 }
2949 }
2950
2951 return $configured;
2952 }
2953
2954 /**
2955 * Used during case component enablement and during ugprade.
2956 *
2957 * @return bool
2958 */
2959 public static function createCaseViews() {
2960 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
2961 $dao = new CRM_Core_DAO();
2962
2963 $sql = self::createCaseViewsQuery('upcoming');
2964 $dao->query($sql);
2965 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
2966 return FALSE;
2967 }
2968
2969 // Above error doesn't get caught?
2970 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
2971 if (is_null($doublecheck)) {
2972 return FALSE;
2973 }
2974
2975 $sql = self::createCaseViewsQuery('recent');
2976 $dao->query($sql);
2977 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
2978 return FALSE;
2979 }
2980
2981 // Above error doesn't get caught?
2982 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
2983 if (is_null($doublecheck)) {
2984 return FALSE;
2985 }
2986
2987 return TRUE;
2988 }
2989
2990 /**
2991 * Helper function, also used by the upgrade in case of error
2992 *
2993 * @param string $section
2994 *
2995 * @return string
2996 */
2997 public static function createCaseViewsQuery($section = 'upcoming') {
2998 $sql = "";
2999 $scheduled_id = CRM_Core_Pseudoconstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
3000 switch ($section) {
3001 case 'upcoming':
3002 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3003 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3004 FROM civicrm_case_activity ca
3005 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3006 WHERE a.activity_date_time =
3007 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3008 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3009 WHERE b.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3010 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id = $scheduled_id
3011 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time ASC LIMIT 1)";
3012 break;
3013
3014 case 'recent':
3015 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3016 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3017 FROM civicrm_case_activity ca
3018 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3019 WHERE a.activity_date_time =
3020 (SELECT b.activity_date_time FROM civicrm_case_activity bca
3021 INNER JOIN civicrm_activity b ON bca.activity_id=b.id
3022 WHERE b.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3023 AND b.is_current_revision = 1 AND b.is_deleted=0 AND b.status_id <> $scheduled_id
3024 AND bca.case_id = ca.case_id ORDER BY b.activity_date_time DESC LIMIT 1)";
3025 break;
3026 }
3027 return $sql;
3028 }
3029
3030 /**
3031 * Add/copy relationships, when new client is added for a case
3032 *
3033 * @param int $caseId
3034 * Case id.
3035 * @param int $contactId
3036 * Contact id / new client id.
3037 */
3038 public static function addCaseRelationships($caseId, $contactId) {
3039 // get the case role / relationships for the case
3040 $caseRelationships = new CRM_Contact_DAO_Relationship();
3041 $caseRelationships->case_id = $caseId;
3042 $caseRelationships->find();
3043 $relationshipTypes = array();
3044
3045 // make sure we don't add duplicate relationships of same relationship type.
3046 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id, $relationshipTypes)) {
3047 $values = array();
3048 CRM_Core_DAO::storeValues($caseRelationships, $values);
3049
3050 // add relationship for new client.
3051 $newRelationship = new CRM_Contact_DAO_Relationship();
3052 $newRelationship->copyValues($values);
3053 $newRelationship->id = NULL;
3054 $newRelationship->case_id = $caseId;
3055 $newRelationship->contact_id_a = $contactId;
3056 $newRelationship->end_date = CRM_Utils_Date::isoToMysql($caseRelationships->end_date);
3057 $newRelationship->start_date = CRM_Utils_Date::isoToMysql($caseRelationships->start_date);
3058
3059 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3060 if (!$newRelationship->find(TRUE)) {
3061 $newRelationship->save();
3062 }
3063 $newRelationship->free();
3064
3065 // store relationship type of newly created relationship
3066 $relationshipTypes[] = $caseRelationships->relationship_type_id;
3067 }
3068 }
3069
3070 /**
3071 * Get the list of clients for a case.
3072 *
3073 * @param int $caseId
3074 *
3075 * @return array
3076 * associated array with client ids
3077 */
3078 public static function getCaseClients($caseId) {
3079 $clients = array();
3080 $caseContact = new CRM_Case_DAO_CaseContact();
3081 $caseContact->case_id = $caseId;
3082 $caseContact->orderBy('id');
3083 $caseContact->find();
3084
3085 while ($caseContact->fetch()) {
3086 $clients[] = $caseContact->contact_id;
3087 }
3088
3089 return $clients;
3090 }
3091
3092 /**
3093 * @param int $caseId
3094 * @param string $direction
3095 * @param int $cid
3096 * @param int $relTypeId
3097 * @throws \CRM_Core_Exception
3098 * @throws \CiviCRM_API3_Exception
3099 */
3100 public static function endCaseRole($caseId, $direction, $cid, $relTypeId) {
3101 // Validate inputs
3102 if ($direction !== 'a' && $direction !== 'b') {
3103 throw new CRM_Core_Exception('Invalid relationship direction');
3104 }
3105
3106 // This case might have multiple clients, so we lookup by relationship instead of by id to get them all
3107 $sql = "SELECT id FROM civicrm_relationship WHERE case_id = %1 AND contact_id_{$direction} = %2 AND relationship_type_id = %3";
3108 $dao = CRM_Core_DAO::executeQuery($sql, array(
3109 1 => array($caseId, 'Positive'),
3110 2 => array($cid, 'Positive'),
3111 3 => array($relTypeId, 'Positive'),
3112 ));
3113 while ($dao->fetch()) {
3114 civicrm_api3('relationship', 'create', array(
3115 'id' => $dao->id,
3116 'is_active' => 0,
3117 'end_date' => 'now',
3118 ));
3119 }
3120 }
3121
3122 /**
3123 * Get options for a given case field.
3124 * @see CRM_Core_DAO::buildOptions
3125 *
3126 * @param string $fieldName
3127 * @param string $context
3128 * @see CRM_Core_DAO::buildOptionsContext
3129 * @param array $props
3130 * Whatever is known about this dao object.
3131 *
3132 * @return array|bool
3133 */
3134 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3135 $className = __CLASS__;
3136 $params = array();
3137 switch ($fieldName) {
3138 // This field is not part of this object but the api supports it
3139 case 'medium_id':
3140 $className = 'CRM_Activity_BAO_Activity';
3141 break;
3142
3143 // Filter status id by case type id
3144 case 'status_id':
3145 if (!empty($props['case_type_id'])) {
3146 $idField = is_numeric($props['case_type_id']) ? 'id' : 'name';
3147 $caseType = civicrm_api3('CaseType', 'getsingle', array($idField => $props['case_type_id'], 'return' => 'definition'));
3148 if (!empty($caseType['definition']['statuses'])) {
3149 $params['condition'] = 'v.name IN ("' . implode('","', $caseType['definition']['statuses']) . '")';
3150 }
3151 }
3152 break;
3153 }
3154 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
3155 }
3156
3157 /**
3158 * @inheritDoc
3159 */
3160 public function addSelectWhereClause() {
3161 // We always return an array with these keys, even if they are empty,
3162 // because this tells the query builder that we have considered these fields for acls
3163 $clauses = array(
3164 'id' => array(),
3165 // Only case admins can view deleted cases
3166 'is_deleted' => CRM_Core_Permission::check('administer CiviCase') ? array() : array("= 0"),
3167 );
3168 // Ensure the user has permission to view the case client
3169 $contactClause = CRM_Utils_SQL::mergeSubquery('Contact');
3170 if ($contactClause) {
3171 $contactClause = implode(' AND contact_id ', $contactClause);
3172 $clauses['id'][] = "IN (SELECT case_id FROM civicrm_case_contact WHERE contact_id $contactClause)";
3173 }
3174 // The api gatekeeper ensures the user has at least "access my cases and activities"
3175 // so if they do not have permission to see all cases we'll assume they can only access their own
3176 if (!CRM_Core_Permission::check('access all cases and activities')) {
3177 $user = (int) CRM_Core_Session::getLoggedInContactID();
3178 $clauses['id'][] = "IN (
3179 SELECT r.case_id FROM civicrm_relationship r, civicrm_case_contact cc WHERE r.is_active = 1 AND cc.case_id = r.case_id AND (
3180 (r.contact_id_a = cc.contact_id AND r.contact_id_b = $user) OR (r.contact_id_b = cc.contact_id AND r.contact_id_a = $user)
3181 )
3182 )";
3183 }
3184 CRM_Utils_Hook::selectWhereClause($this, $clauses);
3185 return $clauses;
3186 }
3187
3188 /**
3189 * CRM-20308: Method to get the contact id to use as from contact for email copy
3190 * 1. Activity Added by Contact's email address
3191 * 2. System Default From Address
3192 * 3. Default Organization Contact email address
3193 * 4. Logged in user
3194 *
3195 * @param int $activityID
3196 *
3197 * @return mixed $emailFromContactId
3198 * @see https://issues.civicrm.org/jira/browse/CRM-20308
3199 */
3200 public static function getReceiptFrom($activityID) {
3201 $name = $address = NULL;
3202
3203 if (!empty($activityID)) {
3204 // There is always a 'Added by' contact for a activity,
3205 // so we can safely use ActivityContact.Getvalue API
3206 $sourceContactId = civicrm_api3('ActivityContact', 'getvalue', array(
3207 'activity_id' => $activityID,
3208 'record_type_id' => 'Activity Source',
3209 'return' => 'contact_id',
3210 ));
3211 list($name, $address) = CRM_Contact_BAO_Contact_Location::getEmailDetails($sourceContactId);
3212 }
3213
3214 // If 'From' email address not found for Source Activity Contact then
3215 // fetch the email from domain or logged in user.
3216 if (empty($address)) {
3217 list($name, $address) = CRM_Core_BAO_Domain::getDefaultReceiptFrom();
3218 }
3219
3220 return "$name <$address>";
3221 }
3222
3223 }