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