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 $urlhash; // varchar(64) primary_key not_null
34 public $file_id; // int(4)
35 public $redirections; // int(4)
36 public $httpcode; // int(4)
37 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
39 /* the code above is auto generated do not remove the tag below */
42 public static function schemaDef()
46 'urlhash' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'sha256 hash of the URL'),
47 'url' => array('type' => 'text', 'description' => 'short URL (or any other kind of redirect) for file (id)'),
48 'file_id' => array('type' => 'int', 'description' => 'short URL for what URL/file'),
49 'redirections' => array('type' => 'int', 'description' => 'redirect count'),
50 'httpcode' => array('type' => 'int', 'description' => 'HTTP status code (20x, 30x, etc.)'),
51 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
53 'primary key' => array('urlhash'),
54 'foreign keys' => array(
55 'file_redirection_file_id_fkey' => array('file' => array('file_id' => 'id')),
60 static public function getByUrl($url)
62 $file = new File_redirection();
63 $file->urlhash = File::hashurl($url);
64 if (!$file->find(true)) {
65 throw new NoResultException($file);
70 static function _commonHttp($url, $redirs) {
71 $request = new HTTPClient($url);
72 $request->setConfig(array(
73 'connect_timeout' => 10, // # seconds to wait
74 'max_redirs' => $redirs, // # max number of http redirections to follow
75 'follow_redirects' => true, // Follow redirects
76 'store_body' => false, // We won't need body content here.
82 * Check if this URL is a redirect and return redir info.
84 * Most code should call File_redirection::where instead, to check if we
85 * already know that redirection and avoid extra hits to the web.
87 * The URL is hit and any redirects are followed, up to 10 levels or until
88 * a protected URL is reached.
90 * @param string $in_url
91 * @return mixed one of:
92 * string - target URL, if this is a direct link or can't be followed
93 * array - redirect info if this is an *unknown* redirect:
94 * associative array with the following elements:
95 * code: HTTP status code
96 * redirects: count of redirects followed
97 * url: URL string of final target
98 * type (optional): MIME type from Content-Type header
99 * size (optional): byte size from Content-Length header
100 * time (optional): timestamp from Last-Modified header
102 public function lookupWhere($short_url, $redirs = 10, $protected = false) {
103 if ($redirs < 0) return false;
105 if(strpos($short_url,'://') === false){
109 $request = self::_commonHttp($short_url, $redirs);
110 // Don't include body in output
111 $request->setMethod(HTTP_Request2::METHOD_HEAD);
112 $response = $request->send();
114 if (405 == $response->getStatus() || 204 == $response->getStatus()) {
115 // HTTP 405 Unsupported Method
116 // Server doesn't support HEAD method? Can this really happen?
117 // We'll try again as a GET and ignore the response data.
119 // HTTP 204 No Content
120 // YFrog sends 204 responses back for our HEAD checks, which
121 // seems like it may be a logic error in their servers. If
122 // we get a 204 back, re-run it as a GET... if there's really
123 // no content it'll be cheap. :)
124 $request = self::_commonHttp($short_url, $redirs);
125 $response = $request->send();
127 } catch (Exception $e) {
128 // Invalid URL or failure to reach server
129 common_log(LOG_ERR, "Error while following redirects for $short_url: " . $e->getMessage());
133 if ($response->getRedirectCount() && File::isProtected($response->getUrl())) {
134 // Bump back up the redirect chain until we find a non-protected URL
135 return self::lookupWhere($short_url, $response->getRedirectCount() - 1, true);
138 $ret = array('code' => $response->getStatus()
139 , 'redirects' => $response->getRedirectCount()
140 , 'url' => $response->getUrl());
142 $type = $response->getHeader('Content-Type');
143 if ($type) $ret['type'] = $type;
144 if ($protected) $ret['protected'] = true;
145 $size = $response->getHeader('Content-Length'); // @fixme bytes?
146 if ($size) $ret['size'] = $size;
147 $time = $response->getHeader('Last-Modified');
148 if ($time) $ret['time'] = strtotime($time);
153 * Check if this URL is a redirect and return redir info.
154 * If a File record is present for this URL, it is not considered a redirect.
155 * If a File_redirection record is present for this URL, the recorded target is returned.
157 * If no File or File_redirect record is present, the URL is hit and any
158 * redirects are followed, up to 10 levels or until a protected URL is
161 * @param string $in_url
162 * @param boolean $discover true to attempt dereferencing the redirect if we don't know it already
163 * @return mixed one of:
164 * string - target URL, if this is a direct link or a known redirect
165 * array - redirect info if this is an *unknown* redirect:
166 * associative array with the following elements:
167 * code: HTTP status code
168 * redirects: count of redirects followed
169 * url: URL string of final target
170 * type (optional): MIME type from Content-Type header
171 * size (optional): byte size from Content-Length header
172 * time (optional): timestamp from Last-Modified header
174 public function where($in_url, $discover=true) {
175 // let's see if we know this...
177 $a = File::getByUrl($in_url);
178 // this is a direct link to $a->url
180 } catch (NoResultException $e) {
182 $b = File_redirection::getByUrl($in_url);
183 // this is a redirect to $b->file_id
184 $a = File::getKV('id', $b->file_id);
186 } catch (NoResultException $e) {
187 // Oh well, let's keep going
192 $ret = File_redirection::lookupWhere($in_url);
195 // No manual dereferencing; leave the unknown URL as is.
201 * Shorten a URL with the current user's configured shortening
202 * options, if applicable.
204 * If it cannot be shortened or the "short" URL is longer than the
205 * original, the original is returned.
207 * If the referenced item has not been seen before, embedding data
210 * @param string $long_url
211 * @param User $user whose shortening options to use; defaults to the current web session user
214 function makeShort($long_url, $user=null)
216 $canon = File_redirection::_canonUrl($long_url);
218 $short_url = File_redirection::_userMakeShort($canon, $user);
220 // Did we get one? Is it shorter?
222 if (!empty($short_url)) {
230 * Shorten a URL with the current user's configured shortening
231 * options, if applicable.
233 * If it cannot be shortened or the "short" URL is longer than the
234 * original, the original is returned.
236 * If the referenced item has not been seen before, embedding data
239 * @param string $long_url
243 function forceShort($long_url, $user)
245 $canon = File_redirection::_canonUrl($long_url);
247 $short_url = File_redirection::_userMakeShort($canon, $user, true);
249 // Did we get one? Is it shorter?
250 if (!empty($short_url)) {
257 function _userMakeShort($long_url, User $user=null, $force = false) {
258 $short_url = common_shorten_url($long_url, $user, $force);
259 if (!empty($short_url) && $short_url != $long_url) {
260 $short_url = (string)$short_url;
262 $file = File::getKV('url', $long_url);
263 if ($file instanceof File) {
264 $file_id = $file->id;
266 // Check if the target URL is itself a redirect...
267 $redir_data = File_redirection::where($long_url);
268 if (is_array($redir_data)) {
269 // We haven't seen the target URL before.
270 // Save file and embedding data about it!
271 $file = File::saveNew($redir_data, $long_url);
272 $file_id = $file->id;
273 } else if (is_string($redir_data)) {
274 // The file is a known redirect target.
275 $file = File::getKV('url', $redir_data);
277 // @fixme should we save a new one?
278 // this case was triggering sometimes for redirects
279 // with unresolvable targets; found while fixing
280 // "can't linkify" bugs with shortened links to
281 // SSL sites with cert issues.
284 $file_id = $file->id;
287 $file_redir = File_redirection::getKV('url', $short_url);
288 if (!$file_redir instanceof File_redirection) {
289 $file_redir = new File_redirection;
290 $file_redir->urlhash = File::hashurl($short_url);
291 $file_redir->url = $short_url;
292 $file_redir->file_id = $file_id;
293 $file_redir->insert();
301 * Basic attempt to canonicalize a URL, cleaning up some standard variants
302 * such as funny syntax or a missing path. Used internally when cleaning
303 * up URLs for storage and following redirect chains.
305 * Note that despite being on File_redirect, this function DOES NOT perform
306 * any dereferencing of redirects.
308 * @param string $in_url input URL
309 * @param string $default_scheme if given a bare link; defaults to 'http://'
312 function _canonUrl($in_url, $default_scheme = 'http://') {
313 if (empty($in_url)) return false;
315 $p = parse_url($out_url);
316 if (empty($p['host']) || empty($p['scheme'])) {
317 list($scheme) = explode(':', $in_url, 2);
318 switch (strtolower($scheme)) {
321 $out_url = str_replace('.-()', '', $out_url);
328 // don't touch anything
332 $out_url = $default_scheme . ltrim($out_url, '/');
333 $p = parse_url($out_url);
334 if (empty($p['scheme'])) return false;
339 if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
340 if (empty($p['host'])) return false;
341 if (empty($p['path'])) {
349 function saveNew($data, $file_id, $url) {
350 $file_redir = new File_redirection;
351 $file_redir->urlhash = File::hashurl($short_url);
352 $file_redir->url = $url;
353 $file_redir->file_id = $file_id;
354 $file_redir->redirections = intval($data['redirects']);
355 $file_redir->httpcode = intval($data['code']);
356 $file_redir->insert();
359 static public function beforeSchemaUpdate()
361 $table = strtolower(get_called_class());
362 $schema = Schema::get();
363 $schemadef = $schema->getTableDef($table);
365 // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
366 if (isset($schemadef['fields']['urlhash']) && in_array('urlhash', $schemadef['primary key'])) {
367 // We already have the urlhash field, so no need to migrate it.
370 echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
371 // We have to create a urlhash that is _not_ the primary key,
372 // transfer data and THEN run checkSchema
373 $schemadef['fields']['urlhash'] = array (
376 'description' => 'sha256 of destination URL after following redirections',
378 $schema->ensureTable($table, $schemadef);
381 $classname = ucfirst($table);
382 $tablefix = new $classname;
383 // urlhash is hash('sha256', $url) in the File table
384 echo "Updating urlhash fields in $table table...";
385 // Maybe very MySQL specific :(
386 $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
387 $schema->quoteIdentifier($table),
389 // The line below is "result of sha256 on column `url`"
392 echo "Resuming core schema upgrade...";