]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/ModeratedPage.php
Add missing return
[SourceForge/phpwiki.git] / lib / plugin / ModeratedPage.php
1 <?php
2
3 /*
4  * Copyright 2004,2005 $ThePhpWikiProgrammingTeam
5  * Copyright 2009 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 along
20  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23
24 /**
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
29  *
30  * Not yet ready! part 3/3 is missing: The moderator approve/reject methods.
31  *
32  * See http://phpwiki.org/PageModeration
33  * Author: ReiniUrban
34  */
35
36 require_once 'lib/WikiPlugin.php';
37
38 class WikiPlugin_ModeratedPage
39     extends WikiPlugin
40 {
41     function getName()
42     {
43         return _("ModeratedPage");
44     }
45
46     function getDescription()
47     {
48         return _("Support moderated pages.");
49     }
50
51     function getDefaultArguments()
52     {
53         return array('page' => '[pagename]',
54             'moderators' => false,
55             'require_level' => false, // 1=bogo
56             'require_access' => 'edit,remove,change',
57             'id' => '',
58             'pass' => '',
59         );
60     }
61
62     function run($dbi, $argstr, &$request, $basepage)
63     {
64         $args = $this->getArgs($argstr, $request);
65
66         // Handle moderation request from URLs sent by e-mail
67         if (!empty($args['id']) and !empty($args['pass'])) {
68             if (!$args['page']) {
69                 return $this->error(sprintf(_("A required argument “%s” is missing."), 'page'));
70             }
71             $page = $dbi->getPage($args['page']);
72             if ($moderated = $page->get("moderated")) {
73                 if (array_key_exists($args['id'], $moderated['data'])) {
74                     $moderation = $moderated['data'][$args['id']];
75                     // handle defaults:
76                     //   approve or reject
77                     if ($request->isPost()) {
78                         $button = $request->getArg('ModeratedPage');
79                         if (isset($button['reject']))
80                             return $this->reject($request, $args, $moderation);
81                         elseif (isset($button['approve']))
82                             return $this->approve($request, $args, $moderation); else
83                             return $this->error("Wrong button pressed");
84                     }
85                     if ($args['pass'] == 'approve')
86                         return $this->approve($request, $args, $moderation);
87                     elseif ($args['pass'] == 'reject')
88                         return $this->reject($request, $args, $moderation); else
89                         return $this->error("Wrong pass " . $args['pass']);
90                 } else {
91                     return $this->error("Wrong id " . htmlentities($args['id']));
92                 }
93             }
94         }
95         return HTML::raw('');
96     }
97
98     /**
99      * resolve moderators and require_access (not yet) from actionpage plugin argstr
100      */
101     function resolve_argstr(&$request, $argstr)
102     {
103         $args = $this->getArgs($argstr);
104         $group = $request->getGroup();
105         if (empty($args['moderators'])) {
106             $admins = $group->getSpecialMembersOf(GROUP_ADMIN);
107             // email or usernames?
108             $args['moderators'] = array_merge($admins, array(ADMIN_USER));
109         } else {
110             // resolve possible group names
111             $moderators = explode(',', $args['moderators']);
112             for ($i = 0; $i < count($moderators); $i++) {
113                 $members = $group->getMembersOf($moderators[$i]);
114                 if (!empty($members)) {
115                     array_splice($moderators, $i, 1, $members);
116                 }
117             }
118             if (!$moderators) $moderators = array(ADMIN_USER);
119             $args['moderators'] = $moderators;
120         }
121         //resolve email for $args['moderators']
122         $page = $request->getPage();
123         $users = array();
124         foreach ($args['moderators'] as $userid) {
125             $users[$userid] = 0;
126         }
127         require_once 'lib/MailNotify.php';
128         $mail = new MailNotify($page->getName());
129
130         list($args['emails'], $args['moderators']) =
131             $mail->getPageChangeEmails(array($page->getName() => $users));
132
133         if (!empty($args['require_access'])) {
134             $args['require_access'] = preg_split("/\s*,\s*/", $args['require_access']);
135             if (empty($args['require_access']))
136                 unset($args['require_access']);
137         }
138         if ($args['require_level'] !== false) {
139             $args['require_level'] = (integer)$args['require_level'];
140         }
141         unset($args['id']);
142         unset($args['page']);
143         unset($args['pass']);
144         return $args;
145     }
146
147     /**
148      * Handle client-side moderation change request.
149      * Hook called on the lock action, if moderation metadata already exists.
150      */
151     function lock_check(&$request, &$page, $moderated)
152     {
153         $action_page = $request->getPage(_("ModeratedPage"));
154         $status = $this->getSiteStatus($request, $action_page);
155         if (is_array($status)) {
156             if (empty($status['emails'])) {
157                 trigger_error(_("No e-mails for the moderators defined"), E_USER_WARNING);
158                 return false;
159             }
160             $page->set('moderation', array('status' => $status));
161             return $this->notice(
162                 fmt("ModeratedPage status update:\n  Moderators: “%s”\n  require_access: “%s”",
163                     join(',', $status['moderators']), $status['require_access']));
164         } else {
165             $page->set('moderation', false);
166             return $this->notice(HTML($status,
167                 fmt("“%s” is no ModeratedPage anymore.", $page->getName())));
168         }
169     }
170
171     /**
172      * Handle client-side moderation change request by the user.
173      * Hook called on the lock action, if moderation metadata should be added.
174      * Need to store the the plugin args (who, when) in the page meta-data
175      */
176     function lock_add(&$request, &$page, &$action_page)
177     {
178         $status = $this->getSiteStatus($request, $action_page);
179         if (is_array($status)) {
180             if (empty($status['emails'])) {
181                 // We really should present such warnings prominently.
182                 trigger_error(_("No e-mails for the moderators defined"), E_USER_WARNING);
183                 return false;
184             }
185             $page->set('moderation', array('status' => $status));
186             return $this->notice(
187                 fmt("ModeratedPage status update: “%s” is now a ModeratedPage.\n  Moderators: “%s”\n  require_access: “%s”",
188                     $page->getName(), join(',', $status['moderators']), $status['require_access']));
189         } else { // error
190             return $status;
191         }
192     }
193
194     function notice($msg)
195     {
196         return HTML::div(array('class' => 'wiki-edithelp'), $msg);
197     }
198
199     function generateId()
200     {
201         better_srand();
202         $s = "";
203         for ($i = 1; $i <= 25; $i++) {
204             $r = function_exists('mt_rand') ? mt_rand(55, 90) : rand(55, 90);
205             $s .= chr(($r < 65) ? ($r - 17) : $r);
206         }
207         $len = $r = function_exists('mt_rand') ? mt_rand(15, 25) : rand(15, 25);
208         return substr(base64_encode($s), 3, $len);
209     }
210
211     /**
212      * Handle client-side POST moderation request on any moderated page.
213      *   if ($page->get('moderation')) WikiPlugin_ModeratedPage::handler(...);
214      * return false if not handled (pass through), true if handled and displayed.
215      */
216     function handler(&$request, &$page)
217     {
218         $action = $request->getArg('action');
219         $moderated = $page->get('moderated');
220         // cached version, need re-lock of each page to update moderators
221         if (!empty($moderated['status']))
222             $status = $moderated['status'];
223         else {
224             $action_page = $request->getPage(_("ModeratedPage"));
225             $status = $this->getSiteStatus($request, $action_page);
226             $moderated['status'] = $status;
227         }
228         if (empty($status['emails'])) {
229             trigger_error(_("No e-mails for the moderators defined"), E_USER_WARNING);
230             return true;
231         }
232         // which action?
233         if (!empty($status['require_access'])
234             and !in_array(action2access($action), $status['require_access'])
235         )
236             return false; // allow and fall through, not moderated
237         if (!empty($status['require_level'])
238             and $request->_user->_level >= $status['require_level']
239         )
240             return false; // allow and fall through, not moderated
241         // else all post actions are moderated by default
242         if (1) /* or in_array($action, array('edit','remove','rename')*/ {
243             $id = $this->generateId();
244             while (!empty($moderated['data'][$id])) $id = $this->generateId(); // avoid duplicates
245             $moderated['id'] = $id; // overwrite current id
246             $tempuser = $request->_user;
247             if (isset($tempuser->_HomePagehandle))
248                 unset($tempuser->_HomePagehandle);
249             $moderated['data'][$id] = array( // add current request
250                 'timestamp' => time(),
251                 'userid' => $request->_user->getId(),
252                 'args' => $request->getArgs(),
253                 'user' => serialize($tempuser),
254             );
255             $this->_tokens['CONTENT'] =
256                 HTML::div(array('class' => 'wikitext'),
257                     fmt("%s: action forwarded to moderator %s",
258                         $action,
259                         join(", ", $status['moderators'])
260                     ));
261             // Send e-mail
262             require_once 'lib/MailNotify.php';
263             $pagename = $page->getName();
264             $mailer = new MailNotify($pagename);
265             $subject = "[" . WIKI_NAME . '] ' . $action . _(": ") . _("ModeratedPage") . ' ' . $pagename;
266             $content = "You are approved as Moderator of the " . WIKI_NAME . " wiki.\n" .
267                 "Someone wanted to edit a moderated page, which you have to approve or reject.\n\n" .
268                 $action . _(": ") . _("ModeratedPage") . ' ' . $pagename . "\n"
269                 //. serialize($moderated['data'][$id])
270                 . "\n<" . WikiURL($pagename, array('action' => _("ModeratedPage"),
271                 'id' => $id, 'pass' => 'approve'), 1) . ">"
272                 . "\n<" . WikiURL($pagename, array('action' => _("ModeratedPage"),
273                 'id' => $id, 'pass' => 'reject'), 1) . ">\n";
274             $mailer->emails = $mailer->userids = $status['emails'];
275             $mailer->from = $request->_user->_userid;
276             if ($mailer->sendMail($subject, $content, "Moderation notice")) {
277                 $page->set('moderated', $moderated);
278                 return false; // pass thru
279             } else {
280                 //DELETEME!
281                 $page->set('moderated', $moderated);
282                 //FIXME: This msg gets lost on the edit redirect
283                 trigger_error(_("ModeratedPage Notification Error: Couldn't send e-mail"),
284                     E_USER_ERROR);
285                 return true;
286             }
287         }
288         return false;
289     }
290
291     /**
292      * Handle admin-side moderation resolve.
293      * We might have to convert the GET to a POST request to continue
294      * with the left-over stored request.
295      * Better we display a post form for verification.
296      */
297     function approve(&$request, $args, &$moderation)
298     {
299         if ($request->isPost()) {
300             // this is unsafe because we dont know if it will succeed. but we tried.
301             $this->cleanup_and_notify($request, $args, $moderation);
302             // start from scratch, dispatch the action as in lib/main to the action handler
303             $request->discardOutput();
304             $oldargs = $request->args;
305             $olduser = $request->_user;
306             $request->args = $moderation['args'];
307             $request->_user->_userid = $moderation['userid']; // keep current perms but fake the id.
308             // TODO: fake author ip also
309             extract($request->args);
310             $method = "action_$action";
311             if (method_exists($request, $method)) {
312                 $request->{$method}();
313             } elseif ($page = $this->findActionPage($action)) {
314                 $this->actionpage($page);
315             } else {
316                 $this->finish(fmt("%s: Bad action", $action));
317             }
318             // now we are gone and nobody brings us back here.
319
320             //$moderated['data'][$id]->args->action+edit(array)+...
321             //                              timestamp,user(obj)+userid
322             // handle $moderated['data'][$id]['args']['action']
323         } else {
324             return $this->approval_form($request, $args, $moderation, 'approve');
325         }
326         return '';
327     }
328
329     /**
330      * Handle admin-side moderation resolve.
331      */
332     function reject(&$request, $args, &$moderation)
333     {
334         // check id, delete action
335         if ($request->isPost()) {
336             // clean up and notify the requestor. Mabye: store and revert to have a diff later on?
337             $this->cleanup_and_notify($request, $args, $moderation);
338         } else {
339             return $this->approval_form($request, $args, $moderation, 'reject');
340         }
341         return '';
342     }
343
344     function cleanup_and_notify(&$request, $args, &$moderation)
345     {
346         $pagename = $moderation['args']['pagename'];
347         $page = $request->_dbi->getPage($pagename);
348         $pass = $args['pass']; // accept or reject
349         $reason = $args['reason']; // summary why
350         $user = $moderation['args']['user'];
351         $action = $moderation['args']['action'];
352         $id = $args['id'];
353         unset($moderation['data'][$id]);
354         unset($moderation['id']);
355         $page->set('moderation', $moderation);
356
357         // TODO: Notify the user, only if the user has an email:
358         if ($email = $user->getPref('email')) {
359             $action_page = $request->getPage(_("ModeratedPage"));
360             $status = $this->getSiteStatus($request, $action_page);
361             require_once 'lib/MailNotify.php';
362             $mailer = new MailNotify($pagename);
363             $subject = "[" . WIKI_NAME . "] $pass $action " . _("ModeratedPage") . _(": ") . $pagename;
364             $mailer->from = $request->_user->UserFrom();
365             $content = sprintf(_("%s approved your wiki action from %s"),
366                 $mailer->from, CTime($moderation['timestamp']))
367                 . "\n\n"
368                 . "Decision: " . $pass
369                 . "Reason: " . $reason
370                 . "\n<" . WikiURL($pagename) . ">\n";
371             $mailer->emails = $mailer->userids = $email;
372             $mailer->sendMail($subject, $content, "Approval notice");
373         }
374     }
375
376     private function approval_form(&$request, $args, $moderation, $pass = 'approve')
377     {
378         $header = HTML::h3(_("Please approve or reject this request:"));
379
380         $loader = new WikiPluginLoader();
381         $BackendInfo = $loader->getPlugin("_BackendInfo");
382         $table = HTML::table(array('border' => 1,
383             'cellpadding' => 2,
384             'cellspacing' => 0));
385         $content = $table;
386         $diff = '';
387         if ($moderation['args']['action'] == 'edit') {
388             $pagename = $moderation['args']['pagename'];
389             $p = $request->_dbi->getPage($pagename);
390             $rev = $p->getCurrentRevision(true);
391             $curr_content = $rev->getPackedContent();
392             $new_content = $moderation['args']['edit']['content'];
393             include_once 'lib/difflib.php';
394             $diff2 = new Diff($curr_content, $new_content);
395             $fmt = new UnifiedDiffFormatter( /*$context_lines*/);
396             $diff = $pagename . " Current Version " .
397                 Iso8601DateTime($p->get('mtime')) . "\n";
398             $diff .= $pagename . " Edited Version " .
399                 Iso8601DateTime($moderation['timestamp']) . "\n";
400             $diff .= $fmt->format($diff2);
401         }
402         $content->pushContent($BackendInfo->_showhash("Request",
403             array('User' => $moderation['userid'],
404                 'When' => CTime($moderation['timestamp']),
405                 'Pagename' => $pagename,
406                 'Action' => $moderation['args']['action'],
407                 'Diff' => HTML::pre($diff))));
408         $content_dbg = $table;
409         $myargs = $args;
410         $BackendInfo->_fixupData($myargs);
411         $content_dbg->pushContent($BackendInfo->_showhash("raw request args", $myargs));
412         $BackendInfo->_fixupData($moderation);
413         $content_dbg->pushContent($BackendInfo->_showhash("raw moderation data", $moderation));
414         $reason = HTML::div(_("Reason: "), HTML::textarea(array('name' => 'reason')));
415         $approve = Button('submit:ModeratedPage[approve]', _("Approve"),
416             $pass == 'approve' ? 'wikiadmin' : 'button');
417         $reject = Button('submit:ModeratedPage[reject]', _("Reject"),
418             $pass == 'reject' ? 'wikiadmin' : 'button');
419         $args['action'] = _("ModeratedPage");
420         return HTML::form(array('action' => $request->getPostURL(),
421                 'method' => 'post'),
422             $header,
423             $content, HTML::p(""), $content_dbg,
424             $reason,
425             ENABLE_PAGEPERM
426                 ? ''
427                 : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)),
428             HiddenInputs($args),
429             $pass == 'approve' ? HTML::p($approve, $reject)
430                 : HTML::p($reject, $approve));
431     }
432
433     /**
434      * Get the side-wide ModeratedPage status, reading the action-page args.
435      * Who are the moderators? What actions should be moderated?
436      */
437     function getSiteStatus(&$request, &$action_page)
438     {
439         $loader = new WikiPluginLoader();
440         $rev = $action_page->getCurrentRevision();
441         $content = $rev->getPackedContent();
442         list($pi) = explode("\n", $content, 2); // plugin ModeratedPage must be first line!
443         if ($parsed = $loader->parsePI($pi)) {
444             $plugin =& $parsed[1];
445             if ($plugin->getName() != _("ModeratedPage"))
446                 return $this->error(sprintf(_("<<ModeratedPage ... >> not found in first line of %s"),
447                     $action_page->getName()));
448             if (!$action_page->get('locked'))
449                 return $this->error(sprintf(_("%s is not locked!"),
450                     $action_page->getName()));
451             return $plugin->resolve_argstr($request, $parsed[2]);
452         } else {
453             return $this->error(sprintf(_("<<ModeratedPage ... >> not found in first line of %s"),
454                 $action_page->getName()));
455         }
456     }
457
458 }
459
460 // Local Variables:
461 // mode: php
462 // tab-width: 8
463 // c-basic-offset: 4
464 // c-hanging-comment-ender-p: nil
465 // indent-tabs-mode: nil
466 // End: