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