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