mediafile.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  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 Cordeiro <diogo@fc.up.pt>
  27. * @copyright 2008-2009, 2019-2020 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. /**
  32. * Class responsible for abstracting media files
  33. */
  34. class MediaFile
  35. {
  36. public $id;
  37. public $filepath;
  38. public $filename;
  39. public $fileRecord;
  40. public $fileurl;
  41. public $short_fileurl;
  42. public $mimetype;
  43. /**
  44. * MediaFile constructor.
  45. *
  46. * @param string $filepath The path of the file this media refers to. Required
  47. * @param string $mimetype The mimetype of the file. Required
  48. * @param string|null $filehash The hash of the file, if known. Optional
  49. * @param int|null $id The DB id of the file. Int if known, null if not.
  50. * If null, it searches for it. If -1, it skips all DB
  51. * interactions (useful for temporary objects)
  52. *
  53. * @throws ClientException
  54. * @throws NoResultException
  55. * @throws ServerException
  56. */
  57. public function __construct(string $filepath, string $mimetype, ?string $filehash = null, ?int $id = null)
  58. {
  59. $this->filepath = $filepath;
  60. $this->filename = basename($this->filepath);
  61. $this->mimetype = $mimetype;
  62. $this->filehash = self::getHashOfFile($this->filepath, $filehash);
  63. $this->id = $id;
  64. // If id is -1, it means we're dealing with a temporary object and don't want to store it in the DB,
  65. // or add redirects
  66. if ($this->id !== -1) {
  67. if (!empty($this->id)) {
  68. // If we have an id, load it
  69. $this->fileRecord = new File();
  70. $this->fileRecord->id = $this->id;
  71. if (!$this->fileRecord->find(true)) {
  72. // If we have set an ID, we need that ID to exist!
  73. throw new NoResultException($this->fileRecord);
  74. }
  75. } else {
  76. // Otherwise, store it
  77. $this->fileRecord = $this->storeFile();
  78. }
  79. $this->fileurl = common_local_url(
  80. 'attachment',
  81. ['attachment' => $this->fileRecord->id]
  82. );
  83. $this->short_fileurl = common_shorten_url($this->fileurl);
  84. }
  85. }
  86. public function attachToNotice(Notice $notice)
  87. {
  88. File_to_post::processNew($this->fileRecord, $notice);
  89. }
  90. public function getPath()
  91. {
  92. return File::path($this->filename);
  93. }
  94. public function shortUrl()
  95. {
  96. return $this->short_fileurl;
  97. }
  98. public function getEnclosure()
  99. {
  100. return $this->getFile()->getEnclosure();
  101. }
  102. public function delete()
  103. {
  104. @unlink($this->filepath);
  105. }
  106. public function getFile()
  107. {
  108. if (!$this->fileRecord instanceof File) {
  109. throw new ServerException('File record did not exist for MediaFile');
  110. }
  111. return $this->fileRecord;
  112. }
  113. /**
  114. * Calculate the hash of a file.
  115. *
  116. * This won't work for files >2GiB because PHP uses only 32bit.
  117. *
  118. * @param string $filepath
  119. * @param null|string $filehash
  120. *
  121. * @return string
  122. * @throws ServerException
  123. *
  124. */
  125. public static function getHashOfFile(string $filepath, $filehash = null)
  126. {
  127. assert(!empty($filepath), __METHOD__ . ': filepath cannot be null');
  128. if ($filehash === null) {
  129. // Calculate if we have an older upload method somewhere (Qvitter) that
  130. // doesn't do this before calling new MediaFile on its local files...
  131. $filehash = hash_file(File::FILEHASH_ALG, $filepath);
  132. if ($filehash === false) {
  133. throw new ServerException('Could not read file for hashing');
  134. }
  135. }
  136. return $filehash;
  137. }
  138. /**
  139. * Retrieve or insert as a file in the DB
  140. *
  141. * @return object File
  142. * @throws ServerException
  143. *
  144. * @throws ClientException
  145. */
  146. protected function storeFile()
  147. {
  148. try {
  149. $file = File::getByHash($this->filehash);
  150. // We're done here. Yes. Already. We assume sha256 won't collide on us anytime soon.
  151. return $file;
  152. } catch (NoResultException $e) {
  153. // Well, let's just continue below.
  154. }
  155. $fileurl = common_local_url('attachment_view', ['filehash' => $this->filehash]);
  156. $file = new File;
  157. $file->filename = $this->filename;
  158. $file->urlhash = File::hashurl($fileurl);
  159. $file->url = $fileurl;
  160. $file->filehash = $this->filehash;
  161. $file->size = filesize($this->filepath);
  162. if ($file->size === false) {
  163. throw new ServerException('Could not read file to get its size');
  164. }
  165. $file->date = time();
  166. $file->mimetype = $this->mimetype;
  167. $file_id = $file->insert();
  168. if ($file_id === false) {
  169. common_log_db_error($file, 'INSERT', __FILE__);
  170. // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
  171. throw new ClientException(_m('There was a database error while saving your file. Please try again.'));
  172. }
  173. // Set file geometrical properties if available
  174. try {
  175. $image = ImageFile::fromFileObject($file);
  176. $orig = clone $file;
  177. $file->width = $image->width;
  178. $file->height = $image->height;
  179. $file->update($orig);
  180. // We have to cleanup after ImageFile, since it
  181. // may have generated a temporary file from a
  182. // video support plugin or something.
  183. // FIXME: Do this more automagically.
  184. if ($image->getPath() != $file->getPath()) {
  185. $image->unlink();
  186. }
  187. } catch (ServerException $e) {
  188. // We just couldn't make out an image from the file. This
  189. // does not have to be UnsupportedMediaException, as we can
  190. // also get ServerException from files not existing etc.
  191. }
  192. return $file;
  193. }
  194. /**
  195. * The maximum allowed file size, as a string
  196. */
  197. public static function maxFileSize()
  198. {
  199. $value = self::maxFileSizeInt();
  200. if ($value > 1024 * 1024) {
  201. $value = $value / (1024 * 1024);
  202. // TRANS: Number of megabytes. %d is the number.
  203. return sprintf(_m('%dMB', '%dMB', $value), $value);
  204. } elseif ($value > 1024) {
  205. $value = $value / 1024;
  206. // TRANS: Number of kilobytes. %d is the number.
  207. return sprintf(_m('%dkB', '%dkB', $value), $value);
  208. } else {
  209. // TRANS: Number of bytes. %d is the number.
  210. return sprintf(_m('%dB', '%dB', $value), $value);
  211. }
  212. }
  213. /**
  214. * The maximum allowed file size, as an int
  215. */
  216. public static function maxFileSizeInt(): int
  217. {
  218. return common_config('attachments', 'file_quota');
  219. }
  220. /**
  221. * Encodes a file name and a file hash in the new file format, which is used to avoid
  222. * having an extension in the file, removing trust in extensions, while keeping the original name
  223. *
  224. * @param mixed $original_name
  225. * @param null|mixed $ext
  226. *
  227. * @throws ClientException
  228. */
  229. public static function encodeFilename($original_name, string $filehash, $ext = null): string
  230. {
  231. if (empty($original_name)) {
  232. $original_name = _m('Untitled attachment');
  233. }
  234. // If we're given an extension explicitly, use it, otherwise...
  235. $ext = $ext ?:
  236. // get a replacement extension if configured, returns false if it's blocked,
  237. // null if no extension
  238. File::getSafeExtension($original_name);
  239. if ($ext === false) {
  240. throw new ClientException(_m('Blacklisted file extension.'));
  241. }
  242. if (!empty($ext)) {
  243. // Remove dots if we have them (make sure they're not repeated)
  244. $ext = preg_replace('/^\.+/', '', $ext);
  245. $original_name = preg_replace('/\.+.+$/i', ".{$ext}", $original_name);
  246. }
  247. $enc_name = bin2hex($original_name);
  248. return "{$enc_name}-{$filehash}";
  249. }
  250. /**
  251. * Decode the new filename format
  252. *
  253. * @return false | null | string on failure, no match (old format) or original file name, respectively
  254. */
  255. public static function decodeFilename(string $encoded_filename)
  256. {
  257. // Should match:
  258. // hex-hash
  259. // thumb-id-widthxheight-hex-hash
  260. // And return the `hex` part
  261. $ret = preg_match('/^(.*-)?([^-]+)-[^-]+$/', $encoded_filename, $matches);
  262. if ($ret === false) {
  263. return false;
  264. } elseif ($ret === 0 || !ctype_xdigit($matches[2])) {
  265. return null; // No match
  266. } else {
  267. $filename = hex2bin($matches[2]);
  268. // Matches extension
  269. if (preg_match('/^(.+?)\.(.+)$/', $filename, $sub_matches) === 1) {
  270. $ext = $sub_matches[2];
  271. // Previously, there was a blacklisted extension array, which could have an alternative
  272. // extension, such as phps, to replace php. We want to turn it back (this is deprecated,
  273. // as it no longer makes sense, since we don't trust trust files based on extension,
  274. // but keep the feature)
  275. $blacklist = common_config('attachments', 'extblacklist');
  276. if (is_array($blacklist)) {
  277. foreach ($blacklist as $upload_ext => $safe_ext) {
  278. if ($ext === $safe_ext) {
  279. $ext = $upload_ext;
  280. break;
  281. }
  282. }
  283. }
  284. return "{$sub_matches[1]}.{$ext}";
  285. } else {
  286. // No extension, don't bother trying to replace it
  287. return $filename;
  288. }
  289. }
  290. }
  291. /**
  292. * Create a new MediaFile or ImageFile object from an upload
  293. *
  294. * Tries to set the mimetype correctly, using the most secure method available and rejects the file otherwise.
  295. * In case the upload is an image, this function returns an new ImageFile (which extends MediaFile)
  296. * The filename has a new format:
  297. * bin2hex("{$original_name}.{$ext}")."-{$filehash}"
  298. * This format should be respected. Notice the dash, which is important to distinguish it from the previous
  299. * format ("{$hash}.{$ext}")
  300. *
  301. * @param string $param Form name
  302. * @param null|Profile $scoped
  303. *
  304. * @return ImageFile|MediaFile
  305. * @throws NoResultException
  306. * @throws NoUploadedMediaException
  307. * @throws ServerException
  308. * @throws UnsupportedMediaException
  309. * @throws UseFileAsThumbnailException
  310. *
  311. * @throws ClientException
  312. */
  313. public static function fromUpload(string $param = 'media', Profile $scoped = null)
  314. {
  315. // The existence of the "error" element means PHP has processed it properly even if it was ok.
  316. if (!(isset($_FILES[$param], $_FILES[$param]['error']))) {
  317. throw new NoUploadedMediaException($param);
  318. }
  319. switch ($_FILES[$param]['error']) {
  320. case UPLOAD_ERR_OK: // success, jump out
  321. break;
  322. case UPLOAD_ERR_INI_SIZE:
  323. case UPLOAD_ERR_FORM_SIZE:
  324. // TRANS: Exception thrown when too large a file is uploaded.
  325. // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
  326. throw new ClientException(sprintf(
  327. _m('That file is too big. The maximum file size is %s.'),
  328. self::maxFileSize()
  329. ));
  330. case UPLOAD_ERR_PARTIAL:
  331. @unlink($_FILES[$param]['tmp_name']);
  332. // TRANS: Client exception.
  333. throw new ClientException(_m('The uploaded file was only partially uploaded.'));
  334. case UPLOAD_ERR_NO_FILE:
  335. // No file; probably just a non-AJAX submission.
  336. throw new NoUploadedMediaException($param);
  337. case UPLOAD_ERR_NO_TMP_DIR:
  338. // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
  339. throw new ClientException(_m('Missing a temporary folder.'));
  340. case UPLOAD_ERR_CANT_WRITE:
  341. // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
  342. throw new ClientException(_m('Failed to write file to disk.'));
  343. case UPLOAD_ERR_EXTENSION:
  344. // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
  345. throw new ClientException(_m('File upload stopped by extension.'));
  346. default:
  347. common_log(LOG_ERR, __METHOD__ . ': Unknown upload error ' . $_FILES[$param]['error']);
  348. // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
  349. throw new ClientException(_m('System error uploading file.'));
  350. }
  351. $filehash = strtolower(self::getHashOfFile($_FILES[$param]['tmp_name']));
  352. try {
  353. $file = File::getByHash($filehash);
  354. // If no exception is thrown the file exists locally, so we'll use that and just add redirections.
  355. // but if the _actual_ locally stored file doesn't exist, getPath will throw FileNotFoundException
  356. $filepath = $file->getPath();
  357. $mimetype = $file->mimetype;
  358. } catch (FileNotFoundException | NoResultException $e) {
  359. // We have to save the upload as a new local file. This is the normal course of action.
  360. if ($scoped instanceof Profile) {
  361. // Throws exception if additional size does not respect quota
  362. // This test is only needed, of course, if we're uploading something new.
  363. File::respectsQuota($scoped, $_FILES[$param]['size']);
  364. }
  365. $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
  366. $media = common_get_mime_media($mimetype);
  367. $basename = basename($_FILES[$param]['name']);
  368. if ($media == 'image') {
  369. // Use -1 for the id to avoid adding this temporary file to the DB
  370. $img = new ImageFile(-1, $_FILES[$param]['tmp_name']);
  371. // Validate the image by re-encoding it. Additionally normalizes old formats to PNG,
  372. // keeping JPEG and GIF untouched
  373. $outpath = $img->resizeTo($img->filepath);
  374. $ext = image_type_to_extension($img->preferredType(), false);
  375. }
  376. $filename = self::encodeFilename($basename, $filehash, isset($ext) ? $ext : File::getSafeExtension($basename));
  377. $filepath = File::path($filename);
  378. if ($media == 'image') {
  379. $result = rename($outpath, $filepath);
  380. } else {
  381. $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
  382. }
  383. if (!$result) {
  384. // TRANS: Client exception thrown when a file upload operation fails because the file could
  385. // TRANS: not be moved from the temporary folder to the permanent file location.
  386. // UX: too specific
  387. throw new ClientException(_m('File could not be moved to destination directory.'));
  388. }
  389. if ($media == 'image') {
  390. return new ImageFile(null, $filepath);
  391. }
  392. }
  393. return new self($filepath, $mimetype, $filehash);
  394. }
  395. public static function fromFilehandle($fh, Profile $scoped = null)
  396. {
  397. $stream = stream_get_meta_data($fh);
  398. // So far we're only handling filehandles originating from tmpfile(),
  399. // so we can always do hash_file on $stream['uri'] as far as I can tell!
  400. $filehash = hash_file(File::FILEHASH_ALG, $stream['uri']);
  401. try {
  402. $file = File::getByHash($filehash);
  403. // Already have it, so let's reuse the locally stored File
  404. // by using getPath we also check whether the file exists
  405. // and throw a FileNotFoundException with the path if it doesn't.
  406. $filename = basename($file->getPath());
  407. $mimetype = $file->mimetype;
  408. } catch (FileNotFoundException $e) {
  409. // This happens if the file we have uploaded has disappeared
  410. // from the local filesystem for some reason. Since we got the
  411. // File object from a sha256 check in fromFilehandle, it's safe
  412. // to just copy the uploaded data to disk!
  413. fseek($fh, 0); // just to be sure, go to the beginning
  414. // dump the contents of our filehandle to the path from our exception
  415. // and report error if it failed.
  416. if (false === file_put_contents($e->path, fread($fh, filesize($stream['uri'])))) {
  417. // TRANS: Client exception thrown when a file upload operation fails because the file could
  418. // TRANS: not be moved from the temporary folder to the permanent file location.
  419. throw new ClientException(_m('File could not be moved to destination directory.'));
  420. }
  421. if (!chmod($e->path, 0664)) {
  422. common_log(LOG_ERR, 'Could not chmod uploaded file: ' . _ve($e->path));
  423. }
  424. $filename = basename($file->getPath());
  425. $mimetype = $file->mimetype;
  426. } catch (NoResultException $e) {
  427. if ($scoped instanceof Profile) {
  428. File::respectsQuota($scoped, filesize($stream['uri']));
  429. }
  430. $mimetype = self::getUploadedMimeType($stream['uri']);
  431. $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
  432. $filepath = File::path($filename);
  433. $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
  434. if (!$result) {
  435. common_log(LOG_ERR, 'File could not be moved (or chmodded) from ' . _ve($stream['uri']) . ' to ' . _ve($filepath));
  436. // TRANS: Client exception thrown when a file upload operation fails because the file could
  437. // TRANS: not be moved from the temporary folder to the permanent file location.
  438. throw new ClientException(_m('File could not be moved to destination directory.'));
  439. }
  440. }
  441. return new self($filename, $mimetype, $filehash);
  442. }
  443. /**
  444. * Attempt to identify the content type of a given file.
  445. *
  446. * @param string $filepath filesystem path as string (file must exist)
  447. * @param bool $originalFilename (optional) for extension-based detection
  448. *
  449. * @return string
  450. *
  451. * @fixme this seems to tie a front-end error message in, kinda confusing
  452. *
  453. * @throws ServerException
  454. *
  455. * @throws ClientException if type is known, but not supported for local uploads
  456. */
  457. public static function getUploadedMimeType(string $filepath, $originalFilename = false)
  458. {
  459. // We only accept filenames to existing files
  460. $mimetype = null;
  461. // From CodeIgniter
  462. // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
  463. $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s[^\/]+)?$/';
  464. /**
  465. * Fileinfo extension - most reliable method
  466. *
  467. * Apparently XAMPP, CentOS, cPanel and who knows what
  468. * other PHP distribution channels EXPLICITLY DISABLE
  469. * ext/fileinfo, which is otherwise enabled by default
  470. * since PHP 5.3 ...
  471. */
  472. if (function_exists('finfo_file')) {
  473. $finfo = @finfo_open(FILEINFO_MIME);
  474. // It is possible that a FALSE value is returned, if there is no magic MIME database
  475. // file found on the system
  476. if (is_resource($finfo)) {
  477. $mime = @finfo_file($finfo, $filepath);
  478. finfo_close($finfo);
  479. /* According to the comments section of the PHP manual page,
  480. * it is possible that this function returns an empty string
  481. * for some files (e.g. if they don't exist in the magic MIME database)
  482. */
  483. if (is_string($mime) && preg_match($regexp, $mime, $matches)) {
  484. $mimetype = $matches[1];
  485. }
  486. }
  487. }
  488. /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
  489. * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
  490. * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better
  491. * than mime_content_type() as well, hence the attempts to try calling the command line with
  492. * three different functions.
  493. *
  494. * Notes:
  495. * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
  496. * - many system admins would disable the exec(), shell_exec(), popen() and similar functions
  497. * due to security concerns, hence the function_usable() checks
  498. */
  499. if (DIRECTORY_SEPARATOR !== '\\') {
  500. $cmd = 'file --brief --mime ' . escapeshellarg($filepath) . ' 2>&1';
  501. if (empty($mimetype) && function_exists('exec')) {
  502. /* This might look confusing, as $mime is being populated with all of the output
  503. * when set in the second parameter. However, we only need the last line, which is
  504. * the actual return value of exec(), and as such - it overwrites anything that could
  505. * already be set for $mime previously. This effectively makes the second parameter a
  506. * dummy value, which is only put to allow us to get the return status code.
  507. */
  508. $mime = @exec($cmd, $mime, $return_status);
  509. if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) {
  510. $mimetype = $matches[1];
  511. }
  512. }
  513. if (empty($mimetype) && function_exists('shell_exec')) {
  514. $mime = @shell_exec($cmd);
  515. if (strlen($mime) > 0) {
  516. $mime = explode("\n", trim($mime));
  517. if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
  518. $mimetype = $matches[1];
  519. }
  520. }
  521. }
  522. if (empty($mimetype) && function_exists('popen')) {
  523. $proc = @popen($cmd, 'r');
  524. if (is_resource($proc)) {
  525. $mime = @fread($proc, 512);
  526. @pclose($proc);
  527. if ($mime !== false) {
  528. $mime = explode("\n", trim($mime));
  529. if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
  530. $mimetype = $matches[1];
  531. }
  532. }
  533. }
  534. }
  535. }
  536. // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type'])
  537. if (empty($mimetype) && function_exists('mime_content_type')) {
  538. $mimetype = @mime_content_type($filepath);
  539. // It's possible that mime_content_type() returns FALSE or an empty string
  540. if ($mimetype == false && strlen($mimetype) > 0) {
  541. throw new ServerException(_m('Could not determine file\'s MIME type.'));
  542. }
  543. }
  544. // Unclear types are such that we can't really tell by the auto
  545. // detect what they are (.bin, .exe etc. are just "octet-stream")
  546. $unclearTypes = ['application/octet-stream',
  547. 'application/vnd.ms-office',
  548. 'application/zip',
  549. 'text/plain',
  550. 'text/html', // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
  551. // TODO: for XML we could do better content-based sniffing too
  552. 'text/xml',];
  553. $supported = common_config('attachments', 'supported');
  554. // If we didn't match, or it is an unclear match
  555. if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
  556. try {
  557. $type = common_supported_filename_to_mime($originalFilename);
  558. return $type;
  559. } catch (UnknownExtensionMimeException $e) {
  560. // FIXME: I think we should keep the file extension here (supported should be === true here)
  561. } catch (Exception $e) {
  562. // Extension parsed but no connected mimetype, so $mimetype is our best guess
  563. }
  564. }
  565. // If $config['attachments']['supported'] equals boolean true, accept any mimetype
  566. if ($supported === true || array_key_exists($mimetype, $supported)) {
  567. // FIXME: Don't know if it always has a mimetype here because
  568. // finfo->file CAN return false on error: http://php.net/finfo_file
  569. // so if $supported === true, this may return something unexpected.
  570. return $mimetype;
  571. }
  572. // We can conclude that we have failed to get the MIME type
  573. $media = common_get_mime_media($mimetype);
  574. if ('application' !== $media) {
  575. // TRANS: Client exception thrown trying to upload a forbidden MIME type.
  576. // TRANS: %1$s is the file type that was denied, %2$s is the application part of
  577. // TRANS: the MIME type that was denied.
  578. $hint = sprintf(_m('"%1$s" is not a supported file type on this server. ' .
  579. 'Try using another %2$s format.'), $mimetype, $media);
  580. } else {
  581. // TRANS: Client exception thrown trying to upload a forbidden MIME type.
  582. // TRANS: %s is the file type that was denied.
  583. $hint = sprintf(_m('"%s" is not a supported file type on this server.'), $mimetype);
  584. }
  585. throw new ClientException($hint);
  586. }
  587. /**
  588. * Title for a file, to display in the interface (if there's no better title) and
  589. * for download filenames
  590. *
  591. * @param $file File object
  592. * @returns string
  593. */
  594. public static function getDisplayName(File $file): string
  595. {
  596. if (empty($file->filename)) {
  597. return _m('Untitled attachment');
  598. }
  599. // New file name format is "{bin2hex(original_name.ext)}-{$hash}"
  600. $filename = self::decodeFilename($file->filename);
  601. // If there was an error in the match, something's wrong with some piece
  602. // of code (could be a file with utf8 chars in the name)
  603. $log_error_msg = "Invalid file name for File with id={$file->id} " .
  604. "({$file->filename}). Some plugin probably did something wrong.";
  605. if ($filename === false) {
  606. common_log(LOG_ERR, $log_error_msg);
  607. } elseif ($filename === null) {
  608. // The old file name format was "{hash}.{ext}" so we didn't have a name
  609. // This extracts the extension
  610. $ret = preg_match('/^.+?\.+?(.+)$/', $file->filename, $matches);
  611. if ($ret !== 1) {
  612. common_log(LOG_ERR, $log_error_msg);
  613. return _m('Untitled attachment');
  614. }
  615. $ext = $matches[1];
  616. // There's a blacklisted extension array, which could have an alternative
  617. // extension, such as phps, to replace php. We want to turn it back
  618. // (currently defaulted to empty, but let's keep the feature)
  619. $blacklist = common_config('attachments', 'extblacklist');
  620. if (is_array($blacklist)) {
  621. foreach ($blacklist as $upload_ext => $safe_ext) {
  622. if ($ext === $safe_ext) {
  623. $ext = $upload_ext;
  624. break;
  625. }
  626. }
  627. }
  628. $filename = "untitled.{$ext}";
  629. }
  630. return $filename;
  631. }
  632. }