ILIAS  trunk Revision v12.0_alpha-1227-g7ff6d300864
class.ilBuddySystemGUI.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
24use ILIAS\UI\Factory as UIFactory;
25use ILIAS\UI\Renderer as UIRenderer;
26
33{
34 private const int BS_REQUEST_HTTP_GET = 1;
35 private const int BS_REQUEST_HTTP_POST = 2;
36
37 protected static bool $isFrontendInitialized = false;
38
42 protected ilObjUser $user;
43 protected ilLanguage $lng;
44 protected Services $http;
46 private UIFactory $ui_factory;
47 private UIRenderer $ui_renderer;
48
49 public function __construct()
50 {
51 global $DIC;
52 $this->main_tpl = $DIC->ui()->mainTemplate();
53
54 $this->http = $DIC->http();
55 $this->ctrl = $DIC['ilCtrl'];
56 $this->user = $DIC['ilUser'];
57 $this->lng = $DIC['lng'];
58 $this->ui_factory = $DIC->ui()->factory();
59 $this->ui_renderer = $DIC->ui()->renderer();
60
61 $this->buddyList = ilBuddyList::getInstanceByGlobalUser();
63
64 $this->lng->loadLanguageModule('buddysystem');
65 }
66
67 public static function initializeFrontend(ilGlobalTemplateInterface $page): void
68 {
69 global $DIC;
70
71 if (
72 !self::$isFrontendInitialized &&
73 ilBuddySystem::getInstance()->isEnabled() &&
74 !$DIC->user()->isAnonymous()
75 ) {
76 $DIC->language()->loadLanguageModule('buddysystem');
77
78 $page->addJavaScript('./assets/js/buddy_system.js');
79 $page->addJavaScript('./assets/js/modal.min.js');
80
81 $config = new stdClass();
82 $config->async_get_unlink_modal_confirmation_html = $DIC->ctrl()->getLinkTargetByClass([
83 ilUIPluginRouterGUI::class,
84 self::class
85 ], 'asyncGetUnlinkModalConfirmationHtml', '', true, false);
86
87 $config->http_post_url = $DIC->ctrl()->getFormActionByClass([
88 ilUIPluginRouterGUI::class,
89 self::class
90 ], '', '', true, false);
91 $config->transition_state_cmd = 'transitionAsync';
92 $page->addOnLoadCode('il.BuddySystem.setConfig(' . json_encode($config, JSON_THROW_ON_ERROR) . ');');
93
94 $btn_config = new stdClass();
95 $btn_config->bnt_class = ilBuddySystemLinkButtonType::ROOT_CSS_CLASS;
96
97 $page->addOnLoadCode('il.BuddySystemButton.setConfig(' . json_encode($btn_config, JSON_THROW_ON_ERROR) . ');');
98 $page->addOnLoadCode('il.BuddySystemButton.init();');
99
100 self::$isFrontendInitialized = true;
101 }
102 }
103
105 {
106 $modal_id = null;
107 $confirmation_modal = $this
108 ->ui_factory
109 ->modal()
110 ->interruptive(
111 $this->lng->txt('confirmation'),
112 $this->lng->txt('buddy_confirm_unlink'),
113 ''
114 )
115 ->withActionButtonLabel($this->lng->txt('confirm'))
116 ->withAdditionalOnLoadCode(function ($id) use (&$modal_id) {
117 $modal_id = $id;
118 return '';
119 });
120
121 $this->http->saveResponse(
122 $this->http->response()->withBody(
123 Streams::ofString(
124 json_encode([
125 'html' => $this->ui_renderer->renderAsync($confirmation_modal),
126 'signals' => [
127 'close' => $confirmation_modal->getCloseSignal()->getId()
128 ],
129 'modalId' => $modal_id
130 ], JSON_THROW_ON_ERROR)
131 )
132 )->withHeader(ResponseHeader::CONTENT_TYPE, 'application/json')
133 );
134 $this->http->sendResponse();
135 $this->http->close();
136 }
137
141 public function executeCommand(): void
142 {
143 if ($this->user->isAnonymous()) {
144 throw new RuntimeException('This controller only accepts requests of logged in users');
145 }
146
147 $this->{$this->ctrl->getCmd() . 'Command'}();
148 }
149
150 protected function isRequestParameterGiven(string $key, int $type): bool
151 {
152 switch ($type) {
154 $body = $this->http->request()->getParsedBody();
155 return (isset($body[$key]) && is_string($body[$key]) && $body[$key] !== '');
156
158 default:
159 $query = $this->http->request()->getQueryParams();
160 return (isset($query[$key]) && is_string($query[$key]) && $query[$key] !== '');
161 }
162 }
163
164 private function requestCommand(): void
165 {
166 $this->transitionCommand(
167 'request',
168 'buddy_relation_requested',
169 static function (ilBuddySystemRelation $relation): void {
170 if (
171 $relation->isUnlinked() &&
172 !ilUtil::yn2tf((string) ilObjUser::_lookupPref($relation->getBuddyUsrId(), 'bs_allow_to_contact_me'))
173 ) {
174 throw new ilException('The requested user does not want to get contact requests');
175 }
176 }
177 );
178 }
179
180 private function ignoreCommand(): void
181 {
182 $this->transitionCommand('ignore', 'buddy_request_ignored');
183 }
184
185 private function linkCommand(): void
186 {
187 $this->transitionCommand('link', 'buddy_request_approved');
188 }
189
190 private function transitionCommand(
191 string $cmd,
192 string $positiveFeedbackLanguageId,
193 ?callable $onBeforeExecute = null
194 ): void {
195 if (!$this->isRequestParameterGiven('user_id', self::BS_REQUEST_HTTP_GET)) {
196 $this->main_tpl->setOnScreenMessage('info', $this->lng->txt('buddy_bs_action_not_possible'), true);
197 $this->ctrl->returnToParent($this);
198 }
199
200 $usrId = (int) $this->http->request()->getQueryParams()['user_id'];
201 try {
202 $relation = ilBuddyList::getInstanceByGlobalUser()->getRelationByUserId($usrId);
203
204 if (null !== $onBeforeExecute) {
205 $onBeforeExecute($relation);
206 }
207
209 $this->main_tpl->setOnScreenMessage('success', $this->lng->txt($positiveFeedbackLanguageId), true);
211 $this->main_tpl->setOnScreenMessage('info', sprintf(
212 $this->lng->txt($e->getMessage()),
214 ), true);
215 } catch (Exception) {
216 $this->main_tpl->setOnScreenMessage('info', $this->lng->txt('buddy_bs_action_not_possible'), true);
217 }
218
219 $this->redirectToReferer();
220 }
221
225 private function transitionAsyncCommand(): void
226 {
227 if (!$this->ctrl->isAsynch()) {
228 throw new RuntimeException('This action only supports AJAX http requests');
229 }
230
231 if (!$this->isRequestParameterGiven('usr_id', self::BS_REQUEST_HTTP_POST)) {
232 throw new RuntimeException('Missing "usr_id" parameter');
233 }
234
235 if (!$this->isRequestParameterGiven('action', self::BS_REQUEST_HTTP_POST)) {
236 throw new RuntimeException('Missing "action" parameter');
237 }
238
239 $response = new stdClass();
240 $response->success = false;
241
242 try {
243 $usr_id = (int) $this->http->request()->getParsedBody()['usr_id'];
244 $action = ilUtil::stripSlashes($this->http->request()->getParsedBody()['action']);
245
246 if (ilObjUser::_isAnonymous($usr_id)) {
247 throw new ilBuddySystemException(sprintf(
248 'You cannot perform a state transition for the anonymous user (id: %s)',
249 $usr_id
250 ));
251 }
252
253 $login = ilObjUser::_lookupLogin($usr_id);
254 if ($login === '') {
255 throw new ilBuddySystemException(sprintf(
256 'You cannot perform a state transition for a non existing user (id: %s)',
257 $usr_id
258 ));
259 }
260
261 $relation = $this->buddyList->getRelationByUserId($usr_id);
262
263 // The ILIAS JF decided to add a new personal setting
264 if (
265 $relation->isUnlinked() &&
266 !ilUtil::yn2tf((string) ilObjUser::_lookupPref($relation->getBuddyUsrId(), 'bs_allow_to_contact_me'))
267 ) {
268 throw new ilException('The requested user does not want to get contact requests');
269 }
270
271 try {
272 $this->buddyList->{$action}($relation);
273 $response->success = true;
275 $response->message = sprintf($this->lng->txt($e->getMessage()), $login);
276 } catch (Exception) {
277 $response->message = $this->lng->txt('buddy_bs_action_not_possible');
278 }
279
280 $response->state = $relation->getState()::class;
281 $response->state_html = $this->stateFactory->getStateButtonRendererByOwnerAndRelation(
282 $this->buddyList->getOwnerId(),
284 )->getHtml();
285 } catch (Exception) {
286 $response->message = $this->lng->txt('buddy_bs_action_not_possible');
287 }
288
289 $this->http->saveResponse(
290 $this->http->response()
291 ->withAddedHeader('Content-Type', 'application/json')
292 ->withBody(ILIAS\Filesystem\Stream\Streams::ofString(json_encode($response, JSON_THROW_ON_ERROR)))
293 );
294 $this->http->sendResponse();
295 $this->http->close();
296 }
297
298 private function redirectToReferer(): void
299 {
300 if (isset($this->http->request()->getServerParams()['HTTP_REFERER'])) {
301 $redirectUrl = $this->http->request()->getServerParams()['HTTP_REFERER'];
302 $urlParts = parse_url($redirectUrl);
303
304 if (isset($urlParts['path'])) {
305 $script = basename($urlParts['path'], '.php');
306 if ($script === 'login') {
307 $this->ctrl->returnToParent($this);
308 } else {
309 $redirectUrl = ltrim(basename($urlParts['path']), '/');
310 if (isset($urlParts['query'])) {
311 $redirectUrl .= '?' . $urlParts['query'];
312 }
313 }
314 }
315
316 if ($redirectUrl !== '') {
317 $this->ctrl->redirectToURL($redirectUrl);
318 }
319 }
320
321 $this->ctrl->returnToParent($this);
322 }
323}
$id
plugin.php for ilComponentBuildPluginInfoObjectiveTest::testAddPlugins
Definition: plugin.php:23
$relation
Builds a Color from either hex- or rgb values.
Definition: Factory.php:31
Stream factory which enables the user to create streams without the knowledge of the concrete class.
Definition: Streams.php:32
Class Services.
Definition: Services.php:38
Class ilBuddyList.
static getInstanceByGlobalUser(?ilObjUser $user=null)
Class ilBuddySystemException.
Class ilBuddySystemGUI.
transitionCommand(string $cmd, string $positiveFeedbackLanguageId, ?callable $onBeforeExecute=null)
isRequestParameterGiven(string $key, int $type)
readonly ilGlobalTemplateInterface $main_tpl
transitionAsyncCommand()
Performs a state transition based on the request action.
ilBuddySystemRelationStateFactory $stateFactory
static initializeFrontend(ilGlobalTemplateInterface $page)
static bool $isFrontendInitialized
Class ilBuddySystemRelation.
Base class for ILIAS Exception handling.
language handling
User class.
static _isAnonymous(int $usr_id)
static _lookupPref(int $a_usr_id, string $a_keyword)
static _lookupLogin(int $a_user_id)
static stripSlashes(string $a_str, bool $a_strip_html=true, string $a_allow="")
static yn2tf(string $a_yn)
Interface ResponseHeader.
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.
addOnLoadCode(string $a_code, int $a_batch=2)
Add on load code.
An entity that renders components to a string output.
Definition: Renderer.php:31
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...
static http()
Fetches the global http state from ILIAS.
Interface Observer \BackgroundTasks Contains several chained tasks and infos about them.
if(!file_exists('../ilias.ini.php'))
global $DIC
Definition: shib_login.php:26
$response
Definition: xapitoken.php:90