]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
Merge branch '0.9.x' 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 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      * Go look at a URL and possibly save data about it if it's new:
120      * - follow redirect chains and store them in file_redirection
121      * - look up oEmbed data and save it in file_oembed
122      * - if a thumbnail is available, save it in file_thumbnail
123      * - save file record with basic info
124      * - optionally save a file_to_post record
125      * - return the File object with the full reference
126      *
127      * @fixme refactor this mess, it's gotten pretty scary.
128      * @param string $given_url the URL we're looking at
129      * @param int $notice_id (optional)
130      * @param bool $followRedirects defaults to true
131      *
132      * @return mixed File on success, -1 on some errors
133      *
134      * @throws ServerException on some errors
135      */
136     public function processNew($given_url, $notice_id=null, $followRedirects=true) {
137         if (empty($given_url)) return -1;   // error, no url to process
138         $given_url = File_redirection::_canonUrl($given_url);
139         if (empty($given_url)) return -1;   // error, no url to process
140         $file = File::staticGet('url', $given_url);
141         if (empty($file)) {
142             $file_redir = File_redirection::staticGet('url', $given_url);
143             if (empty($file_redir)) {
144                 // @fixme for new URLs this also looks up non-redirect data
145                 // such as target content type, size, etc, which we need
146                 // for File::saveNew(); so we call it even if not following
147                 // new redirects.
148                 $redir_data = File_redirection::where($given_url);
149                 if (is_array($redir_data)) {
150                     $redir_url = $redir_data['url'];
151                 } elseif (is_string($redir_data)) {
152                     $redir_url = $redir_data;
153                     $redir_data = array();
154                 } else {
155                     // TRANS: Server exception thrown when a URL cannot be processed.
156                     throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
157                 }
158                 // TODO: max field length
159                 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
160                     $x = File::saveNew($redir_data, $given_url);
161                     $file_id = $x->id;
162                 } else {
163                     // This seems kind of messed up... for now skipping this part
164                     // if we're already under a redirect, so we don't go into
165                     // horrible infinite loops if we've been given an unstable
166                     // redirect (where the final destination of the first request
167                     // doesn't match what we get when we ask for it again).
168                     //
169                     // Seen in the wild with clojure.org, which redirects through
170                     // wikispaces for auth and appends session data in the URL params.
171                     $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
172                     $file_id = $x->id;
173                     File_redirection::saveNew($redir_data, $file_id, $given_url);
174                 }
175             } else {
176                 $file_id = $file_redir->file_id;
177             }
178         } else {
179             $file_id = $file->id;
180             $x = $file;
181         }
182
183         if (empty($x)) {
184             $x = File::staticGet($file_id);
185             if (empty($x)) {
186                 // @todo FIXME: This could possibly be a clearer message :)
187                 // TRANS: Server exception thrown when... Robin thinks something is impossible!
188                 throw new ServerException(_('Robin thinks something is impossible.'));
189             }
190         }
191
192         if (!empty($notice_id)) {
193             File_to_post::processNew($file_id, $notice_id);
194         }
195         return $x;
196     }
197
198     function isRespectsQuota($user,$fileSize) {
199
200         if ($fileSize > common_config('attachments', 'file_quota')) {
201             // TRANS: Message given if an upload is larger than the configured maximum.
202             // TRANS: %1$d is the byte limit for uploads, %2$d is the byte count for the uploaded file.
203             // TRANS: %1$s is used for plural.
204             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.',
205                               'No file may be larger than %1$d bytes and the file you sent was %2$d bytes. Try to upload a smaller version.',
206                               common_config('attachments', 'file_quota')),
207                            common_config('attachments', 'file_quota'), $fileSize);
208         }
209
210         $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'";
211         $this->query($query);
212         $this->fetch();
213         $total = $this->total + $fileSize;
214         if ($total > common_config('attachments', 'user_quota')) {
215             // TRANS: Message given if an upload would exceed user quota.
216             // TRANS: %d (number) is the user quota in bytes and is used for plural.
217             return sprintf(_m('A file this large would exceed your user quota of %d byte.',
218                               'A file this large would exceed your user quota of %d bytes.',
219                               common_config('attachments', 'user_quota')),
220                            common_config('attachments', 'user_quota'));
221         }
222         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
223         $this->query($query);
224         $this->fetch();
225         $total = $this->total + $fileSize;
226         if ($total > common_config('attachments', 'monthly_quota')) {
227             // TRANS: Message given id an upload would exceed a user's monthly quota.
228             // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
229             return sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
230                               'A file this large would exceed your monthly quota of %d bytes.',
231                               common_config('attachments', 'monthly_quota')),
232                            common_config('attachments', 'monthly_quota'));
233         }
234         return true;
235     }
236
237     // where should the file go?
238
239     static function filename($profile, $basename, $mimetype)
240     {
241         require_once 'MIME/Type/Extension.php';
242
243         // We have to temporarily disable auto handling of PEAR errors...
244         PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
245
246         $mte = new MIME_Type_Extension();
247         $ext = $mte->getExtension($mimetype);
248         if (PEAR::isError($ext)) {
249             $ext = strtolower(preg_replace('/\W/', '', $mimetype));
250         }
251
252         // Restore error handling.
253         PEAR::staticPopErrorHandling();
254
255         $nickname = $profile->nickname;
256         $datestamp = strftime('%Y%m%dT%H%M%S', time());
257         $random = strtolower(common_confirmation_code(32));
258         return "$nickname-$datestamp-$random.$ext";
259     }
260
261     /**
262      * Validation for as-saved base filenames
263      */
264     static function validFilename($filename)
265     {
266         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
267     }
268
269     /**
270      * @throws ClientException on invalid filename
271      */
272     static function path($filename)
273     {
274         if (!self::validFilename($filename)) {
275             // TRANS: Client exception thrown if a file upload does not have a valid name.
276             throw new ClientException(_("Invalid filename."));
277         }
278         $dir = common_config('attachments', 'dir');
279
280         if ($dir[strlen($dir)-1] != '/') {
281             $dir .= '/';
282         }
283
284         return $dir . $filename;
285     }
286
287     static function url($filename)
288     {
289         if (!self::validFilename($filename)) {
290             // TRANS: Client exception thrown if a file upload does not have a valid name.
291             throw new ClientException(_("Invalid filename."));
292         }
293
294         if (common_config('site','private')) {
295
296             return common_local_url('getfile',
297                                 array('filename' => $filename));
298
299         }
300
301         if (StatusNet::isHTTPS()) {
302
303             $sslserver = common_config('attachments', 'sslserver');
304
305             if (empty($sslserver)) {
306                 // XXX: this assumes that background dir == site dir + /file/
307                 // not true if there's another server
308                 if (is_string(common_config('site', 'sslserver')) &&
309                     mb_strlen(common_config('site', 'sslserver')) > 0) {
310                     $server = common_config('site', 'sslserver');
311                 } else if (common_config('site', 'server')) {
312                     $server = common_config('site', 'server');
313                 }
314                 $path = common_config('site', 'path') . '/file/';
315             } else {
316                 $server = $sslserver;
317                 $path   = common_config('attachments', 'sslpath');
318                 if (empty($path)) {
319                     $path = common_config('attachments', 'path');
320                 }
321             }
322
323             $protocol = 'https';
324         } else {
325             $path = common_config('attachments', 'path');
326             $server = common_config('attachments', 'server');
327
328             if (empty($server)) {
329                 $server = common_config('site', 'server');
330             }
331
332             $ssl = common_config('attachments', 'ssl');
333
334             $protocol = ($ssl) ? 'https' : 'http';
335         }
336
337         if ($path[strlen($path)-1] != '/') {
338             $path .= '/';
339         }
340
341         if ($path[0] != '/') {
342             $path = '/'.$path;
343         }
344
345         return $protocol.'://'.$server.$path.$filename;
346     }
347
348     function getEnclosure(){
349         $enclosure = (object) array();
350         $enclosure->title=$this->title;
351         $enclosure->url=$this->url;
352         $enclosure->title=$this->title;
353         $enclosure->date=$this->date;
354         $enclosure->modified=$this->modified;
355         $enclosure->size=$this->size;
356         $enclosure->mimetype=$this->mimetype;
357
358         if(! isset($this->filename)){
359             $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
360             $mimetype = $this->mimetype;
361             if($mimetype != null){
362                 $mimetype = strtolower($this->mimetype);
363             }
364             $semicolon = strpos($mimetype,';');
365             if($semicolon){
366                 $mimetype = substr($mimetype,0,$semicolon);
367             }
368             if(in_array($mimetype,$notEnclosureMimeTypes)){
369                 // Never treat generic HTML links as an enclosure type!
370                 // But if we have oEmbed info, we'll consider it golden.
371                 $oembed = File_oembed::staticGet('file_id',$this->id);
372                 if($oembed && in_array($oembed->type, array('photo', 'video'))){
373                     $mimetype = strtolower($oembed->mimetype);
374                     $semicolon = strpos($mimetype,';');
375                     if($semicolon){
376                         $mimetype = substr($mimetype,0,$semicolon);
377                     }
378                     // @fixme uncertain if this is right.
379                     // we want to expose things like YouTube videos as
380                     // viewable attachments, but don't expose them as
381                     // downloadable enclosures.....?
382                     //if (in_array($mimetype, $notEnclosureMimeTypes)) {
383                     //    return false;
384                     //} else {
385                         if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
386                         if($oembed->url) $enclosure->url=$oembed->url;
387                         if($oembed->title) $enclosure->title=$oembed->title;
388                         if($oembed->modified) $enclosure->modified=$oembed->modified;
389                         unset($oembed->size);
390                     //}
391                 } else {
392                     return false;
393                 }
394             }
395         }
396         return $enclosure;
397     }
398
399     // quick back-compat hack, since there's still code using this
400     function isEnclosure()
401     {
402         $enclosure = $this->getEnclosure();
403         return !empty($enclosure);
404     }
405
406     /**
407      * Get the attachment's thumbnail record, if any.
408      *
409      * @return File_thumbnail
410      */
411     function getThumbnail()
412     {
413         return File_thumbnail::staticGet('file_id', $this->id);
414     }
415 }