-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
GetImageUrlController.php
93 lines (80 loc) · 2.47 KB
/
GetImageUrlController.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
<?php
/*
* This file is part of fof/secure-https.
*
* Copyright (c) FriendsOfFlarum.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FoF\SecureHttps\Api\Controllers;
use Flarum\Http\RequestUtil;
use Flarum\User\User;
use FoF\SecureHttps\Exceptions\ImageNotFoundException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
class GetImageUrlController implements RequestHandlerInterface
{
/**
* Handle the request and return a response.
*
* @param ServerRequestInterface $request
*
* @throws \Flarum\User\Exception\PermissionDeniedException
*
* @return ResponseInterface
*/
public function handle(ServerRequestInterface $request): ResponseInterface
{
/**
* @var User
*/
$actor = RequestUtil::getActor($request);
$actor->assertCan('viewDiscussions');
$imgurl = urldecode(Arr::get($request->getQueryParams(), 'imgurl'));
$host = parse_url($imgurl, PHP_URL_HOST);
$isIP = filter_var(
$host,
FILTER_VALIDATE_IP
);
$isPublicIP = filter_var(
$host,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
);
if (!preg_match('/^https?:\/\//', $imgurl) || ($isIP && !$isPublicIP)) {
throw new ImageNotFoundException();
}
$client = new Client();
try {
$res = $client->request('GET', $imgurl, [
'headers' => [
'Accept' => 'image/*',
],
]);
} catch (GuzzleException $e) {
if ($e->getCode() > 0 && $e->getCode() < 500) {
throw new ImageNotFoundException();
}
throw $e;
}
$type = $res->getHeaderLine('Content-Type');
$contents = $res->getBody();
if (!Str::startsWith($type, 'image/') || !$contents->getSize()) {
throw new ImageNotFoundException();
}
return new Response(
$res->getStatusCode(),
[
'Content-Type' => $res->getHeaderLine('Content-Type'),
],
$contents
);
}
}