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