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