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