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