Merge pull request #6507 from annando/composer
[friendica.git/.git] / src / Util / Proxy.php
1 <?php
2
3 namespace Friendica\Util;
4
5 use Friendica\BaseObject;
6 use Friendica\Core\Config;
7 use Friendica\Core\System;
8
9 /**
10  * @brief Proxy utilities class
11  */
12 class Proxy
13 {
14
15         /**
16          * Default time to keep images in proxy storage
17          */
18         const DEFAULT_TIME = 86400; // 1 Day
19
20         /**
21          * Sizes constants
22          */
23         const SIZE_MICRO  = 'micro';
24         const SIZE_THUMB  = 'thumb';
25         const SIZE_SMALL  = 'small';
26         const SIZE_MEDIUM = 'medium';
27         const SIZE_LARGE  = 'large';
28
29         /**
30          * Accepted extensions
31          *
32          * @var array
33          * @todo Make this configurable?
34          */
35         private static $extensions = [
36                 'jpg',
37                 'jpeg',
38                 'gif',
39                 'png',
40         ];
41
42         /**
43          * @brief Private constructor
44          */
45         private function __construct () {
46                 // No instances from utilities classes
47         }
48
49         /**
50          * @brief Transform a remote URL into a local one.
51          *
52          * This function only performs the URL replacement on http URL and if the
53          * provided URL isn't local, "the isn't deactivated" (sic) and if the config
54          * system.proxy_disabled is set to false.
55          *
56          * @param string $url       The URL to proxyfy
57          * @param bool   $writemode Returns a local path the remote URL should be saved to
58          * @param string $size      One of the ProxyUtils::SIZE_* constants
59          *
60          * @return string The proxyfied URL or relative path
61          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
62          */
63         public static function proxifyUrl($url, $writemode = false, $size = '')
64         {
65                 // Get application instance
66                 $a = BaseObject::getApp();
67
68                 // Trim URL first
69                 $url = trim($url);
70
71                 // Is no http in front of it?
72                 /// @TODO To weak test for being a valid URL
73                 if (substr($url, 0, 4) !== 'http') {
74                         return $url;
75                 }
76
77                 // Only continue if it isn't a local image and the isn't deactivated
78                 if (self::isLocalImage($url)) {
79                         $url = str_replace(Strings::normaliseLink(System::baseUrl()) . '/', System::baseUrl() . '/', $url);
80                         return $url;
81                 }
82
83                 // Is the proxy disabled?
84                 if (Config::get('system', 'proxy_disabled')) {
85                         return $url;
86                 }
87
88                 // Image URL may have encoded ampersands for display which aren't desirable for proxy
89                 $url = html_entity_decode($url, ENT_NOQUOTES, 'utf-8');
90
91                 // Creating a sub directory to reduce the amount of files in the cache directory
92                 $basepath = $a->getBasePath() . '/proxy';
93
94                 $shortpath = hash('md5', $url);
95                 $longpath = substr($shortpath, 0, 2);
96
97                 if (is_dir($basepath) && $writemode && !is_dir($basepath . '/' . $longpath)) {
98                         mkdir($basepath . '/' . $longpath);
99                         chmod($basepath . '/' . $longpath, 0777);
100                 }
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 = System::baseUrl() . '/proxy/' . $longpath;
113
114                 if ($size != '') {
115                         $size = ':' . $size;
116                 }
117
118                 // Too long files aren't supported by Apache
119                 // Writemode in combination with long files shouldn't be possible
120                 if ((strlen($proxypath) > 250) && $writemode) {
121                         return $shortpath;
122                 } elseif (strlen($proxypath) > 250) {
123                         return System::baseUrl() . '/proxy/' . $shortpath . '?url=' . urlencode($url);
124                 } elseif ($writemode) {
125                         return $longpath;
126                 } else {
127                         return $proxypath . $size;
128                 }
129         }
130
131         /**
132          * @brief "Proxifies" HTML code's image tags
133          *
134          * "Proxifies", means replaces image URLs in given HTML code with those from
135          * proxy storage directory.
136          *
137          * @param string $html Un-proxified HTML code
138          *
139          * @return string Proxified HTML code
140          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
141          */
142         public static function proxifyHtml($html)
143         {
144                 $html = str_replace(Strings::normaliseLink(System::baseUrl()) . '/', System::baseUrl() . '/', $html);
145
146                 return preg_replace_callback('/(<img [^>]*src *= *["\'])([^"\']+)(["\'][^>]*>)/siU', 'self::replaceUrl', $html);
147         }
148
149         /**
150          * @brief Checks if the URL is a local URL.
151          *
152          * @param string $url
153          * @return boolean
154          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
155          */
156         private static function isLocalImage($url)
157         {
158                 if (substr($url, 0, 1) == '/') {
159                         return true;
160                 }
161
162                 if (strtolower(substr($url, 0, 5)) == 'data:') {
163                         return true;
164                 }
165
166                 // links normalised - bug #431
167                 $baseurl = Strings::normaliseLink(System::baseUrl());
168                 $url = Strings::normaliseLink($url);
169
170                 return (substr($url, 0, strlen($baseurl)) == $baseurl);
171         }
172
173         /**
174          * @brief Return the array of query string parameters from a URL
175          *
176          * @param string $url URL to parse
177          * @return array Associative array of query string parameters
178          */
179         private static function parseQuery($url)
180         {
181                 $query = parse_url($url, PHP_URL_QUERY);
182                 $query = html_entity_decode($query);
183
184                 parse_str($query, $arr);
185
186                 return $arr;
187         }
188
189         /**
190          * @brief Call-back method to replace the UR
191          *
192          * @param array $matches Matches from preg_replace_callback()
193          * @return string Proxified HTML image tag
194          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
195          */
196         private static function replaceUrl(array $matches)
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 }