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