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