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