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