File_redirection.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. try {
  159. $f = File::getByID($r->file_id);
  160. $r->file = $f;
  161. $r->redir_url = $f->url;
  162. } catch (NoResultException $e) {
  163. // Invalid entry, delete and run again
  164. common_log(LOG_ERR, "Could not find File with id=".$r->file_id." referenced in File_redirection, deleting File redirection entry and and trying again...");
  165. $r->delete();
  166. return self::where($in_url);
  167. }
  168. // File_redirecion and File record found, return both
  169. return $r;
  170. } catch (NoResultException $e) {
  171. // File_redirecion record not found, but this might be a direct link to a file
  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. // nope, this was not a direct link to a file either, let's keep going
  179. }
  180. }
  181. if ($discover) {
  182. // try to follow redirects and get the final url
  183. $redir_info = File_redirection::lookupWhere($in_url);
  184. if(is_string($redir_info)) {
  185. $redir_info = array('url' => $redir_info);
  186. }
  187. // the last url in the redirection chain can actually be a redirect!
  188. // this is the case with local /attachment/{file_id} links
  189. // in that case we have the file id already
  190. try {
  191. $r = File_redirection::getByUrl($redir_info['url']);
  192. $f = File::getKV('id',$r->file_id);
  193. if($f instanceof File) {
  194. $redir->file = $f;
  195. $redir->redir_url = $f->url;
  196. } else {
  197. // Invalid entry in File_redirection, delete and run again
  198. common_log(LOG_ERR, "Could not find File with id=".$r->file_id." referenced in File_redirection, deleting File_redirection entry and trying again...");
  199. $r->delete();
  200. return self::where($in_url);
  201. }
  202. } catch (NoResultException $e) {
  203. // save the file now when we know that we don't have it in File_redirection
  204. try {
  205. $redir->file = File::saveNew($redir_info,$redir_info['url']);
  206. } catch (ServerException $e) {
  207. common_log(LOG_ERR, $e);
  208. }
  209. }
  210. // If this is a redirection and we have a file to redirect to, save it
  211. // (if it doesn't exist in File_redirection already)
  212. if($redir->file instanceof File && $redir_info['url'] != $in_url) {
  213. try {
  214. $file_redir = File_redirection::getByUrl($in_url);
  215. } catch (NoResultException $e) {
  216. $file_redir = new File_redirection();
  217. $file_redir->urlhash = File::hashurl($in_url);
  218. $file_redir->url = $in_url;
  219. $file_redir->file_id = $redir->file->getID();
  220. $file_redir->insert();
  221. $file_redir->redir_url = $redir->file->url;
  222. }
  223. $file_redir->file = $redir->file;
  224. return $file_redir;
  225. }
  226. }
  227. return $redir;
  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. * @param User $user whose shortening options to use; defaults to the current web session user
  241. * @return string
  242. */
  243. static function makeShort($long_url, $user=null)
  244. {
  245. $canon = File_redirection::_canonUrl($long_url);
  246. $short_url = File_redirection::_userMakeShort($canon, $user);
  247. // Did we get one? Is it shorter?
  248. return !empty($short_url) ? $short_url : $long_url;
  249. }
  250. /**
  251. * Shorten a URL with the current user's configured shortening
  252. * options, if applicable.
  253. *
  254. * If it cannot be shortened or the "short" URL is longer than the
  255. * original, the original is returned.
  256. *
  257. * If the referenced item has not been seen before, embedding data
  258. * may be saved.
  259. *
  260. * @param string $long_url
  261. * @return string
  262. */
  263. static function forceShort($long_url, $user)
  264. {
  265. $canon = File_redirection::_canonUrl($long_url);
  266. $short_url = File_redirection::_userMakeShort($canon, $user, true);
  267. // Did we get one? Is it shorter?
  268. return !empty($short_url) ? $short_url : $long_url;
  269. }
  270. static function _userMakeShort($long_url, User $user=null, $force = false) {
  271. $short_url = common_shorten_url($long_url, $user, $force);
  272. if (!empty($short_url) && $short_url != $long_url) {
  273. $short_url = (string)$short_url;
  274. // store it
  275. try {
  276. $file = File::getByUrl($long_url);
  277. } catch (NoResultException $e) {
  278. // Check if the target URL is itself a redirect...
  279. // This should already have happened in processNew in common_shorten_url()
  280. $redir = File_redirection::where($long_url);
  281. $file = $redir->file;
  282. }
  283. // Now we definitely have a File object in $file
  284. try {
  285. $file_redir = File_redirection::getByUrl($short_url);
  286. } catch (NoResultException $e) {
  287. $file_redir = new File_redirection();
  288. $file_redir->urlhash = File::hashurl($short_url);
  289. $file_redir->url = $short_url;
  290. $file_redir->file_id = $file->getID();
  291. $file_redir->insert();
  292. }
  293. return $short_url;
  294. }
  295. return null;
  296. }
  297. /**
  298. * Basic attempt to canonicalize a URL, cleaning up some standard variants
  299. * such as funny syntax or a missing path. Used internally when cleaning
  300. * up URLs for storage and following redirect chains.
  301. *
  302. * Note that despite being on File_redirect, this function DOES NOT perform
  303. * any dereferencing of redirects.
  304. *
  305. * @param string $in_url input URL
  306. * @param string $default_scheme if given a bare link; defaults to 'http://'
  307. * @return string
  308. */
  309. static function _canonUrl($in_url, $default_scheme = 'http://') {
  310. if (empty($in_url)) return false;
  311. $out_url = $in_url;
  312. $p = parse_url($out_url);
  313. if (empty($p['host']) || empty($p['scheme'])) {
  314. list($scheme) = explode(':', $in_url, 2);
  315. switch (strtolower($scheme)) {
  316. case 'fax':
  317. case 'tel':
  318. $out_url = str_replace('.-()', '', $out_url);
  319. break;
  320. // non-HTTP schemes, so no redirects
  321. case 'bitcoin':
  322. case 'mailto':
  323. case 'aim':
  324. case 'jabber':
  325. case 'xmpp':
  326. // don't touch anything
  327. break;
  328. // URLs without domain name, so no redirects
  329. case 'magnet':
  330. // don't touch anything
  331. break;
  332. // URLs with coordinates, not browsable domain names
  333. case 'geo':
  334. // don't touch anything
  335. break;
  336. default:
  337. $out_url = $default_scheme . ltrim($out_url, '/');
  338. $p = parse_url($out_url);
  339. if (empty($p['scheme'])) return false;
  340. break;
  341. }
  342. }
  343. if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
  344. if (empty($p['host'])) return false;
  345. if (empty($p['path'])) {
  346. $out_url .= '/';
  347. }
  348. }
  349. return $out_url;
  350. }
  351. static function saveNew($data, $file_id, $url) {
  352. $file_redir = new File_redirection;
  353. $file_redir->urlhash = File::hashurl($url);
  354. $file_redir->url = $url;
  355. $file_redir->file_id = $file_id;
  356. $file_redir->redirections = intval($data['redirects']);
  357. $file_redir->httpcode = intval($data['code']);
  358. $file_redir->insert();
  359. }
  360. static public function beforeSchemaUpdate()
  361. {
  362. $table = strtolower(get_called_class());
  363. $schema = Schema::get();
  364. $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.
  368. return;
  369. }
  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 (
  374. 'type' => 'varchar',
  375. 'length' => 64,
  376. 'not null' => true,
  377. 'description' => 'sha256 hash of the URL',
  378. );
  379. $schemadef['fields']['url'] = array (
  380. 'type' => 'text',
  381. 'description' => 'short URL (or any other kind of redirect) for file (id)',
  382. );
  383. unset($schemadef['primary key']);
  384. $schema->ensureTable($table, $schemadef);
  385. echo "DONE.\n";
  386. $classname = ucfirst($table);
  387. $tablefix = new $classname;
  388. // urlhash is hash('sha256', $url) in the File table
  389. echo "Updating urlhash fields in $table table...";
  390. // Maybe very MySQL specific :(
  391. $tablefix->query(sprintf('UPDATE %1$s SET %2$s=%3$s;',
  392. $schema->quoteIdentifier($table),
  393. 'urlhash',
  394. // The line below is "result of sha256 on column `url`"
  395. 'SHA2(url, 256)'));
  396. echo "DONE.\n";
  397. echo "Resuming core schema upgrade...";
  398. }
  399. public function getFile() {
  400. if (!$this->file instanceof File) {
  401. $this->file = File::getByID($this->file_id);
  402. }
  403. return $this->file;
  404. }
  405. }