]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
Merge branch 'testing' of git@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     function saveNew($redir_data, $given_url) {
71         $x = new File;
72         $x->url = $given_url;
73         if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
74         if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
75         if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
76         if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
77         if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
78         $file_id = $x->insert();
79
80         if (isset($redir_data['type'])
81             && (('text/html' === substr($redir_data['type'], 0, 9) || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))
82             && ($oembed_data = File_oembed::_getOembed($given_url))) {
83
84             $fo = File_oembed::staticGet('file_id', $file_id);
85
86             if (empty($fo)) {
87                 File_oembed::saveNew($oembed_data, $file_id);
88             } else {
89                 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
90             }
91         }
92         return $x;
93     }
94
95     function processNew($given_url, $notice_id=null) {
96         if (empty($given_url)) return -1;   // error, no url to process
97         $given_url = File_redirection::_canonUrl($given_url);
98         if (empty($given_url)) return -1;   // error, no url to process
99         $file = File::staticGet('url', $given_url);
100         if (empty($file)) {
101             $file_redir = File_redirection::staticGet('url', $given_url);
102             if (empty($file_redir)) {
103                 $redir_data = File_redirection::where($given_url);
104                 if (is_array($redir_data)) {
105                     $redir_url = $redir_data['url'];
106                 } elseif (is_string($redir_data)) {
107                     $redir_url = $redir_data;
108                 } else {
109                     throw new ServerException("Can't process url '$given_url'");
110                 }
111                 // TODO: max field length
112                 if ($redir_url === $given_url || strlen($redir_url) > 255) {
113                     $x = File::saveNew($redir_data, $given_url);
114                     $file_id = $x->id;
115                 } else {
116                     $x = File::processNew($redir_url, $notice_id);
117                     $file_id = $x->id;
118                     File_redirection::saveNew($redir_data, $file_id, $given_url);
119                 }
120             } else {
121                 $file_id = $file_redir->file_id;
122             }
123         } else {
124             $file_id = $file->id;
125             $x = $file;
126         }
127
128         if (empty($x)) {
129             $x = File::staticGet($file_id);
130             if (empty($x)) {
131                 throw new ServerException("Robin thinks something is impossible.");
132             }
133         }
134
135         if (!empty($notice_id)) {
136             File_to_post::processNew($file_id, $notice_id);
137         }
138         return $x;
139     }
140
141     function isRespectsQuota($user,$fileSize) {
142
143         if ($fileSize > common_config('attachments', 'file_quota')) {
144             return sprintf(_('No file may be larger than %d bytes ' .
145                              'and the file you sent was %d bytes. Try to upload a smaller version.'),
146                            common_config('attachments', 'file_quota'), $fileSize);
147         }
148
149         $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'";
150         $this->query($query);
151         $this->fetch();
152         $total = $this->total + $fileSize;
153         if ($total > common_config('attachments', 'user_quota')) {
154             return sprintf(_('A file this large would exceed your user quota of %d bytes.'), common_config('attachments', 'user_quota'));
155         }
156         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
157         $this->query($query);
158         $this->fetch();
159         $total = $this->total + $fileSize;
160         if ($total > common_config('attachments', 'monthly_quota')) {
161             return sprintf(_('A file this large would exceed your monthly quota of %d bytes.'), common_config('attachments', 'monthly_quota'));
162         }
163         return true;
164     }
165
166     // where should the file go?
167
168     static function filename($profile, $basename, $mimetype)
169     {
170         require_once 'MIME/Type/Extension.php';
171         $mte = new MIME_Type_Extension();
172         try {
173             $ext = $mte->getExtension($mimetype);
174         } catch ( Exception $e) {
175             $ext = strtolower(preg_replace('/\W/', '', $mimetype));
176         }
177         $nickname = $profile->nickname;
178         $datestamp = strftime('%Y%m%dT%H%M%S', time());
179         $random = strtolower(common_confirmation_code(32));
180         return "$nickname-$datestamp-$random.$ext";
181     }
182
183     /**
184      * Validation for as-saved base filenames
185      */
186     static function validFilename($filename)
187     {
188         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
189     }
190
191     /**
192      * @throws ClientException on invalid filename
193      */
194     static function path($filename)
195     {
196         if (!self::validFilename($filename)) {
197             throw new ClientException("Invalid filename");
198         }
199         $dir = common_config('attachments', 'dir');
200
201         if ($dir[strlen($dir)-1] != '/') {
202             $dir .= '/';
203         }
204
205         return $dir . $filename;
206     }
207
208     static function url($filename)
209     {
210         if (!self::validFilename($filename)) {
211             throw new ClientException("Invalid filename");
212         }
213         if(common_config('site','private')) {
214
215             return common_local_url('getfile',
216                                 array('filename' => $filename));
217
218         } else {
219             $path = common_config('attachments', 'path');
220
221             if ($path[strlen($path)-1] != '/') {
222                 $path .= '/';
223             }
224
225             if ($path[0] != '/') {
226                 $path = '/'.$path;
227             }
228
229             $server = common_config('attachments', 'server');
230
231             if (empty($server)) {
232                 $server = common_config('site', 'server');
233             }
234
235             $ssl = common_config('attachments', 'ssl');
236
237             if (is_null($ssl)) { // null -> guess
238                 if (common_config('site', 'ssl') == 'always' &&
239                     !common_config('attachments', 'server')) {
240                     $ssl = true;
241                 } else {
242                     $ssl = false;
243                 }
244             }
245
246             $protocol = ($ssl) ? 'https' : 'http';
247
248             return $protocol.'://'.$server.$path.$filename;
249         }
250     }
251
252     function getEnclosure(){
253         $enclosure = (object) array();
254         $enclosure->title=$this->title;
255         $enclosure->url=$this->url;
256         $enclosure->title=$this->title;
257         $enclosure->date=$this->date;
258         $enclosure->modified=$this->modified;
259         $enclosure->size=$this->size;
260         $enclosure->mimetype=$this->mimetype;
261
262         if(! isset($this->filename)){
263             $notEnclosureMimeTypes = array('text/html','application/xhtml+xml');
264             $mimetype = strtolower($this->mimetype);
265             $semicolon = strpos($mimetype,';');
266             if($semicolon){
267                 $mimetype = substr($mimetype,0,$semicolon);
268             }
269             if(in_array($mimetype,$notEnclosureMimeTypes)){
270                 $oembed = File_oembed::staticGet('file_id',$this->id);
271                 if($oembed){
272                     $mimetype = strtolower($oembed->mimetype);
273                     $semicolon = strpos($mimetype,';');
274                     if($semicolon){
275                         $mimetype = substr($mimetype,0,$semicolon);
276                     }
277                     if(in_array($mimetype,$notEnclosureMimeTypes)){
278                         return false;
279                     }else{
280                         if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
281                         if($oembed->url) $enclosure->url=$oembed->url;
282                         if($oembed->title) $enclosure->title=$oembed->title;
283                         if($oembed->modified) $enclosure->modified=$oembed->modified;
284                         unset($oembed->size);
285                     }
286                 } else {
287                     return false;
288                 }
289             }
290         }
291         return $enclosure;
292     }
293 }
294