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