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