]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/File.php
File_oembed::saveNew are File::saveNew are static
[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('GNUSOCIAL')) { exit(1); }
21
22 /**
23  * Table Definition for file
24  */
25 class File extends Managed_DataObject
26 {
27     ###START_AUTOCODE
28     /* the code below is auto generated do not remove the above tag */
29
30     public $__table = 'file';                            // table name
31     public $id;                              // int(4)  primary_key not_null
32     public $url;                             // varchar(255)  unique_key
33     public $mimetype;                        // varchar(50)
34     public $size;                            // int(4)
35     public $title;                           // varchar(255)
36     public $date;                            // int(4)
37     public $protected;                       // int(4)
38     public $filename;                        // varchar(255)
39     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
40
41     /* the code above is auto generated do not remove the tag below */
42     ###END_AUTOCODE
43
44     public static function schemaDef()
45     {
46         return array(
47             'fields' => array(
48                 'id' => array('type' => 'serial', 'not null' => true),
49                 'url' => array('type' => 'varchar', 'length' => 255, 'description' => 'destination URL after following redirections'),
50                 'mimetype' => array('type' => 'varchar', 'length' => 50, 'description' => 'mime type of resource'),
51                 'size' => array('type' => 'int', 'description' => 'size of resource when available'),
52                 'title' => array('type' => 'varchar', 'length' => 255, 'description' => 'title of resource when available'),
53                 'date' => array('type' => 'int', 'description' => 'date of resource according to http query'),
54                 'protected' => array('type' => 'int', 'description' => 'true when URL is private (needs login)'),
55                 'filename' => array('type' => 'varchar', 'length' => 255, 'description' => 'if a local file, name of the file'),
56
57                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
58             ),
59             'primary key' => array('id'),
60             'unique keys' => array(
61                 'file_url_key' => array('url'),
62             ),
63         );
64     }
65
66     function isProtected($url) {
67         return 'http://www.facebook.com/login.php' === $url;
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     public static function saveNew(array $redir_data, $given_url) {
78
79         // I don't know why we have to keep doing this but I'm adding this last check to avoid
80         // uniqueness bugs.
81
82         $x = File::getKV('url', $given_url);
83         
84         if (!$x instanceof File) {
85             $x = new File;
86             $x->url = $given_url;
87             if (!empty($redir_data['protected'])) $x->protected = $redir_data['protected'];
88             if (!empty($redir_data['title'])) $x->title = $redir_data['title'];
89             if (!empty($redir_data['type'])) $x->mimetype = $redir_data['type'];
90             if (!empty($redir_data['size'])) $x->size = intval($redir_data['size']);
91             if (isset($redir_data['time']) && $redir_data['time'] > 0) $x->date = intval($redir_data['time']);
92             $file_id = $x->insert();
93         }
94
95         $x->saveOembed($redir_data, $given_url);
96         return $x;
97     }
98
99     /**
100      * Save embedding information for this file, if applicable.
101      *
102      * Normally this won't need to be called manually, as File::saveNew()
103      * takes care of it.
104      *
105      * @param array $redir_data lookup data eg from File_redirection::where()
106      * @param string $given_url
107      * @return boolean success
108      */
109     public function saveOembed(array $redir_data, $given_url)
110     {
111         if (isset($redir_data['type'])
112                 && (('text/html' === substr($redir_data['type'], 0, 9)
113                 || 'application/xhtml+xml' === substr($redir_data['type'], 0, 21)))) {
114             try {
115                 $oembed_data = File_oembed::_getOembed($given_url);
116             } catch (Exception $e) {
117                 return false;
118             }
119             if ($oembed_data === false) {
120                 return false;
121             }
122             $fo = File_oembed::getKV('file_id', $this->id);
123
124             if ($fo instanceof File_oembed) {
125                 common_log(LOG_WARNING, "Strangely, a File_oembed object exists for new file $file_id", __FILE__);
126             } else {
127                 File_oembed::saveNew($oembed_data, $this->id);
128                 return true;
129             }
130         }
131         return false;
132     }
133
134     /**
135      * Go look at a URL and possibly save data about it if it's new:
136      * - follow redirect chains and store them in file_redirection
137      * - look up oEmbed data and save it in file_oembed
138      * - if a thumbnail is available, save it in file_thumbnail
139      * - save file record with basic info
140      * - optionally save a file_to_post record
141      * - return the File object with the full reference
142      *
143      * @fixme refactor this mess, it's gotten pretty scary.
144      * @param string $given_url the URL we're looking at
145      * @param int $notice_id (optional)
146      * @param bool $followRedirects defaults to true
147      *
148      * @return mixed File on success, -1 on some errors
149      *
150      * @throws ServerException on some errors
151      */
152     public function processNew($given_url, $notice_id=null, $followRedirects=true) {
153         if (empty($given_url)) return -1;   // error, no url to process
154         $given_url = File_redirection::_canonUrl($given_url);
155         if (empty($given_url)) return -1;   // error, no url to process
156         $file = File::getKV('url', $given_url);
157         if (empty($file)) {
158             $file_redir = File_redirection::getKV('url', $given_url);
159             if (empty($file_redir)) {
160                 // @fixme for new URLs this also looks up non-redirect data
161                 // such as target content type, size, etc, which we need
162                 // for File::saveNew(); so we call it even if not following
163                 // new redirects.
164                 $redir_data = File_redirection::where($given_url);
165                 if (is_array($redir_data)) {
166                     $redir_url = $redir_data['url'];
167                 } elseif (is_string($redir_data)) {
168                     $redir_url = $redir_data;
169                     $redir_data = array();
170                 } else {
171                     // TRANS: Server exception thrown when a URL cannot be processed.
172                     throw new ServerException(sprintf(_("Cannot process URL '%s'"), $given_url));
173                 }
174                 // TODO: max field length
175                 if ($redir_url === $given_url || strlen($redir_url) > 255 || !$followRedirects) {
176                     $x = File::saveNew($redir_data, $given_url);
177                     $file_id = $x->id;
178                 } else {
179                     // This seems kind of messed up... for now skipping this part
180                     // if we're already under a redirect, so we don't go into
181                     // horrible infinite loops if we've been given an unstable
182                     // redirect (where the final destination of the first request
183                     // doesn't match what we get when we ask for it again).
184                     //
185                     // Seen in the wild with clojure.org, which redirects through
186                     // wikispaces for auth and appends session data in the URL params.
187                     $x = File::processNew($redir_url, $notice_id, /*followRedirects*/false);
188                     $file_id = $x->id;
189                     File_redirection::saveNew($redir_data, $file_id, $given_url);
190                 }
191             } else {
192                 $file_id = $file_redir->file_id;
193             }
194         } else {
195             $file_id = $file->id;
196             $x = $file;
197         }
198
199         if (empty($x)) {
200             $x = File::getKV('id', $file_id);
201             if (empty($x)) {
202                 // @todo FIXME: This could possibly be a clearer message :)
203                 // TRANS: Server exception thrown when... Robin thinks something is impossible!
204                 throw new ServerException(_('Robin thinks something is impossible.'));
205             }
206         }
207
208         if (!empty($notice_id)) {
209             File_to_post::processNew($file_id, $notice_id);
210         }
211         return $x;
212     }
213
214     public static function respectsQuota(Profile $scoped, $fileSize) {
215         if ($fileSize > common_config('attachments', 'file_quota')) {
216             // TRANS: Message used to be inserted as %2$s in  the text "No file may
217             // TRANS: be larger than %1$d byte and the file you sent was %2$s.".
218             // TRANS: %1$d is the number of bytes of an uploaded file.
219             $fileSizeText = sprintf(_m('%1$d byte','%1$d bytes',$fileSize),$fileSize);
220
221             $fileQuota = common_config('attachments', 'file_quota');
222             // TRANS: Message given if an upload is larger than the configured maximum.
223             // TRANS: %1$d (used for plural) is the byte limit for uploads,
224             // TRANS: %2$s is the proper form of "n bytes". This is the only ways to have
225             // TRANS: gettext support multiple plurals in the same message, unfortunately...
226             throw new ClientException(
227                     sprintf(_m('No file may be larger than %1$d byte and the file you sent was %2$s. Try to upload a smaller version.',
228                               'No file may be larger than %1$d bytes and the file you sent was %2$s. Try to upload a smaller version.',
229                               $fileQuota),
230                     $fileQuota, $fileSizeText));
231         }
232
233         $file = new File;
234
235         $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 = {$scoped->id} and file.url like '%/notice/%/file'";
236         $file->query($query);
237         $file->fetch();
238         $total = $file->total + $fileSize;
239         if ($total > common_config('attachments', 'user_quota')) {
240             // TRANS: Message given if an upload would exceed user quota.
241             // TRANS: %d (number) is the user quota in bytes and is used for plural.
242             throw new ClientException(
243                     sprintf(_m('A file this large would exceed your user quota of %d byte.',
244                               'A file this large would exceed your user quota of %d bytes.',
245                               common_config('attachments', 'user_quota')),
246                     common_config('attachments', 'user_quota')));
247         }
248         $query .= ' AND EXTRACT(month FROM file.modified) = EXTRACT(month FROM now()) and EXTRACT(year FROM file.modified) = EXTRACT(year FROM now())';
249         $file->query($query);
250         $file->fetch();
251         $total = $file->total + $fileSize;
252         if ($total > common_config('attachments', 'monthly_quota')) {
253             // TRANS: Message given id an upload would exceed a user's monthly quota.
254             // TRANS: $d (number) is the monthly user quota in bytes and is used for plural.
255             throw new ClientException(
256                     sprintf(_m('A file this large would exceed your monthly quota of %d byte.',
257                               'A file this large would exceed your monthly quota of %d bytes.',
258                               common_config('attachments', 'monthly_quota')),
259                     common_config('attachments', 'monthly_quota')));
260         }
261         return true;
262     }
263
264     // where should the file go?
265
266     static function filename(Profile $profile, $origname, $mimetype)
267     {
268         try {
269             $ext = common_supported_mime_to_ext($mimetype);
270         } catch (Exception $e) {
271             // We don't support this mimetype, but let's guess the extension
272             $ext = substr(strrchr($mimetype, '/'), 1);
273         }
274
275         // Normalize and make the original filename more URL friendly.
276         $origname = basename($origname);
277         if (class_exists('Normalizer')) {
278             // http://php.net/manual/en/class.normalizer.php
279             // http://www.unicode.org/reports/tr15/
280             $origname = Normalizer::normalize($origname, Normalizer::FORM_KC);
281         }
282         $origname = preg_replace('/[^A-Za-z0-9\.\_]/', '_', $origname);
283
284         $nickname = $profile->nickname;
285         $datestamp = strftime('%Y%m%d', time());
286         do {
287             // generate new random strings until we don't run into a filename collision.
288             $random = strtolower(common_confirmation_code(16));
289             $filename = "$nickname-$datestamp-$origname-$random.$ext";
290         } while (file_exists(self::path($filename)));
291         return $filename;
292     }
293
294     /**
295      * Validation for as-saved base filenames
296      */
297     static function validFilename($filename)
298     {
299         return preg_match('/^[A-Za-z0-9._-]+$/', $filename);
300     }
301
302     /**
303      * @throws ClientException on invalid filename
304      */
305     static function path($filename)
306     {
307         if (!self::validFilename($filename)) {
308             // TRANS: Client exception thrown if a file upload does not have a valid name.
309             throw new ClientException(_("Invalid filename."));
310         }
311         $dir = common_config('attachments', 'dir');
312
313         if ($dir[strlen($dir)-1] != '/') {
314             $dir .= '/';
315         }
316
317         return $dir . $filename;
318     }
319
320     static function url($filename)
321     {
322         if (!self::validFilename($filename)) {
323             // TRANS: Client exception thrown if a file upload does not have a valid name.
324             throw new ClientException(_("Invalid filename."));
325         }
326
327         if (common_config('site','private')) {
328
329             return common_local_url('getfile',
330                                 array('filename' => $filename));
331
332         }
333
334         if (StatusNet::isHTTPS()) {
335
336             $sslserver = common_config('attachments', 'sslserver');
337
338             if (empty($sslserver)) {
339                 // XXX: this assumes that background dir == site dir + /file/
340                 // not true if there's another server
341                 if (is_string(common_config('site', 'sslserver')) &&
342                     mb_strlen(common_config('site', 'sslserver')) > 0) {
343                     $server = common_config('site', 'sslserver');
344                 } else if (common_config('site', 'server')) {
345                     $server = common_config('site', 'server');
346                 }
347                 $path = common_config('site', 'path') . '/file/';
348             } else {
349                 $server = $sslserver;
350                 $path   = common_config('attachments', 'sslpath');
351                 if (empty($path)) {
352                     $path = common_config('attachments', 'path');
353                 }
354             }
355
356             $protocol = 'https';
357         } else {
358             $path = common_config('attachments', 'path');
359             $server = common_config('attachments', 'server');
360
361             if (empty($server)) {
362                 $server = common_config('site', 'server');
363             }
364
365             $ssl = common_config('attachments', 'ssl');
366
367             $protocol = ($ssl) ? 'https' : 'http';
368         }
369
370         if ($path[strlen($path)-1] != '/') {
371             $path .= '/';
372         }
373
374         if ($path[0] != '/') {
375             $path = '/'.$path;
376         }
377
378         return $protocol.'://'.$server.$path.$filename;
379     }
380
381     function getEnclosure(){
382         $enclosure = (object) array();
383         $enclosure->title=$this->title;
384         $enclosure->url=$this->url;
385         $enclosure->title=$this->title;
386         $enclosure->date=$this->date;
387         $enclosure->modified=$this->modified;
388         $enclosure->size=$this->size;
389         $enclosure->mimetype=$this->mimetype;
390
391         if(! isset($this->filename)){
392             $notEnclosureMimeTypes = array(null,'text/html','application/xhtml+xml');
393             $mimetype = $this->mimetype;
394             if($mimetype != null){
395                 $mimetype = strtolower($this->mimetype);
396             }
397             $semicolon = strpos($mimetype,';');
398             if($semicolon){
399                 $mimetype = substr($mimetype,0,$semicolon);
400             }
401             if(in_array($mimetype,$notEnclosureMimeTypes)){
402                 // Never treat generic HTML links as an enclosure type!
403                 // But if we have oEmbed info, we'll consider it golden.
404                 $oembed = File_oembed::getKV('file_id',$this->id);
405                 if($oembed && in_array($oembed->type, array('photo', 'video'))){
406                     $mimetype = strtolower($oembed->mimetype);
407                     $semicolon = strpos($mimetype,';');
408                     if($semicolon){
409                         $mimetype = substr($mimetype,0,$semicolon);
410                     }
411                     // @fixme uncertain if this is right.
412                     // we want to expose things like YouTube videos as
413                     // viewable attachments, but don't expose them as
414                     // downloadable enclosures.....?
415                     //if (in_array($mimetype, $notEnclosureMimeTypes)) {
416                     //    return false;
417                     //} else {
418                         if($oembed->mimetype) $enclosure->mimetype=$oembed->mimetype;
419                         if($oembed->url) $enclosure->url=$oembed->url;
420                         if($oembed->title) $enclosure->title=$oembed->title;
421                         if($oembed->modified) $enclosure->modified=$oembed->modified;
422                         unset($oembed->size);
423                     //}
424                 } else {
425                     return false;
426                 }
427             }
428         }
429         return $enclosure;
430     }
431
432     // quick back-compat hack, since there's still code using this
433     function isEnclosure()
434     {
435         $enclosure = $this->getEnclosure();
436         return !empty($enclosure);
437     }
438
439     /**
440      * Get the attachment's thumbnail record, if any.
441      *
442      * @return File_thumbnail
443      */
444     function getThumbnail()
445     {
446         return File_thumbnail::getKV('file_id', $this->id);
447     }
448
449     public function getPath()
450     {
451         return self::path($this->filename);
452     }
453     public function getUrl()
454     {
455         return $this->url;
456     }
457
458     /**
459      * Blow the cache of notices that link to this URL
460      *
461      * @param boolean $last Whether to blow the "last" cache too
462      *
463      * @return void
464      */
465
466     function blowCache($last=false)
467     {
468         self::blow('file:notice-ids:%s', $this->url);
469         if ($last) {
470             self::blow('file:notice-ids:%s;last', $this->url);
471         }
472         self::blow('file:notice-count:%d', $this->id);
473     }
474
475     /**
476      * Stream of notices linking to this URL
477      *
478      * @param integer $offset   Offset to show; default is 0
479      * @param integer $limit    Limit of notices to show
480      * @param integer $since_id Since this notice
481      * @param integer $max_id   Before this notice
482      *
483      * @return array ids of notices that link to this file
484      */
485
486     function stream($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
487     {
488         $stream = new FileNoticeStream($this);
489         return $stream->getNotices($offset, $limit, $since_id, $max_id);
490     }
491
492     function noticeCount()
493     {
494         $cacheKey = sprintf('file:notice-count:%d', $this->id);
495         
496         $count = self::cacheGet($cacheKey);
497
498         if ($count === false) {
499
500             $f2p = new File_to_post();
501
502             $f2p->file_id = $this->id;
503
504             $count = $f2p->count();
505
506             self::cacheSet($cacheKey, $count);
507         } 
508
509         return $count;
510     }
511 }