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 $maxWidth = common_config('attachments', 'thumb_width');
131 $maxHeight = common_config('attachments', 'thumb_height');
132 list($width, $height) = $this->scaleToFit($image->width, $image->height, $maxWidth, $maxHeight);
134 $image->resizeTo($outpath, $width, $height);
135 File_thumbnail::saveThumbnail($this->fileRecord->id,
141 function scaleToFit($width, $height, $maxWidth, $maxHeight)
143 $aspect = $maxWidth / $maxHeight;
145 $h1 = intval($height * $maxWidth / $width);
146 if ($h1 > $maxHeight) {
147 $w2 = intval($width * $maxHeight / $height);
149 return array($w2, $h2);
151 return array($w1, $h1);
154 function rememberFile($file, $short)
156 $this->maybeAddRedir($file->id, $short);
159 function maybeAddRedir($file_id, $url)
161 $file_redir = File_redirection::staticGet('url', $url);
163 if (empty($file_redir)) {
165 $file_redir = new File_redirection;
166 $file_redir->url = $url;
167 $file_redir->file_id = $file_id;
169 $result = $file_redir->insert();
172 common_log_db_error($file_redir, "INSERT", __FILE__);
173 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
174 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
179 static function fromUpload($param = 'media', $user = null)
182 $user = common_current_user();
185 if (!isset($_FILES[$param]['error'])){
189 switch ($_FILES[$param]['error']) {
190 case UPLOAD_ERR_OK: // success, jump out
192 case UPLOAD_ERR_INI_SIZE:
193 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
194 throw new ClientException(_('The uploaded file exceeds the ' .
195 'upload_max_filesize directive in php.ini.'));
197 case UPLOAD_ERR_FORM_SIZE:
198 throw new ClientException(
199 // TRANS: Client exception.
200 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
201 ' that was specified in the HTML form.'));
203 case UPLOAD_ERR_PARTIAL:
204 @unlink($_FILES[$param]['tmp_name']);
205 // TRANS: Client exception.
206 throw new ClientException(_('The uploaded file was only' .
207 ' partially uploaded.'));
209 case UPLOAD_ERR_NO_FILE:
210 // No file; probably just a non-AJAX submission.
212 case UPLOAD_ERR_NO_TMP_DIR:
213 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
214 throw new ClientException(_('Missing a temporary folder.'));
216 case UPLOAD_ERR_CANT_WRITE:
217 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
218 throw new ClientException(_('Failed to write file to disk.'));
220 case UPLOAD_ERR_EXTENSION:
221 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
222 throw new ClientException(_('File upload stopped by extension.'));
225 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
226 $_FILES[$param]['error']);
227 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
228 throw new ClientException(_('System error uploading file.'));
232 if (!MediaFile::respectsQuota($user, $_FILES[$param]['size'])) {
234 // Should never actually get here
236 @unlink($_FILES[$param]['tmp_name']);
237 // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota.
238 throw new ClientException(_('File exceeds user\'s quota.'));
242 $mimetype = MediaFile::getUploadedFileType($_FILES[$param]['tmp_name'],
243 $_FILES[$param]['name']);
247 if (isset($mimetype)) {
249 $basename = basename($_FILES[$param]['name']);
250 $filename = File::filename($user->getProfile(), $basename, $mimetype);
251 $filepath = File::path($filename);
253 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
256 // TRANS: Client exception thrown when a file upload operation fails because the file could
257 // TRANS: not be moved from the temporary folder to the permanent file location.
258 throw new ClientException(_('File could not be moved to destination directory.'));
263 // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME
264 // TRANS: type of the uploaded file could not be determined.
265 throw new ClientException(_('Could not determine file\'s MIME type.'));
269 return new MediaFile($user, $filename, $mimetype);
272 static function fromFilehandle($fh, $user) {
274 $stream = stream_get_meta_data($fh);
276 if (!MediaFile::respectsQuota($user, filesize($stream['uri']))) {
278 // Should never actually get here
280 // TRANS: Client exception thrown when a file upload operation would cause a user to exceed a set quota.
281 throw new ClientException(_('File exceeds user\'s quota.'));
285 $mimetype = MediaFile::getUploadedFileType($fh);
289 if (isset($mimetype)) {
291 $filename = File::filename($user->getProfile(), "email", $mimetype);
293 $filepath = File::path($filename);
295 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
298 // TRANS: Client exception thrown when a file upload operation fails because the file could
299 // TRANS: not be moved from the temporary folder to the permanent file location.
300 throw new ClientException(_('File could not be moved to destination directory.' .
301 $stream['uri'] . ' ' . $filepath));
304 // TRANS: Client exception thrown when a file upload operation has been stopped because the MIME
305 // TRANS: type of the uploaded file could not be determined.
306 throw new ClientException(_('Could not determine file\'s MIME type.'));
310 return new MediaFile($user, $filename, $mimetype);
314 * Attempt to identify the content type of a given file.
316 * @param mixed $f file handle resource, or filesystem path as string
317 * @param string $originalFilename (optional) for extension-based detection
320 * @fixme is this an internal or public method? It's called from GetFileAction
321 * @fixme this seems to tie a front-end error message in, kinda confusing
322 * @fixme this looks like it could return a PEAR_Error in some cases, if
323 * type can't be identified and $config['attachments']['supported'] is true
325 * @throws ClientException if type is known, but not supported for local uploads
327 static function getUploadedFileType($f, $originalFilename=false) {
328 require_once 'MIME/Type.php';
329 require_once 'MIME/Type/Extension.php';
331 // We have to disable auto handling of PEAR errors
332 PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
333 $mte = new MIME_Type_Extension();
335 $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
336 $cmd = common_config('attachments', 'filecommand');
340 // If we couldn't get a clear type from the file extension,
341 // we'll go ahead and try checking the content. Content checks
342 // are unambiguous for most image files, but nearly useless
343 // for office document formats.
347 // assuming a filename
349 $filetype = MIME_Type::autoDetect($f);
353 // assuming a filehandle
355 $stream = stream_get_meta_data($f);
356 $filetype = MIME_Type::autoDetect($stream['uri']);
359 // The content-based sources for MIME_Type::autoDetect()
360 // are wildly unreliable for office-type documents. If we've
361 // gotten an unclear reponse back or just couldn't identify it,
362 // we'll try detecting a type from its extension...
363 $unclearTypes = array('application/octet-stream',
364 'application/vnd.ms-office',
366 // TODO: for XML we could do better content-based sniffing too
369 if ($originalFilename && (!$filetype || in_array($filetype, $unclearTypes))) {
370 $type = $mte->getMIMEType($originalFilename);
371 if (is_string($type)) {
376 $supported = common_config('attachments', 'supported');
377 if (is_array($supported)) {
378 // Normalize extensions to mime types
379 foreach ($supported as $i => $entry) {
380 if (strpos($entry, '/') === false) {
381 common_log(LOG_INFO, "sample.$entry");
382 $supported[$i] = $mte->getMIMEType("sample.$entry");
386 if ($supported === true || in_array($filetype, $supported)) {
387 // Restore PEAR error handlers for our DB code...
388 PEAR::staticPopErrorHandling();
391 $media = MIME_Type::getMedia($filetype);
392 if ('application' !== $media) {
393 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
394 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
395 // TRANS: the MIME type that was denied.
396 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
397 'Try using another %2$s format.'), $filetype, $media);
399 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
400 // TRANS: %s is the file type that was denied.
401 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $filetype);
403 // Restore PEAR error handlers for our DB code...
404 PEAR::staticPopErrorHandling();
405 throw new ClientException($hint);
408 static function respectsQuota($user, $filesize)
411 $result = $file->isRespectsQuota($user, $filesize);
412 if ($result === true) {
415 throw new ClientException($result);