]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
Testing... using photo info for temp thumbnails
[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                 // @todo 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             // TRANS: %1$s is used for plural.
190             return sprintf(_m('No file may be larger than %1$d byte and the file you sent was %2$d bytes. Try to upload a smaller version.',
191                               'No file may be larger than %1$d bytes and the file you sent was %2$d bytes. Try to upload a smaller version.',
192                               common_config('attachments', 'file_quota')),
193                            common_config('attachments', 'file_quota'), $fileSize);
194         }
195
196         $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'";
197         $this->query($query);
198         $this->fetch();
199         $total = $this->total + $fileSize;
200         if ($total > common_config('attachments', 'user_quota')) {
201             // TRANS: Message given if an upload would exceed user quota.
202             // TRANS: %d (number) is the user quota in bytes and is used for plural.
203             return sprintf(_m('A file this large would exceed your user quota of %d byte.',
204                               'A file this large would exceed your user quota of %d bytes.',
205                               common_config('attachments', 'user_quota')),
206                            common_config('attachments', 'user_quota'));
207         }
208         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
209         $this->query($query);
210         $this->fetch();
211         $total = $this->total + $fileSize;
212         if ($total > common_config('attachments', 'monthly_quota')) {
213             // TRANS: Message given id an upload would exceed a user's monthly quota.
214             // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
215             return sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
216                               'A file this large would exceed your monthly quota of %d bytes.',
217                               common_config('attachments', 'monthly_quota')),
218                            common_config('attachments', 'monthly_quota'));
219         }
220         return true;
221     }
222
223     // where should the file go?
224
225     static function filename($profile, $basename, $mimetype)
226     {
227         require_once 'MIME/Type/Extension.php';
228
229         // We have to temporarily disable auto handling of PEAR errors...
230         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
231
232         $mte = new MIME_Type_Extension();
233         $ext = $mte->getExtension($mimetype);
234         if (PEAR::isError($ext)) {
235             $ext = strtolower(preg_replace('/\W/', '', $mimetype));
236         }
237
238         // Restore error handling.
239         PEAR::staticPopErrorHandling();
240
241         $nickname = $profile->nickname;
242         $datestamp = strftime('%Y%m%dT%H%M%S', time());
243         $random = strtolower(common_confirmation_code(32));
244         return "$nickname-$datestamp-$random.$ext";
245     }
246
247     /**
248      * Validation for as-saved base filenames
249      */
250     static function validFilename($filename)
251     {
252         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
253     }
254
255     /**
256      * @throws ClientException on invalid filename
257      */
258     static function path($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         $dir = common_config('attachments', 'dir');
265
266         if ($dir[strlen($dir)-1] != '/') {
267             $dir .= '/';
268         }
269
270         return $dir . $filename;
271     }
272
273     static function url($filename)
274     {
275         if (!self::validFilename($filename)) {
276             // TRANS: Client exception thrown if a file upload does not have a valid name.
277             throw new ClientException(_("Invalid filename."));
278         }
279
280         if (common_config('site','private')) {
281
282             return common_local_url('getfile',
283                                 array('filename' => $filename));
284
285         }
286
287         if (StatusNet::isHTTPS()) {
288
289             $sslserver = common_config('attachments', 'sslserver');
290
291             if (empty($sslserver)) {
292                 // XXX: this assumes that background dir == site dir + /file/
293                 // not true if there's another server
294                 if (is_string(common_config('site', 'sslserver')) &&
295                     mb_strlen(common_config('site', 'sslserver')) > 0) {
296                     $server = common_config('site', 'sslserver');
297                 } else if (common_config('site', 'server')) {
298                     $server = common_config('site', 'server');
299                 }
300                 $path = common_config('site', 'path') . '/file/';
301             } else {
302                 $server = $sslserver;
303                 $path   = common_config('attachments', 'sslpath');
304                 if (empty($path)) {
305                     $path = common_config('attachments', 'path');
306                 }
307             }
308
309             $protocol = 'https';
310         } else {
311             $path = common_config('attachments', 'path');
312             $server = common_config('attachments', 'server');
313
314             if (empty($server)) {
315                 $server = common_config('site', 'server');
316             }
317
318             $ssl = common_config('attachments', 'ssl');
319
320             $protocol = ($ssl) ? 'https' : 'http';
321         }
322
323         if ($path[strlen($path)-1] != '/') {
324             $path .= '/';
325         }
326
327         if ($path[0] != '/') {
328             $path = '/'.$path;
329         }
330
331         return $protocol.'://'.$server.$path.$filename;
332     }
333
334     function getEnclosure(){
335         $enclosure = (object) array();
336         $enclosure->title=$this->title;
337         $enclosure->url=$this->url;
338         $enclosure->title=$this->title;
339         $enclosure->date=$this->date;
340         $enclosure->modified=$this->modified;
341         $enclosure->size=$this->size;
342         $enclosure->mimetype=$this->mimetype;
343
344         if(! isset($this->filename)){
345             $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
346             $mimetype = $this->mimetype;
347             if($mimetype != null){
348                 $mimetype = strtolower($this->mimetype);
349             }
350             $semicolon = strpos($mimetype,';');
351             if($semicolon){
352                 $mimetype = substr($mimetype,0,$semicolon);
353             }
354             if(in_array($mimetype,$notEnclosureMimeTypes)){
355                 // Never treat generic HTML links as an enclosure type!
356                 // But if we have oEmbed info, we'll consider it golden.
357                 $oembed = File_oembed::staticGet('file_id',$this->id);
358                 if($oembed && in_array($oembed->type, array('photo', 'video'))){
359                     $mimetype = strtolower($oembed->mimetype);
360                     $semicolon = strpos($mimetype,';');
361                     if($semicolon){
362                         $mimetype = substr($mimetype,0,$semicolon);
363                     }
364                     if(in_array($mimetype,$notEnclosureMimeTypes)){
365                         return false;
366                     }else{
367                         if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
368                         if($oembed->url) $enclosure->url=$oembed->url;
369                         if($oembed->title) $enclosure->title=$oembed->title;
370                         if($oembed->modified) $enclosure->modified=$oembed->modified;
371                         unset($oembed->size);
372                     }
373                 } else {
374                     return false;
375                 }
376             }
377         }
378         return $enclosure;
379     }
380
381     // quick back-compat hack, since there's still code using this
382     function isEnclosure()
383     {
384         $enclosure = $this->getEnclosure();
385         return !empty($enclosure);
386     }
387 }