mediafile.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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 URL
  293. *
  294. * @param string $url
  295. * @param Profile|null $scoped
  296. * @return ImageFile|MediaFile
  297. * @throws UnsupportedMediaException
  298. * @throws UseFileAsThumbnailException
  299. */
  300. public static function fromUrl(string $url, Profile $scoped=null)
  301. {
  302. $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
  303. try {
  304. $imgData = HTTPClient::quickGet($url);
  305. file_put_contents($temp_filename, $imgData);
  306. unset($imgData); // No need to carry this in memory.
  307. common_debug('ActivityPub Explorer: Stored dowloaded avatar in: ' . $temp_filename);
  308. $id = $profile->getID();
  309. $upload_directory = 'includes/uploads/avatars';
  310. // sets $image & gets image type, name, tmp_name
  311. $image = $_FILES['avatar'];
  312. $image_name = $_FILES['avatar']['name'];
  313. $image_tmp_name = $_FILES['avatar']['tmp_name'];
  314. $image_type = $_FILES['avatar']['type'];
  315. // set file name (make it unique)
  316. $file_name = $activation_id.$image_name;
  317. // finds extension of file uploaded...
  318. $image_extension = strtolower(pathinfo($image,PATHINFO_EXTENSION));
  319. // allowed extensions of file uploaded...
  320. $valid_image_extensions = array('jpeg', 'jpg', 'png', 'gif');
  321. // if image extension is a valid image extension...
  322. if (in_array($image_extension, $valid_image_extensions)) {
  323. // move the file to desired directory ($upload_directory)
  324. move_uploaded_file($file_name, $upload_directory);
  325. common_debug('ActivityPub Explorer: Moved avatar from: ' . $filename . ' to ' . $upload_directory);
  326. } catch (Exception $e) {
  327. common_debug('ActivityPub Explorer: Something went wrong while processing the avatar from: ' . $url . ' details: ' . $e->getMessage());
  328. unlink($temp_filename);
  329. throw $e;
  330. }
  331. if ($media == 'image') {
  332. $result = rename($outpath, $filepath);
  333. } else {
  334. $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
  335. }
  336. if (!$result) {
  337. throw new ClientException(_m('File could not be moved to destination directory.'));
  338. }
  339. return new MediaFile($filepath, $mimetype, $filehash);
  340. }
  341. /**
  342. * Create a new MediaFile or ImageFile object from an upload
  343. *
  344. * Tries to set the mimetype correctly, using the most secure method available and rejects the file otherwise.
  345. * In case the upload is an image, this function returns an new ImageFile (which extends MediaFile)
  346. * The filename has a new format:
  347. * bin2hex("{$original_name}.{$ext}")."-{$filehash}"
  348. * This format should be respected. Notice the dash, which is important to distinguish it from the previous
  349. * format ("{$hash}.{$ext}")
  350. *
  351. * @param string $param Form name
  352. * @param null|Profile $scoped
  353. *
  354. * @return ImageFile|MediaFile
  355. * @throws NoResultException
  356. * @throws NoUploadedMediaException
  357. * @throws ServerException
  358. * @throws UnsupportedMediaException
  359. * @throws UseFileAsThumbnailException
  360. *
  361. * @throws ClientException
  362. */
  363. public static function fromUpload(string $param = 'media', Profile $scoped = null)
  364. {
  365. // The existence of the "error" element means PHP has processed it properly even if it was ok.
  366. if (!(isset($_FILES[$param], $_FILES[$param]['error']))) {
  367. throw new NoUploadedMediaException($param);
  368. }
  369. switch ($_FILES[$param]['error']) {
  370. case UPLOAD_ERR_OK: // success, jump out
  371. break;
  372. case UPLOAD_ERR_INI_SIZE:
  373. case UPLOAD_ERR_FORM_SIZE:
  374. // TRANS: Exception thrown when too large a file is uploaded.
  375. // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
  376. throw new ClientException(sprintf(
  377. _m('That file is too big. The maximum file size is %s.'),
  378. self::maxFileSize()
  379. ));
  380. case UPLOAD_ERR_PARTIAL:
  381. @unlink($_FILES[$param]['tmp_name']);
  382. // TRANS: Client exception.
  383. throw new ClientException(_m('The uploaded file was only partially uploaded.'));
  384. case UPLOAD_ERR_NO_FILE:
  385. // No file; probably just a non-AJAX submission.
  386. throw new NoUploadedMediaException($param);
  387. case UPLOAD_ERR_NO_TMP_DIR:
  388. // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
  389. throw new ClientException(_m('Missing a temporary folder.'));
  390. case UPLOAD_ERR_CANT_WRITE:
  391. // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
  392. throw new ClientException(_m('Failed to write file to disk.'));
  393. case UPLOAD_ERR_EXTENSION:
  394. // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
  395. throw new ClientException(_m('File upload stopped by extension.'));
  396. default:
  397. common_log(LOG_ERR, __METHOD__ . ': Unknown upload error ' . $_FILES[$param]['error']);
  398. // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
  399. throw new ClientException(_m('System error uploading file.'));
  400. }
  401. $filehash = strtolower(self::getHashOfFile($_FILES[$param]['tmp_name']));
  402. try {
  403. $file = File::getByHash($filehash);
  404. // If no exception is thrown the file exists locally, so we'll use that and just add redirections.
  405. // but if the _actual_ locally stored file doesn't exist, getPath will throw FileNotFoundException
  406. $filepath = $file->getPath();
  407. $mimetype = $file->mimetype;
  408. } catch (FileNotFoundException | NoResultException $e) {
  409. // We have to save the upload as a new local file. This is the normal course of action.
  410. if ($scoped instanceof Profile) {
  411. // Throws exception if additional size does not respect quota
  412. // This test is only needed, of course, if we're uploading something new.
  413. File::respectsQuota($scoped, $_FILES[$param]['size']);
  414. }
  415. $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
  416. $media = common_get_mime_media($mimetype);
  417. $basename = basename($_FILES[$param]['name']);
  418. if ($media == 'image') {
  419. // Use -1 for the id to avoid adding this temporary file to the DB
  420. $img = new ImageFile(-1, $_FILES[$param]['tmp_name']);
  421. // Validate the image by re-encoding it. Additionally normalizes old formats to PNG,
  422. // keeping JPEG and GIF untouched
  423. $outpath = $img->resizeTo($img->filepath);
  424. $ext = image_type_to_extension($img->preferredType(), false);
  425. }
  426. $filename = self::encodeFilename($basename, $filehash, isset($ext) ? $ext : File::getSafeExtension($basename));
  427. $filepath = File::path($filename);
  428. if ($media == 'image') {
  429. $result = rename($outpath, $filepath);
  430. } else {
  431. $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
  432. }
  433. if (!$result) {
  434. // TRANS: Client exception thrown when a file upload operation fails because the file could
  435. // TRANS: not be moved from the temporary folder to the permanent file location.
  436. // UX: too specific
  437. throw new ClientException(_m('File could not be moved to destination directory.'));
  438. }
  439. if ($media == 'image') {
  440. return new ImageFile(null, $filepath);
  441. }
  442. }
  443. return new self($filepath, $mimetype, $filehash);
  444. }
  445. public static function fromFilehandle($fh, Profile $scoped = null)
  446. {
  447. $stream = stream_get_meta_data($fh);
  448. // So far we're only handling filehandles originating from tmpfile(),
  449. // so we can always do hash_file on $stream['uri'] as far as I can tell!
  450. $filehash = hash_file(File::FILEHASH_ALG, $stream['uri']);
  451. try {
  452. $file = File::getByHash($filehash);
  453. // Already have it, so let's reuse the locally stored File
  454. // by using getPath we also check whether the file exists
  455. // and throw a FileNotFoundException with the path if it doesn't.
  456. $filename = basename($file->getPath());
  457. $mimetype = $file->mimetype;
  458. } catch (FileNotFoundException $e) {
  459. // This happens if the file we have uploaded has disappeared
  460. // from the local filesystem for some reason. Since we got the
  461. // File object from a sha256 check in fromFilehandle, it's safe
  462. // to just copy the uploaded data to disk!
  463. fseek($fh, 0); // just to be sure, go to the beginning
  464. // dump the contents of our filehandle to the path from our exception
  465. // and report error if it failed.
  466. if (false === file_put_contents($e->path, fread($fh, filesize($stream['uri'])))) {
  467. // TRANS: Client exception thrown when a file upload operation fails because the file could
  468. // TRANS: not be moved from the temporary folder to the permanent file location.
  469. throw new ClientException(_m('File could not be moved to destination directory.'));
  470. }
  471. if (!chmod($e->path, 0664)) {
  472. common_log(LOG_ERR, 'Could not chmod uploaded file: ' . _ve($e->path));
  473. }
  474. $filename = basename($file->getPath());
  475. $mimetype = $file->mimetype;
  476. } catch (NoResultException $e) {
  477. if ($scoped instanceof Profile) {
  478. File::respectsQuota($scoped, filesize($stream['uri']));
  479. }
  480. $mimetype = self::getUploadedMimeType($stream['uri']);
  481. $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
  482. $filepath = File::path($filename);
  483. $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
  484. if (!$result) {
  485. common_log(LOG_ERR, 'File could not be moved (or chmodded) from ' . _ve($stream['uri']) . ' to ' . _ve($filepath));
  486. // TRANS: Client exception thrown when a file upload operation fails because the file could
  487. // TRANS: not be moved from the temporary folder to the permanent file location.
  488. throw new ClientException(_m('File could not be moved to destination directory.'));
  489. }
  490. }
  491. return new self($filename, $mimetype, $filehash);
  492. }
  493. /**
  494. * Attempt to identify the content type of a given file.
  495. *
  496. * @param string $filepath filesystem path as string (file must exist)
  497. * @param bool $originalFilename (optional) for extension-based detection
  498. *
  499. * @return string
  500. *
  501. * @fixme this seems to tie a front-end error message in, kinda confusing
  502. *
  503. * @throws ServerException
  504. *
  505. * @throws ClientException if type is known, but not supported for local uploads
  506. */
  507. public static function getUploadedMimeType(string $filepath, $originalFilename = false)
  508. {
  509. // We only accept filenames to existing files
  510. $mimetype = null;
  511. // From CodeIgniter
  512. // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
  513. $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s[^\/]+)?$/';
  514. /**
  515. * Fileinfo extension - most reliable method
  516. *
  517. * Apparently XAMPP, CentOS, cPanel and who knows what
  518. * other PHP distribution channels EXPLICITLY DISABLE
  519. * ext/fileinfo, which is otherwise enabled by default
  520. * since PHP 5.3 ...
  521. */
  522. if (function_exists('finfo_file')) {
  523. $finfo = @finfo_open(FILEINFO_MIME);
  524. // It is possible that a FALSE value is returned, if there is no magic MIME database
  525. // file found on the system
  526. if (is_resource($finfo)) {
  527. $mime = @finfo_file($finfo, $filepath);
  528. finfo_close($finfo);
  529. /* According to the comments section of the PHP manual page,
  530. * it is possible that this function returns an empty string
  531. * for some files (e.g. if they don't exist in the magic MIME database)
  532. */
  533. if (is_string($mime) && preg_match($regexp, $mime, $matches)) {
  534. $mimetype = $matches[1];
  535. }
  536. }
  537. }
  538. /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
  539. * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
  540. * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better
  541. * than mime_content_type() as well, hence the attempts to try calling the command line with
  542. * three different functions.
  543. *
  544. * Notes:
  545. * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
  546. * - many system admins would disable the exec(), shell_exec(), popen() and similar functions
  547. * due to security concerns, hence the function_usable() checks
  548. */
  549. if (DIRECTORY_SEPARATOR !== '\\') {
  550. $cmd = 'file --brief --mime ' . escapeshellarg($filepath) . ' 2>&1';
  551. if (empty($mimetype) && function_exists('exec')) {
  552. /* This might look confusing, as $mime is being populated with all of the output
  553. * when set in the second parameter. However, we only need the last line, which is
  554. * the actual return value of exec(), and as such - it overwrites anything that could
  555. * already be set for $mime previously. This effectively makes the second parameter a
  556. * dummy value, which is only put to allow us to get the return status code.
  557. */
  558. $mime = @exec($cmd, $mime, $return_status);
  559. if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) {
  560. $mimetype = $matches[1];
  561. }
  562. }
  563. if (empty($mimetype) && function_exists('shell_exec')) {
  564. $mime = @shell_exec($cmd);
  565. if (strlen($mime) > 0) {
  566. $mime = explode("\n", trim($mime));
  567. if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
  568. $mimetype = $matches[1];
  569. }
  570. }
  571. }
  572. if (empty($mimetype) && function_exists('popen')) {
  573. $proc = @popen($cmd, 'r');
  574. if (is_resource($proc)) {
  575. $mime = @fread($proc, 512);
  576. @pclose($proc);
  577. if ($mime !== false) {
  578. $mime = explode("\n", trim($mime));
  579. if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) {
  580. $mimetype = $matches[1];
  581. }
  582. }
  583. }
  584. }
  585. }
  586. // Fall back to mime_content_type(), if available (still better than $_FILES[$field]['type'])
  587. if (empty($mimetype) && function_exists('mime_content_type')) {
  588. $mimetype = @mime_content_type($filepath);
  589. // It's possible that mime_content_type() returns FALSE or an empty string
  590. if ($mimetype == false && strlen($mimetype) > 0) {
  591. throw new ServerException(_m('Could not determine file\'s MIME type.'));
  592. }
  593. }
  594. // Unclear types are such that we can't really tell by the auto
  595. // detect what they are (.bin, .exe etc. are just "octet-stream")
  596. $unclearTypes = ['application/octet-stream',
  597. 'application/vnd.ms-office',
  598. 'application/zip',
  599. 'text/plain',
  600. 'text/html', // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
  601. // TODO: for XML we could do better content-based sniffing too
  602. 'text/xml',];
  603. $supported = common_config('attachments', 'supported');
  604. // If we didn't match, or it is an unclear match
  605. if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
  606. try {
  607. $type = common_supported_filename_to_mime($originalFilename);
  608. return $type;
  609. } catch (UnknownExtensionMimeException $e) {
  610. // FIXME: I think we should keep the file extension here (supported should be === true here)
  611. } catch (Exception $e) {
  612. // Extension parsed but no connected mimetype, so $mimetype is our best guess
  613. }
  614. }
  615. // If $config['attachments']['supported'] equals boolean true, accept any mimetype
  616. if ($supported === true || array_key_exists($mimetype, $supported)) {
  617. // FIXME: Don't know if it always has a mimetype here because
  618. // finfo->file CAN return false on error: http://php.net/finfo_file
  619. // so if $supported === true, this may return something unexpected.
  620. return $mimetype;
  621. }
  622. // We can conclude that we have failed to get the MIME type
  623. $media = common_get_mime_media($mimetype);
  624. if ('application' !== $media) {
  625. // TRANS: Client exception thrown trying to upload a forbidden MIME type.
  626. // TRANS: %1$s is the file type that was denied, %2$s is the application part of
  627. // TRANS: the MIME type that was denied.
  628. $hint = sprintf(_m('"%1$s" is not a supported file type on this server. ' .
  629. 'Try using another %2$s format.'), $mimetype, $media);
  630. } else {
  631. // TRANS: Client exception thrown trying to upload a forbidden MIME type.
  632. // TRANS: %s is the file type that was denied.
  633. $hint = sprintf(_m('"%s" is not a supported file type on this server.'), $mimetype);
  634. }
  635. throw new ClientException($hint);
  636. }
  637. /**
  638. * Title for a file, to display in the interface (if there's no better title) and
  639. * for download filenames
  640. *
  641. * @param $file File object
  642. * @returns string
  643. */
  644. public static function getDisplayName(File $file): string
  645. {
  646. if (empty($file->filename)) {
  647. return _m('Untitled attachment');
  648. }
  649. // New file name format is "{bin2hex(original_name.ext)}-{$hash}"
  650. $filename = self::decodeFilename($file->filename);
  651. // If there was an error in the match, something's wrong with some piece
  652. // of code (could be a file with utf8 chars in the name)
  653. $log_error_msg = "Invalid file name for File with id={$file->id} " .
  654. "({$file->filename}). Some plugin probably did something wrong.";
  655. if ($filename === false) {
  656. common_log(LOG_ERR, $log_error_msg);
  657. } elseif ($filename === null) {
  658. // The old file name format was "{hash}.{ext}" so we didn't have a name
  659. // This extracts the extension
  660. $ret = preg_match('/^.+?\.+?(.+)$/', $file->filename, $matches);
  661. if ($ret !== 1) {
  662. common_log(LOG_ERR, $log_error_msg);
  663. return _m('Untitled attachment');
  664. }
  665. $ext = $matches[1];
  666. // There's a blacklisted extension array, which could have an alternative
  667. // extension, such as phps, to replace php. We want to turn it back
  668. // (currently defaulted to empty, but let's keep the feature)
  669. $blacklist = common_config('attachments', 'extblacklist');
  670. if (is_array($blacklist)) {
  671. foreach ($blacklist as $upload_ext => $safe_ext) {
  672. if ($ext === $safe_ext) {
  673. $ext = $upload_ext;
  674. break;
  675. }
  676. }
  677. }
  678. $filename = "untitled.{$ext}";
  679. }
  680. return $filename;
  681. }
  682. }