-
Notifications
You must be signed in to change notification settings - Fork 673
/
ResponseFactory.php
751 lines (631 loc) · 19.6 KB
/
ResponseFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
<?php
namespace Elgg\Http;
use Elgg\Ajax\Service as AjaxService;
use Elgg\EventsService;
use Elgg\PluginHooksService;
use ElggEntity;
use InvalidArgumentException;
use InvalidParameterException;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RedirectResponse as SymfonyRedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* WARNING: API IN FLUX. DO NOT USE DIRECTLY.
*
* @since 2.3
* @internal
*/
class ResponseFactory {
/**
* @var Request
*/
private $request;
/**
* @var AjaxService
*/
private $ajax;
/**
* @var PluginHooksService
*/
private $hooks;
/**
* @var ResponseTransport
*/
private $transport;
/**
* @var Response|false
*/
private $response_sent = false;
/**
* @var ResponseHeaderBag
*/
private $headers;
/**
* @var EventsService
*/
private $events;
/**
* Constructor
*
* @param Request $request HTTP request
* @param PluginHooksService $hooks Plugin hooks service
* @param AjaxService $ajax AJAX service
* @param ResponseTransport $transport Response transport
* @param EventsService $events Events service
*/
public function __construct(Request $request, PluginHooksService $hooks, AjaxService $ajax, ResponseTransport $transport, EventsService $events) {
$this->request = $request;
$this->hooks = $hooks;
$this->ajax = $ajax;
$this->transport = $transport;
$this->events = $events;
$this->headers = new ResponseHeaderBag();
}
/**
* Sets headers to apply to all responses being sent
*
* @param string $name Header name
* @param string $value Header value
* @param bool $replace Replace existing headers
* @return void
*/
public function setHeader($name, $value, $replace = true) {
$this->headers->set($name, $value, $replace);
}
/**
* Set a cookie, but allow plugins to customize it first.
*
* To customize all cookies, register for the 'init:cookie', 'all' event.
*
* @param \ElggCookie $cookie The cookie that is being set
* @return bool
*/
public function setCookie(\ElggCookie $cookie) {
if (!$this->events->trigger('init:cookie', $cookie->name, $cookie)) {
return false;
}
$symfony_cookie = new Cookie(
$cookie->name,
$cookie->value,
$cookie->expire,
$cookie->path,
$cookie->domain,
$cookie->secure,
$cookie->httpOnly
);
$this->headers->setCookie($symfony_cookie);
return true;
}
/**
* Get headers set to apply to all responses
*
* @param bool $remove_existing Remove existing headers found in headers_list()
* @return ResponseHeaderBag
*/
public function getHeaders($remove_existing = true) {
// Add headers that have already been set by underlying views
// e.g. viewtype page shells set content-type headers
$headers_list = headers_list();
foreach ($headers_list as $header) {
if (stripos($header, 'HTTP/1.1') !== false) {
continue;
}
list($name, $value) = explode(':', $header, 2);
$this->setHeader($name, ltrim($value), false);
if ($remove_existing) {
header_remove($name);
}
}
return $this->headers;
}
/**
* Creates an HTTP response
*
* @param mixed $content The response content
* @param integer $status The response status code
* @param array $headers An array of response headers
*
* @return Response
* @throws InvalidArgumentException
*/
public function prepareResponse($content = '', $status = 200, array $headers = []) {
$header_bag = $this->getHeaders();
$header_bag->add($headers);
$response = new Response($content, $status, $header_bag->all());
$response->prepare($this->request);
return $response;
}
/**
* Creates a redirect response
*
* @param string $url URL to redirect to
* @param integer $status The status code (302 by default)
* @param array $headers An array of response headers (Location is always set to the given URL)
*
* @return SymfonyRedirectResponse
* @throws InvalidArgumentException
*/
public function prepareRedirectResponse($url, $status = 302, array $headers = []) {
$header_bag = $this->getHeaders();
$header_bag->add($headers);
$response = new SymfonyRedirectResponse($url, $status, $header_bag->all());
$response->prepare($this->request);
return $response;
}
/**
* Creates an JSON response
*
* @param mixed $content The response content
* @param integer $status The response status code
* @param array $headers An array of response headers
*
* @return JsonResponse
* @throws InvalidArgumentException
*/
public function prepareJsonResponse($content = '', $status = 200, array $headers = []) {
$header_bag = $this->getHeaders();
$header_bag->add($headers);
/**
* Removing Content-Type header because in some cases content-type headers were already set
* This is a problem when serving a cachable view (for example a .css) in ajax/view
*
* @see https://github.com/Elgg/Elgg/issues/9794
*/
$header_bag->remove('Content-Type');
$response = new JsonResponse($content, $status, $header_bag->all());
$response->prepare($this->request);
return $response;
}
/**
* Send a response
*
* @param Response $response Response object
* @return Response|false
*/
public function send(Response $response) {
if ($this->response_sent) {
if ($this->response_sent !== $response) {
_elgg_services()->logger->error('Unable to send the following response: ' . PHP_EOL
. (string) $response . PHP_EOL
. 'because another response has already been sent: ' . PHP_EOL
. (string) $this->response_sent);
}
} else {
if (!$this->events->triggerBefore('send', 'http_response', $response)) {
return false;
}
$request = $this->request;
$method = $request->getRealMethod() ? : 'GET';
$path = $request->getElggPath();
_elgg_services()->logger->notice("Responding to {$method} {$path}");
if (!$this->transport->send($response)) {
return false;
}
$this->events->triggerAfter('send', 'http_response', $response);
$this->response_sent = $response;
$this->closeSession();
}
return $this->response_sent;
}
/**
* Returns a response that was sent to the client
*
* @return Response|false
*/
public function getSentResponse() {
return $this->response_sent;
}
/**
* Send HTTP response
*
* @param ResponseBuilder $response ResponseBuilder instance
* An instance of an ErrorResponse, OkResponse or RedirectResponse
* @return false|Response
* @throws \InvalidParameterException
*/
public function respond(ResponseBuilder $response) {
$response_type = $this->parseContext();
$response = $this->hooks->trigger('response', $response_type, $response, $response);
if (!$response instanceof ResponseBuilder) {
throw new InvalidParameterException("Handlers for 'response','$response_type' plugin hook must "
. "return an instanceof " . ResponseBuilder::class);
}
if ($response->isNotModified()) {
return $this->send($this->prepareResponse('', ELGG_HTTP_NOT_MODIFIED));
}
// Prevent content type sniffing by the browser
$headers = $response->getHeaders();
$headers['X-Content-Type-Options'] = 'nosniff';
$response->setHeaders($headers);
$is_xhr = $this->request->isXmlHttpRequest();
$is_action = false;
if (0 === strpos($response_type, 'action:')) {
$is_action = true;
}
if ($is_action && $response->getForwardURL() === null) {
// actions must always set a redirect url
$response->setForwardURL(REFERRER);
}
if ($response->getForwardURL() === REFERRER) {
$response->setForwardURL($this->request->headers->get('Referer'));
}
if ($response->getForwardURL() !== null && !$is_xhr) {
// non-xhr requests should issue a forward if redirect url is set
// unless it's an error, in which case we serve an error page
if ($this->isAction() || (!$response->isClientError() && !$response->isServerError())) {
$response->setStatusCode(ELGG_HTTP_FOUND);
}
}
if ($is_xhr && ($is_action || $this->ajax->isAjax2Request())) {
if (!$this->ajax->isAjax2Request()) {
// xhr actions using legacy ajax API should return 200 with wrapped data
$response->setStatusCode(ELGG_HTTP_OK);
}
// Actions always respond with JSON on xhr calls
$headers = $response->getHeaders();
$headers['Content-Type'] = 'application/json; charset=UTF-8';
$response->setHeaders($headers);
if ($response->isOk()) {
$response->setContent($this->wrapAjaxResponse($response->getContent(), $response->getForwardURL()));
}
}
if ($response->isRedirection()) {
$redirect_url = $response->getForwardURL();
return $this->redirect($redirect_url, $response->getStatusCode());
}
if ($this->ajax->isReady() && $response->isSuccessful()) {
return $this->respondFromContent($response);
}
if ($response->isClientError() || $response->isServerError() || $response instanceof ErrorResponse) {
return $this->respondWithError($response);
}
return $this->respondFromContent($response);
}
/**
* Send error HTTP response
*
* @param ResponseBuilder $response ResponseBuilder instance
* An instance of an ErrorResponse, OkResponse or RedirectResponse
*
* @return false|Response
* @throws \InvalidParameterException
*/
public function respondWithError(ResponseBuilder $response) {
$error = $this->stringify($response->getContent());
$status_code = $response->getStatusCode();
if ($this->ajax->isReady()) {
return $this->send($this->ajax->respondWithError($error, $status_code));
}
if ($this->isXhr()) {
// xhr calls to non-actions (e.g. ajax/view or ajax/form) need to receive proper HTTP status code
return $this->send($this->prepareResponse($error, $status_code, $response->getHeaders()));
}
$forward_url = $this->getSiteRefererUrl();
if (!$this->isAction()) {
$params = [
'current_url' => current_page_url(),
'forward_url' => $forward_url,
];
// For BC, let plugins serve their own error page
// @see elgg_error_page_handler
$forward_reason = (string) $status_code;
$this->hooks->trigger('forward', $forward_reason, $params, $forward_url);
if ($this->response_sent) {
// Response was sent from a forward hook
return $this->response_sent;
}
if (elgg_view_exists('resources/error')) {
$params['type'] = $forward_reason;
$params['exception'] = $response->getException();
if (!elgg_is_empty($error)) {
$params['params']['error'] = $error;
}
$error_page = elgg_view_resource('error', $params);
} else {
$error_page = $error;
}
return $this->send($this->prepareResponse($error_page, $status_code));
}
$forward_url = $this->makeSecureForwardUrl($forward_url);
return $this->send($this->prepareRedirectResponse($forward_url));
}
/**
* Send OK response
*
* @param ResponseBuilder $response ResponseBuilder instance
* An instance of an ErrorResponse, OkResponse or RedirectResponse
*
* @return Response|false
*/
public function respondFromContent(ResponseBuilder $response) {
$content = $this->stringify($response->getContent());
if ($this->ajax->isReady()) {
$hook_type = $this->parseContext();
return $this->send($this->ajax->respondFromOutput($content, $hook_type));
}
return $this->send($this->prepareResponse($content, $response->getStatusCode(), $response->getHeaders()));
}
/**
* Wraps response content in an Ajax2 compatible format
*
* @param string $content Response content
* @param string $forward_url Forward URL
* @return string
*/
public function wrapAjaxResponse($content = '', $forward_url = null) {
if (!$this->ajax->isAjax2Request()) {
return $this->wrapLegacyAjaxResponse($content, $forward_url);
}
$content = $this->stringify($content);
if ($forward_url === REFERRER) {
$forward_url = $this->getSiteRefererUrl();
}
$params = [
'value' => '',
'current_url' => current_page_url(),
'forward_url' => elgg_normalize_url($forward_url),
];
$params['value'] = $this->ajax->decodeJson($content);
return $this->stringify($params);
}
/**
* Wraps content for compability with legacy Elgg ajax calls
*
* @param string $content Response content
* @param string $forward_url Forward URL
* @return string
*/
public function wrapLegacyAjaxResponse($content = '', $forward_url = REFERRER) {
$content = $this->stringify($content);
if ($forward_url === REFERRER) {
$forward_url = $this->getSiteRefererUrl();
}
// always pass the full structure to avoid boilerplate JS code.
$params = [
'output' => '',
'status' => 0,
'system_messages' => [
'error' => [],
'success' => []
],
'current_url' => current_page_url(),
'forward_url' => elgg_normalize_url($forward_url),
];
$params['output'] = $this->ajax->decodeJson($content);
// Grab any system messages so we can inject them via ajax too
$system_messages = _elgg_services()->systemMessages->dumpRegister();
if (isset($system_messages['success'])) {
$params['system_messages']['success'] = $system_messages['success'];
}
if (isset($system_messages['error'])) {
$params['system_messages']['error'] = $system_messages['error'];
$params['status'] = -1;
}
$response_type = $this->parseContext();
list($service, $name) = explode(':', $response_type);
$context = [
$service => $name,
];
$params = $this->hooks->trigger('output', 'ajax', $context, $params);
return $this->stringify($params);
}
/**
* Prepares a redirect response
*
* @param string $forward_url Redirection URL
* @param mixed $status_code HTTP status code or forward reason
* @return false|Response
* @throws InvalidParameterException
*/
public function redirect($forward_url = REFERRER, $status_code = ELGG_HTTP_FOUND) {
$location = $forward_url;
if ($forward_url === REFERRER) {
$forward_url = $this->getSiteRefererUrl();
}
$forward_url = $this->makeSecureForwardUrl($forward_url);
// allow plugins to rewrite redirection URL
$params = [
'current_url' => current_page_url(),
'forward_url' => $forward_url,
'location' => $location,
];
$forward_reason = (string) $status_code;
$forward_url = $this->hooks->trigger('forward', $forward_reason, $params, $forward_url);
if ($this->response_sent) {
// Response was sent from a forward hook
// Clearing handlers to void infinite loops
return $this->response_sent;
}
if ($forward_url === REFERRER) {
$forward_url = $this->getSiteRefererUrl();
}
if (!is_string($forward_url)) {
throw new InvalidParameterException("'forward', '$forward_reason' hook must return a valid redirection URL");
}
$forward_url = $this->makeSecureForwardUrl($forward_url);
switch ($status_code) {
case 'system':
case 'csrf':
$status_code = ELGG_HTTP_OK;
break;
case 'admin':
case 'login':
case 'member':
case 'walled_garden':
default :
$status_code = (int) $status_code;
if (!$status_code || $status_code < 100 || $status_code > 599) {
$status_code = ELGG_HTTP_SEE_OTHER;
}
break;
}
if ($this->isXhr()) {
if ($status_code < 100 || ($status_code >= 300 && $status_code <= 399) || $status_code > 599) {
// We only want to preserve OK and error codes
// Redirect responses should be converted to OK responses as this is an XHR request
$status_code = ELGG_HTTP_OK;
}
$output = ob_get_clean();
if (!$this->isAction() && !$this->ajax->isAjax2Request()) {
// legacy ajax calls are always OK
// actions are wrapped by ResponseFactory::respond()
$status_code = ELGG_HTTP_OK;
$output = $this->wrapLegacyAjaxResponse($output, $forward_url);
}
$response = new OkResponse($output, $status_code, $forward_url);
$headers = $response->getHeaders();
$headers['Content-Type'] = 'application/json; charset=UTF-8';
$response->setHeaders($headers);
return $this->respond($response);
}
if ($this->isAction()) {
// actions should always redirect on non xhr-calls
if (!is_int($status_code) || $status_code < 300 || $status_code > 399) {
$status_code = ELGG_HTTP_SEE_OTHER;
}
}
$response = new OkResponse('', $status_code, $forward_url);
if ($response->isRedirection()) {
return $this->send($this->prepareRedirectResponse($forward_url, $status_code));
}
return $this->respond($response);
}
/**
* Parses response type to be used as plugin hook type
* @return string
*/
public function parseContext() {
$segments = $this->request->getUrlSegments();
$identifier = array_shift($segments);
switch ($identifier) {
case 'ajax' :
$page = array_shift($segments);
if ($page === 'view') {
$view = implode('/', $segments);
return "view:$view";
} else if ($page === 'form') {
$form = implode('/', $segments);
return "form:$form";
}
array_unshift($segments, $page);
break;
case 'action' :
$action = implode('/', $segments);
return "action:$action";
}
array_unshift($segments, $identifier);
$path = implode('/', $segments);
return "path:$path";
}
/**
* Check if the request is an XmlHttpRequest
* @return bool
*/
public function isXhr() {
return $this->request->isXmlHttpRequest();
}
/**
* Check if the requested path is an action
* @return bool
*/
public function isAction() {
if (0 === strpos($this->parseContext(), 'action:')) {
return true;
}
return false;
}
/**
* Normalizes content into serializable data by walking through arrays
* and objectifying Elgg entities
*
* @param mixed $content Data to normalize
* @return mixed
*/
public function normalize($content = '') {
if ($content instanceof ElggEntity) {
$content = (array) $content->toObject();
}
if (is_array($content)) {
foreach ($content as $key => $value) {
$content[$key] = $this->normalize($value);
}
}
return $content;
}
/**
* Stringify/serialize response data
*
* Casts objects implementing __toString method to strings
* Serializes non-scalar values to JSON
*
* @param mixed $content Content to serialize
* @return string
*/
public function stringify($content = '') {
$content = $this->normalize($content);
if (is_object($content) && is_callable([$content, '__toString'])) {
return (string) $content;
}
if (is_scalar($content)) {
return (string) $content;
}
if (empty($content)) {
return '';
}
return json_encode($content, ELGG_JSON_ENCODING);
}
/**
* Replaces response transport
*
* @param ResponseTransport $transport Transport interface
* @return void
*/
public function setTransport(ResponseTransport $transport) {
$this->transport = $transport;
}
/**
* Ensures the referer header is a site url
*
* @return string
*/
protected function getSiteRefererUrl() {
$unsafe_url = $this->request->headers->get('Referer');
$safe_url = elgg_normalize_site_url($unsafe_url);
if ($safe_url !== false) {
return $safe_url;
}
return '';
}
/**
* Ensure the url has a valid protocol for browser use
*
* @param string $url url the secure
*
* @return string
*/
protected function makeSecureForwardUrl($url) {
$url = elgg_normalize_url($url);
if (!preg_match('/^(http|https|ftp|sftp|ftps):\/\//', $url)) {
return elgg_get_site_url();
}
return $url;
}
/**
* Closes the session
*
* Force closing the session so session is saved to the database before headers are sent
* preventing race conditions with session data
*
* @see https://github.com/Elgg/Elgg/issues/12348
*
* @return void
*/
protected function closeSession() {
$session = elgg_get_session();
if ($session->isStarted()) {
$session->save();
}
}
}