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