3 * StatusNet, the distributed open-source microblogging tool
5 * Abstraction for media files in general
7 * TODO: combine with ImageFile?
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.
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.
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/>.
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/
33 if (!defined('STATUSNET') && !defined('LACONICA')) {
41 var $fileRecord = null;
44 var $short_fileurl = null;
47 function __construct($user = null, $filename = null, $mimetype = null)
50 $this->user = common_current_user();
53 $this->filename = $filename;
54 $this->mimetype = $mimetype;
55 $this->fileRecord = $this->storeFile();
57 $this->fileurl = common_local_url('attachment',
58 array('attachment' => $this->fileRecord->id));
60 $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
61 $this->short_fileurl = common_shorten_url($this->fileurl);
62 $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
65 function attachToNotice($notice)
67 File_to_post::processNew($this->fileRecord->id, $notice->id);
68 $this->maybeAddRedir($this->fileRecord->id,
69 common_local_url('file', array('notice' => $notice->id)));
74 return $this->short_fileurl;
79 $filepath = File::path($this->filename);
83 function storeFile() {
87 $file->filename = $this->filename;
88 $file->url = File::url($this->filename);
89 $filepath = File::path($this->filename);
90 $file->size = filesize($filepath);
92 $file->mimetype = $this->mimetype;
94 $file_id = $file->insert();
97 common_log_db_error($file, "INSERT", __FILE__);
98 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
99 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
105 function rememberFile($file, $short)
107 $this->maybeAddRedir($file->id, $short);
110 function maybeAddRedir($file_id, $url)
112 $file_redir = File_redirection::staticGet('url', $url);
114 if (empty($file_redir)) {
116 $file_redir = new File_redirection;
117 $file_redir->url = $url;
118 $file_redir->file_id = $file_id;
120 $result = $file_redir->insert();
123 common_log_db_error($file_redir, "INSERT", __FILE__);
124 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
125 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
130 static function fromUpload($param = 'media', $user = null)
133 $user = common_current_user();
136 if (!isset($_FILES[$param]['error'])){
140 switch ($_FILES[$param]['error']) {
141 case UPLOAD_ERR_OK: // success, jump out
143 case UPLOAD_ERR_INI_SIZE:
144 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
145 throw new ClientException(_('The uploaded file exceeds the ' .
146 '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.'));
154 case UPLOAD_ERR_PARTIAL:
155 @unlink($_FILES[$param]['tmp_name']);
156 // TRANS: Client exception.
157 throw new ClientException(_('The uploaded file was only' .
158 ' partially uploaded.'));
160 case UPLOAD_ERR_NO_FILE:
161 // No file; probably just a non-AJAX submission.
163 case UPLOAD_ERR_NO_TMP_DIR:
164 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
165 throw new ClientException(_('Missing a temporary folder.'));
167 case UPLOAD_ERR_CANT_WRITE:
168 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
169 throw new ClientException(_('Failed to write file to disk.'));
171 case UPLOAD_ERR_EXTENSION:
172 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
173 throw new ClientException(_('File upload stopped by extension.'));
176 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
177 $_FILES[$param]['error']);
178 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
179 throw new ClientException(_('System error uploading file.'));
183 if (!MediaFile::respectsQuota($user, $_FILES[$param]['size'])) {
185 // Should never actually get here
187 @unlink($_FILES[$param]['tmp_name']);
188 // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota.
189 throw new ClientException(_('File exceeds user\'s quota.'));
193 $mimetype = MediaFile::getUploadedFileType($_FILES[$param]['tmp_name'],
194 $_FILES[$param]['name']);
198 if (isset($mimetype)) {
200 $basename = basename($_FILES[$param]['name']);
201 $filename = File::filename($user->getProfile(), $basename, $mimetype);
202 $filepath = File::path($filename);
204 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
207 // TRANS: Client exception thrown when a file upload operation fails because the file could
208 // TRANS: not be moved from the temporary folder to the permanent file location.
209 throw new ClientException(_('File could not be moved to destination directory.'));
214 // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME
215 // TRANS: type of the uploaded file could not be determined.
216 throw new ClientException(_('Could not determine file\'s MIME type.'));
220 return new MediaFile($user, $filename, $mimetype);
223 static function fromFilehandle($fh, $user) {
225 $stream = stream_get_meta_data($fh);
227 if (!MediaFile::respectsQuota($user, filesize($stream['uri']))) {
229 // Should never actually get here
231 // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota.
232 throw new ClientException(_('File exceeds user\'s quota.'));
236 $mimetype = MediaFile::getUploadedFileType($fh);
240 if (isset($mimetype)) {
242 $filename = File::filename($user->getProfile(), "email", $mimetype);
244 $filepath = File::path($filename);
246 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
249 // TRANS: Client exception thrown when a file upload operation fails because the file could
250 // TRANS: not be moved from the temporary folder to the permanent file location.
251 throw new ClientException(_('File could not be moved to destination directory.' .
252 $stream['uri'] . ' ' . $filepath));
255 // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME
256 // TRANS: type of the uploaded file could not be determined.
257 throw new ClientException(_('Could not determine file\'s MIME type.'));
261 return new MediaFile($user, $filename, $mimetype);
265 * Attempt to identify the content type of a given file.
267 * @param mixed $f file handle resource, or filesystem path as string
268 * @param string $originalFilename (optional) for extension-based detection
271 * @fixme is this an internal or public method? It's called from GetFileAction
272 * @fixme this seems to tie a front-end error message in, kinda confusing
273 * @fixme this looks like it could return a PEAR_Error in some cases, if
274 * type can't be identified and $config['attachments']['supported'] is true
276 * @throws ClientException if type is known, but not supported for local uploads
278 static function getUploadedFileType($f, $originalFilename=false) {
279 require_once 'MIME/Type.php';
280 require_once 'MIME/Type/Extension.php';
281 $mte = new MIME_Type_Extension();
283 $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
284 $cmd = common_config('attachments', 'filecommand');
288 // If we couldn't get a clear type from the file extension,
289 // we'll go ahead and try checking the content. Content checks
290 // are unambiguous for most image files, but nearly useless
291 // for office document formats.
295 // assuming a filename
297 $filetype = MIME_Type::autoDetect($f);
301 // assuming a filehandle
303 $stream = stream_get_meta_data($f);
304 $filetype = MIME_Type::autoDetect($stream['uri']);
307 // The content-based sources for MIME_Type::autoDetect()
308 // are wildly unreliable for office-type documents. If we've
309 // gotten an unclear reponse back or just couldn't identify it,
310 // we'll try detecting a type from its extension...
311 $unclearTypes = array('application/octet-stream',
312 'application/vnd.ms-office',
315 if ($originalFilename && (!$filetype || in_array($filetype, $unclearTypes))) {
316 $type = $mte->getMIMEType($originalFilename);
317 if (is_string($type)) {
322 $supported = common_config('attachments', 'supported');
323 if (is_array($supported)) {
324 // Normalize extensions to mime types
325 foreach ($supported as $i => $entry) {
326 if (strpos($entry, '/') === false) {
327 common_log(LOG_INFO, "sample.$entry");
328 $supported[$i] = $mte->getMIMEType("sample.$entry");
332 if ($supported === true || in_array($filetype, $supported)) {
335 $media = MIME_Type::getMedia($filetype);
336 if ('application' !== $media) {
337 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
338 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
339 // TRANS: the MIME type that was denied.
340 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
341 'Try using another %2$s format.'), $filetype, $media);
343 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
344 // TRANS: %s is the file type that was denied.
345 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $filetype);
347 throw new ClientException($hint);
350 static function respectsQuota($user, $filesize)
353 $result = $file->isRespectsQuota($user, $filesize);
354 if ($result === true) {
357 throw new ClientException($result);