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