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