mediafile.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * Abstraction for media files in general
  6. *
  7. * TODO: combine with ImageFile?
  8. *
  9. * PHP version 5
  10. *
  11. * LICENCE: This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License as published by
  13. * the Free Software Foundation, either version 3 of the License, or
  14. * (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. *
  24. * @category Media
  25. * @package StatusNet
  26. * @author Robin Millette <robin@millette.info>
  27. * @author Zach Copley <zach@status.net>
  28. * @copyright 2008-2009 StatusNet, Inc.
  29. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  30. * @link http://status.net/
  31. */
  32. if (!defined('GNUSOCIAL')) { exit(1); }
  33. class MediaFile
  34. {
  35. var $filename = null;
  36. var $fileRecord = null;
  37. var $fileurl = null;
  38. var $short_fileurl = null;
  39. var $mimetype = null;
  40. function __construct($filename = null, $mimetype = null, $filehash = null)
  41. {
  42. $this->filename = $filename;
  43. $this->mimetype = $mimetype;
  44. $this->filehash = $filehash;
  45. $this->fileRecord = $this->storeFile();
  46. $this->fileurl = common_local_url('attachment',
  47. array('attachment' => $this->fileRecord->id));
  48. $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
  49. $this->short_fileurl = common_shorten_url($this->fileurl);
  50. $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
  51. }
  52. public function attachToNotice(Notice $notice)
  53. {
  54. File_to_post::processNew($this->fileRecord, $notice);
  55. }
  56. public function getPath()
  57. {
  58. return File::path($this->filename);
  59. }
  60. function shortUrl()
  61. {
  62. return $this->short_fileurl;
  63. }
  64. function getEnclosure()
  65. {
  66. return $this->getFile()->getEnclosure();
  67. }
  68. function delete()
  69. {
  70. $filepath = File::path($this->filename);
  71. @unlink($filepath);
  72. }
  73. public function getFile()
  74. {
  75. if (!$this->fileRecord instanceof File) {
  76. throw new ServerException('File record did not exist for MediaFile');
  77. }
  78. return $this->fileRecord;
  79. }
  80. protected function storeFile()
  81. {
  82. $filepath = File::path($this->filename);
  83. if (!empty($this->filename) && $this->filehash === null) {
  84. // Calculate if we have an older upload method somewhere (Qvitter) that
  85. // doesn't do this before calling new MediaFile on its local files...
  86. $this->filehash = hash_file(File::FILEHASH_ALG, $filepath);
  87. if ($this->filehash === false) {
  88. throw new ServerException('Could not read file for hashing');
  89. }
  90. }
  91. try {
  92. $file = File::getByHash($this->filehash);
  93. // We're done here. Yes. Already. We assume sha256 won't collide on us anytime soon.
  94. return $file;
  95. } catch (NoResultException $e) {
  96. // Well, let's just continue below.
  97. }
  98. $fileurl = File::url($this->filename);
  99. $file = new File;
  100. $file->filename = $this->filename;
  101. $file->urlhash = File::hashurl($fileurl);
  102. $file->url = $fileurl;
  103. $file->filehash = $this->filehash;
  104. $file->size = filesize($filepath);
  105. if ($file->size === false) {
  106. throw new ServerException('Could not read file to get its size');
  107. }
  108. $file->date = time();
  109. $file->mimetype = $this->mimetype;
  110. $file_id = $file->insert();
  111. if ($file_id===false) {
  112. common_log_db_error($file, "INSERT", __FILE__);
  113. // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
  114. throw new ClientException(_('There was a database error while saving your file. Please try again.'));
  115. }
  116. // Set file geometrical properties if available
  117. try {
  118. $image = ImageFile::fromFileObject($file);
  119. $orig = clone($file);
  120. $file->width = $image->width;
  121. $file->height = $image->height;
  122. $file->update($orig);
  123. // We have to cleanup after ImageFile, since it
  124. // may have generated a temporary file from a
  125. // video support plugin or something.
  126. // FIXME: Do this more automagically.
  127. if ($image->getPath() != $file->getPath()) {
  128. $image->unlink();
  129. }
  130. } catch (ServerException $e) {
  131. // We just couldn't make out an image from the file. This
  132. // does not have to be UnsupportedMediaException, as we can
  133. // also get ServerException from files not existing etc.
  134. }
  135. return $file;
  136. }
  137. function rememberFile($file, $short)
  138. {
  139. $this->maybeAddRedir($file->id, $short);
  140. }
  141. function maybeAddRedir($file_id, $url)
  142. {
  143. try {
  144. $file_redir = File_redirection::getByUrl($url);
  145. } catch (NoResultException $e) {
  146. $file_redir = new File_redirection;
  147. $file_redir->urlhash = File::hashurl($url);
  148. $file_redir->url = $url;
  149. $file_redir->file_id = $file_id;
  150. $result = $file_redir->insert();
  151. if ($result===false) {
  152. common_log_db_error($file_redir, "INSERT", __FILE__);
  153. // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
  154. throw new ClientException(_('There was a database error while saving your file. Please try again.'));
  155. }
  156. }
  157. }
  158. static function fromUpload($param='media', Profile $scoped=null)
  159. {
  160. // The existence of the "error" element means PHP has processed it properly even if it was ok.
  161. if (!isset($_FILES[$param]) || !isset($_FILES[$param]['error'])) {
  162. throw new NoUploadedMediaException($param);
  163. }
  164. switch ($_FILES[$param]['error']) {
  165. case UPLOAD_ERR_OK: // success, jump out
  166. break;
  167. case UPLOAD_ERR_INI_SIZE:
  168. // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
  169. throw new ClientException(_('The uploaded file exceeds the ' .
  170. 'upload_max_filesize directive in php.ini.'));
  171. case UPLOAD_ERR_FORM_SIZE:
  172. throw new ClientException(
  173. // TRANS: Client exception.
  174. _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
  175. ' that was specified in the HTML form.'));
  176. case UPLOAD_ERR_PARTIAL:
  177. @unlink($_FILES[$param]['tmp_name']);
  178. // TRANS: Client exception.
  179. throw new ClientException(_('The uploaded file was only' .
  180. ' partially uploaded.'));
  181. case UPLOAD_ERR_NO_FILE:
  182. // No file; probably just a non-AJAX submission.
  183. throw new NoUploadedMediaException($param);
  184. case UPLOAD_ERR_NO_TMP_DIR:
  185. // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
  186. throw new ClientException(_('Missing a temporary folder.'));
  187. case UPLOAD_ERR_CANT_WRITE:
  188. // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
  189. throw new ClientException(_('Failed to write file to disk.'));
  190. case UPLOAD_ERR_EXTENSION:
  191. // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
  192. throw new ClientException(_('File upload stopped by extension.'));
  193. default:
  194. common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
  195. $_FILES[$param]['error']);
  196. // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
  197. throw new ClientException(_('System error uploading file.'));
  198. }
  199. // TODO: Make documentation clearer that this won't work for files >2GiB because
  200. // PHP is stupid in its 32bit head. But noone accepts 2GiB files with PHP
  201. // anyway... I hope.
  202. $filehash = hash_file(File::FILEHASH_ALG, $_FILES[$param]['tmp_name']);
  203. try {
  204. $file = File::getByHash($filehash);
  205. // If no exception is thrown the file exists locally, so we'll use that and just add redirections.
  206. // but if the _actual_ locally stored file doesn't exist, getPath will throw FileNotFoundException
  207. $filename = basename($file->getPath());
  208. $mimetype = $file->mimetype;
  209. } catch (FileNotFoundException $e) {
  210. // The file does not exist in our local filesystem, so store this upload.
  211. if (!move_uploaded_file($_FILES[$param]['tmp_name'], $e->path)) {
  212. // TRANS: Client exception thrown when a file upload operation fails because the file could
  213. // TRANS: not be moved from the temporary folder to the permanent file location.
  214. throw new ClientException(_('File could not be moved to destination directory.'));
  215. }
  216. $filename = basename($file->getPath());
  217. $mimetype = $file->mimetype;
  218. } catch (NoResultException $e) {
  219. // We have to save the upload as a new local file. This is the normal course of action.
  220. if ($scoped instanceof Profile) {
  221. // Throws exception if additional size does not respect quota
  222. // This test is only needed, of course, if we're uploading something new.
  223. File::respectsQuota($scoped, $_FILES[$param]['size']);
  224. }
  225. $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'], $_FILES[$param]['name']);
  226. $basename = basename($_FILES[$param]['name']);
  227. $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype, $basename);
  228. $filepath = File::path($filename);
  229. $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
  230. if (!$result) {
  231. // TRANS: Client exception thrown when a file upload operation fails because the file could
  232. // TRANS: not be moved from the temporary folder to the permanent file location.
  233. throw new ClientException(_('File could not be moved to destination directory.'));
  234. }
  235. }
  236. return new MediaFile($filename, $mimetype, $filehash);
  237. }
  238. static function fromFilehandle($fh, Profile $scoped=null) {
  239. $stream = stream_get_meta_data($fh);
  240. // So far we're only handling filehandles originating from tmpfile(),
  241. // so we can always do hash_file on $stream['uri'] as far as I can tell!
  242. $filehash = hash_file(File::FILEHASH_ALG, $stream['uri']);
  243. try {
  244. $file = File::getByHash($filehash);
  245. // Already have it, so let's reuse the locally stored File
  246. // by using getPath we also check whether the file exists
  247. // and throw a FileNotFoundException with the path if it doesn't.
  248. $filename = basename($file->getPath());
  249. $mimetype = $file->mimetype;
  250. } catch (FileNotFoundException $e) {
  251. // This happens if the file we have uploaded has disappeared
  252. // from the local filesystem for some reason. Since we got the
  253. // File object from a sha256 check in fromFilehandle, it's safe
  254. // to just copy the uploaded data to disk!
  255. fseek($fh, 0); // just to be sure, go to the beginning
  256. // dump the contents of our filehandle to the path from our exception
  257. // and report error if it failed.
  258. if (false === file_put_contents($e->path, fread($fh, filesize($stream['uri'])))) {
  259. // TRANS: Client exception thrown when a file upload operation fails because the file could
  260. // TRANS: not be moved from the temporary folder to the permanent file location.
  261. throw new ClientException(_('File could not be moved to destination directory.'));
  262. }
  263. if (!chmod($e->path, 0664)) {
  264. common_log(LOG_ERR, 'Could not chmod uploaded file: '._ve($e->path));
  265. }
  266. $filename = basename($file->getPath());
  267. $mimetype = $file->mimetype;
  268. } catch (NoResultException $e) {
  269. if ($scoped instanceof Profile) {
  270. File::respectsQuota($scoped, filesize($stream['uri']));
  271. }
  272. $mimetype = self::getUploadedMimeType($stream['uri']);
  273. $filename = strtolower($filehash) . '.' . File::guessMimeExtension($mimetype);
  274. $filepath = File::path($filename);
  275. $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
  276. if (!$result) {
  277. common_log(LOG_ERR, 'File could not be moved (or chmodded) from '._ve($stream['uri']) . ' to ' . _ve($filepath));
  278. // TRANS: Client exception thrown when a file upload operation fails because the file could
  279. // TRANS: not be moved from the temporary folder to the permanent file location.
  280. throw new ClientException(_('File could not be moved to destination directory.' ));
  281. }
  282. }
  283. return new MediaFile($filename, $mimetype, $filehash);
  284. }
  285. /**
  286. * Attempt to identify the content type of a given file.
  287. *
  288. * @param string $filepath filesystem path as string (file must exist)
  289. * @param string $originalFilename (optional) for extension-based detection
  290. * @return string
  291. *
  292. * @fixme this seems to tie a front-end error message in, kinda confusing
  293. *
  294. * @throws ClientException if type is known, but not supported for local uploads
  295. */
  296. static function getUploadedMimeType($filepath, $originalFilename=false) {
  297. // We only accept filenames to existing files
  298. $mimelookup = new finfo(FILEINFO_MIME_TYPE);
  299. $mimetype = $mimelookup->file($filepath);
  300. // Unclear types are such that we can't really tell by the auto
  301. // detect what they are (.bin, .exe etc. are just "octet-stream")
  302. $unclearTypes = array('application/octet-stream',
  303. 'application/vnd.ms-office',
  304. 'application/zip',
  305. 'text/plain',
  306. 'text/html', // Ironically, Wikimedia Commons' SVG_logo.svg is identified as text/html
  307. // TODO: for XML we could do better content-based sniffing too
  308. 'text/xml');
  309. $supported = common_config('attachments', 'supported');
  310. // If we didn't match, or it is an unclear match
  311. if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
  312. try {
  313. $type = common_supported_filename_to_mime($originalFilename);
  314. return $type;
  315. } catch (UnknownExtensionMimeException $e) {
  316. // FIXME: I think we should keep the file extension here (supported should be === true here)
  317. } catch (Exception $e) {
  318. // Extension parsed but no connected mimetype, so $mimetype is our best guess
  319. }
  320. }
  321. // If $config['attachments']['supported'] equals boolean true, accept any mimetype
  322. if ($supported === true || array_key_exists($mimetype, $supported)) {
  323. // FIXME: Don't know if it always has a mimetype here because
  324. // finfo->file CAN return false on error: http://php.net/finfo_file
  325. // so if $supported === true, this may return something unexpected.
  326. return $mimetype;
  327. }
  328. // We can conclude that we have failed to get the MIME type
  329. $media = common_get_mime_media($mimetype);
  330. if ('application' !== $media) {
  331. // TRANS: Client exception thrown trying to upload a forbidden MIME type.
  332. // TRANS: %1$s is the file type that was denied, %2$s is the application part of
  333. // TRANS: the MIME type that was denied.
  334. $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
  335. 'Try using another %2$s format.'), $mimetype, $media);
  336. } else {
  337. // TRANS: Client exception thrown trying to upload a forbidden MIME type.
  338. // TRANS: %s is the file type that was denied.
  339. $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
  340. }
  341. throw new ClientException($hint);
  342. }
  343. }