Import from SVN (r45945, r596)
[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 ?
775 $result->contact_sub_type : $result->contact_type
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 {
1069 $orderBy = " ORDER BY {$sortname} {$sortorder}";
1070 if ($sortname != 'display_date') {
1071 $orderBy .= ', display_date DESC';
1072 }
1073 }
1074
1075 $page = CRM_Utils_Array::value('page', $params);
1076 $rp = CRM_Utils_Array::value('rp', $params);
1077
1078 if (!$page) {
1079
1080 $page = 1;
1081
1082 }
1083 if (!$rp) {
1084 $rp = 10;
1085 }
1086
1087 $start = (($page - 1) * $rp);
1088
1089 $query = $select . $from . $where . $groupBy . $orderBy;
1090
1091 $params = array(1 => array($caseID, 'Integer'));
1092 $dao = CRM_Core_DAO::executeQuery($query, $params);
1093 $params['total'] = $dao->N;
1094
1095 //FIXME: need to optimize/cache these queries
1096 $limit = " LIMIT $start, $rp";
1097 $query .= $limit;
1098 $dao = CRM_Core_DAO::executeQuery($query, $params);
1099
1100
1101 $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
1102 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
1103 $activityPriority = CRM_Core_PseudoConstant::priority();
1104
1105 $url = CRM_Utils_System::url("civicrm/case/activity",
1106 "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE
1107 );
1108
1109 $contextUrl = '';
1110 if ($context == 'fulltext') {
1111 $contextUrl = "&context={$context}";
1112 }
1113 $editUrl = "{$url}&action=update{$contextUrl}";
1114 $deleteUrl = "{$url}&action=delete{$contextUrl}";
1115 $restoreUrl = "{$url}&action=renew{$contextUrl}";
1116 $viewTitle = ts('View this activity.');
1117 $statusTitle = ts('Edit status');
1118
1119 $emailActivityTypeIDs = array(
1120 'Email' => CRM_Core_OptionGroup::getValue('activity_type',
1121 'Email',
1122 'name'
1123 ),
1124 'Inbound Email' => CRM_Core_OptionGroup::getValue('activity_type',
1125 'Inbound Email',
1126 'name'
1127 ),
1128 );
1129
1130 $emailActivityTypeIDs = array(
1131 'Email' => CRM_Core_OptionGroup::getValue('activity_type',
1132 'Email',
1133 'name'
1134 ),
1135 'Inbound Email' => CRM_Core_OptionGroup::getValue('activity_type',
1136 'Inbound Email',
1137 'name'
1138 ),
1139 );
1140
1141 $caseDeleted = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
1142
1143 // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
1144 $compStatusValues = array();
1145 $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
1146 foreach ($compStatusNames as $name) {
1147 $compStatusValues[] = CRM_Core_OptionGroup::getValue('activity_status', $name, 'name');
1148 }
1149 $contactViewUrl = CRM_Utils_System::url("civicrm/contact/view",
1150 "reset=1&cid=", FALSE, NULL, FALSE
1151 );
1152 $hasViewContact = CRM_Core_Permission::giveMeAllACLs();
1153 $clientIds = self::retrieveContactIdsByCaseId($caseID);
1154
1155 if (!$userID) {
1156 $session = CRM_Core_Session::singleton();
1157 $userID = $session->get('userID');
1158 }
1159
1160 while ($dao->fetch()) {
1161
1162 $allowView = self::checkPermission($dao->id, 'view', $dao->activity_type_id, $userID);
1163 $allowEdit = self::checkPermission($dao->id, 'edit', $dao->activity_type_id, $userID);
1164 $allowDelete = self::checkPermission($dao->id, 'delete', $dao->activity_type_id, $userID);
1165
1166 //do not have sufficient permission
1167 //to access given case activity record.
1168 if (!$allowView && !$allowEdit && !$allowDelete) {
1169 continue;
1170 }
1171
1172 $values[$dao->id]['id'] = $dao->id;
1173 $values[$dao->id]['type'] = $activityTypes[$dao->type]['label'];
1174
1175 $reporterName = $dao->reporter;
1176 if ($hasViewContact) {
1177 $reporterName = '<a href="' . $contactViewUrl . $dao->reporter_id . '">' . $dao->reporter . '</a>';
1178 }
1179 $values[$dao->id]['reporter'] = $reporterName;
1180
1181 $targetNames = CRM_Activity_BAO_ActivityTarget::getTargetNames($dao->id);
1182 $targetContactUrls = $withContacts = array();
1183 foreach ($targetNames as $targetId => $targetName) {
1184 if (!in_array($targetId, $clientIds)) {
1185 $withContacts[$targetId] = $targetName;
1186 }
1187 }
1188 foreach ($withContacts as $cid => $name) {
1189 if ($hasViewContact) {
1190 $name = '<a href="' . $contactViewUrl . $cid . '">' . $name . '</a>';
1191 }
1192 $targetContactUrls[] = $name;
1193 }
1194 $values[$dao->id]['with_contacts'] = implode('; ', $targetContactUrls);
1195
1196 $values[$dao->id]['display_date'] = CRM_Utils_Date::customFormat($dao->display_date);
1197 $values[$dao->id]['status'] = $activityStatus[$dao->status];
1198
1199 //check for view activity.
1200 $subject = (empty($dao->subject)) ? '(' . ts('no subject') . ')' : $dao->subject;
1201 if ($allowView) {
1202 $subject = '<a href="javascript:' . $type . 'viewActivity(' . $dao->id . ',' . $contactID . ',' . '\'' . $type . '\' );" title=\'' . $viewTitle . '\'>' . $subject . '</a>';
1203 }
1204 $values[$dao->id]['subject'] = $subject;
1205
1206 // add activity assignee to activity selector. CRM-4485.
1207 if (isset($dao->assignee)) {
1208 if ($dao->ismultiple == 1) {
1209 if ($dao->reporter_id != $dao->assignee_id) {
1210 $values[$dao->id]['reporter'] .= ($hasViewContact) ? ' / ' . "<a href='{$contactViewUrl}{$dao->assignee_id}'>$dao->assignee</a>" : ' / ' . $dao->assignee;
1211 }
1212 $values[$dao->id]['assignee'] = $dao->assignee;
1213 }
1214 else {
1215 $values[$dao->id]['reporter'] .= ' / ' . ts('(multiple)');
1216 }
1217 }
1218 $url = "";
1219 $additionalUrl = "&id={$dao->id}";
1220 if (!$dao->deleted) {
1221 //hide edit link of activity type email.CRM-4530.
1222 if (!in_array($dao->type, $emailActivityTypeIDs)) {
1223 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1224 if ($allowEdit) {
1225 $url = '<a href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1226 }
1227 }
1228 if ($allowDelete) {
1229 if (!empty($url)) {
1230 $url .= " | ";
1231 }
1232 $url .= '<a href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1233 }
1234 }
1235 elseif (!$caseDeleted) {
1236 $url = '<a href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
1237 $values[$dao->id]['status'] = $values[$dao->id]['status'] . '<br /> (deleted)';
1238 }
1239
1240 //check for operations.
1241 if (self::checkPermission($dao->id, 'Move To Case', $dao->activity_type_id)) {
1242 $url .= " | " . '<a href="#" onClick="Javascript:fileOnCase( \'move\',' . $dao->id . ', ' . $caseID . ' ); return false;">' . ts('Move To Case') . '</a> ';
1243 }
1244 if (self::checkPermission($dao->id, 'Copy To Case', $dao->activity_type_id)) {
1245 $url .= " | " . '<a href="#" onClick="Javascript:fileOnCase( \'copy\',' . $dao->id . ',' . $caseID . ' ); return false;">' . ts('Copy To Case') . '</a> ';
1246 }
1247 // if there are file attachments we will return how many and, if only one, add a link to it
1248 if(!empty($dao->attachment_ids)){
1249 $attachmentIDs = explode(',',$dao->attachment_ids);
1250 $values[$dao->id]['no_attachments'] = count($attachmentIDs);
1251 if($values[$dao->id]['no_attachments'] == 1){
1252 // if there is only one it's easy to do a link - otherwise just flag it
1253 $attachmentViewUrl = CRM_Utils_System::url(
1254 "civicrm/file",
1255 "reset=1&eid=" . $dao->id . "&id=" . $dao->attachment_ids,
1256 FALSE,
1257 NULL,
1258 FALSE
1259 );
1260 $url .= " | " . "<a href=$attachmentViewUrl >" . ts('View Attachment') . '</a> ';
1261 }
1262 }
1263
1264
1265 $values[$dao->id]['links'] = $url;
1266 $values[$dao->id]['class'] = "";
1267
1268 if (!empty($dao->priority)) {
1269 if ($dao->priority == CRM_Core_OptionGroup::getValue('priority', 'Urgent', 'name')) {
1270 $values[$dao->id]['class'] = $values[$dao->id]['class'] . "priority-urgent ";
1271 }
1272 elseif ($dao->priority == CRM_Core_OptionGroup::getValue('priority', 'Low', 'name')) {
1273 $values[$dao->id]['class'] = $values[$dao->id]['class'] . "priority-low ";
1274 }
1275 }
1276
1277 if (CRM_Utils_Array::crmInArray($dao->status, $compStatusValues)) {
1278 $values[$dao->id]['class'] = $values[$dao->id]['class'] . " status-completed";
1279 }
1280 else {
1281 if (CRM_Utils_Date::overdue($dao->display_date)) {
1282 $values[$dao->id]['class'] = $values[$dao->id]['class'] . " status-overdue";
1283 }
1284 else {
1285 $values[$dao->id]['class'] = $values[$dao->id]['class'] . " status-scheduled";
1286 }
1287 }
1288
1289 if ($allowEdit) {
1290 $values[$dao->id]['status'] = '<a class="crm-activity-status crm-activity-status-' . $dao->id . ' ' . $values[$dao->id]['class'] . '" href="javascript:changeActivityStatus(' . $dao->id . ',' . $contactID . ',' . $dao->status . ');" title=\'' . $statusTitle . '\'>' . $values[$dao->id]['status'] . '</a>';
1291 }
1292 }
1293 $dao->free();
1294
1295 return $values;
1296 }
1297
1298 /**
1299 * Function to get Case Related Contacts
1300 *
1301 * @param int $caseID case id
1302 * @param boolean $skipDetails if true include details of contacts
1303 *
1304 * @return returns $searchRows array of returnproperties
1305 *
1306 * @static
1307 */
1308 static function getRelatedContacts($caseID, $skipDetails = FALSE) {
1309 $values = array();
1310 $query = 'SELECT cc.display_name as name, cc.sort_name as sort_name, cc.id, crt.label_b_a as role, ce.email
1311 FROM civicrm_relationship cr
1312 LEFT JOIN civicrm_relationship_type crt ON crt.id = cr.relationship_type_id
1313 LEFT JOIN civicrm_contact cc ON cc.id = cr.contact_id_b
1314 LEFT JOIN civicrm_email ce ON ce.contact_id = cc.id
1315 WHERE cr.case_id = %1 AND ce.is_primary= 1
1316 GROUP BY cc.id';
1317
1318 $params = array(1 => array($caseID, 'Integer'));
1319 $dao = CRM_Core_DAO::executeQuery($query, $params);
1320
1321 while ($dao->fetch()) {
1322 if ($skipDetails) {
1323 $values[$dao->id] = 1;
1324 }
1325 else {
1326 $values[] = array(
1327 'contact_id' => $dao->id,
1328 'display_name' => $dao->name,
1329 'sort_name' => $dao->sort_name,
1330 'role' => $dao->role,
1331 'email' => $dao->email,
1332 );
1333 }
1334 }
1335 $dao->free();
1336
1337 return $values;
1338 }
1339
1340 /**
1341 * Function that sends e-mail copy of activity
1342 *
1343 * @param int $activityId activity Id
1344 * @param array $contacts array of related contact
1345 *
1346 * @return void
1347 * @access public
1348 */
1349 static function sendActivityCopy($clientId, $activityId, $contacts, $attachments = NULL, $caseId) {
1350 if (!$activityId) {
1351 return;
1352 }
1353
1354 $tplParams = $activityInfo = array();
1355 //if its a case activity
1356 if ($caseId) {
1357 $activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
1358 $nonCaseActivityTypes = CRM_Core_PseudoConstant::activityType();
1359 if (CRM_Utils_Array::value($activityTypeId, $nonCaseActivityTypes)) {
1360 $anyActivity = TRUE;
1361 }
1362 else {
1363 $anyActivity = FALSE;
1364 }
1365 $tplParams['isCaseActivity'] = 1;
1366 $tplParams['client_id'] = $clientId;
1367 }
1368 else {
1369 $anyActivity = TRUE;
1370 }
1371
1372 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
1373 $isRedact = $xmlProcessorProcess->getRedactActivityEmail();
1374
1375 $xmlProcessorReport = new CRM_Case_XMLProcessor_Report();
1376
1377 $activityInfo = $xmlProcessorReport->getActivityInfo($clientId, $activityId, $anyActivity, $isRedact);
1378 if ($caseId) {
1379 $activityInfo['fields'][] = array('label' => 'Case ID', 'type' => 'String', 'value' => $caseId);
1380 }
1381 $tplParams['activity'] = $activityInfo;
1382 foreach ($tplParams['activity']['fields'] as $k => $val) {
1383 if (CRM_Utils_Array::value('label', $val) == ts('Subject')) {
1384 $activitySubject = $val['value'];
1385 break;
1386 }
1387 }
1388 $session = CRM_Core_Session::singleton();
1389 // CRM-8926 If user is not logged in, use the activity creator as userID
1390 if (!($userID = $session->get('userID'))) {
1391 $userID = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'source_contact_id');
1392 }
1393
1394 //also create activities simultaneously of this copy.
1395 $activityParams = array();
1396
1397 $activityParams['source_record_id'] = $activityId;
1398 $activityParams['source_contact_id'] = $userID;
1399 $activityParams['activity_type_id'] = CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name');
1400 $activityParams['activity_date_time'] = date('YmdHis');
1401 $activityParams['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
1402 $activityParams['medium_id'] = CRM_Core_OptionGroup::getValue('encounter_medium', 'email', 'name');
1403 $activityParams['case_id'] = $caseId;
1404 $activityParams['is_auto'] = 0;
1405 $activityParams['target_id'] = $clientId;
1406
1407 $tplParams['activitySubject'] = $activitySubject;
1408
1409 // if it’s a case activity, add hashed id to the template (CRM-5916)
1410 if ($caseId) {
1411 $tplParams['idHash'] = substr(sha1(CIVICRM_SITE_KEY . $caseId), 0, 7);
1412 }
1413
1414 $result = array();
1415 list($name, $address) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
1416
1417 $receiptFrom = "$name <$address>";
1418
1419 $recordedActivityParams = array();
1420
1421 foreach ($contacts as $mail => $info) {
1422 $tplParams['contact'] = $info;
1423 self::buildPermissionLinks($tplParams, $activityParams);
1424
1425 $displayName = $info['display_name'];
1426
1427 list($result[$info['contact_id']], $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate(
1428 array(
1429 'groupName' => 'msg_tpl_workflow_case',
1430 'valueName' => 'case_activity',
1431 'contactId' => $info['contact_id'],
1432 'tplParams' => $tplParams,
1433 'from' => $receiptFrom,
1434 'toName' => $displayName,
1435 'toEmail' => $mail,
1436 'attachments' => $attachments,
1437 )
1438 );
1439
1440 $activityParams['subject'] = $activitySubject . ' - copy sent to ' . $displayName;
1441 $activityParams['details'] = $message;
1442
1443 if ($result[$info['contact_id']]) {
1444 /*
1445 * Really only need to record one activity with all the targets combined.
1446 * Originally the template was going to possibly have different content, e.g. depending on permissions,
1447 * but it's always the same content at the moment.
1448 */
1449 if (empty($recordedActivityParams)) {
1450 $recordedActivityParams = $activityParams;
1451 }
1452 else {
1453 $recordedActivityParams['subject'] .= "; $displayName";
1454 }
1455 $recordedActivityParams['target_contact_id'][] = $info['contact_id'];
1456 }
1457 else {
1458 unset($result[$info['contact_id']]);
1459 }
1460 }
1461
1462 if (!empty($recordedActivityParams)) {
1463 $activity = CRM_Activity_BAO_Activity::create($recordedActivityParams);
1464
1465 //create case_activity record if its case activity.
1466 if ($caseId) {
1467 $caseParams = array(
1468 'activity_id' => $activity->id,
1469 'case_id' => $caseId,
1470 );
1471 self::processCaseActivity($caseParams);
1472 }
1473 }
1474
1475 return $result;
1476 }
1477
1478 /**
1479 * Retrieve count of activities having a particular type, and
1480 * associated with a particular case.
1481 *
1482 * @param int $caseId ID of the case
1483 * @param int $activityTypeId ID of the activity type
1484 *
1485 * @return array
1486 *
1487 * @access public
1488 *
1489 */
1490 static function getCaseActivityCount($caseId, $activityTypeId) {
1491 $queryParam = array(1 => array($caseId, 'Integer'),
1492 2 => array($activityTypeId, 'Integer'),
1493 );
1494 $query = "SELECT count(ca.id) as countact
1495 FROM civicrm_activity ca
1496 INNER JOIN civicrm_case_activity cca ON ca.id = cca.activity_id
1497 WHERE ca.activity_type_id = %2
1498 AND cca.case_id = %1
1499 AND ca.is_deleted = 0";
1500
1501 $dao = CRM_Core_DAO::executeQuery($query, $queryParam);
1502 if ($dao->fetch()) {
1503 return $dao->countact;
1504 }
1505
1506 return FALSE;
1507 }
1508
1509 /**
1510 * Create an activity for a case via email
1511 *
1512 * @param int $file email sent
1513 *
1514 * @return $activity object of newly creted activity via email
1515 *
1516 * @access public
1517 *
1518 */
1519 static function recordActivityViaEmail($file) {
1520 if (!file_exists($file) ||
1521 !is_readable($file)
1522 ) {
1523 return CRM_Core_Error::fatal(ts('File %1 does not exist or is not readable',
1524 array(1 => $file)
1525 ));
1526 }
1527
1528 $result = CRM_Utils_Mail_Incoming::parse($file);
1529 if ($result['is_error']) {
1530 return $result;
1531 }
1532
1533 foreach ($result['to'] as $to) {
1534 $caseId = NULL;
1535
1536 $emailPattern = '/^([A-Z0-9._%+-]+)\+([\d]+)@[A-Z0-9.-]+\.[A-Z]{2,4}$/i';
1537 $replacement = preg_replace($emailPattern, '$2', $to['email']);
1538
1539 if ($replacement !== $to['email']) {
1540 $caseId = $replacement;
1541 //if caseId is invalid, return as error file
1542 if (!CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $caseId, 'id')) {
1543 return CRM_Core_Error::createAPIError(ts('Invalid case ID ( %1 ) in TO: field.',
1544 array(1 => $caseId)
1545 ));
1546 }
1547 }
1548 else {
1549 continue;
1550 }
1551
1552 // TODO: May want to replace this with a call to getRelatedAndGlobalContacts() when this feature is revisited.
1553 // (Or for efficiency call the global one outside the loop and then union with this each time.)
1554 $contactDetails = self::getRelatedContacts($caseId, TRUE);
1555
1556 if (CRM_Utils_Array::value($result['from']['id'], $contactDetails)) {
1557 $params = array();
1558 $params['subject'] = $result['subject'];
1559 $params['activity_date_time'] = $result['date'];
1560 $params['details'] = $result['body'];
1561 $params['source_contact_id'] = $result['from']['id'];
1562 $params['status_id'] = CRM_Core_OptionGroup::getValue('activity_status',
1563 'Completed',
1564 'name'
1565 );
1566
1567 $details = CRM_Case_PseudoConstant::caseActivityType();
1568 $matches = array();
1569 preg_match('/^\W+([a-zA-Z0-9_ ]+)(\W+)?\n/i',
1570 $result['body'], $matches
1571 );
1572
1573 if (!empty($matches) && isset($matches[1])) {
1574 $activityType = trim($matches[1]);
1575 if (isset($details[$activityType])) {
1576 $params['activity_type_id'] = $details[$activityType]['id'];
1577 }
1578 }
1579 if (!isset($params['activity_type_id'])) {
1580 $params['activity_type_id'] = CRM_Core_OptionGroup::getValue('activity_type', 'Inbound Email', 'name');
1581 }
1582
1583 // create activity
1584 $activity = CRM_Activity_BAO_Activity::create($params);
1585
1586 $caseParams = array(
1587 'activity_id' => $activity->id,
1588 'case_id' => $caseId,
1589 );
1590 self::processCaseActivity($caseParams);
1591 }
1592 else {
1593 return CRM_Core_Error::createAPIError(ts('FROM email contact %1 doesn\'t have a relationship to the referenced case.',
1594 array(1 => $result['from']['email'])
1595 ));
1596 }
1597 }
1598 }
1599
1600 /**
1601 * Function to retrive the scheduled activity type and date
1602 *
1603 * @param array $cases Array of contact and case id
1604 *
1605 * @return array $activityInfo Array of scheduled activity type and date
1606 *
1607 * @access public
1608 *
1609 * @static
1610 */
1611 static function getNextScheduledActivity($cases, $type = 'upcoming') {
1612 $session = CRM_Core_Session::singleton();
1613 $userID = $session->get('userID');
1614
1615 $caseID = implode(',', $cases['case_id']);
1616 $contactID = implode(',', $cases['contact_id']);
1617
1618 $condition = "
1619 AND civicrm_case_contact.contact_id IN( {$contactID} )
1620 AND civicrm_case.id IN( {$caseID})
1621 AND civicrm_case.is_deleted = {$cases['case_deleted']}";
1622
1623 $query = self::getCaseActivityQuery($type, $userID, $condition, $cases['case_deleted']);
1624
1625 $res = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1626
1627 $activityInfo = array();
1628 while ($res->fetch()) {
1629 if ($type == 'upcoming') {
1630 $activityInfo[$res->case_id]['date'] = $res->case_scheduled_activity_date;
1631 $activityInfo[$res->case_id]['type'] = $res->case_scheduled_activity_type;
1632 }
1633 else {
1634 $activityInfo[$res->case_id]['date'] = $res->case_recent_activity_date;
1635 $activityInfo[$res->case_id]['type'] = $res->case_recent_activity_type;
1636 }
1637 }
1638
1639 return $activityInfo;
1640 }
1641
1642 /**
1643 * combine all the exportable fields from the lower levels object
1644 *
1645 * @return array array of exportable Fields
1646 * @access public
1647 * @static
1648 */
1649 static function &exportableFields() {
1650 if (!self::$_exportableFields) {
1651 if (!self::$_exportableFields) {
1652 self::$_exportableFields = array();
1653 }
1654
1655 $fields = CRM_Case_DAO_Case::export();
1656 $fields['case_role'] = array('title' => ts('Role in Case'));
1657 $fields['case_type'] = array('title' => ts('Case Type'),
1658 'name' => 'case_type',
1659 );
1660 $fields['case_status'] = array('title' => ts('Case Status'),
1661 'name' => 'case_status',
1662 );
1663
1664 self::$_exportableFields = $fields;
1665 }
1666 return self::$_exportableFields;
1667 }
1668
1669 /**
1670 * Restore the record that are associated with this case
1671 *
1672 * @param int $caseId id of the case to restore
1673 *
1674 * @return true if success.
1675 * @access public
1676 * @static
1677 */
1678 static function restoreCase($caseId) {
1679 //restore activities
1680 $activities = self::getCaseActivityDates($caseId);
1681 if ($activities) {
1682 foreach ($activities as $value) {
1683 CRM_Activity_BAO_Activity::restoreActivity($value);
1684 }
1685 }
1686 //restore case
1687 $case = new CRM_Case_DAO_Case();
1688 $case->id = $caseId;
1689 $case->is_deleted = 0;
1690 $case->save();
1691
1692 //CRM-7364, enable relationships
1693 self::enableDisableCaseRelationships($caseId, TRUE);
1694 return TRUE;
1695 }
1696
1697 static function getGlobalContacts(&$groupInfo, $sort = NULL, $showLinks = NULL, $returnOnlyCount = FALSE, $offset = 0, $rowCount = 25) {
1698 $globalContacts = array();
1699
1700 $settingsProcessor = new CRM_Case_XMLProcessor_Settings();
1701 $settings = $settingsProcessor->run();
1702 if (!empty($settings)) {
1703 $groupInfo['name'] = $settings['groupname'];
1704 if ($groupInfo['name']) {
1705 $searchParams = array('name' => $groupInfo['name']);
1706 $results = array();
1707 CRM_Contact_BAO_Group::retrieve($searchParams, $results);
1708 if ($results) {
1709 $groupInfo['id'] = $results['id'];
1710 $groupInfo['title'] = $results['title'];
1711 $params = array(array('group', 'IN', array($groupInfo['id'] => 1), 0, 0));
1712 $return = array('sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1713 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1714 list($globalContacts, $_) = CRM_Contact_BAO_Query::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1715
1716 if ($returnOnlyCount) {
1717 return $globalContacts;
1718 }
1719
1720 if ($showLinks) {
1721 foreach($globalContacts as $idx => $contact) {
1722 $globalContacts[$idx]['sort_name'] = '<a href="' . $contactViewUrl . $contact['contact_id'] . '">' . $contact['sort_name'] . '</a>';
1723 }
1724 }
1725 }
1726 }
1727 }
1728 return $globalContacts;
1729 }
1730
1731 /*
1732 * Convenience function to get both case contacts and global in one array
1733 */
1734 static function getRelatedAndGlobalContacts($caseId) {
1735 $relatedContacts = self::getRelatedContacts($caseId);
1736
1737 $groupInfo = array();
1738 $globalContacts = self::getGlobalContacts($groupInfo);
1739
1740 //unset values which are not required.
1741 foreach ($globalContacts as $k => & $v) {
1742 unset($v['email_id']);
1743 unset($v['group_contact_id']);
1744 unset($v['status']);
1745 unset($v['phone']);
1746 $v['role'] = $groupInfo['title'];
1747 }
1748 //include multiple listings for the same contact/different roles.
1749 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1750 return $relatedGlobalContacts;
1751 }
1752
1753 /**
1754 * Function to get Case ActivitiesDueDates with given criteria.
1755 *
1756 * @param int $caseID case id
1757 * @param array $criteriaParams given criteria
1758 * @param boolean $latestDate if set newest or oldest date is selceted.
1759 *
1760 * @return returns case activities due dates
1761 *
1762 * @static
1763 */
1764 static function getCaseActivityDates($caseID, $criteriaParams = array(
1765 ), $latestDate = FALSE) {
1766 $values = array();
1767 $selectDate = " ca.activity_date_time";
1768 $where = $groupBy = ' ';
1769
1770 if (!$caseID) {
1771 return;
1772 }
1773
1774 if ($latestDate) {
1775 if (CRM_Utils_Array::value('activity_type_id', $criteriaParams)) {
1776 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type::escape($criteriaParams['activity_type_id'], 'Integer');
1777 $where .= " AND ca.is_current_revision = 1";
1778 $groupBy .= " GROUP BY ca.activity_type_id";
1779 }
1780
1781 if (CRM_Utils_Array::value('newest', $criteriaParams)) {
1782 $selectDate = " max(ca.activity_date_time) ";
1783 }
1784 else {
1785 $selectDate = " min(ca.activity_date_time) ";
1786 }
1787 }
1788
1789 $query = "SELECT ca.id, {$selectDate} as activity_date
1790 FROM civicrm_activity ca
1791 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1792 WHERE cc.id = %1 {$where} {$groupBy}";
1793
1794 $params = array(1 => array($caseID, 'Integer'));
1795 $dao = CRM_Core_DAO::executeQuery($query, $params);
1796
1797 while ($dao->fetch()) {
1798 $values[$dao->id]['id'] = $dao->id;
1799 $values[$dao->id]['activity_date'] = $dao->activity_date;
1800 }
1801 $dao->free();
1802 return $values;
1803 }
1804
1805 /**
1806 * Function to create activities when Case or Other roles assigned/modified/deleted.
1807 *
1808 * @param int $caseID case id
1809 * @param int $relationshipId relationship id
1810 * @param int $relContactId case role assigne contactId.
1811 *
1812 * @return void on success creates activity and case activity
1813 *
1814 * @static
1815 */
1816 static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1817 if (!$caseId || !$relationshipId || empty($relationshipId)) {
1818 return;
1819 }
1820
1821 $queryParam = array();
1822 if (is_array($relationshipId)) {
1823 $relationshipId = implode(',', $relationshipId);
1824 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1825 }
1826 else {
1827 $relationshipClause = " civicrm_relationship.id = %1";
1828 $queryParam[1] = array($relationshipId, 'Positive');
1829 }
1830
1831 $query = "
1832 SELECT cc.display_name as clientName,
1833 cca.display_name as assigneeContactName,
1834 civicrm_relationship.case_id as caseId,
1835 civicrm_relationship_type.label_a_b as relation_a_b,
1836 civicrm_relationship_type.label_b_a as relation_b_a,
1837 civicrm_relationship.contact_id_b as rel_contact_id,
1838 civicrm_relationship.contact_id_a as assign_contact_id
1839 FROM civicrm_relationship_type, civicrm_relationship
1840 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1841 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1842 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1843
1844 $dao = CRM_Core_DAO::executeQuery($query, $queryParam);
1845
1846 while ($dao->fetch()) {
1847 //to get valid assignee contact(s).
1848 if (isset($dao->caseId) || $dao->rel_contact_id != $contactId) {
1849 $caseRelationship = $dao->relation_a_b;
1850 $assigneContactName = $dao->clientName;
1851 $assigneContactIds[$dao->rel_contact_id] = $dao->rel_contact_id;
1852 }
1853 else {
1854 $caseRelationship = $dao->relation_b_a;
1855 $assigneContactName = $dao->assigneeContactName;
1856 $assigneContactIds[$dao->assign_contact_id] = $dao->assign_contact_id;
1857 }
1858 }
1859
1860 $session = CRM_Core_Session::singleton();
1861 $activityParams = array(
1862 'source_contact_id' => $session->get('userID'),
1863 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1864 'activity_date_time' => date('YmdHis'),
1865 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'),
1866 );
1867
1868 //if $relContactId is passed, role is added or modified.
1869 if (!empty($relContactId)) {
1870 $activityParams['assignee_contact_id'] = $assigneContactIds;
1871
1872 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1873 'Assign Case Role',
1874 'name'
1875 );
1876 }
1877 else {
1878 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1879 'Remove Case Role',
1880 'name'
1881 );
1882 }
1883
1884 $activityParams['activity_type_id'] = $activityTypeID;
1885
1886 $activity = CRM_Activity_BAO_Activity::create($activityParams);
1887
1888 //create case_activity record.
1889 $caseParams = array(
1890 'activity_id' => $activity->id,
1891 'case_id' => $caseId,
1892 );
1893
1894 CRM_Case_BAO_Case::processCaseActivity($caseParams);
1895 }
1896
1897 /**
1898 * Function to get case manger
1899 * contact which is assigned a case role of case manager.
1900 *
1901 * @param int $caseType case type
1902 * @param int $caseId case id
1903 *
1904 * @return array $caseManagerContact array of contact on success otherwise empty
1905 *
1906 * @static
1907 */
1908 static function getCaseManagerContact($caseType, $caseId) {
1909 if (!$caseType || !$caseId) {
1910 return;
1911 }
1912
1913 $caseManagerContact = array();
1914 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1915
1916 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1917
1918 if (!empty($managerRoleId)) {
1919 $managerRoleQuery = "
1920SELECT civicrm_contact.id as casemanager_id,
1921 civicrm_contact.sort_name as casemanager
1922 FROM civicrm_contact
1923 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1924 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1925 WHERE civicrm_case.id = %2";
1926
1927 $managerRoleParams = array(
1928 1 => array($managerRoleId, 'Integer'),
1929 2 => array($caseId, 'Integer'),
1930 );
1931
1932 $dao = CRM_Core_DAO::executeQuery($managerRoleQuery, $managerRoleParams);
1933 if ($dao->fetch()) {
1934 $caseManagerContact['casemanager_id'] = $dao->casemanager_id;
1935 $caseManagerContact['casemanager'] = $dao->casemanager;
1936 }
1937 }
1938
1939 return $caseManagerContact;
1940 }
1941
1942 /**
1943 * Get all cases with no end dates
1944 *
1945 * @return array of case and related data keyed on case id
1946 */
1947 static function getUnclosedCases($params = array(
1948 ), $excludeCaseIds = array(), $excludeDeleted = TRUE) {
1949 //params from ajax call.
1950 $where = array('( ca.end_date is null )');
1951 if ($caseType = CRM_Utils_Array::value('case_type', $params)) {
1952 $where[] = "( ov.label LIKE '%$caseType%' )";
1953 }
1954 if ($sortName = CRM_Utils_Array::value('sort_name', $params)) {
1955 $config = CRM_Core_Config::singleton();
1956 $search = ($config->includeWildCardInName) ? "%$sortName%" : "$sortName%";
1957 $where[] = "( sort_name LIKE '$search' )";
1958 }
1959 if (is_array($excludeCaseIds) &&
1960 !CRM_Utils_System::isNull($excludeCaseIds)
1961 ) {
1962 $where[] = ' ( ca.id NOT IN ( ' . implode(',', $excludeCaseIds) . ' ) ) ';
1963 }
1964 if ($excludeDeleted) {
1965 $where[] = ' ( ca.is_deleted = 0 OR ca.is_deleted IS NULL ) ';
1966 }
1967
1968 //filter for permissioned cases.
1969 $filterCases = array();
1970 $doFilterCases = FALSE;
1971 if (!CRM_Core_Permission::check('access all cases and activities')) {
1972 $doFilterCases = TRUE;
1973 $session = CRM_Core_Session::singleton();
1974 $filterCases = CRM_Case_BAO_Case::getCases(FALSE, $session->get('userID'));
1975 }
1976 $whereClause = implode(' AND ', $where);
1977
1978 $limitClause = '';
1979 if ($limit = CRM_Utils_Array::value('limit', $params)) {
1980 $limitClause = "LIMIT 0, $limit";
1981 }
1982
1983 $query = "
1984 SELECT c.id as contact_id,
1985 c.sort_name,
1986 ca.id,
1987 ca.subject as case_subject,
1988 ov.label as case_type,
1989 ca.start_date as start_date
1990 FROM civicrm_case ca INNER JOIN civicrm_case_contact cc ON ca.id=cc.case_id
1991 INNER JOIN civicrm_contact c ON cc.contact_id=c.id
1992 INNER JOIN civicrm_option_group og ON og.name='case_type'
1993 INNER JOIN civicrm_option_value ov ON (ca.case_type_id=ov.value AND ov.option_group_id=og.id)
1994 WHERE {$whereClause}
1995 ORDER BY c.sort_name
1996 {$limitClause}
1997";
1998 $dao = CRM_Core_DAO::executeQuery($query);
1999 $unclosedCases = array();
2000 while ($dao->fetch()) {
2001 if ($doFilterCases && !array_key_exists($dao->id, $filterCases)) {
2002 continue;
2003 }
2004 $unclosedCases[$dao->id] = array(
2005 'sort_name' => $dao->sort_name,
2006 'case_type' => $dao->case_type,
2007 'contact_id' => $dao->contact_id,
2008 'start_date' => $dao->start_date,
2009 'case_subject' => $dao->case_subject,
2010 );
2011 }
2012 $dao->free();
2013
2014 return $unclosedCases;
2015 }
2016
2017 static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
2018 $whereConditions = array();
2019 if ($excludeDeleted) {
2020 $whereConditions[] = "( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2021 }
2022 if ($contactId) {
2023 $whereConditions[] = "civicrm_case_contact.contact_id = {$contactId}";
2024 }
2025 if (!CRM_Core_Permission::check('access all cases and activities')) {
2026 static $accessibleCaseIds;
2027 if (!is_array($accessibleCaseIds)) {
2028 $session = CRM_Core_Session::singleton();
2029 $accessibleCaseIds = array_keys(self::getCases(FALSE, $session->get('userID')));
2030 }
2031 //no need of further processing.
2032 if (empty($accessibleCaseIds)) {
2033 return 0;
2034 }
2035 $whereConditions[] = "( civicrm_case.id in (" . implode(',', $accessibleCaseIds) . ") )";
2036 }
2037
2038 $whereClause = '';
2039 if (!empty($whereConditions)) {
2040 $whereClause = "WHERE " . implode(' AND ', $whereConditions);
2041 }
2042
2043 $query = "
2044 SELECT count( civicrm_case.id )
2045 FROM civicrm_case
2046LEFT JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2047 {$whereClause}";
2048
2049 return CRM_Core_DAO::singleValueQuery($query);
2050 }
2051
2052 /**
2053 * Retrieve cases related to particular contact.
2054 *
2055 * @param int $contactId contact id
2056 * @param boolean $excludeDeleted do not include deleted cases.
2057 *
2058 * @return an array of cases.
2059 *
2060 * @access public
2061 */
2062 static function getContactCases($contactId, $excludeDeleted = TRUE) {
2063 $cases = array();
2064 if (!$contactId) {
2065 return $cases;
2066 }
2067
2068 $whereClause = "civicrm_case_contact.contact_id = %1";
2069 if ($excludeDeleted) {
2070 $whereClause .= " AND ( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2071 }
2072
2073 $query = "
2074 SELECT civicrm_case.id, case_type_ov.label as case_type, civicrm_case.start_date
2075 FROM civicrm_case
2076INNER JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2077 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2078 LEFT JOIN civicrm_option_value case_type_ov ON ( civicrm_case.case_type_id = case_type_ov.value
2079 AND case_type_og.id = case_type_ov.option_group_id )
2080 WHERE {$whereClause}";
2081
2082 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($contactId, 'Integer')));
2083 while ($dao->fetch()) {
2084 $cases[$dao->id] = array(
2085 'case_id' => $dao->id,
2086 'case_type' => $dao->case_type,
2087 'case_start_date' => $dao->start_date,
2088 );
2089 }
2090 $dao->free();
2091
2092 return $cases;
2093 }
2094
2095 /**
2096 * Retrieve related cases for give case.
2097 *
2098 * @param int $mainCaseId id of main case
2099 * @param int $contactId id of contact
2100 * @param boolean $excludeDeleted do not include deleted cases.
2101 *
2102 * @return an array of related cases.
2103 *
2104 * @access public
2105 */
2106 static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
2107 //FIXME : do check for permissions.
2108
2109 $relatedCases = array();
2110 if (!$mainCaseId || !$contactId) {
2111 return $relatedCases;
2112 }
2113
2114 $linkActType = array_search('Link Cases',
2115 CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name')
2116 );
2117 if (!$linkActType) {
2118 return $relatedCases;
2119 }
2120
2121 $whereClause = "mainCase.id = %2";
2122 if ($excludeDeleted) {
2123 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
2124 }
2125
2126 //1. first fetch related case ids.
2127 $query = "
2128 SELECT relCaseAct.case_id
2129 FROM civicrm_case mainCase
2130 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
2131 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
2132 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
2133 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
2134 WHERE $whereClause";
2135
2136 $dao = CRM_Core_DAO::executeQuery($query, array(
2137 1 => array($linkActType, 'Integer'),
2138 2 => array($mainCaseId, 'Integer'),
2139 ));
2140 $relatedCaseIds = array();
2141 while ($dao->fetch()) {
2142 $relatedCaseIds[$dao->case_id] = $dao->case_id;
2143 }
2144 $dao->free();
2145
2146 // there are no related cases.
2147 if (empty($relatedCaseIds)) {
2148 return $relatedCases;
2149 }
2150
2151 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2152 if ($excludeDeleted) {
2153 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2154 }
2155
2156 //filter for permissioned cases.
2157 $filterCases = array();
2158 $doFilterCases = FALSE;
2159 if (!CRM_Core_Permission::check('access all cases and activities')) {
2160 $doFilterCases = TRUE;
2161 $session = CRM_Core_Session::singleton();
2162 $filterCases = CRM_Case_BAO_Case::getCases(FALSE, $session->get('userID'));
2163 }
2164
2165 //2. fetch the details of related cases.
2166 $query = "
2167 SELECT relCase.id as id,
2168 case_type_ov.label as case_type,
2169 client.display_name as client_name,
2170 client.id as client_id
2171 FROM civicrm_case relCase
2172 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2173 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2174 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2175 LEFT JOIN civicrm_option_value case_type_ov ON ( relCase.case_type_id = case_type_ov.value
2176 AND case_type_og.id = case_type_ov.option_group_id )
2177 WHERE {$whereClause}";
2178
2179 $dao = CRM_Core_DAO::executeQuery($query);
2180 $contactViewUrl = CRM_Utils_System::url("civicrm/contact/view", "reset=1&cid=");
2181 $hasViewContact = CRM_Core_Permission::giveMeAllACLs();
2182
2183 while ($dao->fetch()) {
2184 $caseView = NULL;
2185 if (!$doFilterCases || array_key_exists($dao->id, $filterCases)) {
2186 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2187 $caseViewUrl = CRM_Utils_System::url("civicrm/contact/view/case", $caseViewStr);
2188 $caseView = "<a href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2189 }
2190 $clientView = $dao->client_name;
2191 if ($hasViewContact) {
2192 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2193 }
2194
2195 $relatedCases[$dao->id] = array(
2196 'case_id' => $dao->id,
2197 'case_type' => $dao->case_type,
2198 'client_name' => $clientView,
2199 'links' => $caseView,
2200 );
2201 }
2202 $dao->free();
2203
2204 return $relatedCases;
2205 }
2206
2207 /**
2208 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2209 *
2210 * @see CRM_Dedupe_Merger::cpTables()
2211 *
2212 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2213 */
2214 static function mergeContacts($mainContactId, $otherContactId) {
2215 self::mergeCases($mainContactId, NULL, $otherContactId);
2216 }
2217
2218 /**
2219 * Function perform two task.
2220 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2221 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2222 *
2223 * @param int $mainContactId contact id of main contact record.
2224 * @param int $mainCaseId case id of main case record.
2225 * @param int $otherContactId contact id of record which is going to merge.
2226 * @param int $otherCaseId case id of record which is going to merge.
2227 *
2228 * @return void.
2229 * @static
2230 */
2231 static function mergeCases($mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2232 $otherCaseId = NULL, $changeClient = FALSE ) {
2233 $moveToTrash = TRUE;
2234
2235 $duplicateContacts = FALSE;
2236 if ($mainContactId && $otherContactId &&
2237 $mainContactId != $otherContactId
2238 ) {
2239 $duplicateContacts = TRUE;
2240 }
2241
2242 $duplicateCases = FALSE;
2243 if ($mainCaseId && $otherCaseId &&
2244 $mainCaseId != $otherCaseId
2245 ) {
2246 $duplicateCases = TRUE;
2247 }
2248
2249 $mainCaseIds = array();
2250 if (!$duplicateContacts && !$duplicateCases) {
2251 return $mainCaseIds;
2252 }
2253
2254 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name');
2255 $activityStatuses = CRM_Core_PseudoConstant::activityStatus('name');
2256
2257 $processCaseIds = array($otherCaseId);
2258 if ($duplicateContacts && !$duplicateCases) {
2259 if ($changeClient) {
2260 $processCaseIds = array($mainCaseId);
2261 }
2262 else {
2263 //get all case ids for other contact.
2264 $processCaseIds = self::retrieveCaseIdsByContactId($otherContactId, TRUE);
2265 }
2266 if (!is_array($processCaseIds)) {
2267 return;
2268 }
2269 }
2270
2271 $session = CRM_Core_Session::singleton();
2272 $currentUserId = $session->get('userID');
2273
2274 // copy all cases and connect to main contact id.
2275 foreach ($processCaseIds as $otherCaseId) {
2276 if ($duplicateContacts) {
2277 $mainCase = CRM_Core_DAO::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2278 $mainCaseId = $mainCase->id;
2279 if (!$mainCaseId) {
2280 continue;
2281 }
2282 $mainCase->free();
2283 $mainCaseIds[] = $mainCaseId;
2284 //insert record for case contact.
2285 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2286 $otherCaseContact->case_id = $otherCaseId;
2287 $otherCaseContact->find();
2288 while ($otherCaseContact->fetch()) {
2289 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2290 $mainCaseContact->case_id = $mainCaseId;
2291 $mainCaseContact->contact_id = $otherCaseContact->contact_id;
2292 if ($mainCaseContact->contact_id == $otherContactId) {
2293 $mainCaseContact->contact_id = $mainContactId;
2294 }
2295 //avoid duplicate object.
2296 if (!$mainCaseContact->find(TRUE)) {
2297 $mainCaseContact->save();
2298 }
2299 $mainCaseContact->free();
2300 }
2301 $otherCaseContact->free();
2302 }
2303 elseif (!$otherContactId) {
2304 $otherContactId = $mainContactId;
2305 }
2306
2307 if (!$mainCaseId || !$otherCaseId ||
2308 !$mainContactId || !$otherContactId
2309 ) {
2310 continue;
2311 }
2312
2313 // get all activities for other case.
2314 $otherCaseActivities = array();
2315 CRM_Core_DAO::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2316
2317 //for duplicate cases do not process singleton activities.
2318 $otherActivityIds = $singletonActivityIds = array();
2319 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2320 $otherActId = CRM_Utils_Array::value('activity_id', $otherIds);
2321 if (!$otherActId || in_array($otherActId, $otherActivityIds)) {
2322 continue;
2323 }
2324 $otherActivityIds[] = $otherActId;
2325 }
2326 if ($duplicateCases) {
2327 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2328 $sql = "
2329SELECT id
2330 FROM civicrm_activity
2331 WHERE activity_type_id = $openCaseType
2332 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2333 $dao = CRM_Core_DAO::executeQuery($sql);
2334 while ($dao->fetch()) {
2335 $singletonActivityIds[] = $dao->id;
2336 }
2337 $dao->free();
2338 }
2339 }
2340
2341 // migrate all activities and connect to main contact.
2342 $copiedActivityIds = $activityMappingIds = array();
2343 sort($otherActivityIds);
2344 foreach ($otherActivityIds as $otherActivityId) {
2345
2346 //for duplicate cases -
2347 //do not migrate singleton activities.
2348 if (!$otherActivityId || in_array($otherActivityId, $singletonActivityIds)) {
2349 continue;
2350 }
2351
2352 //migrate activity record.
2353 $otherActivity = new CRM_Activity_DAO_Activity();
2354 $otherActivity->id = $otherActivityId;
2355 if (!$otherActivity->find(TRUE)) {
2356 continue;
2357 }
2358
2359 $mainActVals = array();
2360 $mainActivity = new CRM_Activity_DAO_Activity();
2361 CRM_Core_DAO::storeValues($otherActivity, $mainActVals);
2362 $mainActivity->copyValues($mainActVals);
2363 $mainActivity->id = NULL;
2364 $mainActivity->activity_date_time = CRM_Utils_Date::isoToMysql($otherActivity->activity_date_time);
2365 //do check for merging contact,
2366 if ($mainActivity->source_contact_id == $otherContactId) {
2367 $mainActivity->source_contact_id = $mainContactId;
2368 }
2369 $mainActivity->source_record_id = CRM_Utils_Array::value($mainActivity->source_record_id,
2370 $activityMappingIds
2371 );
2372
2373 $mainActivity->original_id = CRM_Utils_Array::value($mainActivity->original_id,
2374 $activityMappingIds
2375 );
2376
2377 $mainActivity->parent_id = CRM_Utils_Array::value($mainActivity->parent_id,
2378 $activityMappingIds
2379 );
2380 $mainActivity->save();
2381 $mainActivityId = $mainActivity->id;
2382 if (!$mainActivityId) {
2383 continue;
2384 }
2385
2386 $activityMappingIds[$otherActivityId] = $mainActivityId;
2387 // insert log of all activites
2388 CRM_Activity_BAO_Activity::logActivityAction($mainActivity);
2389
2390 $otherActivity->free();
2391 $mainActivity->free();
2392 $copiedActivityIds[] = $otherActivityId;
2393
2394 //create case activity record.
2395 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2396 $mainCaseActivity->case_id = $mainCaseId;
2397 $mainCaseActivity->activity_id = $mainActivityId;
2398 $mainCaseActivity->save();
2399 $mainCaseActivity->free();
2400
2401 //migrate target activities.
2402 $otherTargetActivity = new CRM_Activity_DAO_ActivityTarget();
2403 $otherTargetActivity->activity_id = $otherActivityId;
2404 $otherTargetActivity->find();
2405 while ($otherTargetActivity->fetch()) {
2406 $mainActivityTarget = new CRM_Activity_DAO_ActivityTarget();
2407 $mainActivityTarget->activity_id = $mainActivityId;
2408 $mainActivityTarget->target_contact_id = $otherTargetActivity->target_contact_id;
2409 if ($mainActivityTarget->target_contact_id == $otherContactId) {
2410 $mainActivityTarget->target_contact_id = $mainContactId;
2411 }
2412 //avoid duplicate object.
2413 if (!$mainActivityTarget->find(TRUE)) {
2414 $mainActivityTarget->save();
2415 }
2416 $mainActivityTarget->free();
2417 }
2418 $otherTargetActivity->free();
2419
2420 //migrate assignee activities.
2421 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityAssignment();
2422 $otherAssigneeActivity->activity_id = $otherActivityId;
2423 $otherAssigneeActivity->find();
2424 while ($otherAssigneeActivity->fetch()) {
2425 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityAssignment();
2426 $mainAssigneeActivity->activity_id = $mainActivityId;
2427 $mainAssigneeActivity->assignee_contact_id = $otherAssigneeActivity->assignee_contact_id;
2428 if ($mainAssigneeActivity->assignee_contact_id == $otherContactId) {
2429 $mainAssigneeActivity->assignee_contact_id = $mainContactId;
2430 }
2431 //avoid duplicate object.
2432 if (!$mainAssigneeActivity->find(TRUE)) {
2433 $mainAssigneeActivity->save();
2434 }
2435 $mainAssigneeActivity->free();
2436 }
2437 $otherAssigneeActivity->free();
2438 }
2439
2440 //copy case relationship.
2441 if ($duplicateContacts) {
2442 //migrate relationship records.
2443 $otherRelationship = new CRM_Contact_DAO_Relationship();
2444 $otherRelationship->case_id = $otherCaseId;
2445 $otherRelationship->find();
2446 $otherRelationshipIds = array();
2447 while ($otherRelationship->fetch()) {
2448 $otherRelVals = array();
2449 $updateOtherRel = FALSE;
2450 CRM_Core_DAO::storeValues($otherRelationship, $otherRelVals);
2451
2452 $mainRelationship = new CRM_Contact_DAO_Relationship();
2453 $mainRelationship->copyValues($otherRelVals);
2454 $mainRelationship->id = NULL;
2455 $mainRelationship->case_id = $mainCaseId;
2456 if ($mainRelationship->contact_id_a == $otherContactId) {
2457 $updateOtherRel = TRUE;
2458 $mainRelationship->contact_id_a = $mainContactId;
2459 }
2460
2461 //case creator change only when we merge user contact.
2462 if ($mainRelationship->contact_id_b == $otherContactId) {
2463 //do not change creator for change client.
2464 if (!$changeClient) {
2465 $updateOtherRel = TRUE;
2466 $mainRelationship->contact_id_b = ($currentUserId) ? $currentUserId : $mainContactId;
2467 }
2468 }
2469 $mainRelationship->end_date = CRM_Utils_Date::isoToMysql($otherRelationship->end_date);
2470 $mainRelationship->start_date = CRM_Utils_Date::isoToMysql($otherRelationship->start_date);
2471
2472 //avoid duplicate object.
2473 if (!$mainRelationship->find(TRUE)) {
2474 $mainRelationship->save();
2475 }
2476 $mainRelationship->free();
2477
2478 //get the other relationship ids to update end date.
2479 if ($updateOtherRel) {
2480 $otherRelationshipIds[$otherRelationship->id] = $otherRelationship->id;
2481 }
2482 }
2483 $otherRelationship->free();
2484
2485 //update other relationships end dates
2486 if (!empty($otherRelationshipIds)) {
2487 $sql = 'UPDATE civicrm_relationship
2488 SET end_date = CURDATE()
2489 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2490 CRM_Core_DAO::executeQuery($sql);
2491 }
2492 }
2493
2494 //move other case to trash.
2495 $mergeCase = self::deleteCase($otherCaseId, $moveToTrash);
2496 if (!$mergeCase) {
2497 continue;
2498 }
2499
2500 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2501 if ($changeClient) {
2502 $mainContactDisplayName = CRM_Contact_BAO_Contact::displayName($mainContactId);
2503 $otherContactDisplayName = CRM_Contact_BAO_Contact::displayName($otherContactId);
2504
2505 $mergeActType = array_search('Reassigned Case', $activityTypes);
2506 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2507 array(
2508 1 => $otherCaseId, 2 => $otherContactDisplayName,
2509 3 => $mainContactDisplayName, 4 => $mainCaseId,
2510 )
2511 );
2512 }
2513 elseif ($duplicateContacts) {
2514 $mergeActType = array_search('Merge Case', $activityTypes);
2515 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2516 array(
2517 1 => $otherCaseId, 2 => $otherContactId,
2518 3 => $mainContactId, 4 => $mainCaseId,
2519 )
2520 );
2521 }
2522 else {
2523 $mergeActType = array_search('Merge Case', $activityTypes);
2524 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2525 if (!empty($copiedActivityIds)) {
2526 $sql = '
2527SELECT id, subject, activity_date_time, activity_type_id
2528FROM civicrm_activity
2529WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2530 $dao = CRM_Core_DAO::executeQuery($sql);
2531 while ($dao->fetch()) {
2532 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2533 if ($dao->subject) {
2534 $mergeActSubjectDetails .= " :: {$dao->subject}";
2535 }
2536 $mergeActSubjectDetails .= "<br />";
2537 }
2538 }
2539 }
2540
2541 //create merge activity record.
2542 $activityParams = array(
2543 'subject' => $mergeActSubject,
2544 'details' => $mergeActSubjectDetails,
2545 'status_id' => array_search('Completed', $activityStatuses),
2546 'activity_type_id' => $mergeActType,
2547 'source_contact_id' => $mainContactId,
2548 'activity_date_time' => date('YmdHis'),
2549 );
2550
2551 $mergeActivity = CRM_Activity_BAO_Activity::create($activityParams);
2552 $mergeActivityId = $mergeActivity->id;
2553 if (!$mergeActivityId) {
2554 continue;
2555 }
2556 $mergeActivity->free();
2557
2558 //connect merge activity to case.
2559 $mergeCaseAct = array(
2560 'case_id' => $mainCaseId,
2561 'activity_id' => $mergeActivityId,
2562 );
2563
2564 self::processCaseActivity($mergeCaseAct);
2565 }
2566 return $mainCaseIds;
2567 }
2568
2569 /**
2570 * Validate contact permission for
2571 * edit/view on activity record and build links.
2572 *
2573 * @param array $tplParams params to be sent to template for sending email.
2574 * @param array $activityParams info of the activity.
2575 *
2576 * @return void
2577 * @static
2578 */
2579 static function buildPermissionLinks(&$tplParams, $activityParams) {
2580 $activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2581 'activity_type_id', 'id'
2582 );
2583
2584 if (CRM_Utils_Array::value('isCaseActivity', $tplParams)) {
2585 $tplParams['editActURL'] = CRM_Utils_System::url('civicrm/case/activity',
2586 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2587 );
2588
2589 $tplParams['viewActURL'] = CRM_Utils_System::url('civicrm/case/activity/view',
2590 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2591 );
2592
2593 $tplParams['manageCaseURL'] = CRM_Utils_System::url('civicrm/contact/view/case',
2594 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2595 );
2596 }
2597 else {
2598 $tplParams['editActURL'] = CRM_Utils_System::url('civicrm/contact/view/activity',
2599 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2600 );
2601
2602 $tplParams['viewActURL'] = CRM_Utils_System::url('civicrm/contact/view/activity',
2603 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2604 );
2605 }
2606 }
2607
2608 /**
2609 * Validate contact permission for
2610 * given operation on activity record.
2611 *
2612 * @param int $activityId activity record id.
2613 * @param string $operation user operation.
2614 * @param int $actTypeId activity type id.
2615 * @param int $contactId contact id/if not pass consider logged in
2616 * @param boolean $checkComponent do we need to check component enabled.
2617 *
2618 * @return boolean $allow true/false
2619 * @static
2620 */
2621 static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2622 $allow = FALSE;
2623 if (!$actTypeId && $activityId) {
2624 $actTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2625 }
2626
2627 if (!$activityId || !$operation || !$actTypeId) {
2628 return $allow;
2629 }
2630
2631 //do check for civicase component enabled.
2632 if ($checkComponent) {
2633 static $componentEnabled;
2634 if (!isset($componentEnabled)) {
2635 $config = CRM_Core_Config::singleton();
2636 $componentEnabled = FALSE;
2637 if (in_array('CiviCase', $config->enableComponents)) {
2638 $componentEnabled = TRUE;
2639 }
2640 }
2641 if (!$componentEnabled) {
2642 return $allow;
2643 }
2644 }
2645
2646 //do check for cases.
2647 $caseActOperations = array(
2648 'File On Case',
2649 'Link Cases',
2650 'Move To Case',
2651 'Copy To Case',
2652 );
2653
2654 if (in_array($operation, $caseActOperations)) {
2655 static $unclosedCases;
2656 if (!is_array($unclosedCases)) {
2657 $unclosedCases = self::getUnclosedCases();
2658 }
2659 if ($operation == 'File On Case') {
2660 $allow = (empty($unclosedCases)) ? FALSE : TRUE;
2661 }
2662 else {
2663 $allow = (count($unclosedCases) > 1) ? TRUE : FALSE;
2664 }
2665 }
2666
2667 $actionOperations = array('view', 'edit', 'delete');
2668 if (in_array($operation, $actionOperations)) {
2669
2670 //do cache when user has non/supper permission.
2671 static $allowOperations;
2672
2673 if (!is_array($allowOperations) ||
2674 !array_key_exists($operation, $allowOperations)
2675 ) {
2676
2677 if (!$contactId) {
2678 $session = CRM_Core_Session::singleton();
2679 $contactId = $session->get('userID');
2680 }
2681
2682 //check for permissions.
2683 $permissions = array(
2684 'view' => array(
2685 'access my cases and activities',
2686 'access all cases and activities',
2687 ),
2688 'edit' => array(
2689 'access my cases and activities',
2690 'access all cases and activities',
2691 ),
2692 'delete' => array('delete activities'),
2693 );
2694
2695 //check for core permission.
2696 $hasPermissions = array();
2697 $checkPermissions = CRM_Utils_Array::value($operation, $permissions);
2698 if (is_array($checkPermissions)) {
2699 foreach ($checkPermissions as $per) {
2700 if (CRM_Core_Permission::check($per)) {
2701 $hasPermissions[$operation][] = $per;
2702 }
2703 }
2704 }
2705
2706 //has permissions.
2707 if (!empty($hasPermissions)) {
2708 //need to check activity object specific.
2709 if (in_array($operation, array(
2710 'view', 'edit'))) {
2711 //do we have supper permission.
2712 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2713 $allowOperations[$operation] = $allow = TRUE;
2714 }
2715 else {
2716 //user has only access to my cases and activity.
2717 //here object specific permmions come in picture.
2718
2719 //edit - contact must be source or assignee
2720 //view - contact must be source/assignee/target
2721 $isTarget = $isAssignee = $isSource = FALSE;
2722
2723 $target = new CRM_Activity_DAO_ActivityTarget();
2724 $target->activity_id = $activityId;
2725 $target->target_contact_id = $contactId;
2726 if ($target->find(TRUE)) {
2727 $isTarget = TRUE;
2728 }
2729
2730 $assignee = new CRM_Activity_DAO_ActivityAssignment();
2731 $assignee->activity_id = $activityId;
2732 $assignee->assignee_contact_id = $contactId;
2733 if ($assignee->find(TRUE)) {
2734 $isAssignee = TRUE;
2735 }
2736
2737 $activity = new CRM_Activity_DAO_Activity();
2738 $activity->id = $activityId;
2739 $activity->source_contact_id = $contactId;
2740 if ($activity->find(TRUE)) {
2741 $isSource = TRUE;
2742 }
2743
2744 if ($operation == 'edit') {
2745 if ($isAssignee || $isSource) {
2746 $allow = TRUE;
2747 }
2748 }
2749 if ($operation == 'view') {
2750 if ($isTarget || $isAssignee || $isSource) {
2751 $allow = TRUE;
2752 }
2753 }
2754 }
2755 }
2756 elseif (is_array($hasPermissions[$operation])) {
2757 $allowOperations[$operation] = $allow = TRUE;
2758 }
2759 }
2760 else {
2761 //contact do not have permission.
2762 $allowOperations[$operation] = FALSE;
2763 }
2764 }
2765 else {
2766 //use cache.
2767 //here contact might have supper/non permission.
2768 $allow = $allowOperations[$operation];
2769 }
2770 }
2771
2772 //do further only when operation is granted.
2773 if ($allow) {
2774 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name');
2775
2776 //get the activity type name.
2777 $actTypeName = CRM_Utils_Array::value($actTypeId, $activityTypes);
2778
2779 //do not allow multiple copy / edit action.
2780 $singletonNames = array('Open Case', 'Reassigned Case', 'Merge Case', 'Link Cases', 'Assign Case Role', 'Email', 'Inbound Email');
2781
2782 //do not allow to delete these activities, CRM-4543
2783 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2784
2785 //allow edit operation.
2786 $allowEditNames = array('Open Case');
2787
2788 // do not allow File on Case
2789 $doNotFileNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date','Reassigned Case', 'Merge Case', 'Link Cases', 'Assign Case Role');
2790
2791 if (in_array($actTypeName, $singletonNames)) {
2792 $allow = FALSE;
2793 if ($operation == 'File On Case') {
2794 $allow = (in_array($actTypeName, $doNotFileNames)) ? FALSE : TRUE;
2795 }
2796 if (in_array($operation, $actionOperations)) {
2797 $allow = TRUE;
2798 if ($operation == 'edit') {
2799 $allow = (in_array($actTypeName, $allowEditNames)) ? TRUE : FALSE;
2800 }
2801 elseif ($operation == 'delete') {
2802 $allow = (in_array($actTypeName, $doNotDeleteNames)) ? FALSE : TRUE;
2803 }
2804 }
2805 }
2806 if ($allow && ($operation == 'delete') &&
2807 in_array($actTypeName, $doNotDeleteNames)
2808 ) {
2809 $allow = FALSE;
2810 }
2811
2812 if ($allow && ($operation == 'File On Case') &&
2813 in_array($actTypeName, $doNotFileNames)
2814 ) {
2815 $allow = FALSE;
2816 }
2817
2818 //check settings file for masking actions
2819 //on the basis the activity types
2820 //hide Edit link if activity type is NOT editable
2821 //(special case activities).CRM-5871
2822 if ($allow && in_array($operation, $actionOperations)) {
2823 static $actionFilter = array();
2824 if (!array_key_exists($operation, $actionFilter)) {
2825 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2826 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2827 }
2828 if (array_key_exists($operation, $actionFilter[$operation]) &&
2829 in_array($actTypeId, $actionFilter[$operation][$operation])
2830 ) {
2831 $allow = FALSE;
2832 }
2833 }
2834 }
2835
2836 return $allow;
2837 }
2838
2839 /**
2840 * since we drop 'access CiviCase', allow access
2841 * if user has 'access my cases and activities'
2842 * or 'access all cases and activities'
2843 */
2844 static function accessCiviCase() {
2845 static $componentEnabled;
2846 if (!isset($componentEnabled)) {
2847 $componentEnabled = FALSE;
2848 $config = CRM_Core_Config::singleton();
2849 if (in_array('CiviCase', $config->enableComponents)) {
2850 $componentEnabled = TRUE;
2851 }
2852 }
2853 if (!$componentEnabled) {
2854 return FALSE;
2855 }
2856
2857 if (CRM_Core_Permission::check('access my cases and activities') ||
2858 CRM_Core_Permission::check('access all cases and activities')
2859 ) {
2860 return TRUE;
2861 }
2862
2863 return FALSE;
2864 }
2865
2866 /**
2867 * Function to check whether activity is a case Activity
2868 *
2869 * @param int $activityID activity id
2870 *
2871 * @return boolean $isCaseActivity true/false
2872 */
2873 static function isCaseActivity($activityID) {
2874 $isCaseActivity = FALSE;
2875 if ($activityID) {
2876 $params = array(1 => array($activityID, 'Integer'));
2877 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
2878 if (CRM_Core_DAO::singleValueQuery($query, $params)) {
2879 $isCaseActivity = TRUE;
2880 }
2881 }
2882
2883 return $isCaseActivity;
2884 }
2885
2886 /**
2887 * Function to get all the case type ids currently in use
2888 *
2889 *
2890 * @return array $caseTypeIds
2891 */
2892 static function getUsedCaseType() {
2893 static $caseTypeIds;
2894
2895 if (!is_array($caseTypeIds)) {
2896 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
2897
2898 $dao = CRM_Core_DAO::executeQuery($query);
2899 $caseTypeIds = array();
2900 while ($dao->fetch()) {
2901 $typeId = explode(CRM_Core_DAO::VALUE_SEPARATOR,
2902 $dao->case_type_id
2903 );
2904 $caseTypeIds[] = $typeId[1];
2905 }
2906 }
2907
2908 return $caseTypeIds;
2909 }
2910
2911 /**
2912 * Function to get all the case status ids currently in use
2913 *
2914 *
2915 * @return array $caseStatusIds
2916 */
2917 static function getUsedCaseStatuses() {
2918 static $caseStatusIds;
2919
2920 if (!is_array($caseStatusIds)) {
2921 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
2922
2923 $dao = CRM_Core_DAO::executeQuery($query);
2924 $caseStatusIds = array();
2925 while ($dao->fetch()) {
2926 $caseStatusIds[] = $dao->status_id;
2927 }
2928 }
2929
2930 return $caseStatusIds;
2931 }
2932
2933 /**
2934 * Function to get all the encounter medium ids currently in use
2935 *
2936 *
2937 * @return array
2938 */
2939 static function getUsedEncounterMediums() {
2940 static $mediumIds;
2941
2942 if (!is_array($mediumIds)) {
2943 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
2944
2945 $dao = CRM_Core_DAO::executeQuery($query);
2946 $mediumIds = array();
2947 while ($dao->fetch()) {
2948 $mediumIds[] = $dao->medium_id;
2949 }
2950 }
2951
2952 return $mediumIds;
2953 }
2954
2955 /**
2956 * Function to check case configuration.
2957 *
2958 * @return an array $configured
2959 */
2960 static function isCaseConfigured($contactId = NULL) {
2961 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
2962
2963 //lets check for case configured.
2964 $allCasesCount = CRM_Case_BAO_Case::caseCount(NULL, FALSE);
2965 $configured['configured'] = ($allCasesCount) ? TRUE : FALSE;
2966 if (!$configured['configured']) {
2967 //do check for case type and case status.
2968 $caseTypes = CRM_Case_PseudoConstant::caseType('label', FALSE);
2969 if (!empty($caseTypes)) {
2970 $configured['configured'] = TRUE;
2971 if (!$configured['configured']) {
2972 $caseStatuses = CRM_Case_PseudoConstant::caseStatus('label', FALSE);
2973 if (!empty($caseStatuses)) {
2974 $configured['configured'] = TRUE;
2975 }
2976 }
2977 }
2978 }
2979 if ($configured['configured']) {
2980 //do check for active case type and case status.
2981 $caseTypes = CRM_Case_PseudoConstant::caseType();
2982 if (!empty($caseTypes)) {
2983 $caseStatuses = CRM_Case_PseudoConstant::caseStatus();
2984 if (!empty($caseStatuses)) {
2985 $configured['allowToAddNewCase'] = TRUE;
2986 }
2987 }
2988
2989 //do we need to redirect user to case admin.
2990 if (!$configured['allowToAddNewCase'] && $contactId) {
2991 //check for current contact case count.
2992 $currentContatCasesCount = CRM_Case_BAO_Case::caseCount($contactId);
2993 //redirect user to case admin page.
2994 if (!$currentContatCasesCount) {
2995 $configured['redirectToCaseAdmin'] = TRUE;
2996 }
2997 }
2998 }
2999
3000 return $configured;
3001 }
3002
3003 /*
3004 * Used during case component enablement and during ugprade
3005 */
3006 static function createCaseViews() {
3007 $sql = self::createCaseViewsQuery('upcoming');
3008 CRM_Core_Error::ignoreException();
3009 $dao = new CRM_Core_DAO();
3010 $dao->query($sql);
3011 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
3012 CRM_Core_Error::setCallback();
3013 return FALSE;
3014 }
3015
3016 // Above error doesn't get caught?
3017 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3018 if (is_null($doublecheck)) {
3019 return FALSE;
3020 }
3021
3022 $sql = self::createCaseViewsQuery('recent');
3023 CRM_Core_Error::ignoreException();
3024 $dao->query($sql);
3025 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
3026 CRM_Core_Error::setCallback();
3027 return FALSE;
3028 }
3029
3030 // Above error doesn't get caught?
3031 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3032 if (is_null($doublecheck)) {
3033 return FALSE;
3034 }
3035
3036 return TRUE;
3037 }
3038
3039 /*
3040 * helper function, also used by the upgrade in case of error
3041 */
3042 static function createCaseViewsQuery($section = 'upcoming') {
3043 $sql = "";
3044 $scheduled_id = CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled', 'name');
3045 switch ($section) {
3046 case 'upcoming':
3047 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3048 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3049 FROM civicrm_case_activity ca
3050 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3051 WHERE a.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3052 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id = $scheduled_id";
3053 break;
3054
3055 case 'recent':
3056 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3057 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3058 FROM civicrm_case_activity ca
3059 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3060 WHERE a.activity_date_time <= NOW()
3061 AND a.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3062 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id <> $scheduled_id";
3063 break;
3064 }
3065
3066 return $sql;
3067 }
3068}
3069