4 * Copyright 2004,2005 $ThePhpWikiProgrammingTeam
5 * Copyright 2009 Marc-Etienne Vargenau, Alcatel-Lucent
7 * This file is part of PhpWiki.
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.
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.
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
25 * This plugin requires an action page (default: ModeratedPage)
26 * and provides delayed execution of restricted actions,
27 * after a special moderators request. Usually by email.
28 * http://mywiki/SomeModeratedPage?action=ModeratedPage&id=kdclcr78431zr43uhrn&pass=approve
30 * Not yet ready! part 3/3 is missing: The moderator approve/reject methods.
32 * See http://phpwiki.org/PageModeration
36 require_once("lib/WikiPlugin.php");
38 class WikiPlugin_ModeratedPage
42 return _("ModeratedPage");
44 function getDescription () {
45 return _("Support moderated pages");
47 function getDefaultArguments() {
48 return array('page' => '[pagename]',
49 'moderators' => false,
50 'require_level' => false, // 1=bogo
51 'require_access' => 'edit,remove,change',
57 function run($dbi, $argstr, &$request, $basepage) {
58 $args = $this->getArgs($argstr, $request);
60 // Handle moderation request from urls sent by email
61 if (!empty($args['id']) and !empty($args['pass'])) {
63 return $this->error("No page specified");
64 $page = $dbi->getPage($args['page']);
65 if ($moderated = $page->get("moderated")) {
66 if (array_key_exists($args['id'], $moderated['data'])) {
67 $moderation = $moderated['data'][$args['id']];
70 if ($request->isPost()) {
71 $button = $request->getArg('ModeratedPage');
72 if (isset($button['reject']))
73 return $this->reject($request, $args, $moderation);
74 elseif (isset($button['approve']))
75 return $this->approve($request, $args, $moderation);
77 return $this->error("Wrong button pressed");
79 if ($args['pass'] == 'approve')
80 return $this->approve($request, $args, $moderation);
81 elseif ($args['pass'] == 'reject')
82 return $this->reject($request, $args, $moderation);
84 return $this->error("Wrong pass ".$args['pass']);
86 return $this->error("Wrong id ".htmlentities($args['id']));
94 * resolve moderators and require_access (not yet) from actionpage plugin argstr
96 function resolve_argstr(&$request, $argstr) {
97 $args = $this->getArgs($argstr);
98 $group = $request->getGroup();
99 if (empty($args['moderators'])) {
100 $admins = $group->getSpecialMembersOf(GROUP_ADMIN);
101 // email or usernames?
102 $args['moderators'] = array_merge($admins, array(ADMIN_USER));
104 // resolve possible group names
105 $moderators = explode(',', $args['moderators']);
106 for ($i=0; $i < count($moderators); $i++) {
107 $members = $group->getMembersOf($moderators[$i]);
108 if (!empty($members)) {
109 array_splice($moderators, $i, 1, $members);
112 if (!$moderators) $moderators = array(ADMIN_USER);
113 $args['moderators'] = $moderators;
115 //resolve email for $args['moderators']
116 $page = $request->getPage();
118 foreach ($args['moderators'] as $userid) {
121 require_once("lib/MailNotify.php");
122 $mail = new MailNotify($page->getName());
124 list($args['emails'], $args['moderators']) =
125 $mail->getPageChangeEmails(array($page->getName() => $users));
127 if (!empty($args['require_access'])) {
128 $args['require_access'] = preg_split("/\s*,\s*/", $args['require_access']);
129 if (empty($args['require_access']))
130 unset($args['require_access']);
132 if ($args['require_level'] !== false) {
133 $args['require_level'] = (integer) $args['require_level'];
136 unset($args['page']);
137 unset($args['pass']);
142 * Handle client-side moderation change request.
143 * Hook called on the lock action, if moderation metadata already exists.
145 function lock_check(&$request, &$page, $moderated) {
146 $action_page = $request->getPage(_("ModeratedPage"));
147 $status = $this->getSiteStatus($request, $action_page);
148 if (is_array($status)) {
149 if (empty($status['emails'])) {
150 trigger_error(_("ModeratedPage: No emails for the moderators defined"),
154 $page->set('moderation', array('status' => $status));
155 return $this->notice(
156 fmt("ModeratedPage status update:\n Moderators: '%s'\n require_access: '%s'",
157 join(',', $status['moderators']), $status['require_access']));
159 $page->set('moderation', false);
160 return $this->notice(HTML($status,
161 fmt("'%s' is no ModeratedPage anymore.", $page->getName())));
166 * Handle client-side moderation change request by the user.
167 * Hook called on the lock action, if moderation metadata should be added.
168 * Need to store the the plugin args (who, when) in the page meta-data
170 function lock_add(&$request, &$page, &$action_page) {
171 $status = $this->getSiteStatus($request, $action_page);
172 if (is_array($status)) {
173 if (empty($status['emails'])) {
174 // We really should present such warnings prominently.
175 trigger_error(_("ModeratedPage: No emails for the moderators defined"),
179 $page->set('moderation', array('status' => $status));
180 return $this->notice(
181 fmt("ModeratedPage status update: '%s' is now a ModeratedPage.\n Moderators: '%s'\n require_access: '%s'",
182 $page->getName(), join(',', $status['moderators']), $status['require_access']));
189 function notice($msg) {
190 return HTML::div(array('class' => 'wiki-edithelp'), $msg);
193 function generateId() {
196 for ($i = 1; $i <= 25; $i++) {
197 $r = function_exists('mt_rand') ? mt_rand(55, 90) : rand(55, 90);
198 $s .= chr(($r < 65) ? ($r-17) : $r);
200 $len = $r = function_exists('mt_rand') ? mt_rand(15, 25) : rand(15,25);
201 return substr(base64_encode($s),3,$len);
205 * Handle client-side POST moderation request on any moderated page.
206 * if ($page->get('moderation')) WikiPlugin_ModeratedPage::handler(...);
207 * return false if not handled (pass through), true if handled and displayed.
209 function handler(&$request, &$page) {
210 $action = $request->getArg('action');
211 $moderated = $page->get('moderated');
212 // cached version, need re-lock of each page to update moderators
213 if (!empty($moderated['status']))
214 $status = $moderated['status'];
216 $action_page = $request->getPage(_("ModeratedPage"));
217 $status = $this->getSiteStatus($request, $action_page);
218 $moderated['status'] = $status;
220 if (empty($status['emails'])) {
221 trigger_error(_("ModeratedPage: No emails for the moderators defined"),
226 if (!empty($status['require_access'])
227 and !in_array(action2access($action), $status['require_access']))
228 return false; // allow and fall through, not moderated
229 if (!empty($status['require_level'])
230 and $request->_user->_level >= $status['require_level'])
231 return false; // allow and fall through, not moderated
232 // else all post actions are moderated by default
233 if (1) /* or in_array($action, array('edit','remove','rename')*/ {
234 $id = $this->generateId();
235 while (!empty($moderated['data'][$id])) $id = $this->generateId(); // avoid duplicates
236 $moderated['id'] = $id; // overwrite current id
237 $tempuser = $request->_user;
238 if (isset($tempuser->_HomePagehandle))
239 unset($tempuser->_HomePagehandle);
240 $moderated['data'][$id] = array( // add current request
241 'timestamp' => time(),
242 'userid' => $request->_user->getId(),
243 'args' => $request->getArgs(),
244 'user' => serialize( $tempuser ),
246 $this->_tokens['CONTENT'] =
247 HTML::div(array('class' => 'wikitext'),
248 fmt("%s: action forwarded to moderator %s",
250 join(", ", $status['moderators'])
253 require_once("lib/MailNotify.php");
254 $pagename = $page->getName();
255 $mailer = new MailNotify($pagename);
256 $subject = "[".WIKI_NAME.'] '.$action.': '._("ModeratedPage").' '.$pagename;
257 $content = "You are approved as Moderator of the ".WIKI_NAME. " wiki.\n".
258 "Someone wanted to edit a moderated page, which you have to approve or reject.\n\n".
259 $action.': '._("ModeratedPage").' '.$pagename."\n"
260 //. serialize($moderated['data'][$id])
261 ."\n<".WikiURL($pagename, array('action' => _("ModeratedPage"),
262 'id' => $id, 'pass' => 'approve'), 1).">"
263 ."\n<".WikiURL($pagename, array('action' => _("ModeratedPage"),
264 'id' => $id, 'pass' => 'reject'), 1).">\n";
265 $mailer->emails = $mailer->userids = $status['emails'];
266 $mailer->from = $request->_user->_userid;
267 if ($mailer->sendMail($subject, $content, "Moderation notice")) {
268 $page->set('moderated', $moderated);
269 return false; // pass thru
272 $page->set('moderated', $moderated);
273 //FIXME: This msg gets lost on the edit redirect
274 trigger_error(_("ModeratedPage Notification Error: Couldn't send email"),
283 * Handle admin-side moderation resolve.
284 * We might have to convert the GET to a POST request to continue
285 * with the left-over stored request.
286 * Better we display a post form for verification.
288 function approve(&$request, $args, &$moderation) {
289 if ($request->isPost()) {
290 // this is unsafe because we dont know if it will succeed. but we tried.
291 $this->cleanup_and_notify($request, $args, $moderation);
292 // start from scratch, dispatch the action as in lib/main to the action handler
293 $request->discardOutput();
294 $oldargs = $request->args;
295 $olduser = $request->_user;
296 $request->args = $moderation['args'];
297 $request->_user->_userid = $moderation['userid']; // keep current perms but fake the id.
298 // TODO: fake author ip also
299 extract($request->args);
300 $method = "action_$action";
301 if (method_exists($request, $method)) {
302 $request->{$method}();
304 elseif ($page = $this->findActionPage($action)) {
305 $this->actionpage($page);
308 $this->finish(fmt("%s: Bad action", $action));
310 // now we are gone and nobody brings us back here.
312 //$moderated['data'][$id]->args->action+edit(array)+...
313 // timestamp,user(obj)+userid
314 // handle $moderated['data'][$id]['args']['action']
316 return $this->_approval_form($request, $args, $moderation, 'approve');
321 * Handle admin-side moderation resolve.
323 function reject(&$request, $args, &$moderation) {
324 // check id, delete action
325 if ($request->isPost()) {
326 // clean up and notify the requestor. Mabye: store and revert to have a diff later on?
327 $this->cleanup_and_notify($request, $args, $moderation);
329 return $this->_approval_form($request, $args, $moderation, 'reject');
333 function cleanup_and_notify (&$request, $args, &$moderation) {
334 $pagename = $moderation['args']['pagename'];
335 $page = $request->_dbi->getPage($pagename);
336 $pass = $args['pass']; // accept or reject
337 $reason = $args['reason']; // summary why
338 $user = $moderation['args']['user'];
339 $action = $moderation['args']['action'];
341 unset($moderation['data'][$id]);
342 unset($moderation['id']);
343 $page->set('moderation', $moderation);
345 // TODO: Notify the user, only if the user has an email:
346 if ($email = $user->getPref('email')) {
347 $action_page = $request->getPage(_("ModeratedPage"));
348 $status = $this->getSiteStatus($request, $action_page);
349 require_once("lib/MailNotify.php");
350 $mailer = new MailNotify($pagename);
351 $subject = "[".WIKI_NAME."] $pass $action "._("ModeratedPage").': '.$pagename;
352 $mailer->from = $request->_user->UserFrom();
353 $content = sprintf(_("%s approved your wiki action from %s"),
354 $mailer->from,CTime($moderation['timestamp']))
358 ."\n<".WikiURL($pagename).">\n";
359 $mailer->emails = $mailer->userids = $email;
360 $mailer->sendMail($subject, $content, "Approval notice");
364 function _approval_form(&$request, $args, $moderation, $pass='approve') {
365 $header = HTML::h3(_("Please approve or reject this request:"));
367 $loader = new WikiPluginLoader();
368 $BackendInfo = $loader->getPlugin("_BackendInfo");
369 $table = HTML::table(array('border' => 1,
371 'cellspacing' => 0));
374 if ($moderation['args']['action'] == 'edit') {
375 $pagename = $moderation['args']['pagename'];
376 $p = $request->_dbi->getPage($pagename);
377 $rev = $p->getCurrentRevision(true);
378 $curr_content = $rev->getPackedContent();
379 $new_content = $moderation['args']['edit']['content'];
380 include_once("lib/difflib.php");
381 $diff2 = new Diff($curr_content, $new_content);
382 $fmt = new UnifiedDiffFormatter(/*$context_lines*/);
383 $diff = $pagename . " Current Version " .
384 Iso8601DateTime($p->get('mtime')) . "\n";
385 $diff .= $pagename . " Edited Version " .
386 Iso8601DateTime($moderation['timestamp']) . "\n";
387 $diff .= $fmt->format($diff2);
389 $content->pushContent($BackendInfo->_showhash("Request",
390 array('User' => $moderation['userid'],
391 'When' => CTime($moderation['timestamp']),
392 'Pagename' => $pagename,
393 'Action' => $moderation['args']['action'],
394 'Diff' => HTML::pre($diff))));
395 $content_dbg = $table;
397 $BackendInfo->_fixupData($myargs);
398 $content_dbg->pushContent($BackendInfo->_showhash("raw request args", $myargs));
399 $BackendInfo->_fixupData($moderation);
400 $content_dbg->pushContent($BackendInfo->_showhash("raw moderation data", $moderation));
401 $reason = HTML::div(_("Reason: "), HTML::textarea(array('name' => 'reason')));
402 $approve = Button('submit:ModeratedPage[approve]', _("Approve"),
403 $pass == 'approve' ? 'wikiadmin' : 'button');
404 $reject = Button('submit:ModeratedPage[reject]', _("Reject"),
405 $pass == 'reject' ? 'wikiadmin' : 'button');
406 $args['action'] = _("ModeratedPage");
407 return HTML::form(array('action' => $request->getPostURL(),
410 $content, HTML::p(""), $content_dbg,
414 : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)),
416 $pass == 'approve' ? HTML::p($approve, $reject)
417 : HTML::p($reject, $approve));
421 * Get the side-wide ModeratedPage status, reading the action-page args.
422 * Who are the moderators? What actions should be moderated?
424 function getSiteStatus(&$request, &$action_page) {
425 $loader = new WikiPluginLoader();
426 $rev = $action_page->getCurrentRevision();
427 $content = $rev->getPackedContent();
428 list($pi) = explode("\n", $content, 2); // plugin ModeratedPage must be first line!
429 if ($parsed = $loader->parsePI($pi)) {
430 $plugin =& $parsed[1];
431 if ($plugin->getName() != _("ModeratedPage"))
432 return $this->error(sprintf(_("<?plugin ModeratedPage ... ?> not found in first line of %s"),
433 $action_page->getName()));
434 if (!$action_page->get('locked'))
435 return $this->error(sprintf(_("%s is not locked!"),
436 $action_page->getName()));
437 return $plugin->resolve_argstr($request, $parsed[2]);
439 return $this->error(sprintf(_("<?plugin ModeratedPage ... ?> not found in first line of %s"),
440 $action_page->getName()));
451 // c-hanging-comment-ender-p: nil
452 // indent-tabs-mode: nil