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;
47 function __construct(Profile $scoped, $filename = null, $mimetype = null)
49 $this->scoped = $scoped;
51 $this->filename = $filename;
52 $this->mimetype = $mimetype;
53 $this->fileRecord = $this->storeFile();
54 $this->thumbnailRecord = $this->storeThumbnail();
56 $this->fileurl = common_local_url('attachment',
57 array('attachment' => $this->fileRecord->id));
59 $this->maybeAddRedir($this->fileRecord->id, $this->fileurl);
60 $this->short_fileurl = common_shorten_url($this->fileurl);
61 $this->maybeAddRedir($this->fileRecord->id, $this->short_fileurl);
64 function attachToNotice($notice)
66 File_to_post::processNew($this->fileRecord->id, $notice->id);
67 $this->maybeAddRedir($this->fileRecord->id,
68 common_local_url('file', array('notice' => $notice->id)));
73 return $this->short_fileurl;
78 $filepath = File::path($this->filename);
82 function storeFile() {
86 $file->filename = $this->filename;
87 $file->url = File::url($this->filename);
88 $filepath = File::path($this->filename);
89 $file->size = filesize($filepath);
91 $file->mimetype = $this->mimetype;
93 $file_id = $file->insert();
96 common_log_db_error($file, "INSERT", __FILE__);
97 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
98 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
105 * Generate and store a thumbnail image for the uploaded file, if applicable.
107 * @return File_thumbnail or null
109 function storeThumbnail()
111 if (substr($this->mimetype, 0, strlen('image/')) != 'image/') {
112 // @fixme video thumbs would be nice!
116 $image = new ImageFile($this->fileRecord->id,
117 File::path($this->filename));
118 } catch (Exception $e) {
119 // Unsupported image type.
123 $outname = File::filename($this->scoped, 'thumb-' . $this->filename, $this->mimetype);
124 $outpath = File::path($outname);
126 $maxWidth = common_config('attachments', 'thumb_width');
127 $maxHeight = common_config('attachments', 'thumb_height');
128 list($width, $height) = $this->scaleToFit($image->width, $image->height, $maxWidth, $maxHeight);
130 $image->resizeTo($outpath, $width, $height);
131 File_thumbnail::saveThumbnail($this->fileRecord->id,
137 function scaleToFit($width, $height, $maxWidth, $maxHeight)
139 $aspect = $maxWidth / $maxHeight;
141 $h1 = intval($height * $maxWidth / $width);
142 if ($h1 > $maxHeight) {
143 $w2 = intval($width * $maxHeight / $height);
145 return array($w2, $h2);
147 return array($w1, $h1);
150 function rememberFile($file, $short)
152 $this->maybeAddRedir($file->id, $short);
155 function maybeAddRedir($file_id, $url)
157 $file_redir = File_redirection::getKV('url', $url);
159 if (empty($file_redir)) {
161 $file_redir = new File_redirection;
162 $file_redir->url = $url;
163 $file_redir->file_id = $file_id;
165 $result = $file_redir->insert();
168 common_log_db_error($file_redir, "INSERT", __FILE__);
169 // TRANS: Client exception thrown when a database error was thrown during a file upload operation.
170 throw new ClientException(_('There was a database error while saving your file. Please try again.'));
175 static function fromUpload($param = 'media', Profile $scoped)
177 if (is_null($scoped)) {
178 $scoped = Profile::current();
181 if (!isset($_FILES[$param]['error'])){
185 switch ($_FILES[$param]['error']) {
186 case UPLOAD_ERR_OK: // success, jump out
188 case UPLOAD_ERR_INI_SIZE:
189 // TRANS: Client exception thrown when an uploaded file is larger than set in php.ini.
190 throw new ClientException(_('The uploaded file exceeds the ' .
191 'upload_max_filesize directive in php.ini.'));
193 case UPLOAD_ERR_FORM_SIZE:
194 throw new ClientException(
195 // TRANS: Client exception.
196 _('The uploaded file exceeds the MAX_FILE_SIZE directive' .
197 ' that was specified in the HTML form.'));
199 case UPLOAD_ERR_PARTIAL:
200 @unlink($_FILES[$param]['tmp_name']);
201 // TRANS: Client exception.
202 throw new ClientException(_('The uploaded file was only' .
203 ' partially uploaded.'));
205 case UPLOAD_ERR_NO_FILE:
206 // No file; probably just a non-AJAX submission.
208 case UPLOAD_ERR_NO_TMP_DIR:
209 // TRANS: Client exception thrown when a temporary folder is not present to store a file upload.
210 throw new ClientException(_('Missing a temporary folder.'));
212 case UPLOAD_ERR_CANT_WRITE:
213 // TRANS: Client exception thrown when writing to disk is not possible during a file upload operation.
214 throw new ClientException(_('Failed to write file to disk.'));
216 case UPLOAD_ERR_EXTENSION:
217 // TRANS: Client exception thrown when a file upload operation has been stopped by an extension.
218 throw new ClientException(_('File upload stopped by extension.'));
221 common_log(LOG_ERR, __METHOD__ . ": Unknown upload error " .
222 $_FILES[$param]['error']);
223 // TRANS: Client exception thrown when a file upload operation has failed with an unknown reason.
224 throw new ClientException(_('System error uploading file.'));
228 // Throws exception if additional size does not respect quota
229 File::respectsQuota($scoped, $_FILES[$param]['size']);
231 $mimetype = MediaFile::getUploadedFileType($_FILES[$param]['tmp_name'],
232 $_FILES[$param]['name']);
234 $basename = basename($_FILES[$param]['name']);
235 $filename = File::filename($scoped, $basename, $mimetype);
236 $filepath = File::path($filename);
238 $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
241 // TRANS: Client exception thrown when a file upload operation fails because the file could
242 // TRANS: not be moved from the temporary folder to the permanent file location.
243 throw new ClientException(_('File could not be moved to destination directory.'));
246 return new MediaFile($scoped, $filename, $mimetype);
249 static function fromFilehandle($fh, Profile $scoped) {
251 $stream = stream_get_meta_data($fh);
253 File::respectsQuota($scoped, filesize($stream['uri']));
255 $mimetype = MediaFile::getUploadedFileType($fh);
257 $filename = File::filename($scoped, "email", $mimetype);
259 $filepath = File::path($filename);
261 $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
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.' .
267 $stream['uri'] . ' ' . $filepath));
270 return new MediaFile($scoped, $filename, $mimetype);
274 * Attempt to identify the content type of a given file.
276 * @param mixed $f file handle resource, or filesystem path as string
277 * @param string $originalFilename (optional) for extension-based detection
280 * @fixme is this an internal or public method? It's called from GetFileAction
281 * @fixme this seems to tie a front-end error message in, kinda confusing
282 * @fixme this looks like it could return a PEAR_Error in some cases, if
283 * type can't be identified and $config['attachments']['supported'] is true
285 * @throws ClientException if type is known, but not supported for local uploads
287 static function getUploadedFileType($f, $originalFilename=false) {
290 require_once 'MIME/Type.php';
291 require_once 'MIME/Type/Extension.php';
293 // We have to disable auto handling of PEAR errors
294 $_PEAR->staticPushErrorHandling(PEAR_ERROR_RETURN);
295 $mte = new MIME_Type_Extension();
297 $cmd = &$_PEAR->getStaticProperty('MIME_Type', 'fileCmd');
298 $cmd = common_config('attachments', 'filecommand');
302 // If we couldn't get a clear type from the file extension,
303 // we'll go ahead and try checking the content. Content checks
304 // are unambiguous for most image files, but nearly useless
305 // for office document formats.
309 // assuming a filename
311 $filetype = MIME_Type::autoDetect($f);
315 // assuming a filehandle
317 $stream = stream_get_meta_data($f);
318 $filetype = MIME_Type::autoDetect($stream['uri']);
321 // The content-based sources for MIME_Type::autoDetect()
322 // are wildly unreliable for office-type documents. If we've
323 // gotten an unclear reponse back or just couldn't identify it,
324 // we'll try detecting a type from its extension...
325 $unclearTypes = array('application/octet-stream',
326 'application/vnd.ms-office',
328 // TODO: for XML we could do better content-based sniffing too
331 if ($originalFilename && (!$filetype || in_array($filetype, $unclearTypes))) {
332 $type = $mte->getMIMEType($originalFilename);
333 if (is_string($type)) {
338 $supported = common_config('attachments', 'supported');
339 if (is_array($supported)) {
340 // Normalize extensions to mime types
341 foreach ($supported as $i => $entry) {
342 if (strpos($entry, '/') === false) {
343 common_log(LOG_INFO, "sample.$entry");
344 $supported[$i] = $mte->getMIMEType("sample.$entry");
348 if ($supported === true || in_array($filetype, $supported)) {
349 // Restore PEAR error handlers for our DB code...
350 $_PEAR->staticPopErrorHandling();
353 $media = MIME_Type::getMedia($filetype);
354 if ('application' !== $media) {
355 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
356 // TRANS: %1$s is the file type that was denied, %2$s is the application part of
357 // TRANS: the MIME type that was denied.
358 $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' .
359 'Try using another %2$s format.'), $filetype, $media);
361 // TRANS: Client exception thrown trying to upload a forbidden MIME type.
362 // TRANS: %s is the file type that was denied.
363 $hint = sprintf(_('"%s" is not a supported file type on this server.'), $filetype);
365 // Restore PEAR error handlers for our DB code...
366 $_PEAR->staticPopErrorHandling();
367 throw new ClientException($hint);