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