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('GNUSOCIAL')) { exit(1); }
37 protected $scoped = null;
40 var $fileRecord = null;
42 var $short_fileurl = null;
44 var $thumbnailRecord = null;
46 function __construct(Profile $scoped, $filename = null, $mimetype = null)
48 $this->scoped = $scoped;
50 $this->filename = $filename;
51 $this->mimetype = $mimetype;
52 $this->fileRecord = $this->storeFile();
54 $this->thumbnailRecord = $this->storeThumbnail();
55 } catch (UnsupportedMediaException $e) {
56 // FIXME: Add "unknown media" icon or something
57 $this->thumbnailRecord = null;
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 public function attachToNotice(Notice $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)));
75 public function getPath()
77 return File::path($this->filename);
82 return $this->short_fileurl;
87 $filepath = File::path($this->filename);
91 function storeFile() {
95 $file->filename = $this->filename;
96 $file->url = File::url($this->filename);
97 $filepath = File::path($this->filename);
98 $file->size = filesize($filepath);
100 $file->mimetype = $this->mimetype;
102 $file_id = $file->insert();
105 common_log_db_error($file, "INSERT", __FILE__);
106 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
107 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
114 * Generate and store a thumbnail image for the uploaded file, if applicable.
116 * @return File_thumbnail or null
118 function storeThumbnail()
121 $media = common_get_mime_media($this->mimetype);
123 if (Event::handle('CreateFileImageThumbnail', array($this, &$imgPath, $media))) {
126 $imgPath = $this->getPath();
129 throw new UnsupportedMediaException(_('Unsupported media format.'), $this->getPath());
132 if (!file_exists($imgPath)) {
133 throw new ServerException(sprintf('Thumbnail source is not stored locally: %s', $imgPath));
137 $image = new ImageFile($this->fileRecord->id, $imgPath);
138 } catch (UnsupportedMediaException $e) {
139 // Avoid deleting the original
140 if ($image->getPath() != $this->getPath()) {
146 $outname = File::filename($this->scoped, 'thumb-' . $this->filename, $this->mimetype);
147 $outpath = File::path($outname);
149 $maxWidth = common_config('attachments', 'thumb_width');
150 $maxHeight = common_config('attachments', 'thumb_height');
151 list($width, $height) = $this->scaleToFit($image->width, $image->height, $maxWidth, $maxHeight);
153 $image->resizeTo($outpath, $width, $height);
155 // Avoid deleting the original
156 if ($image->getPath() != $this->getPath()) {
159 return File_thumbnail::saveThumbnail($this->fileRecord->id,
165 function scaleToFit($width, $height, $maxWidth, $maxHeight)
167 $aspect = $maxWidth / $maxHeight;
169 $h1 = intval($height * $maxWidth / $width);
170 if ($h1 > $maxHeight) {
171 $w2 = intval($width * $maxHeight / $height);
173 return array($w2, $h2);
175 return array($w1, $h1);
178 function rememberFile($file, $short)
180 $this->maybeAddRedir($file->id, $short);
183 function maybeAddRedir($file_id, $url)
185 $file_redir = File_redirection::getKV('url', $url);
187 if (empty($file_redir)) {
189 $file_redir = new File_redirection;
190 $file_redir->url = $url;
191 $file_redir->file_id = $file_id;
193 $result = $file_redir->insert();
196 common_log_db_error($file_redir, "INSERT", __FILE__);
197 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
198 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
203 static function fromUpload($param = 'media', Profile $scoped)
205 if (is_null($scoped)) {
206 $scoped = Profile::current();
209 if (!isset($_FILES[$param]['error'])){
213 switch ($_FILES[$param]['error']) {
214 case UPLOAD_ERR_OK: // success, jump out
216 case UPLOAD_ERR_INI_SIZE:
217 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
218 throw new ClientException(_('The uploaded file exceeds the ' .
219 'upload_max_filesize directive in php.ini.'));
220 case UPLOAD_ERR_FORM_SIZE:
221 throw new ClientException(
222 // TRANS: Client exception.
223 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
224 ' that was specified in the HTML form.'));
225 case UPLOAD_ERR_PARTIAL:
226 @unlink($_FILES[$param]['tmp_name']);
227 // TRANS: Client exception.
228 throw new ClientException(_('The uploaded file was only' .
229 ' partially uploaded.'));
230 case UPLOAD_ERR_NO_FILE:
231 // No file; probably just a non-AJAX submission.
233 case UPLOAD_ERR_NO_TMP_DIR:
234 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
235 throw new ClientException(_('Missing a temporary folder.'));
236 case UPLOAD_ERR_CANT_WRITE:
237 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
238 throw new ClientException(_('Failed to write file to disk.'));
239 case UPLOAD_ERR_EXTENSION:
240 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
241 throw new ClientException(_('File upload stopped by extension.'));
243 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
244 $_FILES[$param]['error']);
245 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
246 throw new ClientException(_('System error uploading file.'));
249 // Throws exception if additional size does not respect quota
250 File::respectsQuota($scoped, $_FILES[$param]['size']);
252 $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'],
253 $_FILES[$param]['name']);
255 $basename = basename($_FILES[$param]['name']);
256 $filename = File::filename($scoped, $basename, $mimetype);
257 $filepath = File::path($filename);
259 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
262 // TRANS: Client exception thrown when a file upload operation fails because the file could
263 // TRANS: not be moved from the temporary folder to the permanent file location.
264 throw new ClientException(_('File could not be moved to destination directory.'));
267 return new MediaFile($scoped, $filename, $mimetype);
270 static function fromFilehandle($fh, Profile $scoped) {
272 $stream = stream_get_meta_data($fh);
274 File::respectsQuota($scoped, filesize($stream['uri']));
276 $mimetype = self::getUploadedMimeType($stream['uri']);
278 $filename = File::filename($scoped, "email", $mimetype);
280 $filepath = File::path($filename);
282 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
285 // TRANS: Client exception thrown when a file upload operation fails because the file could
286 // TRANS: not be moved from the temporary folder to the permanent file location.
287 throw new ClientException(_('File could not be moved to destination directory.' .
288 $stream['uri'] . ' ' . $filepath));
291 return new MediaFile($scoped, $filename, $mimetype);
295 * Attempt to identify the content type of a given file.
297 * @param string $filepath filesystem path as string (file must exist)
298 * @param string $originalFilename (optional) for extension-based detection
301 * @fixme this seems to tie a front-end error message in, kinda confusing
303 * @throws ClientException if type is known, but not supported for local uploads
305 static function getUploadedMimeType($filepath, $originalFilename=false) {
306 // We only accept filenames to existing files
307 $mimelookup = new finfo(FILEINFO_MIME_TYPE);
308 $mimetype = $mimelookup->file($filepath);
310 // Unclear types are such that we can't really tell by the auto
311 // detect what they are (.bin, .exe etc. are just "octet-stream")
312 $unclearTypes = array('application/octet-stream',
313 'application/vnd.ms-office',
315 // TODO: for XML we could do better content-based sniffing too
318 $supported = common_config('attachments', 'supported');
320 // If we didn't match, or it is an unclear match
321 if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
323 $type = common_supported_ext_to_mime($originalFilename);
325 } catch (Exception $e) {
326 // Extension not found, so $mimetype is our best guess
330 // If $config['attachments']['supported'] equals boolean true, accept any mimetype
331 if ($supported === true || array_key_exists($mimetype, $supported)) {
332 // FIXME: Don't know if it always has a mimetype here because
333 // finfo->file CAN return false on error: http://php.net/finfo_file
334 // so if $supported === true, this may return something unexpected.
338 // We can conclude that we have failed to get the MIME type
339 $media = common_get_mime_media($mimetype);
340 if ('application' !== $media) {
341 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
342 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
343 // TRANS: the MIME type that was denied.
344 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
345 'Try using another %2$s format.'), $mimetype, $media);
347 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
348 // TRANS: %s is the file type that was denied.
349 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
351 throw new ClientException($hint);