]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File_redirection.php
Merge commit 'refs/merge-requests/157' of git://gitorious.org/statusnet/mainline...
[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 /**
27  * Table Definition for file_redirection
28  */
29
30 class File_redirection extends Memcached_DataObject
31 {
32     ###START_AUTOCODE
33     /* the code below is auto generated do not remove the above tag */
34
35     public $__table = 'file_redirection';                // table name
36     public $url;                             // varchar(255)  primary_key not_null
37     public $file_id;                         // int(4)
38     public $redirections;                    // int(4)
39     public $httpcode;                        // int(4)
40     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
41
42     /* Static get */
43     function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('File_redirection',$k,$v); }
44
45     /* the code above is auto generated do not remove the tag below */
46     ###END_AUTOCODE
47
48     static function _commonHttp($url, $redirs) {
49         $request = new HTTPClient($url);
50         $request->setConfig(array(
51             'connect_timeout' => 10, // # seconds to wait
52             'max_redirs' => $redirs, // # max number of http redirections to follow
53             'follow_redirects' => true, // Follow redirects
54             'store_body' => false, // We won't need body content here.
55         ));
56         return $request;
57     }
58
59     /**
60      * Check if this URL is a redirect and return redir info.
61      *
62      * Most code should call File_redirection::where instead, to check if we
63      * already know that redirection and avoid extra hits to the web.
64      *
65      * The URL is hit and any redirects are followed, up to 10 levels or until
66      * a protected URL is reached.
67      *
68      * @param string $in_url
69      * @return mixed one of:
70      *         string - target URL, if this is a direct link or can't be followed
71      *         array - redirect info if this is an *unknown* redirect:
72      *              associative array with the following elements:
73      *                code: HTTP status code
74      *                redirects: count of redirects followed
75      *                url: URL string of final target
76      *                type (optional): MIME type from Content-Type header
77      *                size (optional): byte size from Content-Length header
78      *                time (optional): timestamp from Last-Modified header
79      */
80     public function lookupWhere($short_url, $redirs = 10, $protected = false) {
81         if ($redirs < 0) return false;
82
83         if(strpos($short_url,'://') === false){
84             return $short_url;
85         }
86         try {
87             $request = self::_commonHttp($short_url, $redirs);
88             // Don't include body in output
89             $request->setMethod(HTTP_Request2::METHOD_HEAD);
90             $response = $request->send();
91
92             if (405 == $response->getStatus() || 204 == $response->getStatus()) {
93                 // HTTP 405 Unsupported Method
94                 // Server doesn't support HEAD method? Can this really happen?
95                 // We'll try again as a GET and ignore the response data.
96                 //
97                 // HTTP 204 No Content
98                 // YFrog sends 204 responses back for our HEAD checks, which
99                 // seems like it may be a logic error in their servers. If
100                 // we get a 204 back, re-run it as a GET... if there's really
101                 // no content it'll be cheap. :)
102                 $request = self::_commonHttp($short_url, $redirs);
103                 $response = $request->send();
104             }
105         } catch (Exception $e) {
106             // Invalid URL or failure to reach server
107             common_log(LOG_ERR, "Error while following redirects for $short_url: " . $e->getMessage());
108             return $short_url;
109         }
110
111         if ($response->getRedirectCount() && File::isProtected($response->getUrl())) {
112             // Bump back up the redirect chain until we find a non-protected URL
113             return self::lookupWhere($short_url, $response->getRedirectCount() - 1, true);
114         }
115
116         $ret = array('code' => $response->getStatus()
117                 , 'redirects' => $response->getRedirectCount()
118                 , 'url' => $response->getUrl());
119
120         $type = $response->getHeader('Content-Type');
121         if ($type) $ret['type'] = $type;
122         if ($protected) $ret['protected'] = true;
123         $size = $response->getHeader('Content-Length'); // @fixme bytes?
124         if ($size) $ret['size'] = $size;
125         $time = $response->getHeader('Last-Modified');
126         if ($time) $ret['time'] = strtotime($time);
127         return $ret;
128     }
129
130     /**
131      * Check if this URL is a redirect and return redir info.
132      * If a File record is present for this URL, it is not considered a redirect.
133      * If a File_redirection record is present for this URL, the recorded target is returned.
134      *
135      * If no File or File_redirect record is present, the URL is hit and any
136      * redirects are followed, up to 10 levels or until a protected URL is
137      * reached.
138      *
139      * @param string $in_url
140      * @param boolean $discover true to attempt dereferencing the redirect if we don't know it already
141      * @return mixed one of:
142      *         string - target URL, if this is a direct link or a known redirect
143      *         array - redirect info if this is an *unknown* redirect:
144      *              associative array with the following elements:
145      *                code: HTTP status code
146      *                redirects: count of redirects followed
147      *                url: URL string of final target
148      *                type (optional): MIME type from Content-Type header
149      *                size (optional): byte size from Content-Length header
150      *                time (optional): timestamp from Last-Modified header
151      */
152     public function where($in_url, $discover=true) {
153         // let's see if we know this...
154         $a = File::staticGet('url', $in_url);
155
156         if (!empty($a)) {
157             // this is a direct link to $a->url
158             return $a->url;
159         } else {
160             $b = File_redirection::staticGet('url', $in_url);
161             if (!empty($b)) {
162                 // this is a redirect to $b->file_id
163                 $a = File::staticGet('id', $b->file_id);
164                 return $a->url;
165             }
166         }
167
168         if ($discover) {
169             $ret = File_redirection::lookupWhere($in_url);
170             return $ret;
171         } else {
172             // No manual dereferencing; leave the unknown URL as is.
173             return $in_url;
174         }
175     }
176
177     /**
178      * Shorten a URL with the current user's configured shortening
179      * options, if applicable.
180      *
181      * If it cannot be shortened or the "short" URL is longer than the
182      * original, the original is returned.
183      *
184      * If the referenced item has not been seen before, embedding data
185      * may be saved.
186      *
187      * @param string $long_url
188      * @param User $user whose shortening options to use; defaults to the current web session user
189      * @return string
190      */
191     function makeShort($long_url, $user=null)
192     {
193         $canon = File_redirection::_canonUrl($long_url);
194
195         $short_url = File_redirection::_userMakeShort($canon, $user);
196
197         // Did we get one? Is it shorter?
198
199         if (!empty($short_url)) {
200             return $short_url;
201         } else {
202             return $long_url;
203         }
204     }
205
206     /**
207      * Shorten a URL with the current user's configured shortening
208      * options, if applicable.
209      *
210      * If it cannot be shortened or the "short" URL is longer than the
211      * original, the original is returned.
212      *
213      * If the referenced item has not been seen before, embedding data
214      * may be saved.
215      *
216      * @param string $long_url
217      * @return string
218      */
219
220     function forceShort($long_url, $user)
221     {
222         $canon = File_redirection::_canonUrl($long_url);
223
224         $short_url = File_redirection::_userMakeShort($canon, $user, true);
225
226         // Did we get one? Is it shorter?
227         if (!empty($short_url)) {
228             return $short_url;
229         } else {
230             return $long_url;
231         }
232     }
233
234     function _userMakeShort($long_url, User $user=null, $force = false) {
235         $short_url = common_shorten_url($long_url, $user, $force);
236         if (!empty($short_url) && $short_url != $long_url) {
237             $short_url = (string)$short_url;
238             // store it
239             $file = File::staticGet('url', $long_url);
240             if (empty($file)) {
241                 // Check if the target URL is itself a redirect...
242                 $redir_data = File_redirection::where($long_url);
243                 if (is_array($redir_data)) {
244                     // We haven't seen the target URL before.
245                     // Save file and embedding data about it!
246                     $file = File::saveNew($redir_data, $long_url);
247                     $file_id = $file->id;
248                     if (!empty($redir_data['oembed']['json'])) {
249                         File_oembed::saveNew($redir_data['oembed']['json'], $file_id);
250                     }
251                 } else if (is_string($redir_data)) {
252                     // The file is a known redirect target.
253                     $file = File::staticGet('url', $redir_data);
254                     if (empty($file)) {
255                         // @fixme should we save a new one?
256                         // this case was triggering sometimes for redirects
257                         // with unresolvable targets; found while fixing
258                         // "can't linkify" bugs with shortened links to
259                         // SSL sites with cert issues.
260                         return null;
261                     }
262                     $file_id = $file->id;
263                 }
264             } else {
265                 $file_id = $file->id;
266             }
267             $file_redir = File_redirection::staticGet('url', $short_url);
268             if (empty($file_redir)) {
269                 $file_redir = new File_redirection;
270                 $file_redir->url = $short_url;
271                 $file_redir->file_id = $file_id;
272                 $file_redir->insert();
273             }
274             return $short_url;
275         }
276         return null;
277     }
278
279     /**
280      * Basic attempt to canonicalize a URL, cleaning up some standard variants
281      * such as funny syntax or a missing path. Used internally when cleaning
282      * up URLs for storage and following redirect chains.
283      *
284      * Note that despite being on File_redirect, this function DOES NOT perform
285      * any dereferencing of redirects.
286      *
287      * @param string $in_url input URL
288      * @param string $default_scheme if given a bare link; defaults to 'http://'
289      * @return string
290      */
291     function _canonUrl($in_url, $default_scheme = 'http://') {
292         if (empty($in_url)) return false;
293         $out_url = $in_url;
294         $p = parse_url($out_url);
295         if (empty($p['host']) || empty($p['scheme'])) {
296             list($scheme) = explode(':', $in_url, 2);
297             switch ($scheme) {
298             case 'fax':
299             case 'tel':
300                 $out_url = str_replace('.-()', '', $out_url);
301                 break;
302
303             case 'mailto':
304             case 'aim':
305             case 'jabber':
306             case 'xmpp':
307                 // don't touch anything
308                 break;
309
310             default:
311                 $out_url = $default_scheme . ltrim($out_url, '/');
312                 $p = parse_url($out_url);
313                 if (empty($p['scheme'])) return false;
314                 break;
315             }
316         }
317
318         if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
319             if (empty($p['host'])) return false;
320             if (empty($p['path'])) {
321                 $out_url .= '/';
322             }
323         }
324
325         return $out_url;
326     }
327
328     function saveNew($data, $file_id, $url) {
329         $file_redir = new File_redirection;
330         $file_redir->url = $url;
331         $file_redir->file_id = $file_id;
332         $file_redir->redirections = intval($data['redirects']);
333         $file_redir->httpcode = intval($data['code']);
334         $file_redir->insert();
335     }
336 }