]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File_redirection.php
Merge branch 'direct-feed-sub' into 'master'
[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     protected $file; /* Cache the associated file sometimes */
43
44     public static function schemaDef()
45     {
46         return array(
47             'fields' => array(
48                 'urlhash' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'sha256 hash of the URL'),
49                 'url' => array('type' => 'text', '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('urlhash'),
56             'foreign keys' => array(
57                 'file_redirection_file_id_fkey' => array('file' => array('file_id' => 'id')),
58             ),
59         );
60     }
61
62     static public function getByUrl($url)
63     {
64         return self::getByPK(array('urlhash' => File::hashurl($url)));
65     }
66
67     static function _commonHttp($url, $redirs) {
68         $request = new HTTPClient($url);
69         $request->setConfig(array(
70             'connect_timeout' => 10, // # seconds to wait
71             'max_redirs' => $redirs, // # max number of http redirections to follow
72             'follow_redirects' => true, // Follow redirects
73             'store_body' => false, // We won't need body content here.
74         ));
75         return $request;
76     }
77
78     /**
79      * Check if this URL is a redirect and return redir info.
80      *
81      * Most code should call File_redirection::where instead, to check if we
82      * already know that redirection and avoid extra hits to the web.
83      *
84      * The URL is hit and any redirects are followed, up to 10 levels or until
85      * a protected URL is reached.
86      *
87      * @param string $in_url
88      * @return mixed one of:
89      *         string - target URL, if this is a direct link or can't be followed
90      *         array - redirect info if this is an *unknown* redirect:
91      *              associative array with the following elements:
92      *                code: HTTP status code
93      *                redirects: count of redirects followed
94      *                url: URL string of final target
95      *                type (optional): MIME type from Content-Type header
96      *                size (optional): byte size from Content-Length header
97      *                time (optional): timestamp from Last-Modified header
98      */
99     static function lookupWhere($short_url, $redirs = 10, $protected = false) {
100         if ($redirs < 0) return false;
101
102         if(strpos($short_url,'://') === false){
103             return $short_url;
104         }
105         try {
106             $request = self::_commonHttp($short_url, $redirs);
107             // Don't include body in output
108             $request->setMethod(HTTP_Request2::METHOD_HEAD);
109             $response = $request->send();
110
111             if (405 == $response->getStatus() || 204 == $response->getStatus()) {
112                 // HTTP 405 Unsupported Method
113                 // Server doesn't support HEAD method? Can this really happen?
114                 // We'll try again as a GET and ignore the response data.
115                 //
116                 // HTTP 204 No Content
117                 // YFrog sends 204 responses back for our HEAD checks, which
118                 // seems like it may be a logic error in their servers. If
119                 // we get a 204 back, re-run it as a GET... if there's really
120                 // no content it'll be cheap. :)
121                 $request = self::_commonHttp($short_url, $redirs);
122                 $response = $request->send();
123             }
124         } catch (Exception $e) {
125             // Invalid URL or failure to reach server
126             common_log(LOG_ERR, "Error while following redirects for $short_url: " . $e->getMessage());
127             return $short_url;
128         }
129
130         if ($response->getRedirectCount() && File::isProtected($response->getUrl())) {
131             // Bump back up the redirect chain until we find a non-protected URL
132             return self::lookupWhere($short_url, $response->getRedirectCount() - 1, true);
133         }
134
135         $ret = array('code' => $response->getStatus()
136                 , 'redirects' => $response->getRedirectCount()
137                 , 'url' => $response->getUrl());
138
139         $type = $response->getHeader('Content-Type');
140         if ($type) $ret['type'] = $type;
141         if ($protected) $ret['protected'] = true;
142         $size = $response->getHeader('Content-Length'); // @fixme bytes?
143         if ($size) $ret['size'] = $size;
144         $time = $response->getHeader('Last-Modified');
145         if ($time) $ret['time'] = strtotime($time);
146         return $ret;
147     }
148
149     /**
150      * Check if this URL is a redirect and return redir info.
151      * If a File record is present for this URL, it is not considered a redirect.
152      * If a File_redirection record is present for this URL, the recorded target is returned.
153      *
154      * If no File or File_redirect record is present, the URL is hit and any
155      * redirects are followed, up to 10 levels or until a protected URL is
156      * reached.
157      *
158      * @param string $in_url
159      * @param boolean $discover true to attempt dereferencing the redirect if we don't know it already
160      * @return File_redirection
161      */
162     static function where($in_url, $discover=true) {
163         $redir = new File_redirection();
164         $redir->url = $in_url;
165         $redir->urlhash = File::hashurl($redir->url);
166         $redir->redirections = 0;
167
168         try {
169             $r = File_redirection::getByUrl($in_url);
170             if($r instanceof File_redirection) {
171                 return $r;
172             }
173         } catch (NoResultException $e) {
174             try {
175                 $f = File::getByUrl($in_url);
176                 $redir->file_id = $f->id;
177                 $redir->file = $f;
178                 return $redir;
179             } catch (NoResultException $e) {
180                 // Oh well, let's keep going
181             }
182         }
183
184         if ($discover) {
185             $redir_info = File_redirection::lookupWhere($in_url);
186             if(is_string($redir_info)) {
187                 $redir_info = array('url' => $redir_info);
188             }
189
190             // Double check that we don't already have the resolved URL
191             $r = self::where($redir_info['url'], false);
192             if (!empty($r->file_id)) {
193                 return $r;
194             }
195         }
196
197         $redir->httpcode = $redir_info['code'];
198         $redir->redirections = intval($redir_info['redirects']);
199         $redir->file = new File();
200         $redir->file->url = $redir_info ? $redir_info['url'] : $in_url;
201         $redir->file->mimetype = $redir_info['type'];
202         $redir->file->size = $redir_info['size'];
203         $redir->file->date = $redir_info['time'];
204         if($redir_info['protected']) $redir->file->protected = true;
205
206         return $redir;
207     }
208
209     /**
210      * Shorten a URL with the current user's configured shortening
211      * options, if applicable.
212      *
213      * If it cannot be shortened or the "short" URL is longer than the
214      * original, the original is returned.
215      *
216      * If the referenced item has not been seen before, embedding data
217      * may be saved.
218      *
219      * @param string $long_url
220      * @param User $user whose shortening options to use; defaults to the current web session user
221      * @return string
222      */
223     static function makeShort($long_url, $user=null)
224     {
225         $canon = File_redirection::_canonUrl($long_url);
226
227         $short_url = File_redirection::_userMakeShort($canon, $user);
228
229         // Did we get one? Is it shorter?
230
231         return !empty($short_url) ? $short_url : $long_url;
232     }
233
234     /**
235      * Shorten a URL with the current user's configured shortening
236      * options, if applicable.
237      *
238      * If it cannot be shortened or the "short" URL is longer than the
239      * original, the original is returned.
240      *
241      * If the referenced item has not been seen before, embedding data
242      * may be saved.
243      *
244      * @param string $long_url
245      * @return string
246      */
247
248     static function forceShort($long_url, $user)
249     {
250         $canon = File_redirection::_canonUrl($long_url);
251
252         $short_url = File_redirection::_userMakeShort($canon, $user, true);
253
254         // Did we get one? Is it shorter?
255         return !empty($short_url) ? $short_url : $long_url;
256     }
257
258     static function _userMakeShort($long_url, User $user=null, $force = false) {
259         $short_url = common_shorten_url($long_url, $user, $force);
260         if (!empty($short_url) && $short_url != $long_url) {
261             $short_url = (string)$short_url;
262             // store it
263             $file = File::getKV('url', $long_url);
264             if (!$file instanceof File) {
265                 // Check if the target URL is itself a redirect...
266                 $redir = File_redirection::where($long_url);
267                 $file = $redir->getFile();
268                 if (empty($file->id)) {
269                     $file->saveFile();
270                 }
271             }
272             $file_redir = File_redirection::getKV('url', $short_url);
273             if (!$file_redir instanceof File_redirection) {
274                 $file_redir = new File_redirection;
275                 $file_redir->urlhash = File::hashurl($short_url);
276                 $file_redir->url = $short_url;
277                 $file_redir->file_id = $file->id;
278                 $file_redir->insert();
279             }
280             return $short_url;
281         }
282         return null;
283     }
284
285     /**
286      * Basic attempt to canonicalize a URL, cleaning up some standard variants
287      * such as funny syntax or a missing path. Used internally when cleaning
288      * up URLs for storage and following redirect chains.
289      *
290      * Note that despite being on File_redirect, this function DOES NOT perform
291      * any dereferencing of redirects.
292      *
293      * @param string $in_url input URL
294      * @param string $default_scheme if given a bare link; defaults to 'http://'
295      * @return string
296      */
297     static function _canonUrl($in_url, $default_scheme = 'http://') {
298         if (empty($in_url)) return false;
299         $out_url = $in_url;
300         $p = parse_url($out_url);
301         if (empty($p['host']) || empty($p['scheme'])) {
302             list($scheme) = explode(':', $in_url, 2);
303             switch (strtolower($scheme)) {
304             case 'fax':
305             case 'tel':
306                 $out_url = str_replace('.-()', '', $out_url);
307                 break;
308
309             case 'mailto':
310             case 'magnet':
311             case 'aim':
312             case 'jabber':
313             case 'xmpp':
314                 // don't touch anything
315                 break;
316
317             default:
318                 $out_url = $default_scheme . ltrim($out_url, '/');
319                 $p = parse_url($out_url);
320                 if (empty($p['scheme'])) return false;
321                 break;
322             }
323         }
324
325         if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
326             if (empty($p['host'])) return false;
327             if (empty($p['path'])) {
328                 $out_url .= '/';
329             }
330         }
331
332         return $out_url;
333     }
334
335     static function saveNew($data, $file_id, $url) {
336         $file_redir = new File_redirection;
337         $file_redir->urlhash = File::hashurl($url);
338         $file_redir->url = $url;
339         $file_redir->file_id = $file_id;
340         $file_redir->redirections = intval($data['redirects']);
341         $file_redir->httpcode = intval($data['code']);
342         $file_redir->insert();
343     }
344
345     static public function beforeSchemaUpdate()
346     {
347         $table = strtolower(get_called_class());
348         $schema = Schema::get();
349         $schemadef = $schema->getTableDef($table);
350
351         // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
352         if (isset($schemadef['fields']['urlhash']) && in_array('urlhash', $schemadef['primary key'])) {
353             // We already have the urlhash field, so no need to migrate it.
354             return;
355         }
356         echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
357         // We have to create a urlhash that is _not_ the primary key,
358         // transfer data and THEN run checkSchema
359         $schemadef['fields']['urlhash'] = array (
360                                               'type' => 'varchar',
361                                               'length' => 64,
362                                               'not null' => true,
363                                               'description' => 'sha256 hash of the URL',
364                                             );
365         $schemadef['fields']['url'] = array (
366                                               'type' => 'text',
367                                               'description' => 'short URL (or any other kind of redirect) for file (id)',
368                                             );
369         unset($schemadef['primary key']);
370         $schema->ensureTable($table, $schemadef);
371         echo "DONE.\n";
372
373         $classname = ucfirst($table);
374         $tablefix = new $classname;
375         // urlhash is hash('sha256', $url) in the File table
376         echo "Updating urlhash fields in $table table...";
377         // Maybe very MySQL specific :(
378         $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
379                             $schema->quoteIdentifier($table),
380                             'urlhash',
381                             // The line below is "result of sha256 on column `url`"
382                             'SHA2(url, 256)'));
383         echo "DONE.\n";
384         echo "Resuming core schema upgrade...";
385     }
386
387     public function getFile() {
388         if(empty($this->file) && $this->file_id) {
389             $this->file = File::getKV('id', $this->file_id);
390         }
391
392         return $this->file;
393     }
394 }