ILIAS  release_9 Revision v9.13-25-g2c18ec4c24f
class.ilChatroomViewGUI.php
Go to the documentation of this file.
1 <?php
2 
19 declare(strict_types=1);
20 
24 
32 {
33  public function joinWithCustomName(): void
34  {
35  $this->redirectIfNoPermission('read');
36 
37  $this->gui->switchToVisibleMode();
38  $this->setupTemplate();
39  $room = ilChatroom::byObjectId($this->gui->getObject()->getId());
40  $chat_user = new ilChatroomUser($this->ilUser, $room);
41  $failure = true;
42  $username = '';
43 
44  if ($this->hasRequestValue('custom_username_radio')) {
45  if (
46  $this->hasRequestValue('custom_username_text') &&
47  $this->getRequestValue('custom_username_radio', $this->refinery->kindlyTo()->string()) === 'custom_username'
48  ) {
49  $username = $this->getRequestValue('custom_username_text', $this->refinery->kindlyTo()->string());
50  $failure = false;
51  } elseif (
52  method_exists(
53  $chat_user,
54  'build' . $this->getRequestValue('custom_username_radio', $this->refinery->kindlyTo()->string())
55  )
56  ) {
57  $username = $chat_user->{
58  'build' . $this->getRequestValue('custom_username_radio', $this->refinery->kindlyTo()->string())
59  }();
60  $failure = false;
61  }
62  }
63 
64  if (!$failure && trim($username) !== '') {
65  if (!$room->isSubscribed($chat_user->getUserId())) {
66  $chat_user->setUsername($chat_user->buildUniqueUsername($username));
67  }
68 
69  $this->showRoom($room, $chat_user);
70  } else {
71  $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('no_username_given'));
72  $this->showNameSelection($chat_user);
73  }
74  }
75 
79  private function setupTemplate(): void
80  {
81  $this->mainTpl->addJavaScript('Modules/Chatroom/js/chat.js');
82  $this->mainTpl->addJavaScript('Modules/Chatroom/js/iliaschat.jquery.js');
83  $this->mainTpl->addJavaScript('node_modules/jquery-outside-events/jquery.ba-outside-events.js');
84  $this->mainTpl->addJavaScript('./Services/UIComponent/AdvancedSelectionList/js/AdvancedSelectionList.js');
85 
86  $this->mainTpl->addCss('Modules/Chatroom/templates/default/style.css');
87 
88  $this->mainTpl->setPermanentLink($this->gui->getObject()->getType(), $this->gui->getObject()->getRefId());
89  }
90 
94  private function showRoom(ilChatroom $room, ilChatroomUser $chat_user): void
95  {
96  $this->redirectIfNoPermission('read');
97 
98  $user_id = $chat_user->getUserId();
99 
100  $ref_id = $this->getRequestValue('ref_id', $this->refinery->kindlyTo()->int());
101  $this->navigationHistory->addItem(
102  $ref_id,
103  $this->ilCtrl->getLinkTargetByClass(ilRepositoryGUI::class, 'view'),
104  'chtr'
105  );
106 
107  if ($room->isUserBanned($user_id)) {
108  $this->cancelJoin($this->ilLng->txt('banned'));
109  return;
110  }
111 
112  $scope = $room->getRoomId();
113  $connector = $this->gui->getConnector();
114  $response = $connector->connect($scope, $user_id);
115 
116  if (!$response) {
117  $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('unable_to_connect'), true);
118  $this->ilCtrl->redirectByClass(ilInfoScreenGUI::class, 'info');
119  }
120 
121  if (!$room->isSubscribed($chat_user->getUserId())) {
122  $room->connectUser($chat_user);
123  }
124 
125  $response = $connector->sendEnterPrivateRoom($scope, $user_id);
126  if (!$response) {
127  $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('unable_to_connect'), true);
128  $this->ilCtrl->redirectByClass('ilinfoscreengui', 'info');
129  }
130 
131  $settings = $connector->getSettings();
132 
133  $initial = new stdClass();
134  $initial->users = $room->getConnectedUsers();
135  $initial->redirect_url = $this->ilCtrl->getLinkTarget($this->gui, 'view-lostConnection', '', false);
136  $initial->profile_image_url = $this->ilCtrl->getLinkTarget($this->gui, 'view-getUserProfileImages', '', true);
137  $initial->no_profile_image_url = ilUtil::getImagePath('placeholder/no_photo_xxsmall.jpg');
138  $initial->subdirectory = $settings->getSubDirectory();
139 
140  $initial->userinfo = [
141  'moderator' => ilChatroom::checkUserPermissions('moderate', $ref_id, false),
142  'id' => $chat_user->getUserId(),
143  'login' => $chat_user->getUsername(),
144  'broadcast_typing' => $chat_user->enabledBroadcastTyping(),
145  ];
146 
147  $initial->messages = [];
148 
149  if ((int) $room->getSetting('display_past_msgs')) {
150  $initial->messages = array_merge(
151  $initial->messages,
152  array_reverse($room->getLastMessages($room->getSetting('display_past_msgs'), $chat_user))
153  );
154  }
155 
156  $roomTpl = new ilTemplate('tpl.chatroom.html', true, true, 'Modules/Chatroom');
157  $roomTpl->setVariable('BASEURL', $settings->generateClientUrl());
158  $roomTpl->setVariable('INSTANCE', $settings->getInstance());
159  $roomTpl->setVariable('SCOPE', $scope);
160  $roomTpl->setVariable('POSTURL', $this->ilCtrl->getLinkTarget($this->gui, 'postMessage', '', true));
161 
162  $roomTpl->setVariable('ACTIONS', $this->ilLng->txt('actions'));
163  $roomTpl->setVariable('LBL_USER', $this->ilLng->txt('user'));
164  $roomTpl->setVariable('LBL_USER_TEXT', $this->ilLng->txt('invite_username'));
165  $showAutoMessages = true;
166  if ($this->ilUser->getPref('chat_hide_automsg_' . $room->getRoomId())) {
167  $showAutoMessages = false;
168  }
169 
170  $initial->state = new stdClass();
171  $initial->state->scrolling = true;
172  $initial->state->show_auto_msg = $showAutoMessages;
173 
174  $roomTpl->setVariable('INITIAL_DATA', json_encode($initial, JSON_THROW_ON_ERROR));
175  $roomTpl->setVariable('INITIAL_USERS', json_encode($room->getConnectedUsers(), JSON_THROW_ON_ERROR));
176  $roomTpl->setVariable('CHAT_OUTPUT', $this->panel($this->ilLng->txt('messages'), $this->legacy('<div id="chat_messages"></div>')));
177  $roomTpl->setVariable('CHAT_INPUT', $this->panel($this->ilLng->txt('write_message'), $this->sendMessageForm()));
178 
179  $this->renderLanguageVariables($roomTpl);
180 
182 
183  $this->mainTpl->setContent($roomTpl->get());
184  $this->mainTpl->setRightContent($this->userList() . $this->chatFunctions($showAutoMessages));
185  }
186 
187  private function sendMessageForm(): Component
188  {
189  $template = new ilTemplate('tpl.chatroom_send_message_form.html', true, true, 'Modules/Chatroom');
190  $this->renderSendMessageBox($template);
191 
192  return $this->legacy($template->get());
193  }
194 
195  private function userList(): string
196  {
197  $roomRightTpl = new ilTemplate('tpl.chatroom_right.html', true, true, 'Modules/Chatroom');
198  $this->renderRightUsersBlock($roomRightTpl);
199 
200  return $this->panel($this->ilLng->txt('users'), $this->legacy($roomRightTpl->get()));
201  }
202 
203  private function chatFunctions(bool $showAutoMessages): string
204  {
205  $auto_scroll = $this
206  ->uiFactory
207  ->button()
208  ->toggle(
209  $this->ilLng->txt('auto_scroll'),
210  '#',
211  '#',
212  true
213  )
214  ->withAriaLabel($this->ilLng->txt('auto_scroll'))
215  ->withOnLoadCode(static function (string $id): string {
216  return '$("#' . $id . '").on("click", function(e) {
217  let t = $(this), msg = $("#chat_messages");
218  if (t.hasClass("on")) {
219  msg.trigger("msg-scrolling:toggle", [true]);
220  } else {
221  msg.trigger("msg-scrolling:toggle", [false]);
222  }
223  });';
224  });
225 
226  $toggleUrl = $this->ilCtrl->getFormAction($this->gui, 'view-toggleAutoMessageDisplayState', '', true, false);
227  $messages = $this
228  ->uiFactory
229  ->button()
230  ->toggle(
231  $this->ilLng->txt('chat_show_auto_messages'),
232  '#',
233  '#',
234  $showAutoMessages
235  )
236  ->withAriaLabel($this->ilLng->txt('chat_show_auto_messages'))
237  ->withOnLoadCode(static function (string $id) use ($toggleUrl): string {
238  return '$("#' . $id . '").on("click", function(e) {
239  let t = $(this), msg = $("#chat_messages");
240  if (t.hasClass("on")) {
241  msg.trigger("auto-message:toggle", [true, "' . $toggleUrl . '"]);
242  } else {
243  msg.trigger("auto-message:toggle", [false, "' . $toggleUrl . '"]);
244  }
245  });';
246  });
247 
248  return $this->panel($this->ilLng->txt('chat_functions'), [
249  $this->legacy('<div id="chat_function_list"></div>'),
250  $this->legacy(sprintf('<div>%s%s</div>', $this->checkbox($auto_scroll), $this->checkbox($messages))),
251  ]);
252  }
253 
254  private function checkbox(Component $component): string
255  {
256  return sprintf('<div class="chatroom-centered-checkboxes">%s</div>', $this->uiRenderer->render($component));
257  }
258 
259  private function legacy(string $html): Component
260  {
261  return $this->uiFactory->legacy($html);
262  }
263 
264  private function panel(string $title, $body): string
265  {
266  $panel = $this->uiFactory->panel()->standard($title, $body);
267 
268  return $this->uiRenderer->render($panel);
269  }
270 
271  public function toggleAutoMessageDisplayState(): void
272  {
273  $this->redirectIfNoPermission('read');
274 
275  $room = ilChatroom::byObjectId($this->gui->getObject()->getId());
276 
277  $state = 0;
278  if ($this->http->wrapper()->post()->has('state')) {
279  $state = $this->http->wrapper()->post()->retrieve('state', $this->refinery->kindlyTo()->int());
280  }
281 
283  $this->ilUser->getId(),
284  'chat_hide_automsg_' . $room->getRoomId(),
285  (string) ((int) (!(bool) $state))
286  );
287 
288  $this->http->saveResponse(
289  $this->http->response()
290  ->withHeader(ResponseHeader::CONTENT_TYPE, 'application/json')
291  ->withBody(Streams::ofString(json_encode(['success' => true], JSON_THROW_ON_ERROR)))
292  );
293  $this->http->sendResponse();
294  $this->http->close();
295  }
296 
300  private function cancelJoin(string $message): void
301  {
302  $this->mainTpl->setOnScreenMessage('failure', $message);
303  }
304 
305  protected function renderSendMessageBox(ilTemplate $roomTpl): void
306  {
307  $roomTpl->setVariable('LBL_TOALL', $this->ilLng->txt('chat_message_to_all'));
308  $roomTpl->setVariable('LBL_SEND', $this->ilLng->txt('send'));
309  }
310 
311  protected function renderLanguageVariables(ilTemplate $roomTpl): void
312  {
313  $js_translations = [
314  'LBL_MAINROOM' => 'chat_mainroom',
315  'LBL_LEFT_PRIVATE_ROOM' => 'left_private_room',
316  'LBL_JOIN' => 'chat_join',
317  'LBL_INVITE_TO_PRIVATE_ROOM' => 'invite_to_private_room',
318  'LBL_KICK' => 'chat_kick',
319  'LBL_BAN' => 'chat_ban',
320  'LBL_KICK_QUESTION' => 'kick_question',
321  'LBL_BAN_QUESTION' => 'ban_question',
322  'LBL_ADDRESS' => 'chat_address',
323  'LBL_WHISPER' => 'chat_whisper',
324  'LBL_CONNECT' => 'chat_connection_established',
325  'LBL_DISCONNECT' => 'chat_connection_disconnected',
326  'LBL_TO_MAINROOM' => 'chat_to_mainroom',
327  'LBL_WELCOME_TO_CHAT' => 'welcome_to_chat',
328  'LBL_USER_INVITED' => 'user_invited',
329  'LBL_USER_KICKED' => 'user_kicked',
330  'LBL_USER_INVITED_SELF' => 'user_invited_self',
331  'LBL_PRIVATE_ROOM_CLOSED' => 'private_room_closed',
332  'LBL_PRIVATE_ROOM_ENTERED' => 'private_room_entered',
333  'LBL_PRIVATE_ROOM_LEFT' => 'private_room_left',
334  'LBL_PRIVATE_ROOM_ENTERED_USER' => 'private_room_entered_user',
335  'LBL_KICKED_FROM_PRIVATE_ROOM' => 'kicked_from_private_room',
336  'LBL_OK' => 'ok',
337  'LBL_DELETE' => 'delete',
338  'LBL_INVITE' => 'chat_invite',
339  'LBL_CANCEL' => 'cancel',
340  'LBL_WHISPER_TO' => 'whisper_to',
341  'LBL_SPEAK_TO' => 'speak_to',
342  'LBL_HISTORY_CLEARED' => 'history_cleared',
343  'LBL_CLEAR_ROOM_HISTORY' => 'clear_room_history',
344  'LBL_CLEAR_ROOM_HISTORY_QUESTION' => 'clear_room_history_question',
345  'LBL_END_WHISPER' => 'end_whisper',
346  'LBL_TIMEFORMAT' => 'lang_timeformat_no_sec',
347  'LBL_DATEFORMAT' => 'lang_dateformat',
348  ];
349  foreach ($js_translations as $placeholder => $lng_variable) {
350  $roomTpl->setVariable($placeholder, json_encode($this->ilLng->txt($lng_variable), JSON_THROW_ON_ERROR));
351  }
352  $this->ilLng->toJSMap([
353  'chat_user_x_is_typing' => $this->ilLng->txt('chat_user_x_is_typing'),
354  'chat_users_are_typing' => $this->ilLng->txt('chat_users_are_typing'),
355  ]);
356 
357  $roomTpl->setVariable('LBL_LAYOUT', $this->ilLng->txt('layout'));
358  $roomTpl->setVariable('LBL_SHOW_SETTINGS', $this->ilLng->txt('show_settings'));
359  $roomTpl->setVariable('LBL_USER_IN_ROOM', $this->ilLng->txt('user_in_room'));
360  $roomTpl->setVariable('LBL_USER_IN_ILIAS', $this->ilLng->txt('user_in_ilias'));
361  $roomTpl->setVariable('LBL_NO_USER', $this->ilLng->txt('msg_no_search_result'));
362  $roomTpl->setVariable('LOADING_IMAGE', ilUtil::getImagePath('media/loader.svg'));
363  }
364 
365  protected function renderRightUsersBlock(ilTemplate $roomTpl): void
366  {
367  $roomTpl->setVariable('LBL_NO_FURTHER_USERS', $this->ilLng->txt('no_further_users'));
368  }
369 
370  private function showNameSelection(ilChatroomUser $chat_user): void
371  {
372  $name_options = $chat_user->getChatNameSuggestions();
373  $formFactory = new ilChatroomFormFactory();
374  $selectionForm = $formFactory->getUserChatNameSelectionForm($name_options);
375 
376  $this->ilCtrl->saveParameter($this->gui, 'sub');
377 
378  $selectionForm->addCommandButton('view-joinWithCustomName', $this->ilLng->txt('enter'));
379  $selectionForm->setFormAction(
380  $this->ilCtrl->getFormAction($this->gui, 'view-joinWithCustomName')
381  );
382 
383  $this->mainTpl->setVariable('ADM_CONTENT', $selectionForm->getHTML());
384  }
385 
392  public function executeDefault(string $requestedMethod): void
393  {
394  $this->redirectIfNoPermission('read');
395 
396  $this->gui->switchToVisibleMode();
397  $this->setupTemplate();
398 
399  $chatSettings = new ilSetting('chatroom');
400  if (!$chatSettings->get('chat_enabled', '0')) {
401  $this->ilCtrl->redirect($this->gui, 'settings-general');
402  }
403 
404  $room = ilChatroom::byObjectId($this->gui->getObject()->getId());
405 
406  if (!$room->getSetting('allow_anonymous') && $this->ilUser->isAnonymous()) {
407  $this->cancelJoin($this->ilLng->txt('chat_anonymous_not_allowed'));
408  return;
409  }
410 
411  $chat_user = new ilChatroomUser($this->ilUser, $room);
412 
413  if ($room->getSetting('allow_custom_usernames')) {
414  if ($room->isSubscribed($chat_user->getUserId())) {
415  $chat_user->setUsername($chat_user->getUsername());
416  $this->showRoom($room, $chat_user);
417  } else {
418  $this->showNameSelection($chat_user);
419  }
420  } else {
421  $chat_user->setUsername($this->ilUser->getLogin());
422  $this->showRoom($room, $chat_user);
423  }
424  }
425 
426  public function logout(): void
427  {
428  $pid = $this->tree->getParentId($this->gui->getRefId());
429  $this->ilCtrl->setParameterByClass(ilRepositoryGUI::class, 'ref_id', $pid);
430  $this->ilCtrl->redirectByClass(ilRepositoryGUI::class);
431  }
432 
433  public function lostConnection(): void
434  {
435  if ($this->http->wrapper()->query()->has('msg')) {
436  match ($this->http->wrapper()->query()->retrieve('msg', $this->refinery->kindlyTo()->string())) {
437  'kicked' => $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('kicked'), true),
438  'banned' => $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('banned'), true),
439  default => $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('lost_connection'), true),
440  };
441  } else {
442  $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('lost_connection'), true);
443  }
444 
445  $this->ilCtrl->redirectByClass(ilInfoScreenGUI::class, 'info');
446  }
447 
448  public function getUserProfileImages(): void
449  {
450  global $DIC;
451 
452  $response = [];
453 
454  $usr_ids = null;
455  if ($this->hasRequestValue('usr_ids')) {
456  $usr_ids = $this->getRequestValue('usr_ids', $this->refinery->kindlyTo()->string());
457  }
458  if (null === $usr_ids || '' === $usr_ids) {
459  $this->sendResponse($response);
460  }
461 
462  $this->ilLng->loadLanguageModule('user');
463 
465 
466  $user_ids = array_filter(array_map('intval', array_map('trim', explode(',', (string) $usr_ids))));
467 
468  $room = ilChatroom::byObjectId($this->gui->getObject()->getId());
469  $chatRoomUserDetails = ilChatroomUser::getUserInformation($user_ids, $room->getRoomId());
470  $chatRoomUserDetailsByUsrId = array_combine(
471  array_map(
472  static function (stdClass $userData): int {
473  return (int) $userData->id;
474  },
475  $chatRoomUserDetails
476  ),
477  $chatRoomUserDetails
478  );
479 
480  $public_data = ilUserUtil::getNamePresentation($user_ids, true, false, '', false, true, false, true);
481  $public_names = ilUserUtil::getNamePresentation($user_ids, false, false, '', false, true, false, false);
482 
483  foreach ($user_ids as $usr_id) {
484  if (!array_key_exists($usr_id, $chatRoomUserDetailsByUsrId)) {
485  continue;
486  }
487 
488  if ($room->getSetting('allow_custom_usernames')) {
490  $avatar = $DIC["user.avatar.factory"]->avatar('xsmall');
491  $avatar->setUsrId(ANONYMOUS_USER_ID);
492  $avatar->setName(ilStr::subStr($chatRoomUserDetailsByUsrId[$usr_id]->login, 0, 2));
493 
494  $public_name = $chatRoomUserDetailsByUsrId[$usr_id]->login;
495  $public_image = $avatar->getUrl();
496  } else {
497  $public_image = $public_data[$usr_id]['img'] ?? '';
498  $public_name = '';
499  if (isset($public_names[$usr_id])) {
500  $public_name = $public_names[$usr_id];
501  if (isset($public_data[$usr_id]['login']) && 'unknown' === $public_name) {
502  $public_name = $public_data[$usr_id]['login'];
503  }
504  }
505  }
506 
507  $response[$usr_id] = [
508  'public_name' => $public_name,
509  'profile_image' => $public_image,
510  ];
511  }
512 
513  $this->sendResponse($response);
514  }
515 }
static checkUserPermissions($permissions, int $ref_id, bool $send_info=true)
Checks user permissions by given array and ref_id.
getSetting(string $name)
array $settings
Setting values (LTI parameters, custom parameters and local parameters).
Definition: System.php:200
getUserId()
Returns Ilias User ID.
$scope
Definition: ltiregstart.php:53
const ANONYMOUS_USER_ID
Definition: constants.php:27
renderLanguageVariables(ilTemplate $roomTpl)
panel(string $title, $body)
chatFunctions(bool $showAutoMessages)
redirectIfNoPermission($permission)
Checks for requested permissions and redirects if the permission check failed.
static getImagePath(string $img, string $module_path="", string $mode="output", bool $offline=false)
get image path (for images located in a template directory)
Class ilChatroomViewGUI.
static initJS(ilGlobalTemplateInterface $a_main_tpl=null)
getRequestValue(string $key, Transformation $trafo, $default=null)
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
getLastMessages(int $number, ilChatroomUser $chatuser)
$response
Definition: xapitoken.php:93
renderSendMessageBox(ilTemplate $roomTpl)
static subStr(string $a_str, int $a_start, ?int $a_length=null)
Definition: class.ilStr.php:24
getConnectedUsers(bool $only_data=true)
static getUserInformation(array $usrIds, ?int $roomId=null)
static setTokenMaxLifetimeInSeconds(int $token_max_lifetime_in_seconds)
global $DIC
Definition: feed.php:28
$messages
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
Definition: xapiexit.php:22
cancelJoin(string $message)
Calls ilUtil::sendFailure method using given $message as parameter.
static http()
Fetches the global http state from ILIAS.
$ref_id
Definition: ltiauth.php:67
setVariable($variable, $value='')
Sets a variable value.
Definition: IT.php:546
static getNamePresentation( $a_user_id, bool $a_user_image=false, bool $a_profile_link=false, string $a_profile_back_link='', bool $a_force_first_lastname=false, bool $a_omit_login=false, bool $a_sortable=true, bool $a_return_data_array=false, $a_ctrl_path='ilpublicuserprofilegui')
Default behaviour is:
Class ilChatroomGUIHandler.
setupTemplate()
Adds CSS and JavaScript files that should be included in the header.
isSubscribed(int $chat_userid)
isUserBanned(int $user_id)
showRoom(ilChatroom $room, ilChatroomUser $chat_user)
Prepares and displays chatroom and connects user to it.
connectUser(ilChatroomUser $user)
Class ilChatroom.
getChatNameSuggestions()
Returns an array of chat-name suggestions.
executeDefault(string $requestedMethod)
Chatroom and Chatuser get prepared before $this->showRoom method is called.
sendResponse($response, bool $isJson=false)
Sends a json encoded response and exits the php process.
Class ilChatroomUser.
static byObjectId(int $object_id)
showNameSelection(ilChatroomUser $chat_user)
$id
plugin.php for ilComponentBuildPluginInfoObjectiveTest::testAddPlugins
Definition: plugin.php:23
static _writePref(int $a_usr_id, string $a_keyword, string $a_value)
$message
Definition: xapiexit.php:32
getUsername()
Returns username from Object or SESSION.
renderRightUsersBlock(ilTemplate $roomTpl)
checkbox(Component $component)