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