]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
Slight cleanup in typing and syntax of File and File_* classes
[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     ###START_AUTOCODE
28     /* the code below is auto generated do not remove the above tag */
29
30     public $__table = 'file';                            // table name
31     public $id;                              // int(4)  primary_key not_null
32     public $url;                             // varchar(255)  unique_key
33     public $mimetype;                        // varchar(50)
34     public $size;                            // int(4)
35     public $title;                           // varchar(255)
36     public $date;                            // int(4)
37     public $protected;                       // int(4)
38     public $filename;                        // varchar(255)
39     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
40
41     /* the code above is auto generated do not remove the tag below */
42     ###END_AUTOCODE
43
44     public static function schemaDef()
45     {
46         return array(
47             'fields' => array(
48                 'id' => array('type' => 'serial', 'not null' => true),
49                 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'destination URL after following redirections'),
50                 'mimetype' => array('type' => 'varchar', 'length' => 50, 'description' => 'mime type of resource'),
51                 'size' => array('type' => 'int', 'description' => 'size of resource when available'),
52                 'title' => array('type' => 'varchar', 'length' => 255, 'description' => 'title of resource when available'),
53                 'date' => array('type' => 'int', 'description' => 'date of resource according to http query'),
54                 'protected' => array('type' => 'int', 'description' => 'true when URL is private (needs login)'),
55                 'filename' => array('type' => 'varchar', 'length' => 255, 'description' => 'if a local file, name of the file'),
56
57                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
58             ),
59             'primary key' => array('id'),
60             'unique keys' => array(
61                 'file_url_key' => array('url'),
62             ),
63         );
64     }
65
66     function isProtected($url) {
67         return 'http://www.facebook.com/login.php' === $url;
68     }
69
70     /**
71      * Save a new file record.
72      *
73      * @param array $redir_data lookup data eg from File_redirection::where()
74      * @param string $given_url
75      * @return File
76      */
77     function saveNew(array $redir_data, $given_url) {
78
79         // I don't know why we have to keep doing this but I'm adding this last check to avoid
80         // uniqueness bugs.
81
82         $x = File::getKV('url', $given_url);
83         
84         if (!$x instanceof File) {
85             $x = new File;
86             $x->url = $given_url;
87             if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
88             if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
89             if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
90             if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
91             if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
92             $file_id = $x->insert();
93         }
94
95         $x->saveOembed($redir_data, $given_url);
96         return $x;
97     }
98
99     /**
100      * Save embedding information for this file, if applicable.
101      *
102      * Normally this won't need to be called manually, as File::saveNew()
103      * takes care of it.
104      *
105      * @param array $redir_data lookup data eg from File_redirection::where()
106      * @param string $given_url
107      * @return boolean success
108      */
109     public function saveOembed(array $redir_data, $given_url)
110     {
111         if (isset($redir_data['type'])
112                 && (('text/html' === substr($redir_data['type'], 0, 9)
113                 || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))) {
114             try {
115                 $oembed_data = File_oembed::_getOembed($given_url);
116             } catch (Exception $e) {
117                 return false;
118             }
119
120             $fo = File_oembed::getKV('file_id', $this->id);
121
122             if ($fo instanceof File_oembed) {
123                 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
124             } else {
125                 File_oembed::saveNew($oembed_data, $this->id);
126                 return true;
127             }
128         }
129         return false;
130     }
131
132     /**
133      * Go look at a URL and possibly save data about it if it's new:
134      * - follow redirect chains and store them in file_redirection
135      * - look up oEmbed data and save it in file_oembed
136      * - if a thumbnail is available, save it in file_thumbnail
137      * - save file record with basic info
138      * - optionally save a file_to_post record
139      * - return the File object with the full reference
140      *
141      * @fixme refactor this mess, it's gotten pretty scary.
142      * @param string $given_url the URL we're looking at
143      * @param int $notice_id (optional)
144      * @param bool $followRedirects defaults to true
145      *
146      * @return mixed File on success, -1 on some errors
147      *
148      * @throws ServerException on some errors
149      */
150     public function processNew($given_url, $notice_id=null, $followRedirects=true) {
151         if (empty($given_url)) return -1;   // error, no url to process
152         $given_url = File_redirection::_canonUrl($given_url);
153         if (empty($given_url)) return -1;   // error, no url to process
154         $file = File::getKV('url', $given_url);
155         if (empty($file)) {
156             $file_redir = File_redirection::getKV('url', $given_url);
157             if (empty($file_redir)) {
158                 // @fixme for new URLs this also looks up non-redirect data
159                 // such as target content type, size, etc, which we need
160                 // for File::saveNew(); so we call it even if not following
161                 // new redirects.
162                 $redir_data = File_redirection::where($given_url);
163                 if (is_array($redir_data)) {
164                     $redir_url = $redir_data['url'];
165                 } elseif (is_string($redir_data)) {
166                     $redir_url = $redir_data;
167                     $redir_data = array();
168                 } else {
169                     // TRANS: Server exception thrown when a URL cannot be processed.
170                     throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
171                 }
172                 // TODO: max field length
173                 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
174                     $x = File::saveNew($redir_data, $given_url);
175                     $file_id = $x->id;
176                 } else {
177                     // This seems kind of messed up... for now skipping this part
178                     // if we're already under a redirect, so we don't go into
179                     // horrible infinite loops if we've been given an unstable
180                     // redirect (where the final destination of the first request
181                     // doesn't match what we get when we ask for it again).
182                     //
183                     // Seen in the wild with clojure.org, which redirects through
184                     // wikispaces for auth and appends session data in the URL params.
185                     $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
186                     $file_id = $x->id;
187                     File_redirection::saveNew($redir_data, $file_id, $given_url);
188                 }
189             } else {
190                 $file_id = $file_redir->file_id;
191             }
192         } else {
193             $file_id = $file->id;
194             $x = $file;
195         }
196
197         if (empty($x)) {
198             $x = File::getKV('id', $file_id);
199             if (empty($x)) {
200                 // @todo FIXME: This could possibly be a clearer message :)
201                 // TRANS: Server exception thrown when... Robin thinks something is impossible!
202                 throw new ServerException(_('Robin thinks something is impossible.'));
203             }
204         }
205
206         if (!empty($notice_id)) {
207             File_to_post::processNew($file_id, $notice_id);
208         }
209         return $x;
210     }
211
212     public static function respectsQuota(Profile $scoped, $fileSize) {
213         if ($fileSize > common_config('attachments', 'file_quota')) {
214             // TRANS: Message used to be inserted as %2$s in  the text "No file may
215             // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
216             // TRANS: %1$d is the number of bytes of an uploaded file.
217             $fileSizeText = sprintf(_m('%1$d byte','%1$d bytes',$fileSize),$fileSize);
218
219             $fileQuota = common_config('attachments', 'file_quota');
220             // TRANS: Message given if an upload is larger than the configured maximum.
221             // TRANS: %1$d (used for plural) is the byte limit for uploads,
222             // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
223             // TRANS: gettext support multiple plurals in the same message, unfortunately...
224             throw new ClientException(
225                     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.',
226                               'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
227                               $fileQuota),
228                     $fileQuota, $fileSizeText));
229         }
230
231         $file = new File;
232
233         $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'";
234         $file->query($query);
235         $file->fetch();
236         $total = $file->total + $fileSize;
237         if ($total > common_config('attachments', 'user_quota')) {
238             // TRANS: Message given if an upload would exceed user quota.
239             // TRANS: %d (number) is the user quota in bytes and is used for plural.
240             throw new ClientException(
241                     sprintf(_m('A file this large would exceed your user quota of %d byte.',
242                               'A file this large would exceed your user quota of %d bytes.',
243                               common_config('attachments', 'user_quota')),
244                     common_config('attachments', 'user_quota')));
245         }
246         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
247         $file->query($query);
248         $file->fetch();
249         $total = $file->total + $fileSize;
250         if ($total > common_config('attachments', 'monthly_quota')) {
251             // TRANS: Message given id an upload would exceed a user's monthly quota.
252             // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
253             throw new ClientException(
254                     sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
255                               'A file this large would exceed your monthly quota of %d bytes.',
256                               common_config('attachments', 'monthly_quota')),
257                     common_config('attachments', 'monthly_quota')));
258         }
259         return true;
260     }
261
262     // where should the file go?
263
264     static function filename($profile, $basename, $mimetype)
265     {
266         require_once 'MIME/Type/Extension.php';
267
268         // We have to temporarily disable auto handling of PEAR errors...
269         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
270
271         $mte = new MIME_Type_Extension();
272         $ext = $mte->getExtension($mimetype);
273         if (PEAR::isError($ext)) {
274             $ext = strtolower(preg_replace('/\W/', '', $mimetype));
275         }
276
277         // Restore error handling.
278         PEAR::staticPopErrorHandling();
279
280         $nickname = $profile->nickname;
281         $datestamp = strftime('%Y%m%dT%H%M%S', time());
282         $random = strtolower(common_confirmation_code(32));
283         return "$nickname-$datestamp-$random.$ext";
284     }
285
286     /**
287      * Validation for as-saved base filenames
288      */
289     static function validFilename($filename)
290     {
291         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
292     }
293
294     /**
295      * @throws ClientException on invalid filename
296      */
297     static function path($filename)
298     {
299         if (!self::validFilename($filename)) {
300             // TRANS: Client exception thrown if a file upload does not have a valid name.
301             throw new ClientException(_("Invalid filename."));
302         }
303         $dir = common_config('attachments', 'dir');
304
305         if ($dir[strlen($dir)-1] != '/') {
306             $dir .= '/';
307         }
308
309         return $dir . $filename;
310     }
311
312     static function url($filename)
313     {
314         if (!self::validFilename($filename)) {
315             // TRANS: Client exception thrown if a file upload does not have a valid name.
316             throw new ClientException(_("Invalid filename."));
317         }
318
319         if (common_config('site','private')) {
320
321             return common_local_url('getfile',
322                                 array('filename' => $filename));
323
324         }
325
326         if (StatusNet::isHTTPS()) {
327
328             $sslserver = common_config('attachments', 'sslserver');
329
330             if (empty($sslserver)) {
331                 // XXX: this assumes that background dir == site dir + /file/
332                 // not true if there's another server
333                 if (is_string(common_config('site', 'sslserver')) &&
334                     mb_strlen(common_config('site', 'sslserver')) > 0) {
335                     $server = common_config('site', 'sslserver');
336                 } else if (common_config('site', 'server')) {
337                     $server = common_config('site', 'server');
338                 }
339                 $path = common_config('site', 'path') . '/file/';
340             } else {
341                 $server = $sslserver;
342                 $path   = common_config('attachments', 'sslpath');
343                 if (empty($path)) {
344                     $path = common_config('attachments', 'path');
345                 }
346             }
347
348             $protocol = 'https';
349         } else {
350             $path = common_config('attachments', 'path');
351             $server = common_config('attachments', 'server');
352
353             if (empty($server)) {
354                 $server = common_config('site', 'server');
355             }
356
357             $ssl = common_config('attachments', 'ssl');
358
359             $protocol = ($ssl) ? 'https' : 'http';
360         }
361
362         if ($path[strlen($path)-1] != '/') {
363             $path .= '/';
364         }
365
366         if ($path[0] != '/') {
367             $path = '/'.$path;
368         }
369
370         return $protocol.'://'.$server.$path.$filename;
371     }
372
373     function getEnclosure(){
374         $enclosure = (object) array();
375         $enclosure->title=$this->title;
376         $enclosure->url=$this->url;
377         $enclosure->title=$this->title;
378         $enclosure->date=$this->date;
379         $enclosure->modified=$this->modified;
380         $enclosure->size=$this->size;
381         $enclosure->mimetype=$this->mimetype;
382
383         if(! isset($this->filename)){
384             $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
385             $mimetype = $this->mimetype;
386             if($mimetype != null){
387                 $mimetype = strtolower($this->mimetype);
388             }
389             $semicolon = strpos($mimetype,';');
390             if($semicolon){
391                 $mimetype = substr($mimetype,0,$semicolon);
392             }
393             if(in_array($mimetype,$notEnclosureMimeTypes)){
394                 // Never treat generic HTML links as an enclosure type!
395                 // But if we have oEmbed info, we'll consider it golden.
396                 $oembed = File_oembed::getKV('file_id',$this->id);
397                 if($oembed && in_array($oembed->type, array('photo', 'video'))){
398                     $mimetype = strtolower($oembed->mimetype);
399                     $semicolon = strpos($mimetype,';');
400                     if($semicolon){
401                         $mimetype = substr($mimetype,0,$semicolon);
402                     }
403                     // @fixme uncertain if this is right.
404                     // we want to expose things like YouTube videos as
405                     // viewable attachments, but don't expose them as
406                     // downloadable enclosures.....?
407                     //if (in_array($mimetype, $notEnclosureMimeTypes)) {
408                     //    return false;
409                     //} else {
410                         if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
411                         if($oembed->url) $enclosure->url=$oembed->url;
412                         if($oembed->title) $enclosure->title=$oembed->title;
413                         if($oembed->modified) $enclosure->modified=$oembed->modified;
414                         unset($oembed->size);
415                     //}
416                 } else {
417                     return false;
418                 }
419             }
420         }
421         return $enclosure;
422     }
423
424     // quick back-compat hack, since there's still code using this
425     function isEnclosure()
426     {
427         $enclosure = $this->getEnclosure();
428         return !empty($enclosure);
429     }
430
431     /**
432      * Get the attachment's thumbnail record, if any.
433      *
434      * @return File_thumbnail
435      */
436     function getThumbnail()
437     {
438         return File_thumbnail::getKV('file_id', $this->id);
439     }
440
441     /**
442      * Blow the cache of notices that link to this URL
443      *
444      * @param boolean $last Whether to blow the "last" cache too
445      *
446      * @return void
447      */
448
449     function blowCache($last=false)
450     {
451         self::blow('file:notice-ids:%s', $this->url);
452         if ($last) {
453             self::blow('file:notice-ids:%s;last', $this->url);
454         }
455         self::blow('file:notice-count:%d', $this->id);
456     }
457
458     /**
459      * Stream of notices linking to this URL
460      *
461      * @param integer $offset   Offset to show; default is 0
462      * @param integer $limit    Limit of notices to show
463      * @param integer $since_id Since this notice
464      * @param integer $max_id   Before this notice
465      *
466      * @return array ids of notices that link to this file
467      */
468
469     function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
470     {
471         $stream = new FileNoticeStream($this);
472         return $stream->getNotices($offset, $limit, $since_id, $max_id);
473     }
474
475     function noticeCount()
476     {
477         $cacheKey = sprintf('file:notice-count:%d', $this->id);
478         
479         $count = self::cacheGet($cacheKey);
480
481         if ($count === false) {
482
483             $f2p = new File_to_post();
484
485             $f2p->file_id = $this->id;
486
487             $count = $f2p->count();
488
489             self::cacheSet($cacheKey, $count);
490         } 
491
492         return $count;
493     }
494 }