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