]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
Merge branch 'testing' of gitorious.org:statusnet/mainline into 0.9.x
[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
33 class File extends Memcached_DataObject
34 {
35     ###START_AUTOCODE
36     /* the code below is auto generated do not remove the above tag */
37
38     public $__table = 'file';                            // table name
39     public $id;                              // int(4)  primary_key not_null
40     public $url;                             // varchar(255)  unique_key
41     public $mimetype;                        // varchar(50)
42     public $size;                            // int(4)
43     public $title;                           // varchar(255)
44     public $date;                            // int(4)
45     public $protected;                       // int(4)
46     public $filename;                        // varchar(255)
47     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
48
49     /* Static get */
50     function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('File',$k,$v); }
51
52     /* the code above is auto generated do not remove the tag below */
53     ###END_AUTOCODE
54
55     function isProtected($url) {
56         return 'http://www.facebook.com/login.php' === $url;
57     }
58
59     function getAttachments($post_id) {
60         $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);
61         $this->query($query);
62         $att = array();
63         while ($this->fetch()) {
64             $att[] = clone($this);
65         }
66         $this->free();
67         return $att;
68     }
69
70     /**
71      * Save a new file record.
72      *
73      * @param array $redir_data lookup data eg from File_redirection::where()
74      * @param string $given_url
75      * @return File
76      */
77     function saveNew(array $redir_data, $given_url) {
78         $x = new File;
79         $x->url = $given_url;
80         if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
81         if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
82         if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
83         if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
84         if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
85         $file_id = $x->insert();
86
87         $x->saveOembed($redir_data, $given_url);
88         return $x;
89     }
90
91     /**
92      * Save embedding information for this file, if applicable.
93      *
94      * Normally this won't need to be called manually, as File::saveNew()
95      * takes care of it.
96      *
97      * @param array $redir_data lookup data eg from File_redirection::where()
98      * @param string $given_url
99      * @return boolean success
100      */
101     public function saveOembed($redir_data, $given_url)
102     {
103         if (isset($redir_data['type'])
104             && (('text/html' === substr($redir_data['type'], 0, 9) || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))
105             && ($oembed_data = File_oembed::_getOembed($given_url))) {
106
107             $fo = File_oembed::staticGet('file_id', $this->id);
108
109             if (empty($fo)) {
110                 File_oembed::saveNew($oembed_data, $this->id);
111                 return true;
112             } else {
113                 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
114             }
115         }
116         return false;
117     }
118
119     /**
120      * @fixme refactor this mess, it's gotten pretty scary.
121      * @param bool $followRedirects
122      */
123     function processNew($given_url, $notice_id=null, $followRedirects=true) {
124         if (empty($given_url)) return -1;   // error, no url to process
125         $given_url = File_redirection::_canonUrl($given_url);
126         if (empty($given_url)) return -1;   // error, no url to process
127         $file = File::staticGet('url', $given_url);
128         if (empty($file)) {
129             $file_redir = File_redirection::staticGet('url', $given_url);
130             if (empty($file_redir)) {
131                 // @fixme for new URLs this also looks up non-redirect data
132                 // such as target content type, size, etc, which we need
133                 // for File::saveNew(); so we call it even if not following
134                 // new redirects.
135                 $redir_data = File_redirection::where($given_url);
136                 if (is_array($redir_data)) {
137                     $redir_url = $redir_data['url'];
138                 } elseif (is_string($redir_data)) {
139                     $redir_url = $redir_data;
140                     $redir_data = array();
141                 } else {
142                     throw new ServerException("Can't process url '$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                 throw new ServerException("Robin thinks something is impossible.");
173             }
174         }
175
176         if (!empty($notice_id)) {
177             File_to_post::processNew($file_id, $notice_id);
178         }
179         return $x;
180     }
181
182     function isRespectsQuota($user,$fileSize) {
183
184         if ($fileSize > common_config('attachments', 'file_quota')) {
185             return sprintf(_('No file may be larger than %d bytes ' .
186                              'and the file you sent was %d bytes. Try to upload a smaller version.'),
187                            common_config('attachments', 'file_quota'), $fileSize);
188         }
189
190         $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'";
191         $this->query($query);
192         $this->fetch();
193         $total = $this->total + $fileSize;
194         if ($total > common_config('attachments', 'user_quota')) {
195             return sprintf(_('A file this large would exceed your user quota of %d bytes.'), common_config('attachments', 'user_quota'));
196         }
197         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
198         $this->query($query);
199         $this->fetch();
200         $total = $this->total + $fileSize;
201         if ($total > common_config('attachments', 'monthly_quota')) {
202             return sprintf(_('A file this large would exceed your monthly quota of %d bytes.'), common_config('attachments', 'monthly_quota'));
203         }
204         return true;
205     }
206
207     // where should the file go?
208
209     static function filename($profile, $basename, $mimetype)
210     {
211         require_once 'MIME/Type/Extension.php';
212         $mte = new MIME_Type_Extension();
213         try {
214             $ext = $mte->getExtension($mimetype);
215         } catch ( Exception $e) {
216             $ext = strtolower(preg_replace('/\W/', '', $mimetype));
217         }
218         $nickname = $profile->nickname;
219         $datestamp = strftime('%Y%m%dT%H%M%S', time());
220         $random = strtolower(common_confirmation_code(32));
221         return "$nickname-$datestamp-$random.$ext";
222     }
223
224     /**
225      * Validation for as-saved base filenames
226      */
227     static function validFilename($filename)
228     {
229         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
230     }
231
232     /**
233      * @throws ClientException on invalid filename
234      */
235     static function path($filename)
236     {
237         if (!self::validFilename($filename)) {
238             throw new ClientException("Invalid filename");
239         }
240         $dir = common_config('attachments', 'dir');
241
242         if ($dir[strlen($dir)-1] != '/') {
243             $dir .= '/';
244         }
245
246         return $dir . $filename;
247     }
248
249     static function url($filename)
250     {
251         if (!self::validFilename($filename)) {
252             throw new ClientException("Invalid filename");
253         }
254         if(common_config('site','private')) {
255
256             return common_local_url('getfile',
257                                 array('filename' => $filename));
258
259         } else {
260             $path = common_config('attachments', 'path');
261
262             if ($path[strlen($path)-1] != '/') {
263                 $path .= '/';
264             }
265
266             if ($path[0] != '/') {
267                 $path = '/'.$path;
268             }
269
270             $server = common_config('attachments', 'server');
271
272             if (empty($server)) {
273                 $server = common_config('site', 'server');
274             }
275
276             $ssl = common_config('attachments', 'ssl');
277
278             if (is_null($ssl)) { // null -> guess
279                 if (common_config('site', 'ssl') == 'always' &&
280                     !common_config('attachments', 'server')) {
281                     $ssl = true;
282                 } else {
283                     $ssl = false;
284                 }
285             }
286
287             $protocol = ($ssl) ? 'https' : 'http';
288
289             return $protocol.'://'.$server.$path.$filename;
290         }
291     }
292
293     function getEnclosure(){
294         $enclosure = (object) array();
295         $enclosure->title=$this->title;
296         $enclosure->url=$this->url;
297         $enclosure->title=$this->title;
298         $enclosure->date=$this->date;
299         $enclosure->modified=$this->modified;
300         $enclosure->size=$this->size;
301         $enclosure->mimetype=$this->mimetype;
302
303         if(! isset($this->filename)){
304             $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
305             if($mimetype != null){
306                 $mimetype = strtolower($this->mimetype);
307             }
308             $semicolon = strpos($mimetype,';');
309             if($semicolon){
310                 $mimetype = substr($mimetype,0,$semicolon);
311             }
312             if(in_array($mimetype,$notEnclosureMimeTypes)){
313                 $oembed = File_oembed::staticGet('file_id',$this->id);
314                 if($oembed){
315                     $mimetype = strtolower($oembed->mimetype);
316                     $semicolon = strpos($mimetype,';');
317                     if($semicolon){
318                         $mimetype = substr($mimetype,0,$semicolon);
319                     }
320                     if(in_array($mimetype,$notEnclosureMimeTypes)){
321                         return false;
322                     }else{
323                         if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
324                         if($oembed->url) $enclosure->url=$oembed->url;
325                         if($oembed->title) $enclosure->title=$oembed->title;
326                         if($oembed->modified) $enclosure->modified=$oembed->modified;
327                         unset($oembed->size);
328                     }
329                 } else {
330                     return false;
331                 }
332             }
333         }
334         return $enclosure;
335     }
336
337     // quick back-compat hack, since there's still code using this
338     function isEnclosure()
339     {
340         $enclosure = $this->getEnclosure();
341         return !empty($enclosure);
342     }
343 }
344