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