ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
class.ilBuddySystemGUI.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
22
29{
30 private const int BS_REQUEST_HTTP_GET = 1;
31 private const int BS_REQUEST_HTTP_POST = 2;
32
33 protected static bool $isFrontendInitialized = false;
34
38 protected ilObjUser $user;
39 protected ilLanguage $lng;
40 protected Services $http;
42
43 public function __construct()
44 {
45 global $DIC;
46 $this->main_tpl = $DIC->ui()->mainTemplate();
47
48 $this->http = $DIC->http();
49 $this->ctrl = $DIC['ilCtrl'];
50 $this->user = $DIC['ilUser'];
51 $this->lng = $DIC['lng'];
52
53 $this->buddyList = ilBuddyList::getInstanceByGlobalUser();
55
56 $this->lng->loadLanguageModule('buddysystem');
57 }
58
59 public static function initializeFrontend(ilGlobalTemplateInterface $page): void
60 {
61 global $DIC;
62
63 if (
64 !self::$isFrontendInitialized &&
65 ilBuddySystem::getInstance()->isEnabled() &&
66 !$DIC->user()->isAnonymous()
67 ) {
68 $DIC->language()->loadLanguageModule('buddysystem');
69
70 $page->addJavaScript('./assets/js/buddy_system.js');
71
72 $config = new stdClass();
73 $config->http_post_url = $DIC->ctrl()->getFormActionByClass([
74 ilUIPluginRouterGUI::class,
75 self::class
76 ], '', '', true, false);
77 $config->transition_state_cmd = 'transitionAsync';
78 $page->addOnLoadCode('il.BuddySystem.setConfig(' . json_encode($config, JSON_THROW_ON_ERROR) . ');');
79
80 $btn_config = new stdClass();
81 $btn_config->bnt_class = ilBuddySystemLinkButtonType::ROOT_CSS_CLASS;
82
83 $page->addOnLoadCode('il.BuddySystemButton.setConfig(' . json_encode($btn_config, JSON_THROW_ON_ERROR) . ');');
84 $page->addOnLoadCode('il.BuddySystemButton.init();');
85
86 self::$isFrontendInitialized = true;
87 }
88 }
89
93 public function executeCommand(): void
94 {
95 if ($this->user->isAnonymous()) {
96 throw new RuntimeException('This controller only accepts requests of logged in users');
97 }
98
99 $this->{$this->ctrl->getCmd() . 'Command'}();
100 }
101
102 protected function isRequestParameterGiven(string $key, int $type): bool
103 {
104 switch ($type) {
106 $body = $this->http->request()->getParsedBody();
107 return (isset($body[$key]) && is_string($body[$key]) && $body[$key] !== '');
108
110 default:
111 $query = $this->http->request()->getQueryParams();
112 return (isset($query[$key]) && is_string($query[$key]) && $query[$key] !== '');
113 }
114 }
115
116 private function requestCommand(): void
117 {
118 $this->transitionCommand(
119 'request',
120 'buddy_relation_requested',
121 static function (ilBuddySystemRelation $relation): void {
122 if (
123 $relation->isUnlinked() &&
124 !ilUtil::yn2tf((string) ilObjUser::_lookupPref($relation->getBuddyUsrId(), 'bs_allow_to_contact_me'))
125 ) {
126 throw new ilException('The requested user does not want to get contact requests');
127 }
128 }
129 );
130 }
131
132 private function ignoreCommand(): void
133 {
134 $this->transitionCommand('ignore', 'buddy_request_ignored');
135 }
136
137 private function linkCommand(): void
138 {
139 $this->transitionCommand('link', 'buddy_request_approved');
140 }
141
142 private function transitionCommand(
143 string $cmd,
144 string $positiveFeedbackLanguageId,
145 ?callable $onBeforeExecute = null
146 ): void {
147 if (!$this->isRequestParameterGiven('user_id', self::BS_REQUEST_HTTP_GET)) {
148 $this->main_tpl->setOnScreenMessage('info', $this->lng->txt('buddy_bs_action_not_possible'), true);
149 $this->ctrl->returnToParent($this);
150 }
151
152 $usrId = (int) $this->http->request()->getQueryParams()['user_id'];
153 try {
154 $relation = ilBuddyList::getInstanceByGlobalUser()->getRelationByUserId($usrId);
155
156 if (null !== $onBeforeExecute) {
157 $onBeforeExecute($relation);
158 }
159
161 $this->main_tpl->setOnScreenMessage('success', $this->lng->txt($positiveFeedbackLanguageId), true);
163 $this->main_tpl->setOnScreenMessage('info', sprintf(
164 $this->lng->txt($e->getMessage()),
166 ), true);
167 } catch (Exception) {
168 $this->main_tpl->setOnScreenMessage('info', $this->lng->txt('buddy_bs_action_not_possible'), true);
169 }
170
171 $this->redirectToReferer();
172 }
173
177 private function transitionAsyncCommand(): void
178 {
179 if (!$this->ctrl->isAsynch()) {
180 throw new RuntimeException('This action only supports AJAX http requests');
181 }
182
183 if (!$this->isRequestParameterGiven('usr_id', self::BS_REQUEST_HTTP_POST)) {
184 throw new RuntimeException('Missing "usr_id" parameter');
185 }
186
187 if (!$this->isRequestParameterGiven('action', self::BS_REQUEST_HTTP_POST)) {
188 throw new RuntimeException('Missing "action" parameter');
189 }
190
191 $response = new stdClass();
192 $response->success = false;
193
194 try {
195 $usr_id = (int) $this->http->request()->getParsedBody()['usr_id'];
196 $action = ilUtil::stripSlashes($this->http->request()->getParsedBody()['action']);
197
198 if (ilObjUser::_isAnonymous($usr_id)) {
199 throw new ilBuddySystemException(sprintf(
200 'You cannot perform a state transition for the anonymous user (id: %s)',
201 $usr_id
202 ));
203 }
204
205 $login = ilObjUser::_lookupLogin($usr_id);
206 if ($login === '') {
207 throw new ilBuddySystemException(sprintf(
208 'You cannot perform a state transition for a non existing user (id: %s)',
209 $usr_id
210 ));
211 }
212
213 $relation = $this->buddyList->getRelationByUserId($usr_id);
214
215 // The ILIAS JF decided to add a new personal setting
216 if (
217 $relation->isUnlinked() &&
218 !ilUtil::yn2tf((string) ilObjUser::_lookupPref($relation->getBuddyUsrId(), 'bs_allow_to_contact_me'))
219 ) {
220 throw new ilException('The requested user does not want to get contact requests');
221 }
222
223 try {
224 $this->buddyList->{$action}($relation);
225 $response->success = true;
227 $response->message = sprintf($this->lng->txt($e->getMessage()), $login);
228 } catch (Exception) {
229 $response->message = $this->lng->txt('buddy_bs_action_not_possible');
230 }
231
232 $response->state = $relation->getState()::class;
233 $response->state_html = $this->stateFactory->getStateButtonRendererByOwnerAndRelation(
234 $this->buddyList->getOwnerId(),
236 )->getHtml();
237 } catch (Exception) {
238 $response->message = $this->lng->txt('buddy_bs_action_not_possible');
239 }
240
241 $this->http->saveResponse(
242 $this->http->response()
243 ->withAddedHeader('Content-Type', 'application/json')
244 ->withBody(ILIAS\Filesystem\Stream\Streams::ofString(json_encode($response, JSON_THROW_ON_ERROR)))
245 );
246 $this->http->sendResponse();
247 $this->http->close();
248 }
249
250 private function redirectToReferer(): void
251 {
252 if (isset($this->http->request()->getServerParams()['HTTP_REFERER'])) {
253 $redirectUrl = $this->http->request()->getServerParams()['HTTP_REFERER'];
254 $urlParts = parse_url($redirectUrl);
255
256 if (isset($urlParts['path'])) {
257 $script = basename($urlParts['path'], '.php');
258 if ($script === 'login') {
259 $this->ctrl->returnToParent($this);
260 } else {
261 $redirectUrl = ltrim(basename($urlParts['path']), '/');
262 if (isset($urlParts['query'])) {
263 $redirectUrl .= '?' . $urlParts['query'];
264 }
265 }
266 }
267
268 if ($redirectUrl !== '') {
269 $this->ctrl->redirectToURL($redirectUrl);
270 }
271 }
272
273 $this->ctrl->returnToParent($this);
274 }
275}
$relation
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)
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.
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:93