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