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