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';
26 define('USER_AGENT', 'StatusNet user agent / file probe');
29 * Table Definition for file_redirection
32 class File_redirection extends Memcached_DataObject
35 /* the code below is auto generated do not remove the above tag */
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
45 function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('File_redirection',$k,$v); }
47 /* the code above is auto generated do not remove the tag below */
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.
62 * Check if this URL is a redirect and return redir info.
64 * Most code should call File_redirection::where instead, to check if we
65 * already know that redirection and avoid extra hits to the web.
67 * The URL is hit and any redirects are followed, up to 10 levels or until
68 * a protected URL is reached.
70 * @param string $in_url
71 * @return mixed one of:
72 * string - target URL, if this is a direct link or can't be followed
73 * array - redirect info if this is an *unknown* redirect:
74 * associative array with the following elements:
75 * code: HTTP status code
76 * redirects: count of redirects followed
77 * url: URL string of final target
78 * type (optional): MIME type from Content-Type header
79 * size (optional): byte size from Content-Length header
80 * time (optional): timestamp from Last-Modified header
82 public function lookupWhere($short_url, $redirs = 10, $protected = false) {
83 if ($redirs < 0) return false;
85 if(strpos($short_url,'://') === false){
89 $request = self::_commonHttp($short_url, $redirs);
90 // Don't include body in output
91 $request->setMethod(HTTP_Request2::METHOD_HEAD);
92 $response = $request->send();
94 if (405 == $response->getStatus() || 204 == $response->getStatus()) {
95 // HTTP 405 Unsupported Method
96 // Server doesn't support HEAD method? Can this really happen?
97 // We'll try again as a GET and ignore the response data.
99 // HTTP 204 No Content
100 // YFrog sends 204 responses back for our HEAD checks, which
101 // seems like it may be a logic error in their servers. If
102 // we get a 204 back, re-run it as a GET... if there's really
103 // no content it'll be cheap. :)
104 $request = self::_commonHttp($short_url, $redirs);
105 $response = $request->send();
107 } catch (Exception $e) {
108 // Invalid URL or failure to reach server
109 common_log(LOG_ERR, "Error while following redirects for $short_url: " . $e->getMessage());
113 if ($response->getRedirectCount() && File::isProtected($response->getUrl())) {
114 // Bump back up the redirect chain until we find a non-protected URL
115 return self::lookupWhere($short_url, $response->getRedirectCount() - 1, true);
118 $ret = array('code' => $response->getStatus()
119 , 'redirects' => $response->getRedirectCount()
120 , 'url' => $response->getUrl());
122 $type = $response->getHeader('Content-Type');
123 if ($type) $ret['type'] = $type;
124 if ($protected) $ret['protected'] = true;
125 $size = $response->getHeader('Content-Length'); // @fixme bytes?
126 if ($size) $ret['size'] = $size;
127 $time = $response->getHeader('Last-Modified');
128 if ($time) $ret['time'] = strtotime($time);
133 * Check if this URL is a redirect and return redir info.
134 * If a File record is present for this URL, it is not considered a redirect.
135 * If a File_redirection record is present for this URL, the recorded target is returned.
137 * If no File or File_redirect record is present, the URL is hit and any
138 * redirects are followed, up to 10 levels or until a protected URL is
141 * @param string $in_url
142 * @param boolean $discover true to attempt dereferencing the redirect if we don't know it already
143 * @return mixed one of:
144 * string - target URL, if this is a direct link or a known redirect
145 * array - redirect info if this is an *unknown* redirect:
146 * associative array with the following elements:
147 * code: HTTP status code
148 * redirects: count of redirects followed
149 * url: URL string of final target
150 * type (optional): MIME type from Content-Type header
151 * size (optional): byte size from Content-Length header
152 * time (optional): timestamp from Last-Modified header
154 public function where($in_url, $discover=true) {
155 // let's see if we know this...
156 $a = File::staticGet('url', $in_url);
159 // this is a direct link to $a->url
162 $b = File_redirection::staticGet('url', $in_url);
164 // this is a redirect to $b->file_id
165 $a = File::staticGet('id', $b->file_id);
171 $ret = File_redirection::lookupWhere($in_url);
174 // No manual dereferencing; leave the unknown URL as is.
180 * Shorten a URL with the current user's configured shortening
181 * options, if applicable.
183 * If it cannot be shortened or the "short" URL is longer than the
184 * original, the original is returned.
186 * If the referenced item has not been seen before, embedding data
189 * @param string $long_url
190 * @param User $user whose shortening options to use; defaults to the current web session user
193 function makeShort($long_url, $user=null)
195 $canon = File_redirection::_canonUrl($long_url);
197 $short_url = File_redirection::_userMakeShort($canon, $user);
199 // Did we get one? Is it shorter?
201 if (!empty($short_url)) {
209 * Shorten a URL with the current user's configured shortening
210 * options, if applicable.
212 * If it cannot be shortened or the "short" URL is longer than the
213 * original, the original is returned.
215 * If the referenced item has not been seen before, embedding data
218 * @param string $long_url
222 function forceShort($long_url, $user)
224 $canon = File_redirection::_canonUrl($long_url);
226 $short_url = File_redirection::_userMakeShort($canon, $user, true);
228 // Did we get one? Is it shorter?
229 if (!empty($short_url)) {
236 function _userMakeShort($long_url, User $user=null, $force = false) {
237 $short_url = common_shorten_url($long_url, $user, $force);
238 if (!empty($short_url) && $short_url != $long_url) {
239 $short_url = (string)$short_url;
241 $file = File::staticGet('url', $long_url);
243 // Check if the target URL is itself a redirect...
244 $redir_data = File_redirection::where($long_url);
245 if (is_array($redir_data)) {
246 // We haven't seen the target URL before.
247 // Save file and embedding data about it!
248 $file = File::saveNew($redir_data, $long_url);
249 $file_id = $file->id;
250 if (!empty($redir_data['oembed']['json'])) {
251 File_oembed::saveNew($redir_data['oembed']['json'], $file_id);
253 } else if (is_string($redir_data)) {
254 // The file is a known redirect target.
255 $file = File::staticGet('url', $redir_data);
257 // @fixme should we save a new one?
258 // this case was triggering sometimes for redirects
259 // with unresolvable targets; found while fixing
260 // "can't linkify" bugs with shortened links to
261 // SSL sites with cert issues.
264 $file_id = $file->id;
267 $file_id = $file->id;
269 $file_redir = File_redirection::staticGet('url', $short_url);
270 if (empty($file_redir)) {
271 $file_redir = new File_redirection;
272 $file_redir->url = $short_url;
273 $file_redir->file_id = $file_id;
274 $file_redir->insert();
282 * Basic attempt to canonicalize a URL, cleaning up some standard variants
283 * such as funny syntax or a missing path. Used internally when cleaning
284 * up URLs for storage and following redirect chains.
286 * Note that despite being on File_redirect, this function DOES NOT perform
287 * any dereferencing of redirects.
289 * @param string $in_url input URL
290 * @param string $default_scheme if given a bare link; defaults to 'http://'
293 function _canonUrl($in_url, $default_scheme = 'http://') {
294 if (empty($in_url)) return false;
296 $p = parse_url($out_url);
297 if (empty($p['host']) || empty($p['scheme'])) {
298 list($scheme) = explode(':', $in_url, 2);
302 $out_url = str_replace('.-()', '', $out_url);
309 // don't touch anything
313 $out_url = $default_scheme . ltrim($out_url, '/');
314 $p = parse_url($out_url);
315 if (empty($p['scheme'])) return false;
320 if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
321 if (empty($p['host'])) return false;
322 if (empty($p['path'])) {
330 function saveNew($data, $file_id, $url) {
331 $file_redir = new File_redirection;
332 $file_redir->url = $url;
333 $file_redir->file_id = $file_id;
334 $file_redir->redirections = intval($data['redirects']);
335 $file_redir->httpcode = intval($data['code']);
336 $file_redir->insert();