mediafile.php 15 KB

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