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