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