ILIAS  trunk Revision v11.0_alpha-2638-g80c1d007f79
class.ilOnScreenChatGUI.php
Go to the documentation of this file.
1 <?php
2 
19 declare(strict_types=1);
20 
26 
34 {
35  protected static bool $frontend_initialized = false;
36 
37  private readonly ILIAS\DI\Container $dic;
38  private readonly ILIAS\HTTP\Services $http;
39  private readonly ilCtrlInterface $ctrl;
40  private readonly ilObjUser $actor;
41 
42  public function __construct()
43  {
44  global $DIC;
45 
46  $this->dic = $DIC;
47  $this->http = $DIC->http();
48  $this->ctrl = $DIC->ctrl();
49  $this->actor = $DIC->user();
50  }
51 
52  private function getResponseWithText(string $body): ResponseInterface
53  {
54  return $this->dic->http()->response()->withBody(Streams::ofString($body));
55  }
56 
57  protected static function isOnScreenChatAccessible(ilSetting $chatSettings): bool
58  {
59  global $DIC;
60 
61  return (
62  $chatSettings->get('chat_enabled', '0') &&
63  $chatSettings->get('enable_osc', '0') &&
64  $DIC->user() && !$DIC->user()->isAnonymous()
65  );
66  }
67 
68  public function executeCommand(): void
69  {
70  $cmd = $this->ctrl->getCmd();
71  switch ($cmd) {
72  case 'getUserProfileData':
73  $response = $this->getUserProfileData();
74  break;
75 
76  case 'verifyLogin':
77  $response = $this->verifyLogin();
78  break;
79 
80  case 'getRenderedConversationItems':
82  $this->dic,
83  new Conversation($this->dic->database(), $this->dic->user()),
84  new Subscriber($this->dic->database(), $this->dic->user())
85  );
86 
87  $conversationIds = (string) ($this->dic->http()->request()->getQueryParams()['ids'] ?? '');
88  $noAggregates = ($this->dic->http()->request()->getQueryParams()['no_aggregates'] ?? '');
89 
91  $this->dic->ui()->renderer()->renderAsync($provider->getAsyncItem(
92  $conversationIds,
93  $noAggregates !== 'true'
94  ))
95  );
96  break;
97 
98  case 'inviteModal':
99  $this->dic->language()->loadLanguageModule('chatroom');
100  $txt = $this->dic->language()->txt(...);
101  $modal = $this->dic->ui()->factory()->modal()->roundtrip($txt('chat_osc_invite_to_conversation'), $this->dic->ui()->factory()->legacy()->content($txt('chat_osc_search_modal_info')), [
102  $this->dic->ui()->factory()->input()->field()->text($txt('chat_osc_user')),
103  ])->withSubmitLabel($txt('confirm'));
104  $response = $this->renderAsyncModal('inviteModal', $modal);
105  break;
106 
107  case 'confirmRemove':
108  $this->dic->language()->loadLanguageModule('chatroom');
109  $txt = $this->dic->language()->txt(...);
110  $modal = $this->dic->ui()->factory()->modal()->interruptive(
111  $txt('chat_osc_leave_grp_conv'),
112  $txt('chat_osc_sure_to_leave_grp_conv'),
113  ''
114  )->withActionButtonLabel($txt('confirm'));
115  $response = $this->renderAsyncModal('confirmRemove', $modal);
116  break;
117 
118  case 'getUserlist':
119  default:
120  $response = $this->getUserList();
121  }
122 
123  if ($this->ctrl->isAsynch()) {
124  $this->http->saveResponse($response);
125  $this->http->sendResponse();
126  $this->http->close();
127  }
128  }
129 
130  private function verifyLogin(): ResponseInterface
131  {
133 
134  return $this->getResponseWithText(json_encode([
135  'loggedIn' => $this->actor->getId() && !$this->actor->isAnonymous()
136  ], JSON_THROW_ON_ERROR));
137  }
138 
139  private function getUserList(): ResponseInterface
140  {
141  if (!$this->actor->getId() || $this->actor->isAnonymous()) {
142  return $this->getResponseWithText(json_encode([], JSON_THROW_ON_ERROR));
143  }
144 
146  $auto->setUser($this->actor);
148  if (isset($this->http->request()->getQueryParams()['fetchall'])) {
149  $auto->setLimit(ilUserAutoComplete::MAX_ENTRIES);
150  }
151  $auto->setMoreLinkAvailable(true);
152  $auto->setSearchFields(['firstname', 'lastname']);
153  $auto->setResultField('login');
154  $auto->enableFieldSearchableCheck(true);
155 
156  return $this->getResponseWithText($auto->getList($this->http->request()->getQueryParams()['term'] ?? ''));
157  }
158 
159  private function getUserProfileData(): ResponseInterface
160  {
161  if (!$this->actor->getId() || $this->actor->isAnonymous()) {
162  return $this->getResponseWithText(json_encode([], JSON_THROW_ON_ERROR));
163  }
164 
165  $usrIds = (string) ($this->http->request()->getQueryParams()['usr_ids'] ?? '');
166  if ($usrIds === '') {
167  return $this->getResponseWithText(json_encode([], JSON_THROW_ON_ERROR));
168  }
169 
170  $this->dic->language()->loadLanguageModule('user');
171  $subscriberRepo = new Subscriber($this->dic->database(), $this->dic->user());
172  $data = $subscriberRepo->getDataByUserIds(explode(',', $usrIds));
173 
175 
176  return $this->getResponseWithText(json_encode($data, JSON_THROW_ON_ERROR));
177  }
178 
179  public static function initializeFrontend(ilGlobalTemplateInterface $page): void
180  {
181  global $DIC;
182 
183  if (!self::$frontend_initialized) {
184  $clientSettings = new ilSetting('chatroom');
185 
186  if (!self::isOnScreenChatAccessible($clientSettings)) {
187  self::$frontend_initialized = true;
188  return;
189  }
190 
192 
193  $DIC->language()->loadLanguageModule('chatroom');
194  $DIC->language()->loadLanguageModule('user');
195 
196  $renderer = $DIC->ui()->renderer();
197  $factory = $DIC->ui()->factory();
198 
199  $chatWindowTemplate = new ilTemplate('tpl.chat-window.html', false, false, 'components/ILIAS/OnScreenChat');
200  $chatWindowTemplate->setVariable('SUBMIT_ACTION', $renderer->render(
201  $factory->button()->standard($DIC->language()->txt('chat_osc_send'), 'onscreenchat-submit')
202  ));
203  $chatWindowTemplate->setVariable('ADD_ACTION', $renderer->render(
204  $factory->symbol()->glyph()->add('addUser')
205  ));
206  $chatWindowTemplate->setVariable('MINIMIZE_ACTION', $renderer->render(
207  $factory->button()->minimize()
208  ));
209  $chatWindowTemplate->setVariable('CONVERSATION_ICON', ilUtil::img(ilUtil::getImagePath('standard/icon_pcht.svg')));
210 
211  $subscriberRepo = new Subscriber($DIC->database(), $DIC->user());
212 
213  $guiConfig = [
214  'chatWindowTemplate' => $chatWindowTemplate->get(),
215  'messageTemplate' => (new ilTemplate(
216  'tpl.chat-message.html',
217  false,
218  false,
219  'components/ILIAS/OnScreenChat'
220  ))->get(),
221  'nothingFoundTemplate' => $DIC->ui()->renderer()->render($DIC->ui()->factory()->messageBox()->info($DIC->language()->txt('chat_osc_no_usr_found'))),
222  'userId' => $DIC->user()->getId(),
223  'username' => $DIC->user()->getLogin(),
224  'modalURLTemplate' => ILIAS_HTTP_PATH . '/' . $DIC->ctrl()->getLinkTargetByClass(
225  ilOnScreenChatGUI::class,
226  'postMessage',
227  null,
228  true
229  ),
230  'userListURL' => ILIAS_HTTP_PATH . '/' . $DIC->ctrl()->getLinkTargetByClass(
231  'ilonscreenchatgui',
232  'getUserList',
233  '',
234  true,
235  false
236  ),
237  'userProfileDataURL' => $DIC->ctrl()->getLinkTargetByClass(
238  'ilonscreenchatgui',
239  'getUserProfileData',
240  '',
241  true,
242  false
243  ),
244  'verifyLoginURL' => $DIC->ctrl()->getLinkTargetByClass(
245  'ilonscreenchatgui',
246  'verifyLogin',
247  '',
248  true,
249  false
250  ),
251  'renderConversationItemsURL' => $DIC->ctrl()->getLinkTargetByClass(
252  'ilonscreenchatgui',
253  'getRenderedConversationItems',
254  '',
255  true,
256  false
257  ),
258  'loaderImg' => ilUtil::getImagePath('media/loader.svg'),
259  'locale' => $DIC->language()->getLangKey(),
260  'initialUserData' => $subscriberRepo->getInitialUserProfileData(),
261  'enabledBrowserNotifications' => (
262  $clientSettings->get('enable_browser_notifications', '0') &&
263  ilUtil::yn2tf((string) $DIC->user()->getPref('chat_osc_browser_notifications'))
264  ),
265  'broadcast_typing' => (
266  ilUtil::yn2tf((string) $DIC->user()->getPref('chat_broadcast_typing'))
267  ),
268  'notificationIconPath' => ilUtil::getImagePath('standard/icon_chta.png'),
269  ];
270 
271  $chatConfig = [
272  'url' => $settings->generateClientUrl() . '/' . $settings->getInstance() . '-im',
273  'subDirectory' => $settings->getSubDirectory() . '/socket.io',
274  'userId' => $DIC->user()->getId(),
275  'username' => $DIC->user()->getLogin(),
276  ];
277 
278  $DIC->language()->toJS([
279  'chat_osc_no_usr_found',
280  'chat_osc_write_a_msg',
281  'autocomplete_more',
282  'chat_osc_minimize',
283  'chat_osc_invite_to_conversation',
284  'chat_osc_user',
285  'chat_osc_add_user',
286  'chat_osc_subs_rej_msgs',
287  'chat_osc_subs_rej_msgs_p',
288  'chat_osc_self_rej_msgs',
289  'chat_osc_search_modal_info',
290  'chat_osc_head_grp_x_persons',
291  'osc_noti_title',
292  'chat_osc_conversations',
293  'chat_osc_sure_to_leave_grp_conv',
294  'chat_osc_user_left_grp_conv',
295  'confirm',
296  'cancel',
297  'chat_osc_leave_grp_conv',
298  'chat_osc_no_conv',
299  'chat_osc_nc_conv_x_p',
300  'chat_osc_nc_conv_x_s',
301  'chat_osc_nc_no_conv',
302  'chat_user_x_is_typing',
303  'chat_users_are_typing',
304  'today',
305  'yesterday',
306  ], $page);
307 
311 
312  $page->addJavaScript('assets/js/modal.min.js');
313  $page->addJavaScript('assets/js/socket.io.min.js');
314  $page->addJavaScript('assets/js/Chatroom.min.js');
315  $page->addJavaScript('assets/js/moment-with-locales.min.js');
316  $page->addJavaScript('assets/js/BrowserNotifications.min.js');
317  $page->addJavaScript('assets/js/onscreenchat-notifications.js');
318  $page->addJavaScript('assets/js/moment.js');
319  $page->addJavaScript('assets/js/chat.js');
320  $page->addJavaScript('assets/js/onscreenchat.js');
321  $page->addOnLoadCode("il.Chat.setConfig(" . json_encode($chatConfig, JSON_THROW_ON_ERROR) . ");");
322  $page->addOnLoadCode("il.OnScreenChat.setConfig(" . json_encode($guiConfig, JSON_THROW_ON_ERROR) . ");");
323  $page->addOnLoadCode("il.OnScreenChat.init();");
324  $page->addOnLoadCode('il.OnScreenChatNotifications.init(' . json_encode([
325  'conversationIdleTimeThreshold' => max(
326  1,
327  (int) $clientSettings->get('conversation_idle_state_in_minutes', '1')
328  ),
329  'logLevel' => $DIC['ilLoggerFactory']->getSettings()->getLevelByComponent('osch'),
330  ], JSON_THROW_ON_ERROR) . ');');
331 
332  self::$frontend_initialized = true;
333  }
334  }
335 
336  private function renderAsyncModal(string $bus_name, $modal)
337  {
338  return $this->getResponseWithText($this->dic->ui()->renderer()->renderAsync($modal->withAdditionalOnLoadCode(fn($id) => (
339  'il.OnScreenChat.bus.send(' . json_encode($bus_name, JSON_THROW_ON_ERROR) . ', ' . json_encode([(string) $modal->getShowSignal(), (string) $modal->getCloseSignal()], JSON_THROW_ON_ERROR) . ');'
340  ))));
341  }
342 }
static enableWebAccessWithoutSession(bool $enable_web_access_without_session)
static initjQueryUI(?ilGlobalTemplateInterface $a_tpl=null)
inits and adds the jQuery-UI JS-File to the global template (see included_components.txt for included components)
$renderer
get(string $a_keyword, ?string $a_default_value=null)
get setting
Class ilOnScreenChatUserUserAutoComplete.
static initLinkify(?ilGlobalTemplateInterface $a_tpl=null)
addOnLoadCode(string $a_code, int $a_batch=2)
Add on load code.
$response
Definition: xapitoken.php:93
static initializeFrontend(ilGlobalTemplateInterface $page)
static img(string $a_src, ?string $a_alt=null, $a_width="", $a_height="", $a_border=0, $a_id="", $a_class="")
Build img tag.
while($session_entry=$r->fetchRow(ilDBConstants::FETCHMODE_ASSOC)) return null
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
$provider
Definition: ltitoken.php:80
readonly ILIAS HTTP Services $http
Class ilOnScreenChatGUI.
static http()
Fetches the global http state from ILIAS.
static isOnScreenChatAccessible(ilSetting $chatSettings)
renderAsyncModal(string $bus_name, $modal)
static initjQuery(?ilGlobalTemplateInterface $a_tpl=null)
inits and adds the jQuery JS-File to the global or a passed template
global $DIC
Definition: shib_login.php:26
static getImagePath(string $image_name, string $module_path="", string $mode="output", bool $offline=false)
get image path (for images located in a template directory)
readonly ilCtrlInterface $ctrl
$txt
Definition: error.php:31
readonly ILIAS DI Container $dic
readonly ilObjUser $actor
$id
plugin.php for ilComponentBuildPluginInfoObjectiveTest::testAddPlugins
Definition: plugin.php:23
addJavaScript(string $a_js_file, bool $a_add_version_parameter=true, int $a_batch=2)
Add a javascript file that should be included in the header.
static yn2tf(string $a_yn)
getResponseWithText(string $body)