]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File_redirection.php
Merge branch '0.9.x' into 1.0.x
[quix0rs-gnu-social.git] / classes / File_redirection.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
23 require_once INSTALLDIR.'/classes/File.php';
24 require_once INSTALLDIR.'/classes/File_oembed.php';
25
26 define('USER_AGENT', 'StatusNet user agent / file probe');
27
28 /**
29  * Table Definition for file_redirection
30  */
31
32 class File_redirection extends Memcached_DataObject
33 {
34     ###START_AUTOCODE
35     /* the code below is auto generated do not remove the above tag */
36
37     public $__table = 'file_redirection';                // table name
38     public $url;                             // varchar(255)  primary_key not_null
39     public $file_id;                         // int(4)
40     public $redirections;                    // int(4)
41     public $httpcode;                        // int(4)
42     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
43
44     /* Static get */
45     function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('File_redirection',$k,$v); }
46
47     /* the code above is auto generated do not remove the tag below */
48     ###END_AUTOCODE
49
50     static function _commonHttp($url, $redirs) {
51         $request = new HTTPClient($url);
52         $request->setConfig(array(
53             'connect_timeout' => 10, // # seconds to wait
54             'max_redirs' => $redirs, // # max number of http redirections to follow
55             'follow_redirects' => true, // Follow redirects
56             'store_body' => false, // We won't need body content here.
57         ));
58         return $request;
59     }
60
61     /**
62      * Check if this URL is a redirect and return redir info.
63      *
64      * Most code should call File_redirection::where instead, to check if we
65      * already know that redirection and avoid extra hits to the web.
66      *
67      * The URL is hit and any redirects are followed, up to 10 levels or until
68      * a protected URL is reached.
69      *
70      * @param string $in_url
71      * @return mixed one of:
72      *         string - target URL, if this is a direct link or can't be followed
73      *         array - redirect info if this is an *unknown* redirect:
74      *              associative array with the following elements:
75      *                code: HTTP status code
76      *                redirects: count of redirects followed
77      *                url: URL string of final target
78      *                type (optional): MIME type from Content-Type header
79      *                size (optional): byte size from Content-Length header
80      *                time (optional): timestamp from Last-Modified header
81      */
82     public function lookupWhere($short_url, $redirs = 10, $protected = false) {
83         if ($redirs < 0) return false;
84
85         if(strpos($short_url,'://') === false){
86             return $short_url;
87         }
88         try {
89             $request = self::_commonHttp($short_url, $redirs);
90             // Don't include body in output
91             $request->setMethod(HTTP_Request2::METHOD_HEAD);
92             $response = $request->send();
93
94             if (405 == $response->getStatus()) {
95                 // Server doesn't support HEAD method? Can this really happen?
96                 // We'll try again as a GET and ignore the response data.
97                 $request = self::_commonHttp($short_url, $redirs);
98                 $response = $request->send();
99             }
100         } catch (Exception $e) {
101             // Invalid URL or failure to reach server
102             common_log(LOG_ERR, "Error while following redirects for $short_url: " . $e->getMessage());
103             return $short_url;
104         }
105
106         if ($response->getRedirectCount() && File::isProtected($response->getUrl())) {
107             // Bump back up the redirect chain until we find a non-protected URL
108             return self::lookupWhere($short_url, $response->getRedirectCount() - 1, true);
109         }
110
111         $ret = array('code' => $response->getStatus()
112                 , 'redirects' => $response->getRedirectCount()
113                 , 'url' => $response->getUrl());
114
115         $type = $response->getHeader('Content-Type');
116         if ($type) $ret['type'] = $type;
117         if ($protected) $ret['protected'] = true;
118         $size = $response->getHeader('Content-Length'); // @fixme bytes?
119         if ($size) $ret['size'] = $size;
120         $time = $response->getHeader('Last-Modified');
121         if ($time) $ret['time'] = strtotime($time);
122         return $ret;
123     }
124
125     /**
126      * Check if this URL is a redirect and return redir info.
127      * If a File record is present for this URL, it is not considered a redirect.
128      * If a File_redirection record is present for this URL, the recorded target is returned.
129      *
130      * If no File or File_redirect record is present, the URL is hit and any
131      * redirects are followed, up to 10 levels or until a protected URL is
132      * reached.
133      *
134      * @param string $in_url
135      * @return mixed one of:
136      *         string - target URL, if this is a direct link or a known redirect
137      *         array - redirect info if this is an *unknown* redirect:
138      *              associative array with the following elements:
139      *                code: HTTP status code
140      *                redirects: count of redirects followed
141      *                url: URL string of final target
142      *                type (optional): MIME type from Content-Type header
143      *                size (optional): byte size from Content-Length header
144      *                time (optional): timestamp from Last-Modified header
145      */
146     public function where($in_url) {
147         // let's see if we know this...
148         $a = File::staticGet('url', $in_url);
149
150         if (!empty($a)) {
151             // this is a direct link to $a->url
152             return $a->url;
153         } else {
154             $b = File_redirection::staticGet('url', $in_url);
155             if (!empty($b)) {
156                 // this is a redirect to $b->file_id
157                 $a = File::staticGet('id', $b->file_id);
158                 return $a->url;
159             }
160         }
161
162         $ret = File_redirection::lookupWhere($in_url);
163         return $ret;
164     }
165
166     /**
167      * Shorten a URL with the current user's configured shortening
168      * options, if applicable.
169      *
170      * If it cannot be shortened or the "short" URL is longer than the
171      * original, the original is returned.
172      *
173      * If the referenced item has not been seen before, embedding data
174      * may be saved.
175      *
176      * @param string $long_url
177      * @return string
178      */
179
180     function makeShort($long_url)
181     {
182         $canon = File_redirection::_canonUrl($long_url);
183
184         $short_url = File_redirection::_userMakeShort($canon);
185
186         // Did we get one? Is it shorter?
187
188         if (!empty($short_url)) {
189             return $short_url;
190         } else {
191             return $long_url;
192         }
193     }
194
195     /**
196      * Shorten a URL with the current user's configured shortening
197      * options, if applicable.
198      *
199      * If it cannot be shortened or the "short" URL is longer than the
200      * original, the original is returned.
201      *
202      * If the referenced item has not been seen before, embedding data
203      * may be saved.
204      *
205      * @param string $long_url
206      * @return string
207      */
208
209     function forceShort($long_url)
210     {
211         $canon = File_redirection::_canonUrl($long_url);
212
213         $short_url = File_redirection::_userMakeShort($canon, true);
214
215         // Did we get one? Is it shorter?
216         if (!empty($short_url)) {
217             return $short_url;
218         } else {
219             return $long_url;
220         }
221     }
222
223     function _userMakeShort($long_url, $force = false) {
224         $short_url = common_shorten_url($long_url, $force);
225         if (!empty($short_url) && $short_url != $long_url) {
226             $short_url = (string)$short_url;
227             // store it
228             $file = File::staticGet('url', $long_url);
229             if (empty($file)) {
230                 // Check if the target URL is itself a redirect...
231                 $redir_data = File_redirection::where($long_url);
232                 if (is_array($redir_data)) {
233                     // We haven't seen the target URL before.
234                     // Save file and embedding data about it!
235                     $file = File::saveNew($redir_data, $long_url);
236                     $file_id = $file->id;
237                     if (!empty($redir_data['oembed']['json'])) {
238                         File_oembed::saveNew($redir_data['oembed']['json'], $file_id);
239                     }
240                 } else if (is_string($redir_data)) {
241                     // The file is a known redirect target.
242                     $file = File::staticGet('url', $redir_data);
243                     if (empty($file)) {
244                         // @fixme should we save a new one?
245                         // this case was triggering sometimes for redirects
246                         // with unresolvable targets; found while fixing
247                         // "can't linkify" bugs with shortened links to
248                         // SSL sites with cert issues.
249                         return null;
250                     }
251                     $file_id = $file->id;
252                 }
253             } else {
254                 $file_id = $file->id;
255             }
256             $file_redir = File_redirection::staticGet('url', $short_url);
257             if (empty($file_redir)) {
258                 $file_redir = new File_redirection;
259                 $file_redir->url = $short_url;
260                 $file_redir->file_id = $file_id;
261                 $file_redir->insert();
262             }
263             return $short_url;
264         }
265         return null;
266     }
267
268     function _canonUrl($in_url, $default_scheme = 'http://') {
269         if (empty($in_url)) return false;
270         $out_url = $in_url;
271         $p = parse_url($out_url);
272         if (empty($p['host']) || empty($p['scheme'])) {
273             list($scheme) = explode(':', $in_url, 2);
274             switch ($scheme) {
275             case 'fax':
276             case 'tel':
277                 $out_url = str_replace('.-()', '', $out_url);
278                 break;
279
280             case 'mailto':
281             case 'aim':
282             case 'jabber':
283             case 'xmpp':
284                 // don't touch anything
285                 break;
286
287             default:
288                 $out_url = $default_scheme . ltrim($out_url, '/');
289                 $p = parse_url($out_url);
290                 if (empty($p['scheme'])) return false;
291                 break;
292             }
293         }
294
295         if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
296             if (empty($p['host'])) return false;
297             if (empty($p['path'])) {
298                 $out_url .= '/';
299             }
300         }
301
302         return $out_url;
303     }
304
305     function saveNew($data, $file_id, $url) {
306         $file_redir = new File_redirection;
307         $file_redir->url = $url;
308         $file_redir->file_id = $file_id;
309         $file_redir->redirections = intval($data['redirects']);
310         $file_redir->httpcode = intval($data['code']);
311         $file_redir->insert();
312     }
313 }