Merge pull request #7797 from JKingsnorth/CRM-17977
[civicrm-core.git] / CRM / Activity / Page / AJAX.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
32 *
33 */
34
35 /**
36 * This class contains all the function that are called using AJAX (jQuery)
37 */
38 class CRM_Activity_Page_AJAX {
39 public static function getCaseActivity() {
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');
45
46 $optionalParameters = array(
47 'source_contact_id' => 'Integer',
48 'status_id' => 'Integer',
49 'activity_deleted' => 'Boolean',
50 'activity_type_id' => 'Integer',
51 'activity_date_low' => 'Date',
52 'activity_date_high' => 'Date',
53 );
54
55 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
56 $params += CRM_Core_Page_AJAX::validateParams(array(), $optionalParameters);
57
58 // get the activities related to given case
59 $activities = CRM_Case_BAO_Case::getCaseActivity($caseID, $params, $contactID, $context, $userID);
60
61 CRM_Utils_JSON::output($activities);
62 }
63
64 public static function getCaseGlobalRelationships() {
65 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
66
67 // get the activities related to given case
68 $globalGroupInfo = array();
69
70 // get the total row count
71 CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo, NULL, FALSE, TRUE, NULL, NULL);
72 // limit the rows
73 $relGlobal = CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo, $params['sortBy'], $showLinks = TRUE, FALSE, $params['offset'], $params['rp']);
74
75 $relationships = array();
76 // after sort we can update username fields to be a url
77 foreach ($relGlobal as $key => $value) {
78 $relationship = array();
79 $relationship['sort_name'] = $value['sort_name'];
80 $relationship['phone'] = $value['phone'];
81 $relationship['email'] = $value['email'];
82
83 array_push($relationships, $relationship);
84 }
85
86 $globalRelationshipsDT = array();
87 $globalRelationshipsDT['data'] = $relationships;
88 $globalRelationshipsDT['recordsTotal'] = count($relationships);
89 $globalRelationshipsDT['recordsFiltered'] = count($relationships);
90
91 CRM_Utils_JSON::output($globalRelationshipsDT);
92 }
93
94 public static function getCaseClientRelationships() {
95 $caseID = CRM_Utils_Type::escape($_GET['caseID'], 'Integer');
96 $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
97
98 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
99
100 // Retrieve ALL client relationships
101 $relClient = CRM_Contact_BAO_Relationship::getRelationship($contactID,
102 CRM_Contact_BAO_Relationship::CURRENT,
103 0, 0, 0, NULL, NULL, FALSE
104 );
105
106 $caseRelationships = CRM_Case_BAO_Case::getCaseRoles($contactID, $caseID);
107
108 // Now build 'Other Relationships' array by removing relationships that are already listed under Case Roles
109 // so they don't show up twice.
110 $clientRelationships = array();
111 foreach ($relClient as $r) {
112 if (!array_key_exists($r['id'], $caseRelationships)) {
113 $clientRelationships[] = $r;
114 }
115 }
116
117 // sort clientRelationships array using jquery call params
118 foreach ($clientRelationships as $key => $row) {
119 $sortArray[$key] = $row[$params['_raw_values']['sort'][0]];
120 }
121 $sort_type = "SORT_" . strtoupper($params['_raw_values']['order'][0]);
122 array_multisort($sortArray, constant($sort_type), $clientRelationships);
123
124 $relationships = array();
125 // after sort we can update username fields to be a url
126 foreach ($clientRelationships as $key => $value) {
127 $relationship = array();
128 $relationship['relation'] = $value['relation'];
129 $relationship['name'] = '<a href=' . CRM_Utils_System::url('civicrm/contact/view',
130 'action=view&reset=1&cid=' . $clientRelationships[$key]['cid']) . '>' . $clientRelationships[$key]['name'] . '</a>';
131 $relationship['phone'] = $value['phone'];
132 $relationship['email'] = $value['email'];
133
134 array_push($relationships, $relationship);
135 }
136
137 $clientRelationshipsDT = array();
138 $clientRelationshipsDT['data'] = $relationships;
139 $clientRelationshipsDT['recordsTotal'] = count($relationships);
140 $clientRelationshipsDT['recordsFiltered'] = count($relationships);
141
142 CRM_Utils_JSON::output($clientRelationshipsDT);
143 }
144
145
146 public static function getCaseRoles() {
147 $caseID = CRM_Utils_Type::escape($_GET['caseID'], 'Integer');
148 $contactID = CRM_Utils_Type::escape($_GET['cid'], 'Integer');
149
150 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
151
152 $caseRelationships = CRM_Case_BAO_Case::getCaseRoles($contactID, $caseID);
153 $caseTypeName = CRM_Case_BAO_Case::getCaseType($caseID, 'name');
154 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
155 $caseRoles = $xmlProcessor->get($caseTypeName, 'CaseRoles');
156
157 $hasAccessToAllCases = CRM_Core_Permission::check('access all cases and activities');
158
159 $managerRoleId = $xmlProcessor->getCaseManagerRoleId($caseTypeName);
160
161 foreach ($caseRelationships as $key => $value) {
162 // This role has been filled
163 unset($caseRoles[$value['relation_type']]);
164 // mark original case relationships record to use on setting edit links below
165 $caseRelationships[$key]['source'] = 'caseRel';
166 }
167
168 $caseRoles['client'] = CRM_Case_BAO_Case::getContactNames($caseID);
169
170 // move/transform caseRoles array data to caseRelationships
171 // for sorting and display
172 // CRM-14466 added cid to the non-client array to avoid php notice
173 foreach ($caseRoles as $id => $value) {
174 if ($id != "client") {
175 $rel = array();
176 $rel['relation'] = $value;
177 $rel['relation_type'] = $id;
178 $rel['name'] = '(not assigned)';
179 $rel['phone'] = '';
180 $rel['email'] = '';
181 $rel['source'] = 'caseRoles';
182 $caseRelationships[] = $rel;
183 }
184 else {
185 foreach ($value as $clientRole) {
186 $relClient = array();
187 $relClient['relation'] = 'Client';
188 $relClient['name'] = $clientRole['sort_name'];
189 $relClient['phone'] = $clientRole['phone'];
190 $relClient['email'] = $clientRole['email'];
191 $relClient['cid'] = $clientRole['contact_id'];
192 $relClient['source'] = 'contact';
193 $caseRelationships[] = $relClient;
194 }
195 }
196 }
197
198 // sort clientRelationships array using jquery call params
199 foreach ($caseRelationships as $key => $row) {
200 $sortArray[$key] = $row[$params['_raw_values']['sort'][0]];
201 }
202 $sort_type = "SORT_" . strtoupper($params['_raw_values']['order'][0]);
203 array_multisort($sortArray, constant($sort_type), $caseRelationships);
204
205 $relationships = array();
206
207 // set user name, email and edit columns links
208 foreach ($caseRelationships as $key => &$row) {
209 $typeLabel = $row['relation'];
210 // Add "<br />(Case Manager)" to label
211 if ($row['relation_type'] == $managerRoleId) {
212 $row['relation'] .= '<br />' . '(' . ts('Case Manager') . ')';
213 }
214 // view user links
215 if (!empty($row['cid'])) {
216 $row['name'] = '<a class="view-contact" title="' . ts('View Contact') . '" href=' . CRM_Utils_System::url('civicrm/contact/view',
217 'action=view&reset=1&cid=' . $row['cid']) . '>' . $row['name'] . '</a>';
218 }
219 // email column links/icon
220 if ($row['email']) {
221 $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>';
222 }
223 // edit links
224 $row['actions'] = '';
225 if ($hasAccessToAllCases) {
226 $contactType = empty($row['relation_type']) ? '' : (string) CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $row['relation_type'], 'contact_type_b');
227 $contactType = $contactType == 'Contact' ? '' : $contactType;
228 switch ($row['source']) {
229 case 'caseRel':
230 $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="' . '" data-rel_id="' . $row['rel_id'] . '"data-key="' . CRM_Core_Key::get('civicrm/ajax/relation') . '">' .
231 '<i class="crm-i fa-pencil"></i>' .
232 '</a>' .
233 '<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') . '">' .
234 '<span class="icon delete-icon"></span>' .
235 '</a>';
236 break;
237
238 case 'caseRoles':
239 $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'] . '_b_a" data-key="' . CRM_Core_Key::get('civicrm/ajax/relation') . '">' .
240 '<i class="crm-i fa-pencil"></i>' .
241 '</a>';
242 break;
243 }
244 }
245 unset($row['cid']);
246 unset($row['relation_type']);
247 unset($row['rel_id']);
248 unset($row['client_id']);
249 unset($row['source']);
250 array_push($relationships, $row);
251 }
252 $params['total'] = count($relationships);
253
254 $caseRelationshipsDT = array();
255 $caseRelationshipsDT['data'] = $relationships;
256 $caseRelationshipsDT['recordsTotal'] = $params['total'];
257 $caseRelationshipsDT['recordsFiltered'] = $params['total'];
258
259 CRM_Utils_JSON::output($caseRelationshipsDT);
260
261 }
262
263 public static function convertToCaseActivity() {
264 $params = array('caseID', 'activityID', 'contactID', 'newSubject', 'targetContactIds', 'mode');
265 $vals = array();
266 foreach ($params as $param) {
267 $vals[$param] = CRM_Utils_Array::value($param, $_POST);
268 }
269
270 CRM_Utils_JSON::output(self::_convertToCaseActivity($vals));
271 }
272
273 /**
274 * @param array $params
275 *
276 * @return array
277 */
278 public static function _convertToCaseActivity($params) {
279 if (!$params['activityID'] || !$params['caseID']) {
280 return (array('error_msg' => 'required params missing.'));
281 }
282
283 $otherActivity = new CRM_Activity_DAO_Activity();
284 $otherActivity->id = $params['activityID'];
285 if (!$otherActivity->find(TRUE)) {
286 return (array('error_msg' => 'activity record is missing.'));
287 }
288 $actDateTime = CRM_Utils_Date::isoToMysql($otherActivity->activity_date_time);
289
290 // Create new activity record.
291 $mainActivity = new CRM_Activity_DAO_Activity();
292 $mainActVals = array();
293 CRM_Core_DAO::storeValues($otherActivity, $mainActVals);
294
295 // Get new activity subject.
296 if (!empty($params['newSubject'])) {
297 $mainActVals['subject'] = $params['newSubject'];
298 }
299
300 $mainActivity->copyValues($mainActVals);
301 $mainActivity->id = NULL;
302 $mainActivity->activity_date_time = $actDateTime;
303 // Make sure this is current revision.
304 $mainActivity->is_current_revision = TRUE;
305 // Drop all relations.
306 $mainActivity->parent_id = $mainActivity->original_id = NULL;
307
308 $mainActivity->save();
309 $mainActivityId = $mainActivity->id;
310 CRM_Activity_BAO_Activity::logActivityAction($mainActivity);
311 $mainActivity->free();
312
313 // Mark previous activity as deleted. If it was a non-case activity
314 // then just change the subject.
315 if (in_array($params['mode'], array(
316 'move',
317 'file',
318 ))) {
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(
327 1 => $params['caseID'],
328 )) . ' ' . $otherActivity->subject;
329 }
330 $otherActivity->activity_date_time = $actDateTime;
331 $otherActivity->save();
332
333 $caseActivity->free();
334 }
335 $otherActivity->free();
336
337 $targetContacts = array();
338 if (!empty($params['targetContactIds'])) {
339 $targetContacts = array_unique(explode(',', $params['targetContactIds']));
340 }
341
342 $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
343 $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
344 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
345 $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
346
347 $sourceContactID = CRM_Activity_BAO_Activity::getSourceContactID($params['activityID']);
348 $src_params = array(
349 'activity_id' => $mainActivityId,
350 'contact_id' => $sourceContactID,
351 'record_type_id' => $sourceID,
352 );
353 CRM_Activity_BAO_ActivityContact::create($src_params);
354
355 foreach ($targetContacts as $key => $value) {
356 $targ_params = array(
357 'activity_id' => $mainActivityId,
358 'contact_id' => $value,
359 'record_type_id' => $targetID,
360 );
361 CRM_Activity_BAO_ActivityContact::create($targ_params);
362 }
363
364 // typically this will be empty, since assignees on another case may be completely different
365 $assigneeContacts = array();
366 if (!empty($params['assigneeContactIds'])) {
367 $assigneeContacts = array_unique(explode(',', $params['assigneeContactIds']));
368 }
369 foreach ($assigneeContacts as $key => $value) {
370 $assigneeParams = array(
371 'activity_id' => $mainActivityId,
372 'contact_id' => $value,
373 'record_type_id' => $assigneeID,
374 );
375 CRM_Activity_BAO_ActivityContact::create($assigneeParams);
376 }
377
378 // Attach newly created activity to case.
379 $caseActivity = new CRM_Case_DAO_CaseActivity();
380 $caseActivity->case_id = $params['caseID'];
381 $caseActivity->activity_id = $mainActivityId;
382 $caseActivity->save();
383 $error_msg = $caseActivity->_lastError;
384 $caseActivity->free();
385
386 $params['mainActivityId'] = $mainActivityId;
387 CRM_Activity_BAO_Activity::copyExtendedActivityData($params);
388
389 return (array('error_msg' => $error_msg, 'newId' => $mainActivity->id));
390 }
391
392 public static function getContactActivity() {
393 $requiredParameters = array(
394 'cid' => 'Integer',
395 );
396
397 $optionalParameters = array(
398 'context' => 'String',
399 );
400
401 $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
402 $params += CRM_Core_Page_AJAX::validateParams($requiredParameters, $optionalParameters);
403
404 // To be consistent, the cid parameter should be renamed to contact_id in
405 // the template file, see templates/CRM/Activity/Selector/Selector.tpl
406 $params['contact_id'] = $params['cid'];
407 unset($params['cid']);
408
409 // get the contact activities
410 $activities = CRM_Activity_BAO_Activity::getContactActivitySelector($params);
411
412 foreach ($activities['data'] as $key => $value) {
413 // Check if recurring activity.
414 if (!empty($value['is_recurring_activity'])) {
415 $repeat = $value['is_recurring_activity'];
416 $activities['data'][$key]['activity_type'] .= '<br/><span class="bold">' . ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1])) . '</span>';
417 }
418 }
419
420 // store the activity filter preference CRM-11761
421 $session = CRM_Core_Session::singleton();
422 $userID = $session->get('userID');
423 if ($userID) {
424 $activityFilter = array(
425 'activity_type_filter_id' => empty($params['activity_type_id']) ? '' : CRM_Utils_Type::escape($params['activity_type_id'], 'Integer'),
426 'activity_type_exclude_filter_id' => empty($params['activity_type_exclude_id']) ? '' : CRM_Utils_Type::escape($params['activity_type_exclude_id'], 'Integer'),
427 );
428
429 /**
430 * @var \Civi\Core\SettingsBag $cSettings
431 */
432 $cSettings = Civi::service('settings_manager')->getBagByContact(CRM_Core_Config::domainID(), $userID);
433 $cSettings->set('activity_tab_filter', $activityFilter);
434 }
435
436 CRM_Utils_JSON::output($activities);
437 }
438
439 }