]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mediafile.php
Better event name (creating thumbnail _source_)
[quix0rs-gnu-social.git] / lib / mediafile.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Abstraction for media files in general
6  *
7  * TODO: combine with ImageFile?
8  *
9  * PHP version 5
10  *
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.
15  *
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.
20  *
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/>.
23  *
24  * @category  Media
25  * @package   StatusNet
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/
31  */
32
33 if (!defined('GNUSOCIAL')) { exit(1); }
34
35 class MediaFile
36 {
37     protected $scoped   = null;
38
39     var $filename      = null;
40     var $fileRecord    = null;
41     var $fileurl       = null;
42     var $short_fileurl = null;
43     var $mimetype      = null;
44     var $thumbnailRecord = null;
45
46     function __construct(Profile $scoped, $filename = null, $mimetype = null)
47     {
48         $this->scoped = $scoped;
49
50         $this->filename   = $filename;
51         $this->mimetype   = $mimetype;
52         $this->fileRecord = $this->storeFile();
53         try {
54             $this->thumbnailRecord = $this->storeThumbnail();
55         } catch (UnsupportedMediaException $e) {
56             // FIXME: Add "unknown media" icon or something
57             $this->thumbnailRecord = null;
58         }
59
60         $this->fileurl = common_local_url('attachment',
61                                     array('attachment' => $this->fileRecord->id));
62
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);
66     }
67
68     public function attachToNotice(Notice $notice)
69     {
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)));
73     }
74
75     public function getPath()
76     {
77         return File::path($this->filename);
78     }
79
80     function shortUrl()
81     {
82         return $this->short_fileurl;
83     }
84
85     function delete()
86     {
87         $filepath = File::path($this->filename);
88         @unlink($filepath);
89     }
90
91     function storeFile() {
92
93         $file = new File;
94
95         $file->filename = $this->filename;
96         $file->url      = File::url($this->filename);
97         $filepath       = File::path($this->filename);
98         $file->size     = filesize($filepath);
99         $file->date     = time();
100         $file->mimetype = $this->mimetype;
101
102         $file_id = $file->insert();
103
104         if (!$file_id) {
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.'));
108         }
109
110         return $file;
111     }
112
113     /**
114      * Generate and store a thumbnail image for the uploaded file, if applicable.
115      *
116      * @return File_thumbnail or null
117      */
118     function storeThumbnail($maxWidth=null, $maxHeight=null, $square=true)
119     {
120         $imgPath = null;
121         $media = common_get_mime_media($this->mimetype);
122
123         if (Event::handle('CreateFileImageThumbnailSource', array($this, &$imgPath, $media))) {
124             switch ($media) {
125             case 'image':
126                 $imgPath = $this->getPath();
127                 break;
128             default: 
129                 throw new UnsupportedMediaException(_('Unsupported media format.'), $this->getPath());
130             }
131         }
132         if (!file_exists($imgPath)) {
133             throw new ServerException(sprintf('Thumbnail source is not stored locally: %s', $imgPath));
134         }
135
136         try {
137             $image = new ImageFile($this->fileRecord->id, $imgPath);
138         } catch (UnsupportedMediaException $e) {
139             // Avoid deleting the original
140             if ($image->getPath() != $this->getPath()) {
141                 $image->unlink();
142             }
143             throw $e;
144         }
145
146         $outname = File::filename($this->scoped, 'thumb-' . $this->filename, $this->mimetype);
147         $outpath = File::path($outname);
148
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'));
155
156         $image->resizeTo($outpath, $width, $height, $x, $y, $w2, $h2);
157
158         // Avoid deleting the original
159         if ($image->getPath() != $this->getPath()) {
160             $image->unlink();
161         }
162         return File_thumbnail::saveThumbnail($this->fileRecord->id,
163                                       File::url($outname),
164                                       $width,
165                                       $height);
166     }
167
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)
170     {
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;
182             $square = true;
183         }
184         
185         // cropping data
186         $cx = 0;    // crop x
187         $cy = 0;    // crop y
188         $cw = null; // crop area width
189         $ch = null; // crop area height
190
191         if ($square) {
192             // resulting width and height
193             $rw = $maxWidth;
194             $rh = $maxHeight;
195
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;
201             $cw = $minSide;
202             $ch = $minSide;
203         } else {
204             // resulting sizes
205             $rw = $maxWidth;
206             $rh = floor($height * $maxWidth / $width);
207
208             if ($rh > $maxHeight) {
209                 $rw = floor($width * $maxHeight / $height);
210                 $rh = $maxHeight;
211             }
212         }
213         return array($rw, $rh, $cx, $cy, $cw, $ch);
214     }
215
216     function rememberFile($file, $short)
217     {
218         $this->maybeAddRedir($file->id, $short);
219     }
220
221     function maybeAddRedir($file_id, $url)
222     {
223         $file_redir = File_redirection::getKV('url', $url);
224
225         if (empty($file_redir)) {
226
227             $file_redir = new File_redirection;
228             $file_redir->url = $url;
229             $file_redir->file_id = $file_id;
230
231             $result = $file_redir->insert();
232
233             if (!$result) {
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.'));
237             }
238         }
239     }
240
241     static function fromUpload($param = 'media', Profile $scoped)
242     {
243         if (is_null($scoped)) {
244             $scoped = Profile::current();
245         }
246
247         if (!isset($_FILES[$param]['error'])){
248             return;
249         }
250
251         switch ($_FILES[$param]['error']) {
252         case UPLOAD_ERR_OK: // success, jump out
253             break;
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.
270             return;
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.'));
280         default:
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.'));
285         }
286
287         // Throws exception if additional size does not respect quota
288         File::respectsQuota($scoped, $_FILES[$param]['size']);
289
290         $mimetype = self::getUploadedMimeType($_FILES[$param]['tmp_name'],
291                                                    $_FILES[$param]['name']);
292
293         $basename = basename($_FILES[$param]['name']);
294         $filename = File::filename($scoped, $basename, $mimetype);
295         $filepath = File::path($filename);
296
297         $result = move_uploaded_file($_FILES[$param]['tmp_name'], $filepath);
298
299         if (!$result) {
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.'));
303         }
304
305         return new MediaFile($scoped, $filename, $mimetype);
306     }
307
308     static function fromFilehandle($fh, Profile $scoped) {
309
310         $stream = stream_get_meta_data($fh);
311
312         File::respectsQuota($scoped, filesize($stream['uri']));
313
314         $mimetype = self::getUploadedMimeType($stream['uri']);
315
316         $filename = File::filename($scoped, "email", $mimetype);
317
318         $filepath = File::path($filename);
319
320         $result = copy($stream['uri'], $filepath) && chmod($filepath, 0664);
321
322         if (!$result) {
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));
327         }
328
329         return new MediaFile($scoped, $filename, $mimetype);
330     }
331
332     /**
333      * Attempt to identify the content type of a given file.
334      * 
335      * @param string $filepath filesystem path as string (file must exist)
336      * @param string $originalFilename (optional) for extension-based detection
337      * @return string
338      * 
339      * @fixme this seems to tie a front-end error message in, kinda confusing
340      * 
341      * @throws ClientException if type is known, but not supported for local uploads
342      */
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);
347
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',
352                               'application/zip',
353                               // TODO: for XML we could do better content-based sniffing too
354                               'text/xml');
355
356         $supported = common_config('attachments', 'supported');
357
358         // If we didn't match, or it is an unclear match
359         if ($originalFilename && (!$mimetype || in_array($mimetype, $unclearTypes))) {
360             try {
361                 $type = common_supported_ext_to_mime($originalFilename);
362                 return $type;
363             } catch (Exception $e) {
364                 // Extension not found, so $mimetype is our best guess
365             }
366         }
367
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.
373             return $mimetype;
374         }
375
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);
384         } else {
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);
388         }
389         throw new ClientException($hint);
390     }
391 }