]> git.mxchange.org Git - friendica.git/blob - src/Util/Proxy.php
Differentiate between no description or an empty description
[friendica.git] / src / Util / Proxy.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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 use GuzzleHttp\Psr7\Uri;
28
29 /**
30  * Proxy utilities class
31  */
32 class Proxy
33 {
34         /**
35          * Sizes constants
36          */
37         const SIZE_MICRO  = 'micro'; // 48
38         const SIZE_THUMB  = 'thumb'; // 80
39         const SIZE_SMALL  = 'small'; // 300
40         const SIZE_MEDIUM = 'medium'; // 600
41         const SIZE_LARGE  = 'large'; // 1024
42
43         /**
44          * Pixel Sizes
45          */
46         const PIXEL_MICRO  = 48;
47         const PIXEL_THUMB  = 80;
48         const PIXEL_SMALL  = 300;
49         const PIXEL_MEDIUM = 600;
50         const PIXEL_LARGE  = 1024;
51
52         /**
53          * Accepted extensions
54          *
55          * @var array
56          * @todo Make this configurable?
57          */
58         private static $extensions = [
59                 'jpg',
60                 'jpeg',
61                 'gif',
62                 'png',
63         ];
64
65         /**
66          * Private constructor
67          */
68         private function __construct () {
69                 // No instances from utilities classes
70         }
71
72         /**
73          * Transform a remote URL into a local one.
74          *
75          * This function only performs the URL replacement on http URL and if the
76          * provided URL isn't local
77          *
78          * @param string $url       The URL to proxify
79          * @param string $size      One of the Proxy::SIZE_* constants
80          * @return string The proxified URL or relative path
81          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
82          */
83         public static function proxifyUrl(string $url, string $size = ''): string
84         {
85                 if (!DI::config()->get('system', 'proxify_content')) {
86                         return $url;
87                 }
88
89                 // Trim URL first
90                 $url = trim($url);
91
92                 // Quit if not an HTTP/HTTPS link or if local
93                 if (!in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https']) || self::isLocalImage($url)) {
94                         return $url;
95                 }
96
97                 // Image URL may have encoded ampersands for display which aren't desirable for proxy
98                 $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
99
100                 $shortpath = hash('md5', $url);
101                 $longpath = substr($shortpath, 0, 2);
102
103                 $longpath .= '/' . strtr(base64_encode($url), '+/', '-_');
104
105                 // Extract the URL extension
106                 $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
107
108                 if (in_array($extension, self::$extensions)) {
109                         $shortpath .= '.' . $extension;
110                         $longpath .= '.' . $extension;
111                 }
112
113                 $proxypath = DI::baseUrl() . '/proxy/' . $longpath;
114
115                 if ($size != '') {
116                         $size = ':' . $size;
117                 }
118
119                 Logger::info('Created proxy link', ['url' => $url, 'callstack' => System::callstack(20)]);
120
121                 // Too long files aren't supported by Apache
122                 if (strlen($proxypath) > 250) {
123                         return DI::baseUrl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
124                 } else {
125                         return $proxypath . $size;
126                 }
127         }
128
129         /**
130          * "Proxifies" HTML code's image tags
131          *
132          * "Proxifies", means replaces image URLs in given HTML code with those from
133          * proxy storage directory.
134          *
135          * @param string $html Un-proxified HTML code
136          *
137          * @return string Proxified HTML code
138          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
139          */
140         public static function proxifyHtml(string $html): string
141         {
142                 $html = str_replace(Strings::normaliseLink(DI::baseUrl()) . '/', DI::baseUrl() . '/', $html);
143
144                 return preg_replace_callback('/(<img [^>]*src *= *["\'])([^"\']+)(["\'][^>]*>)/siU', [self::class, 'replaceUrl'], $html);
145         }
146
147         /**
148          * Checks if the URL is a local URL.
149          *
150          * @param string $url
151          *
152          * @return boolean
153          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
154          */
155         public static function isLocalImage(string $url): bool
156         {
157                 if (substr($url, 0, 1) == '/') {
158                         return true;
159                 }
160
161                 if (strtolower(substr($url, 0, 5)) == 'data:') {
162                         return true;
163                 }
164
165                 return Network::isLocalLink($url);
166         }
167
168         /**
169          * Return the array of query string parameters from a URL
170          *
171          * @param string $url URL to parse
172          *
173          * @return array Associative array of query string parameters
174          */
175         private static function parseQuery(string $url): array
176         {
177                 try {
178                         $uri = new Uri($url);
179
180                         parse_str($uri->getQuery(), $arr);
181
182                         return $arr;
183                 } catch (\Throwable $e) {
184                         return [];
185                 }
186         }
187
188         /**
189          * Call-back method to replace the UR
190          *
191          * @param array $matches Matches from preg_replace_callback()
192          *
193          * @return string Proxified HTML image tag
194          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
195          */
196         private static function replaceUrl(array $matches): string
197         {
198                 // if the picture seems to be from another picture cache then take the original source
199                 $queryvar = self::parseQuery($matches[2]);
200
201                 if (!empty($queryvar['url']) && substr($queryvar['url'], 0, 4) == 'http') {
202                         $matches[2] = urldecode($queryvar['url']);
203                 }
204
205                 // Following line changed per bug #431
206                 if (self::isLocalImage($matches[2])) {
207                         return $matches[1] . $matches[2] . $matches[3];
208                 }
209
210                 // Return proxified HTML
211                 return $matches[1] . self::proxifyUrl(htmlspecialchars_decode($matches[2])) . $matches[3];
212         }
213
214 }