]> git.mxchange.org Git - friendica.git/blob - src/Util/Proxy.php
Merge remote-tracking branch 'upstream/develop' into server-detection
[friendica.git] / src / Util / Proxy.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Util;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\System;
26 use Friendica\DI;
27
28 /**
29  * Proxy utilities class
30  */
31 class Proxy
32 {
33         /**
34          * Sizes constants
35          */
36         const SIZE_MICRO  = 'micro'; // 48
37         const SIZE_THUMB  = 'thumb'; // 80
38         const SIZE_SMALL  = 'small'; // 300
39         const SIZE_MEDIUM = 'medium'; // 600
40         const SIZE_LARGE  = 'large'; // 1024
41
42         /**
43          * Pixel Sizes
44          */
45         const PIXEL_MICRO  = 48;
46         const PIXEL_THUMB  = 80;
47         const PIXEL_SMALL  = 300;
48         const PIXEL_MEDIUM = 600;
49         const PIXEL_LARGE  = 1024;
50
51         /**
52          * Accepted extensions
53          *
54          * @var array
55          * @todo Make this configurable?
56          */
57         private static $extensions = [
58                 'jpg',
59                 'jpeg',
60                 'gif',
61                 'png',
62         ];
63
64         /**
65          * Private constructor
66          */
67         private function __construct () {
68                 // No instances from utilities classes
69         }
70
71         /**
72          * Transform a remote URL into a local one.
73          *
74          * This function only performs the URL replacement on http URL and if the
75          * provided URL isn't local
76          *
77          * @param string $url       The URL to proxyfy
78          * @param string $size      One of the Proxy::SIZE_* constants
79          * @return string The proxyfied URL or relative path
80          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
81          */
82         public static function proxifyUrl(string $url, string $size = ''): string
83         {
84                 if (!DI::config()->get('system', 'proxify_content')) {
85                         return $url;
86                 }
87
88                 // Trim URL first
89                 $url = trim($url);
90
91                 // Quit if not an HTTP/HTTPS link or if local
92                 if (!in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https']) || self::isLocalImage($url)) {
93                         return $url;
94                 }
95
96                 // Image URL may have encoded ampersands for display which aren't desirable for proxy
97                 $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
98
99                 $shortpath = hash('md5', $url);
100                 $longpath = substr($shortpath, 0, 2);
101
102                 $longpath .= '/' . strtr(base64_encode($url), '+/', '-_');
103
104                 // Extract the URL extension
105                 $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
106
107                 if (in_array($extension, self::$extensions)) {
108                         $shortpath .= '.' . $extension;
109                         $longpath .= '.' . $extension;
110                 }
111
112                 $proxypath = DI::baseUrl() . '/proxy/' . $longpath;
113
114                 if ($size != '') {
115                         $size = ':' . $size;
116                 }
117
118                 Logger::info('Created proxy link', ['url' => $url, 'callstack' => System::callstack(20)]);
119
120                 // Too long files aren't supported by Apache
121                 if (strlen($proxypath) > 250) {
122                         return DI::baseUrl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
123                 } else {
124                         return $proxypath . $size;
125                 }
126         }
127
128         /**
129          * "Proxifies" HTML code's image tags
130          *
131          * "Proxifies", means replaces image URLs in given HTML code with those from
132          * proxy storage directory.
133          *
134          * @param string $html Un-proxified HTML code
135          * @return string Proxified HTML code
136          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
137          */
138         public static function proxifyHtml(string $html): string
139         {
140                 $html = str_replace(Strings::normaliseLink(DI::baseUrl()) . '/', DI::baseUrl() . '/', $html);
141
142                 return preg_replace_callback('/(<img [^>]*src *= *["\'])([^"\']+)(["\'][^>]*>)/siU', 'self::replaceUrl', $html);
143         }
144
145         /**
146          * Checks if the URL is a local URL.
147          *
148          * @param string $url
149          * @return boolean
150          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
151          */
152         public static function isLocalImage(string $url): bool
153         {
154                 if (substr($url, 0, 1) == '/') {
155                         return true;
156                 }
157
158                 if (strtolower(substr($url, 0, 5)) == 'data:') {
159                         return true;
160                 }
161
162                 return Network::isLocalLink($url);
163         }
164
165         /**
166          * Return the array of query string parameters from a URL
167          *
168          * @param string $url URL to parse
169          * @return array Associative array of query string parameters
170          */
171         private static function parseQuery(string $url): array
172         {
173                 $query = parse_url($url, PHP_URL_QUERY);
174                 $query = html_entity_decode($query);
175
176                 parse_str($query, $arr);
177
178                 return $arr;
179         }
180
181         /**
182          * Call-back method to replace the UR
183          *
184          * @param array $matches Matches from preg_replace_callback()
185          * @return string Proxified HTML image tag
186          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
187          */
188         private static function replaceUrl(array $matches): string
189         {
190                 // if the picture seems to be from another picture cache then take the original source
191                 $queryvar = self::parseQuery($matches[2]);
192
193                 if (!empty($queryvar['url']) && substr($queryvar['url'], 0, 4) == 'http') {
194                         $matches[2] = urldecode($queryvar['url']);
195                 }
196
197                 // Following line changed per bug #431
198                 if (self::isLocalImage($matches[2])) {
199                         return $matches[1] . $matches[2] . $matches[3];
200                 }
201
202                 // Return proxified HTML
203                 return $matches[1] . self::proxifyUrl(htmlspecialchars_decode($matches[2])) . $matches[3];
204         }
205
206 }