]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
static method for getting best URL shortening service
[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         try {
198             $ext = $mte->getExtension($mimetype);
199         } catch ( Exception $e) {
200             $ext = strtolower(preg_replace('/\W/', '', $mimetype));
201         }
202         $nickname = $profile->nickname;
203         $datestamp = strftime('%Y%m%dT%H%M%S', time());
204         $random = strtolower(common_confirmation_code(32));
205         return "$nickname-$datestamp-$random.$ext";
206     }
207
208     /**
209      * Validation for as-saved base filenames
210      */
211     static function validFilename($filename)
212     {
213         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
214     }
215
216     /**
217      * @throws ClientException on invalid filename
218      */
219     static function path($filename)
220     {
221         if (!self::validFilename($filename)) {
222             throw new ClientException("Invalid filename");
223         }
224         $dir = common_config('attachments', 'dir');
225
226         if ($dir[strlen($dir)-1] != '/') {
227             $dir .= '/';
228         }
229
230         return $dir . $filename;
231     }
232
233     static function url($filename)
234     {
235         if (!self::validFilename($filename)) {
236             throw new ClientException("Invalid filename");
237         }
238         if(common_config('site','private')) {
239
240             return common_local_url('getfile',
241                                 array('filename' => $filename));
242
243         } else {
244             $path = common_config('attachments', 'path');
245
246             if ($path[strlen($path)-1] != '/') {
247                 $path .= '/';
248             }
249
250             if ($path[0] != '/') {
251                 $path = '/'.$path;
252             }
253
254             $server = common_config('attachments', 'server');
255
256             if (empty($server)) {
257                 $server = common_config('site', 'server');
258             }
259
260             $ssl = common_config('attachments', 'ssl');
261
262             if (is_null($ssl)) { // null -> guess
263                 if (common_config('site', 'ssl') == 'always' &&
264                     !common_config('attachments', 'server')) {
265                     $ssl = true;
266                 } else {
267                     $ssl = false;
268                 }
269             }
270
271             $protocol = ($ssl) ? 'https' : 'http';
272
273             return $protocol.'://'.$server.$path.$filename;
274         }
275     }
276
277     function getEnclosure(){
278         $enclosure = (object) array();
279         $enclosure->title=$this->title;
280         $enclosure->url=$this->url;
281         $enclosure->title=$this->title;
282         $enclosure->date=$this->date;
283         $enclosure->modified=$this->modified;
284         $enclosure->size=$this->size;
285         $enclosure->mimetype=$this->mimetype;
286
287         if(! isset($this->filename)){
288             $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
289             if($mimetype != null){
290                 $mimetype = strtolower($this->mimetype);
291             }
292             $semicolon = strpos($mimetype,';');
293             if($semicolon){
294                 $mimetype = substr($mimetype,0,$semicolon);
295             }
296             if(in_array($mimetype,$notEnclosureMimeTypes)){
297                 $oembed = File_oembed::staticGet('file_id',$this->id);
298                 if($oembed){
299                     $mimetype = strtolower($oembed->mimetype);
300                     $semicolon = strpos($mimetype,';');
301                     if($semicolon){
302                         $mimetype = substr($mimetype,0,$semicolon);
303                     }
304                     if(in_array($mimetype,$notEnclosureMimeTypes)){
305                         return false;
306                     }else{
307                         if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
308                         if($oembed->url) $enclosure->url=$oembed->url;
309                         if($oembed->title) $enclosure->title=$oembed->title;
310                         if($oembed->modified) $enclosure->modified=$oembed->modified;
311                         unset($oembed->size);
312                     }
313                 } else {
314                     return false;
315                 }
316             }
317         }
318         return $enclosure;
319     }
320
321     // quick back-compat hack, since there's still code using this
322     function isEnclosure()
323     {
324         $enclosure = $this->getEnclosure();
325         return !empty($enclosure);
326     }
327 }
328