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();
55 $this->filename = $filename;
56 $this->mimetype = $mimetype;
57 $this->fileRecord = $this->storeFile();
58 $this->thumbnailRecord = $this->storeThumbnail();
60 $this->fileurl = common_local_url('attachment',
61 array('attachment' => $this->fileRecord->id));
63 $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
64 $this->short_fileurl = common_shorten_url($this->fileurl);
65 $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
68 function attachToNotice($notice)
70 File_to_post::processNew($this->fileRecord->id, $notice->id);
71 $this->maybeAddRedir($this->fileRecord->id,
72 common_local_url('file', array('notice' => $notice->id)));
77 return $this->short_fileurl;
82 $filepath = File::path($this->filename);
86 function storeFile() {
90 $file->filename = $this->filename;
91 $file->url = File::url($this->filename);
92 $filepath = File::path($this->filename);
93 $file->size = filesize($filepath);
95 $file->mimetype = $this->mimetype;
97 $file_id = $file->insert();
100 common_log_db_error($file, "INSERT", __FILE__);
101 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
102 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
109 * Generate and store a thumbnail image for the uploaded file, if applicable.
111 * @return File_thumbnail or null
113 function storeThumbnail()
115 if (substr($this->mimetype, 0, strlen('image/')) != 'image/') {
116 // @fixme video thumbs would be nice!
120 $image = new ImageFile($this->fileRecord->id,
121 File::path($this->filename));
122 } catch (Exception $e) {
123 // Unsupported image type.
127 $outname = File::filename($this->user->getProfile(), 'thumb-' . $this->filename, $this->mimetype);
128 $outpath = File::path($outname);
130 $width = common_config('attachments', 'thumb_width');
131 $height = common_config('attachments', 'thumb_height');
133 $image->resizeTo($outpath, $width, $height);
134 File_thumbnail::saveThumbnail($this->fileRecord->id,
140 function rememberFile($file, $short)
142 $this->maybeAddRedir($file->id, $short);
145 function maybeAddRedir($file_id, $url)
147 $file_redir = File_redirection::staticGet('url', $url);
149 if (empty($file_redir)) {
151 $file_redir = new File_redirection;
152 $file_redir->url = $url;
153 $file_redir->file_id = $file_id;
155 $result = $file_redir->insert();
158 common_log_db_error($file_redir, "INSERT", __FILE__);
159 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
160 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
165 static function fromUpload($param = 'media', $user = null)
168 $user = common_current_user();
171 if (!isset($_FILES[$param]['error'])){
175 switch ($_FILES[$param]['error']) {
176 case UPLOAD_ERR_OK: // success, jump out
178 case UPLOAD_ERR_INI_SIZE:
179 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
180 throw new ClientException(_('The uploaded file exceeds the ' .
181 'upload_max_filesize directive in php.ini.'));
183 case UPLOAD_ERR_FORM_SIZE:
184 throw new ClientException(
185 // TRANS: Client exception.
186 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
187 ' that was specified in the HTML form.'));
189 case UPLOAD_ERR_PARTIAL:
190 @unlink($_FILES[$param]['tmp_name']);
191 // TRANS: Client exception.
192 throw new ClientException(_('The uploaded file was only' .
193 ' partially uploaded.'));
195 case UPLOAD_ERR_NO_FILE:
196 // No file; probably just a non-AJAX submission.
198 case UPLOAD_ERR_NO_TMP_DIR:
199 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
200 throw new ClientException(_('Missing a temporary folder.'));
202 case UPLOAD_ERR_CANT_WRITE:
203 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
204 throw new ClientException(_('Failed to write file to disk.'));
206 case UPLOAD_ERR_EXTENSION:
207 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
208 throw new ClientException(_('File upload stopped by extension.'));
211 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
212 $_FILES[$param]['error']);
213 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
214 throw new ClientException(_('System error uploading file.'));
218 if (!MediaFile::respectsQuota($user, $_FILES[$param]['size'])) {
220 // Should never actually get here
222 @unlink($_FILES[$param]['tmp_name']);
223 // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota.
224 throw new ClientException(_('File exceeds user\'s quota.'));
228 $mimetype = MediaFile::getUploadedFileType($_FILES[$param]['tmp_name'],
229 $_FILES[$param]['name']);
233 if (isset($mimetype)) {
235 $basename = basename($_FILES[$param]['name']);
236 $filename = File::filename($user->getProfile(), $basename, $mimetype);
237 $filepath = File::path($filename);
239 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
242 // TRANS: Client exception thrown when a file upload operation fails because the file could
243 // TRANS: not be moved from the temporary folder to the permanent file location.
244 throw new ClientException(_('File could not be moved to destination directory.'));
249 // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME
250 // TRANS: type of the uploaded file could not be determined.
251 throw new ClientException(_('Could not determine file\'s MIME type.'));
255 return new MediaFile($user, $filename, $mimetype);
258 static function fromFilehandle($fh, $user) {
260 $stream = stream_get_meta_data($fh);
262 if (!MediaFile::respectsQuota($user, filesize($stream['uri']))) {
264 // Should never actually get here
266 // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota.
267 throw new ClientException(_('File exceeds user\'s quota.'));
271 $mimetype = MediaFile::getUploadedFileType($fh);
275 if (isset($mimetype)) {
277 $filename = File::filename($user->getProfile(), "email", $mimetype);
279 $filepath = File::path($filename);
281 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
284 // TRANS: Client exception thrown when a file upload operation fails because the file could
285 // TRANS: not be moved from the temporary folder to the permanent file location.
286 throw new ClientException(_('File could not be moved to destination directory.' .
287 $stream['uri'] . ' ' . $filepath));
290 // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME
291 // TRANS: type of the uploaded file could not be determined.
292 throw new ClientException(_('Could not determine file\'s MIME type.'));
296 return new MediaFile($user, $filename, $mimetype);
300 * Attempt to identify the content type of a given file.
302 * @param mixed $f file handle resource, or filesystem path as string
303 * @param string $originalFilename (optional) for extension-based detection
306 * @fixme is this an internal or public method? It's called from GetFileAction
307 * @fixme this seems to tie a front-end error message in, kinda confusing
308 * @fixme this looks like it could return a PEAR_Error in some cases, if
309 * type can't be identified and $config['attachments']['supported'] is true
311 * @throws ClientException if type is known, but not supported for local uploads
313 static function getUploadedFileType($f, $originalFilename=false) {
314 require_once 'MIME/Type.php';
315 require_once 'MIME/Type/Extension.php';
317 // We have to disable auto handling of PEAR errors
318 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
319 $mte = new MIME_Type_Extension();
321 $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
322 $cmd = common_config('attachments', 'filecommand');
326 // If we couldn't get a clear type from the file extension,
327 // we'll go ahead and try checking the content. Content checks
328 // are unambiguous for most image files, but nearly useless
329 // for office document formats.
333 // assuming a filename
335 $filetype = MIME_Type::autoDetect($f);
339 // assuming a filehandle
341 $stream = stream_get_meta_data($f);
342 $filetype = MIME_Type::autoDetect($stream['uri']);
345 // The content-based sources for MIME_Type::autoDetect()
346 // are wildly unreliable for office-type documents. If we've
347 // gotten an unclear reponse back or just couldn't identify it,
348 // we'll try detecting a type from its extension...
349 $unclearTypes = array('application/octet-stream',
350 'application/vnd.ms-office',
353 if ($originalFilename && (!$filetype || in_array($filetype, $unclearTypes))) {
354 $type = $mte->getMIMEType($originalFilename);
355 if (is_string($type)) {
360 $supported = common_config('attachments', 'supported');
361 if (is_array($supported)) {
362 // Normalize extensions to mime types
363 foreach ($supported as $i => $entry) {
364 if (strpos($entry, '/') === false) {
365 common_log(LOG_INFO, "sample.$entry");
366 $supported[$i] = $mte->getMIMEType("sample.$entry");
370 if ($supported === true || in_array($filetype, $supported)) {
371 // Restore PEAR error handlers for our DB code...
372 PEAR::staticPopErrorHandling();
375 $media = MIME_Type::getMedia($filetype);
376 if ('application' !== $media) {
377 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
378 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
379 // TRANS: the MIME type that was denied.
380 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
381 'Try using another %2$s format.'), $filetype, $media);
383 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
384 // TRANS: %s is the file type that was denied.
385 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $filetype);
387 // Restore PEAR error handlers for our DB code...
388 PEAR::staticPopErrorHandling();
389 throw new ClientException($hint);
392 static function respectsQuota($user, $filesize)
395 $result = $file->isRespectsQuota($user, $filesize);
396 if ($result === true) {
399 throw new ClientException($result);