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