3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
22 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
23 require_once INSTALLDIR.'/classes/File.php';
24 require_once INSTALLDIR.'/classes/File_oembed.php';
27 * Table Definition for file_redirection
30 class File_redirection extends Memcached_DataObject
33 /* the code below is auto generated do not remove the above tag */
35 public $__table = 'file_redirection'; // table name
36 public $url; // varchar(255) primary_key not_null
37 public $file_id; // int(4)
38 public $redirections; // int(4)
39 public $httpcode; // int(4)
40 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
43 function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('File_redirection',$k,$v); }
45 /* the code above is auto generated do not remove the tag below */
48 static function _commonHttp($url, $redirs) {
49 $request = new HTTPClient($url);
50 $request->setConfig(array(
51 'connect_timeout' => 10, // # seconds to wait
52 'max_redirs' => $redirs, // # max number of http redirections to follow
53 'follow_redirects' => true, // Follow redirects
54 'store_body' => false, // We won't need body content here.
60 * Check if this URL is a redirect and return redir info.
62 * Most code should call File_redirection::where instead, to check if we
63 * already know that redirection and avoid extra hits to the web.
65 * The URL is hit and any redirects are followed, up to 10 levels or until
66 * a protected URL is reached.
68 * @param string $in_url
69 * @return mixed one of:
70 * string - target URL, if this is a direct link or can't be followed
71 * array - redirect info if this is an *unknown* redirect:
72 * associative array with the following elements:
73 * code: HTTP status code
74 * redirects: count of redirects followed
75 * url: URL string of final target
76 * type (optional): MIME type from Content-Type header
77 * size (optional): byte size from Content-Length header
78 * time (optional): timestamp from Last-Modified header
80 public function lookupWhere($short_url, $redirs = 10, $protected = false) {
81 if ($redirs < 0) return false;
83 if(strpos($short_url,'://') === false){
87 $request = self::_commonHttp($short_url, $redirs);
88 // Don't include body in output
89 $request->setMethod(HTTP_Request2::METHOD_HEAD);
90 $response = $request->send();
92 if (405 == $response->getStatus() || 204 == $response->getStatus()) {
93 // HTTP 405 Unsupported Method
94 // Server doesn't support HEAD method? Can this really happen?
95 // We'll try again as a GET and ignore the response data.
97 // HTTP 204 No Content
98 // YFrog sends 204 responses back for our HEAD checks, which
99 // seems like it may be a logic error in their servers. If
100 // we get a 204 back, re-run it as a GET... if there's really
101 // no content it'll be cheap. :)
102 $request = self::_commonHttp($short_url, $redirs);
103 $response = $request->send();
105 } catch (Exception $e) {
106 // Invalid URL or failure to reach server
107 common_log(LOG_ERR, "Error while following redirects for $short_url: " . $e->getMessage());
111 if ($response->getRedirectCount() && File::isProtected($response->getUrl())) {
112 // Bump back up the redirect chain until we find a non-protected URL
113 return self::lookupWhere($short_url, $response->getRedirectCount() - 1, true);
116 $ret = array('code' => $response->getStatus()
117 , 'redirects' => $response->getRedirectCount()
118 , 'url' => $response->getUrl());
120 $type = $response->getHeader('Content-Type');
121 if ($type) $ret['type'] = $type;
122 if ($protected) $ret['protected'] = true;
123 $size = $response->getHeader('Content-Length'); // @fixme bytes?
124 if ($size) $ret['size'] = $size;
125 $time = $response->getHeader('Last-Modified');
126 if ($time) $ret['time'] = strtotime($time);
131 * Check if this URL is a redirect and return redir info.
132 * If a File record is present for this URL, it is not considered a redirect.
133 * If a File_redirection record is present for this URL, the recorded target is returned.
135 * If no File or File_redirect record is present, the URL is hit and any
136 * redirects are followed, up to 10 levels or until a protected URL is
139 * @param string $in_url
140 * @param boolean $discover true to attempt dereferencing the redirect if we don't know it already
141 * @return mixed one of:
142 * string - target URL, if this is a direct link or a known redirect
143 * array - redirect info if this is an *unknown* redirect:
144 * associative array with the following elements:
145 * code: HTTP status code
146 * redirects: count of redirects followed
147 * url: URL string of final target
148 * type (optional): MIME type from Content-Type header
149 * size (optional): byte size from Content-Length header
150 * time (optional): timestamp from Last-Modified header
152 public function where($in_url, $discover=true) {
153 // let's see if we know this...
154 $a = File::staticGet('url', $in_url);
157 // this is a direct link to $a->url
160 $b = File_redirection::staticGet('url', $in_url);
162 // this is a redirect to $b->file_id
163 $a = File::staticGet('id', $b->file_id);
169 $ret = File_redirection::lookupWhere($in_url);
172 // No manual dereferencing; leave the unknown URL as is.
178 * Shorten a URL with the current user's configured shortening
179 * options, if applicable.
181 * If it cannot be shortened or the "short" URL is longer than the
182 * original, the original is returned.
184 * If the referenced item has not been seen before, embedding data
187 * @param string $long_url
188 * @param User $user whose shortening options to use; defaults to the current web session user
191 function makeShort($long_url, $user=null)
193 $canon = File_redirection::_canonUrl($long_url);
195 $short_url = File_redirection::_userMakeShort($canon, $user);
197 // Did we get one? Is it shorter?
199 if (!empty($short_url)) {
207 * Shorten a URL with the current user's configured shortening
208 * options, if applicable.
210 * If it cannot be shortened or the "short" URL is longer than the
211 * original, the original is returned.
213 * If the referenced item has not been seen before, embedding data
216 * @param string $long_url
220 function forceShort($long_url, $user)
222 $canon = File_redirection::_canonUrl($long_url);
224 $short_url = File_redirection::_userMakeShort($canon, $user, true);
226 // Did we get one? Is it shorter?
227 if (!empty($short_url)) {
234 function _userMakeShort($long_url, User $user=null, $force = false) {
235 $short_url = common_shorten_url($long_url, $user, $force);
236 if (!empty($short_url) && $short_url != $long_url) {
237 $short_url = (string)$short_url;
239 $file = File::staticGet('url', $long_url);
241 // Check if the target URL is itself a redirect...
242 $redir_data = File_redirection::where($long_url);
243 if (is_array($redir_data)) {
244 // We haven't seen the target URL before.
245 // Save file and embedding data about it!
246 $file = File::saveNew($redir_data, $long_url);
247 $file_id = $file->id;
248 if (!empty($redir_data['oembed']['json'])) {
249 File_oembed::saveNew($redir_data['oembed']['json'], $file_id);
251 } else if (is_string($redir_data)) {
252 // The file is a known redirect target.
253 $file = File::staticGet('url', $redir_data);
255 // @fixme should we save a new one?
256 // this case was triggering sometimes for redirects
257 // with unresolvable targets; found while fixing
258 // "can't linkify" bugs with shortened links to
259 // SSL sites with cert issues.
262 $file_id = $file->id;
265 $file_id = $file->id;
267 $file_redir = File_redirection::staticGet('url', $short_url);
268 if (empty($file_redir)) {
269 $file_redir = new File_redirection;
270 $file_redir->url = $short_url;
271 $file_redir->file_id = $file_id;
272 $file_redir->insert();
280 * Basic attempt to canonicalize a URL, cleaning up some standard variants
281 * such as funny syntax or a missing path. Used internally when cleaning
282 * up URLs for storage and following redirect chains.
284 * Note that despite being on File_redirect, this function DOES NOT perform
285 * any dereferencing of redirects.
287 * @param string $in_url input URL
288 * @param string $default_scheme if given a bare link; defaults to 'http://'
291 function _canonUrl($in_url, $default_scheme = 'http://') {
292 if (empty($in_url)) return false;
294 $p = parse_url($out_url);
295 if (empty($p['host']) || empty($p['scheme'])) {
296 list($scheme) = explode(':', $in_url, 2);
300 $out_url = str_replace('.-()', '', $out_url);
307 // don't touch anything
311 $out_url = $default_scheme . ltrim($out_url, '/');
312 $p = parse_url($out_url);
313 if (empty($p['scheme'])) return false;
318 if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
319 if (empty($p['host'])) return false;
320 if (empty($p['path'])) {
328 function saveNew($data, $file_id, $url) {
329 $file_redir = new File_redirection;
330 $file_redir->url = $url;
331 $file_redir->file_id = $file_id;
332 $file_redir->redirections = intval($data['redirects']);
333 $file_redir->httpcode = intval($data['code']);
334 $file_redir->insert();