]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
Merge commit 'refs/merge-requests/31' of https://gitorious.org/social/mainline into...
[quix0rs-gnu-social.git] / classes / File.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('GNUSOCIAL')) { exit(1); }
21
22 /**
23  * Table Definition for file
24  */
25 class File extends Managed_DataObject
26 {
27     public $__table = 'file';                            // table name
28     public $id;                              // int(4)  primary_key not_null
29     public $url;                             // varchar(255)  unique_key
30     public $mimetype;                        // varchar(50)
31     public $size;                            // int(4)
32     public $title;                           // varchar(255)
33     public $date;                            // int(4)
34     public $protected;                       // int(4)
35     public $filename;                        // varchar(255)
36     public $width;                           // int(4)
37     public $height;                          // int(4)
38     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
39
40     public static function schemaDef()
41     {
42         return array(
43             'fields' => array(
44                 'id' => array('type' => 'serial', 'not null' => true),
45                 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'destination URL after following redirections'),
46                 'mimetype' => array('type' => 'varchar', 'length' => 50, 'description' => 'mime type of resource'),
47                 'size' => array('type' => 'int', 'description' => 'size of resource when available'),
48                 'title' => array('type' => 'varchar', 'length' => 255, 'description' => 'title of resource when available'),
49                 'date' => array('type' => 'int', 'description' => 'date of resource according to http query'),
50                 'protected' => array('type' => 'int', 'description' => 'true when URL is private (needs login)'),
51                 'filename' => array('type' => 'varchar', 'length' => 255, 'description' => 'if a local file, name of the file'),
52                 'width' => array('type' => 'int', 'description' => 'width in pixels, if it can be described as such and data is available'),
53                 'height' => array('type' => 'int', 'description' => 'height in pixels, if it can be described as such and data is available'),
54
55                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
56             ),
57             'primary key' => array('id'),
58             'unique keys' => array(
59                 'file_url_key' => array('url'),
60             ),
61         );
62     }
63
64     function isProtected($url) {
65         return 'http://www.facebook.com/login.php' === $url;
66     }
67
68     /**
69      * Save a new file record.
70      *
71      * @param array $redir_data lookup data eg from File_redirection::where()
72      * @param string $given_url
73      * @return File
74      */
75     public static function saveNew(array $redir_data, $given_url) {
76
77         // I don't know why we have to keep doing this but I'm adding this last check to avoid
78         // uniqueness bugs.
79
80         $file = File::getKV('url', $given_url);
81         
82         if (!$file instanceof File) {
83             $file = new File;
84             $file->url = $given_url;
85             if (!empty($redir_data['protected'])) $file->protected = $redir_data['protected'];
86             if (!empty($redir_data['title'])) $file->title = $redir_data['title'];
87             if (!empty($redir_data['type'])) $file->mimetype = $redir_data['type'];
88             if (!empty($redir_data['size'])) $file->size = intval($redir_data['size']);
89             if (isset($redir_data['time']) && $redir_data['time'] > 0) $file->date = intval($redir_data['time']);
90             $file_id = $file->insert();
91         }
92
93         Event::handle('EndFileSaveNew', array($file, $redir_data, $given_url));
94         assert ($file instanceof File);
95         return $file;
96     }
97
98     /**
99      * Go look at a URL and possibly save data about it if it's new:
100      * - follow redirect chains and store them in file_redirection
101      * - if a thumbnail is available, save it in file_thumbnail
102      * - save file record with basic info
103      * - optionally save a file_to_post record
104      * - return the File object with the full reference
105      *
106      * @fixme refactor this mess, it's gotten pretty scary.
107      * @param string $given_url the URL we're looking at
108      * @param int $notice_id (optional)
109      * @param bool $followRedirects defaults to true
110      *
111      * @return mixed File on success, -1 on some errors
112      *
113      * @throws ServerException on failure
114      */
115     public static function processNew($given_url, $notice_id=null, $followRedirects=true) {
116         if (empty($given_url)) {
117             throw new ServerException('No given URL to process');
118         }
119
120         $given_url = File_redirection::_canonUrl($given_url);
121         if (empty($given_url)) {
122             throw new ServerException('No canonical URL from given URL to process');
123         }
124
125         $file = File::getKV('url', $given_url);
126         if (!$file instanceof File) {
127             // First check if we have a lookup trace for this URL already
128             $file_redir = File_redirection::getKV('url', $given_url);
129             if ($file_redir instanceof File_redirection) {
130                 $file = File::getKV('id', $file_redir->file_id);
131                 if (!$file instanceof File) {
132                     // File did not exist, let's clean up the File_redirection entry
133                     $file_redir->delete();
134                 }
135             }
136
137             // If we still don't have a File object, let's create one now!
138             if (!$file instanceof File) {
139                 // @fixme for new URLs this also looks up non-redirect data
140                 // such as target content type, size, etc, which we need
141                 // for File::saveNew(); so we call it even if not following
142                 // new redirects.
143                 $redir_data = File_redirection::where($given_url);
144                 if (is_array($redir_data)) {
145                     $redir_url = $redir_data['url'];
146                 } elseif (is_string($redir_data)) {
147                     $redir_url = $redir_data;
148                     $redir_data = array();
149                 } else {
150                     // TRANS: Server exception thrown when a URL cannot be processed.
151                     throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
152                 }
153
154                 // TODO: max field length
155                 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
156                     // Save the File object based on our lookup trace
157                     $file = File::saveNew($redir_data, $given_url);
158                 } else {
159                     // This seems kind of messed up... for now skipping this part
160                     // if we're already under a redirect, so we don't go into
161                     // horrible infinite loops if we've been given an unstable
162                     // redirect (where the final destination of the first request
163                     // doesn't match what we get when we ask for it again).
164                     //
165                     // Seen in the wild with clojure.org, which redirects through
166                     // wikispaces for auth and appends session data in the URL params.
167                     $file = self::processNew($redir_url, $notice_id, /*followRedirects*/false);
168                     File_redirection::saveNew($redir_data, $file->id, $given_url);
169                 }
170             }
171
172             if (!$file instanceof File) {
173                 // This should only happen if File::saveNew somehow did not return a File object,
174                 // though we have an assert for that in case the event there might've gone wrong.
175                 // If anything else goes wrong, there should've been an exception thrown.
176                 throw new ServerException('URL processing failed without new File object');
177             }
178         }
179
180         if (!empty($notice_id)) {
181             File_to_post::processNew($file->id, $notice_id);
182         }
183         return $file;
184     }
185
186     public static function respectsQuota(Profile $scoped, $fileSize) {
187         if ($fileSize > common_config('attachments', 'file_quota')) {
188             // TRANS: Message used to be inserted as %2$s in  the text "No file may
189             // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
190             // TRANS: %1$d is the number of bytes of an uploaded file.
191             $fileSizeText = sprintf(_m('%1$d byte','%1$d bytes',$fileSize),$fileSize);
192
193             $fileQuota = common_config('attachments', 'file_quota');
194             // TRANS: Message given if an upload is larger than the configured maximum.
195             // TRANS: %1$d (used for plural) is the byte limit for uploads,
196             // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
197             // TRANS: gettext support multiple plurals in the same message, unfortunately...
198             throw new ClientException(
199                     sprintf(_m('No file may be larger than %1$d byte and the file you sent was %2$s. Try to upload a smaller version.',
200                               'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
201                               $fileQuota),
202                     $fileQuota, $fileSizeText));
203         }
204
205         $file = new File;
206
207         $query = "select sum(size) as total from file join file_to_post on file_to_post.file_id = file.id join notice on file_to_post.post_id = notice.id where profile_id = {$scoped->id} and file.url like '%/notice/%/file'";
208         $file->query($query);
209         $file->fetch();
210         $total = $file->total + $fileSize;
211         if ($total > common_config('attachments', 'user_quota')) {
212             // TRANS: Message given if an upload would exceed user quota.
213             // TRANS: %d (number) is the user quota in bytes and is used for plural.
214             throw new ClientException(
215                     sprintf(_m('A file this large would exceed your user quota of %d byte.',
216                               'A file this large would exceed your user quota of %d bytes.',
217                               common_config('attachments', 'user_quota')),
218                     common_config('attachments', 'user_quota')));
219         }
220         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
221         $file->query($query);
222         $file->fetch();
223         $total = $file->total + $fileSize;
224         if ($total > common_config('attachments', 'monthly_quota')) {
225             // TRANS: Message given id an upload would exceed a user's monthly quota.
226             // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
227             throw new ClientException(
228                     sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
229                               'A file this large would exceed your monthly quota of %d bytes.',
230                               common_config('attachments', 'monthly_quota')),
231                     common_config('attachments', 'monthly_quota')));
232         }
233         return true;
234     }
235
236     // where should the file go?
237
238     static function filename(Profile $profile, $origname, $mimetype)
239     {
240         try {
241             $ext = common_supported_mime_to_ext($mimetype);
242         } catch (Exception $e) {
243             // We don't support this mimetype, but let's guess the extension
244             $ext = substr(strrchr($mimetype, '/'), 1);
245         }
246
247         // Normalize and make the original filename more URL friendly.
248         $origname = basename($origname, ".$ext");
249         if (class_exists('Normalizer')) {
250             // http://php.net/manual/en/class.normalizer.php
251             // http://www.unicode.org/reports/tr15/
252             $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
253         }
254         $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
255
256         $nickname = $profile->getNickname();
257         $datestamp = strftime('%Y%m%d', time());
258         do {
259             // generate new random strings until we don't run into a filename collision.
260             $random = strtolower(common_confirmation_code(16));
261             $filename = "$nickname-$datestamp-$origname-$random.$ext";
262         } while (file_exists(self::path($filename)));
263         return $filename;
264     }
265
266     /**
267      * Validation for as-saved base filenames
268      */
269     static function validFilename($filename)
270     {
271         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
272     }
273
274     /**
275      * @throws ClientException on invalid filename
276      */
277     static function path($filename)
278     {
279         if (!self::validFilename($filename)) {
280             // TRANS: Client exception thrown if a file upload does not have a valid name.
281             throw new ClientException(_("Invalid filename."));
282         }
283         $dir = common_config('attachments', 'dir');
284
285         if ($dir[strlen($dir)-1] != '/') {
286             $dir .= '/';
287         }
288
289         return $dir . $filename;
290     }
291
292     static function url($filename)
293     {
294         if (!self::validFilename($filename)) {
295             // TRANS: Client exception thrown if a file upload does not have a valid name.
296             throw new ClientException(_("Invalid filename."));
297         }
298
299         if (common_config('site','private')) {
300
301             return common_local_url('getfile',
302                                 array('filename' => $filename));
303
304         }
305
306         if (StatusNet::useHTTPS()) {
307
308             $sslserver = common_config('attachments', 'sslserver');
309
310             if (empty($sslserver)) {
311                 // XXX: this assumes that background dir == site dir + /file/
312                 // not true if there's another server
313                 if (is_string(common_config('site', 'sslserver')) &&
314                     mb_strlen(common_config('site', 'sslserver')) > 0) {
315                     $server = common_config('site', 'sslserver');
316                 } else if (common_config('site', 'server')) {
317                     $server = common_config('site', 'server');
318                 }
319                 $path = common_config('site', 'path') . '/file/';
320             } else {
321                 $server = $sslserver;
322                 $path   = common_config('attachments', 'sslpath');
323                 if (empty($path)) {
324                     $path = common_config('attachments', 'path');
325                 }
326             }
327
328             $protocol = 'https';
329         } else {
330             $path = common_config('attachments', 'path');
331             $server = common_config('attachments', 'server');
332
333             if (empty($server)) {
334                 $server = common_config('site', 'server');
335             }
336
337             $ssl = common_config('attachments', 'ssl');
338
339             $protocol = ($ssl) ? 'https' : 'http';
340         }
341
342         if ($path[strlen($path)-1] != '/') {
343             $path .= '/';
344         }
345
346         if ($path[0] != '/') {
347             $path = '/'.$path;
348         }
349
350         return $protocol.'://'.$server.$path.$filename;
351     }
352
353     function getEnclosure(){
354         $enclosure = (object) array();
355         foreach (array('title', 'url', 'date', 'modified', 'size', 'mimetype') as $key) {
356             $enclosure->$key = $this->$key;
357         }
358
359         $needMoreMetadataMimetypes = array(null, 'application/xhtml+xml');
360
361         if (!isset($this->filename) && in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
362             // This fetches enclosure metadata for non-local links with unset/HTML mimetypes,
363             // which may be enriched through oEmbed or similar (implemented as plugins)
364             Event::handle('FileEnclosureMetadata', array($this, &$enclosure));
365         }
366         if (empty($enclosure->mimetype) || in_array(common_bare_mime($enclosure->mimetype), $needMoreMetadataMimetypes)) {
367             // This means we either don't know what it is, so it can't
368             // be shown as an enclosure, or it is an HTML link which
369             // does not link to a resource with further metadata.
370             throw new ServerException('Unknown enclosure mimetype, not enough metadata');
371         }
372         return $enclosure;
373     }
374
375     /**
376      * Get the attachment's thumbnail record, if any.
377      * Make sure you supply proper 'int' typed variables (or null).
378      *
379      * @param $width  int   Max width of thumbnail in pixels. (if null, use common_config values)
380      * @param $height int   Max height of thumbnail in pixels. (if null, square-crop to $width)
381      * @param $crop   bool  Crop to the max-values' aspect ratio
382      *
383      * @return File_thumbnail
384      */
385     public function getThumbnail($width=null, $height=null, $crop=false, $force_still=true)
386     {
387         // Get some more information about this file through our ImageFile class
388         $image = ImageFile::fromFileObject($this);
389         if ($image->animated && !common_config('thumbnail', 'animated')) {
390             // null  means "always use file as thumbnail"
391             // false means you get choice between frozen frame or original when calling getThumbnail
392             if (is_null(common_config('thumbnail', 'animated')) || !$force_still) {
393                 throw new UseFileAsThumbnailException($this->id);
394             }
395         }
396
397         if ($width === null) {
398             $width = common_config('thumbnail', 'width');
399             $height = common_config('thumbnail', 'height');
400             $crop = common_config('thumbnail', 'crop');
401         }
402
403         if ($height === null) {
404             $height = $width;
405             $crop = true;
406         }
407
408         // Get proper aspect ratio width and height before lookup
409         // We have to do it through an ImageFile object because of orientation etc.
410         // Only other solution would've been to rotate + rewrite uploaded files.
411         list($width, $height, $x, $y, $w, $h) =
412                                 $image->scaleToFit($width, $height, $crop);
413
414         $params = array('file_id'=> $this->id,
415                         'width'  => $width,
416                         'height' => $height);
417         $thumb = File_thumbnail::pkeyGet($params);
418         if ($thumb instanceof File_thumbnail) {
419             return $thumb;
420         }
421
422         // throws exception on failure to generate thumbnail
423         $outname = "thumb-{$width}x{$height}-" . $image->filename;
424         $outpath = self::path($outname);
425
426         // The boundary box for our resizing
427         $box = array('width'=>$width, 'height'=>$height,
428                      'x'=>$x,         'y'=>$y,
429                      'w'=>$w,         'h'=>$h);
430
431         // Doublecheck that parameters are sane and integers.
432         if ($box['width'] < 1 || $box['width'] > common_config('thumbnail', 'maxsize')
433                 || $box['height'] < 1 || $box['height'] > common_config('thumbnail', 'maxsize')
434                 || $box['w'] < 1 || $box['x'] >= $image->width
435                 || $box['h'] < 1 || $box['y'] >= $image->height) {
436             // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile->scaleToFit
437             common_debug("Boundary box parameters for resize of {$image->filepath} : ".var_export($box,true));
438             throw new ServerException('Bad thumbnail size parameters.');
439         }
440
441         common_debug(sprintf('Generating a thumbnail of File id==%u of size %ux%u', $this->id, $width, $height));
442         // Perform resize and store into file
443         $image->resizeTo($outpath, $box);
444
445         // Avoid deleting the original
446         if ($image->getPath() != self::path($image->filename)) {
447             $image->unlink();
448         }
449         return File_thumbnail::saveThumbnail($this->id,
450                                       self::url($outname),
451                                       $width, $height,
452                                       $outname);
453     }
454
455     public function getPath()
456     {
457         return self::path($this->filename);
458     }
459
460     public function getUrl()
461     {
462         if (!empty($this->filename)) {
463             // A locally stored file, so let's generate a URL for our instance.
464             $url = self::url($this->filename);
465             if ($url != $this->url) {
466                 // For indexing purposes, in case we do a lookup on the 'url' field.
467                 // also we're fixing possible changes from http to https, or paths
468                 $this->updateUrl($url);
469             }
470             return $url;
471         }
472
473         // No local filename available, return the URL we have stored
474         return $this->url;
475     }
476
477     public function updateUrl($url)
478     {
479         $file = File::getKV('url', $url);
480         if ($file instanceof File) {
481             throw new ServerException('URL already exists in DB');
482         }
483         $sql = 'UPDATE %1$s SET url=%2$s WHERE url=%3$s;';
484         $result = $this->query(sprintf($sql, $this->__table,
485                                              $this->_quote((string)$url),
486                                              $this->_quote((string)$this->url)));
487         if ($result === false) {
488             common_log_db_error($this, 'UPDATE', __FILE__);
489             throw new ServerException("Could not UPDATE {$this->__table}.url");
490         }
491
492         return $result;
493     }
494
495     /**
496      * Blow the cache of notices that link to this URL
497      *
498      * @param boolean $last Whether to blow the "last" cache too
499      *
500      * @return void
501      */
502
503     function blowCache($last=false)
504     {
505         self::blow('file:notice-ids:%s', $this->url);
506         if ($last) {
507             self::blow('file:notice-ids:%s;last', $this->url);
508         }
509         self::blow('file:notice-count:%d', $this->id);
510     }
511
512     /**
513      * Stream of notices linking to this URL
514      *
515      * @param integer $offset   Offset to show; default is 0
516      * @param integer $limit    Limit of notices to show
517      * @param integer $since_id Since this notice
518      * @param integer $max_id   Before this notice
519      *
520      * @return array ids of notices that link to this file
521      */
522
523     function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
524     {
525         $stream = new FileNoticeStream($this);
526         return $stream->getNotices($offset, $limit, $since_id, $max_id);
527     }
528
529     function noticeCount()
530     {
531         $cacheKey = sprintf('file:notice-count:%d', $this->id);
532         
533         $count = self::cacheGet($cacheKey);
534
535         if ($count === false) {
536
537             $f2p = new File_to_post();
538
539             $f2p->file_id = $this->id;
540
541             $count = $f2p->count();
542
543             self::cacheSet($cacheKey, $count);
544         } 
545
546         return $count;
547     }
548
549     public function isLocal()
550     {
551         return !empty($this->filename);
552     }
553
554     public function delete($useWhere=false)
555     {
556         // Delete the file, if it exists locally
557         if (!empty($this->filename) && file_exists(self::path($this->filename))) {
558             $deleted = @unlink(self::path($this->filename));
559             if (!$deleted) {
560                 common_log(LOG_ERR, sprintf('Could not unlink existing file: "%s"', self::path($this->filename)));
561             }
562         }
563
564         // Clear out related things in the database and filesystem, such as thumbnails
565         if (Event::handle('FileDeleteRelated', array($this))) {
566             $thumbs = new File_thumbnail();
567             $thumbs->file_id = $this->id;
568             if ($thumbs->find()) {
569                 while ($thumbs->fetch()) {
570                     $thumbs->delete();
571                 }
572             }
573         }
574
575         // And finally remove the entry from the database
576         return parent::delete($useWhere);
577     }
578
579     public function getTitle()
580     {
581         $title = $this->title ?: $this->filename;
582
583         return $title ?: null;
584     }
585 }