ILIAS  trunk Revision v12.0_alpha-377-g3641b37b9db
class.ilChatroomViewGUI.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
26
34{
35 public function joinWithCustomName(): void
36 {
37 $this->redirectIfNoPermission('read');
38
39 $this->gui->switchToVisibleMode();
40 $this->setupTemplate();
41 $room = ilChatroom::byObjectId($this->gui->getObject()->getId());
42 $chat_user = new ilChatroomUser($this->ilUser, $room);
43 $failure = true;
44 $username = '';
45 $custom_username = false;
46
47 if ($this->hasRequestValue('custom_username_radio')) {
48 if (
49 $this->hasRequestValue('custom_username_text') &&
50 $this->getRequestValue('custom_username_radio', $this->refinery->kindlyTo()->string()) === 'custom_username'
51 ) {
52 $custom_username = true;
53 $username = $this->getRequestValue('custom_username_text', $this->refinery->kindlyTo()->string());
54 $failure = false;
55 } elseif (
56 method_exists(
57 $chat_user,
58 'build' . $this->getRequestValue('custom_username_radio', $this->refinery->kindlyTo()->string())
59 )
60 ) {
61 $username = $chat_user->{
62 'build' . $this->getRequestValue('custom_username_radio', $this->refinery->kindlyTo()->string())
63 }();
64 $failure = false;
65 }
66 }
67
68 if (!$failure && trim($username) !== '') {
69 if (!$room->isSubscribed($chat_user->getUserId())) {
70 $chat_user->setUsername($chat_user->buildUniqueUsername($username));
71 $chat_user->setProfilePictureVisible(!$custom_username);
72 }
73
74 $this->showRoom($room, $chat_user);
75 } else {
76 $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('no_username_given'));
77 $this->showNameSelection($chat_user);
78 }
79 }
80
84 private function setupTemplate(): void
85 {
86 ilLinkifyUtil::initLinkify($this->mainTpl);
87 $this->mainTpl->addJavaScript('assets/js/socket.io.min.js');
88 $this->mainTpl->addJavaScript('assets/js/Chatroom.min.js');
89
90 $this->mainTpl->setPermanentLink($this->gui->getObject()->getType(), $this->gui->getObject()->getRefId());
91 }
92
96 private function showRoom(ilChatroom $room, ilChatroomUser $chat_user): void
97 {
98 $this->redirectIfNoPermission('read');
99
100 $user_id = $chat_user->getUserId();
101
102 $ref_id = $this->getRequestValue('ref_id', $this->refinery->kindlyTo()->int());
103 $this->navigationHistory->addItem(
104 $ref_id,
105 $this->ilCtrl->getLinkTargetByClass(ilRepositoryGUI::class, 'view'),
106 'chtr'
107 );
108
109 if ($room->isUserBanned($user_id)) {
110 $this->cancelJoin($this->ilLng->txt('banned'));
111 return;
112 }
113
114 $scope = $room->getRoomId();
115 $connector = $this->gui->getConnector();
116 $response = $connector->connect($scope, $user_id);
117
118 if (!$response) {
119 $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('unable_to_connect'), true);
120 $this->ilCtrl->redirectByClass(ilInfoScreenGUI::class, 'showSummary');
121 }
122
123 if (!$room->isSubscribed($chat_user->getUserId())) {
124 $room->connectUser($chat_user);
125 }
126
127 $response = $connector->sendEnterPrivateRoom($scope, $user_id);
128 if (!$response) {
129 $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('unable_to_connect'), true);
130 $this->ilCtrl->redirectByClass(ilInfoScreenGUI::class, 'showSummary');
131 }
132
133 $messages = $room->getSetting('display_past_msgs') ? array_reverse(array_filter(
134 $room->getLastMessages($room->getSetting('display_past_msgs'), $chat_user),
135 fn($entry) => $entry->type !== 'notice'
136 )) : [];
137
138 $is_moderator = ilChatroom::checkUserPermissions('moderate', $ref_id, false);
139 $show_auto_messages = !$this->ilUser->getPref('chat_hide_automsg_' . $room->getRoomId());
140
141 $build = $this->buildChat($room, $connector->getSettings());
142
143 $room_tpl = $build->template(false, $build->initialData(
144 $room->getConnectedUsers(),
145 $show_auto_messages,
146 $this->ilCtrl->getLinkTarget($this->gui, 'view-lostConnection', '', false),
147 [
148 'moderator' => $is_moderator,
149 'id' => $chat_user->getUserId(),
150 'login' => $chat_user->getUsername(),
151 'broadcast_typing' => $chat_user->enabledBroadcastTyping(),
152 'profile_picture_visible' => $chat_user->isProfilePictureVisible(),
153 ],
154 $messages
155 ), $this->panel($this->ilLng->txt('write_message'), $this->sendMessageForm()), $this->panel($this->ilLng->txt('messages'), $this->legacy('<div id="chat_messages"></div>')));
156
157 $this->mainTpl->setContent($room_tpl->get());
158 $this->mainTpl->setRightContent($this->userList() . $this->chatFunctions($show_auto_messages, $is_moderator));
159 }
160
161 public function readOnlyChatWindow(ilChatroom $room, array $messages): ilTemplate
162 {
163 $build = $this->buildChat($room, $this->gui->getConnector()->getSettings());
164
165 return $build->template(true, $build->initialData([], true, null, [
166 'moderator' => false,
167 'id' => -1,
168 'login' => null,
169 'broadcast_typing' => false,
170 ], $messages), $this->panel($this->ilLng->txt('messages'), $this->legacy('<div id="chat_messages"></div>')), '');
171 }
172
173 private function sendMessageForm(): Component
174 {
175 $template = new ilTemplate('tpl.chatroom_send_message_form.html', true, true, 'components/ILIAS/Chatroom');
176 $this->renderSendMessageBox($template);
177
178 return $this->legacy($template->get());
179 }
180
181 private function userList(): string
182 {
183 $roomRightTpl = new ilTemplate('tpl.chatroom_right.html', true, true, 'components/ILIAS/Chatroom');
184 $this->renderRightUsersBlock($roomRightTpl);
185
186 return $this->panel($this->ilLng->txt('users'), $this->legacy($roomRightTpl->get()));
187 }
188
189 private function chatFunctions(bool $show_auto_messages, bool $is_moderator): string
190 {
191 $txt = $this->ilLng->txt(...);
192 $js_escape = json_encode(...);
193 $format = fn($format, ...$args) => sprintf($format, ...array_map($js_escape, $args));
194 $register = fn($name, $c) => $c->withOnLoadCode(fn($id) => $format(
195 'il.Chatroom.bus.send(%s, document.getElementById(%s));',
196 $name,
197 $id
198 ));
199
200 $b = $this->uiFactory->button();
201 $toggle = fn($label, $enabled) => $b->toggle($label, '#', '#', $enabled)->withAriaLabel($label);
202
203 $bind = fn($key, $m) => $m->withAdditionalOnLoadCode(fn(string $id) => $format(
204 '$(() => il.Chatroom.bus.send(%s, {
205 node: document.getElementById(%s),
206 showModal: () => $(document).trigger(%s, {}),
207 closeModal: () => $(document).trigger(%s, {})
208 }));',
209 $key,
210 $id,
211 $m->getShowSignal()->getId(),
212 $m->getCloseSignal()->getId()
213 ));
214
215 $interrupt = fn($key, $label, $text, $button = null) => $bind($key, $this->uiFactory->modal()->interruptive(
216 $label,
217 $text,
218 ''
219 ))->withActionButtonLabel($button ?? $label);
220
221 $auto_scroll = $register('auto-scroll-toggle', $toggle($txt('auto_scroll'), true));
222 $messages = $register('system-messages-toggle', $toggle($txt('chat_show_auto_messages'), $show_auto_messages));
223
224 $invite = $bind('invite-modal', $this->uiFactory->modal()->roundtrip($txt('chat_invite'), $this->legacy($txt('invite_to_private_room')), [
225 $this->uiFactory->input()->field()->text($txt('chat_invite')),
226 ])->withSubmitLabel($txt('chat_invite')));
227
228 $buttons = [];
229 $buttons[] = $register('invite-button', $b->shy($txt('invite_to_private_room'), ''));
230 if ($is_moderator) {
231 $buttons[] = $register('clear-history-button', $b->shy($txt('clear_room_history'), ''));
232 }
233
234 return $this->panel($txt('chat_functions'), [
235 $this->legacy('<div id="chat_function_list">'),
236 ...$buttons,
237 $invite,
238 $interrupt('kick-modal', $txt('chat_kick'), $txt('kick_question')),
239 $interrupt('ban-modal', $txt('chat_ban'), $txt('ban_question')),
240 $interrupt('clear-history-modal', $txt('clear_room_history'), $txt('clear_room_history_question')),
241 $this->legacy('</div>'),
242 $this->legacy(sprintf('<div>%s%s</div>', $this->checkbox($auto_scroll), $this->checkbox($messages))),
243 ]);
244 }
245
246 private function checkbox(Component $component): string
247 {
248 return sprintf('<div class="chatroom-centered-checkboxes">%s</div>', $this->uiRenderer->render($component));
249 }
250
251 private function legacy(string $html): Component
252 {
253 return $this->uiFactory->legacy()->content($html);
254 }
255
259 private function panel(string $title, $body): string
260 {
261 if (is_array($body)) {
262 $body = $this->uiFactory->legacy()->content(join('', array_map($this->uiRenderer->render(...), $body)));
263 }
264 $panel = $this->uiFactory->panel()->secondary()->legacy($title, $body);
265
266 return $this->uiRenderer->render($panel);
267 }
268
269 public function toggleAutoMessageDisplayState(): void
270 {
271 $this->redirectIfNoPermission('read');
272
273 $room = ilChatroom::byObjectId($this->gui->getObject()->getId());
274
275 $state = 0;
276 if ($this->http->wrapper()->post()->has('state')) {
277 $state = $this->http->wrapper()->post()->retrieve('state', $this->refinery->kindlyTo()->int());
278 }
279
280 $this->ilUser->writePref(
281 'chat_hide_automsg_' . $room->getRoomId(),
282 (string) ((int) (!(bool) $state))
283 );
284
285 $this->http->saveResponse(
286 $this->http->response()
287 ->withHeader(ResponseHeader::CONTENT_TYPE, 'application/json')
288 ->withBody(Streams::ofString(json_encode(['success' => true], JSON_THROW_ON_ERROR)))
289 );
290 $this->http->sendResponse();
291 $this->http->close();
292 }
293
297 private function cancelJoin(string $message): void
298 {
299 $this->mainTpl->setOnScreenMessage('failure', $message);
300 }
301
302 protected function renderSendMessageBox(ilTemplate $roomTpl): void
303 {
304 $roomTpl->setVariable('PLACEHOLDER', $this->ilLng->txt('chat_osc_write_a_msg'));
305 $roomTpl->setVariable('LBL_SEND', $this->ilLng->txt('send'));
306 }
307
308 protected function renderRightUsersBlock(ilTemplate $roomTpl): void
309 {
310 $roomTpl->setVariable('LBL_NO_FURTHER_USERS', $this->ilLng->txt('no_further_users'));
311 }
312
313 private function showNameSelection(ilChatroomUser $chat_user): void
314 {
315 $name_options = $chat_user->getChatNameSuggestions();
316 $formFactory = new ilChatroomFormFactory();
317 $selectionForm = $formFactory->getUserChatNameSelectionForm($name_options);
318
319 $this->ilCtrl->saveParameter($this->gui, 'sub');
320
321 $selectionForm->addCommandButton('view-joinWithCustomName', $this->ilLng->txt('enter'));
322 $selectionForm->setFormAction(
323 $this->ilCtrl->getFormAction($this->gui, 'view-joinWithCustomName')
324 );
325
326 $this->mainTpl->setVariable('ADM_CONTENT', $selectionForm->getHTML());
327 }
328
335 public function executeDefault(string $requestedMethod): void
336 {
337 $this->redirectIfNoPermission('read');
338
339 $this->gui->switchToVisibleMode();
340 $this->setupTemplate();
341
342 $chatSettings = new ilSetting('chatroom');
343 if (!$chatSettings->get('chat_enabled', '0')) {
344 $this->ilCtrl->redirect($this->gui, 'settings-general');
345 }
346
347 $room = ilChatroom::byObjectId($this->gui->getObject()->getId());
348
349 if (!$room->getSetting('allow_anonymous') && $this->ilUser->isAnonymous()) {
350 $this->cancelJoin($this->ilLng->txt('chat_anonymous_not_allowed'));
351 return;
352 }
353
354 $chat_user = new ilChatroomUser($this->ilUser, $room);
355
356 if ($room->getSetting('allow_custom_usernames')) {
357 if ($room->isSubscribed($chat_user->getUserId())) {
358 $chat_user->setUsername($chat_user->getUsername());
359 $this->showRoom($room, $chat_user);
360 } else {
361 $this->showNameSelection($chat_user);
362 }
363 } else {
364 $chat_user->setUsername($this->ilUser->getPublicName());
365 $chat_user->setProfilePictureVisible(true);
366 $this->showRoom($room, $chat_user);
367 }
368 }
369
370 public function logout(): void
371 {
372 $pid = $this->tree->getParentId($this->gui->getRefId());
373 $this->ilCtrl->setParameterByClass(ilRepositoryGUI::class, 'ref_id', $pid);
374 $this->ilCtrl->redirectByClass(ilRepositoryGUI::class);
375 }
376
377 public function lostConnection(): void
378 {
379 if ($this->http->wrapper()->query()->has('msg')) {
380 match ($this->http->wrapper()->query()->retrieve('msg', $this->refinery->kindlyTo()->string())) {
381 'kicked' => $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('kicked'), true),
382 'banned' => $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('banned'), true),
383 default => $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('lost_connection'), true),
384 };
385 } else {
386 $this->mainTpl->setOnScreenMessage('failure', $this->ilLng->txt('lost_connection'), true);
387 }
388
389 $this->ilCtrl->redirectByClass(ilInfoScreenGUI::class, 'showSummary');
390 }
391
392 public function getUserProfileImages(): void
393 {
394 global $DIC;
395
396 $response = [];
397
398 $request = json_decode($this->http->request()->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
399
401
402 $users = $this->refinery->kindlyTo()->listOf($this->refinery->byTrying([
403 $this->refinery->kindlyTo()->recordOf([
404 'id' => $this->refinery->kindlyTo()->int(),
405 'username' => $this->refinery->kindlyTo()->string(),
406 'profile_picture_visible' => $this->refinery->kindlyTo()->bool(),
407 ]),
408 $this->refinery->kindlyTo()->recordOf([
409 'id' => $this->refinery->kindlyTo()->int(),
410 'username' => $this->refinery->kindlyTo()->string(),
411 ]),
412 ]))->transform($request['profiles'] ?? []);
413
414 $user_ids = array_column($users, 'id');
415
416 $public_data = ilUserUtil::getNamePresentation($user_ids, true, false, '', false, true, false, true);
417
418 foreach ($users as $user) {
419 if ($user['profile_picture_visible'] ?? false) {
420 $public_image = $public_data[$user['id']]['img'] ?? '';
421 } else {
423 $avatar = $DIC["user.avatar.factory"]->avatar('xsmall');
424 $avatar->setUsrId(ANONYMOUS_USER_ID);
425 $avatar->setName(ilStr::subStr($user['username'], 0, 2));
426 $public_image = $avatar->getUrl();
427 }
428
429 $response[json_encode($user, JSON_THROW_ON_ERROR)] = $public_image;
430 }
431
432 $this->sendJSONResponse($response);
433 }
434
435 public function userEntry(): void
436 {
437 global $DIC;
438
439 $kindly = $this->refinery->kindlyTo();
440 $s = $kindly->string();
441 $int = $kindly->int();
442 $get = $this->http->wrapper()->query()->retrieve(...);
443 $get_or = fn($k, $t, $d = null) => $get($k, $this->refinery->byTrying([$t, $this->refinery->always($d)]));
444
445 $ref_id = $get('ref_id', $int);
446 $user_id = $get('user_id', $int);
447 $username = $get('username', $s);
448 $actions = $get_or('actions', $kindly->dictOf($s), []);
449
450 $avatar = $DIC["user.avatar.factory"]->avatar('xsmall');
451 $avatar->setUsrId(ANONYMOUS_USER_ID);
452 $avatar->setName(ilStr::subStr($username, 0, 2));
453 $public_image = $avatar->getUrl();
454 $item = $this->uiFactory->item()->standard($username)->withLeadImage($this->uiFactory->image()->standard(
455 $public_image,
456 'Profile image of ' . $username
457 ));
458
460 $item = $item->withProperties([
461 $this->ilLng->txt('role') => $this->ilLng->txt('il_chat_moderator'),
462 ]);
463 }
464 $item = $item->withActions($this->uiFactory->dropdown()->standard($this->buildUserActions($user_id, $actions)));
465
466
467 $this->sendResponse($this->uiRenderer->renderAsync($item), 'text/html');
468 }
469
474 private function buildUserActions(int $user_id, array $actions): array
475 {
476 $chat_settings = new ilSetting('chatroom');
477 $osc_enabled = $chat_settings->get('chat_enabled') && $chat_settings->get('enable_osc');
478 $translations = [
479 'kick' => $this->ilLng->txt('chat_kick'),
480 'ban' => $this->ilLng->txt('chat_ban'),
481 ];
482
483 if ($osc_enabled && ilObjUser::_lookupPref($user_id, 'chat_osc_accept_msg') === 'y') {
484 $translations['chat'] = $this->ilLng->txt('start_private_chat');
485 }
486
487 $buttons = [];
488 foreach ($actions as $key => $bus_id) {
489 $label = $translations[$key] ?? false;
490 if ($label) {
491 $buttons[] = $this->uiFactory->button()->shy($label, '')->withAdditionalOnLoadCode(fn(string $id): string => (
492 'il.Chatroom.bus.send(' . json_encode(
493 $bus_id,
494 JSON_THROW_ON_ERROR
495 ) . ', document.getElementById(' . json_encode($id, JSON_THROW_ON_ERROR) . '));'
496 ));
497 }
498 }
499
500 return $buttons;
501 }
502
503 private function buildChat(ilChatroom $room, ilChatroomServerSettings $settings): BuildChat
504 {
505 return new BuildChat($this->ilCtrl, $this->ilLng, $this->gui, $room, $settings, $this->ilUser, $this->uiFactory, $this->uiRenderer);
506 }
507}
$id
plugin.php for ilComponentBuildPluginInfoObjectiveTest::testAddPlugins
Definition: plugin.php:23
setVariable($variable, $value='')
Sets a variable value.
Definition: IT.php:544
Stream factory which enables the user to create streams without the knowledge of the concrete class.
Definition: Streams.php:32
Class ilChatroomGUIHandler.
redirectIfNoPermission($permission)
Checks for requested permissions and redirects if the permission check failed.
getRequestValue(string $key, Transformation $trafo, $default=null)
Class ilChatroomServerSettings.
Class ilChatroomUser.
getChatNameSuggestions()
Returns an array of chat-name suggestions.
getUserId()
Returns Ilias User ID.
getUsername()
Returns username from Object or SESSION.
Class ilChatroomViewGUI.
readOnlyChatWindow(ilChatroom $room, array $messages)
buildChat(ilChatroom $room, ilChatroomServerSettings $settings)
panel(string $title, $body)
renderRightUsersBlock(ilTemplate $roomTpl)
cancelJoin(string $message)
Calls ilUtil::sendFailure method using given $message as parameter.
checkbox(Component $component)
setupTemplate()
Adds CSS and JavaScript files that should be included in the header.
showNameSelection(ilChatroomUser $chat_user)
buildUserActions(int $user_id, array $actions)
executeDefault(string $requestedMethod)
Chatroom and Chatuser get prepared before $this->showRoom method is called.
chatFunctions(bool $show_auto_messages, bool $is_moderator)
showRoom(ilChatroom $room, ilChatroomUser $chat_user)
Prepares and displays chatroom and connects user to it.
renderSendMessageBox(ilTemplate $roomTpl)
Class ilChatroom.
getConnectedUsers(bool $only_data=true)
static checkPermissionsOfUser(int $usr_id, $permissions, int $ref_id)
Checks user permissions in question for a given user id in relation to a given ref_id.
connectUser(ilChatroomUser $user)
static checkUserPermissions($permissions, int $ref_id, bool $send_info=true)
Checks user permissions by given array and ref_id.
getSetting(string $name)
isUserBanned(int $user_id)
isSubscribed(int $chat_userid)
getLastMessages(int $number, ilChatroomUser $chatuser)
static byObjectId(int $object_id)
Class ilCtrl provides processing control methods.
redirectByClass( $a_class, ?string $a_cmd=null, ?string $a_anchor=null, bool $is_async=false)
@inheritDoc
getFormAction(object $a_gui_obj, ?string $a_fallback_cmd=null, ?string $a_anchor=null, bool $is_async=false, bool $has_xml_style=false)
@inheritDoc
saveParameter(object $a_gui_obj, $a_parameter)
@inheritDoc
redirect(object $a_gui_obj, ?string $a_cmd=null, ?string $a_anchor=null, bool $is_async=false)
@inheritDoc
setParameterByClass(string $a_class, string $a_parameter, $a_value)
@inheritDoc
getLinkTargetByClass( $a_class, ?string $a_cmd=null, ?string $a_anchor=null, bool $is_async=false, bool $has_xml_style=false)
@inheritDoc
static initLinkify(?ilGlobalTemplateInterface $a_tpl=null)
static _lookupPref(int $a_usr_id, string $a_keyword)
ILIAS Setting Class.
static subStr(string $a_str, int $a_start, ?int $a_length=null)
Definition: class.ilStr.php:21
special template class to simplify handling of ITX/PEAR
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=null)
Default behaviour is:
static setTokenMaxLifetimeInSeconds(int $token_max_lifetime_in_seconds)
const ANONYMOUS_USER_ID
Definition: constants.php:27
$c
Definition: deliver.php:25
Interface ResponseHeader.
This describes commonalities between standard and primary buttons.
Definition: Button.php:34
A component is the most general form of an entity in the UI.
Definition: Component.php:28
$ref_id
Definition: ltiauth.php:66
$scope
Definition: ltiregstart.php:51
static http()
Fetches the global http state from ILIAS.
global $DIC
Definition: shib_login.php:26
$text
Definition: xapiexit.php:21
$response
Definition: xapitoken.php:90