]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
ba8332841409f936c5c3e28ad615fef34e479151
[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     function processNew($given_url, $notice_id=null) {
120         if (empty($given_url)) return -1;   // error, no url to process
121         $given_url = File_redirection::_canonUrl($given_url);
122         if (empty($given_url)) return -1;   // error, no url to process
123         $file = File::staticGet('url', $given_url);
124         if (empty($file)) {
125             $file_redir = File_redirection::staticGet('url', $given_url);
126             if (empty($file_redir)) {
127                 $redir_data = File_redirection::where($given_url);
128                 if (is_array($redir_data)) {
129                     $redir_url = $redir_data['url'];
130                 } elseif (is_string($redir_data)) {
131                     $redir_url = $redir_data;
132                     $redir_data = array();
133                 } else {
134                     throw new ServerException("Can't process url '$given_url'");
135                 }
136                 // TODO: max field length
137                 if ($redir_url === $given_url || strlen($redir_url) > 255) {
138                     $x = File::saveNew($redir_data, $given_url);
139                     $file_id = $x->id;
140                 } else {
141                     $x = File::processNew($redir_url, $notice_id);
142                     $file_id = $x->id;
143                     File_redirection::saveNew($redir_data, $file_id, $given_url);
144                 }
145             } else {
146                 $file_id = $file_redir->file_id;
147             }
148         } else {
149             $file_id = $file->id;
150             $x = $file;
151         }
152
153         if (empty($x)) {
154             $x = File::staticGet($file_id);
155             if (empty($x)) {
156                 throw new ServerException("Robin thinks something is impossible.");
157             }
158         }
159
160         if (!empty($notice_id)) {
161             File_to_post::processNew($file_id, $notice_id);
162         }
163         return $x;
164     }
165
166     function isRespectsQuota($user,$fileSize) {
167
168         if ($fileSize > common_config('attachments', 'file_quota')) {
169             return sprintf(_('No file may be larger than %d bytes ' .
170                              'and the file you sent was %d bytes. Try to upload a smaller version.'),
171                            common_config('attachments', 'file_quota'), $fileSize);
172         }
173
174         $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'";
175         $this->query($query);
176         $this->fetch();
177         $total = $this->total + $fileSize;
178         if ($total > common_config('attachments', 'user_quota')) {
179             return sprintf(_('A file this large would exceed your user quota of %d bytes.'), common_config('attachments', 'user_quota'));
180         }
181         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
182         $this->query($query);
183         $this->fetch();
184         $total = $this->total + $fileSize;
185         if ($total > common_config('attachments', 'monthly_quota')) {
186             return sprintf(_('A file this large would exceed your monthly quota of %d bytes.'), common_config('attachments', 'monthly_quota'));
187         }
188         return true;
189     }
190
191     // where should the file go?
192
193     static function filename($profile, $basename, $mimetype)
194     {
195         require_once 'MIME/Type/Extension.php';
196         $mte = new MIME_Type_Extension();
197         $ext = $mte->getExtension($mimetype);
198         $nickname = $profile->nickname;
199         $datestamp = strftime('%Y%m%dT%H%M%S', time());
200         $random = strtolower(common_confirmation_code(32));
201         return "$nickname-$datestamp-$random.$ext";
202     }
203
204     /**
205      * Validation for as-saved base filenames
206      */
207     static function validFilename($filename)
208     {
209         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
210     }
211
212     /**
213      * @throws ClientException on invalid filename
214      */
215     static function path($filename)
216     {
217         if (!self::validFilename($filename)) {
218             throw new ClientException("Invalid filename");
219         }
220         $dir = common_config('attachments', 'dir');
221
222         if ($dir[strlen($dir)-1] != '/') {
223             $dir .= '/';
224         }
225
226         return $dir . $filename;
227     }
228
229     static function url($filename)
230     {
231         if (!self::validFilename($filename)) {
232             throw new ClientException("Invalid filename");
233         }
234         if(common_config('site','private')) {
235
236             return common_local_url('getfile',
237                                 array('filename' => $filename));
238
239         } else {
240             $path = common_config('attachments', 'path');
241
242             if ($path[strlen($path)-1] != '/') {
243                 $path .= '/';
244             }
245
246             if ($path[0] != '/') {
247                 $path = '/'.$path;
248             }
249
250             $server = common_config('attachments', 'server');
251
252             if (empty($server)) {
253                 $server = common_config('site', 'server');
254             }
255
256             $ssl = common_config('attachments', 'ssl');
257
258             if (is_null($ssl)) { // null -> guess
259                 if (common_config('site', 'ssl') == 'always' &&
260                     !common_config('attachments', 'server')) {
261                     $ssl = true;
262                 } else {
263                     $ssl = false;
264                 }
265             }
266
267             $protocol = ($ssl) ? 'https' : 'http';
268
269             return $protocol.'://'.$server.$path.$filename;
270         }
271     }
272
273     function getEnclosure(){
274         $enclosure = (object) array();
275         $enclosure->title=$this->title;
276         $enclosure->url=$this->url;
277         $enclosure->title=$this->title;
278         $enclosure->date=$this->date;
279         $enclosure->modified=$this->modified;
280         $enclosure->size=$this->size;
281         $enclosure->mimetype=$this->mimetype;
282
283         if(! isset($this->filename)){
284             $notEnclosureMimeTypes = array('text/html','application/xhtml+xml');
285             $mimetype = strtolower($this->mimetype);
286             $semicolon = strpos($mimetype,';');
287             if($semicolon){
288                 $mimetype = substr($mimetype,0,$semicolon);
289             }
290             if(in_array($mimetype,$notEnclosureMimeTypes)){
291                 $oembed = File_oembed::staticGet('file_id',$this->id);
292                 if($oembed){
293                     $mimetype = strtolower($oembed->mimetype);
294                     $semicolon = strpos($mimetype,';');
295                     if($semicolon){
296                         $mimetype = substr($mimetype,0,$semicolon);
297                     }
298                     if(in_array($mimetype,$notEnclosureMimeTypes)){
299                         return false;
300                     }else{
301                         if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
302                         if($oembed->url) $enclosure->url=$oembed->url;
303                         if($oembed->title) $enclosure->title=$oembed->title;
304                         if($oembed->modified) $enclosure->modified=$oembed->modified;
305                         unset($oembed->size);
306                     }
307                 } else {
308                     return false;
309                 }
310             }
311         }
312         return $enclosure;
313     }
314
315     // quick back-compat hack, since there's still code using this
316     function isEnclosure()
317     {
318         $enclosure = $this->getEnclosure();
319         return !empty($enclosure);
320     }
321 }
322