]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/UpLoad.php
Nice alert boxes for upload
[SourceForge/phpwiki.git] / lib / plugin / UpLoad.php
1 <?php // -*-php-*-
2 rcs_id('$Id$');
3 /*
4  Copyright 2003,2004,2007 $ThePhpWikiProgrammingTeam
5  Copyright 2008 Marc-Etienne Vargenau, Alcatel-Lucent
6
7  This file is part of PhpWiki.
8
9  PhpWiki is free software; you can redistribute it and/or modify
10  it under the terms of the GNU General Public License as published by
11  the Free Software Foundation; either version 2 of the License, or
12  (at your option) any later version.
13
14  PhpWiki is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  GNU General Public License for more details.
18
19  You should have received a copy of the GNU General Public License
20  along with PhpWiki; if not, write to the Free Software
21  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
23  */
24
25 /**
26  * UpLoad:  Allow Administrator to upload files to a special directory,
27  *          which should preferably be added to the InterWikiMap
28  * Usage:   <?plugin UpLoad ?>
29  * Author:  NathanGass <gass@iogram.ch>
30  * Changes: ReiniUrban <rurban@x-ray.at>,
31  *          qubit <rtryon@dartmouth.edu>
32  *          Marc-Etienne Vargenau, Alcatel-Lucent
33  * Note:    See also Jochen Kalmbach's plugin/UserFileManagement.php
34  */
35
36 class WikiPlugin_UpLoad
37 extends WikiPlugin
38 {
39     var $disallowed_extensions;
40     // TODO: use PagePerms instead
41     var $only_authenticated = true; // allow only authenticated users may upload.
42
43     function getName () {
44         return "UpLoad";
45     }
46
47     function getDescription () {
48         return _("Upload files to the local InterWiki Upload:<filename>");
49     }
50
51     function getVersion() {
52         return preg_replace("/[Revision: $]/", '',
53                             "\$Revision$");
54     }
55
56     function getDefaultArguments() {
57         return array('logfile'  => 'phpwiki-upload.log',
58                      // add a link of the fresh file automatically to the 
59                      // end of the page (or current page)
60                      'autolink' => true, 
61                      'page'     => '[pagename]',
62                      'size'     => 50,
63                      'mode'     => 'actionpage', // or edit
64                      );
65     }
66
67     function run($dbi, $argstr, &$request, $basepage) {
68         $this->allowed_extensions = explode("\n",
69 "7z
70 avi
71 bmp
72 bz2
73 c
74 cfg
75 diff
76 doc
77 gif
78 h
79 ini
80 jpeg
81 jpg
82 kmz
83 mp3
84 odg
85 odp
86 ods
87 odt
88 patch
89 pdf
90 png
91 ppt
92 rar
93 tar
94 tar.gz
95 txt
96 xls
97 zip");
98         $this->disallowed_extensions = explode("\n",
99 "ad[ep]
100 asd
101 ba[st]
102 chm
103 cmd
104 com
105 cgi
106 cpl
107 crt
108 dll
109 eml
110 exe
111 hlp
112 hta
113 in[fs]
114 isp
115 jse?
116 lnk
117 md[betw]
118 ms[cipt]
119 nws
120 ocx
121 ops
122 pcd
123 p[ir]f
124 php\d?
125 phtml
126 pl
127 py
128 reg
129 sc[frt]
130 sh[bsm]?
131 swf
132 url
133 vb[esx]?
134 vxd
135 ws[cfh]");
136         //removed "\{[[:xdigit:]]{8}(?:-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}\}"
137
138         $args = $this->getArgs($argstr, $request);
139         extract($args);
140
141         $file_dir = getUploadFilePath();
142         $file_dir .= "/";
143         $form = HTML::form(array('action'  => $request->getPostURL(),
144                                  'enctype' => 'multipart/form-data',
145                                  'method'  => 'post'));
146         $contents = HTML::div(array('class' => 'wikiaction'));
147         $contents->pushContent(HTML::input(array('type' => 'hidden',
148                                                  'name' => 'MAX_FILE_SIZE',
149                                                  'value'=> MAX_UPLOAD_SIZE)));
150         $contents->pushContent(HTML::input(array('name' => 'userfile',
151                                                  'type' => 'file',
152                                                  'size' => $size)));
153         if ($mode == 'edit') {
154             $contents->pushContent(HTML::input(array('name' => 'action',
155                                                      'type' => 'hidden',
156                                                      'value'=> 'edit')));
157             $contents->pushContent(HTML::raw(" "));
158             $contents->pushContent(HTML::input(array('value' => _("Upload"),
159                                                      'name'  => 'edit[upload]',
160                                                      'type'  => 'submit')));
161         } else {
162             $contents->pushContent(HTML::raw(" "));
163             $contents->pushContent(HTML::input(array('value' => _("Upload"),
164                                                      'type'  => 'submit')));
165         }
166         $form->pushContent($contents);
167
168         $message = HTML();
169         if ($request->isPost() and $this->only_authenticated) {
170             // Make sure that the user is logged in.
171             $user = $request->getUser();
172             if (!$user->isAuthenticated()) {
173                 global $WikiTheme;
174                 if (isa($WikiTheme, 'Theme_gforge')) {
175                     $message->pushContent(HTML::div(array('class' => 'error'),
176                                             HTML::p(_("You cannot upload files.")),
177                                             HTML::ul(
178                                               HTML::li(_("Check you are logged in.")),
179                                               HTML::li(_("Check you are in the right project.")),
180                                               HTML::li(_("Check you are a member of the current project."))
181                                             )
182                                          ));
183                 } else {
184                     $message->pushContent(HTML::div(array('class' => 'error'),
185                                             HTML::p(_("ACCESS DENIED: You must log in to upload files."))));
186                 }
187                 $result = HTML();
188                 $result->pushContent($form);
189                 $result->pushContent($message);
190                 return $result;
191             }
192         }
193         
194         $userfile = $request->getUploadedFile('userfile');
195         if ($userfile) {
196             $userfile_name = $userfile->getName();
197             $userfile_name = trim(basename($userfile_name));
198             if (UPLOAD_USERDIR) {
199                 $file_dir .= $request->_user->_userid;
200                 if (!file_exists($file_dir))
201                     mkdir($file_dir, 0775);
202                 $file_dir .= "/";
203                 $u_userfile = $request->_user->_userid . "/" . $userfile_name;
204             } else {
205                 $u_userfile = $userfile_name;
206             }
207             $u_userfile = preg_replace("/ /", "%20", $u_userfile);
208             $userfile_tmpname = $userfile->getTmpName();
209             $err_header = HTML::div(array('class' => 'error'),
210                                 HTML::p(fmt("ERROR uploading '%s'", $userfile_name)));
211             if (preg_match("/(\." . join("|\.", $this->disallowed_extensions) . ")(\.|\$)/i",
212                            $userfile_name))
213             {
214                 $message->pushContent($err_header);
215                 $message->pushContent(HTML::p(fmt("Files with extension %s are not allowed.",
216                                               join(", ", $this->disallowed_extensions))));
217             }
218             elseif (! DISABLE_UPLOAD_ONLY_ALLOWED_EXTENSIONS and 
219                     ! preg_match("/(\." . join("|\.", $this->allowed_extensions) . ")\$/i", 
220                                $userfile_name))
221             {
222                 $message->pushContent($err_header);
223                 $message->pushContent(HTML::p(fmt("Only files with the extension %s are allowed.",
224                                               join(", ", $this->allowed_extensions))));
225             }
226             elseif (preg_match("/[^._a-zA-Z0-9- ]/", $userfile_name))
227             {
228                 $message->pushContent($err_header);
229                 $message->pushContent(HTML::p(_("Invalid filename. File names may only contain alphanumeric characters and dot, underscore, space or dash.")));
230             }
231             elseif (file_exists($file_dir . $userfile_name)) {
232                 $message->pushContent($err_header);
233                 $message->pushContent(HTML::p(fmt("There is already a file with name %s uploaded.",
234                                                   $u_userfile)));
235             }
236             elseif ($userfile->getSize() > (MAX_UPLOAD_SIZE)) {
237                 $message->pushContent($err_header);
238                 $message->pushContent(HTML::p(_("Sorry but this file is too big.")));
239             }
240             elseif (move_uploaded_file($userfile_tmpname, $file_dir . $userfile_name) or
241                     (IsWindows() and rename($userfile_tmpname, $file_dir . $userfile_name))
242                     )
243             {
244                 $interwiki = new PageType_interwikimap();
245                 $link = $interwiki->link("Upload:$u_userfile");
246                 $message->pushContent(HTML::div(array('class' => 'feedback'),
247                                                 HTML::p(_("File successfully uploaded.")),
248                                                 HTML::p($link)));
249
250                 // the upload was a success and we need to mark this event in the "upload log"
251                 if ($logfile) { 
252                     $upload_log = $file_dir . basename($logfile);
253                     $this->log($userfile, $upload_log, $message);
254                 }
255                 if ($autolink) {
256                     require_once("lib/loadsave.php");
257                     $pagehandle = $dbi->getPage($page);
258                     if ($pagehandle->exists()) {// don't replace default contents
259                         $current = $pagehandle->getCurrentRevision();
260                         $version = $current->getVersion();
261                         $text = $current->getPackedContent();
262                         $newtext = $text . "\n* Upload:$u_userfile"; // don't inline images
263                         $meta = $current->_data;
264                         $meta['summary'] = sprintf(_("uploaded %s"),$u_userfile);
265                         $pagehandle->save($newtext, $version + 1, $meta);
266                     }
267                 }
268             } else {
269                 $message->pushContent($err_header);
270                 $message->pushContent(HTML::br(),_("Uploading failed."),HTML::br());
271             }
272         }
273         else {
274             $message->pushContent(HTML::br(),_("No file selected. Please select one."),HTML::br());
275         }
276
277         //$result = HTML::div( array( 'class' => 'wikiaction' ) );
278         $result = HTML();
279         $result->pushContent($form);
280         $result->pushContent($message);
281         return $result;
282     }
283
284     function log ($userfile, $upload_log, &$message) {
285         global $WikiTheme;
286         $user = $GLOBALS['request']->_user;
287         if (file_exists($upload_log) and (!is_writable($upload_log))) {
288             trigger_error(_("The upload logfile exists but is not writable."), E_USER_WARNING);
289         }
290         elseif (!$log_handle = fopen ($upload_log, "a")) {
291             trigger_error(_("Can't open the upload logfile."), E_USER_WARNING);
292         }
293         else {        // file size in KB; precision of 0.1
294             $file_size = round(($userfile->getSize())/1024, 1);
295             if ($file_size <= 0) {
296                 $file_size = "&lt; 0.1";
297             }
298             $userfile_name = $userfile->getName();
299             fwrite($log_handle,
300                    "\n"
301                    . "<tr><td><a href=\"$userfile_name\">$userfile_name</a></td>"
302                    . "<td align=\"right\">$file_size kB</td>"
303                    . "<td>&nbsp;&nbsp;" . $WikiTheme->formatDate(time()) . "</td>"
304                    . "<td>&nbsp;&nbsp;<em>" . $user->getId() . "</em></td></tr>");
305             fclose($log_handle);
306         }
307         return;
308     }
309
310 }
311
312 // (c-file-style: "gnu")
313 // Local Variables:
314 // mode: php
315 // tab-width: 8
316 // c-basic-offset: 4
317 // c-hanging-comment-ender-p: nil
318 // indent-tabs-mode: nil
319 // End:
320 ?>