]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File_redirection.php
Merge branch 'master' into mmn_fixes
[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' => false, // We follow redirects ourselves in lib/httpclient.php
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             } elseif (400 == $response->getStatus()) {
124                 throw new Exception('Got error 400 on HEAD request, will not go further.');
125             }
126         } catch (Exception $e) {
127             // Invalid URL or failure to reach server
128             common_log(LOG_ERR, "Error while following redirects for $short_url: " . $e->getMessage());
129             return $short_url;
130         }
131         
132                 // if last url after all redirections is protected, 
133                 // use the url before it in the redirection chain
134         if ($response->getRedirectCount() && File::isProtected($response->getEffectiveUrl())) {
135                         $return_url = $response->redirUrls[$response->getRedirectCount()-1];
136         } else {
137                         $return_url = $response->getEffectiveUrl();
138         }
139
140         $ret = array('code' => $response->getStatus()
141                 , 'redirects' => $response->getRedirectCount()
142                 , 'url' => $return_url);
143
144         $type = $response->getHeader('Content-Type');
145         if ($type) $ret['type'] = $type;
146         if ($protected) $ret['protected'] = true;
147         $size = $response->getHeader('Content-Length'); // @fixme bytes?
148         if ($size) $ret['size'] = $size;
149         $time = $response->getHeader('Last-Modified');
150         if ($time) $ret['time'] = strtotime($time);
151         return $ret;
152     }
153
154     /**
155      * Check if this URL is a redirect and return redir info.
156      * If a File record is present for this URL, it is not considered a redirect.
157      * If a File_redirection record is present for this URL, the recorded target is returned.
158      *
159      * If no File or File_redirect record is present, the URL is hit and any
160      * redirects are followed, up to 10 levels or until a protected URL is
161      * reached.
162      *
163      * @param string $in_url
164      * @param boolean $discover true to attempt dereferencing the redirect if we don't know it already
165      * @return File_redirection
166      */
167     static function where($in_url, $discover=true) {
168         $redir = new File_redirection();
169         $redir->url = $in_url;
170         $redir->urlhash = File::hashurl($redir->url);
171         $redir->redirections = 0;
172
173         try {
174             $r = File_redirection::getByUrl($in_url);
175
176             $f = File::getKV('id',$r->file_id);
177
178             if($file instanceof File) {
179                 $r->file = $f;
180                 $r->redir_url = $f->url;            
181             } else {
182                 // Invalid entry, delete and run again
183                 common_log(LOG_ERR, "Could not find File with id=".$r->file_id." referenced in File_redirection, deleting File redirection entry and and trying again...");                 
184                 $r->delete();
185                 return self::where($in_url);            
186             }
187             
188             // File_redirecion and File record found, return both
189             return $r;
190             
191         } catch (NoResultException $e) {
192             // File_redirecion record not found, but this might be a direct link to a file
193             try {
194                 $f = File::getByUrl($in_url);
195                 $redir->file_id = $f->id;
196                 $redir->file = $f;
197                 return $redir;
198             } catch (NoResultException $e) {                    
199                 // nope, this was not a direct link to a file either, let's keep going
200             }
201         }
202
203         if ($discover) {    
204             // try to follow redirects and get the final url        
205             $redir_info = File_redirection::lookupWhere($in_url);
206             if(is_string($redir_info)) {
207                 $redir_info = array('url' => $redir_info);
208             }
209             
210             // the last url in the redirection chain can actually be a redirect!
211             // this is the case with local /attachment/{file_id} links
212             // in that case we have the file id already
213             try {
214                 $r = File_redirection::getByUrl($redir_info['url']);
215                 
216                 $f = File::getKV('id',$r->file_id);
217                 
218                 if($f instanceof File) {
219                     $redir->file = $f;
220                     $redir->redir_url = $f->url;                
221                 } else {
222                     // Invalid entry in File_redirection, delete and run again
223                     common_log(LOG_ERR, "Could not find File with id=".$r->file_id." referenced in File_redirection, deleting File_redirection entry and trying again...");                 
224                     $r->delete();
225                     return self::where($in_url);                
226                 }
227             } catch (NoResultException $e) {
228                 // save the file now when we know that we don't have it in File_redirection
229                 try {
230                     $redir->file = File::saveNew($redir_info,$redir_info['url']);
231                 } catch (ServerException $e) {
232                     common_log(LOG_ERR, $e);
233                 }   
234             }
235              
236             // If this is a redirection and we have a file to redirect to, save it
237             // (if it doesn't exist in File_redirection already)            
238             if($redir->file instanceof File && $redir_info['url'] != $in_url) {
239                 try {
240                     $file_redir = File_redirection::getByUrl($in_url);
241                 } catch (NoResultException $e) {
242                     $file_redir = new File_redirection();
243                     $file_redir->urlhash = File::hashurl($in_url);
244                     $file_redir->url = $in_url;
245                     $file_redir->file_id = $redir->file->getID();
246                     $file_redir->insert();
247                     $file_redir->redir_url = $redir->file->url;                 
248                 }       
249
250                 $file_redir->file = $redir->file;       
251                 return $file_redir; 
252             } 
253         }
254
255         return $redir;
256     }
257
258     /**
259      * Shorten a URL with the current user's configured shortening
260      * options, if applicable.
261      *
262      * If it cannot be shortened or the "short" URL is longer than the
263      * original, the original is returned.
264      *
265      * If the referenced item has not been seen before, embedding data
266      * may be saved.
267      *
268      * @param string $long_url
269      * @param User $user whose shortening options to use; defaults to the current web session user
270      * @return string
271      */
272     static function makeShort($long_url, $user=null)
273     {
274         $canon = File_redirection::_canonUrl($long_url);
275
276         $short_url = File_redirection::_userMakeShort($canon, $user);
277
278         // Did we get one? Is it shorter?
279
280         return !empty($short_url) ? $short_url : $long_url;
281     }
282
283     /**
284      * Shorten a URL with the current user's configured shortening
285      * options, if applicable.
286      *
287      * If it cannot be shortened or the "short" URL is longer than the
288      * original, the original is returned.
289      *
290      * If the referenced item has not been seen before, embedding data
291      * may be saved.
292      *
293      * @param string $long_url
294      * @return string
295      */
296
297     static function forceShort($long_url, $user)
298     {
299         $canon = File_redirection::_canonUrl($long_url);
300
301         $short_url = File_redirection::_userMakeShort($canon, $user, true);
302
303         // Did we get one? Is it shorter?
304         return !empty($short_url) ? $short_url : $long_url;
305     }
306
307     static function _userMakeShort($long_url, User $user=null, $force = false) {
308         $short_url = common_shorten_url($long_url, $user, $force);
309         if (!empty($short_url) && $short_url != $long_url) {
310             $short_url = (string)$short_url;
311             // store it
312             try {
313                 $file = File::getByUrl($long_url);
314             } catch (NoResultException $e) {
315                 // Check if the target URL is itself a redirect...
316                 // This should already have happened in processNew in common_shorten_url()
317                 $redir = File_redirection::where($long_url);
318                 $file = $redir->file;
319             }
320             // Now we definitely have a File object in $file
321             try {
322                 $file_redir = File_redirection::getByUrl($short_url);
323             } catch (NoResultException $e) {
324                 $file_redir = new File_redirection();
325                 $file_redir->urlhash = File::hashurl($short_url);
326                 $file_redir->url = $short_url;
327                 $file_redir->file_id = $file->getID();
328                 $file_redir->insert();
329             }
330             return $short_url;
331         }
332         return null;
333     }
334
335     /**
336      * Basic attempt to canonicalize a URL, cleaning up some standard variants
337      * such as funny syntax or a missing path. Used internally when cleaning
338      * up URLs for storage and following redirect chains.
339      *
340      * Note that despite being on File_redirect, this function DOES NOT perform
341      * any dereferencing of redirects.
342      *
343      * @param string $in_url input URL
344      * @param string $default_scheme if given a bare link; defaults to 'http://'
345      * @return string
346      */
347     static function _canonUrl($in_url, $default_scheme = 'http://') {
348         if (empty($in_url)) return false;
349         $out_url = $in_url;
350         $p = parse_url($out_url);
351         if (empty($p['host']) || empty($p['scheme'])) {
352             list($scheme) = explode(':', $in_url, 2);
353             switch (strtolower($scheme)) {
354             case 'fax':
355             case 'tel':
356                 $out_url = str_replace('.-()', '', $out_url);
357                 break;
358
359             // non-HTTP schemes, so no redirects
360             case 'bitcoin':
361             case 'mailto':
362             case 'aim':
363             case 'jabber':
364             case 'xmpp':
365                 // don't touch anything
366                 break;
367
368             // URLs without domain name, so no redirects
369             case 'magnet':
370                 // don't touch anything
371                 break;
372
373             // URLs with coordinates, not browsable domain names
374             case 'geo':
375                 // don't touch anything
376                 break;
377
378             default:
379                 $out_url = $default_scheme . ltrim($out_url, '/');
380                 $p = parse_url($out_url);
381                 if (empty($p['scheme'])) return false;
382                 break;
383             }
384         }
385
386         if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
387             if (empty($p['host'])) return false;
388             if (empty($p['path'])) {
389                 $out_url .= '/';
390             }
391         }
392
393         return $out_url;
394     }
395
396     static function saveNew($data, $file_id, $url) {
397         $file_redir = new File_redirection;
398         $file_redir->urlhash = File::hashurl($url);
399         $file_redir->url = $url;
400         $file_redir->file_id = $file_id;
401         $file_redir->redirections = intval($data['redirects']);
402         $file_redir->httpcode = intval($data['code']);
403         $file_redir->insert();
404     }
405
406     static public function beforeSchemaUpdate()
407     {
408         $table = strtolower(get_called_class());
409         $schema = Schema::get();
410         $schemadef = $schema->getTableDef($table);
411
412         // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
413         if (isset($schemadef['fields']['urlhash']) && in_array('urlhash', $schemadef['primary key'])) {
414             // We already have the urlhash field, so no need to migrate it.
415             return;
416         }
417         echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
418         // We have to create a urlhash that is _not_ the primary key,
419         // transfer data and THEN run checkSchema
420         $schemadef['fields']['urlhash'] = array (
421                                               'type' => 'varchar',
422                                               'length' => 64,
423                                               'not null' => true,
424                                               'description' => 'sha256 hash of the URL',
425                                             );
426         $schemadef['fields']['url'] = array (
427                                               'type' => 'text',
428                                               'description' => 'short URL (or any other kind of redirect) for file (id)',
429                                             );
430         unset($schemadef['primary key']);
431         $schema->ensureTable($table, $schemadef);
432         echo "DONE.\n";
433
434         $classname = ucfirst($table);
435         $tablefix = new $classname;
436         // urlhash is hash('sha256', $url) in the File table
437         echo "Updating urlhash fields in $table table...";
438         // Maybe very MySQL specific :(
439         $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
440                             $schema->quoteIdentifier($table),
441                             'urlhash',
442                             // The line below is "result of sha256 on column `url`"
443                             'SHA2(url, 256)'));
444         echo "DONE.\n";
445         echo "Resuming core schema upgrade...";
446     }
447
448     public function getFile() {
449         if(empty($this->file) && $this->file_id) {
450             $this->file = File::getKV('id', $this->file_id);
451         }
452
453         return $this->file;
454     }
455 }