Merge remote-tracking branch 'upstream/4.4' into 4.4-master-2014-02-06-10-43-01
[civicrm-core.git] / CRM / Case / BAO / Case.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35
36 /**
37 * This class contains the 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 $subject = '<a href="javascript:' . $type . 'viewActivity(' . $dao->id . ',' . $contactID . ',' . '\'' . $type . '\' );" title=\'' . $viewTitle . '\'>' . $subject . '</a>';
1248 }
1249 $values[$dao->id]['subject'] = $subject;
1250
1251 // add activity assignee to activity selector. CRM-4485.
1252 if (isset($dao->assignee)) {
1253 if ($dao->ismultiple == 1) {
1254 if ($dao->reporter_id != $dao->assignee_id) {
1255 $values[$dao->id]['reporter'] .= ($hasViewContact) ? ' / ' . "<a href='{$contactViewUrl}{$dao->assignee_id}'>$dao->assignee</a>" : ' / ' . $dao->assignee;
1256 }
1257 $values[$dao->id]['assignee'] = $dao->assignee;
1258 }
1259 else {
1260 $values[$dao->id]['reporter'] .= ' / ' . ts('(multiple)');
1261 }
1262 }
1263 $url = "";
1264 $additionalUrl = "&id={$dao->id}";
1265 if (!$dao->deleted) {
1266 //hide edit link of activity type email.CRM-4530.
1267 if (!in_array($dao->type, $emailActivityTypeIDs)) {
1268 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
1269 if ($allowEdit) {
1270 $url = '<a href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
1271 }
1272 }
1273 if ($allowDelete) {
1274 if (!empty($url)) {
1275 $url .= " | ";
1276 }
1277 $url .= '<a href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
1278 }
1279 }
1280 elseif (!$caseDeleted) {
1281 $url = '<a 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 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 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 >" . ts('View Attachment') . '</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('sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1761 $return = array('contact_id' => 1, 'sort_name' => 1, 'display_name' => 1, 'email' => 1, 'phone' => 1);
1762 list($globalContacts, $_) = CRM_Contact_BAO_Query::apiQuery($params, $return, NULL, $sort, $offset, $rowCount, TRUE, $returnOnlyCount);
1763
1764 if ($returnOnlyCount) {
1765 return $globalContacts;
1766 }
1767
1768 if ($showLinks) {
1769 foreach ($globalContacts as $idx => $contact) {
1770 $globalContacts[$idx]['sort_name'] = '<a href="' . $contactViewUrl . $contact['contact_id'] . '">' . $contact['sort_name'] . '</a>';
1771 }
1772 }
1773 }
1774 }
1775 }
1776 return $globalContacts;
1777 }
1778
1779 /*
1780 * Convenience function to get both case contacts and global in one array
1781 */
1782 static function getRelatedAndGlobalContacts($caseId) {
1783 $relatedContacts = self::getRelatedContacts($caseId);
1784
1785 $groupInfo = array();
1786 $globalContacts = self::getGlobalContacts($groupInfo);
1787
1788 //unset values which are not required.
1789 foreach ($globalContacts as $k => & $v) {
1790 unset($v['email_id']);
1791 unset($v['group_contact_id']);
1792 unset($v['status']);
1793 unset($v['phone']);
1794 $v['role'] = $groupInfo['title'];
1795 }
1796 //include multiple listings for the same contact/different roles.
1797 $relatedGlobalContacts = array_merge($relatedContacts, $globalContacts);
1798 return $relatedGlobalContacts;
1799 }
1800
1801 /**
1802 * Function to get Case ActivitiesDueDates with given criteria.
1803 *
1804 * @param int $caseID case id
1805 * @param array $criteriaParams given criteria
1806 * @param boolean $latestDate if set newest or oldest date is selceted.
1807 *
1808 * @return returns case activities due dates
1809 *
1810 * @static
1811 */
1812 static function getCaseActivityDates($caseID, $criteriaParams = array(), $latestDate = FALSE) {
1813 $values = array();
1814 $selectDate = " ca.activity_date_time";
1815 $where = $groupBy = ' ';
1816
1817 if (!$caseID) {
1818 return;
1819 }
1820
1821 if ($latestDate) {
1822 if (!empty($criteriaParams['activity_type_id'])) {
1823 $where .= " AND ca.activity_type_id = " . CRM_Utils_Type::escape($criteriaParams['activity_type_id'], 'Integer');
1824 $where .= " AND ca.is_current_revision = 1";
1825 $groupBy .= " GROUP BY ca.activity_type_id";
1826 }
1827
1828 if (!empty($criteriaParams['newest'])) {
1829 $selectDate = " max(ca.activity_date_time) ";
1830 }
1831 else {
1832 $selectDate = " min(ca.activity_date_time) ";
1833 }
1834 }
1835
1836 $query = "SELECT ca.id, {$selectDate} as activity_date
1837 FROM civicrm_activity ca
1838 LEFT JOIN civicrm_case_activity cca ON cca.activity_id = ca.id LEFT JOIN civicrm_case cc ON cc.id = cca.case_id
1839 WHERE cc.id = %1 {$where} {$groupBy}";
1840
1841 $params = array(1 => array($caseID, 'Integer'));
1842 $dao = CRM_Core_DAO::executeQuery($query, $params);
1843
1844 while ($dao->fetch()) {
1845 $values[$dao->id]['id'] = $dao->id;
1846 $values[$dao->id]['activity_date'] = $dao->activity_date;
1847 }
1848 $dao->free();
1849 return $values;
1850 }
1851
1852 /**
1853 * Function to create activities when Case or Other roles assigned/modified/deleted.
1854 *
1855 * @param int $caseID case id
1856 * @param int $relationshipId relationship id
1857 * @param int $relContactId case role assignee contactId.
1858 *
1859 * @return void on success creates activity and case activity
1860 *
1861 * @static
1862 */
1863 static function createCaseRoleActivity($caseId, $relationshipId, $relContactId = NULL, $contactId = NULL) {
1864 if (!$caseId || !$relationshipId || empty($relationshipId)) {
1865 return;
1866 }
1867
1868 $queryParam = array();
1869 if (is_array($relationshipId)) {
1870 $relationshipId = implode(',', $relationshipId);
1871 $relationshipClause = " civicrm_relationship.id IN ($relationshipId)";
1872 }
1873 else {
1874 $relationshipClause = " civicrm_relationship.id = %1";
1875 $queryParam[1] = array($relationshipId, 'Positive');
1876 }
1877
1878 $query = "
1879 SELECT cc.display_name as clientName,
1880 cca.display_name as assigneeContactName,
1881 civicrm_relationship.case_id as caseId,
1882 civicrm_relationship_type.label_a_b as relation_a_b,
1883 civicrm_relationship_type.label_b_a as relation_b_a,
1884 civicrm_relationship.contact_id_b as rel_contact_id,
1885 civicrm_relationship.contact_id_a as assign_contact_id
1886 FROM civicrm_relationship_type, civicrm_relationship
1887 LEFT JOIN civicrm_contact cc ON cc.id = civicrm_relationship.contact_id_b
1888 LEFT JOIN civicrm_contact cca ON cca.id = civicrm_relationship.contact_id_a
1889 WHERE civicrm_relationship.relationship_type_id = civicrm_relationship_type.id AND {$relationshipClause}";
1890
1891 $dao = CRM_Core_DAO::executeQuery($query, $queryParam);
1892
1893 while ($dao->fetch()) {
1894 //to get valid assignee contact(s).
1895 if (isset($dao->caseId) || $dao->rel_contact_id != $contactId) {
1896 $caseRelationship = $dao->relation_a_b;
1897 $assigneContactName = $dao->clientName;
1898 $assigneContactIds[$dao->rel_contact_id] = $dao->rel_contact_id;
1899 }
1900 else {
1901 $caseRelationship = $dao->relation_b_a;
1902 $assigneContactName = $dao->assigneeContactName;
1903 $assigneContactIds[$dao->assign_contact_id] = $dao->assign_contact_id;
1904 }
1905 }
1906
1907 $session = CRM_Core_Session::singleton();
1908 $activityParams = array(
1909 'source_contact_id' => $session->get('userID'),
1910 'subject' => $caseRelationship . ' : ' . $assigneContactName,
1911 'activity_date_time' => date('YmdHis'),
1912 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'),
1913 );
1914
1915 //if $relContactId is passed, role is added or modified.
1916 if (!empty($relContactId)) {
1917 $activityParams['assignee_contact_id'] = $assigneContactIds;
1918
1919 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1920 'Assign Case Role',
1921 'name'
1922 );
1923 }
1924 else {
1925 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
1926 'Remove Case Role',
1927 'name'
1928 );
1929 }
1930
1931 $activityParams['activity_type_id'] = $activityTypeID;
1932
1933 $activity = CRM_Activity_BAO_Activity::create($activityParams);
1934
1935 //create case_activity record.
1936 $caseParams = array(
1937 'activity_id' => $activity->id,
1938 'case_id' => $caseId,
1939 );
1940
1941 CRM_Case_BAO_Case::processCaseActivity($caseParams);
1942 }
1943
1944 /**
1945 * Function to get case manger
1946 * contact which is assigned a case role of case manager.
1947 *
1948 * @param int $caseType case type
1949 * @param int $caseId case id
1950 *
1951 * @return array $caseManagerContact array of contact on success otherwise empty
1952 *
1953 * @static
1954 */
1955 static function getCaseManagerContact($caseType, $caseId) {
1956 if (!$caseType || !$caseId) {
1957 return;
1958 }
1959
1960 $caseManagerContact = array();
1961 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
1962
1963 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseType);
1964
1965 if (!empty($managerRoleId)) {
1966 $managerRoleQuery = "
1967 SELECT civicrm_contact.id as casemanager_id,
1968 civicrm_contact.sort_name as casemanager
1969 FROM civicrm_contact
1970 LEFT JOIN civicrm_relationship ON (civicrm_relationship.contact_id_b = civicrm_contact.id AND civicrm_relationship.relationship_type_id = %1)
1971 LEFT JOIN civicrm_case ON civicrm_case.id = civicrm_relationship.case_id
1972 WHERE civicrm_case.id = %2";
1973
1974 $managerRoleParams = array(
1975 1 => array($managerRoleId, 'Integer'),
1976 2 => array($caseId, 'Integer'),
1977 );
1978
1979 $dao = CRM_Core_DAO::executeQuery($managerRoleQuery, $managerRoleParams);
1980 if ($dao->fetch()) {
1981 $caseManagerContact['casemanager_id'] = $dao->casemanager_id;
1982 $caseManagerContact['casemanager'] = $dao->casemanager;
1983 }
1984 }
1985
1986 return $caseManagerContact;
1987 }
1988
1989 /**
1990 * Get all cases with no end dates
1991 *
1992 * @return array of case and related data keyed on case id
1993 */
1994 static function getUnclosedCases($params = array(), $excludeCaseIds = array(), $excludeDeleted = TRUE) {
1995 //params from ajax call.
1996 $where = array('( ca.end_date is null )');
1997 if ($caseType = CRM_Utils_Array::value('case_type', $params)) {
1998 $where[] = "( ov.label LIKE '%$caseType%' )";
1999 }
2000 if ($sortName = CRM_Utils_Array::value('sort_name', $params)) {
2001 $config = CRM_Core_Config::singleton();
2002 $search = ($config->includeWildCardInName) ? "%$sortName%" : "$sortName%";
2003 $where[] = "( sort_name LIKE '$search' )";
2004 }
2005 if (is_array($excludeCaseIds) &&
2006 !CRM_Utils_System::isNull($excludeCaseIds)
2007 ) {
2008 $where[] = ' ( ca.id NOT IN ( ' . implode(',', $excludeCaseIds) . ' ) ) ';
2009 }
2010 if ($excludeDeleted) {
2011 $where[] = ' ( ca.is_deleted = 0 OR ca.is_deleted IS NULL ) ';
2012 }
2013
2014 //filter for permissioned cases.
2015 $filterCases = array();
2016 $doFilterCases = FALSE;
2017 if (!CRM_Core_Permission::check('access all cases and activities')) {
2018 $doFilterCases = TRUE;
2019 $session = CRM_Core_Session::singleton();
2020 $filterCases = CRM_Case_BAO_Case::getCases(FALSE, $session->get('userID'));
2021 }
2022 $whereClause = implode(' AND ', $where);
2023
2024 $limitClause = '';
2025 if ($limit = CRM_Utils_Array::value('limit', $params)) {
2026 $limitClause = "LIMIT 0, $limit";
2027 }
2028
2029 $query = "
2030 SELECT c.id as contact_id,
2031 c.sort_name,
2032 ca.id,
2033 ca.subject as case_subject,
2034 ov.label as case_type,
2035 ca.start_date as start_date
2036 FROM civicrm_case ca INNER JOIN civicrm_case_contact cc ON ca.id=cc.case_id
2037 INNER JOIN civicrm_contact c ON cc.contact_id=c.id
2038 INNER JOIN civicrm_option_group og ON og.name='case_type'
2039 INNER JOIN civicrm_option_value ov ON (ca.case_type_id=ov.value AND ov.option_group_id=og.id)
2040 WHERE {$whereClause}
2041 ORDER BY c.sort_name
2042 {$limitClause}
2043 ";
2044 $dao = CRM_Core_DAO::executeQuery($query);
2045 $unclosedCases = array();
2046 while ($dao->fetch()) {
2047 if ($doFilterCases && !array_key_exists($dao->id, $filterCases)) {
2048 continue;
2049 }
2050 $unclosedCases[$dao->id] = array(
2051 'sort_name' => $dao->sort_name,
2052 'case_type' => $dao->case_type,
2053 'contact_id' => $dao->contact_id,
2054 'start_date' => $dao->start_date,
2055 'case_subject' => $dao->case_subject,
2056 );
2057 }
2058 $dao->free();
2059
2060 return $unclosedCases;
2061 }
2062
2063 static function caseCount($contactId = NULL, $excludeDeleted = TRUE) {
2064 $whereConditions = array();
2065 if ($excludeDeleted) {
2066 $whereConditions[] = "( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2067 }
2068 if ($contactId) {
2069 $whereConditions[] = "civicrm_case_contact.contact_id = {$contactId}";
2070 }
2071 if (!CRM_Core_Permission::check('access all cases and activities')) {
2072 static $accessibleCaseIds;
2073 if (!is_array($accessibleCaseIds)) {
2074 $session = CRM_Core_Session::singleton();
2075 $accessibleCaseIds = array_keys(self::getCases(FALSE, $session->get('userID'), 'any'));
2076 }
2077 //no need of further processing.
2078 if (empty($accessibleCaseIds)) {
2079 return 0;
2080 }
2081 $whereConditions[] = "( civicrm_case.id in (" . implode(',', $accessibleCaseIds) . ") )";
2082 }
2083
2084 $whereClause = '';
2085 if (!empty($whereConditions)) {
2086 $whereClause = "WHERE " . implode(' AND ', $whereConditions);
2087 }
2088
2089 $query = "
2090 SELECT count( civicrm_case.id )
2091 FROM civicrm_case
2092 LEFT JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2093 {$whereClause}";
2094
2095 return CRM_Core_DAO::singleValueQuery($query);
2096 }
2097
2098 /**
2099 * Retrieve cases related to particular contact.
2100 *
2101 * @param int $contactId contact id
2102 * @param boolean $excludeDeleted do not include deleted cases.
2103 *
2104 * @return an array of cases.
2105 *
2106 * @access public
2107 */
2108 static function getContactCases($contactId, $excludeDeleted = TRUE) {
2109 $cases = array();
2110 if (!$contactId) {
2111 return $cases;
2112 }
2113
2114 $whereClause = "civicrm_case_contact.contact_id = %1";
2115 if ($excludeDeleted) {
2116 $whereClause .= " AND ( civicrm_case.is_deleted = 0 OR civicrm_case.is_deleted IS NULL )";
2117 }
2118
2119 $query = "
2120 SELECT civicrm_case.id, case_type_ov.label as case_type, civicrm_case.start_date
2121 FROM civicrm_case
2122 INNER JOIN civicrm_case_contact ON ( civicrm_case.id = civicrm_case_contact.case_id )
2123 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2124 LEFT JOIN civicrm_option_value case_type_ov ON ( civicrm_case.case_type_id = case_type_ov.value
2125 AND case_type_og.id = case_type_ov.option_group_id )
2126 WHERE {$whereClause}";
2127
2128 $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($contactId, 'Integer')));
2129 while ($dao->fetch()) {
2130 $cases[$dao->id] = array(
2131 'case_id' => $dao->id,
2132 'case_type' => $dao->case_type,
2133 'case_start_date' => $dao->start_date,
2134 );
2135 }
2136 $dao->free();
2137
2138 return $cases;
2139 }
2140
2141 /**
2142 * Retrieve related cases for give case.
2143 *
2144 * @param int $mainCaseId id of main case
2145 * @param int $contactId id of contact
2146 * @param boolean $excludeDeleted do not include deleted cases.
2147 *
2148 * @return an array of related cases.
2149 *
2150 * @access public
2151 */
2152 static function getRelatedCases($mainCaseId, $contactId, $excludeDeleted = TRUE) {
2153 //FIXME : do check for permissions.
2154
2155 $relatedCases = array();
2156 if (!$mainCaseId || !$contactId) {
2157 return $relatedCases;
2158 }
2159
2160 $linkActType = array_search('Link Cases',
2161 CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name')
2162 );
2163 if (!$linkActType) {
2164 return $relatedCases;
2165 }
2166
2167 $whereClause = "mainCase.id = %2";
2168 if ($excludeDeleted) {
2169 $whereClause .= " AND ( relAct.is_deleted = 0 OR relAct.is_deleted IS NULL )";
2170 }
2171
2172 //1. first fetch related case ids.
2173 $query = "
2174 SELECT relCaseAct.case_id
2175 FROM civicrm_case mainCase
2176 INNER JOIN civicrm_case_activity mainCaseAct ON (mainCaseAct.case_id = mainCase.id)
2177 INNER JOIN civicrm_activity mainAct ON (mainCaseAct.activity_id = mainAct.id AND mainAct.activity_type_id = %1)
2178 INNER JOIN civicrm_case_activity relCaseAct ON (relCaseAct.activity_id = mainAct.id AND mainCaseAct.id != relCaseAct.id)
2179 INNER JOIN civicrm_activity relAct ON (relCaseAct.activity_id = relAct.id AND relAct.activity_type_id = %1)
2180 WHERE $whereClause";
2181
2182 $dao = CRM_Core_DAO::executeQuery($query, array(
2183 1 => array($linkActType, 'Integer'),
2184 2 => array($mainCaseId, 'Integer'),
2185 ));
2186 $relatedCaseIds = array();
2187 while ($dao->fetch()) {
2188 $relatedCaseIds[$dao->case_id] = $dao->case_id;
2189 }
2190 $dao->free();
2191
2192 // there are no related cases.
2193 if (empty($relatedCaseIds)) {
2194 return $relatedCases;
2195 }
2196
2197 $whereClause = 'relCase.id IN ( ' . implode(',', $relatedCaseIds) . ' )';
2198 if ($excludeDeleted) {
2199 $whereClause .= " AND ( relCase.is_deleted = 0 OR relCase.is_deleted IS NULL )";
2200 }
2201
2202 //filter for permissioned cases.
2203 $filterCases = array();
2204 $doFilterCases = FALSE;
2205 if (!CRM_Core_Permission::check('access all cases and activities')) {
2206 $doFilterCases = TRUE;
2207 $session = CRM_Core_Session::singleton();
2208 $filterCases = CRM_Case_BAO_Case::getCases(FALSE, $session->get('userID'));
2209 }
2210
2211 //2. fetch the details of related cases.
2212 $query = "
2213 SELECT relCase.id as id,
2214 case_type_ov.label as case_type,
2215 client.display_name as client_name,
2216 client.id as client_id
2217 FROM civicrm_case relCase
2218 INNER JOIN civicrm_case_contact relCaseContact ON ( relCase.id = relCaseContact.case_id )
2219 INNER JOIN civicrm_contact client ON ( client.id = relCaseContact.contact_id )
2220 LEFT JOIN civicrm_option_group case_type_og ON ( case_type_og.name = 'case_type' )
2221 LEFT JOIN civicrm_option_value case_type_ov ON ( relCase.case_type_id = case_type_ov.value
2222 AND case_type_og.id = case_type_ov.option_group_id )
2223 WHERE {$whereClause}";
2224
2225 $dao = CRM_Core_DAO::executeQuery($query);
2226 $contactViewUrl = CRM_Utils_System::url("civicrm/contact/view", "reset=1&cid=");
2227 $hasViewContact = CRM_Core_Permission::giveMeAllACLs();
2228
2229 while ($dao->fetch()) {
2230 $caseView = NULL;
2231 if (!$doFilterCases || array_key_exists($dao->id, $filterCases)) {
2232 $caseViewStr = "reset=1&id={$dao->id}&cid={$dao->client_id}&action=view&context=case&selectedChild=case";
2233 $caseViewUrl = CRM_Utils_System::url("civicrm/contact/view/case", $caseViewStr);
2234 $caseView = "<a href='{$caseViewUrl}'>" . ts('View Case') . "</a>";
2235 }
2236 $clientView = $dao->client_name;
2237 if ($hasViewContact) {
2238 $clientView = "<a href='{$contactViewUrl}{$dao->client_id}'>$dao->client_name</a>";
2239 }
2240
2241 $relatedCases[$dao->id] = array(
2242 'case_id' => $dao->id,
2243 'case_type' => $dao->case_type,
2244 'client_name' => $clientView,
2245 'links' => $caseView,
2246 );
2247 }
2248 $dao->free();
2249
2250 return $relatedCases;
2251 }
2252
2253 /**
2254 * Merge two duplicate contacts' cases - follow CRM-5758 rules.
2255 *
2256 * @see CRM_Dedupe_Merger::cpTables()
2257 *
2258 * TODO: use the 3rd $sqls param to append sql statements rather than executing them here
2259 */
2260 static function mergeContacts($mainContactId, $otherContactId) {
2261 self::mergeCases($mainContactId, NULL, $otherContactId);
2262 }
2263
2264 /**
2265 * Function perform two task.
2266 * 1. Merge two duplicate contacts cases - follow CRM-5758 rules.
2267 * 2. Merge two cases of same contact - follow CRM-5598 rules.
2268 *
2269 * @param int $mainContactId contact id of main contact record.
2270 * @param int $mainCaseId case id of main case record.
2271 * @param int $otherContactId contact id of record which is going to merge.
2272 * @param int $otherCaseId case id of record which is going to merge.
2273 *
2274 * @return void.
2275 * @static
2276 */
2277 static function mergeCases($mainContactId, $mainCaseId = NULL, $otherContactId = NULL,
2278 $otherCaseId = NULL, $changeClient = FALSE) {
2279 $moveToTrash = TRUE;
2280
2281 $duplicateContacts = FALSE;
2282 if ($mainContactId && $otherContactId &&
2283 $mainContactId != $otherContactId
2284 ) {
2285 $duplicateContacts = TRUE;
2286 }
2287
2288 $duplicateCases = FALSE;
2289 if ($mainCaseId && $otherCaseId &&
2290 $mainCaseId != $otherCaseId
2291 ) {
2292 $duplicateCases = TRUE;
2293 }
2294
2295 $mainCaseIds = array();
2296 if (!$duplicateContacts && !$duplicateCases) {
2297 return $mainCaseIds;
2298 }
2299
2300 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name');
2301 $activityStatuses = CRM_Core_PseudoConstant::activityStatus('name');
2302 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2303 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2304 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2305 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2306
2307 $processCaseIds = array($otherCaseId);
2308 if ($duplicateContacts && !$duplicateCases) {
2309 if ($changeClient) {
2310 $processCaseIds = array($mainCaseId);
2311 }
2312 else {
2313 //get all case ids for other contact.
2314 $processCaseIds = self::retrieveCaseIdsByContactId($otherContactId, TRUE);
2315 }
2316 if (!is_array($processCaseIds)) {
2317 return;
2318 }
2319 }
2320
2321 $session = CRM_Core_Session::singleton();
2322 $currentUserId = $session->get('userID');
2323
2324 // copy all cases and connect to main contact id.
2325 foreach ($processCaseIds as $otherCaseId) {
2326 if ($duplicateContacts) {
2327 $mainCase = CRM_Core_DAO::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId));
2328 $mainCaseId = $mainCase->id;
2329 if (!$mainCaseId) {
2330 continue;
2331 }
2332
2333 // CRM-11662 Copy Case custom data
2334 $extends = array('case');
2335 $groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
2336 if ($groupTree) {
2337 foreach ($groupTree as $groupID => $group) {
2338 $table[$groupTree[$groupID]['table_name']] = array('entity_id');
2339 foreach ($group['fields'] as $fieldID => $field) {
2340 $table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
2341 }
2342 }
2343
2344 foreach ($table as $tableName => $tableColumns) {
2345 $insert = 'INSERT INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
2346 $tableColumns[0] = $mainCaseId;
2347 $select = 'SELECT ' . implode(', ', $tableColumns);
2348 $from = ' FROM ' . $tableName;
2349 $where = " WHERE {$tableName}.entity_id = {$otherCaseId}";
2350 $query = $insert . $select . $from . $where;
2351 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
2352 }
2353 }
2354
2355 $mainCase->free();
2356
2357 $mainCaseIds[] = $mainCaseId;
2358 //insert record for case contact.
2359 $otherCaseContact = new CRM_Case_DAO_CaseContact();
2360 $otherCaseContact->case_id = $otherCaseId;
2361 $otherCaseContact->find();
2362 while ($otherCaseContact->fetch()) {
2363 $mainCaseContact = new CRM_Case_DAO_CaseContact();
2364 $mainCaseContact->case_id = $mainCaseId;
2365 $mainCaseContact->contact_id = $otherCaseContact->contact_id;
2366 if ($mainCaseContact->contact_id == $otherContactId) {
2367 $mainCaseContact->contact_id = $mainContactId;
2368 }
2369 //avoid duplicate object.
2370 if (!$mainCaseContact->find(TRUE)) {
2371 $mainCaseContact->save();
2372 }
2373 $mainCaseContact->free();
2374 }
2375 $otherCaseContact->free();
2376 }
2377 elseif (!$otherContactId) {
2378 $otherContactId = $mainContactId;
2379 }
2380
2381 if (!$mainCaseId || !$otherCaseId ||
2382 !$mainContactId || !$otherContactId
2383 ) {
2384 continue;
2385 }
2386
2387 // get all activities for other case.
2388 $otherCaseActivities = array();
2389 CRM_Core_DAO::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities);
2390
2391 //for duplicate cases do not process singleton activities.
2392 $otherActivityIds = $singletonActivityIds = array();
2393 foreach ($otherCaseActivities as $caseActivityId => $otherIds) {
2394 $otherActId = CRM_Utils_Array::value('activity_id', $otherIds);
2395 if (!$otherActId || in_array($otherActId, $otherActivityIds)) {
2396 continue;
2397 }
2398 $otherActivityIds[] = $otherActId;
2399 }
2400 if ($duplicateCases) {
2401 if ($openCaseType = array_search('Open Case', $activityTypes)) {
2402 $sql = "
2403 SELECT id
2404 FROM civicrm_activity
2405 WHERE activity_type_id = $openCaseType
2406 AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');';
2407 $dao = CRM_Core_DAO::executeQuery($sql);
2408 while ($dao->fetch()) {
2409 $singletonActivityIds[] = $dao->id;
2410 }
2411 $dao->free();
2412 }
2413 }
2414
2415 // migrate all activities and connect to main contact.
2416 $copiedActivityIds = $activityMappingIds = array();
2417 sort($otherActivityIds);
2418 foreach ($otherActivityIds as $otherActivityId) {
2419
2420 //for duplicate cases -
2421 //do not migrate singleton activities.
2422 if (!$otherActivityId || in_array($otherActivityId, $singletonActivityIds)) {
2423 continue;
2424 }
2425
2426 //migrate activity record.
2427 $otherActivity = new CRM_Activity_DAO_Activity();
2428 $otherActivity->id = $otherActivityId;
2429 if (!$otherActivity->find(TRUE)) {
2430 continue;
2431 }
2432
2433 $mainActVals = array();
2434 $mainActivity = new CRM_Activity_DAO_Activity();
2435 CRM_Core_DAO::storeValues($otherActivity, $mainActVals);
2436 $mainActivity->copyValues($mainActVals);
2437 $mainActivity->id = NULL;
2438 $mainActivity->activity_date_time = CRM_Utils_Date::isoToMysql($otherActivity->activity_date_time);
2439 $mainActivity->source_record_id = CRM_Utils_Array::value($mainActivity->source_record_id,
2440 $activityMappingIds
2441 );
2442
2443 $mainActivity->original_id = CRM_Utils_Array::value($mainActivity->original_id,
2444 $activityMappingIds
2445 );
2446
2447 $mainActivity->parent_id = CRM_Utils_Array::value($mainActivity->parent_id,
2448 $activityMappingIds
2449 );
2450 $mainActivity->save();
2451 $mainActivityId = $mainActivity->id;
2452 if (!$mainActivityId) {
2453 continue;
2454 }
2455
2456 $activityMappingIds[$otherActivityId] = $mainActivityId;
2457 // insert log of all activities
2458 CRM_Activity_BAO_Activity::logActivityAction($mainActivity);
2459
2460 $otherActivity->free();
2461 $mainActivity->free();
2462 $copiedActivityIds[] = $otherActivityId;
2463
2464 //create case activity record.
2465 $mainCaseActivity = new CRM_Case_DAO_CaseActivity();
2466 $mainCaseActivity->case_id = $mainCaseId;
2467 $mainCaseActivity->activity_id = $mainActivityId;
2468 $mainCaseActivity->save();
2469 $mainCaseActivity->free();
2470
2471 //migrate source activity.
2472 $otherSourceActivity = new CRM_Activity_DAO_ActivityContact();
2473 $otherSourceActivity->activity_id = $otherActivityId;
2474 $otherSourceActivity->record_type_id = $sourceID;
2475 $otherSourceActivity->find();
2476 while ($otherSourceActivity->fetch()) {
2477 $mainActivitySource = new CRM_Activity_DAO_ActivityContact();
2478 $mainActivitySource->record_type_id = $sourceID;
2479 $mainActivitySource->activity_id = $mainActivityId;
2480 $mainActivitySource->contact_id = $otherSourceActivity->contact_id;
2481 if ($mainActivitySource->contact_id == $otherContactId) {
2482 $mainActivitySource->contact_id = $mainContactId;
2483 }
2484 //avoid duplicate object.
2485 if (!$mainActivitySource->find(TRUE)) {
2486 $mainActivitySource->save();
2487 }
2488 $mainActivitySource->free();
2489 }
2490 $otherSourceActivity->free();
2491
2492 //migrate target activities.
2493 $otherTargetActivity = new CRM_Activity_DAO_ActivityContact();
2494 $otherTargetActivity->activity_id = $otherActivityId;
2495 $otherTargetActivity->record_type_id = $targetID;
2496 $otherTargetActivity->find();
2497 while ($otherTargetActivity->fetch()) {
2498 $mainActivityTarget = new CRM_Activity_DAO_ActivityContact();
2499 $mainActivityTarget->record_type_id = $targetID;
2500 $mainActivityTarget->activity_id = $mainActivityId;
2501 $mainActivityTarget->contact_id = $otherTargetActivity->contact_id;
2502 if ($mainActivityTarget->contact_id == $otherContactId) {
2503 $mainActivityTarget->contact_id = $mainContactId;
2504 }
2505 //avoid duplicate object.
2506 if (!$mainActivityTarget->find(TRUE)) {
2507 $mainActivityTarget->save();
2508 }
2509 $mainActivityTarget->free();
2510 }
2511 $otherTargetActivity->free();
2512
2513 //migrate assignee activities.
2514 $otherAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2515 $otherAssigneeActivity->activity_id = $otherActivityId;
2516 $otherAssigneeActivity->record_type_id = $assigneeID;
2517 $otherAssigneeActivity->find();
2518 while ($otherAssigneeActivity->fetch()) {
2519 $mainAssigneeActivity = new CRM_Activity_DAO_ActivityContact();
2520 $mainAssigneeActivity->activity_id = $mainActivityId;
2521 $mainAssigneeActivity->record_type_id = $assigneeID;
2522 $mainAssigneeActivity->contact_id = $otherAssigneeActivity->contact_id;
2523 if ($mainAssigneeActivity->contact_id == $otherContactId) {
2524 $mainAssigneeActivity->contact_id = $mainContactId;
2525 }
2526 //avoid duplicate object.
2527 if (!$mainAssigneeActivity->find(TRUE)) {
2528 $mainAssigneeActivity->save();
2529 }
2530 $mainAssigneeActivity->free();
2531 }
2532 $otherAssigneeActivity->free();
2533
2534 // copy custom fields and attachments
2535 $aparams = array(
2536 'activityID' => $otherActivityId,
2537 'mainActivityId' => $mainActivityId,
2538 );
2539 CRM_Activity_BAO_Activity::copyExtendedActivityData($aparams);
2540 }
2541
2542 //copy case relationship.
2543 if ($duplicateContacts) {
2544 //migrate relationship records.
2545 $otherRelationship = new CRM_Contact_DAO_Relationship();
2546 $otherRelationship->case_id = $otherCaseId;
2547 $otherRelationship->find();
2548 $otherRelationshipIds = array();
2549 while ($otherRelationship->fetch()) {
2550 $otherRelVals = array();
2551 $updateOtherRel = FALSE;
2552 CRM_Core_DAO::storeValues($otherRelationship, $otherRelVals);
2553
2554 $mainRelationship = new CRM_Contact_DAO_Relationship();
2555 $mainRelationship->copyValues($otherRelVals);
2556 $mainRelationship->id = NULL;
2557 $mainRelationship->case_id = $mainCaseId;
2558 if ($mainRelationship->contact_id_a == $otherContactId) {
2559 $updateOtherRel = TRUE;
2560 $mainRelationship->contact_id_a = $mainContactId;
2561 }
2562
2563 //case creator change only when we merge user contact.
2564 if ($mainRelationship->contact_id_b == $otherContactId) {
2565 //do not change creator for change client.
2566 if (!$changeClient) {
2567 $updateOtherRel = TRUE;
2568 $mainRelationship->contact_id_b = ($currentUserId) ? $currentUserId : $mainContactId;
2569 }
2570 }
2571 $mainRelationship->end_date = CRM_Utils_Date::isoToMysql($otherRelationship->end_date);
2572 $mainRelationship->start_date = CRM_Utils_Date::isoToMysql($otherRelationship->start_date);
2573
2574 //avoid duplicate object.
2575 if (!$mainRelationship->find(TRUE)) {
2576 $mainRelationship->save();
2577 }
2578 $mainRelationship->free();
2579
2580 //get the other relationship ids to update end date.
2581 if ($updateOtherRel) {
2582 $otherRelationshipIds[$otherRelationship->id] = $otherRelationship->id;
2583 }
2584 }
2585 $otherRelationship->free();
2586
2587 //update other relationships end dates
2588 if (!empty($otherRelationshipIds)) {
2589 $sql = 'UPDATE civicrm_relationship
2590 SET end_date = CURDATE()
2591 WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')';
2592 CRM_Core_DAO::executeQuery($sql);
2593 }
2594 }
2595
2596 //move other case to trash.
2597 $mergeCase = self::deleteCase($otherCaseId, $moveToTrash);
2598 if (!$mergeCase) {
2599 continue;
2600 }
2601
2602 $mergeActSubject = $mergeActSubjectDetails = $mergeActType = '';
2603 if ($changeClient) {
2604 $mainContactDisplayName = CRM_Contact_BAO_Contact::displayName($mainContactId);
2605 $otherContactDisplayName = CRM_Contact_BAO_Contact::displayName($otherContactId);
2606
2607 $mergeActType = array_search('Reassigned Case', $activityTypes);
2608 $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.",
2609 array(
2610 1 => $otherCaseId,
2611 2 => $otherContactDisplayName,
2612 3 => $mainContactDisplayName,
2613 4 => $mainCaseId
2614 )
2615 );
2616 }
2617 elseif ($duplicateContacts) {
2618 $mergeActType = array_search('Merge Case', $activityTypes);
2619 $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.",
2620 array(
2621 1 => $otherCaseId,
2622 2 => $otherContactId,
2623 3 => $mainContactId,
2624 4 => $mainCaseId
2625 )
2626 );
2627 }
2628 else {
2629 $mergeActType = array_search('Merge Case', $activityTypes);
2630 $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId));
2631 if (!empty($copiedActivityIds)) {
2632 $sql = '
2633 SELECT id, subject, activity_date_time, activity_type_id
2634 FROM civicrm_activity
2635 WHERE id IN (' . implode(',', $copiedActivityIds) . ')';
2636 $dao = CRM_Core_DAO::executeQuery($sql);
2637 while ($dao->fetch()) {
2638 $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}";
2639 if ($dao->subject) {
2640 $mergeActSubjectDetails .= " :: {$dao->subject}";
2641 }
2642 $mergeActSubjectDetails .= "<br />";
2643 }
2644 }
2645 }
2646
2647 //create merge activity record.
2648 $activityParams = array(
2649 'subject' => $mergeActSubject,
2650 'details' => $mergeActSubjectDetails,
2651 'status_id' => array_search('Completed', $activityStatuses),
2652 'activity_type_id' => $mergeActType,
2653 'source_contact_id' => $mainContactId,
2654 'activity_date_time' => date('YmdHis'),
2655 );
2656
2657 $mergeActivity = CRM_Activity_BAO_Activity::create($activityParams);
2658 $mergeActivityId = $mergeActivity->id;
2659 if (!$mergeActivityId) {
2660 continue;
2661 }
2662 $mergeActivity->free();
2663
2664 //connect merge activity to case.
2665 $mergeCaseAct = array(
2666 'case_id' => $mainCaseId,
2667 'activity_id' => $mergeActivityId,
2668 );
2669
2670 self::processCaseActivity($mergeCaseAct);
2671 }
2672 return $mainCaseIds;
2673 }
2674
2675 /**
2676 * Validate contact permission for
2677 * edit/view on activity record and build links.
2678 *
2679 * @param array $tplParams params to be sent to template for sending email.
2680 * @param array $activityParams info of the activity.
2681 *
2682 * @return void
2683 * @static
2684 */
2685 static function buildPermissionLinks(&$tplParams, $activityParams) {
2686 $activityTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityParams['source_record_id'],
2687 'activity_type_id', 'id'
2688 );
2689
2690 if (!empty($tplParams['isCaseActivity'])) {
2691 $tplParams['editActURL'] = CRM_Utils_System::url('civicrm/case/activity',
2692 "reset=1&cid={$activityParams['target_id']}&caseid={$activityParams['case_id']}&action=update&id={$activityParams['source_record_id']}", TRUE
2693 );
2694
2695 $tplParams['viewActURL'] = CRM_Utils_System::url('civicrm/case/activity/view',
2696 "reset=1&aid={$activityParams['source_record_id']}&cid={$activityParams['target_id']}&caseID={$activityParams['case_id']}", TRUE
2697 );
2698
2699 $tplParams['manageCaseURL'] = CRM_Utils_System::url('civicrm/contact/view/case',
2700 "reset=1&id={$activityParams['case_id']}&cid={$activityParams['target_id']}&action=view&context=home", TRUE
2701 );
2702 }
2703 else {
2704 $tplParams['editActURL'] = CRM_Utils_System::url('civicrm/contact/view/activity',
2705 "atype=$activityTypeId&action=update&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2706 );
2707
2708 $tplParams['viewActURL'] = CRM_Utils_System::url('civicrm/contact/view/activity',
2709 "atype=$activityTypeId&action=view&reset=1&id={$activityParams['source_record_id']}&cid={$tplParams['contact']['contact_id']}&context=activity", TRUE
2710 );
2711 }
2712 }
2713
2714 /**
2715 * Validate contact permission for
2716 * given operation on activity record.
2717 *
2718 * @param int $activityId activity record id.
2719 * @param string $operation user operation.
2720 * @param int $actTypeId activity type id.
2721 * @param int $contactId contact id/if not pass consider logged in
2722 * @param boolean $checkComponent do we need to check component enabled.
2723 *
2724 * @return boolean $allow true/false
2725 * @static
2726 */
2727 static function checkPermission($activityId, $operation, $actTypeId = NULL, $contactId = NULL, $checkComponent = TRUE) {
2728 $allow = FALSE;
2729 if (!$actTypeId && $activityId) {
2730 $actTypeId = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $activityId, 'activity_type_id');
2731 }
2732
2733 if (!$activityId || !$operation || !$actTypeId) {
2734 return $allow;
2735 }
2736
2737 //do check for civicase component enabled.
2738 if ($checkComponent) {
2739 static $componentEnabled;
2740 if (!isset($componentEnabled)) {
2741 $config = CRM_Core_Config::singleton();
2742 $componentEnabled = FALSE;
2743 if (in_array('CiviCase', $config->enableComponents)) {
2744 $componentEnabled = TRUE;
2745 }
2746 }
2747 if (!$componentEnabled) {
2748 return $allow;
2749 }
2750 }
2751
2752 //do check for cases.
2753 $caseActOperations = array(
2754 'File On Case',
2755 'Link Cases',
2756 'Move To Case',
2757 'Copy To Case',
2758 );
2759
2760 if (in_array($operation, $caseActOperations)) {
2761 static $unclosedCases;
2762 if (!is_array($unclosedCases)) {
2763 $unclosedCases = self::getUnclosedCases();
2764 }
2765 if ($operation == 'File On Case') {
2766 $allow = (empty($unclosedCases)) ? FALSE : TRUE;
2767 }
2768 else {
2769 $allow = (count($unclosedCases) > 1) ? TRUE : FALSE;
2770 }
2771 }
2772
2773 $actionOperations = array('view', 'edit', 'delete');
2774 if (in_array($operation, $actionOperations)) {
2775
2776 //do cache when user has non/supper permission.
2777 static $allowOperations;
2778
2779 if (!is_array($allowOperations) ||
2780 !array_key_exists($operation, $allowOperations)
2781 ) {
2782
2783 if (!$contactId) {
2784 $session = CRM_Core_Session::singleton();
2785 $contactId = $session->get('userID');
2786 }
2787
2788 //check for permissions.
2789 $permissions = array(
2790 'view' => array(
2791 'access my cases and activities',
2792 'access all cases and activities',
2793 ),
2794 'edit' => array(
2795 'access my cases and activities',
2796 'access all cases and activities',
2797 ),
2798 'delete' => array('delete activities'),
2799 );
2800
2801 //check for core permission.
2802 $hasPermissions = array();
2803 $checkPermissions = CRM_Utils_Array::value($operation, $permissions);
2804 if (is_array($checkPermissions)) {
2805 foreach ($checkPermissions as $per) {
2806 if (CRM_Core_Permission::check($per)) {
2807 $hasPermissions[$operation][] = $per;
2808 }
2809 }
2810 }
2811
2812 //has permissions.
2813 if (!empty($hasPermissions)) {
2814 //need to check activity object specific.
2815 if (in_array($operation, array(
2816 'view',
2817 'edit'
2818 ))
2819 ) {
2820 //do we have supper permission.
2821 if (in_array('access all cases and activities', $hasPermissions[$operation])) {
2822 $allowOperations[$operation] = $allow = TRUE;
2823 }
2824 else {
2825 //user has only access to my cases and activity.
2826 //here object specific permmions come in picture.
2827
2828 //edit - contact must be source or assignee
2829 //view - contact must be source/assignee/target
2830 $isTarget = $isAssignee = $isSource = FALSE;
2831 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
2832 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
2833 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
2834 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
2835
2836 $target = new CRM_Activity_DAO_ActivityContact();
2837 $target->record_type_id = $targetID;
2838 $target->activity_id = $activityId;
2839 $target->contact_id = $contactId;
2840 if ($target->find(TRUE)) {
2841 $isTarget = TRUE;
2842 }
2843
2844 $assignee = new CRM_Activity_DAO_ActivityContact();
2845 $assignee->activity_id = $activityId;
2846 $assignee->record_type_id = $assigneeID;
2847 $assignee->contact_id = $contactId;
2848 if ($assignee->find(TRUE)) {
2849 $isAssignee = TRUE;
2850 }
2851
2852 $source = new CRM_Activity_DAO_ActivityContact();
2853 $source->activity_id = $activityId;
2854 $source->record_type_id = $sourceID;
2855 $source->contact_id = $contactId;
2856 if ($source->find(TRUE)) {
2857 $isSource = TRUE;
2858 }
2859
2860 if ($operation == 'edit') {
2861 if ($isAssignee || $isSource) {
2862 $allow = TRUE;
2863 }
2864 }
2865 if ($operation == 'view') {
2866 if ($isTarget || $isAssignee || $isSource) {
2867 $allow = TRUE;
2868 }
2869 }
2870 }
2871 }
2872 elseif (is_array($hasPermissions[$operation])) {
2873 $allowOperations[$operation] = $allow = TRUE;
2874 }
2875 }
2876 else {
2877 //contact do not have permission.
2878 $allowOperations[$operation] = FALSE;
2879 }
2880 }
2881 else {
2882 //use cache.
2883 //here contact might have supper/non permission.
2884 $allow = $allowOperations[$operation];
2885 }
2886 }
2887
2888 //do further only when operation is granted.
2889 if ($allow) {
2890 $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name');
2891
2892 //get the activity type name.
2893 $actTypeName = CRM_Utils_Array::value($actTypeId, $activityTypes);
2894
2895 //do not allow multiple copy / edit action.
2896 $singletonNames = array(
2897 'Open Case',
2898 'Reassigned Case',
2899 'Merge Case',
2900 'Link Cases',
2901 'Assign Case Role',
2902 'Email',
2903 'Inbound Email'
2904 );
2905
2906 //do not allow to delete these activities, CRM-4543
2907 $doNotDeleteNames = array('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date');
2908
2909 //allow edit operation.
2910 $allowEditNames = array('Open Case');
2911
2912 // do not allow File on Case
2913 $doNotFileNames = array(
2914 'Open Case',
2915 'Change Case Type',
2916 'Change Case Status',
2917 'Change Case Start Date',
2918 'Reassigned Case',
2919 'Merge Case',
2920 'Link Cases',
2921 'Assign Case Role'
2922 );
2923
2924 if (in_array($actTypeName, $singletonNames)) {
2925 $allow = FALSE;
2926 if ($operation == 'File On Case') {
2927 $allow = (in_array($actTypeName, $doNotFileNames)) ? FALSE : TRUE;
2928 }
2929 if (in_array($operation, $actionOperations)) {
2930 $allow = TRUE;
2931 if ($operation == 'edit') {
2932 $allow = (in_array($actTypeName, $allowEditNames)) ? TRUE : FALSE;
2933 }
2934 elseif ($operation == 'delete') {
2935 $allow = (in_array($actTypeName, $doNotDeleteNames)) ? FALSE : TRUE;
2936 }
2937 }
2938 }
2939 if ($allow && ($operation == 'delete') &&
2940 in_array($actTypeName, $doNotDeleteNames)
2941 ) {
2942 $allow = FALSE;
2943 }
2944
2945 if ($allow && ($operation == 'File On Case') &&
2946 in_array($actTypeName, $doNotFileNames)
2947 ) {
2948 $allow = FALSE;
2949 }
2950
2951 //check settings file for masking actions
2952 //on the basis the activity types
2953 //hide Edit link if activity type is NOT editable
2954 //(special case activities).CRM-5871
2955 if ($allow && in_array($operation, $actionOperations)) {
2956 static $actionFilter = array();
2957 if (!array_key_exists($operation, $actionFilter)) {
2958 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
2959 $actionFilter[$operation] = $xmlProcessor->get('Settings', 'ActivityTypes', FALSE, $operation);
2960 }
2961 if (array_key_exists($operation, $actionFilter[$operation]) &&
2962 in_array($actTypeId, $actionFilter[$operation][$operation])
2963 ) {
2964 $allow = FALSE;
2965 }
2966 }
2967 }
2968
2969 return $allow;
2970 }
2971
2972 /**
2973 * since we drop 'access CiviCase', allow access
2974 * if user has 'access my cases and activities'
2975 * or 'access all cases and activities'
2976 */
2977 static function accessCiviCase() {
2978 static $componentEnabled;
2979 if (!isset($componentEnabled)) {
2980 $componentEnabled = FALSE;
2981 $config = CRM_Core_Config::singleton();
2982 if (in_array('CiviCase', $config->enableComponents)) {
2983 $componentEnabled = TRUE;
2984 }
2985 }
2986 if (!$componentEnabled) {
2987 return FALSE;
2988 }
2989
2990 if (CRM_Core_Permission::check('access my cases and activities') ||
2991 CRM_Core_Permission::check('access all cases and activities')
2992 ) {
2993 return TRUE;
2994 }
2995
2996 return FALSE;
2997 }
2998
2999 /**
3000 * Function to check whether activity is a case Activity
3001 *
3002 * @param int $activityID activity id
3003 *
3004 * @return boolean $isCaseActivity true/false
3005 */
3006 static function isCaseActivity($activityID) {
3007 $isCaseActivity = FALSE;
3008 if ($activityID) {
3009 $params = array(1 => array($activityID, 'Integer'));
3010 $query = "SELECT id FROM civicrm_case_activity WHERE activity_id = %1";
3011 if (CRM_Core_DAO::singleValueQuery($query, $params)) {
3012 $isCaseActivity = TRUE;
3013 }
3014 }
3015
3016 return $isCaseActivity;
3017 }
3018
3019 /**
3020 * Function to get all the case type ids currently in use
3021 *
3022 *
3023 * @return array $caseTypeIds
3024 */
3025 static function getUsedCaseType() {
3026 static $caseTypeIds;
3027
3028 if (!is_array($caseTypeIds)) {
3029 $query = "SELECT DISTINCT( civicrm_case.case_type_id ) FROM civicrm_case";
3030
3031 $dao = CRM_Core_DAO::executeQuery($query);
3032 $caseTypeIds = array();
3033 while ($dao->fetch()) {
3034 $typeId = explode(CRM_Core_DAO::VALUE_SEPARATOR,
3035 $dao->case_type_id
3036 );
3037 $caseTypeIds[] = $typeId[1];
3038 }
3039 }
3040
3041 return $caseTypeIds;
3042 }
3043
3044 /**
3045 * Function to get all the case status ids currently in use
3046 *
3047 *
3048 * @return array $caseStatusIds
3049 */
3050 static function getUsedCaseStatuses() {
3051 static $caseStatusIds;
3052
3053 if (!is_array($caseStatusIds)) {
3054 $query = "SELECT DISTINCT( civicrm_case.status_id ) FROM civicrm_case";
3055
3056 $dao = CRM_Core_DAO::executeQuery($query);
3057 $caseStatusIds = array();
3058 while ($dao->fetch()) {
3059 $caseStatusIds[] = $dao->status_id;
3060 }
3061 }
3062
3063 return $caseStatusIds;
3064 }
3065
3066 /**
3067 * Function to get all the encounter medium ids currently in use
3068 * @return array
3069 */
3070 static function getUsedEncounterMediums() {
3071 static $mediumIds;
3072
3073 if (!is_array($mediumIds)) {
3074 $query = "SELECT DISTINCT( civicrm_activity.medium_id ) FROM civicrm_activity";
3075
3076 $dao = CRM_Core_DAO::executeQuery($query);
3077 $mediumIds = array();
3078 while ($dao->fetch()) {
3079 $mediumIds[] = $dao->medium_id;
3080 }
3081 }
3082
3083 return $mediumIds;
3084 }
3085
3086 /**
3087 * Function to check case configuration.
3088 *
3089 * @return array $configured
3090 */
3091 static function isCaseConfigured($contactId = NULL) {
3092 $configured = array_fill_keys(array('configured', 'allowToAddNewCase', 'redirectToCaseAdmin'), FALSE);
3093
3094 //lets check for case configured.
3095 $allCasesCount = CRM_Case_BAO_Case::caseCount(NULL, FALSE);
3096 $configured['configured'] = ($allCasesCount) ? TRUE : FALSE;
3097 if (!$configured['configured']) {
3098 //do check for case type and case status.
3099 $caseTypes = CRM_Case_PseudoConstant::caseType('label', FALSE);
3100 if (!empty($caseTypes)) {
3101 $configured['configured'] = TRUE;
3102 if (!$configured['configured']) {
3103 $caseStatuses = CRM_Case_PseudoConstant::caseStatus('label', FALSE);
3104 if (!empty($caseStatuses)) {
3105 $configured['configured'] = TRUE;
3106 }
3107 }
3108 }
3109 }
3110 if ($configured['configured']) {
3111 //do check for active case type and case status.
3112 $caseTypes = CRM_Case_PseudoConstant::caseType();
3113 if (!empty($caseTypes)) {
3114 $caseStatuses = CRM_Case_PseudoConstant::caseStatus();
3115 if (!empty($caseStatuses)) {
3116 $configured['allowToAddNewCase'] = TRUE;
3117 }
3118 }
3119
3120 //do we need to redirect user to case admin.
3121 if (!$configured['allowToAddNewCase'] && $contactId) {
3122 //check for current contact case count.
3123 $currentContatCasesCount = CRM_Case_BAO_Case::caseCount($contactId);
3124 //redirect user to case admin page.
3125 if (!$currentContatCasesCount) {
3126 $configured['redirectToCaseAdmin'] = TRUE;
3127 }
3128 }
3129 }
3130
3131 return $configured;
3132 }
3133
3134 /**
3135 * Used during case component enablement and during ugprade
3136 */
3137 static function createCaseViews() {
3138 $dao = new CRM_Core_DAO();
3139
3140 $sql = self::createCaseViewsQuery('upcoming');
3141 CRM_Core_Error::ignoreException();
3142 $dao->query($sql);
3143 CRM_Core_Error::setCallback();
3144 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
3145 return FALSE;
3146 }
3147
3148 // Above error doesn't get caught?
3149 CRM_Core_Error::ignoreException();
3150 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_upcoming");
3151 CRM_Core_Error::setCallback();
3152 if (is_null($doublecheck)) {
3153 return FALSE;
3154 }
3155
3156 $sql = self::createCaseViewsQuery('recent');
3157 CRM_Core_Error::ignoreException();
3158 $dao->query($sql);
3159 CRM_Core_Error::setCallback();
3160 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
3161 return FALSE;
3162 }
3163
3164 // Above error doesn't get caught?
3165 CRM_Core_Error::ignoreException();
3166 $doublecheck = $dao->singleValueQuery("SELECT count(id) FROM civicrm_view_case_activity_recent");
3167 CRM_Core_Error::setCallback();
3168 if (is_null($doublecheck)) {
3169 return FALSE;
3170 }
3171
3172 return TRUE;
3173 }
3174
3175 /**
3176 * helper function, also used by the upgrade in case of error
3177 */
3178 static function createCaseViewsQuery($section = 'upcoming') {
3179 $sql = "";
3180 $scheduled_id = CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled', 'name');
3181 switch ($section) {
3182 case 'upcoming':
3183 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_upcoming`
3184 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3185 FROM civicrm_case_activity ca
3186 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3187 WHERE a.activity_date_time <= DATE_ADD( NOW(), INTERVAL 14 DAY )
3188 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id = $scheduled_id";
3189 break;
3190
3191 case 'recent':
3192 $sql = "CREATE OR REPLACE VIEW `civicrm_view_case_activity_recent`
3193 AS SELECT ca.case_id, a.id, a.activity_date_time, a.status_id, a.activity_type_id
3194 FROM civicrm_case_activity ca
3195 INNER JOIN civicrm_activity a ON ca.activity_id=a.id
3196 WHERE a.activity_date_time <= NOW()
3197 AND a.activity_date_time >= DATE_SUB( NOW(), INTERVAL 14 DAY )
3198 AND a.is_current_revision = 1 AND a.is_deleted=0 AND a.status_id <> $scheduled_id";
3199 break;
3200 }
3201 return $sql;
3202 }
3203
3204 /**
3205 * Function to add/copy relationships, when new client is added for a case
3206 *
3207 * @param int $caseId case id
3208 * @param int $contactId contact id / new client id
3209 *
3210 * @return void
3211 */
3212 static function addCaseRelationships($caseId, $contactId) {
3213 // get the case role / relationships for the case
3214 $caseRelationships = new CRM_Contact_DAO_Relationship();
3215 $caseRelationships->case_id = $caseId;
3216 $caseRelationships->find();
3217 $relationshipTypes = array();
3218
3219 // make sure we don't add duplicate relationships of same relationship type.
3220 while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id, $relationshipTypes)) {
3221 $values = array();
3222 CRM_Core_DAO::storeValues($caseRelationships, $values);
3223
3224 // add relationship for new client.
3225 $newRelationship = new CRM_Contact_DAO_Relationship();
3226 $newRelationship->copyValues($values);
3227 $newRelationship->id = NULL;
3228 $newRelationship->case_id = $caseId;
3229 $newRelationship->contact_id_a = $contactId;
3230 $newRelationship->end_date = CRM_Utils_Date::isoToMysql($caseRelationships->end_date);
3231 $newRelationship->start_date = CRM_Utils_Date::isoToMysql($caseRelationships->start_date);
3232
3233 // another check to avoid duplicate relationship, in cases where client is removed and re-added again.
3234 if (!$newRelationship->find(TRUE)) {
3235 $newRelationship->save();
3236 }
3237 $newRelationship->free();
3238
3239 // store relationship type of newly created relationship
3240 $relationshipTypes[] = $caseRelationships->relationship_type_id;
3241 }
3242 }
3243
3244 /**
3245 * Function to get the list of clients for a case
3246 *
3247 * @param int $caseId
3248 *
3249 * @return array $clients associated array with client ids
3250 * @static
3251 */
3252 static function getCaseClients($caseId) {
3253 $clients = array();
3254 $caseContact = new CRM_Case_DAO_CaseContact();
3255 $caseContact->case_id = $caseId;
3256 $caseContact->find();
3257
3258 while ($caseContact->fetch()) {
3259 $clients[] = $caseContact->contact_id;
3260 }
3261
3262 return $clients;
3263 }
3264
3265 /**
3266 * Get options for a given case field.
3267 * @see CRM_Core_DAO::buildOptions
3268 *
3269 * @param String $fieldName
3270 * @param String $context: @see CRM_Core_DAO::buildOptionsContext
3271 * @param Array $props: whatever is known about this dao object
3272 */
3273 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
3274 $className = __CLASS__;
3275 $params = array();
3276 switch ($fieldName) {
3277 // This field is not part of this object but the api supports it
3278 case 'medium_id':
3279 $className = 'CRM_Activity_BAO_Activity';
3280 break;
3281 }
3282 return CRM_Core_PseudoConstant::get($className, $fieldName, $params, $context);
3283 }
3284 }
3285