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