mediafile.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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)
  42. {
  43. $this->scoped = $scoped;
  44. $this->filename = $filename;
  45. $this->mimetype = $mimetype;
  46. $this->fileRecord = $this->storeFile();
  47. $this->fileurl = common_local_url('attachment',
  48. array('attachment' => $this->fileRecord->id));
  49. $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
  50. $this->short_fileurl = common_shorten_url($this->fileurl);
  51. $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
  52. }
  53. public function attachToNotice(Notice $notice)
  54. {
  55. File_to_post::processNew($this->fileRecord->id, $notice->id);
  56. }
  57. public function getPath()
  58. {
  59. return File::path($this->filename);
  60. }
  61. function shortUrl()
  62. {
  63. return $this->short_fileurl;
  64. }
  65. function delete()
  66. {
  67. $filepath = File::path($this->filename);
  68. @unlink($filepath);
  69. }
  70. public function getFile()
  71. {
  72. if (!$this->fileRecord instanceof File) {
  73. throw new ServerException('File record did not exist for MediaFile');
  74. }
  75. return $this->fileRecord;
  76. }
  77. protected function storeFile()
  78. {
  79. $file = new File;
  80. $file->filename = $this->filename;
  81. $file->url = File::url($this->filename);
  82. $filepath = File::path($this->filename);
  83. $file->size = filesize($filepath);
  84. $file->date = time();
  85. $file->mimetype = $this->mimetype;
  86. $file_id = $file->insert();
  87. if ($file_id===false) {
  88. common_log_db_error($file, "INSERT", __FILE__);
  89. // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
  90. throw new ClientException(_('There was a database error while saving your file. Please try again.'));
  91. }
  92. // Set file geometrical properties if available
  93. try {
  94. $image = ImageFile::fromFileObject($file);
  95. $orig = clone($file);
  96. $file->width = $image->width;
  97. $file->height = $image->height;
  98. $file->update($orig);
  99. // We have to cleanup after ImageFile, since it
  100. // may have generated a temporary file from a
  101. // video support plugin or something.
  102. // FIXME: Do this more automagically.
  103. if ($image->getPath() != $file->getPath()) {
  104. $image->unlink();
  105. }
  106. } catch (ServerException $e) {
  107. // We just couldn't make out an image from the file. This
  108. // does not have to be UnsupportedMediaException, as we can
  109. // also get ServerException from files not existing etc.
  110. }
  111. return $file;
  112. }
  113. function rememberFile($file, $short)
  114. {
  115. $this->maybeAddRedir($file->id, $short);
  116. }
  117. function maybeAddRedir($file_id, $url)
  118. {
  119. $file_redir = File_redirection::getKV('url', $url);
  120. if (!$file_redir instanceof File_redirection) {
  121. $file_redir = new File_redirection;
  122. $file_redir->url = $url;
  123. $file_redir->file_id = $file_id;
  124. $result = $file_redir->insert();
  125. if ($result===false) {
  126. common_log_db_error($file_redir, "INSERT", __FILE__);
  127. // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
  128. throw new ClientException(_('There was a database error while saving your file. Please try again.'));
  129. }
  130. }
  131. }
  132. static function fromUpload($param='media', Profile $scoped=null)
  133. {
  134. if (is_null($scoped)) {
  135. $scoped = Profile::current();
  136. }
  137. // The existence of the "error" element means PHP has processed it properly even if it was ok.
  138. if (!isset($_FILES[$param]) || !isset($_FILES[$param]['error'])) {
  139. throw new NoUploadedMediaException($param);
  140. }
  141. switch ($_FILES[$param]['error']) {
  142. case UPLOAD_ERR_OK: // success, jump out
  143. break;
  144. case UPLOAD_ERR_INI_SIZE:
  145. // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
  146. throw new ClientException(_('The uploaded file exceeds the ' .
  147. 'upload_max_filesize directive in php.ini.'));
  148. case UPLOAD_ERR_FORM_SIZE:
  149. throw new ClientException(
  150. // TRANS: Client exception.
  151. _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
  152. ' that was specified in the HTML form.'));
  153. case UPLOAD_ERR_PARTIAL:
  154. @unlink($_FILES[$param]['tmp_name']);
  155. // TRANS: Client exception.
  156. throw new ClientException(_('The uploaded file was only' .
  157. ' partially uploaded.'));
  158. case UPLOAD_ERR_NO_FILE:
  159. // No file; probably just a non-AJAX submission.
  160. throw new NoUploadedMediaException($param);
  161. case UPLOAD_ERR_NO_TMP_DIR:
  162. // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
  163. throw new ClientException(_('Missing a temporary folder.'));
  164. case UPLOAD_ERR_CANT_WRITE:
  165. // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
  166. throw new ClientException(_('Failed to write file to disk.'));
  167. case UPLOAD_ERR_EXTENSION:
  168. // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
  169. throw new ClientException(_('File upload stopped by extension.'));
  170. default:
  171. common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
  172. $_FILES[$param]['error']);
  173. // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
  174. throw new ClientException(_('System error uploading file.'));
  175. }
  176. // Throws exception if additional size does not respect quota
  177. File::respectsQuota($scoped, $_FILES[$param]['size']);
  178. $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'],
  179. $_FILES[$param]['name']);
  180. $basename = basename($_FILES[$param]['name']);
  181. $filename = File::filename($scoped, $basename, $mimetype);
  182. $filepath = File::path($filename);
  183. $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
  184. if (!$result) {
  185. // TRANS: Client exception thrown when a file upload operation fails because the file could
  186. // TRANS: not be moved from the temporary folder to the permanent file location.
  187. throw new ClientException(_('File could not be moved to destination directory.'));
  188. }
  189. return new MediaFile($scoped, $filename, $mimetype);
  190. }
  191. static function fromFilehandle($fh, Profile $scoped) {
  192. $stream = stream_get_meta_data($fh);
  193. File::respectsQuota($scoped, filesize($stream['uri']));
  194. $mimetype = self::getUploadedMimeType($stream['uri']);
  195. $filename = File::filename($scoped, "email", $mimetype);
  196. $filepath = File::path($filename);
  197. $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
  198. if (!$result) {
  199. // TRANS: Client exception thrown when a file upload operation fails because the file could
  200. // TRANS: not be moved from the temporary folder to the permanent file location.
  201. throw new ClientException(_('File could not be moved to destination directory.' .
  202. $stream['uri'] . ' ' . $filepath));
  203. }
  204. return new MediaFile($scoped, $filename, $mimetype);
  205. }
  206. /**
  207. * Attempt to identify the content type of a given file.
  208. *
  209. * @param string $filepath filesystem path as string (file must exist)
  210. * @param string $originalFilename (optional) for extension-based detection
  211. * @return string
  212. *
  213. * @fixme this seems to tie a front-end error message in, kinda confusing
  214. *
  215. * @throws ClientException if type is known, but not supported for local uploads
  216. */
  217. static function getUploadedMimeType($filepath, $originalFilename=false) {
  218. // We only accept filenames to existing files
  219. $mimelookup = new finfo(FILEINFO_MIME_TYPE);
  220. $mimetype = $mimelookup->file($filepath);
  221. // Unclear types are such that we can't really tell by the auto
  222. // detect what they are (.bin, .exe etc. are just "octet-stream")
  223. $unclearTypes = array('application/octet-stream',
  224. 'application/vnd.ms-office',
  225. 'application/zip',
  226. // TODO: for XML we could do better content-based sniffing too
  227. 'text/xml');
  228. $supported = common_config('attachments', 'supported');
  229. // If we didn't match, or it is an unclear match
  230. if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
  231. try {
  232. $type = common_supported_ext_to_mime($originalFilename);
  233. return $type;
  234. } catch (Exception $e) {
  235. // Extension not found, so $mimetype is our best guess
  236. }
  237. }
  238. // If $config['attachments']['supported'] equals boolean true, accept any mimetype
  239. if ($supported === true || array_key_exists($mimetype, $supported)) {
  240. // FIXME: Don't know if it always has a mimetype here because
  241. // finfo->file CAN return false on error: http://php.net/finfo_file
  242. // so if $supported === true, this may return something unexpected.
  243. return $mimetype;
  244. }
  245. // We can conclude that we have failed to get the MIME type
  246. $media = common_get_mime_media($mimetype);
  247. if ('application' !== $media) {
  248. // TRANS: Client exception thrown trying to upload a forbidden MIME type.
  249. // TRANS: %1$s is the file type that was denied, %2$s is the application part of
  250. // TRANS: the MIME type that was denied.
  251. $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
  252. 'Try using another %2$s format.'), $mimetype, $media);
  253. } else {
  254. // TRANS: Client exception thrown trying to upload a forbidden MIME type.
  255. // TRANS: %s is the file type that was denied.
  256. $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
  257. }
  258. throw new ClientException($hint);
  259. }
  260. }