File_redirection.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. defined('GNUSOCIAL') || die();
  17. /**
  18. * Table Definition for file_redirection
  19. */
  20. class File_redirection extends Managed_DataObject
  21. {
  22. ###START_AUTOCODE
  23. /* the code below is auto generated do not remove the above tag */
  24. public $__table = 'file_redirection'; // table name
  25. public $urlhash; // varchar(64) primary_key not_null
  26. public $url; // text
  27. public $file_id; // int(4)
  28. public $redirections; // int(4)
  29. public $httpcode; // int(4)
  30. public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
  31. /* the code above is auto generated do not remove the tag below */
  32. ###END_AUTOCODE
  33. protected $file; /* Cache the associated file sometimes */
  34. public static function schemaDef()
  35. {
  36. return array(
  37. 'fields' => array(
  38. 'urlhash' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'sha256 hash of the URL'),
  39. 'url' => array('type' => 'text', 'description' => 'short URL (or any other kind of redirect) for file (id)'),
  40. 'file_id' => array('type' => 'int', 'description' => 'short URL for what URL/file'),
  41. 'redirections' => array('type' => 'int', 'description' => 'redirect count'),
  42. 'httpcode' => array('type' => 'int', 'description' => 'HTTP status code (20x, 30x, etc.)'),
  43. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  44. ),
  45. 'primary key' => array('urlhash'),
  46. 'foreign keys' => array(
  47. 'file_redirection_file_id_fkey' => array('file', array('file_id' => 'id')),
  48. ),
  49. 'indexes' => array(
  50. 'file_redirection_file_id_idx' => array('file_id'),
  51. ),
  52. );
  53. }
  54. public static function getByUrl($url)
  55. {
  56. return self::getByPK(array('urlhash' => File::hashurl($url)));
  57. }
  58. public static function _commonHttp($url, $redirs)
  59. {
  60. $request = new HTTPClient($url);
  61. $request->setConfig(array(
  62. 'connect_timeout' => 10, // # seconds to wait
  63. 'max_redirs' => $redirs, // # max number of http redirections to follow
  64. 'follow_redirects' => false, // We follow redirects ourselves in lib/httpclient.php
  65. 'store_body' => false, // We won't need body content here.
  66. ));
  67. return $request;
  68. }
  69. /**
  70. * Check if this URL is a redirect and return redir info.
  71. *
  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.
  74. *
  75. * The URL is hit and any redirects are followed, up to 10 levels or until
  76. * a protected URL is reached.
  77. *
  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
  89. */
  90. public static function lookupWhere($short_url, $redirs = 10, $protected = false)
  91. {
  92. if ($redirs < 0) {
  93. return false;
  94. }
  95. if (strpos($short_url, '://') === false) {
  96. return $short_url;
  97. }
  98. try {
  99. $request = self::_commonHttp($short_url, $redirs);
  100. // Don't include body in output
  101. $request->setMethod(HTTP_Request2::METHOD_HEAD);
  102. $response = $request->send();
  103. if (405 == $response->getStatus() || 204 == $response->getStatus()) {
  104. // HTTP 405 Unsupported Method
  105. // Server doesn't support HEAD method? Can this really happen?
  106. // We'll try again as a GET and ignore the response data.
  107. //
  108. // HTTP 204 No Content
  109. // YFrog sends 204 responses back for our HEAD checks, which
  110. // seems like it may be a logic error in their servers. If
  111. // we get a 204 back, re-run it as a GET... if there's really
  112. // no content it'll be cheap. :)
  113. $request = self::_commonHttp($short_url, $redirs);
  114. $response = $request->send();
  115. } elseif (400 == $response->getStatus()) {
  116. throw new Exception('Got error 400 on HEAD request, will not go further.');
  117. }
  118. } catch (Exception $e) {
  119. // Invalid URL or failure to reach server
  120. common_log(LOG_ERR, "Error while following redirects for $short_url: " . $e->getMessage());
  121. return $short_url;
  122. }
  123. // if last url after all redirections is protected,
  124. // use the url before it in the redirection chain
  125. if ($response->getRedirectCount() && File::isProtected($response->getEffectiveUrl())) {
  126. $return_url = $response->redirUrls[$response->getRedirectCount() - 1];
  127. } else {
  128. $return_url = $response->getEffectiveUrl();
  129. }
  130. $ret = array('code' => $response->getStatus()
  131. , 'redirects' => $response->getRedirectCount()
  132. , 'url' => $return_url);
  133. $type = $response->getHeader('Content-Type');
  134. if ($type) {
  135. $ret['type'] = $type;
  136. }
  137. if ($protected) {
  138. $ret['protected'] = true;
  139. }
  140. $size = $response->getHeader('Content-Length'); // @fixme bytes?
  141. if ($size) {
  142. $ret['size'] = $size;
  143. }
  144. $time = $response->getHeader('Last-Modified');
  145. if ($time) {
  146. $ret['time'] = strtotime($time);
  147. }
  148. return $ret;
  149. }
  150. /**
  151. * Check if this URL is a redirect and return redir info.
  152. * If a File record is present for this URL, it is not considered a redirect.
  153. * If a File_redirection record is present for this URL, the recorded target is returned.
  154. *
  155. * If no File or File_redirect record is present, the URL is hit and any
  156. * redirects are followed, up to 10 levels or until a protected URL is
  157. * reached.
  158. *
  159. * @param string $in_url
  160. * @param boolean $discover true to attempt dereferencing the redirect if we don't know it already
  161. * @return File_redirection
  162. */
  163. public static function where($in_url, $discover = true)
  164. {
  165. $redir = new File_redirection();
  166. $redir->url = $in_url;
  167. $redir->urlhash = File::hashurl($redir->url);
  168. $redir->redirections = 0;
  169. try {
  170. $r = File_redirection::getByUrl($in_url);
  171. try {
  172. $f = File::getByID($r->file_id);
  173. $r->file = $f;
  174. $r->redir_url = $f->url;
  175. } catch (NoResultException $e) {
  176. // Invalid entry, delete and run again
  177. common_log(
  178. LOG_ERR,
  179. 'Could not find File with id=' . $r->file_id . ' referenced in File_redirection, deleting File redirection entry and and trying again...'
  180. );
  181. $r->delete();
  182. return self::where($in_url);
  183. }
  184. // File_redirecion and File record found, return both
  185. return $r;
  186. } catch (NoResultException $e) {
  187. // File_redirecion record not found, but this might be a direct link to a file
  188. try {
  189. $f = File::getByUrl($in_url);
  190. $redir->file_id = $f->id;
  191. $redir->file = $f;
  192. return $redir;
  193. } catch (NoResultException $e) {
  194. // nope, this was not a direct link to a file either, let's keep going
  195. }
  196. }
  197. if ($discover) {
  198. // try to follow redirects and get the final url
  199. $redir_info = File_redirection::lookupWhere($in_url);
  200. if (is_string($redir_info)) {
  201. $redir_info = array('url' => $redir_info);
  202. }
  203. // the last url in the redirection chain can actually be a redirect!
  204. // this is the case with local /attachment/{file_id} links
  205. // in that case we have the file id already
  206. try {
  207. $r = File_redirection::getByUrl($redir_info['url']);
  208. $f = File::getKV('id', $r->file_id);
  209. if ($f instanceof File) {
  210. $redir->file = $f;
  211. $redir->redir_url = $f->url;
  212. } else {
  213. // Invalid entry in File_redirection, delete and run again
  214. common_log(
  215. LOG_ERR,
  216. 'Could not find File with id=' . $r->file_id . ' referenced in File_redirection, deleting File_redirection entry and trying again...'
  217. );
  218. $r->delete();
  219. return self::where($in_url);
  220. }
  221. } catch (NoResultException $e) {
  222. // save the file now when we know that we don't have it in File_redirection
  223. try {
  224. $redir->file = File::saveNew($redir_info, $redir_info['url']);
  225. } catch (ServerException $e) {
  226. common_log(LOG_ERR, $e);
  227. }
  228. }
  229. // If this is a redirection and we have a file to redirect to, save it
  230. // (if it doesn't exist in File_redirection already)
  231. if ($redir->file instanceof File && $redir_info['url'] != $in_url) {
  232. try {
  233. $file_redir = File_redirection::getByUrl($in_url);
  234. } catch (NoResultException $e) {
  235. $file_redir = new File_redirection();
  236. $file_redir->urlhash = File::hashurl($in_url);
  237. $file_redir->url = $in_url;
  238. $file_redir->file_id = $redir->file->getID();
  239. $file_redir->insert();
  240. $file_redir->redir_url = $redir->file->url;
  241. }
  242. $file_redir->file = $redir->file;
  243. return $file_redir;
  244. }
  245. }
  246. return $redir;
  247. }
  248. /**
  249. * Shorten a URL with the current user's configured shortening
  250. * options, if applicable.
  251. *
  252. * If it cannot be shortened or the "short" URL is longer than the
  253. * original, the original is returned.
  254. *
  255. * If the referenced item has not been seen before, embedding data
  256. * may be saved.
  257. *
  258. * @param string $long_url
  259. * @param User $user whose shortening options to use; defaults to the current web session user
  260. * @return string
  261. */
  262. public static function makeShort($long_url, $user = null)
  263. {
  264. $canon = File_redirection::_canonUrl($long_url);
  265. $short_url = File_redirection::_userMakeShort($canon, $user);
  266. // Did we get one? Is it shorter?
  267. return !empty($short_url) ? $short_url : $long_url;
  268. }
  269. /**
  270. * Shorten a URL with the current user's configured shortening
  271. * options, if applicable.
  272. *
  273. * If it cannot be shortened or the "short" URL is longer than the
  274. * original, the original is returned.
  275. *
  276. * If the referenced item has not been seen before, embedding data
  277. * may be saved.
  278. *
  279. * @param string $long_url
  280. * @return string
  281. */
  282. public static function forceShort($long_url, $user)
  283. {
  284. $canon = File_redirection::_canonUrl($long_url);
  285. $short_url = File_redirection::_userMakeShort($canon, $user, true);
  286. // Did we get one? Is it shorter?
  287. return !empty($short_url) ? $short_url : $long_url;
  288. }
  289. public static function _userMakeShort($long_url, User $user = null, $force = false)
  290. {
  291. $short_url = common_shorten_url($long_url, $user, $force);
  292. if (!empty($short_url) && $short_url != $long_url) {
  293. $short_url = (string)$short_url;
  294. // store it
  295. try {
  296. $file = File::getByUrl($long_url);
  297. } catch (NoResultException $e) {
  298. // Check if the target URL is itself a redirect...
  299. // This should already have happened in processNew in common_shorten_url()
  300. $redir = File_redirection::where($long_url);
  301. $file = $redir->file;
  302. }
  303. // Now we definitely have a File object in $file
  304. try {
  305. $file_redir = File_redirection::getByUrl($short_url);
  306. } catch (NoResultException $e) {
  307. $file_redir = new File_redirection();
  308. $file_redir->urlhash = File::hashurl($short_url);
  309. $file_redir->url = $short_url;
  310. $file_redir->file_id = $file->getID();
  311. $file_redir->insert();
  312. }
  313. return $short_url;
  314. }
  315. return null;
  316. }
  317. /**
  318. * Basic attempt to canonicalize a URL, cleaning up some standard variants
  319. * such as funny syntax or a missing path. Used internally when cleaning
  320. * up URLs for storage and following redirect chains.
  321. *
  322. * Note that despite being on File_redirect, this function DOES NOT perform
  323. * any dereferencing of redirects.
  324. *
  325. * @param string $in_url input URL
  326. * @param string $default_scheme if given a bare link; defaults to 'http://'
  327. * @return string
  328. */
  329. public static function _canonUrl($in_url, $default_scheme = 'http://')
  330. {
  331. if (empty($in_url)) {
  332. return false;
  333. }
  334. $out_url = $in_url;
  335. $p = parse_url($out_url);
  336. if (empty($p['host']) || empty($p['scheme'])) {
  337. list($scheme) = explode(':', $in_url, 2);
  338. switch (strtolower($scheme)) {
  339. case 'fax':
  340. case 'tel':
  341. $out_url = str_replace('.-()', '', $out_url);
  342. break;
  343. // non-HTTP schemes, so no redirects
  344. case 'bitcoin':
  345. case 'mailto':
  346. case 'aim':
  347. case 'jabber':
  348. case 'xmpp':
  349. // don't touch anything
  350. break;
  351. // URLs without domain name, so no redirects
  352. case 'magnet':
  353. // don't touch anything
  354. break;
  355. // URLs with coordinates, not browsable domain names
  356. case 'geo':
  357. // don't touch anything
  358. break;
  359. default:
  360. $out_url = $default_scheme . ltrim($out_url, '/');
  361. $p = parse_url($out_url);
  362. if (empty($p['scheme'])) {
  363. return false;
  364. }
  365. break;
  366. }
  367. }
  368. if (('ftp' == $p['scheme']) || ('ftps' == $p['scheme']) || ('http' == $p['scheme']) || ('https' == $p['scheme'])) {
  369. if (empty($p['host'])) {
  370. return false;
  371. }
  372. if (empty($p['path'])) {
  373. $out_url .= '/';
  374. }
  375. }
  376. return $out_url;
  377. }
  378. public static function saveNew($data, $file_id, $url)
  379. {
  380. $file_redir = new File_redirection;
  381. $file_redir->urlhash = File::hashurl($url);
  382. $file_redir->url = $url;
  383. $file_redir->file_id = $file_id;
  384. $file_redir->redirections = intval($data['redirects']);
  385. $file_redir->httpcode = intval($data['code']);
  386. $file_redir->insert();
  387. }
  388. public static function beforeSchemaUpdate()
  389. {
  390. $table = strtolower(get_called_class());
  391. $schema = Schema::get();
  392. $schemadef = $schema->getTableDef($table);
  393. // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
  394. if (isset($schemadef['fields']['urlhash']) && in_array('urlhash', $schemadef['primary key'])) {
  395. // We already have the urlhash field, so no need to migrate it.
  396. return;
  397. }
  398. echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
  399. // We have to create a urlhash that is _not_ the primary key,
  400. // transfer data and THEN run checkSchema
  401. $schemadef['fields']['urlhash'] = [
  402. 'type' => 'varchar',
  403. 'length' => 64,
  404. 'not null' => true,
  405. 'description' => 'sha256 hash of the URL',
  406. ];
  407. $schemadef['fields']['url'] = [
  408. 'type' => 'text',
  409. 'description' => 'short URL (or any other kind of redirect) for file (id)',
  410. ];
  411. unset($schemadef['primary key']);
  412. $schema->ensureTable($table, $schemadef);
  413. echo "DONE.\n";
  414. $classname = ucfirst($table);
  415. $tablefix = new $classname;
  416. // urlhash is hash('sha256', $url) in the File table
  417. echo "Updating urlhash fields in $table table...";
  418. switch (common_config('db', 'type')) {
  419. case 'pgsql':
  420. $url_sha256 = 'encode(sha256(CAST("url" AS bytea)), \'hex\')';
  421. break;
  422. case 'mysql':
  423. $url_sha256 = 'sha2(`url`, 256)';
  424. break;
  425. default:
  426. throw new ServerException('Unknown DB type selected.');
  427. }
  428. $tablefix->query(sprintf(
  429. 'UPDATE %1$s SET urlhash = %2$s, modified = CURRENT_TIMESTAMP;',
  430. $tablefix->escapedTableName(),
  431. $url_sha256
  432. ));
  433. echo "DONE.\n";
  434. echo "Resuming core schema upgrade...";
  435. }
  436. public function getFile()
  437. {
  438. if (!$this->file instanceof File) {
  439. $this->file = File::getByID($this->file_id);
  440. }
  441. return $this->file;
  442. }
  443. }