File.php 37 KB

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