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