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 protected $file; /* Cache the associated file sometimes */
44 public static function schemaDef()
48 'urlhash' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'sha256 hash of the URL'),
49 'url' => array('type' => 'text', 'description' => 'short URL (or any other kind of redirect) for file (id)'),
50 'file_id' => array('type' => 'int', 'description' => 'short URL for what URL/file'),
51 'redirections' => array('type' => 'int', 'description' => 'redirect count'),
52 'httpcode' => array('type' => 'int', 'description' => 'HTTP status code (20x, 30x, etc.)'),
53 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
55 'primary key' => array('urlhash'),
56 'foreign keys' => array(
57 'file_redirection_file_id_fkey' => array('file' => array('file_id' => 'id')),
62 static public function getByUrl($url)
64 return self::getByPK(array('urlhash' => File::hashurl($url)));
67 static function _commonHttp($url, $redirs) {
68 $request = new HTTPClient($url);
69 $request->setConfig(array(
70 'connect_timeout' => 10, // # seconds to wait
71 'max_redirs' => $redirs, // # max number of http redirections to follow
72 'follow_redirects' => false, // We follow redirects ourselves in lib/httpclient.php
73 'store_body' => false, // We won't need body content here.
79 * Check if this URL is a redirect and return redir info.
81 * Most code should call File_redirection::where instead, to check if we
82 * already know that redirection and avoid extra hits to the web.
84 * The URL is hit and any redirects are followed, up to 10 levels or until
85 * a protected URL is reached.
87 * @param string $in_url
88 * @return mixed one of:
89 * string - target URL, if this is a direct link or can't be followed
90 * array - redirect info if this is an *unknown* redirect:
91 * associative array with the following elements:
92 * code: HTTP status code
93 * redirects: count of redirects followed
94 * url: URL string of final target
95 * type (optional): MIME type from Content-Type header
96 * size (optional): byte size from Content-Length header
97 * time (optional): timestamp from Last-Modified header
99 static function lookupWhere($short_url, $redirs = 10, $protected = false) {
100 if ($redirs < 0) return false;
102 if(strpos($short_url,'://') === false){
106 $request = self::_commonHttp($short_url, $redirs);
107 // Don't include body in output
108 $request->setMethod(HTTP_Request2::METHOD_HEAD);
109 $response = $request->send();
111 if (405 == $response->getStatus() || 204 == $response->getStatus()) {
112 // HTTP 405 Unsupported Method
113 // Server doesn't support HEAD method? Can this really happen?
114 // We'll try again as a GET and ignore the response data.
116 // HTTP 204 No Content
117 // YFrog sends 204 responses back for our HEAD checks, which
118 // seems like it may be a logic error in their servers. If
119 // we get a 204 back, re-run it as a GET... if there's really
120 // no content it'll be cheap. :)
121 $request = self::_commonHttp($short_url, $redirs);
122 $response = $request->send();
123 } elseif (400 == $response->getStatus()) {
124 throw new Exception('Got error 400 on HEAD request, will not go further.');
126 } catch (Exception $e) {
127 // Invalid URL or failure to reach server
128 common_log(LOG_ERR, "Error while following redirects for $short_url: " . $e->getMessage());
132 // if last url after all redirections is protected,
133 // use the url before it in the redirection chain
134 if ($response->getRedirectCount() && File::isProtected($response->getEffectiveUrl())) {
135 $return_url = $response->redirUrls[$response->getRedirectCount()-1];
137 $return_url = $response->getEffectiveUrl();
140 $ret = array('code' => $response->getStatus()
141 , 'redirects' => $response->getRedirectCount()
142 , 'url' => $return_url);
144 $type = $response->getHeader('Content-Type');
145 if ($type) $ret['type'] = $type;
146 if ($protected) $ret['protected'] = true;
147 $size = $response->getHeader('Content-Length'); // @fixme bytes?
148 if ($size) $ret['size'] = $size;
149 $time = $response->getHeader('Last-Modified');
150 if ($time) $ret['time'] = strtotime($time);
155 * Check if this URL is a redirect and return redir info.
156 * If a File record is present for this URL, it is not considered a redirect.
157 * If a File_redirection record is present for this URL, the recorded target is returned.
159 * If no File or File_redirect record is present, the URL is hit and any
160 * redirects are followed, up to 10 levels or until a protected URL is
163 * @param string $in_url
164 * @param boolean $discover true to attempt dereferencing the redirect if we don't know it already
165 * @return File_redirection
167 static function where($in_url, $discover=true) {
168 $redir = new File_redirection();
169 $redir->url = $in_url;
170 $redir->urlhash = File::hashurl($redir->url);
171 $redir->redirections = 0;
174 $r = File_redirection::getByUrl($in_url);
175 if($r instanceof File_redirection) {
177 $f = File::getKV('id',$r->file_id);
179 $r->redir_url = $f->url;
180 } catch (NoResultException $e) {
181 // Invalid entry, delete and run again
182 common_log(LOG_ERR, "Could not find File with id=".$r->file_id." referenced in File_redirection, deleting File redirection entry and creating new File and File_redirection entries.");
184 return self::where($in_url);
188 } catch (NoResultException $e) {
190 $f = File::getByUrl($in_url);
191 $redir->file_id = $f->id;
194 } catch (NoResultException $e) {
195 // Oh well, let's keep going
200 $redir_info = File_redirection::lookupWhere($in_url);
201 if(is_string($redir_info)) {
202 $redir_info = array('url' => $redir_info);
205 // Save the file if we don't have it already
206 $redir->file = File::saveNew($redir_info,$redir_info['url']);
208 // If this is a redirection, save it
209 // (if it hasn't been saved yet by some other process while we we
210 // were running lookupWhere())
211 if($redir_info['url'] != $in_url) {
213 $file_redir = File_redirection::getByUrl($in_url);
214 } catch (NoResultException $e) {
215 $file_redir = new File_redirection();
216 $file_redir->urlhash = File::hashurl($in_url);
217 $file_redir->url = $in_url;
218 $file_redir->file_id = $redir->file->getID();
219 $file_redir->insert();
220 $file_redir->redir_url = $redir->file->url;
223 $file_redir->file = $redir->file;
232 * Shorten a URL with the current user's configured shortening
233 * options, if applicable.
235 * If it cannot be shortened or the "short" URL is longer than the
236 * original, the original is returned.
238 * If the referenced item has not been seen before, embedding data
241 * @param string $long_url
242 * @param User $user whose shortening options to use; defaults to the current web session user
245 static function makeShort($long_url, $user=null)
247 $canon = File_redirection::_canonUrl($long_url);
249 $short_url = File_redirection::_userMakeShort($canon, $user);
251 // Did we get one? Is it shorter?
253 return !empty($short_url) ? $short_url : $long_url;
257 * Shorten a URL with the current user's configured shortening
258 * options, if applicable.
260 * If it cannot be shortened or the "short" URL is longer than the
261 * original, the original is returned.
263 * If the referenced item has not been seen before, embedding data
266 * @param string $long_url
270 static function forceShort($long_url, $user)
272 $canon = File_redirection::_canonUrl($long_url);
274 $short_url = File_redirection::_userMakeShort($canon, $user, true);
276 // Did we get one? Is it shorter?
277 return !empty($short_url) ? $short_url : $long_url;
280 static function _userMakeShort($long_url, User $user=null, $force = false) {
281 $short_url = common_shorten_url($long_url, $user, $force);
282 if (!empty($short_url) && $short_url != $long_url) {
283 $short_url = (string)$short_url;
286 $file = File::getByUrl($long_url);
287 } catch (NoResultException $e) {
288 // Check if the target URL is itself a redirect...
289 // This should already have happened in processNew in common_shorten_url()
290 $redir = File_redirection::where($long_url);
291 $file = $redir->file;
293 // Now we definitely have a File object in $file
295 $file_redir = File_redirection::getByUrl($short_url);
296 } catch (NoResultException $e) {
297 $file_redir = new File_redirection();
298 $file_redir->urlhash = File::hashurl($short_url);
299 $file_redir->url = $short_url;
300 $file_redir->file_id = $file->getID();
301 $file_redir->insert();
309 * Basic attempt to canonicalize a URL, cleaning up some standard variants
310 * such as funny syntax or a missing path. Used internally when cleaning
311 * up URLs for storage and following redirect chains.
313 * Note that despite being on File_redirect, this function DOES NOT perform
314 * any dereferencing of redirects.
316 * @param string $in_url input URL
317 * @param string $default_scheme if given a bare link; defaults to 'http://'
320 static function _canonUrl($in_url, $default_scheme = 'http://') {
321 if (empty($in_url)) return false;
323 $p = parse_url($out_url);
324 if (empty($p['host']) || empty($p['scheme'])) {
325 list($scheme) = explode(':', $in_url, 2);
326 switch (strtolower($scheme)) {
329 $out_url = str_replace('.-()', '', $out_url);
332 // non-HTTP schemes, so no redirects
338 // don't touch anything
341 // URLs without domain name, so no redirects
343 // don't touch anything
346 // URLs with coordinates, not browsable domain names
348 // don't touch anything
352 $out_url = $default_scheme . ltrim($out_url, '/');
353 $p = parse_url($out_url);
354 if (empty($p['scheme'])) return false;
359 if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
360 if (empty($p['host'])) return false;
361 if (empty($p['path'])) {
369 static function saveNew($data, $file_id, $url) {
370 $file_redir = new File_redirection;
371 $file_redir->urlhash = File::hashurl($url);
372 $file_redir->url = $url;
373 $file_redir->file_id = $file_id;
374 $file_redir->redirections = intval($data['redirects']);
375 $file_redir->httpcode = intval($data['code']);
376 $file_redir->insert();
379 static public function beforeSchemaUpdate()
381 $table = strtolower(get_called_class());
382 $schema = Schema::get();
383 $schemadef = $schema->getTableDef($table);
385 // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
386 if (isset($schemadef['fields']['urlhash']) && in_array('urlhash', $schemadef['primary key'])) {
387 // We already have the urlhash field, so no need to migrate it.
390 echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
391 // We have to create a urlhash that is _not_ the primary key,
392 // transfer data and THEN run checkSchema
393 $schemadef['fields']['urlhash'] = array (
397 'description' => 'sha256 hash of the URL',
399 $schemadef['fields']['url'] = array (
401 'description' => 'short URL (or any other kind of redirect) for file (id)',
403 unset($schemadef['primary key']);
404 $schema->ensureTable($table, $schemadef);
407 $classname = ucfirst($table);
408 $tablefix = new $classname;
409 // urlhash is hash('sha256', $url) in the File table
410 echo "Updating urlhash fields in $table table...";
411 // Maybe very MySQL specific :(
412 $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
413 $schema->quoteIdentifier($table),
415 // The line below is "result of sha256 on column `url`"
418 echo "Resuming core schema upgrade...";
421 public function getFile() {
422 if(empty($this->file) && $this->file_id) {
423 $this->file = File::getKV('id', $this->file_id);