mediafile.php 15 KB

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