]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
Enable events for showing Attachment representation
[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 $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
37
38     public static function schemaDef()
39     {
40         return array(
41             'fields' => array(
42                 'id' => array('type' => 'serial', 'not null' => true),
43                 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'destination URL after following redirections'),
44                 'mimetype' => array('type' => 'varchar', 'length' => 50, 'description' => 'mime type of resource'),
45                 'size' => array('type' => 'int', 'description' => 'size of resource when available'),
46                 'title' => array('type' => 'varchar', 'length' => 255, 'description' => 'title of resource when available'),
47                 'date' => array('type' => 'int', 'description' => 'date of resource according to http query'),
48                 'protected' => array('type' => 'int', 'description' => 'true when URL is private (needs login)'),
49                 'filename' => array('type' => 'varchar', 'length' => 255, 'description' => 'if a local file, name of the file'),
50                 'width' => array('type' => 'int', 'description' => 'width in pixels, if it can be described as such and data is available'),
51                 'height' => array('type' => 'int', 'description' => 'height in pixels, if it can be described as such and data is available'),
52
53                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
54             ),
55             'primary key' => array('id'),
56             'unique keys' => array(
57                 'file_url_key' => array('url'),
58             ),
59         );
60     }
61
62     function isProtected($url) {
63         return 'http://www.facebook.com/login.php' === $url;
64     }
65
66     /**
67      * Save a new file record.
68      *
69      * @param array $redir_data lookup data eg from File_redirection::where()
70      * @param string $given_url
71      * @return File
72      */
73     public static function saveNew(array $redir_data, $given_url) {
74
75         // I don't know why we have to keep doing this but I'm adding this last check to avoid
76         // uniqueness bugs.
77
78         $x = File::getKV('url', $given_url);
79         
80         if (!$x instanceof File) {
81             $x = new File;
82             $x->url = $given_url;
83             if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
84             if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
85             if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
86             if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
87             if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
88             $file_id = $x->insert();
89         }
90
91         $x->saveOembed($redir_data, $given_url);
92         return $x;
93     }
94
95     /**
96      * Save embedding information for this file, if applicable.
97      *
98      * Normally this won't need to be called manually, as File::saveNew()
99      * takes care of it.
100      *
101      * @param array $redir_data lookup data eg from File_redirection::where()
102      * @param string $given_url
103      * @return boolean success
104      */
105     public function saveOembed(array $redir_data, $given_url)
106     {
107         if (isset($redir_data['type'])
108                 && (('text/html' === substr($redir_data['type'], 0, 9)
109                 || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))) {
110             try {
111                 $oembed_data = File_oembed::_getOembed($given_url);
112             } catch (Exception $e) {
113                 return false;
114             }
115             if ($oembed_data === false) {
116                 return false;
117             }
118             $fo = File_oembed::getKV('file_id', $this->id);
119
120             if ($fo instanceof File_oembed) {
121                 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
122             } else {
123                 File_oembed::saveNew($oembed_data, $this->id);
124                 return true;
125             }
126         }
127         return false;
128     }
129
130     /**
131      * Go look at a URL and possibly save data about it if it's new:
132      * - follow redirect chains and store them in file_redirection
133      * - look up oEmbed data and save it in file_oembed
134      * - if a thumbnail is available, save it in file_thumbnail
135      * - save file record with basic info
136      * - optionally save a file_to_post record
137      * - return the File object with the full reference
138      *
139      * @fixme refactor this mess, it's gotten pretty scary.
140      * @param string $given_url the URL we're looking at
141      * @param int $notice_id (optional)
142      * @param bool $followRedirects defaults to true
143      *
144      * @return mixed File on success, -1 on some errors
145      *
146      * @throws ServerException on some errors
147      */
148     public function processNew($given_url, $notice_id=null, $followRedirects=true) {
149         if (empty($given_url)) return -1;   // error, no url to process
150         $given_url = File_redirection::_canonUrl($given_url);
151         if (empty($given_url)) return -1;   // error, no url to process
152         $file = File::getKV('url', $given_url);
153         if (empty($file)) {
154             $file_redir = File_redirection::getKV('url', $given_url);
155             if (empty($file_redir)) {
156                 // @fixme for new URLs this also looks up non-redirect data
157                 // such as target content type, size, etc, which we need
158                 // for File::saveNew(); so we call it even if not following
159                 // new redirects.
160                 $redir_data = File_redirection::where($given_url);
161                 if (is_array($redir_data)) {
162                     $redir_url = $redir_data['url'];
163                 } elseif (is_string($redir_data)) {
164                     $redir_url = $redir_data;
165                     $redir_data = array();
166                 } else {
167                     // TRANS: Server exception thrown when a URL cannot be processed.
168                     throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
169                 }
170                 // TODO: max field length
171                 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
172                     $x = File::saveNew($redir_data, $given_url);
173                     $file_id = $x->id;
174                 } else {
175                     // This seems kind of messed up... for now skipping this part
176                     // if we're already under a redirect, so we don't go into
177                     // horrible infinite loops if we've been given an unstable
178                     // redirect (where the final destination of the first request
179                     // doesn't match what we get when we ask for it again).
180                     //
181                     // Seen in the wild with clojure.org, which redirects through
182                     // wikispaces for auth and appends session data in the URL params.
183                     $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
184                     $file_id = $x->id;
185                     File_redirection::saveNew($redir_data, $file_id, $given_url);
186                 }
187             } else {
188                 $file_id = $file_redir->file_id;
189             }
190         } else {
191             $file_id = $file->id;
192             $x = $file;
193         }
194
195         if (empty($x)) {
196             $x = File::getKV('id', $file_id);
197             if (empty($x)) {
198                 // @todo FIXME: This could possibly be a clearer message :)
199                 // TRANS: Server exception thrown when... Robin thinks something is impossible!
200                 throw new ServerException(_('Robin thinks something is impossible.'));
201             }
202         }
203
204         if (!empty($notice_id)) {
205             File_to_post::processNew($file_id, $notice_id);
206         }
207         return $x;
208     }
209
210     public static function respectsQuota(Profile $scoped, $fileSize) {
211         if ($fileSize > common_config('attachments', 'file_quota')) {
212             // TRANS: Message used to be inserted as %2$s in  the text "No file may
213             // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
214             // TRANS: %1$d is the number of bytes of an uploaded file.
215             $fileSizeText = sprintf(_m('%1$d byte','%1$d bytes',$fileSize),$fileSize);
216
217             $fileQuota = common_config('attachments', 'file_quota');
218             // TRANS: Message given if an upload is larger than the configured maximum.
219             // TRANS: %1$d (used for plural) is the byte limit for uploads,
220             // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
221             // TRANS: gettext support multiple plurals in the same message, unfortunately...
222             throw new ClientException(
223                     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.',
224                               'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
225                               $fileQuota),
226                     $fileQuota, $fileSizeText));
227         }
228
229         $file = new File;
230
231         $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'";
232         $file->query($query);
233         $file->fetch();
234         $total = $file->total + $fileSize;
235         if ($total > common_config('attachments', 'user_quota')) {
236             // TRANS: Message given if an upload would exceed user quota.
237             // TRANS: %d (number) is the user quota in bytes and is used for plural.
238             throw new ClientException(
239                     sprintf(_m('A file this large would exceed your user quota of %d byte.',
240                               'A file this large would exceed your user quota of %d bytes.',
241                               common_config('attachments', 'user_quota')),
242                     common_config('attachments', 'user_quota')));
243         }
244         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
245         $file->query($query);
246         $file->fetch();
247         $total = $file->total + $fileSize;
248         if ($total > common_config('attachments', 'monthly_quota')) {
249             // TRANS: Message given id an upload would exceed a user's monthly quota.
250             // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
251             throw new ClientException(
252                     sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
253                               'A file this large would exceed your monthly quota of %d bytes.',
254                               common_config('attachments', 'monthly_quota')),
255                     common_config('attachments', 'monthly_quota')));
256         }
257         return true;
258     }
259
260     // where should the file go?
261
262     static function filename(Profile $profile, $origname, $mimetype)
263     {
264         try {
265             $ext = common_supported_mime_to_ext($mimetype);
266         } catch (Exception $e) {
267             // We don't support this mimetype, but let's guess the extension
268             $ext = substr(strrchr($mimetype, '/'), 1);
269         }
270
271         // Normalize and make the original filename more URL friendly.
272         $origname = basename($origname);
273         if (class_exists('Normalizer')) {
274             // http://php.net/manual/en/class.normalizer.php
275             // http://www.unicode.org/reports/tr15/
276             $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
277         }
278         $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
279
280         $nickname = $profile->nickname;
281         $datestamp = strftime('%Y%m%d', time());
282         do {
283             // generate new random strings until we don't run into a filename collision.
284             $random = strtolower(common_confirmation_code(16));
285             $filename = "$nickname-$datestamp-$origname-$random.$ext";
286         } while (file_exists(self::path($filename)));
287         return $filename;
288     }
289
290     /**
291      * Validation for as-saved base filenames
292      */
293     static function validFilename($filename)
294     {
295         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
296     }
297
298     /**
299      * @throws ClientException on invalid filename
300      */
301     static function path($filename)
302     {
303         if (!self::validFilename($filename)) {
304             // TRANS: Client exception thrown if a file upload does not have a valid name.
305             throw new ClientException(_("Invalid filename."));
306         }
307         $dir = common_config('attachments', 'dir');
308
309         if ($dir[strlen($dir)-1] != '/') {
310             $dir .= '/';
311         }
312
313         return $dir . $filename;
314     }
315
316     static function url($filename)
317     {
318         if (!self::validFilename($filename)) {
319             // TRANS: Client exception thrown if a file upload does not have a valid name.
320             throw new ClientException(_("Invalid filename."));
321         }
322
323         if (common_config('site','private')) {
324
325             return common_local_url('getfile',
326                                 array('filename' => $filename));
327
328         }
329
330         if (StatusNet::isHTTPS()) {
331
332             $sslserver = common_config('attachments', 'sslserver');
333
334             if (empty($sslserver)) {
335                 // XXX: this assumes that background dir == site dir + /file/
336                 // not true if there's another server
337                 if (is_string(common_config('site', 'sslserver')) &&
338                     mb_strlen(common_config('site', 'sslserver')) > 0) {
339                     $server = common_config('site', 'sslserver');
340                 } else if (common_config('site', 'server')) {
341                     $server = common_config('site', 'server');
342                 }
343                 $path = common_config('site', 'path') . '/file/';
344             } else {
345                 $server = $sslserver;
346                 $path   = common_config('attachments', 'sslpath');
347                 if (empty($path)) {
348                     $path = common_config('attachments', 'path');
349                 }
350             }
351
352             $protocol = 'https';
353         } else {
354             $path = common_config('attachments', 'path');
355             $server = common_config('attachments', 'server');
356
357             if (empty($server)) {
358                 $server = common_config('site', 'server');
359             }
360
361             $ssl = common_config('attachments', 'ssl');
362
363             $protocol = ($ssl) ? 'https' : 'http';
364         }
365
366         if ($path[strlen($path)-1] != '/') {
367             $path .= '/';
368         }
369
370         if ($path[0] != '/') {
371             $path = '/'.$path;
372         }
373
374         return $protocol.'://'.$server.$path.$filename;
375     }
376
377     function getEnclosure(){
378         $enclosure = (object) array();
379         $enclosure->title=$this->title;
380         $enclosure->url=$this->url;
381         $enclosure->title=$this->title;
382         $enclosure->date=$this->date;
383         $enclosure->modified=$this->modified;
384         $enclosure->size=$this->size;
385         $enclosure->mimetype=$this->mimetype;
386
387         if(! isset($this->filename)){
388             $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
389             $mimetype = $this->mimetype;
390             if($mimetype != null){
391                 $mimetype = strtolower($this->mimetype);
392             }
393             $semicolon = strpos($mimetype,';');
394             if($semicolon){
395                 $mimetype = substr($mimetype,0,$semicolon);
396             }
397             if(in_array($mimetype,$notEnclosureMimeTypes)){
398                 // Never treat generic HTML links as an enclosure type!
399                 // But if we have oEmbed info, we'll consider it golden.
400                 $oembed = File_oembed::getKV('file_id',$this->id);
401                 if($oembed && in_array($oembed->type, array('photo', 'video'))){
402                     $mimetype = strtolower($oembed->mimetype);
403                     $semicolon = strpos($mimetype,';');
404                     if($semicolon){
405                         $mimetype = substr($mimetype,0,$semicolon);
406                     }
407                     // @fixme uncertain if this is right.
408                     // we want to expose things like YouTube videos as
409                     // viewable attachments, but don't expose them as
410                     // downloadable enclosures.....?
411                     //if (in_array($mimetype, $notEnclosureMimeTypes)) {
412                     //    return false;
413                     //} else {
414                         if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
415                         if($oembed->url) $enclosure->url=$oembed->url;
416                         if($oembed->title) $enclosure->title=$oembed->title;
417                         if($oembed->modified) $enclosure->modified=$oembed->modified;
418                         unset($oembed->size);
419                     //}
420                 } else {
421                     return false;
422                 }
423             }
424         }
425         return $enclosure;
426     }
427
428     // quick back-compat hack, since there's still code using this
429     function isEnclosure()
430     {
431         $enclosure = $this->getEnclosure();
432         return !empty($enclosure);
433     }
434
435     /**
436      * Get the attachment's thumbnail record, if any.
437      * Make sure you supply proper 'int' typed variables (or null).
438      *
439      * @param $width  int   Max width of thumbnail in pixels. (if null, use common_config values)
440      * @param $height int   Max height of thumbnail in pixels. (if null, square-crop to $width)
441      * @param $crop   bool  Crop to the max-values' aspect ratio
442      *
443      * @return File_thumbnail
444      */
445     public function getThumbnail($width=null, $height=null, $crop=false)
446     {
447         if (intval($this->width) < 1 || intval($this->height) < 1) {
448             // Old files may have 0 until migrated with scripts/upgrade.php
449             // For any legitimately unrepresentable ones, we could generate our
450             // own image (like a square with MIME type in text)
451             throw new UnsupportedMediaException('No image geometry available.');
452         }
453
454         if ($width === null) {
455             $width = common_config('thumbnail', 'width');
456             $height = common_config('thumbnail', 'height');
457             $crop = common_config('thumbnail', 'crop');
458         }
459
460         if ($height === null) {
461             $height = $width;
462             $crop = true;
463         }
464         
465         // Get proper aspect ratio width and height before lookup
466         list($width, $height, $x, $y, $w2, $h2) =
467                                 ImageFile::getScalingValues($this->width, $this->height, $width, $height, $crop);
468
469         // Doublecheck that parameters are sane and integers.
470         if ($width < 1 || $width > common_config('thumbnail', 'maxsize')
471                 || $height < 1 || $height > common_config('thumbnail', 'maxsize')) {
472             // Fail on bad width parameter. If this occurs, it's due to algorithm in ImageFile::getScalingValues
473             throw new ServerException('Bad thumbnail size parameters.');
474         }
475
476         $params = array('file_id'=> $this->id,
477                         'width'  => $width,
478                         'height' => $height);
479         $thumb = File_thumbnail::pkeyGet($params);
480         if ($thumb === null) {
481             // throws exception on failure to generate thumbnail
482             $thumb = $this->generateThumbnail($width, $height, $crop);
483         }
484         return $thumb;
485     }
486
487     /**
488      * Generate and store a thumbnail image for the uploaded file, if applicable.
489      * Call this only if you know what you're doing.
490      *
491      * @param $width  int    Maximum thumbnail width in pixels
492      * @param $height int    Maximum thumbnail height in pixels, if null, crop to $width
493      *
494      * @return File_thumbnail or null
495      */
496     protected function generateThumbnail($width, $height, $crop)
497     {
498         $width = intval($width);
499         if ($height === null) {
500             $height = $width;
501             $crop = true;
502         }
503
504         $image = ImageFile::fromFileObject($this);
505
506         list($width, $height, $x, $y, $w2, $h2) =
507                                 $image->scaleToFit($width, $height, $crop);
508
509         $outname = "thumb-{$width}x{$height}-" . $this->filename;
510         $outpath = self::path($outname);
511
512         $image->resizeTo($outpath, $width, $height, $x, $y, $w2, $h2);
513
514         // Avoid deleting the original
515         if ($image->getPath() != $this->getPath()) {
516             $image->unlink();
517         }
518         return File_thumbnail::saveThumbnail($this->id,
519                                       self::url($outname),
520                                       $width, $height);
521     }
522
523     public function getPath()
524     {
525         return self::path($this->filename);
526     }
527     public function getUrl()
528     {
529         return $this->url;
530     }
531
532     /**
533      * Blow the cache of notices that link to this URL
534      *
535      * @param boolean $last Whether to blow the "last" cache too
536      *
537      * @return void
538      */
539
540     function blowCache($last=false)
541     {
542         self::blow('file:notice-ids:%s', $this->url);
543         if ($last) {
544             self::blow('file:notice-ids:%s;last', $this->url);
545         }
546         self::blow('file:notice-count:%d', $this->id);
547     }
548
549     /**
550      * Stream of notices linking to this URL
551      *
552      * @param integer $offset   Offset to show; default is 0
553      * @param integer $limit    Limit of notices to show
554      * @param integer $since_id Since this notice
555      * @param integer $max_id   Before this notice
556      *
557      * @return array ids of notices that link to this file
558      */
559
560     function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
561     {
562         $stream = new FileNoticeStream($this);
563         return $stream->getNotices($offset, $limit, $since_id, $max_id);
564     }
565
566     function noticeCount()
567     {
568         $cacheKey = sprintf('file:notice-count:%d', $this->id);
569         
570         $count = self::cacheGet($cacheKey);
571
572         if ($count === false) {
573
574             $f2p = new File_to_post();
575
576             $f2p->file_id = $this->id;
577
578             $count = $f2p->count();
579
580             self::cacheSet($cacheKey, $count);
581         } 
582
583         return $count;
584     }
585 }