]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
* i18n/L10n and translator documentation updates.
[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     function getAttachments($post_id) {
59         $query = "select file.* from file join file_to_post on (file_id = file.id) join notice on (post_id = notice.id) where post_id = " . $this->escape($post_id);
60         $this->query($query);
61         $att = array();
62         while ($this->fetch()) {
63             $att[] = clone($this);
64         }
65         $this->free();
66         return $att;
67     }
68
69     /**
70      * Save a new file record.
71      *
72      * @param array $redir_data lookup data eg from File_redirection::where()
73      * @param string $given_url
74      * @return File
75      */
76     function saveNew(array $redir_data, $given_url) {
77         $x = new File;
78         $x->url = $given_url;
79         if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
80         if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
81         if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
82         if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
83         if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
84         $file_id = $x->insert();
85
86         $x->saveOembed($redir_data, $given_url);
87         return $x;
88     }
89
90     /**
91      * Save embedding information for this file, if applicable.
92      *
93      * Normally this won't need to be called manually, as File::saveNew()
94      * takes care of it.
95      *
96      * @param array $redir_data lookup data eg from File_redirection::where()
97      * @param string $given_url
98      * @return boolean success
99      */
100     public function saveOembed($redir_data, $given_url)
101     {
102         if (isset($redir_data['type'])
103             && (('text/html' === substr($redir_data['type'], 0, 9) || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))
104             && ($oembed_data = File_oembed::_getOembed($given_url))) {
105
106             $fo = File_oembed::staticGet('file_id', $this->id);
107
108             if (empty($fo)) {
109                 File_oembed::saveNew($oembed_data, $this->id);
110                 return true;
111             } else {
112                 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
113             }
114         }
115         return false;
116     }
117
118     /**
119      * @fixme refactor this mess, it's gotten pretty scary.
120      * @param bool $followRedirects
121      */
122     function processNew($given_url, $notice_id=null, $followRedirects=true) {
123         if (empty($given_url)) return -1;   // error, no url to process
124         $given_url = File_redirection::_canonUrl($given_url);
125         if (empty($given_url)) return -1;   // error, no url to process
126         $file = File::staticGet('url', $given_url);
127         if (empty($file)) {
128             $file_redir = File_redirection::staticGet('url', $given_url);
129             if (empty($file_redir)) {
130                 // @fixme for new URLs this also looks up non-redirect data
131                 // such as target content type, size, etc, which we need
132                 // for File::saveNew(); so we call it even if not following
133                 // new redirects.
134                 $redir_data = File_redirection::where($given_url);
135                 if (is_array($redir_data)) {
136                     $redir_url = $redir_data['url'];
137                 } elseif (is_string($redir_data)) {
138                     $redir_url = $redir_data;
139                     $redir_data = array();
140                 } else {
141                     // TRANS: Server exception thrown when a URL cannot be processed.
142                     throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
143                 }
144                 // TODO: max field length
145                 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
146                     $x = File::saveNew($redir_data, $given_url);
147                     $file_id = $x->id;
148                 } else {
149                     // This seems kind of messed up... for now skipping this part
150                     // if we're already under a redirect, so we don't go into
151                     // horrible infinite loops if we've been given an unstable
152                     // redirect (where the final destination of the first request
153                     // doesn't match what we get when we ask for it again).
154                     //
155                     // Seen in the wild with clojure.org, which redirects through
156                     // wikispaces for auth and appends session data in the URL params.
157                     $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
158                     $file_id = $x->id;
159                     File_redirection::saveNew($redir_data, $file_id, $given_url);
160                 }
161             } else {
162                 $file_id = $file_redir->file_id;
163             }
164         } else {
165             $file_id = $file->id;
166             $x = $file;
167         }
168
169         if (empty($x)) {
170             $x = File::staticGet($file_id);
171             if (empty($x)) {
172                 // FIXME: This could possibly be a clearer message :)
173                 // TRANS: Server exception thrown when... Robin thinks something is impossible!
174                 throw new ServerException(_("Robin thinks something is impossible."));
175             }
176         }
177
178         if (!empty($notice_id)) {
179             File_to_post::processNew($file_id, $notice_id);
180         }
181         return $x;
182     }
183
184     function isRespectsQuota($user,$fileSize) {
185
186         if ($fileSize > common_config('attachments', 'file_quota')) {
187             // TRANS: Message given if an upload is larger than the configured maximum.
188             // TRANS: %1$d is the byte limit for uploads, %2$d is the byte count for the uploaded file.
189             return sprintf(_('No file may be larger than %1$d bytes ' .
190                              'and the file you sent was %2$d bytes. Try to upload a smaller version.'),
191                            common_config('attachments', 'file_quota'), $fileSize);
192         }
193
194         $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'";
195         $this->query($query);
196         $this->fetch();
197         $total = $this->total + $fileSize;
198         if ($total > common_config('attachments', 'user_quota')) {
199             // TRANS: Message given if an upload would exceed user quota.
200             // TRANS: %d (number) is the user quota in bytes.
201             return sprintf(_('A file this large would exceed your user quota of %d bytes.'), common_config('attachments', 'user_quota'));
202         }
203         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
204         $this->query($query);
205         $this->fetch();
206         $total = $this->total + $fileSize;
207         if ($total > common_config('attachments', 'monthly_quota')) {
208             // TRANS: Message given id an upload would exceed a user's monthly quota.
209             // TRANS: $d (number) is the monthly user quota in bytes.
210             return sprintf(_('A file this large would exceed your monthly quota of %d bytes.'), common_config('attachments', 'monthly_quota'));
211         }
212         return true;
213     }
214
215     // where should the file go?
216
217     static function filename($profile, $basename, $mimetype)
218     {
219         require_once 'MIME/Type/Extension.php';
220         $mte = new MIME_Type_Extension();
221         try {
222             $ext = $mte->getExtension($mimetype);
223         } catch ( Exception $e) {
224             $ext = strtolower(preg_replace('/\W/', '', $mimetype));
225         }
226         $nickname = $profile->nickname;
227         $datestamp = strftime('%Y%m%dT%H%M%S', time());
228         $random = strtolower(common_confirmation_code(32));
229         return "$nickname-$datestamp-$random.$ext";
230     }
231
232     /**
233      * Validation for as-saved base filenames
234      */
235     static function validFilename($filename)
236     {
237         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
238     }
239
240     /**
241      * @throws ClientException on invalid filename
242      */
243     static function path($filename)
244     {
245         if (!self::validFilename($filename)) {
246             // TRANS: Client exception thrown if a file upload does not have a valid name.
247             throw new ClientException(_("Invalid filename."));
248         }
249         $dir = common_config('attachments', 'dir');
250
251         if ($dir[strlen($dir)-1] != '/') {
252             $dir .= '/';
253         }
254
255         return $dir . $filename;
256     }
257
258     static function url($filename)
259     {
260         if (!self::validFilename($filename)) {
261             // TRANS: Client exception thrown if a file upload does not have a valid name.
262             throw new ClientException(_("Invalid filename."));
263         }
264         if(common_config('site','private')) {
265
266             return common_local_url('getfile',
267                                 array('filename' => $filename));
268
269         } else {
270             $path = common_config('attachments', 'path');
271
272             if ($path[strlen($path)-1] != '/') {
273                 $path .= '/';
274             }
275
276             if ($path[0] != '/') {
277                 $path = '/'.$path;
278             }
279
280             $server = common_config('attachments', 'server');
281
282             if (empty($server)) {
283                 $server = common_config('site', 'server');
284             }
285
286             $ssl = common_config('attachments', 'ssl');
287
288             if (is_null($ssl)) { // null -> guess
289                 if (common_config('site', 'ssl') == 'always' &&
290                     !common_config('attachments', 'server')) {
291                     $ssl = true;
292                 } else {
293                     $ssl = false;
294                 }
295             }
296
297             $protocol = ($ssl) ? 'https' : 'http';
298
299             return $protocol.'://'.$server.$path.$filename;
300         }
301     }
302
303     function getEnclosure(){
304         $enclosure = (object) array();
305         $enclosure->title=$this->title;
306         $enclosure->url=$this->url;
307         $enclosure->title=$this->title;
308         $enclosure->date=$this->date;
309         $enclosure->modified=$this->modified;
310         $enclosure->size=$this->size;
311         $enclosure->mimetype=$this->mimetype;
312
313         if(! isset($this->filename)){
314             $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
315             $mimetype = $this->mimetype;
316             if($mimetype != null){
317                 $mimetype = strtolower($this->mimetype);
318             }
319             $semicolon = strpos($mimetype,';');
320             if($semicolon){
321                 $mimetype = substr($mimetype,0,$semicolon);
322             }
323             if(in_array($mimetype,$notEnclosureMimeTypes)){
324                 $oembed = File_oembed::staticGet('file_id',$this->id);
325                 if($oembed){
326                     $mimetype = strtolower($oembed->mimetype);
327                     $semicolon = strpos($mimetype,';');
328                     if($semicolon){
329                         $mimetype = substr($mimetype,0,$semicolon);
330                     }
331                     if(in_array($mimetype,$notEnclosureMimeTypes)){
332                         return false;
333                     }else{
334                         if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
335                         if($oembed->url) $enclosure->url=$oembed->url;
336                         if($oembed->title) $enclosure->title=$oembed->title;
337                         if($oembed->modified) $enclosure->modified=$oembed->modified;
338                         unset($oembed->size);
339                     }
340                 } else {
341                     return false;
342                 }
343             }
344         }
345         return $enclosure;
346     }
347
348     // quick back-compat hack, since there's still code using this
349     function isEnclosure()
350     {
351         $enclosure = $this->getEnclosure();
352         return !empty($enclosure);
353     }
354 }