]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File_redirection.php
Fix for attachment "h bug": posting a shortened link to an oembed-able resource that...
[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('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
23 require_once INSTALLDIR.'/classes/File.php';
24 require_once INSTALLDIR.'/classes/File_oembed.php';
25
26 define('USER_AGENT', 'StatusNet user agent / file probe');
27
28 /**
29  * Table Definition for file_redirection
30  */
31
32 class File_redirection extends Memcached_DataObject
33 {
34     ###START_AUTOCODE
35     /* the code below is auto generated do not remove the above tag */
36
37     public $__table = 'file_redirection';                // table name
38     public $url;                             // varchar(255)  primary_key not_null
39     public $file_id;                         // int(4)
40     public $redirections;                    // int(4)
41     public $httpcode;                        // int(4)
42     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
43
44     /* Static get */
45     function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('File_redirection',$k,$v); }
46
47     /* the code above is auto generated do not remove the tag below */
48     ###END_AUTOCODE
49
50     static function _commonHttp($url, $redirs) {
51         $request = new HTTPClient($url);
52         $request->setConfig(array(
53             'connect_timeout' => 10, // # seconds to wait
54             'max_redirs' => $redirs, // # max number of http redirections to follow
55             'follow_redirects' => true, // Follow redirects
56             'store_body' => false, // We won't need body content here.
57         ));
58         return $request;
59     }
60
61     function _redirectWhere_imp($short_url, $redirs = 10, $protected = false) {
62         if ($redirs < 0) return false;
63
64         // let's see if we know this...
65         $a = File::staticGet('url', $short_url);
66
67         if (!empty($a)) {
68             // this is a direct link to $a->url
69             return $a->url;
70         } else {
71             $b = File_redirection::staticGet('url', $short_url);
72             if (!empty($b)) {
73                 // this is a redirect to $b->file_id
74                 $a = File::staticGet('id', $b->file_id);
75                 return $a->url;
76             }
77         }
78
79         if(strpos($short_url,'://') === false){
80             return $short_url;
81         }
82         try {
83             $request = self::_commonHttp($short_url, $redirs);
84             // Don't include body in output
85             $request->setMethod(HTTP_Request2::METHOD_HEAD);
86             $response = $request->send();
87
88             if (405 == $response->getStatus()) {
89                 // Server doesn't support HEAD method? Can this really happen?
90                 // We'll try again as a GET and ignore the response data.
91                 $request = self::_commonHttp($short_url, $redirs);
92                 $response = $request->send();
93             }
94         } catch (Exception $e) {
95             // Invalid URL or failure to reach server
96             return $short_url;
97         }
98
99         if ($response->getRedirectCount() && File::isProtected($response->getUrl())) {
100             // Bump back up the redirect chain until we find a non-protected URL
101             return self::_redirectWhere_imp($short_url, $response->getRedirectCount() - 1, true);
102         }
103
104         $ret = array('code' => $response->getStatus()
105                 , 'redirects' => $response->getRedirectCount()
106                 , 'url' => $response->getUrl());
107
108         $type = $response->getHeader('Content-Type');
109         if ($type) $ret['type'] = $type;
110         if ($protected) $ret['protected'] = true;
111         $size = $response->getHeader('Content-Length'); // @fixme bytes?
112         if ($size) $ret['size'] = $size;
113         $time = $response->getHeader('Last-Modified');
114         if ($time) $ret['time'] = strtotime($time);
115         return $ret;
116     }
117
118     /**
119      * Check if this URL is a redirect and return redir info.
120      * If a File record is present for this URL, it is not considered a redirect.
121      * If a File_redirection record is present for this URL, the recorded target is returned.
122      *
123      * If no File or File_redirect record is present, the URL is hit and any
124      * redirects are followed, up to 10 levels or until a protected URL is
125      * reached.
126      *
127      * @param string $in_url
128      * @return mixed one of:
129      *         string - target URL, if this is a direct link or a known redirect
130      *         array - redirect info if this is an *unknown* redirect:
131      *              associative array with the following elements:
132      *                code: HTTP status code
133      *                redirects: count of redirects followed
134      *                url: URL string of final target
135      *                type (optional): MIME type from Content-Type header
136      *                size (optional): byte size from Content-Length header
137      *                time (optional): timestamp from Last-Modified header
138      */
139     function where($in_url) {
140         $ret = File_redirection::_redirectWhere_imp($in_url);
141         return $ret;
142     }
143
144     /**
145      * Shorten a URL with the current user's configured shortening
146      * options, if applicable.
147      *
148      * If it cannot be shortened or the "short" URL is longer than the
149      * original, the original is returned.
150      *
151      * If the referenced item has not been seen before, embedding data
152      * may be saved.
153      *
154      * @param string $long_url
155      * @return string
156      */
157     function makeShort($long_url) {
158
159         $canon = File_redirection::_canonUrl($long_url);
160
161         $short_url = File_redirection::_userMakeShort($canon);
162
163         // Did we get one? Is it shorter?
164         if (!empty($short_url) && mb_strlen($short_url) < mb_strlen($long_url)) {
165             return $short_url;
166         } else {
167             return $long_url;
168         }
169     }
170
171     function _userMakeShort($long_url) {
172         $short_url = common_shorten_url($long_url);
173         if (!empty($short_url) && $short_url != $long_url) {
174             $short_url = (string)$short_url;
175             // store it
176             $file = File::staticGet('url', $long_url);
177             if (empty($file)) {
178                 // Check if the target URL is itself a redirect...
179                 $redir_data = File_redirection::where($long_url);
180                 if (is_array($redir_data)) {
181                     // We haven't seen the target URL before.
182                     // Save file and embedding data about it!
183                     $file = File::saveNew($redir_data, $long_url);
184                     $file_id = $file->id;
185                     if (!empty($redir_data['oembed']['json'])) {
186                         File_oembed::saveNew($redir_data['oembed']['json'], $file_id);
187                     }
188                 } else if (is_string($redir_data)) {
189                     // The file is a known redirect target.
190                     $file = File::staticGet('url', $redir_data);
191                     $file_id = $file->id;
192                 }
193             } else {
194                 $file_id = $file->id;
195             }
196             $file_redir = File_redirection::staticGet('url', $short_url);
197             if (empty($file_redir)) {
198                 $file_redir = new File_redirection;
199                 $file_redir->url = $short_url;
200                 $file_redir->file_id = $file_id;
201                 $file_redir->insert();
202             }
203             return $short_url;
204         }
205         return null;
206     }
207
208     function _canonUrl($in_url, $default_scheme = 'http://') {
209         if (empty($in_url)) return false;
210         $out_url = $in_url;
211         $p = parse_url($out_url);
212         if (empty($p['host']) || empty($p['scheme'])) {
213             list($scheme) = explode(':', $in_url, 2);
214             switch ($scheme) {
215             case 'fax':
216             case 'tel':
217                 $out_url = str_replace('.-()', '', $out_url);
218                 break;
219
220             case 'mailto':
221             case 'aim':
222             case 'jabber':
223             case 'xmpp':
224                 // don't touch anything
225                 break;
226
227             default:
228                 $out_url = $default_scheme . ltrim($out_url, '/');
229                 $p = parse_url($out_url);
230                 if (empty($p['scheme'])) return false;
231                 break;
232             }
233         }
234
235         if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
236             if (empty($p['host'])) return false;
237             if (empty($p['path'])) {
238                 $out_url .= '/';
239             }
240         }
241
242         return $out_url;
243     }
244
245     function saveNew($data, $file_id, $url) {
246         $file_redir = new File_redirection;
247         $file_redir->url = $url;
248         $file_redir->file_id = $file_id;
249         $file_redir->redirections = intval($data['redirects']);
250         $file_redir->httpcode = intval($data['code']);
251         $file_redir->insert();
252     }
253 }
254