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('GNUSOCIAL')) { exit(1); }
23 * Table Definition for file_redirection
26 class File_redirection extends Managed_DataObject
29 /* the code below is auto generated do not remove the above tag */
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
38 /* the code above is auto generated do not remove the tag below */
41 public static function schemaDef()
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'),
51 'primary key' => array('url'),
52 'foreign keys' => array(
53 'file_redirection_file_id_fkey' => array('file' => array('file_id' => 'id')),
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.
70 * Check if this URL is a redirect and return redir info.
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.
75 * The URL is hit and any redirects are followed, up to 10 levels or until
76 * a protected URL is reached.
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
90 public function lookupWhere($short_url, $redirs = 10, $protected = false) {
91 if ($redirs < 0) return false;
93 if(strpos($short_url,'://') === false){
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();
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.
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();
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());
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);
126 $ret = array('code' => $response->getStatus()
127 , 'redirects' => $response->getRedirectCount()
128 , 'url' => $response->getUrl());
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);
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.
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
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
162 public function where($in_url, $discover=true) {
163 // let's see if we know this...
164 $a = File::getKV('url', $in_url);
167 // this is a direct link to $a->url
170 $b = File_redirection::getKV('url', $in_url);
172 // this is a redirect to $b->file_id
173 $a = File::getKV('id', $b->file_id);
179 $ret = File_redirection::lookupWhere($in_url);
182 // No manual dereferencing; leave the unknown URL as is.
188 * Shorten a URL with the current user's configured shortening
189 * options, if applicable.
191 * If it cannot be shortened or the "short" URL is longer than the
192 * original, the original is returned.
194 * If the referenced item has not been seen before, embedding data
197 * @param string $long_url
198 * @param User $user whose shortening options to use; defaults to the current web session user
201 function makeShort($long_url, $user=null)
203 $canon = File_redirection::_canonUrl($long_url);
205 $short_url = File_redirection::_userMakeShort($canon, $user);
207 // Did we get one? Is it shorter?
209 if (!empty($short_url)) {
217 * Shorten a URL with the current user's configured shortening
218 * options, if applicable.
220 * If it cannot be shortened or the "short" URL is longer than the
221 * original, the original is returned.
223 * If the referenced item has not been seen before, embedding data
226 * @param string $long_url
230 function forceShort($long_url, $user)
232 $canon = File_redirection::_canonUrl($long_url);
234 $short_url = File_redirection::_userMakeShort($canon, $user, true);
236 // Did we get one? Is it shorter?
237 if (!empty($short_url)) {
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;
249 $file = File::getKV('url', $long_url);
250 if ($file instanceof File) {
251 $file_id = $file->id;
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);
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.
271 $file_id = $file->id;
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();
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.
291 * Note that despite being on File_redirect, this function DOES NOT perform
292 * any dereferencing of redirects.
294 * @param string $in_url input URL
295 * @param string $default_scheme if given a bare link; defaults to 'http://'
298 function _canonUrl($in_url, $default_scheme = 'http://') {
299 if (empty($in_url)) return false;
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)) {
307 $out_url = str_replace('.-()', '', $out_url);
314 // don't touch anything
318 $out_url = $default_scheme . ltrim($out_url, '/');
319 $p = parse_url($out_url);
320 if (empty($p['scheme'])) return false;
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'])) {
335 function saveNew($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();