File.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. /**
  17. * @category Files
  18. * @package GNUsocial
  19. * @author Mikael Nordfeldth <mmn@hethane.se>
  20. * @author Miguel Dantas <biodantas@gmail.com>
  21. * @copyright 2008-2009, 2019 Free Software Foundation http://fsf.org
  22. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  23. */
  24. defined('GNUSOCIAL') || die();
  25. /**
  26. * Table Definition for file
  27. */
  28. class File extends Managed_DataObject
  29. {
  30. public $__table = 'file'; // table name
  31. public $id; // int(4) primary_key not_null
  32. public $urlhash; // varchar(64) unique_key
  33. public $url; // text
  34. public $filehash; // varchar(64) indexed
  35. public $mimetype; // varchar(50)
  36. public $size; // int(4)
  37. public $title; // text()
  38. public $date; // int(4)
  39. public $protected; // int(4)
  40. public $filename; // text()
  41. public $width; // int(4)
  42. public $height; // int(4)
  43. public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
  44. const URLHASH_ALG = 'sha256';
  45. const FILEHASH_ALG = 'sha256';
  46. public static function schemaDef()
  47. {
  48. return array(
  49. 'fields' => array(
  50. 'id' => array('type' => 'serial', 'not null' => true),
  51. 'urlhash' => array('type' => 'varchar', 'length' => 64, 'description' => 'sha256 of destination URL (url field)'),
  52. 'url' => array('type' => 'text', 'description' => 'destination URL after following possible redirections'),
  53. 'filehash' => array('type' => 'varchar', 'length' => 64, 'not null' => false, 'description' => 'sha256 of the file contents, only for locally stored files of course'),
  54. 'mimetype' => array('type' => 'varchar', 'length' => 50, 'description' => 'mime type of resource'),
  55. 'size' => array('type' => 'int', 'description' => 'size of resource when available'),
  56. 'title' => array('type' => 'text', 'description' => 'title of resource when available'),
  57. 'date' => array('type' => 'int', 'description' => 'date of resource according to http query'),
  58. 'protected' => array('type' => 'int', 'description' => 'true when URL is private (needs login)'),
  59. 'filename' => array('type' => 'text', 'description' => 'if file is stored locally (too) this is the filename'),
  60. 'width' => array('type' => 'int', 'description' => 'width in pixels, if it can be described as such and data is available'),
  61. 'height' => array('type' => 'int', 'description' => 'height in pixels, if it can be described as such and data is available'),
  62. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  63. ),
  64. 'primary key' => array('id'),
  65. 'unique keys' => array(
  66. 'file_urlhash_key' => array('urlhash'),
  67. ),
  68. 'indexes' => array(
  69. 'file_filehash_idx' => array('filehash'),
  70. ),
  71. );
  72. }
  73. public static function isProtected($url)
  74. {
  75. $protected_urls_exps = array(
  76. 'https://www.facebook.com/login.php',
  77. common_path('main/login')
  78. );
  79. foreach ($protected_urls_exps as $protected_url_exp) {
  80. if (preg_match('!^'.preg_quote($protected_url_exp).'(.*)$!i', $url) === 1) {
  81. return true;
  82. }
  83. }
  84. return false;
  85. }
  86. /**
  87. * Save a new file record.
  88. *
  89. * @param array $redir_data lookup data eg from File_redirection::where()
  90. * @param string $given_url
  91. * @return File
  92. * @throws ServerException
  93. */
  94. public static function saveNew(array $redir_data, $given_url)
  95. {
  96. $file = null;
  97. try {
  98. // I don't know why we have to keep doing this but we run a last check to avoid
  99. // uniqueness bugs.
  100. $file = File::getByUrl($given_url);
  101. return $file;
  102. } catch (NoResultException $e) {
  103. // We don't have the file's URL since before, so let's continue.
  104. }
  105. // If the given url is a local attachment url, don't save a new file record.
  106. $uh = parse_url($given_url, PHP_URL_HOST);
  107. $up = parse_url($given_url, PHP_URL_PATH);
  108. if ($uh == common_config('site', 'server') || $uh == common_config('attachments', 'server')) {
  109. unset($uh);
  110. $r = Router::get();
  111. // Skip the / in the beginning or $r->map won't match
  112. try {
  113. $args = $r->map(mb_substr($up, 1));
  114. if ($args['action'] === 'attachment' ||
  115. $args['action'] === 'attachment_view' ||
  116. $args['action'] === 'attachment_download' ||
  117. $args['action'] === 'attachment_thumbnail' ) {
  118. try {
  119. if (array_key_exists('attachment', $args)) {
  120. return File::getByID((int)$args['attachment']);
  121. } elseif (array_key_exists('filehash', $args)) {
  122. $file = File::getByHash($args['filehash']);
  123. $file->fetch();
  124. return $file;
  125. }
  126. } catch (NoResultException $e) {
  127. // apparently this link goes to us, but is _not_ an existing attachment (File) ID?
  128. }
  129. }
  130. } catch (Exception $e) {
  131. // Some other exception was thrown from $r->map, likely a
  132. // ClientException (404) because of some malformed link to
  133. // our own instance. It's still a valid URL however, so we
  134. // won't abort anything... I noticed this when linking:
  135. // https://social.umeahackerspace.se/mmn/foaf' (notice the
  136. // apostrophe in the end, making it unrecognizable for our
  137. // URL routing.
  138. // That specific issue (the apostrophe being part of a link
  139. // is something that may or may not have been fixed since,
  140. // in lib/util.php in common_replace_urls_callback().
  141. }
  142. }
  143. $file = new File;
  144. $file->url = $given_url;
  145. if (!empty($redir_data['protected'])) {
  146. $file->protected = $redir_data['protected'];
  147. }
  148. if (!empty($redir_data['title'])) {
  149. $file->title = $redir_data['title'];
  150. }
  151. if (!empty($redir_data['type'])) {
  152. $file->mimetype = $redir_data['type'];
  153. }
  154. if (!empty($redir_data['size'])) {
  155. $file->size = (int)$redir_data['size'];
  156. }
  157. if (isset($redir_data['time']) && $redir_data['time'] > 0) {
  158. $file->date = (int)$redir_data['time'];
  159. }
  160. $file->saveFile();
  161. return $file;
  162. }
  163. public function saveFile()
  164. {
  165. $this->urlhash = is_null($this->url) ? null : self::hashurl($this->url);
  166. if (!Event::handle('StartFileSaveNew', array(&$this))) {
  167. throw new ServerException('File not saved due to an aborted StartFileSaveNew event.');
  168. }
  169. $this->id = $this->insert();
  170. if ($this->id === false) {
  171. throw new ServerException('File/URL metadata could not be saved to the database.');
  172. }
  173. Event::handle('EndFileSaveNew', array($this));
  174. }
  175. /**
  176. * Go look at a URL and possibly save data about it if it's new:
  177. * - follow redirect chains and store them in file_redirection
  178. * - if a thumbnail is available, save it in file_thumbnail
  179. * - save file record with basic info
  180. * - optionally save a file_to_post record
  181. * - return the File object with the full reference
  182. *
  183. * @param string $given_url the URL we're looking at
  184. * @param Notice|null $notice (optional)
  185. * @param bool $followRedirects defaults to true
  186. *
  187. * @return mixed File on success, -1 on some errors
  188. *
  189. * @throws ServerException on failure
  190. */
  191. public static function processNew($given_url, ?Notice $notice=null, bool $followRedirects=true)
  192. {
  193. if (empty($given_url)) {
  194. throw new ServerException('No given URL to process');
  195. }
  196. $given_url = File_redirection::_canonUrl($given_url);
  197. if (empty($given_url)) {
  198. throw new ServerException('No canonical URL from given URL to process');
  199. }
  200. $redir = File_redirection::where($given_url);
  201. try {
  202. $file = $redir->getFile();
  203. } catch (EmptyPkeyValueException $e) {
  204. common_log(LOG_ERR, 'File_redirection::where gave object with empty file_id for given_url '._ve($given_url));
  205. throw new ServerException('URL processing failed without new File object');
  206. } catch (NoResultException $e) {
  207. // This should not happen
  208. common_log(LOG_ERR, 'File_redirection after discovery could still not return a File object.');
  209. throw new ServerException('URL processing failed without new File object');
  210. }
  211. if ($notice instanceof Notice) {
  212. File_to_post::processNew($file, $notice);
  213. }
  214. return $file;
  215. }
  216. public static function respectsQuota(Profile $scoped, $fileSize)
  217. {
  218. if ($fileSize > common_config('attachments', 'file_quota')) {
  219. // TRANS: Message used to be inserted as %2$s in the text "No file may
  220. // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
  221. // TRANS: %1$d is the number of bytes of an uploaded file.
  222. $fileSizeText = sprintf(_m('%1$d byte', '%1$d bytes', $fileSize), $fileSize);
  223. $fileQuota = common_config('attachments', 'file_quota');
  224. // TRANS: Message given if an upload is larger than the configured maximum.
  225. // TRANS: %1$d (used for plural) is the byte limit for uploads,
  226. // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
  227. // TRANS: gettext support multiple plurals in the same message, unfortunately...
  228. throw new ClientException(
  229. sprintf(
  230. _m(
  231. 'No file may be larger than %1$d byte and the file you sent was %2$s. Try to upload a smaller version.',
  232. 'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
  233. $fileQuota
  234. ),
  235. $fileQuota,
  236. $fileSizeText
  237. )
  238. );
  239. }
  240. $file = new File;
  241. $query = "SELECT sum(size) AS total
  242. FROM file
  243. INNER JOIN file_to_post
  244. ON file_to_post.file_id = file.id
  245. INNER JOIN notice
  246. ON file_to_post.post_id = notice.id
  247. WHERE profile_id = {$scoped->id} AND
  248. filename IS NULL AND
  249. file.url IS NOT NULL";
  250. $file->query($query);
  251. $file->fetch();
  252. $total = $file->total + $fileSize;
  253. if ($total > common_config('attachments', 'user_quota')) {
  254. // TRANS: Message given if an upload would exceed user quota.
  255. // TRANS: %d (number) is the user quota in bytes and is used for plural.
  256. throw new ClientException(
  257. sprintf(
  258. _m(
  259. 'A file this large would exceed your user quota of %d byte.',
  260. 'A file this large would exceed your user quota of %d bytes.',
  261. common_config('attachments', 'user_quota')
  262. ),
  263. common_config('attachments', 'user_quota')
  264. )
  265. );
  266. }
  267. $query .= ' AND EXTRACT(MONTH FROM file.modified) = EXTRACT(MONTH FROM CURRENT_DATE)'
  268. . ' AND EXTRACT(YEAR FROM file.modified) = EXTRACT(YEAR FROM CURRENT_DATE)';
  269. $file->query($query);
  270. $file->fetch();
  271. $total = $file->total + $fileSize;
  272. if ($total > common_config('attachments', 'monthly_quota')) {
  273. // TRANS: Message given id an upload would exceed a user's monthly quota.
  274. // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
  275. throw new ClientException(
  276. sprintf(
  277. _m(
  278. 'A file this large would exceed your monthly quota of %d byte.',
  279. 'A file this large would exceed your monthly quota of %d bytes.',
  280. common_config('attachments', 'monthly_quota')
  281. ),
  282. common_config('attachments', 'monthly_quota')
  283. )
  284. );
  285. }
  286. return true;
  287. }
  288. public function getFilename()
  289. {
  290. return self::tryFilename($this->filename);
  291. }
  292. public function getSize(): int
  293. {
  294. return (int)$this->size;
  295. }
  296. // where should the file go?
  297. public static function filename(Profile $profile, $origname, $mimetype)
  298. {
  299. $ext = self::guessMimeExtension($mimetype, $origname);
  300. // Normalize and make the original filename more URL friendly.
  301. $origname = basename($origname, ".$ext");
  302. if (class_exists('Normalizer')) {
  303. // http://php.net/manual/en/class.normalizer.php
  304. // http://www.unicode.org/reports/tr15/
  305. $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
  306. }
  307. $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
  308. $nickname = $profile->getNickname();
  309. $datestamp = strftime('%Y%m%d', time());
  310. do {
  311. // generate new random strings until we don't run into a filename collision.
  312. $random = strtolower(common_confirmation_code(16));
  313. $filename = "$nickname-$datestamp-$origname-$random.$ext";
  314. } while (file_exists(self::path($filename)));
  315. return $filename;
  316. }
  317. /**
  318. * @param string $filename
  319. * @return null|string|bool Value from the 'extblacklist' array, in the config
  320. * @throws ServerException
  321. */
  322. public static function getSafeExtension(string $filename)
  323. {
  324. if (preg_match('/^.+?\.([A-Za-z0-9]+)$/', $filename, $matches) === 1) {
  325. // we matched on a file extension, so let's see if it means something.
  326. $ext = mb_strtolower($matches[1]);
  327. $blacklist = common_config('attachments', 'extblacklist');
  328. // If we got an extension from $filename we want to check if it's in a blacklist
  329. // so we avoid people uploading restricted files
  330. if (array_key_exists($ext, $blacklist)) {
  331. if (!is_string($blacklist[$ext])) {
  332. // Blocked
  333. return false;
  334. }
  335. // return a safe replacement extension ('php' => 'phps' for example)
  336. return $blacklist[$ext];
  337. } else {
  338. // the attachment extension based on its filename was not blacklisted so it's ok to use it
  339. return $ext;
  340. }
  341. } else {
  342. // No extension
  343. return null;
  344. }
  345. }
  346. /**
  347. * @param $mimetype string The mimetype we've discovered for this file.
  348. * @param $filename string An optional filename which we can use on failure.
  349. * @return mixed|string
  350. * @throws ClientException
  351. * @throws ServerException
  352. */
  353. public static function guessMimeExtension($mimetype, $filename=null)
  354. {
  355. try {
  356. // first see if we know the extension for our mimetype
  357. $ext = common_supported_mime_to_ext($mimetype);
  358. // we do, so use it!
  359. return $ext;
  360. } catch (UnknownMimeExtensionException $e) {
  361. // We don't know the extension for this mimetype, but let's guess.
  362. // If we can't recognize the extension from the MIME, we try
  363. // to guess based on filename, if one was supplied.
  364. if (!is_null($filename)) {
  365. $ext = self::getSafeExtension($filename);
  366. if ($ext === false) {
  367. // we don't have a safe replacement extension
  368. throw new ClientException(_m('Blacklisted file extension.'));
  369. } else {
  370. return $ext;
  371. }
  372. }
  373. } catch (Exception $e) {
  374. common_log(LOG_INFO, 'Problem when figuring out extension for mimetype: '._ve($e));
  375. }
  376. // If nothing else has given us a result, try to extract it from
  377. // the mimetype value (this turns .jpg to .jpeg for example...)
  378. $matches = array();
  379. // Will get jpeg from image/jpeg as well as json from application/jrd+json
  380. if (!preg_match('/[\/+-\.]([a-z0-9]+)/', mb_strtolower($mimetype), $matches)) {
  381. throw new Exception("Malformed mimetype: {$mimetype}");
  382. }
  383. return mb_strtolower($matches[1]);
  384. }
  385. /**
  386. * Validation for as-saved base filenames
  387. * @param mixed $filename
  388. * @return false|int
  389. */
  390. public static function validFilename($filename)
  391. {
  392. return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
  393. }
  394. /**
  395. * @param mixed $filename
  396. * @return string
  397. * @throws InvalidFilenameException
  398. */
  399. public static function tryFilename($filename): string
  400. {
  401. if (!self::validFilename($filename)) {
  402. throw new InvalidFilenameException($filename);
  403. }
  404. // if successful, return the filename for easy if-statementing
  405. return $filename;
  406. }
  407. /**
  408. * Construct a path
  409. *
  410. * @param mixed $filename Will be tested by tryFilename
  411. * @param string|null $dir Attachments directory by default
  412. * @param bool $test_filename
  413. * @return string
  414. * @throws InvalidFilenameException
  415. * @throws ServerException
  416. */
  417. public static function path($filename, ?string $dir = null, bool $test_filename = true)
  418. {
  419. if ($test_filename) {
  420. self::tryFilename($filename);
  421. }
  422. $dir = $dir ?? common_config('attachments', 'dir');
  423. if (!in_array($dir[mb_strlen($dir)-1], ['/', '\\'])) {
  424. $dir .= DIRECTORY_SEPARATOR;
  425. }
  426. return $dir . $filename;
  427. }
  428. /**
  429. * Don't use for attachments, only for assets.
  430. *
  431. * @param $filename
  432. * @return mixed|string
  433. * @throws InvalidFilenameException
  434. * @throws ServerException
  435. */
  436. public static function url($filename)
  437. {
  438. self::tryFilename($filename);
  439. if (common_config('site', 'private')) {
  440. return common_local_url(
  441. 'getfile',
  442. array('filename' => $filename)
  443. );
  444. }
  445. if (GNUsocial::useHTTPS()) {
  446. $sslserver = common_config('attachments', 'sslserver');
  447. if (empty($sslserver)) {
  448. // XXX: this assumes that background dir == site dir + /file/
  449. // not true if there's another server
  450. if (is_string(common_config('site', 'sslserver')) &&
  451. mb_strlen(common_config('site', 'sslserver')) > 0) {
  452. $server = common_config('site', 'sslserver');
  453. } elseif (common_config('site', 'server')) {
  454. $server = common_config('site', 'server');
  455. }
  456. $path = common_config('site', 'path') . '/file/';
  457. } else {
  458. $server = $sslserver;
  459. $path = common_config('attachments', 'sslpath');
  460. if (empty($path)) {
  461. $path = common_config('attachments', 'path');
  462. }
  463. }
  464. $protocol = 'https';
  465. } else {
  466. $path = common_config('attachments', 'path');
  467. $server = common_config('attachments', 'server');
  468. if (empty($server)) {
  469. $server = common_config('site', 'server');
  470. }
  471. $ssl = common_config('attachments', 'ssl');
  472. $protocol = ($ssl) ? 'https' : 'http';
  473. }
  474. if ($path[strlen($path)-1] != '/') {
  475. $path .= '/';
  476. }
  477. if ($path[0] != '/') {
  478. $path = '/'.$path;
  479. }
  480. return $protocol.'://'.$server.$path.$filename;
  481. }
  482. public static $_enclosures = array();
  483. public function getEnclosure()
  484. {
  485. if (isset(self::$_enclosures[$this->getID()])) {
  486. return self::$_enclosures[$this->getID()];
  487. }
  488. $enclosure = (object) array();
  489. foreach (array('title', 'url', 'date', 'modified', 'size', 'mimetype', 'width', 'height') as $key) {
  490. if ($this->$key !== '') {
  491. $enclosure->$key = $this->$key;
  492. }
  493. }
  494. $needMoreMetadataMimetypes = array(null, 'application/xhtml+xml', 'text/html');
  495. if (isset($enclosure->url) && in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
  496. // This fetches enclosure metadata for non-local links with unset/HTML mimetypes,
  497. // which may be enriched through oEmbed or similar (implemented as plugins)
  498. Event::handle('FileEnclosureMetadata', array($this, &$enclosure));
  499. }
  500. if (empty($enclosure->mimetype)) {
  501. // This means we either don't know what it is, so it can't
  502. // be shown as an enclosure, or it is an HTML link which
  503. // does not link to a resource with further metadata.
  504. throw new ServerException('Unknown enclosure mimetype, not enough metadata');
  505. }
  506. self::$_enclosures[$this->getID()] = $enclosure;
  507. return $enclosure;
  508. }
  509. public function hasThumbnail()
  510. {
  511. try {
  512. $this->getThumbnail();
  513. } catch (Exception $e) {
  514. return false;
  515. }
  516. return true;
  517. }
  518. /**
  519. * Get the attachment's thumbnail record, if any or generate one.
  520. *
  521. * @param int|null $width Max width of thumbnail in pixels. (if null, use common_config values)
  522. * @param int|null $height Max height of thumbnail in pixels. (if null, square-crop to $width)
  523. * @param bool $crop Crop to the max-values' aspect ratio
  524. * @param bool $force_still Don't allow fallback to showing original (such as animated GIF)
  525. * @param bool|null $upscale Whether or not to scale smaller images up to larger thumbnail sizes. (null = site default)
  526. *
  527. * @return File_thumbnail
  528. *
  529. * @throws ClientException
  530. * @throws FileNotFoundException
  531. * @throws FileNotStoredLocallyException
  532. * @throws InvalidFilenameException
  533. * @throws NoResultException
  534. * @throws ServerException on various other errors
  535. * @throws UnsupportedMediaException if, despite trying, we can't understand how to make a thumbnail for this format
  536. * @throws UseFileAsThumbnailException if the file is considered an image itself and should be itself as thumbnail
  537. */
  538. public function getThumbnail (?int $width = null, ?int $height = null, bool $crop = false, bool $force_still = true, ?bool $upscale = null): File_thumbnail
  539. {
  540. return File_thumbnail::fromFileObject($this, $width, $height, $crop, $force_still, $upscale);
  541. }
  542. public function getPath()
  543. {
  544. $filepath = self::path($this->filename);
  545. if (!file_exists($filepath)) {
  546. throw new FileNotFoundException($filepath);
  547. }
  548. return $filepath;
  549. }
  550. /**
  551. * Returns the path to either a file, or it's thumbnail if the file doesn't exist.
  552. * This is useful in case the original file is deleted, or, as is the case for Embed
  553. * thumbnails, we only have a thumbnail and not a file
  554. * @param File_thumbnail|null $thumbnail
  555. * @return string Path
  556. * @throws FileNotFoundException
  557. * @throws FileNotStoredLocallyException
  558. * @throws InvalidFilenameException
  559. * @throws ServerException
  560. */
  561. public function getFileOrThumbnailPath(?File_thumbnail $thumbnail = null): string
  562. {
  563. if (!empty($thumbnail)) {
  564. return $thumbnail->getPath();
  565. }
  566. if (!empty($this->filename)) {
  567. $filepath = self::path($this->filename);
  568. if (file_exists($filepath)) {
  569. return $filepath;
  570. } else {
  571. throw new FileNotFoundException($filepath);
  572. }
  573. } else {
  574. try {
  575. return File_thumbnail::byFile($this, true)->getPath();
  576. } catch (NoResultException $e) {
  577. // File not stored locally
  578. throw new FileNotStoredLocallyException($this);
  579. }
  580. }
  581. }
  582. /**
  583. * Return the mime type of the thumbnail if we have it, or, if not, of the File
  584. * @param File_thumbnail|null $thumbnail
  585. * @return string
  586. * @throws FileNotFoundException
  587. * @throws NoResultException
  588. * @throws ServerException
  589. * @throws UnsupportedMediaException
  590. * @throws Exception
  591. */
  592. public function getFileOrThumbnailMimetype(?File_thumbnail $thumbnail = null) : string
  593. {
  594. if (!empty($thumbnail)) {
  595. $filepath = $thumbnail->getPath();
  596. } elseif (!empty($this->filename)) {
  597. return $this->mimetype;
  598. } else {
  599. $filepath = File_thumbnail::byFile($this, true)->getPath();
  600. }
  601. $info = @getimagesize($filepath);
  602. if ($info !== false) {
  603. return $info['mime'];
  604. } else {
  605. throw new UnsupportedMediaException(_m("Thumbnail is not an image."));
  606. }
  607. }
  608. /**
  609. * Return the size of the thumbnail if we have it, or, if not, of the File
  610. * @param File_thumbnail|null $thumbnail
  611. * @return int
  612. * @throws FileNotFoundException
  613. * @throws NoResultException
  614. * @throws ServerException
  615. */
  616. public function getFileOrThumbnailSize(?File_thumbnail $thumbnail = null) : int
  617. {
  618. if (!empty($thumbnail)) {
  619. return filesize($thumbnail->getPath());
  620. } elseif (!empty($this->filename)) {
  621. return $this->getSize();
  622. } else {
  623. return filesize(File_thumbnail::byFile($this)->getPath());
  624. }
  625. }
  626. public function getAttachmentUrl()
  627. {
  628. return common_local_url('attachment', array('attachment'=>$this->getID()));
  629. }
  630. public function getAttachmentDownloadUrl()
  631. {
  632. return common_local_url('attachment_download', ['filehash' => $this->filehash]);
  633. }
  634. public function getAttachmentViewUrl()
  635. {
  636. return common_local_url('attachment_view', ['filehash' => $this->filehash]);
  637. }
  638. /**
  639. * @param bool|null $use_local true means require local, null means prefer original, false means use whatever is stored
  640. * @return string
  641. * @throws FileNotStoredLocallyException
  642. */
  643. public function getUrl(?bool $use_local=null): ?string
  644. {
  645. if ($use_local !== false) {
  646. if (empty($this->url)) {
  647. // A locally stored file, so let's generate a URL for our instance.
  648. return $this->getAttachmentViewUrl();
  649. }
  650. if ($use_local) {
  651. // if the file isn't ours but and we require a local URL anyway
  652. throw new FileNotStoredLocallyException($this);
  653. }
  654. }
  655. // The original file's URL
  656. return $this->url;
  657. }
  658. public static function getByUrl($url)
  659. {
  660. $file = new File();
  661. $file->urlhash = self::hashurl($url);
  662. if (!$file->find(true)) {
  663. throw new NoResultException($file);
  664. }
  665. return $file;
  666. }
  667. /**
  668. * @param string $hashstr String of (preferrably lower case) hexadecimal characters, same as result of 'hash_file(...)'
  669. * @return File
  670. * @throws NoResultException
  671. */
  672. public static function getByHash($hashstr)
  673. {
  674. $file = new File();
  675. $file->filehash = strtolower($hashstr);
  676. if (!$file->find()) {
  677. throw new NoResultException($file);
  678. }
  679. return $file;
  680. }
  681. public function updateUrl($url)
  682. {
  683. $file = File::getKV('urlhash', self::hashurl($url));
  684. if ($file instanceof File) {
  685. throw new ServerException('URL already exists in DB');
  686. }
  687. $result = $this->query(sprintf(
  688. <<<'END'
  689. UPDATE %1$s
  690. SET urlhash = %2$s, url = %3$s, modified = CURRENT_TIMESTAMP
  691. WHERE urlhash = %4$s;
  692. END,
  693. $this->tableName(),
  694. $this->_quote((string)self::hashurl($url)),
  695. $this->_quote((string)$url),
  696. $this->_quote((string)$this->urlhash)
  697. ));
  698. if ($result === false) {
  699. common_log_db_error($this, 'UPDATE', __FILE__);
  700. throw new ServerException("Could not UPDATE {$this->tableName()}.url");
  701. }
  702. return $result;
  703. }
  704. /**
  705. * Blow the cache of notices that link to this URL
  706. *
  707. * @param boolean $last Whether to blow the "last" cache too
  708. *
  709. * @return void
  710. */
  711. public function blowCache($last=false)
  712. {
  713. self::blow('file:notice-ids:%s', $this->id);
  714. if ($last) {
  715. self::blow('file:notice-ids:%s;last', $this->id);
  716. }
  717. self::blow('file:notice-count:%d', $this->id);
  718. }
  719. /**
  720. * Stream of notices linking to this URL
  721. *
  722. * @param integer $offset Offset to show; default is 0
  723. * @param integer $limit Limit of notices to show
  724. * @param integer $since_id Since this notice
  725. * @param integer $max_id Before this notice
  726. *
  727. * @return array ids of notices that link to this file
  728. */
  729. public function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
  730. {
  731. // FIXME: Try to get the Profile::current() here in some other way to avoid mixing
  732. // the current session user with possibly background/queue processing.
  733. $stream = new FileNoticeStream($this, Profile::current());
  734. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  735. }
  736. public function noticeCount()
  737. {
  738. $cacheKey = sprintf('file:notice-count:%d', $this->id);
  739. $count = self::cacheGet($cacheKey);
  740. if ($count === false) {
  741. $f2p = new File_to_post();
  742. $f2p->file_id = $this->id;
  743. $count = $f2p->count();
  744. self::cacheSet($cacheKey, $count);
  745. }
  746. return $count;
  747. }
  748. public function isLocal()
  749. {
  750. return empty($this->url) && !empty($this->filename);
  751. }
  752. public function unlink() {
  753. // Delete the file, if it exists locally
  754. if (!empty($this->filename) && file_exists(self::path($this->filename))) {
  755. $deleted = @unlink(self::path($this->filename));
  756. if (!$deleted) {
  757. common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', self::path($this->filename)));
  758. }
  759. }
  760. }
  761. public function delete($useWhere=false)
  762. {
  763. // Delete the file, if it exists locally
  764. $this->unlink();
  765. // Clear out related things in the database and filesystem, such as thumbnails
  766. $related = [
  767. 'File_redirection',
  768. 'File_thumbnail',
  769. 'File_to_post'
  770. ];
  771. Event::handle('FileDeleteRelated', [$this, &$related]);
  772. foreach ($related as $cls) {
  773. $inst = new $cls();
  774. $inst->file_id = $this->id;
  775. if ($inst->find()) {
  776. while ($inst->fetch()) {
  777. $inst->delete();
  778. }
  779. }
  780. }
  781. // And finally remove the entry from the database
  782. return parent::delete($useWhere);
  783. }
  784. public function getTitle()
  785. {
  786. $title = $this->title ?: MediaFile::getDisplayName($this);
  787. return $title ?: null;
  788. }
  789. public function setTitle($title)
  790. {
  791. $orig = clone($this);
  792. $this->title = mb_strlen($title) > 0 ? $title : null;
  793. return $this->update($orig);
  794. }
  795. public static function hashurl($url)
  796. {
  797. if (empty($url)) {
  798. throw new Exception('No URL provided to hash algorithm.');
  799. }
  800. return hash(self::URLHASH_ALG, $url);
  801. }
  802. public static function beforeSchemaUpdate()
  803. {
  804. $table = strtolower(get_called_class());
  805. $schema = Schema::get();
  806. $schemadef = $schema->getTableDef($table);
  807. // 2015-02-19 We have to upgrade our table definitions to have the urlhash field populated
  808. if (isset($schemadef['fields']['urlhash']) && isset($schemadef['unique keys']['file_urlhash_key'])) {
  809. // We already have the urlhash field, so no need to migrate it.
  810. return;
  811. }
  812. echo "\nFound old $table table, upgrading it to contain 'urlhash' field...";
  813. $file = new File();
  814. $file->query(sprintf(
  815. 'SELECT id, LEFT(url, 191) AS shortenedurl, COUNT(*) FROM %1$s ' .
  816. 'WHERE LENGTH(url) > 191 GROUP BY id, shortenedurl HAVING COUNT(*) > 1',
  817. common_database_tablename($table)
  818. ));
  819. print "\nFound {$file->N} URLs with too long entries in file table\n";
  820. while ($file->fetch()) {
  821. // We've got a URL that is too long for our future file table
  822. // so we'll cut it. We could save the original URL, but there is
  823. // no guarantee it is complete anyway since the previous max was 255 chars.
  824. $dupfile = new File();
  825. // First we find file entries that would be duplicates of this when shortened
  826. // ... and we'll just throw the dupes out the window for now! It's already so borken.
  827. $dupfile->query(sprintf('SELECT * FROM file WHERE LEFT(url, 191) = %1$s', $dupfile->_quote($file->shortenedurl)));
  828. // Leave one of the URLs in the database by using ->find(true) (fetches first entry)
  829. if ($dupfile->find(true)) {
  830. print "\nShortening url entry for $table id: {$file->id} [";
  831. $orig = clone($dupfile);
  832. $origurl = $dupfile->url; // save for logging purposes
  833. $dupfile->url = $file->shortenedurl; // make sure it's only 191 chars from now on
  834. $dupfile->update($orig);
  835. print "\nDeleting duplicate entries of too long URL on $table id: {$file->id} [";
  836. // only start deleting with this fetch.
  837. while ($dupfile->fetch()) {
  838. common_log(LOG_INFO, sprintf('Deleting duplicate File entry of %1$d: %2$d (original URL: %3$s collides with these first 191 characters: %4$s', $dupfile->id, $file->id, $origurl, $file->shortenedurl));
  839. print ".";
  840. $dupfile->delete();
  841. }
  842. print "]\n";
  843. } else {
  844. print "\nWarning! URL suddenly disappeared from database: {$file->url}\n";
  845. }
  846. }
  847. echo "...and now all the non-duplicates which are longer than 191 characters...\n";
  848. $file->query('UPDATE file SET url = LEFT(url, 191) WHERE LENGTH(url) > 191');
  849. echo "\n...now running hacky pre-schemaupdate change for $table:";
  850. // We have to create a urlhash that is _not_ the primary key,
  851. // transfer data and THEN run checkSchema
  852. $schemadef['fields']['urlhash'] = array(
  853. 'type' => 'varchar',
  854. 'length' => 64,
  855. 'not null' => false, // this is because when adding column, all entries will _be_ NULL!
  856. 'description' => 'sha256 of destination URL (url field)',
  857. );
  858. $schemadef['fields']['url'] = array(
  859. 'type' => 'text',
  860. 'description' => 'destination URL after following possible redirections',
  861. );
  862. unset($schemadef['unique keys']);
  863. $schema->ensureTable($table, $schemadef);
  864. echo "DONE.\n";
  865. $classname = ucfirst($table);
  866. $tablefix = new $classname;
  867. // urlhash is hash('sha256', $url) in the File table
  868. echo "Updating urlhash fields in $table table...";
  869. switch (common_config('db', 'type')) {
  870. case 'pgsql':
  871. $url_sha256 = 'encode(sha256(CAST("url" AS bytea)), \'hex\')';
  872. break;
  873. case 'mysql':
  874. $url_sha256 = 'sha2(`url`, 256)';
  875. break;
  876. default:
  877. throw new ServerException('Unknown DB type selected.');
  878. }
  879. $tablefix->query(sprintf(
  880. 'UPDATE %1$s SET urlhash = %2$s, modified = CURRENT_TIMESTAMP;',
  881. $tablefix->escapedTableName(),
  882. $url_sha256
  883. ));
  884. echo "DONE.\n";
  885. echo "Resuming core schema upgrade...";
  886. }
  887. }