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