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')) {
39 protected $scoped = null;
42 var $fileRecord = null;
44 var $short_fileurl = null;
46 var $thumbnailRecord = null;
48 function __construct(Profile $scoped, $filename = null, $mimetype = null)
50 $this->scoped = $scoped;
52 $this->filename = $filename;
53 $this->mimetype = $mimetype;
54 $this->fileRecord = $this->storeFile();
56 $this->thumbnailRecord = $this->storeThumbnail();
57 } catch (UnsupportedMediaException $e) {
58 // FIXME: Add "unknown media" icon or something
59 $this->thumbnailRecord = null;
62 $this->fileurl = common_local_url('attachment',
63 array('attachment' => $this->fileRecord->id));
65 $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
66 $this->short_fileurl = common_shorten_url($this->fileurl);
67 $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
70 function attachToNotice($notice)
72 File_to_post::processNew($this->fileRecord->id, $notice->id);
73 $this->maybeAddRedir($this->fileRecord->id,
74 common_local_url('file', array('notice' => $notice->id)));
77 public function getPath()
79 return File::path($this->filename);
84 return $this->short_fileurl;
89 $filepath = File::path($this->filename);
93 function storeFile() {
97 $file->filename = $this->filename;
98 $file->url = File::url($this->filename);
99 $filepath = File::path($this->filename);
100 $file->size = filesize($filepath);
101 $file->date = time();
102 $file->mimetype = $this->mimetype;
104 $file_id = $file->insert();
107 common_log_db_error($file, "INSERT", __FILE__);
108 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
109 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
116 * Generate and store a thumbnail image for the uploaded file, if applicable.
118 * @return File_thumbnail or null
120 function storeThumbnail()
123 $media = common_get_mime_media($this->mimetype);
125 if (Event::handle('CreateFileImageThumbnail', array($this, &$imgPath, $media))) {
128 $imgPath = $this->getPath();
131 throw new UnsupportedMediaException(_('Unsupported media format.'), $this->getPath());
134 if (!file_exists($imgPath)) {
135 throw new ServerException(sprintf('Thumbnail source is not stored locally: %s', $imgPath));
139 $image = new ImageFile($this->fileRecord->id, $imgPath);
140 } catch (UnsupportedMediaException $e) {
141 // Avoid deleting the original
142 if ($image->getPath() != $this->getPath()) {
148 $outname = File::filename($this->scoped, 'thumb-' . $this->filename, $this->mimetype);
149 $outpath = File::path($outname);
151 $maxWidth = common_config('attachments', 'thumb_width');
152 $maxHeight = common_config('attachments', 'thumb_height');
153 list($width, $height) = $this->scaleToFit($image->width, $image->height, $maxWidth, $maxHeight);
155 $image->resizeTo($outpath, $width, $height);
157 // Avoid deleting the original
158 if ($image->getPath() != $this->getPath()) {
161 return File_thumbnail::saveThumbnail($this->fileRecord->id,
167 function scaleToFit($width, $height, $maxWidth, $maxHeight)
169 $aspect = $maxWidth / $maxHeight;
171 $h1 = intval($height * $maxWidth / $width);
172 if ($h1 > $maxHeight) {
173 $w2 = intval($width * $maxHeight / $height);
175 return array($w2, $h2);
177 return array($w1, $h1);
180 function rememberFile($file, $short)
182 $this->maybeAddRedir($file->id, $short);
185 function maybeAddRedir($file_id, $url)
187 $file_redir = File_redirection::getKV('url', $url);
189 if (empty($file_redir)) {
191 $file_redir = new File_redirection;
192 $file_redir->url = $url;
193 $file_redir->file_id = $file_id;
195 $result = $file_redir->insert();
198 common_log_db_error($file_redir, "INSERT", __FILE__);
199 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
200 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
205 static function fromUpload($param = 'media', Profile $scoped)
207 if (is_null($scoped)) {
208 $scoped = Profile::current();
211 if (!isset($_FILES[$param]['error'])){
215 switch ($_FILES[$param]['error']) {
216 case UPLOAD_ERR_OK: // success, jump out
218 case UPLOAD_ERR_INI_SIZE:
219 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
220 throw new ClientException(_('The uploaded file exceeds the ' .
221 'upload_max_filesize directive in php.ini.'));
222 case UPLOAD_ERR_FORM_SIZE:
223 throw new ClientException(
224 // TRANS: Client exception.
225 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
226 ' that was specified in the HTML form.'));
227 case UPLOAD_ERR_PARTIAL:
228 @unlink($_FILES[$param]['tmp_name']);
229 // TRANS: Client exception.
230 throw new ClientException(_('The uploaded file was only' .
231 ' partially uploaded.'));
232 case UPLOAD_ERR_NO_FILE:
233 // No file; probably just a non-AJAX submission.
235 case UPLOAD_ERR_NO_TMP_DIR:
236 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
237 throw new ClientException(_('Missing a temporary folder.'));
238 case UPLOAD_ERR_CANT_WRITE:
239 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
240 throw new ClientException(_('Failed to write file to disk.'));
241 case UPLOAD_ERR_EXTENSION:
242 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
243 throw new ClientException(_('File upload stopped by extension.'));
245 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
246 $_FILES[$param]['error']);
247 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
248 throw new ClientException(_('System error uploading file.'));
251 // Throws exception if additional size does not respect quota
252 File::respectsQuota($scoped, $_FILES[$param]['size']);
254 $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'],
255 $_FILES[$param]['name']);
257 $basename = basename($_FILES[$param]['name']);
258 $filename = File::filename($scoped, $basename, $mimetype);
259 $filepath = File::path($filename);
261 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
264 // TRANS: Client exception thrown when a file upload operation fails because the file could
265 // TRANS: not be moved from the temporary folder to the permanent file location.
266 throw new ClientException(_('File could not be moved to destination directory.'));
269 return new MediaFile($scoped, $filename, $mimetype);
272 static function fromFilehandle($fh, Profile $scoped) {
274 $stream = stream_get_meta_data($fh);
276 File::respectsQuota($scoped, filesize($stream['uri']));
278 $mimetype = self::getUploadedMimeType($stream['uri']);
280 $filename = File::filename($scoped, "email", $mimetype);
282 $filepath = File::path($filename);
284 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
287 // TRANS: Client exception thrown when a file upload operation fails because the file could
288 // TRANS: not be moved from the temporary folder to the permanent file location.
289 throw new ClientException(_('File could not be moved to destination directory.' .
290 $stream['uri'] . ' ' . $filepath));
293 return new MediaFile($scoped, $filename, $mimetype);
297 * Attempt to identify the content type of a given file.
299 * @param string $filepath filesystem path as string (file must exist)
300 * @param string $originalFilename (optional) for extension-based detection
303 * @fixme this seems to tie a front-end error message in, kinda confusing
305 * @throws ClientException if type is known, but not supported for local uploads
307 static function getUploadedMimeType($filepath, $originalFilename=false) {
308 // We only accept filenames to existing files
309 $mimelookup = new finfo(FILEINFO_MIME_TYPE);
310 $mimetype = $mimelookup->file($filepath);
312 // Unclear types are such that we can't really tell by the auto
313 // detect what they are (.bin, .exe etc. are just "octet-stream")
314 $unclearTypes = array('application/octet-stream',
315 'application/vnd.ms-office',
317 // TODO: for XML we could do better content-based sniffing too
320 $supported = common_config('attachments', 'supported');
322 // If we didn't match, or it is an unclear match
323 if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
325 $type = common_supported_ext_to_mime($originalFilename);
327 } catch (Exception $e) {
328 // Extension not found, so $mimetype is our best guess
332 // If $config['attachments']['supported'] equals boolean true, accept any mimetype
333 if ($supported === true || array_key_exists($mimetype, $supported)) {
334 // FIXME: Don't know if it always has a mimetype here because
335 // finfo->file CAN return false on error: http://php.net/finfo_file
336 // so if $supported === true, this may return something unexpected.
340 // We can conclude that we have failed to get the MIME type
341 $media = common_get_mime_media($mimetype);
342 if ('application' !== $media) {
343 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
344 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
345 // TRANS: the MIME type that was denied.
346 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
347 'Try using another %2$s format.'), $mimetype, $media);
349 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
350 // TRANS: %s is the file type that was denied.
351 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
353 throw new ClientException($hint);