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