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