File_redirection.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2008, 2009, StatusNet, Inc.
  5. *
  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.
  10. *
  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.
  15. *
  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/>.
  18. */
  19. if (!defined('GNUSOCIAL')) { exit(1); }
  20. /**
  21. * Table Definition for file_redirection
  22. */
  23. class File_redirection extends Managed_DataObject
  24. {
  25. ###START_AUTOCODE
  26. /* the code below is auto generated do not remove the above tag */
  27. public $__table = 'file_redirection'; // table name
  28. public $urlhash; // varchar(64) primary_key not_null
  29. public $url; // text
  30. public $file_id; // int(4)
  31. public $redirections; // int(4)
  32. public $httpcode; // int(4)
  33. public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
  34. /* the code above is auto generated do not remove the tag below */
  35. ###END_AUTOCODE
  36. protected $file; /* Cache the associated file sometimes */
  37. public static function schemaDef()
  38. {
  39. return array(
  40. 'fields' => array(
  41. 'urlhash' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'sha256 hash of the URL'),
  42. 'url' => array('type' => 'text', 'description' => 'short URL (or any other kind of redirect) for file (id)'),
  43. 'file_id' => array('type' => 'int', 'description' => 'short URL for what URL/file'),
  44. 'redirections' => array('type' => 'int', 'description' => 'redirect count'),
  45. 'httpcode' => array('type' => 'int', 'description' => 'HTTP status code (20x, 30x, etc.)'),
  46. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  47. ),
  48. 'primary key' => array('urlhash'),
  49. 'foreign keys' => array(
  50. 'file_redirection_file_id_fkey' => array('file' => array('file_id' => 'id')),
  51. ),
  52. );
  53. }
  54. static public function getByUrl($url)
  55. {
  56. return self::getByPK(array('urlhash' => File::hashurl($url)));
  57. }
  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' => false, // We follow redirects ourselves in lib/httpclient.php
  64. 'store_body' => false, // We won't need body content here.
  65. ));
  66. return $request;
  67. }
  68. /**
  69. * Check if this URL is a redirect and return redir info.
  70. *
  71. * Most code should call File_redirection::where instead, to check if we
  72. * already know that redirection and avoid extra hits to the web.
  73. *
  74. * The URL is hit and any redirects are followed, up to 10 levels or until
  75. * a protected URL is reached.
  76. *
  77. * @param string $in_url
  78. * @return mixed one of:
  79. * string - target URL, if this is a direct link or can't be followed
  80. * array - redirect info if this is an *unknown* redirect:
  81. * associative array with the following elements:
  82. * code: HTTP status code
  83. * redirects: count of redirects followed
  84. * url: URL string of final target
  85. * type (optional): MIME type from Content-Type header
  86. * size (optional): byte size from Content-Length header
  87. * time (optional): timestamp from Last-Modified header
  88. */
  89. static function lookupWhere($short_url, $redirs = 10, $protected = false) {
  90. if ($redirs < 0) return false;
  91. if(strpos($short_url,'://') === false){
  92. return $short_url;
  93. }
  94. try {
  95. $request = self::_commonHttp($short_url, $redirs);
  96. // Don't include body in output
  97. $request->setMethod(HTTP_Request2::METHOD_HEAD);
  98. $response = $request->send();
  99. if (405 == $response->getStatus() || 204 == $response->getStatus()) {
  100. // HTTP 405 Unsupported Method
  101. // Server doesn't support HEAD method? Can this really happen?
  102. // We'll try again as a GET and ignore the response data.
  103. //
  104. // HTTP 204 No Content
  105. // YFrog sends 204 responses back for our HEAD checks, which
  106. // seems like it may be a logic error in their servers. If
  107. // we get a 204 back, re-run it as a GET... if there's really
  108. // no content it'll be cheap. :)
  109. $request = self::_commonHttp($short_url, $redirs);
  110. $response = $request->send();
  111. } elseif (400 == $response->getStatus()) {
  112. throw new Exception('Got error 400 on HEAD request, will not go further.');
  113. }
  114. } catch (Exception $e) {
  115. // Invalid URL or failure to reach server
  116. common_log(LOG_ERR, "Error while following redirects for $short_url: " . $e->getMessage());
  117. return $short_url;
  118. }
  119. // if last url after all redirections is protected,
  120. // use the url before it in the redirection chain
  121. if ($response->getRedirectCount() && File::isProtected($response->getEffectiveUrl())) {
  122. $return_url = $response->redirUrls[$response->getRedirectCount()-1];
  123. } else {
  124. $return_url = $response->getEffectiveUrl();
  125. }
  126. $ret = array('code' => $response->getStatus()
  127. , 'redirects' => $response->getRedirectCount()
  128. , 'url' => $return_url);
  129. $type = $response->getHeader('Content-Type');
  130. if ($type) $ret['type'] = $type;
  131. if ($protected) $ret['protected'] = true;
  132. $size = $response->getHeader('Content-Length'); // @fixme bytes?
  133. if ($size) $ret['size'] = $size;
  134. $time = $response->getHeader('Last-Modified');
  135. if ($time) $ret['time'] = strtotime($time);
  136. return $ret;
  137. }
  138. /**
  139. * Check if this URL is a redirect and return redir info.
  140. * If a File record is present for this URL, it is not considered a redirect.
  141. * If a File_redirection record is present for this URL, the recorded target is returned.
  142. *
  143. * If no File or File_redirect record is present, the URL is hit and any
  144. * redirects are followed, up to 10 levels or until a protected URL is
  145. * reached.
  146. *
  147. * @param string $in_url
  148. * @param boolean $discover true to attempt dereferencing the redirect if we don't know it already
  149. * @return File_redirection
  150. */
  151. static function where($in_url, $discover=true) {
  152. $redir = new File_redirection();
  153. $redir->url = $in_url;
  154. $redir->urlhash = File::hashurl($redir->url);
  155. $redir->redirections = 0;
  156. try {
  157. $r = File_redirection::getByUrl($in_url);
  158. if($r instanceof File_redirection) {
  159. try {
  160. $f = File::getKV('id',$r->file_id);
  161. $r->file = $f;
  162. $r->redir_url = $f->url;
  163. } catch (NoResultException $e) {
  164. // Invalid entry, delete and run again
  165. 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.");
  166. $r->delete();
  167. return self::where($in_url);
  168. }
  169. return $r;
  170. }
  171. } catch (NoResultException $e) {
  172. try {
  173. $f = File::getByUrl($in_url);
  174. $redir->file_id = $f->id;
  175. $redir->file = $f;
  176. return $redir;
  177. } catch (NoResultException $e) {
  178. // Oh well, let's keep going
  179. }
  180. }
  181. if ($discover) {
  182. $redir_info = File_redirection::lookupWhere($in_url);
  183. if(is_string($redir_info)) {
  184. $redir_info = array('url' => $redir_info);
  185. }
  186. // Save the file if we don't have it already
  187. $redir->file = File::saveNew($redir_info,$redir_info['url']);
  188. // If this is a redirection, save it
  189. // (if it hasn't been saved yet by some other process while we we
  190. // were running lookupWhere())
  191. if($redir_info['url'] != $in_url) {
  192. try {
  193. $file_redir = File_redirection::getByUrl($in_url);
  194. } catch (NoResultException $e) {
  195. $file_redir = new File_redirection();
  196. $file_redir->urlhash = File::hashurl($in_url);
  197. $file_redir->url = $in_url;
  198. $file_redir->file_id = $redir->file->getID();
  199. $file_redir->insert();
  200. $file_redir->redir_url = $redir->file->url;
  201. }
  202. $file_redir->file = $redir->file;
  203. return $file_redir;
  204. }
  205. }
  206. return $redir;
  207. }
  208. /**
  209. * Shorten a URL with the current user's configured shortening
  210. * options, if applicable.
  211. *
  212. * If it cannot be shortened or the "short" URL is longer than the
  213. * original, the original is returned.
  214. *
  215. * If the referenced item has not been seen before, embedding data
  216. * may be saved.
  217. *
  218. * @param string $long_url
  219. * @param User $user whose shortening options to use; defaults to the current web session user
  220. * @return string
  221. */
  222. static function makeShort($long_url, $user=null)
  223. {
  224. $canon = File_redirection::_canonUrl($long_url);
  225. $short_url = File_redirection::_userMakeShort($canon, $user);
  226. // Did we get one? Is it shorter?
  227. return !empty($short_url) ? $short_url : $long_url;
  228. }
  229. /**
  230. * Shorten a URL with the current user's configured shortening
  231. * options, if applicable.
  232. *
  233. * If it cannot be shortened or the "short" URL is longer than the
  234. * original, the original is returned.
  235. *
  236. * If the referenced item has not been seen before, embedding data
  237. * may be saved.
  238. *
  239. * @param string $long_url
  240. * @return string
  241. */
  242. static function forceShort($long_url, $user)
  243. {
  244. $canon = File_redirection::_canonUrl($long_url);
  245. $short_url = File_redirection::_userMakeShort($canon, $user, true);
  246. // Did we get one? Is it shorter?
  247. return !empty($short_url) ? $short_url : $long_url;
  248. }
  249. static function _userMakeShort($long_url, User $user=null, $force = false) {
  250. $short_url = common_shorten_url($long_url, $user, $force);
  251. if (!empty($short_url) && $short_url != $long_url) {
  252. $short_url = (string)$short_url;
  253. // store it
  254. try {
  255. $file = File::getByUrl($long_url);
  256. } catch (NoResultException $e) {
  257. // Check if the target URL is itself a redirect...
  258. // This should already have happened in processNew in common_shorten_url()
  259. $redir = File_redirection::where($long_url);
  260. $file = $redir->file;
  261. }
  262. // Now we definitely have a File object in $file
  263. try {
  264. $file_redir = File_redirection::getByUrl($short_url);
  265. } catch (NoResultException $e) {
  266. $file_redir = new File_redirection();
  267. $file_redir->urlhash = File::hashurl($short_url);
  268. $file_redir->url = $short_url;
  269. $file_redir->file_id = $file->getID();
  270. $file_redir->insert();
  271. }
  272. return $short_url;
  273. }
  274. return null;
  275. }
  276. /**
  277. * Basic attempt to canonicalize a URL, cleaning up some standard variants
  278. * such as funny syntax or a missing path. Used internally when cleaning
  279. * up URLs for storage and following redirect chains.
  280. *
  281. * Note that despite being on File_redirect, this function DOES NOT perform
  282. * any dereferencing of redirects.
  283. *
  284. * @param string $in_url input URL
  285. * @param string $default_scheme if given a bare link; defaults to 'http://'
  286. * @return string
  287. */
  288. static function _canonUrl($in_url, $default_scheme = 'http://') {
  289. if (empty($in_url)) return false;
  290. $out_url = $in_url;
  291. $p = parse_url($out_url);
  292. if (empty($p['host']) || empty($p['scheme'])) {
  293. list($scheme) = explode(':', $in_url, 2);
  294. switch (strtolower($scheme)) {
  295. case 'fax':
  296. case 'tel':
  297. $out_url = str_replace('.-()', '', $out_url);
  298. break;
  299. // non-HTTP schemes, so no redirects
  300. case 'bitcoin':
  301. case 'mailto':
  302. case 'aim':
  303. case 'jabber':
  304. case 'xmpp':
  305. // don't touch anything
  306. break;
  307. // URLs without domain name, so no redirects
  308. case 'magnet':
  309. // don't touch anything
  310. break;
  311. // URLs with coordinates, not browsable domain names
  312. case 'geo':
  313. // don't touch anything
  314. break;
  315. default:
  316. $out_url = $default_scheme . ltrim($out_url, '/');
  317. $p = parse_url($out_url);
  318. if (empty($p['scheme'])) return false;
  319. break;
  320. }
  321. }
  322. if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
  323. if (empty($p['host'])) return false;
  324. if (empty($p['path'])) {
  325. $out_url .= '/';
  326. }
  327. }
  328. return $out_url;
  329. }
  330. static function saveNew($data, $file_id, $url) {
  331. $file_redir = new File_redirection;
  332. $file_redir->urlhash = File::hashurl($url);
  333. $file_redir->url = $url;
  334. $file_redir->file_id = $file_id;
  335. $file_redir->redirections = intval($data['redirects']);
  336. $file_redir->httpcode = intval($data['code']);
  337. $file_redir->insert();
  338. }
  339. static public function beforeSchemaUpdate()
  340. {
  341. $table = strtolower(get_called_class());
  342. $schema = Schema::get();
  343. $schemadef = $schema->getTableDef($table);
  344. // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
  345. if (isset($schemadef['fields']['urlhash']) && in_array('urlhash', $schemadef['primary key'])) {
  346. // We already have the urlhash field, so no need to migrate it.
  347. return;
  348. }
  349. echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
  350. // We have to create a urlhash that is _not_ the primary key,
  351. // transfer data and THEN run checkSchema
  352. $schemadef['fields']['urlhash'] = array (
  353. 'type' => 'varchar',
  354. 'length' => 64,
  355. 'not null' => true,
  356. 'description' => 'sha256 hash of the URL',
  357. );
  358. $schemadef['fields']['url'] = array (
  359. 'type' => 'text',
  360. 'description' => 'short URL (or any other kind of redirect) for file (id)',
  361. );
  362. unset($schemadef['primary key']);
  363. $schema->ensureTable($table, $schemadef);
  364. echo "DONE.\n";
  365. $classname = ucfirst($table);
  366. $tablefix = new $classname;
  367. // urlhash is hash('sha256', $url) in the File table
  368. echo "Updating urlhash fields in $table table...";
  369. // Maybe very MySQL specific :(
  370. $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
  371. $schema->quoteIdentifier($table),
  372. 'urlhash',
  373. // The line below is "result of sha256 on column `url`"
  374. 'SHA2(url, 256)'));
  375. echo "DONE.\n";
  376. echo "Resuming core schema upgrade...";
  377. }
  378. public function getFile() {
  379. if(empty($this->file) && $this->file_id) {
  380. $this->file = File::getKV('id', $this->file_id);
  381. }
  382. return $this->file;
  383. }
  384. }