mediafile.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  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. * Abstraction for media files
  18. *
  19. * @category Media
  20. * @package GNUsocial
  21. *
  22. * @author Robin Millette <robin@millette.info>
  23. * @author Miguel Dantas <biodantas@gmail.com>
  24. * @author Zach Copley <zach@status.net>
  25. * @author Mikael Nordfeldth <mmn@hethane.se>
  26. * @author Diogo Peralta Cordeiro <mail+gnusocial@diogo.site>
  27. * @copyright 2008-2009, 2019-2021 Free Software Foundation http://fsf.org
  28. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  29. */
  30. defined('GNUSOCIAL') || die();
  31. require_once INSTALLDIR . '/lib/util/tempfile.php';
  32. /**
  33. * Class responsible for abstracting media files
  34. */
  35. class MediaFile
  36. {
  37. public $id;
  38. public $filepath;
  39. public $filename;
  40. public $fileRecord;
  41. public $fileurl;
  42. public $short_fileurl;
  43. public $mimetype;
  44. /**
  45. * MediaFile constructor.
  46. *
  47. * @param string|null $filepath The path of the file this media refers to. Required
  48. * @param string $mimetype The mimetype of the file. Required
  49. * @param string|null $filehash The hash of the file, if known. Optional
  50. * @param int|null $id The DB id of the file. Int if known, null if not.
  51. * If null, it searches for it. If -1, it skips all DB
  52. * interactions (useful for temporary objects)
  53. * @param string|null $fileurl Provide if remote
  54. * @throws ClientException
  55. * @throws NoResultException
  56. * @throws ServerException
  57. */
  58. public function __construct(?string $filepath = null, string $mimetype, ?string $filehash = null, ?int $id = null, ?string $fileurl = null)
  59. {
  60. $this->filepath = $filepath;
  61. $this->filename = basename($this->filepath);
  62. $this->mimetype = $mimetype;
  63. $this->filehash = is_null($filepath) ? null : self::getHashOfFile($this->filepath, $filehash);
  64. $this->id = $id;
  65. $this->fileurl = $fileurl;
  66. // If id is -1, it means we're dealing with a temporary object and don't want to store it in the DB,
  67. // or add redirects
  68. if ($this->id !== -1) {
  69. if (!empty($this->id)) {
  70. // If we have an id, load it
  71. $this->fileRecord = new File();
  72. $this->fileRecord->id = $this->id;
  73. if (!$this->fileRecord->find(true)) {
  74. // If we have set an ID, we need that ID to exist!
  75. throw new NoResultException($this->fileRecord);
  76. }
  77. } else {
  78. // Otherwise, store it
  79. $this->fileRecord = $this->storeFile();
  80. }
  81. }
  82. }
  83. /**
  84. * Shortcut method to get a MediaFile from a File
  85. *
  86. * @param File $file
  87. * @return MediaFile|ImageFile
  88. * @throws ClientException
  89. * @throws FileNotFoundException
  90. * @throws NoResultException
  91. * @throws ServerException
  92. */
  93. public static function fromFileObject(File $file)
  94. {
  95. $filepath = null;
  96. try {
  97. $filepath = $file->getPath();
  98. } catch (Exception $e) {}
  99. return new self($filepath, common_get_mime_media($file->mimetype), $file->filehash, $file->getID());
  100. }
  101. public function attachToNotice(Notice $notice)
  102. {
  103. File_to_post::processNew($this->fileRecord, $notice);
  104. }
  105. public function getPath()
  106. {
  107. return File::path($this->filename);
  108. }
  109. /**
  110. * @param bool|null $use_local true means require local, null means prefer original, false means use whatever is stored
  111. * @return string
  112. */
  113. public function getUrl(?bool $use_local=null): ?string
  114. {
  115. if ($use_local !== false) {
  116. if (empty($this->fileurl)) {
  117. // A locally stored file, so let's generate a URL for our instance.
  118. return common_local_url('attachment_view', ['filehash' => $this->filehash]);
  119. }
  120. }
  121. // The original file's URL
  122. return $this->fileurl;
  123. }
  124. public function shortUrl()
  125. {
  126. return common_shorten_url($this->getUrl());
  127. }
  128. public function getEnclosure()
  129. {
  130. return $this->getFile()->getEnclosure();
  131. }
  132. public function delete($useWhere=false)
  133. {
  134. if (!is_null($this->fileRecord)) {
  135. $this->fileRecord->delete($useWhere);
  136. }
  137. @unlink($this->filepath);
  138. }
  139. public function unlink()
  140. {
  141. $this->filename = null;
  142. // Delete the file, if it exists locally
  143. if (!empty($this->filepath) && file_exists($this->filepath)) {
  144. $deleted = @unlink($this->filepath);
  145. if (!$deleted) {
  146. common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', $this->filepath));
  147. }
  148. }
  149. $this->fileRecord->unlink();
  150. }
  151. public function getFile()
  152. {
  153. if (!$this->fileRecord instanceof File) {
  154. throw new ServerException('File record did not exist for MediaFile');
  155. }
  156. return $this->fileRecord;
  157. }
  158. /**
  159. * Calculate the hash of a file.
  160. *
  161. * This won't work for files >2GiB because PHP uses only 32bit.
  162. *
  163. * @param string $filepath
  164. * @param null|string $filehash
  165. *
  166. * @return string
  167. * @throws ServerException
  168. *
  169. */
  170. public static function getHashOfFile(string $filepath, $filehash = null)
  171. {
  172. assert(!empty($filepath), __METHOD__ . ': filepath cannot be null');
  173. if ($filehash === null) {
  174. // Calculate if we have an older upload method somewhere (Qvitter) that
  175. // doesn't do this before calling new MediaFile on its local files...
  176. $filehash = hash_file(File::FILEHASH_ALG, $filepath);
  177. if ($filehash === false) {
  178. throw new ServerException('Could not read file for hashing');
  179. }
  180. }
  181. return $filehash;
  182. }
  183. /**
  184. * Retrieve or insert as a file in the DB
  185. *
  186. * @return object File
  187. * @throws ServerException
  188. *
  189. * @throws ClientException
  190. */
  191. protected function storeFile()
  192. {
  193. try {
  194. $file = File::getByHash($this->filehash);
  195. if (is_null($this->fileurl) && is_null($file->getUrl(false))) {
  196. // An already existing local file is being re-added, return it
  197. return $file;
  198. }
  199. } catch (NoResultException $e) {
  200. // Well, let's just continue below.
  201. }
  202. $file = new File;
  203. $file->filename = $this->filename;
  204. $file->url = $this->fileurl;
  205. $file->urlhash = is_null($file->url) ? null : File::hashurl($file->url);
  206. $file->filehash = $this->filehash;
  207. $file->size = filesize($this->filepath);
  208. if ($file->size === false) {
  209. throw new ServerException('Could not read file to get its size');
  210. }
  211. $file->date = time();
  212. $file->mimetype = $this->mimetype;
  213. $file_id = $file->insert();
  214. if ($file_id === false) {
  215. common_log_db_error($file, 'INSERT', __FILE__);
  216. // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
  217. throw new ClientException(_m('There was a database error while saving your file. Please try again.'));
  218. }
  219. // Set file geometrical properties if available
  220. try {
  221. $image = ImageFile::fromFileObject($file);
  222. $orig = clone($file);
  223. $file->width = $image->width;
  224. $file->height = $image->height;
  225. $file->update($orig);
  226. // We have to cleanup after ImageFile, since it
  227. // may have generated a temporary file from a
  228. // video support plugin or something.
  229. // FIXME: Do this more automagically.
  230. // Honestly, I think this is unlikely these days,
  231. // but better be safe than sorry, I guess
  232. if ($image->getPath() != $file->getPath()) {
  233. $image->unlink();
  234. }
  235. } catch (ServerException $e) {
  236. // We just couldn't make out an image from the file. This
  237. // does not have to be UnsupportedMediaException, as we can
  238. // also get ServerException from files not existing etc.
  239. }
  240. return $file;
  241. }
  242. /**
  243. * The maximum allowed file size, as a string
  244. */
  245. public static function maxFileSize()
  246. {
  247. $value = self::maxFileSizeInt();
  248. if ($value > 1024 * 1024) {
  249. $value = $value / (1024 * 1024);
  250. // TRANS: Number of megabytes. %d is the number.
  251. return sprintf(_m('%dMB', '%dMB', $value), $value);
  252. } elseif ($value > 1024) {
  253. $value = $value / 1024;
  254. // TRANS: Number of kilobytes. %d is the number.
  255. return sprintf(_m('%dkB', '%dkB', $value), $value);
  256. } else {
  257. // TRANS: Number of bytes. %d is the number.
  258. return sprintf(_m('%dB', '%dB', $value), $value);
  259. }
  260. }
  261. /**
  262. * The maximum allowed file size, as an int
  263. */
  264. public static function maxFileSizeInt(): int
  265. {
  266. return common_config('attachments', 'file_quota');
  267. }
  268. /**
  269. * Encodes a file name and a file hash in the new file format, which is used to avoid
  270. * having an extension in the file, removing trust in extensions, while keeping the original name
  271. *
  272. * @param null|string $original_name
  273. * @param string $filehash
  274. * @param null|string|bool $ext from File::getSafeExtension
  275. *
  276. * @return string
  277. * @throws ClientException
  278. * @throws ServerException
  279. */
  280. public static function encodeFilename($original_name, string $filehash, $ext = null): string
  281. {
  282. if (empty($original_name)) {
  283. $original_name = _m('Untitled attachment');
  284. }
  285. // If we're given an extension explicitly, use it, otherwise...
  286. $ext = $ext ?:
  287. // get a replacement extension if configured, returns false if it's blocked,
  288. // null if no extension
  289. File::getSafeExtension($original_name);
  290. if ($ext === false) {
  291. throw new ClientException(_m('Blacklisted file extension.'));
  292. }
  293. if (!empty($ext)) {
  294. // Remove dots if we have them (make sure they're not repeated)
  295. $ext = preg_replace('/^\.+/', '', $ext);
  296. $original_name = preg_replace('/\.+.+$/i', ".{$ext}", $original_name);
  297. }
  298. $enc_name = bin2hex($original_name);
  299. return "{$enc_name}-{$filehash}";
  300. }
  301. /**
  302. * Decode the new filename format
  303. *
  304. * @return false | null | string on failure, no match (old format) or original file name, respectively
  305. */
  306. public static function decodeFilename(string $encoded_filename)
  307. {
  308. // Should match:
  309. // hex-hash
  310. // thumb-id-widthxheight-hex-hash
  311. // And return the `hex` part
  312. $ret = preg_match('/^(.*-)?([^-]+)-[^-]+$/', $encoded_filename, $matches);
  313. if ($ret === false) {
  314. return false;
  315. } elseif ($ret === 0 || !ctype_xdigit($matches[2])) {
  316. return null; // No match
  317. } else {
  318. $filename = hex2bin($matches[2]);
  319. // Matches extension
  320. if (preg_match('/^(.+?)\.(.+)$/', $filename, $sub_matches) === 1) {
  321. $ext = $sub_matches[2];
  322. // Previously, there was a blacklisted extension array, which could have an alternative
  323. // extension, such as phps, to replace php. We want to turn it back (this is deprecated,
  324. // as it no longer makes sense, since we don't trust trust files based on extension,
  325. // but keep the feature)
  326. $blacklist = common_config('attachments', 'extblacklist');
  327. if (is_array($blacklist)) {
  328. foreach ($blacklist as $upload_ext => $safe_ext) {
  329. if ($ext === $safe_ext) {
  330. $ext = $upload_ext;
  331. break;
  332. }
  333. }
  334. }
  335. return "{$sub_matches[1]}.{$ext}";
  336. } else {
  337. // No extension, don't bother trying to replace it
  338. return $filename;
  339. }
  340. }
  341. }
  342. /**
  343. * Create a new MediaFile or ImageFile object from an upload
  344. *
  345. * Tries to set the mimetype correctly, using the most secure method available and rejects the file otherwise.
  346. * In case the upload is an image, this function returns an new ImageFile (which extends MediaFile)
  347. * The filename has a new format:
  348. * bin2hex("{$original_name}.{$ext}")."-{$filehash}"
  349. * This format should be respected. Notice the dash, which is important to distinguish it from the previous
  350. * format ("{$hash}.{$ext}")
  351. *
  352. * @param string $param Form name
  353. * @param Profile|null $scoped
  354. * @return ImageFile|MediaFile
  355. * @throws ClientException
  356. * @throws InvalidFilenameException
  357. * @throws NoResultException
  358. * @throws NoUploadedMediaException
  359. * @throws ServerException
  360. * @throws UnsupportedMediaException
  361. * @throws UseFileAsThumbnailException
  362. */
  363. public static function fromUpload(string $param = 'media', ?Profile $scoped = null)
  364. {
  365. // The existence of the "error" element means PHP has processed it properly even if it was ok.
  366. if (!(isset($_FILES[$param], $_FILES[$param]['error']))) {
  367. throw new NoUploadedMediaException($param);
  368. }
  369. switch ($_FILES[$param]['error']) {
  370. case UPLOAD_ERR_OK: // success, jump out
  371. break;
  372. case UPLOAD_ERR_INI_SIZE:
  373. case UPLOAD_ERR_FORM_SIZE:
  374. // TRANS: Exception thrown when too large a file is uploaded.
  375. // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
  376. throw new ClientException(sprintf(
  377. _m('That file is too big. The maximum file size is %s.'),
  378. self::maxFileSize()
  379. ));
  380. case UPLOAD_ERR_PARTIAL:
  381. @unlink($_FILES[$param]['tmp_name']);
  382. // TRANS: Client exception.
  383. throw new ClientException(_m('The uploaded file was only partially uploaded.'));
  384. case UPLOAD_ERR_NO_FILE:
  385. // No file; probably just a non-AJAX submission.
  386. throw new NoUploadedMediaException($param);
  387. case UPLOAD_ERR_NO_TMP_DIR:
  388. // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
  389. throw new ClientException(_m('Missing a temporary folder.'));
  390. case UPLOAD_ERR_CANT_WRITE:
  391. // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
  392. throw new ClientException(_m('Failed to write file to disk.'));
  393. case UPLOAD_ERR_EXTENSION:
  394. // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
  395. throw new ClientException(_m('File upload stopped by extension.'));
  396. default:
  397. common_log(LOG_ERR, __METHOD__ . ': Unknown upload error ' . $_FILES[$param]['error']);
  398. // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
  399. throw new ClientException(_m('System error uploading file.'));
  400. }
  401. $filehash = strtolower(self::getHashOfFile($_FILES[$param]['tmp_name']));
  402. $fileid = null;
  403. try {
  404. $file = File::getByHash($filehash);
  405. // There can be more than one file for the same filehash IF the url are different (due to different metadata).
  406. while ($file->fetch()) {
  407. if ($file->getUrl(false)) {
  408. // Files uploaded by Actors of this instance won't have an url, skip.
  409. continue;
  410. }
  411. try {
  412. return ImageFile::fromFileObject($file);
  413. } catch (UnsupportedMediaException $e) {
  414. return MediaFile::fromFileObject($file);
  415. }
  416. }
  417. // Assert: If we got to this line, then we only traversed URLs on the while loop above.
  418. if (common_config('attachments', 'prefer_remote')) {
  419. // Was this file imported from a remote source already?
  420. $filepath = $file->getPath(); // This function will throw FileNotFoundException if not.
  421. // Assert: If we got to this line, then we can use this file and just add redirections.
  422. $mimetype = $file->mimetype;
  423. $fileid = $file->getID();
  424. } else {
  425. throw new FileNotFoundException('This isn\'t a path.'); // A bit of dadaist art.
  426. // It's natural that a sysadmin prefers to not add redirections to the first remote link of an
  427. // attachment, it's not a very consistent thing to do. On the other hand, lack of space can drive
  428. // a person crazy.
  429. // Also note that if one configured StoreRemoteMedia to not save original images (very likely), then
  430. // having prefer_remote enabled will never store the original attachment (sort of the idea here).
  431. }
  432. } catch (FileNotFoundException | NoResultException $e) {
  433. // We have to save the upload as a new local file. This is the normal course of action.
  434. if ($scoped instanceof Profile) {
  435. // Throws exception if additional size does not respect quota
  436. // This test is only needed, of course, if we're uploading something new.
  437. File::respectsQuota($scoped, $_FILES[$param]['size']);
  438. }
  439. $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
  440. $media = common_get_mime_media($mimetype);
  441. $basename = basename($_FILES[$param]['name']);
  442. if ($media == 'image') {
  443. // Use -1 for the id to avoid adding this temporary file to the DB
  444. $img = new ImageFile(-1, $_FILES[$param]['tmp_name']);
  445. // Validate the image by re-encoding it. Additionally normalizes old formats to WebP,
  446. // keeping GIF untouched if animated
  447. $outpath = $img->resizeTo($img->filepath);
  448. $ext = image_type_to_extension($img->preferredType(), false);
  449. }
  450. $filename = self::encodeFilename($basename, $filehash, isset($ext) ? $ext : File::getSafeExtension($basename));
  451. $filepath = File::path($filename);
  452. if ($media == 'image') {
  453. $result = rename($outpath, $filepath);
  454. } else {
  455. $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
  456. }
  457. if (!$result) {
  458. // TRANS: Client exception thrown when a file upload operation fails because the file could
  459. // TRANS: not be moved from the temporary folder to the permanent file location.
  460. // UX: too specific
  461. throw new ClientException(_m('File could not be moved to destination directory.'));
  462. }
  463. if ($media == 'image') {
  464. return new ImageFile(null, $filepath, $filehash);
  465. }
  466. }
  467. return new self($filepath, $mimetype, $filehash, $fileid);
  468. }
  469. /**
  470. * Create a new MediaFile or ImageFile object from an url
  471. *
  472. * Tries to set the mimetype correctly, using the most secure method available and rejects the file otherwise.
  473. * In case the url is an image, this function returns an new ImageFile (which extends MediaFile)
  474. * The filename has the following format: bin2hex("{$original_name}.{$ext}")."-{$filehash}"
  475. *
  476. * @param string $url Remote media URL
  477. * @param Profile|null $scoped
  478. * @param string|null $name
  479. * @param int|null $file_id same as in this class constructor
  480. * @return ImageFile|MediaFile
  481. * @throws ClientException
  482. * @throws HTTP_Request2_Exception
  483. * @throws InvalidFilenameException
  484. * @throws NoResultException
  485. * @throws ServerException
  486. * @throws UnsupportedMediaException
  487. * @throws UseFileAsThumbnailException
  488. */
  489. public static function fromUrl(string $url, ?Profile $scoped = null, ?string $name = null, ?int $file_id = null)
  490. {
  491. if (!common_valid_http_url($url)) {
  492. // TRANS: Server exception. %s is a URL.
  493. throw new ServerException(sprintf('Invalid remote media URL %s.', $url));
  494. }
  495. $http = new HTTPClient();
  496. common_debug(sprintf('Performing HEAD request for incoming activity to avoid ' .
  497. 'unnecessarily downloading too large files. URL: %s',
  498. $url));
  499. $head = $http->head($url);
  500. $url = $head->getEffectiveUrl(); // to avoid going through redirects again
  501. if (empty($url)) {
  502. throw new ServerException(sprintf('URL after redirects is somehow empty, for URL %s.', $url));
  503. }
  504. $headers = $head->getHeader();
  505. $headers = array_change_key_case($headers, CASE_LOWER);
  506. if (array_key_exists('content-length', $headers)) {
  507. $fileQuota = common_config('attachments', 'file_quota');
  508. $fileSize = $headers['content-length'];
  509. if ($fileSize > $fileQuota) {
  510. // TRANS: Message used to be inserted as %2$s in the text "No file may
  511. // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
  512. // TRANS: %1$d is the number of bytes of an uploaded file.
  513. $fileSizeText = sprintf(_m('%1$d byte', '%1$d bytes', $fileSize), $fileSize);
  514. // TRANS: Message given if an upload is larger than the configured maximum.
  515. // TRANS: %1$d (used for plural) is the byte limit for uploads,
  516. // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
  517. // TRANS: gettext support multiple plurals in the same message, unfortunately...
  518. throw new ClientException(
  519. sprintf(
  520. _m(
  521. 'No file may be larger than %1$d byte and the file you sent was %2$s. Try to upload a smaller version.',
  522. 'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
  523. $fileQuota
  524. ),
  525. $fileQuota,
  526. $fileSizeText
  527. )
  528. );
  529. }
  530. } else {
  531. throw new ServerException(sprintf('Invalid remote media URL headers %s.', $url));
  532. }
  533. unset($head);
  534. unset($headers);
  535. $tempfile = new TemporaryFile('gs-mediafile');
  536. fwrite($tempfile->getResource(), HTTPClient::quickGet($url));
  537. fflush($tempfile->getResource());
  538. $filehash = strtolower(self::getHashOfFile($tempfile->getRealPath()));
  539. try {
  540. $file = File::getByUrl($url);
  541. /*
  542. * If no exception is thrown the file exists locally, so we'll use
  543. * that and just add redirections.
  544. * But if the _actual_ locally stored file doesn't exist, getPath
  545. * will throw FileNotFoundException.
  546. */
  547. $filepath = $file->getPath();
  548. $mimetype = $file->mimetype;
  549. } catch (FileNotFoundException | NoResultException $e) {
  550. // We have to save the downloaded as a new local file.
  551. // This is the normal course of action.
  552. if ($scoped instanceof Profile) {
  553. // Throws exception if additional size does not respect quota
  554. // This test is only needed, of course, if something new is uploaded.
  555. File::respectsQuota($scoped, filesize($tempfile->getRealPath()));
  556. }
  557. $mimetype = self::getUploadedMimeType(
  558. $tempfile->getRealPath(),
  559. $name ?? false
  560. );
  561. $media = common_get_mime_media($mimetype);
  562. $basename = basename($name ?? ('media' . common_timestamp()));
  563. if ($media === 'image') {
  564. // Use -1 for the id to avoid adding this temporary file to the DB.
  565. $img = new ImageFile(-1, $tempfile->getRealPath());
  566. // Validate the image by re-encoding it.
  567. // Additionally normalises old formats to PNG,
  568. // keeping JPEG and GIF untouched.
  569. $outpath = $img->resizeTo($img->filepath);
  570. $ext = image_type_to_extension($img->preferredType(), false);
  571. }
  572. $filename = self::encodeFilename(
  573. $basename,
  574. $filehash,
  575. $ext ?? File::getSafeExtension($basename)
  576. );
  577. $filepath = File::path($filename);
  578. if ($media === 'image') {
  579. $result = rename($outpath, $filepath);
  580. } else {
  581. try {
  582. $tempfile->commit($filepath);
  583. $result = true;
  584. } catch (TemporaryFileException $e) {
  585. $result = false;
  586. }
  587. }
  588. if (!$result) {
  589. // TRANS: Server exception thrown when a file upload operation fails because the file could
  590. // TRANS: not be moved from the temporary directory to the permanent file location.
  591. throw new ServerException(_m('File could not be moved to destination directory.'));
  592. }
  593. if ($media === 'image') {
  594. return new ImageFile($file_id, $filepath, $filehash, $url);
  595. }
  596. }
  597. return new self($filepath, $mimetype, $filehash, $file_id, $url);
  598. }
  599. public static function fromFileInfo(SplFileInfo $finfo, Profile $scoped = null)
  600. {
  601. $filehash = hash_file(File::FILEHASH_ALG, $finfo->getRealPath());
  602. try {
  603. $file = File::getByHash($filehash);
  604. $file->fetch();
  605. // Already have it, so let's reuse the locally stored File
  606. // by using getPath we also check whether the file exists
  607. // and throw a FileNotFoundException with the path if it doesn't.
  608. $filename = basename($file->getPath());
  609. $mimetype = $file->mimetype;
  610. } catch (FileNotFoundException $e) {
  611. // This happens if the file we have uploaded has disappeared
  612. // from the local filesystem for some reason. Since we got the
  613. // File object from a sha256 check in fromFileInfo, it's safe
  614. // to just copy the uploaded data to disk!
  615. // dump the contents of our filehandle to the path from our exception
  616. // and report error if it failed.
  617. if (file_put_contents($e->path, file_get_contents($finfo->getRealPath())) === false) {
  618. // TRANS: Client exception thrown when a file upload operation fails because the file could
  619. // TRANS: not be moved from the temporary folder to the permanent file location.
  620. throw new ClientException(_m('File could not be moved to destination directory.'));
  621. }
  622. if (!chmod($e->path, 0664)) {
  623. common_log(LOG_ERR, 'Could not chmod uploaded file: ' . _ve($e->path));
  624. }
  625. $filename = basename($file->getPath());
  626. $mimetype = $file->mimetype;
  627. } catch (NoResultException $e) {
  628. if ($scoped instanceof Profile) {
  629. File::respectsQuota($scoped, filesize($finfo->getRealPath()));
  630. }
  631. $mimetype = self::getUploadedMimeType($finfo->getRealPath());
  632. $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
  633. $filepath = File::path($filename);
  634. $result = copy($finfo->getRealPath(), $filepath) && chmod($filepath, 0664);
  635. if (!$result) {
  636. common_log(LOG_ERR, 'File could not be moved (or chmodded) from ' . _ve($stream['uri']) . ' to ' . _ve($filepath));
  637. // TRANS: Client exception thrown when a file upload operation fails because the file could
  638. // TRANS: not be moved from the temporary folder to the permanent file location.
  639. throw new ClientException(_m('File could not be moved to destination directory.'));
  640. }
  641. }
  642. return new self($filename, $mimetype, $filehash);
  643. }
  644. /**
  645. * Attempt to identify the content type of a given file.
  646. *
  647. * @param string $filepath filesystem path as string (file must exist)
  648. * @param bool $originalFilename (optional) for extension-based detection
  649. *
  650. * @return string
  651. *
  652. * @fixme this seems to tie a front-end error message in, kinda confusing
  653. *
  654. * @throws ServerException
  655. *
  656. * @throws ClientException if type is known, but not supported for local uploads
  657. */
  658. public static function getUploadedMimeType(string $filepath, $originalFilename = false)
  659. {
  660. // We only accept filenames to existing files
  661. $mimetype = null;
  662. // From CodeIgniter
  663. // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
  664. $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s[^\/]+)?$/';
  665. /**
  666. * Fileinfo extension - most reliable method
  667. *
  668. * Apparently XAMPP, CentOS, cPanel and who knows what
  669. * other PHP distribution channels EXPLICITLY DISABLE
  670. * ext/fileinfo, which is otherwise enabled by default
  671. * since PHP 5.3 ...
  672. */
  673. if (function_exists('finfo_file')) {
  674. $finfo = @finfo_open(FILEINFO_MIME);
  675. // It is possible that a FALSE value is returned, if there is no magic MIME database
  676. // file found on the system
  677. if (is_resource($finfo)) {
  678. $mime = @finfo_file($finfo, $filepath);
  679. finfo_close($finfo);
  680. /* According to the comments section of the PHP manual page,
  681. * it is possible that this function returns an empty string
  682. * for some files (e.g. if they don't exist in the magic MIME database)
  683. */
  684. if (is_string($mime) && preg_match($regexp, $mime, $matches)) {
  685. $mimetype = $matches[1];
  686. }
  687. }
  688. }
  689. /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
  690. * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
  691. * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better
  692. * than mime_content_type() as well, hence the attempts to try calling the command line with
  693. * three different functions.
  694. *
  695. * Notes:
  696. * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
  697. * - many system admins would disable the exec(), shell_exec(), popen() and similar functions
  698. * due to security concerns, hence the function_usable() checks
  699. */
  700. if (DIRECTORY_SEPARATOR !== '\\') {
  701. $cmd = 'file --brief --mime ' . escapeshellarg($filepath) . ' 2>&1';
  702. if (empty($mimetype) && function_exists('exec')) {
  703. /* This might look confusing, as $mime is being populated with all of the output
  704. * when set in the second parameter. However, we only need the last line, which is
  705. * the actual return value of exec(), and as such - it overwrites anything that could
  706. * already be set for $mime previously. This effectively makes the second parameter a
  707. * dummy value, which is only put to allow us to get the return status code.
  708. */
  709. $mime = @exec($cmd, $mime, $return_status);
  710. if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) {
  711. $mimetype = $matches[1];
  712. }
  713. }
  714. if (empty($mimetype) && function_exists('shell_exec')) {
  715. $mime = @shell_exec($cmd);
  716. if (strlen($mime) > 0) {
  717. $mime = explode("\n", trim($mime));
  718. if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
  719. $mimetype = $matches[1];
  720. }
  721. }
  722. }
  723. if (empty($mimetype) && function_exists('popen')) {
  724. $proc = @popen($cmd, 'r');
  725. if (is_resource($proc)) {
  726. $mime = @fread($proc, 512);
  727. @pclose($proc);
  728. if ($mime !== false) {
  729. $mime = explode("\n", trim($mime));
  730. if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
  731. $mimetype = $matches[1];
  732. }
  733. }
  734. }
  735. }
  736. }
  737. // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type'])
  738. if (empty($mimetype) && function_exists('mime_content_type')) {
  739. $mimetype = @mime_content_type($filepath);
  740. // It's possible that mime_content_type() returns FALSE or an empty string
  741. if ($mimetype == false && strlen($mimetype) > 0) {
  742. throw new ServerException(_m('Could not determine file\'s MIME type.'));
  743. }
  744. }
  745. // Unclear types are such that we can't really tell by the auto
  746. // detect what they are (.bin, .exe etc. are just "octet-stream")
  747. $unclearTypes = ['application/octet-stream',
  748. 'application/vnd.ms-office',
  749. 'application/zip',
  750. 'text/plain',
  751. 'text/html', // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
  752. // TODO: for XML we could do better content-based sniffing too
  753. 'text/xml',];
  754. $supported = common_config('attachments', 'supported');
  755. // If we didn't match, or it is an unclear match
  756. if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
  757. try {
  758. $type = common_supported_filename_to_mime($originalFilename);
  759. return $type;
  760. } catch (UnknownExtensionMimeException $e) {
  761. // FIXME: I think we should keep the file extension here (supported should be === true here)
  762. } catch (Exception $e) {
  763. // Extension parsed but no connected mimetype, so $mimetype is our best guess
  764. }
  765. }
  766. // If $config['attachments']['supported'] equals boolean true, accept any mimetype
  767. if ($supported === true || array_key_exists($mimetype, $supported)) {
  768. // FIXME: Don't know if it always has a mimetype here because
  769. // finfo->file CAN return false on error: http://php.net/finfo_file
  770. // so if $supported === true, this may return something unexpected.
  771. return $mimetype;
  772. }
  773. // We can conclude that we have failed to get the MIME type
  774. $media = common_get_mime_media($mimetype);
  775. if ('application' !== $media) {
  776. // TRANS: Client exception thrown trying to upload a forbidden MIME type.
  777. // TRANS: %1$s is the file type that was denied, %2$s is the application part of
  778. // TRANS: the MIME type that was denied.
  779. $hint = sprintf(_m('"%1$s" is not a supported file type on this server. ' .
  780. 'Try using another %2$s format.'), $mimetype, $media);
  781. } else {
  782. // TRANS: Client exception thrown trying to upload a forbidden MIME type.
  783. // TRANS: %s is the file type that was denied.
  784. $hint = sprintf(_m('"%s" is not a supported file type on this server.'), $mimetype);
  785. }
  786. throw new ClientException($hint);
  787. }
  788. /**
  789. * Title for a file, to display in the interface (if there's no better title) and
  790. * for download filenames
  791. *
  792. * @param $file File object
  793. * @returns string
  794. */
  795. public static function getDisplayName(File $file): string
  796. {
  797. if (empty($file->filename)) {
  798. return _m('Untitled attachment');
  799. }
  800. // New file name format is "{bin2hex(original_name.ext)}-{$hash}"
  801. $filename = self::decodeFilename($file->filename);
  802. // If there was an error in the match, something's wrong with some piece
  803. // of code (could be a file with utf8 chars in the name)
  804. $log_error_msg = "Invalid file name for File with id={$file->id} " .
  805. "({$file->filename}). Some plugin probably did something wrong.";
  806. if ($filename === false) {
  807. common_log(LOG_ERR, $log_error_msg);
  808. } elseif ($filename === null) {
  809. // The old file name format was "{hash}.{ext}" so we didn't have a name
  810. // This extracts the extension
  811. $ret = preg_match('/^.+?\.+?(.+)$/', $file->filename, $matches);
  812. if ($ret !== 1) {
  813. common_log(LOG_ERR, $log_error_msg);
  814. return _m('Untitled attachment');
  815. }
  816. $ext = $matches[1];
  817. // There's a blacklisted extension array, which could have an alternative
  818. // extension, such as phps, to replace php. We want to turn it back
  819. // (currently defaulted to empty, but let's keep the feature)
  820. $blacklist = common_config('attachments', 'extblacklist');
  821. if (is_array($blacklist)) {
  822. foreach ($blacklist as $upload_ext => $safe_ext) {
  823. if ($ext === $safe_ext) {
  824. $ext = $upload_ext;
  825. break;
  826. }
  827. }
  828. }
  829. $filename = "untitled.{$ext}";
  830. }
  831. return $filename;
  832. }
  833. }