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