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($maxWidth=null, $maxHeight=null, $square=true)
121 $media = common_get_mime_media($this->mimetype);
123 if (Event::handle('CreateFileImageThumbnailSource', 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 = $maxWidth ?: common_config('attachments', 'thumb_width');
150 $maxHeight = $maxHeight ?: common_config('attachments', 'thumb_height');
151 list($width, $height, $x, $y, $w2, $h2) =
152 $this->scaleToFit($image->width, $image->height,
153 $maxWidth, $maxHeight,
154 common_config('attachments', 'thumb_square'));
156 $image->resizeTo($outpath, $width, $height, $x, $y, $w2, $h2);
158 // Avoid deleting the original
159 if ($image->getPath() != $this->getPath()) {
162 return File_thumbnail::saveThumbnail($this->fileRecord->id,
168 // This will give parameters to scale up if max values are larger than original
169 function scaleToFit($width, $height, $maxWidth=null, $maxHeight=null, $square=true)
171 if ($width <= 0 || $height <= 0
172 || ($maxWidth !== null && $maxWidth <= 0)
173 || ($maxHeight !== null && $maxHeight <= 0)) {
174 throw new ServerException('Bad scaleToFit parameters for MediaFile');
175 } elseif ($maxWidth === null) {
176 // maxWidth must be a positive number
177 throw new ServerException('MediaFile::scaleToFit maxWidth is null');
178 } elseif ($square || $maxHeight === null) {
179 // if square thumb ratio or if maxHeight is null,
180 // we set maxHeight to equal maxWidth
181 $maxHeight = $maxWidth;
188 $cw = null; // crop area width
189 $ch = null; // crop area height
192 // resulting width and height
196 // minSide will determine the smallest image size
197 // and crop-values are determined from this
198 $minSide = $width > $height ? $height : $width;
199 $cx = $width / 2 - $minSide / 2;
200 $cy = $height / 2 - $minSide / 2;
206 $rh = floor($height * $maxWidth / $width);
208 if ($rh > $maxHeight) {
209 $rw = floor($width * $maxHeight / $height);
213 return array($rw, $rh, $cx, $cy, $cw, $ch);
216 function rememberFile($file, $short)
218 $this->maybeAddRedir($file->id, $short);
221 function maybeAddRedir($file_id, $url)
223 $file_redir = File_redirection::getKV('url', $url);
225 if (empty($file_redir)) {
227 $file_redir = new File_redirection;
228 $file_redir->url = $url;
229 $file_redir->file_id = $file_id;
231 $result = $file_redir->insert();
234 common_log_db_error($file_redir, "INSERT", __FILE__);
235 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
236 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
241 static function fromUpload($param = 'media', Profile $scoped)
243 if (is_null($scoped)) {
244 $scoped = Profile::current();
247 if (!isset($_FILES[$param]['error'])){
251 switch ($_FILES[$param]['error']) {
252 case UPLOAD_ERR_OK: // success, jump out
254 case UPLOAD_ERR_INI_SIZE:
255 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
256 throw new ClientException(_('The uploaded file exceeds the ' .
257 'upload_max_filesize directive in php.ini.'));
258 case UPLOAD_ERR_FORM_SIZE:
259 throw new ClientException(
260 // TRANS: Client exception.
261 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
262 ' that was specified in the HTML form.'));
263 case UPLOAD_ERR_PARTIAL:
264 @unlink($_FILES[$param]['tmp_name']);
265 // TRANS: Client exception.
266 throw new ClientException(_('The uploaded file was only' .
267 ' partially uploaded.'));
268 case UPLOAD_ERR_NO_FILE:
269 // No file; probably just a non-AJAX submission.
271 case UPLOAD_ERR_NO_TMP_DIR:
272 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
273 throw new ClientException(_('Missing a temporary folder.'));
274 case UPLOAD_ERR_CANT_WRITE:
275 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
276 throw new ClientException(_('Failed to write file to disk.'));
277 case UPLOAD_ERR_EXTENSION:
278 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
279 throw new ClientException(_('File upload stopped by extension.'));
281 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
282 $_FILES[$param]['error']);
283 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
284 throw new ClientException(_('System error uploading file.'));
287 // Throws exception if additional size does not respect quota
288 File::respectsQuota($scoped, $_FILES[$param]['size']);
290 $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'],
291 $_FILES[$param]['name']);
293 $basename = basename($_FILES[$param]['name']);
294 $filename = File::filename($scoped, $basename, $mimetype);
295 $filepath = File::path($filename);
297 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
300 // TRANS: Client exception thrown when a file upload operation fails because the file could
301 // TRANS: not be moved from the temporary folder to the permanent file location.
302 throw new ClientException(_('File could not be moved to destination directory.'));
305 return new MediaFile($scoped, $filename, $mimetype);
308 static function fromFilehandle($fh, Profile $scoped) {
310 $stream = stream_get_meta_data($fh);
312 File::respectsQuota($scoped, filesize($stream['uri']));
314 $mimetype = self::getUploadedMimeType($stream['uri']);
316 $filename = File::filename($scoped, "email", $mimetype);
318 $filepath = File::path($filename);
320 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
323 // TRANS: Client exception thrown when a file upload operation fails because the file could
324 // TRANS: not be moved from the temporary folder to the permanent file location.
325 throw new ClientException(_('File could not be moved to destination directory.' .
326 $stream['uri'] . ' ' . $filepath));
329 return new MediaFile($scoped, $filename, $mimetype);
333 * Attempt to identify the content type of a given file.
335 * @param string $filepath filesystem path as string (file must exist)
336 * @param string $originalFilename (optional) for extension-based detection
339 * @fixme this seems to tie a front-end error message in, kinda confusing
341 * @throws ClientException if type is known, but not supported for local uploads
343 static function getUploadedMimeType($filepath, $originalFilename=false) {
344 // We only accept filenames to existing files
345 $mimelookup = new finfo(FILEINFO_MIME_TYPE);
346 $mimetype = $mimelookup->file($filepath);
348 // Unclear types are such that we can't really tell by the auto
349 // detect what they are (.bin, .exe etc. are just "octet-stream")
350 $unclearTypes = array('application/octet-stream',
351 'application/vnd.ms-office',
353 // TODO: for XML we could do better content-based sniffing too
356 $supported = common_config('attachments', 'supported');
358 // If we didn't match, or it is an unclear match
359 if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
361 $type = common_supported_ext_to_mime($originalFilename);
363 } catch (Exception $e) {
364 // Extension not found, so $mimetype is our best guess
368 // If $config['attachments']['supported'] equals boolean true, accept any mimetype
369 if ($supported === true || array_key_exists($mimetype, $supported)) {
370 // FIXME: Don't know if it always has a mimetype here because
371 // finfo->file CAN return false on error: http://php.net/finfo_file
372 // so if $supported === true, this may return something unexpected.
376 // We can conclude that we have failed to get the MIME type
377 $media = common_get_mime_media($mimetype);
378 if ('application' !== $media) {
379 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
380 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
381 // TRANS: the MIME type that was denied.
382 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
383 'Try using another %2$s format.'), $mimetype, $media);
385 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
386 // TRANS: %s is the file type that was denied.
387 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $mimetype);
389 throw new ClientException($hint);