]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File_redirection.php
Merge branch 'master' into nightly
[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('GNUSOCIAL')) { exit(1); }
21
22 /**
23  * Table Definition for file_redirection
24  */
25
26 class File_redirection extends Managed_DataObject
27 {
28     ###START_AUTOCODE
29     /* the code below is auto generated do not remove the above tag */
30
31     public $__table = 'file_redirection';                // table name
32     public $urlhash;                         // varchar(64) primary_key not_null
33     public $url;                             // text
34     public $file_id;                         // int(4)
35     public $redirections;                    // int(4)
36     public $httpcode;                        // int(4)
37     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
38
39     /* the code above is auto generated do not remove the tag below */
40     ###END_AUTOCODE
41
42     public static function schemaDef()
43     {
44         return array(
45             'fields' => array(
46                 'urlhash' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'sha256 hash of the URL'),
47                 'url' => array('type' => 'text', 'description' => 'short URL (or any other kind of redirect) for file (id)'),
48                 'file_id' => array('type' => 'int', 'description' => 'short URL for what URL/file'),
49                 'redirections' => array('type' => 'int', 'description' => 'redirect count'),
50                 'httpcode' => array('type' => 'int', 'description' => 'HTTP status code (20x, 30x, etc.)'),
51                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
52             ),
53             'primary key' => array('urlhash'),
54             'foreign keys' => array(
55                 'file_redirection_file_id_fkey' => array('file' => array('file_id' => 'id')),
56             ),
57         );
58     }
59
60     static public function getByUrl($url)
61     {
62         return self::getByPK(array('urlhash' => File::hashurl($url)));
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     static 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     static function where($in_url, $discover=true) {
170         // let's see if we know this...
171         try {
172             $a = File::getByUrl($in_url);
173             // this is a direct link to $a->url
174             return $a->url;
175         } catch (NoResultException $e) {
176             try {
177                 $b = File_redirection::getByUrl($in_url);
178                 // this is a redirect to $b->file_id
179                 $a = File::getByID($b->file_id);
180                 return $a->url;
181             } catch (NoResultException $e) {
182                 // Oh well, let's keep going
183             }
184         }
185
186         if ($discover) {
187             $ret = File_redirection::lookupWhere($in_url);
188             return $ret;
189         }
190
191         // No manual dereferencing; leave the unknown URL as is.
192         return $in_url;
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      * @param User $user whose shortening options to use; defaults to the current web session user
207      * @return string
208      */
209     static function makeShort($long_url, $user=null)
210     {
211         $canon = File_redirection::_canonUrl($long_url);
212
213         $short_url = File_redirection::_userMakeShort($canon, $user);
214
215         // Did we get one? Is it shorter?
216
217         return !empty($short_url) ? $short_url : $long_url;
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     static 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         return !empty($short_url) ? $short_url : $long_url;
242     }
243
244     static function _userMakeShort($long_url, User $user=null, $force = false) {
245         $short_url = common_shorten_url($long_url, $user, $force);
246         if (!empty($short_url) && $short_url != $long_url) {
247             $short_url = (string)$short_url;
248             // store it
249             $file = File::getKV('url', $long_url);
250             if ($file instanceof File) {
251                 $file_id = $file->getID();
252             } else {
253                 // Check if the target URL is itself a redirect...
254                 $redir_data = File_redirection::where($long_url);
255                 if (is_array($redir_data)) {
256                     // We haven't seen the target URL before.
257                     // Save file and embedding data about it!
258                     $file = File::saveNew($redir_data, $long_url);
259                     $file_id = $file->getID();
260                 } else if (is_string($redir_data)) {
261                     // The file is a known redirect target.
262                     $file = File::getKV('url', $redir_data);
263                     if (empty($file)) {
264                         // @fixme should we save a new one?
265                         // this case was triggering sometimes for redirects
266                         // with unresolvable targets; found while fixing
267                         // "can't linkify" bugs with shortened links to
268                         // SSL sites with cert issues.
269                         return null;
270                     }
271                     $file_id = $file->getID();
272                 }
273             }
274             $file_redir = File_redirection::getKV('url', $short_url);
275             if (!$file_redir instanceof File_redirection) {
276                 $file_redir = new File_redirection;
277                 $file_redir->urlhash = File::hashurl($short_url);
278                 $file_redir->url = $short_url;
279                 $file_redir->file_id = $file_id;
280                 $file_redir->insert();
281             }
282             return $short_url;
283         }
284         return null;
285     }
286
287     /**
288      * Basic attempt to canonicalize a URL, cleaning up some standard variants
289      * such as funny syntax or a missing path. Used internally when cleaning
290      * up URLs for storage and following redirect chains.
291      *
292      * Note that despite being on File_redirect, this function DOES NOT perform
293      * any dereferencing of redirects.
294      *
295      * @param string $in_url input URL
296      * @param string $default_scheme if given a bare link; defaults to 'http://'
297      * @return string
298      */
299     static function _canonUrl($in_url, $default_scheme = 'http://') {
300         if (empty($in_url)) return false;
301         $out_url = $in_url;
302         $p = parse_url($out_url);
303         if (empty($p['host']) || empty($p['scheme'])) {
304             list($scheme) = explode(':', $in_url, 2);
305             switch (strtolower($scheme)) {
306             case 'fax':
307             case 'tel':
308                 $out_url = str_replace('.-()', '', $out_url);
309                 break;
310
311             case 'mailto':
312             case 'magnet':
313             case 'aim':
314             case 'jabber':
315             case 'xmpp':
316                 // don't touch anything
317                 break;
318
319             default:
320                 $out_url = $default_scheme . ltrim($out_url, '/');
321                 $p = parse_url($out_url);
322                 if (empty($p['scheme'])) return false;
323                 break;
324             }
325         }
326
327         if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
328             if (empty($p['host'])) return false;
329             if (empty($p['path'])) {
330                 $out_url .= '/';
331             }
332         }
333
334         return $out_url;
335     }
336
337     static function saveNew($data, $file_id, $url) {
338         $file_redir = new File_redirection;
339         $file_redir->urlhash = File::hashurl($short_url);
340         $file_redir->url = $url;
341         $file_redir->file_id = $file_id;
342         $file_redir->redirections = intval($data['redirects']);
343         $file_redir->httpcode = intval($data['code']);
344         $file_redir->insert();
345     }
346
347     static public function beforeSchemaUpdate()
348     {
349         $table = strtolower(get_called_class());
350         $schema = Schema::get();
351         $schemadef = $schema->getTableDef($table);
352
353         // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
354         if (isset($schemadef['fields']['urlhash']) && in_array('urlhash', $schemadef['primary key'])) {
355             // We already have the urlhash field, so no need to migrate it.
356             return;
357         }
358         echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
359         // We have to create a urlhash that is _not_ the primary key,
360         // transfer data and THEN run checkSchema
361         $schemadef['fields']['urlhash'] = array (
362                                               'type' => 'varchar',
363                                               'length' => 64,
364                                               'not null' => true,
365                                               'description' => 'sha256 hash of the URL',
366                                             );
367         $schemadef['fields']['url'] = array (
368                                               'type' => 'text',
369                                               'description' => 'short URL (or any other kind of redirect) for file (id)',
370                                             );
371         unset($schemadef['primary key']);
372         $schema->ensureTable($table, $schemadef);
373         echo "DONE.\n";
374
375         $classname = ucfirst($table);
376         $tablefix = new $classname;
377         // urlhash is hash('sha256', $url) in the File table
378         echo "Updating urlhash fields in $table table...";
379         // Maybe very MySQL specific :(
380         $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
381                             $schema->quoteIdentifier($table),
382                             'urlhash',
383                             // The line below is "result of sha256 on column `url`"
384                             'SHA2(url, 256)'));
385         echo "DONE.\n";
386         echo "Resuming core schema upgrade...";
387     }
388 }