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