]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/UpLoad.php
added DISABLE_UPLOAD_ONLY_ALLOWED_EXTENSIONS
[SourceForge/phpwiki.git] / lib / plugin / UpLoad.php
1 <?php // -*-php-*-
2 rcs_id('$Id: UpLoad.php,v 1.25 2007-04-18 20:40:48 rurban Exp $');
3 /*
4  Copyright 2003,2004,2007 $ThePhpWikiProgrammingTeam
5
6  This file is part of PhpWiki.
7
8  PhpWiki is free software; you can redistribute it and/or modify
9  it under the terms of the GNU General Public License as published by
10  the Free Software Foundation; either version 2 of the License, or
11  (at your option) any later version.
12
13  PhpWiki is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with PhpWiki; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21
22  */
23
24 /**
25  * UpLoad:  Allow Administrator to upload files to a special directory,
26  *          which should preferably be added to the InterWikiMap
27  * Usage:   <?plugin UpLoad ?>
28  * Author:  NathanGass <gass@iogram.ch>
29  * Changes: ReiniUrban <rurban@x-ray.at>,
30  *          qubit <rtryon@dartmouth.edu>
31  * Note:    See also Jochen Kalmbach's plugin/UserFileManagement.php
32  */
33
34 class WikiPlugin_UpLoad
35 extends WikiPlugin
36 {
37     var $disallowed_extensions;
38     // TODO: use PagePerms instead
39     var $only_authenticated = true; // allow only authenticated users may upload.
40
41     function getName () {
42         return "UpLoad";
43     }
44
45     function getDescription () {
46         return _("Upload files to the local InterWiki Upload:<filename>");
47     }
48
49     function getDefaultArguments() {
50         return array('logfile'  => 'phpwiki-upload.log',
51                      // add a link of the fresh file automatically to the 
52                      // end of the page (or current page)
53                      'autolink' => true, 
54                      'page'     => '[pagename]',
55                      );
56     }
57
58     function run($dbi, $argstr, &$request, $basepage) {
59         $this->allowed_extensions = explode("\n",
60 "7z
61 bz2
62 doc
63 gif
64 gz
65 jpeg
66 jpg
67 mp3
68 pdf
69 png
70 rar
71 tar
72 txt
73 zip");
74         $this->disallowed_extensions = explode("\n",
75 "ad[ep]
76 asd
77 ba[st]
78 chm
79 cmd
80 com
81 cgi
82 cpl
83 crt
84 dll
85 eml
86 exe
87 hlp
88 hta
89 in[fs]
90 isp
91 jse?
92 lnk
93 md[betw]
94 ms[cipt]
95 nws
96 ocx
97 ops
98 pcd
99 p[ir]f
100 php\d?
101 phtml
102 pl
103 py
104 reg
105 sc[frt]
106 sh[bsm]?
107 swf
108 url
109 vb[esx]?
110 vxd
111 ws[cfh]");
112         //removed "\{[[:xdigit:]]{8}(?:-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}\}"
113
114         $args = $this->getArgs($argstr, $request);
115         extract($args);
116
117         $file_dir = getUploadFilePath();
118         $form = HTML::form(array('action' => $request->getPostURL(),
119                                  'enctype' => 'multipart/form-data',
120                                  'method' => 'post'));
121         $contents = HTML::div(array('class' => 'wikiaction'));
122         $contents->pushContent(HTML::input(array('type' => 'hidden',
123                                                  'name' => 'MAX_FILE_SIZE',
124                                                  'value' => MAX_UPLOAD_SIZE)));
125         $contents->pushContent(HTML::input(array('name' => 'userfile',
126                                                  'type' => 'file',
127                                                  'size' => '50')));
128         $contents->pushContent(HTML::raw(" "));
129         $contents->pushContent(HTML::input(array('value' => _("Upload"),
130                                                  'type' => 'submit')));
131         $form->pushContent($contents);
132
133         $message = HTML();
134         if ($request->isPost() and $this->only_authenticated) {
135             // Make sure that the user is logged in.
136             $user = $request->getUser();
137             if (!$user->isAuthenticated()) {
138                 $message->pushContent(HTML::h2(_("ACCESS DENIED: You must log in to upload files.")),
139                                           HTML::br(),HTML::br());
140                 $result = HTML();
141                 $result->pushContent($form);
142                 $result->pushContent($message);
143                 return $result;
144             }
145         }
146         
147         $userfile = $request->getUploadedFile('userfile');
148         if ($userfile) {
149             $userfile_name = $userfile->getName();
150             $userfile_name = trim(basename($userfile_name));
151             if (UPLOAD_USERDIR) {
152                 $file_dir .= $request->_user->_userid;
153                 if (!file_exists($file_dir))
154                     mkdir($file_dir, 0775);
155                 $file_dir .= "/";
156                 $u_userfile = $request->_user->_userid . "/" . $userfile_name;
157             } else {
158                 $u_userfile = $userfile_name;
159             }
160             $u_userfile = preg_replace("/ /", "%20", $u_userfile);
161             $userfile_tmpname = $userfile->getTmpName();
162             $err_header = HTML::h2(fmt("ERROR uploading '%s': ", $userfile_name));
163             if (preg_match("/(\." . join("|\.", $this->disallowed_extensions) . ")(\.|\$)/i",
164                            $userfile_name))
165             {
166                 $message->pushContent($err_header);
167                 $message->pushContent(fmt("Files with extension %s are not allowed.",
168                                           join(", ", $this->disallowed_extensions)),HTML::br(),HTML::br());
169             }
170             elseif (! DISABLE_UPLOAD_ONLY_ALLOWED_EXTENSIONS and 
171                     ! preg_match("/(\." . join("|\.", $this->allowed_extensions) . ")\$/i", 
172                                $userfile_name))
173             {
174                 $message->pushContent($err_header);
175                 $message->pushContent(fmt("Only files with the extension %s are allowed.",
176                                           join(", ", $this->allowed_extensions)),HTML::br(),HTML::br());
177             }
178             elseif (preg_match("/[^._a-zA-Z0-9- ]/", $userfile_name))
179             {
180                 $message->pushContent($err_header);
181                 $message->pushContent(_("Invalid filename. File names may only contain alphanumeric characters and dot, underscore, space or dash."),
182                                       HTML::br(),HTML::br());
183             }
184             elseif (file_exists($file_dir . $userfile_name)) {
185                 $message->pushContent($err_header);
186                 $message->pushContent(fmt("There is already a file with name %s uploaded.",
187                                           $u_userfile),HTML::br(),HTML::br());
188             }
189             elseif ($userfile->getSize() > (MAX_UPLOAD_SIZE)) {
190                 $message->pushContent($err_header);
191                 $message->pushContent(_("Sorry but this file is too big."),HTML::br(),HTML::br());
192             }
193             elseif (move_uploaded_file($userfile_tmpname, $file_dir . $userfile_name) or
194                     (IsWindows() and rename($userfile_tmpname, $file_dir . $userfile_name))
195                     )
196             {
197                 $interwiki = new PageType_interwikimap();
198                 $link = $interwiki->link("Upload:$u_userfile");
199                 $message->pushContent(HTML::h2(_("File successfully uploaded.")));
200                 $message->pushContent(HTML::ul(HTML::li($link)));
201
202                 // the upload was a success and we need to mark this event in the "upload log"
203                 if ($logfile) { 
204                     $upload_log = $file_dir . basename($logfile);
205                     $this->log($userfile, $upload_log, $message);
206                 }
207                 if ($autolink) {
208                     require_once("lib/loadsave.php");
209                     $pagehandle = $dbi->getPage($page);
210                     if ($pagehandle->exists()) {// don't replace default contents
211                         $current = $pagehandle->getCurrentRevision();
212                         $version = $current->getVersion();
213                         $text = $current->getPackedContent();
214                         $newtext = $text . "\n* [Upload:$u_userfile]";
215                         $meta = $current->_data;
216                         $meta['summary'] = sprintf(_("uploaded %s"),$u_userfile);
217                         $pagehandle->save($newtext, $version + 1, $meta);
218                     }
219                 }
220             }
221             else {
222                 $message->pushContent($err_header);
223                 $message->pushContent(HTML::br(),_("Uploading failed."),HTML::br());
224             }
225         }
226         else {
227             $message->pushContent(HTML::br(),HTML::br());
228         }
229
230         //$result = HTML::div( array( 'class' => 'wikiaction' ) );
231         $result = HTML();
232         $result->pushContent($form);
233         $result->pushContent($message);
234         return $result;
235     }
236
237     function log ($userfile, $upload_log, &$message) {
238         global $WikiTheme;
239         $user = $GLOBALS['request']->_user;
240         if (!is_writable($upload_log)) {
241             trigger_error(_("The upload logfile is not writable."), E_USER_WARNING);
242         }
243         elseif (!$log_handle = fopen ($upload_log, "a")) {
244             trigger_error(_("Can't open the upload logfile."), E_USER_WARNING);
245         }
246         else {        // file size in KB; precision of 0.1
247             $file_size = round(($userfile->getSize())/1024, 1);
248             if ($file_size <= 0) {
249                 $file_size = "&lt; 0.1";
250             }
251             $userfile_name = $userfile->getName();
252             fwrite($log_handle,
253                    "\n"
254                    . "<tr><td><a href=\"$userfile_name\">$userfile_name</a></td>"
255                    . "<td align=\"right\">$file_size kB</td>"
256                    . "<td>&nbsp;&nbsp;" . $WikiTheme->formatDate(time()) . "</td>"
257                    . "<td>&nbsp;&nbsp;<em>" . $user->getId() . "</em></td></tr>");
258             fclose($log_handle);
259         }
260         return;
261     }
262
263 }
264
265 // $Log: not supported by cvs2svn $
266 // Revision 1.24  2007/04/11 17:49:01  rurban
267 // Chgeck against .php\d, i.e. php3
268 //
269 // Revision 1.23  2007/04/08 12:43:45  rurban
270 // Important security fix!
271 // Disallow files like "deface.php.3" also. Those are actually in the wild!
272 //
273 // Revision 1.22  2007/02/17 14:16:56  rurban
274 // allow spaces in filenames
275 //
276 // Revision 1.21  2007/01/04 16:46:50  rurban
277 // Support UPLOAD_USERDIR
278 //
279 // Revision 1.20  2006/08/15 13:40:40  rurban
280 // help finding the file (should not be needed)
281 //
282 // Revision 1.19  2005/04/11 19:40:15  rurban
283 // Simplify upload. See https://sourceforge.net/forum/message.php?msg_id=3093651
284 // Improve UpLoad warnings.
285 // Move auth check before upload.
286 //
287 // Revision 1.18  2005/02/12 17:24:24  rurban
288 // locale update: missing . : fixed. unified strings
289 // proper linebreaks
290 //
291 // Revision 1.17  2004/11/09 08:15:50  rurban
292 // trim filename
293 //
294 // Revision 1.16  2004/10/21 19:03:37  rurban
295 // Be more stricter with uploads: Filenames may only contain alphanumeric
296 // characters. Patch #1037825
297 //
298 // Revision 1.15  2004/09/22 13:46:26  rurban
299 // centralize upload paths.
300 // major WikiPluginCached feature enhancement:
301 //   support _STATIC pages in uploads/ instead of dynamic getimg.php? subrequests.
302 //   mainly for debugging, cache problems and action=pdf
303 //
304 // Revision 1.14  2004/06/16 10:38:59  rurban
305 // Disallow refernces in calls if the declaration is a reference
306 // ("allow_call_time_pass_reference clean").
307 //   PhpWiki is now allow_call_time_pass_reference = Off clean,
308 //   but several external libraries may not.
309 //   In detail these libs look to be affected (not tested):
310 //   * Pear_DB odbc
311 //   * adodb oracle
312 //
313 // Revision 1.13  2004/06/14 11:31:39  rurban
314 // renamed global $Theme to $WikiTheme (gforge nameclash)
315 // inherit PageList default options from PageList
316 //   default sortby=pagename
317 // use options in PageList_Selectable (limit, sortby, ...)
318 // added action revert, with button at action=diff
319 // added option regex to WikiAdminSearchReplace
320 //
321 // Revision 1.12  2004/06/13 11:34:22  rurban
322 // fixed bug #969532 (space in uploaded filenames)
323 // improved upload error messages
324 //
325 // Revision 1.11  2004/06/11 09:07:30  rurban
326 // support theme-specific LinkIconAttr: front or after or none
327 //
328 // Revision 1.10  2004/04/12 10:19:18  rurban
329 // fixed copyright year
330 //
331 // Revision 1.9  2004/04/12 10:18:22  rurban
332 // removed the hairy regex line
333 //
334 // Revision 1.8  2004/04/12 09:12:22  rurban
335 // fix syntax errors
336 //
337 // Revision 1.7  2004/04/09 17:49:03  rurban
338 // Added PhpWiki RssFeed to Sidebar
339 // sidebar formatting
340 // some browser dependant fixes (old-browser support)
341 //
342 // Revision 1.6  2004/02/27 01:36:51  rurban
343 // autolink enabled
344 //
345 // Revision 1.5  2004/02/27 01:24:43  rurban
346 // use IntwerWiki links for uploaded file.
347 // autolink to page prepared, but not yet ready
348 //
349 // Revision 1.4  2004/02/21 19:12:59  rurban
350 // patch by Sascha Carlin
351 //
352 // Revision 1.3  2004/02/17 12:11:36  rurban
353 // added missing 4th basepage arg at plugin->run() to almost all plugins. This caused no harm so far, because it was silently dropped on normal usage. However on plugin internal ->run invocations it failed. (InterWikiSearch, IncludeSiteMap, ...)
354 //
355 // Revision 1.2  2004/01/26 09:18:00  rurban
356 // * changed stored pref representation as before.
357 //   the array of objects is 1) bigger and 2)
358 //   less portable. If we would import packed pref
359 //   objects and the object definition was changed, PHP would fail.
360 //   This doesn't happen with an simple array of non-default values.
361 // * use $prefs->retrieve and $prefs->store methods, where retrieve
362 //   understands the interim format of array of objects also.
363 // * simplified $prefs->get() and fixed $prefs->set()
364 // * added $user->_userid and class '_WikiUser' portability functions
365 // * fixed $user object ->_level upgrading, mostly using sessions.
366 //   this fixes yesterdays problems with loosing authorization level.
367 // * fixed WikiUserNew::checkPass to return the _level
368 // * fixed WikiUserNew::isSignedIn
369 // * added explodePageList to class PageList, support sortby arg
370 // * fixed UserPreferences for WikiUserNew
371 // * fixed WikiPlugin for empty defaults array
372 // * UnfoldSubpages: added pagename arg, renamed pages arg,
373 //   removed sort arg, support sortby arg
374 //
375 // Revision 1.1  2003/11/04 18:41:41  carstenklapp
376 // New plugin which was submitted to the mailing list some time
377 // ago. (This is the best UpLoad function I have seen for PhpWiki so
378 // far. Cleaned up text formatting and typos from the version on the
379 // mailing list. Still needs a few adjustments.)
380
381 // (c-file-style: "gnu")
382 // Local Variables:
383 // mode: php
384 // tab-width: 8
385 // c-basic-offset: 4
386 // c-hanging-comment-ender-p: nil
387 // indent-tabs-mode: nil
388 // End:
389 ?>