mediafile.php 30 KB

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