Activity tab performance fix - switch to faster getActivities & getActivitiesCount
[civicrm-core.git] / CRM / Activity / Page / AJAX.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 *
33 */
34
35/**
36 * This class contains all the function that are called using AJAX (jQuery)
37 */
38class CRM_Activity_Page_AJAX {
00be9182 39 public static function getCaseActivity() {
5d817a13
MM
40 // Should those params be passed through the validateParams method?
41 $caseID = CRM_Utils_Type::validate($_GET['caseID'], 'Integer');
42 $contactID = CRM_Utils_Type::validate($_GET['cid'], 'Integer');
43 $userID = CRM_Utils_Type::validate($_GET['userID'], 'Integer');
44 $context = CRM_Utils_Type::validate(CRM_Utils_Array::value('context', $_GET), 'String');
6a488035 45
9c3f979f
MM
46 $optionalParameters = array(
47 'source_contact_id' => 'Integer',
48 'status_id' => 'Integer',
49 'activity_deleted' => 'Boolean',
50 'activity_type_id' => 'Integer',
ab9eca19
CW
51 // "Date" validation fails because it expects only numbers with no hyphens
52 'activity_date_low' => 'Alphanumeric',
53 'activity_date_high' => 'Alphanumeric',
9c3f979f 54 );
6a488035 55
9c3f979f 56 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
5d817a13 57 $params += CRM_Core_Page_AJAX::validateParams(array(), $optionalParameters);
6a488035
TO
58
59 // get the activities related to given case
60 $activities = CRM_Case_BAO_Case::getCaseActivity($caseID, $params, $contactID, $context, $userID);
61
ad280fb6 62 CRM_Utils_JSON::output($activities);
6a488035
TO
63 }
64
00be9182 65 public static function getCaseGlobalRelationships() {
9c3f979f 66 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
1d85d241 67
6a488035
TO
68 // get the activities related to given case
69 $globalGroupInfo = array();
1d85d241 70
6a488035 71 // get the total row count
9c3f979f 72 CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo, NULL, FALSE, TRUE, NULL, NULL);
6a488035 73 // limit the rows
9c3f979f 74 $relGlobal = CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo, $params['sortBy'], $showLinks = TRUE, FALSE, $params['offset'], $params['rp']);
1d85d241 75
ad280fb6
JL
76 $relationships = array();
77 // after sort we can update username fields to be a url
78 foreach ($relGlobal as $key => $value) {
79 $relationship = array();
80 $relationship['sort_name'] = $value['sort_name'];
81 $relationship['phone'] = $value['phone'];
82 $relationship['email'] = $value['email'];
1d85d241 83
ad280fb6
JL
84 array_push($relationships, $relationship);
85 }
86
ad280fb6
JL
87 $globalRelationshipsDT = array();
88 $globalRelationshipsDT['data'] = $relationships;
9c3f979f
MM
89 $globalRelationshipsDT['recordsTotal'] = count($relationships);
90 $globalRelationshipsDT['recordsFiltered'] = count($relationships);
aab589e2 91
ad280fb6 92 CRM_Utils_JSON::output($globalRelationshipsDT);
1d85d241
DL
93 }
94
00be9182 95 public static function getCaseClientRelationships() {
353ffa53 96 $caseID = CRM_Utils_Type::escape($_GET['caseID'], 'Integer');
6a488035 97 $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
1d85d241 98
9c3f979f 99 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
6a488035
TO
100
101 // Retrieve ALL client relationships
102 $relClient = CRM_Contact_BAO_Relationship::getRelationship($contactID,
103 CRM_Contact_BAO_Relationship::CURRENT,
104 0, 0, 0, NULL, NULL, FALSE
105 );
1d85d241 106
6a488035 107 $caseRelationships = CRM_Case_BAO_Case::getCaseRoles($contactID, $caseID);
1d85d241 108
6a488035
TO
109 // Now build 'Other Relationships' array by removing relationships that are already listed under Case Roles
110 // so they don't show up twice.
111 $clientRelationships = array();
112 foreach ($relClient as $r) {
113 if (!array_key_exists($r['id'], $caseRelationships)) {
114 $clientRelationships[] = $r;
115 }
116 }
1d85d241 117
6a488035
TO
118 // sort clientRelationships array using jquery call params
119 foreach ($clientRelationships as $key => $row) {
9c3f979f 120 $sortArray[$key] = $row[$params['_raw_values']['sort'][0]];
6a488035 121 }
9c3f979f 122 $sort_type = "SORT_" . strtoupper($params['_raw_values']['order'][0]);
0e2079a1 123 array_multisort($sortArray, constant($sort_type), $clientRelationships);
1d85d241 124
ad280fb6 125 $relationships = array();
6a488035 126 // after sort we can update username fields to be a url
22e263ad 127 foreach ($clientRelationships as $key => $value) {
ad280fb6
JL
128 $relationship = array();
129 $relationship['relation'] = $value['relation'];
130 $relationship['name'] = '<a href=' . CRM_Utils_System::url('civicrm/contact/view',
353ffa53 131 'action=view&reset=1&cid=' . $clientRelationships[$key]['cid']) . '>' . $clientRelationships[$key]['name'] . '</a>';
ad280fb6
JL
132 $relationship['phone'] = $value['phone'];
133 $relationship['email'] = $value['email'];
134
135 array_push($relationships, $relationship);
6a488035 136 }
1d85d241 137
ad280fb6
JL
138 $clientRelationshipsDT = array();
139 $clientRelationshipsDT['data'] = $relationships;
9c3f979f
MM
140 $clientRelationshipsDT['recordsTotal'] = count($relationships);
141 $clientRelationshipsDT['recordsFiltered'] = count($relationships);
aab589e2 142
ad280fb6 143 CRM_Utils_JSON::output($clientRelationshipsDT);
1d85d241
DL
144 }
145
146
00be9182 147 public static function getCaseRoles() {
353ffa53 148 $caseID = CRM_Utils_Type::escape($_GET['caseID'], 'Integer');
6a488035 149 $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
1d85d241 150
9c3f979f 151 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
6a488035
TO
152
153 $caseRelationships = CRM_Case_BAO_Case::getCaseRoles($contactID, $caseID);
154 $caseTypeName = CRM_Case_BAO_Case::getCaseType($caseID, 'name');
155 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
353ffa53 156 $caseRoles = $xmlProcessor->get($caseTypeName, 'CaseRoles');
1d85d241 157
6a488035 158 $hasAccessToAllCases = CRM_Core_Permission::check('access all cases and activities');
1d85d241 159
6a488035 160 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseTypeName);
ad280fb6 161
6a488035 162 foreach ($caseRelationships as $key => $value) {
3b1c37fe
CW
163 // This role has been filled
164 unset($caseRoles[$value['relation_type']]);
b44e3f84 165 // mark original case relationships record to use on setting edit links below
6a488035
TO
166 $caseRelationships[$key]['source'] = 'caseRel';
167 }
1d85d241 168
6a488035
TO
169 $caseRoles['client'] = CRM_Case_BAO_Case::getContactNames($caseID);
170
171 // move/transform caseRoles array data to caseRelationships
172 // for sorting and display
5b6db2c7 173 // CRM-14466 added cid to the non-client array to avoid php notice
22e263ad 174 foreach ($caseRoles as $id => $value) {
6a488035
TO
175 if ($id != "client") {
176 $rel = array();
177 $rel['relation'] = $value;
178 $rel['relation_type'] = $id;
179 $rel['name'] = '(not assigned)';
180 $rel['phone'] = '';
181 $rel['email'] = '';
182 $rel['source'] = 'caseRoles';
183 $caseRelationships[] = $rel;
0db6c3e1
TO
184 }
185 else {
22e263ad 186 foreach ($value as $clientRole) {
6a488035
TO
187 $relClient = array();
188 $relClient['relation'] = 'Client';
189 $relClient['name'] = $clientRole['sort_name'];
190 $relClient['phone'] = $clientRole['phone'];
191 $relClient['email'] = $clientRole['email'];
192 $relClient['cid'] = $clientRole['contact_id'];
193 $relClient['source'] = 'contact';
194 $caseRelationships[] = $relClient;
195 }
196 }
197 }
198
199 // sort clientRelationships array using jquery call params
200 foreach ($caseRelationships as $key => $row) {
9c3f979f 201 $sortArray[$key] = $row[$params['_raw_values']['sort'][0]];
6a488035 202 }
9c3f979f 203 $sort_type = "SORT_" . strtoupper($params['_raw_values']['order'][0]);
0e2079a1 204 array_multisort($sortArray, constant($sort_type), $caseRelationships);
6a488035 205
ad280fb6 206 $relationships = array();
5b6db2c7 207
6a488035 208 // set user name, email and edit columns links
ad280fb6 209 foreach ($caseRelationships as $key => &$row) {
3b1c37fe
CW
210 $typeLabel = $row['relation'];
211 // Add "<br />(Case Manager)" to label
3a66e411 212 if (!empty($row['relation_type']) && $row['relation_type'] == $managerRoleId) {
3b1c37fe
CW
213 $row['relation'] .= '<br />' . '(' . ts('Case Manager') . ')';
214 }
6a488035 215 // view user links
3662628a 216 if (!empty($row['cid'])) {
86bfa4f6 217 $row['name'] = '<a class="view-contact" title="' . ts('View Contact') . '" href=' . CRM_Utils_System::url('civicrm/contact/view',
353ffa53 218 'action=view&reset=1&cid=' . $row['cid']) . '>' . $row['name'] . '</a>';
5b6db2c7 219 }
6a488035 220 // email column links/icon
c91df8b4 221 if ($row['email']) {
aac8c264 222 $row['email'] = '<a class="crm-hover-button crm-popup" href="' . CRM_Utils_System::url('civicrm/activity/email/add', 'reset=1&action=add&atype=3&cid=' . $row['cid']) . '&caseid=' . $caseID . '" title="' . ts('Send an Email') . '"><i class="crm-i fa-envelope"></i></a>';
6a488035
TO
223 }
224 // edit links
3662628a 225 $row['actions'] = '';
6a488035 226 if ($hasAccessToAllCases) {
e3756c36
CW
227 $contactType = empty($row['relation_type']) ? '' : (string) CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $row['relation_type'], 'contact_type_b');
228 $contactType = $contactType == 'Contact' ? '' : $contactType;
22e263ad 229 switch ($row['source']) {
32864ccf 230 case 'caseRel':
9cc8181f 231 $row['actions'] = '<a href="#editCaseRoleDialog" title="' . ts('Reassign %1', array(1 => $typeLabel)) . '" class="crm-hover-button case-miniform" data-contact_type="' . $contactType . '" data-rel_type="' . $row['relation_type'] . '_' . $row['relationship_direction'] . '" data-cid="' . $row['cid'] . '" data-rel_id="' . $row['rel_id'] . '"data-key="' . CRM_Core_Key::get('civicrm/ajax/relation') . '">' .
aac8c264 232 '<i class="crm-i fa-pencil"></i>' .
353ffa53 233 '</a>' .
3b1c37fe 234 '<a href="#deleteCaseRoleDialog" title="' . ts('Remove %1', array(1 => $typeLabel)) . '" class="crm-hover-button case-miniform" data-contact_type="' . $contactType . '" data-rel_type="' . $row['relation_type'] . '_' . $row['relationship_direction'] . '" data-cid="' . $row['cid'] . '" data-key="' . CRM_Core_Key::get('civicrm/ajax/delcaserole') . '">' .
92fcb95f 235 '<span class="icon delete-icon"></span>' .
353ffa53 236 '</a>';
32864ccf 237 break;
1d85d241 238
32864ccf 239 case 'caseRoles':
2320202e 240 $row['actions'] = '<a href="#editCaseRoleDialog" title="' . ts('Assign %1', array(1 => $typeLabel)) . '" class="crm-hover-button case-miniform" data-contact_type="' . $contactType . '" data-rel_type="' . $row['relation_type'] . '_a_b" data-key="' . CRM_Core_Key::get('civicrm/ajax/relation') . '">' .
aac8c264 241 '<i class="crm-i fa-pencil"></i>' .
353ffa53 242 '</a>';
32864ccf 243 break;
6a488035 244 }
6a488035 245 }
ad280fb6
JL
246 unset($row['cid']);
247 unset($row['relation_type']);
248 unset($row['rel_id']);
249 unset($row['client_id']);
250 unset($row['source']);
251 array_push($relationships, $row);
6a488035 252 }
ad280fb6
JL
253 $params['total'] = count($relationships);
254
255 $caseRelationshipsDT = array();
256 $caseRelationshipsDT['data'] = $relationships;
257 $caseRelationshipsDT['recordsTotal'] = $params['total'];
258 $caseRelationshipsDT['recordsFiltered'] = $params['total'];
259
260 CRM_Utils_JSON::output($caseRelationshipsDT);
ffd93213 261
1d85d241
DL
262 }
263
00be9182 264 public static function convertToCaseActivity() {
6a488035 265 $params = array('caseID', 'activityID', 'contactID', 'newSubject', 'targetContactIds', 'mode');
ecdef330 266 $vals = array();
6a488035
TO
267 foreach ($params as $param) {
268 $vals[$param] = CRM_Utils_Array::value($param, $_POST);
269 }
270
ecdef330 271 CRM_Utils_JSON::output(self::_convertToCaseActivity($vals));
6a488035
TO
272 }
273
ffd93213 274 /**
c490a46a 275 * @param array $params
ffd93213
EM
276 *
277 * @return array
278 */
00be9182 279 public static function _convertToCaseActivity($params) {
6a488035
TO
280 if (!$params['activityID'] || !$params['caseID']) {
281 return (array('error_msg' => 'required params missing.'));
282 }
283
284 $otherActivity = new CRM_Activity_DAO_Activity();
285 $otherActivity->id = $params['activityID'];
286 if (!$otherActivity->find(TRUE)) {
287 return (array('error_msg' => 'activity record is missing.'));
288 }
289 $actDateTime = CRM_Utils_Date::isoToMysql($otherActivity->activity_date_time);
290
7808aae6 291 // Create new activity record.
6a488035
TO
292 $mainActivity = new CRM_Activity_DAO_Activity();
293 $mainActVals = array();
294 CRM_Core_DAO::storeValues($otherActivity, $mainActVals);
295
7808aae6 296 // Get new activity subject.
6a488035
TO
297 if (!empty($params['newSubject'])) {
298 $mainActVals['subject'] = $params['newSubject'];
299 }
300
301 $mainActivity->copyValues($mainActVals);
302 $mainActivity->id = NULL;
303 $mainActivity->activity_date_time = $actDateTime;
7808aae6 304 // Make sure this is current revision.
6a488035 305 $mainActivity->is_current_revision = TRUE;
9a30d940
MWMC
306 $mainActivity->original_id = $otherActivity->id;
307 $otherActivity->is_current_revision = FALSE;
6a488035
TO
308
309 $mainActivity->save();
310 $mainActivityId = $mainActivity->id;
311 CRM_Activity_BAO_Activity::logActivityAction($mainActivity);
6a488035 312
7808aae6
SB
313 // Mark previous activity as deleted. If it was a non-case activity
314 // then just change the subject.
6a488035 315 if (in_array($params['mode'], array(
353ffa53 316 'move',
79d7553f 317 'file',
353ffa53 318 ))) {
6a488035
TO
319 $caseActivity = new CRM_Case_DAO_CaseActivity();
320 $caseActivity->case_id = $params['caseID'];
321 $caseActivity->activity_id = $otherActivity->id;
322 if ($params['mode'] == 'move' || $caseActivity->find(TRUE)) {
323 $otherActivity->is_deleted = 1;
324 }
325 else {
326 $otherActivity->subject = ts('(Filed on case %1)', array(
c5c263ca
AH
327 1 => $params['caseID'],
328 )) . ' ' . $otherActivity->subject;
6a488035 329 }
6a488035
TO
330 $otherActivity->save();
331
6a488035 332 }
6a488035
TO
333
334 $targetContacts = array();
335 if (!empty($params['targetContactIds'])) {
336 $targetContacts = array_unique(explode(',', $params['targetContactIds']));
337 }
f813f78e 338
44f817d4 339 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
a24b3694 340 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
341 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
342 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
343
7b1ec1c6 344 $sourceContactID = CRM_Activity_BAO_Activity::getSourceContactID($params['activityID']);
345 $src_params = array(
346 'activity_id' => $mainActivityId,
347 'contact_id' => $sourceContactID,
21dfd5f5 348 'record_type_id' => $sourceID,
7b1ec1c6 349 );
350 CRM_Activity_BAO_ActivityContact::create($src_params);
351
6a488035
TO
352 foreach ($targetContacts as $key => $value) {
353 $targ_params = array(
354 'activity_id' => $mainActivityId,
1d85d241 355 'contact_id' => $value,
21dfd5f5 356 'record_type_id' => $targetID,
6a488035 357 );
1d85d241 358 CRM_Activity_BAO_ActivityContact::create($targ_params);
6a488035
TO
359 }
360
c012436d
BS
361 //CRM-21114 retrieve assignee contacts from original case; allow overriding from params
362 $assigneeContacts = CRM_Activity_BAO_ActivityContact::retrieveContactIdsByActivityId($params['activityID'], $assigneeID);
6a488035
TO
363 if (!empty($params['assigneeContactIds'])) {
364 $assigneeContacts = array_unique(explode(',', $params['assigneeContactIds']));
365 }
366 foreach ($assigneeContacts as $key => $value) {
367 $assigneeParams = array(
368 'activity_id' => $mainActivityId,
1d85d241 369 'contact_id' => $value,
21dfd5f5 370 'record_type_id' => $assigneeID,
6a488035 371 );
1d85d241 372 CRM_Activity_BAO_ActivityContact::create($assigneeParams);
6a488035
TO
373 }
374
7808aae6 375 // Attach newly created activity to case.
6a488035
TO
376 $caseActivity = new CRM_Case_DAO_CaseActivity();
377 $caseActivity->case_id = $params['caseID'];
378 $caseActivity->activity_id = $mainActivityId;
379 $caseActivity->save();
380 $error_msg = $caseActivity->_lastError;
6a488035
TO
381
382 $params['mainActivityId'] = $mainActivityId;
383 CRM_Activity_BAO_Activity::copyExtendedActivityData($params);
388995aa 384 CRM_Utils_Hook::post('create', 'CaseActivity', $caseActivity->id, $caseActivity);
6a488035
TO
385
386 return (array('error_msg' => $error_msg, 'newId' => $mainActivity->id));
387 }
388
f2ac86d1 389 /**
390 * Get activities for the contact.
391 *
392 * @return array
393 */
00be9182 394 public static function getContactActivity() {
9c3f979f
MM
395 $requiredParameters = array(
396 'cid' => 'Integer',
397 );
6a488035 398
9c3f979f
MM
399 $optionalParameters = array(
400 'context' => 'String',
23289ddd 401 'activity_type_id' => 'Integer',
402 'activity_type_exclude_id' => 'Integer',
49d4d222 403 'activity_status_id' => 'String',
6e793248 404 'activity_date_time_relative' => 'String',
405 'activity_date_time_low' => 'String',
406 'activity_date_time_high' => 'String',
9c3f979f 407 );
6a488035 408
9c3f979f 409 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
5d817a13 410 $params += CRM_Core_Page_AJAX::validateParams($requiredParameters, $optionalParameters);
6a488035 411
e8691b2c
MM
412 // To be consistent, the cid parameter should be renamed to contact_id in
413 // the template file, see templates/CRM/Activity/Selector/Selector.tpl
414 $params['contact_id'] = $params['cid'];
415 unset($params['cid']);
416
6a488035
TO
417 // get the contact activities
418 $activities = CRM_Activity_BAO_Activity::getContactActivitySelector($params);
419
c7d77593 420 foreach ($activities['data'] as $key => $value) {
7808aae6 421 // Check if recurring activity.
b53cbfbc 422 if (!empty($value['is_recurring_activity'])) {
04374d9d 423 $repeat = $value['is_recurring_activity'];
c7d77593 424 $activities['data'][$key]['activity_type'] .= '<br/><span class="bold">' . ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1])) . '</span>';
97c7504f 425 }
426 }
427
6a488035 428 // store the activity filter preference CRM-11761
a6d192c8 429 if (Civi::settings()->get('preserve_activity_tab_filter') && ($userID = CRM_Core_Session::getLoggedInContactID())) {
430 unset($optionalParameters['context']);
431 foreach ($optionalParameters as $searchField => $dataType) {
c3a9ccbb
JP
432 $formSearchField = $searchField;
433 if ($searchField == 'activity_type_id') {
434 $formSearchField = 'activity_type_filter_id';
435 }
436 elseif ($searchField == 'activity_type_exclude_id') {
437 $formSearchField = 'activity_type_exclude_filter_id';
438 }
a6d192c8 439 if (!empty($params[$searchField])) {
c3a9ccbb 440 $activityFilter[$formSearchField] = CRM_Utils_Type::escape($params[$searchField], $dataType);
a6d192c8 441 if (in_array($searchField, array('activity_date_low', 'activity_date_high'))) {
442 $activityFilter['activity_date_relative'] = 0;
443 }
444 elseif ($searchField == 'activity_status_id') {
445 $activityFilter['status_id'] = explode(',', $activityFilter[$searchField]);
446 }
447 }
448 elseif (in_array($searchField, array('activity_type_id', 'activity_type_exclude_id'))) {
c3a9ccbb 449 $activityFilter[$formSearchField] = '';
a6d192c8 450 }
451 }
f3548d18 452
c3c679b0 453 Civi::contactSettings()->set('activity_tab_filter', $activityFilter);
6a488035 454 }
c3a9ccbb
JP
455 if (!empty($_GET['is_unit_test'])) {
456 return array($activities, $activityFilter);
457 }
1d85d241 458
7d12de7f 459 CRM_Utils_JSON::output($activities);
6a488035 460 }
96025800 461
6a488035 462}