Elgg  Version 5.1
Service.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Ajax;
4 
12 
19 class Service {
20 
24  private $events;
25 
29  private $msgs;
30 
34  private $request;
35 
39  private $amd_config;
40 
44  private $response_sent = false;
45 
49  private $allowed_views = [];
50 
59  public function __construct(EventsService $events, SystemMessagesService $msgs, Request $request, Config $amdConfig) {
60  $this->events = $events;
61  $this->msgs = $msgs;
62  $this->request = $request;
63  $this->amd_config = $amdConfig;
64 
65  $message_filter = [$this, 'prepareResponse'];
66  $this->events->registerHandler(AjaxResponse::RESPONSE_EVENT, 'all', $message_filter, 999);
67  }
68 
74  public function isAjax2Request(): bool {
75  $version = $this->request->headers->get('X-Elgg-Ajax-API');
76  return ($version === '2');
77  }
78 
88  public function isReady(): bool {
89  return !$this->response_sent && $this->isAjax2Request();
90  }
91 
99  public function decodeJson($string) {
100  if (!is_string($string)) {
101  return $string;
102  }
103 
104  $object = json_decode($string);
105  return ($object === null) ? $string : $object;
106  }
107 
117  public function respondFromOutput($output, string $event_type = '', bool $try_decode = true) {
118  if ($try_decode) {
119  $output = $this->decodeJson($output);
120  }
121 
122  $api_response = new Response();
123  if (is_object($output) && isset($output->value)) {
124  $api_response->setData($output);
125  } elseif (is_array($output) && isset($output['value'])) {
126  $api_response->setData((object) $output);
127  } else {
128  $api_response->setData((object) ['value' => $output]);
129  }
130 
131  $api_response = $this->filterApiResponse($api_response, $event_type);
132  $response = $this->buildHttpResponse($api_response);
133 
134  $this->response_sent = true;
135  return _elgg_services()->responseFactory->send($response);
136  }
137 
146  public function respondFromApiResponse(AjaxResponse $api_response, string $event_type = '') {
147  $api_response = $this->filterApiResponse($api_response, $event_type);
148  $response = $this->buildHttpResponse($api_response);
149 
150  $this->response_sent = true;
151  return _elgg_services()->responseFactory->send($response);
152  }
153 
162  public function respondWithError(string $msg = '', int $status = 400) {
163  $response = new JsonResponse(['error' => $msg], $status);
164 
165  // clear already set system messages as we respond directly with an error as message body
166  $this->msgs->dumpRegister();
167 
168  $this->response_sent = true;
169  return _elgg_services()->responseFactory->send($response);
170  }
171 
181  private function filterApiResponse(AjaxResponse $api_response, string $event_type = ''): AjaxResponse {
182  $api_response->setTtl($this->request->getParam('elgg_response_ttl', 0, false));
183 
184  if ($event_type) {
185  $event_name = AjaxResponse::RESPONSE_EVENT;
186  $api_response = $this->events->triggerResults($event_name, $event_type, [], $api_response);
187  if (!$api_response instanceof AjaxResponse) {
188  throw new RuntimeException("The value returned by event [{$event_name}, {$event_type}] was not an ApiResponse");
189  }
190  }
191 
192  return $api_response;
193  }
194 
203  private function buildHttpResponse(AjaxResponse $api_response): JsonResponse {
204  if ($api_response->isCancelled()) {
205  return new JsonResponse(['error' => 'The response was cancelled'], 400);
206  }
207 
208  $response = _elgg_services()->responseFactory->prepareJsonResponse($api_response->getData());
209 
210  $ttl = $api_response->getTtl();
211  if ($ttl > 0) {
212  // JsonRequest sets a default Cache-Control header we don't want
213  $response->headers->remove('Cache-Control');
214 
215  $response->setClientTtl($ttl);
216 
217  // if we don't set Expires, Apache will add a far-off max-age and Expires for us.
218  $response->headers->set('Expires', gmdate('D, d M Y H:i:s \G\M\T', time() + $ttl));
219  }
220 
221  return $response;
222  }
223 
232  public function prepareResponse(\Elgg\Event $event) {
233  $response = $event->getValue();
234  if (!$response instanceof AjaxResponse) {
235  return;
236  }
237 
238  if ($this->request->getParam('elgg_fetch_messages', true)) {
239  $messages = $this->msgs->dumpRegister();
240  foreach ($messages as $type => $msgs) {
241  $messages[$type] = array_map(function($value) {
242  return (string) $value;
243  }, $msgs);
244  }
245 
246  $response->getData()->_elgg_msgs = (object) $messages;
247  }
248 
249  if ($this->request->getParam('elgg_fetch_deps', true)) {
250  $response->getData()->_elgg_deps = (array) $this->amd_config->getDependencies();
251  }
252 
253  return $response;
254  }
255 
263  public function registerView(string $view): void {
264  $this->allowed_views[$view] = true;
265  }
266 
274  public function unregisterView(string $view): void {
275  unset($this->allowed_views[$view]);
276  }
277 
283  public function getViews(): array {
284  return array_keys($this->allowed_views);
285  }
286 }
$messages
Definition: admin.php:12
isCancelled()
Has the response been cancelled?
respondFromOutput($output, string $event_type= '', bool $try_decode=true)
Send a JSON HTTP response with the given output.
Definition: Service.php:117
Elgg HTTP request.
Definition: Request.php:17
Exception thrown if an error which can only be found on runtime occurs.
$response
Definition: content.php:10
setTtl($ttl=0)
Set the max-age for client caching.
isAjax2Request()
Did the request come from the elgg/Ajax module?
Definition: Service.php:74
$version
c Accompany it with the information you received as to the offer to distribute corresponding source complete source code means all the source code for all modules it plus any associated interface definition plus the scripts used to control compilation and installation of the executable as a special the source code distributed need not include anything that is normally and so on of the operating system on which the executable unless that component itself accompanies the executable If distribution of executable or object code is made by offering access to copy from a designated then offering equivalent access to copy the source code from the same place counts as distribution of the source even though third parties are not compelled to copy the source along with the object code You may not or distribute the Program except as expressly provided under this License Any attempt otherwise to sublicense or distribute the Program is void
Definition: LICENSE.txt:215
registerView(string $view)
Register a view to be available for ajax calls.
Definition: Service.php:263
Events service.
$type
Definition: delete.php:22
respondWithError(string $msg= '', int $status=400)
Send a JSON HTTP 400 response.
Definition: Service.php:162
Models the Ajax API service.
Definition: Service.php:19
if($item instanceof\ElggEntity) elseif($item instanceof\ElggRiverItem) elseif($item instanceof\ElggRelationship) elseif(is_callable([$item, 'getType']))
Definition: item.php:48
$value
Definition: generic.php:51
prepareResponse(\Elgg\Event $event)
Prepare the response with additional metadata, like system messages and required AMD modules...
Definition: Service.php:232
if(!empty($avatar)&&!$avatar->isValid()) elseif(empty($avatar)) if(!$owner->saveIconFromUploadedFile('avatar')) if(!elgg_trigger_event('profileiconupdate', $owner->type, $owner)) $view
Definition: upload.php:39
decodeJson($string)
Attempt to JSON decode the given string.
Definition: Service.php:99
JSON endpoint response.
unregisterView(string $view)
Unregister a view for ajax calls.
Definition: Service.php:274
Control configuration of RequireJS.
Definition: Config.php:12
__construct(EventsService $events, SystemMessagesService $msgs, Request $request, Config $amdConfig)
Constructor.
Definition: Service.php:59
respondFromApiResponse(AjaxResponse $api_response, string $event_type= '')
Send a JSON HTTP response based on the given API response.
Definition: Service.php:146
$amdConfig
if($email instanceof\Elgg\Email) $object
Definition: body.php:24
getData()
Get the response data, which will be a stdClass object with property "value".
System messages service.
isReady()
Is the service ready to respond to the request?
Definition: Service.php:88
_elgg_services()
Get the global service provider.
Definition: elgglib.php:346
JSON endpoint response.
Definition: Response.php:13
$output
Definition: download.php:9
getTtl()
Get the max-age for client caching.
getViews()
Returns an array of views allowed for ajax calls.
Definition: Service.php:283
Models an event passed to event handlers.
Definition: Event.php:11