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