mediafile.php 33 KB

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