]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/ModeratedPage.php
Translate ": " so that a space can be added in French
[SourceForge/phpwiki.git] / lib / plugin / ModeratedPage.php
1 <?php // -*-php-*-
2 // rcs_id('$Id$');
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
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  * 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         return _("ModeratedPage");
43     }
44     function getDescription () {
45         return _("Support moderated pages");
46     }
47     function getDefaultArguments() {
48         return array('page'          => '[pagename]',
49                      'moderators'    => false,
50                      'require_level' => false,   // 1=bogo
51                      'require_access' => 'edit,remove,change',
52                      'id'   => '',
53                      'pass' => '',
54                     );
55     }
56
57     function run($dbi, $argstr, &$request, $basepage) {
58         $args = $this->getArgs($argstr, $request);
59
60         // Handle moderation request from urls sent by email
61         if (!empty($args['id']) and !empty($args['pass'])) {
62             if (!$args['page'])
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']];
68                     // handle defaults:
69                     //   approve or reject
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);
76                             else
77                                 return $this->error("Wrong button pressed");
78                     }
79                     if ($args['pass'] == 'approve')
80                         return $this->approve($request, $args, $moderation);
81                     elseif ($args['pass'] == 'reject')
82                         return $this->reject($request, $args, $moderation);
83                     else
84                         return $this->error("Wrong pass ".$args['pass']);
85                 } else {
86                     return $this->error("Wrong id ".htmlentities($args['id']));
87                 }
88             }
89         }
90         return HTML::raw('');
91     }
92
93     /**
94      * resolve moderators and require_access (not yet) from actionpage plugin argstr
95      */
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));
103         } else {
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);
110                 }
111             }
112             if (!$moderators) $moderators = array(ADMIN_USER);
113             $args['moderators'] = $moderators;
114         }
115         //resolve email for $args['moderators']
116         $page = $request->getPage();
117         $users = array();
118         foreach ($args['moderators'] as $userid) {
119             $users[$userid] = 0;
120         }
121         require_once("lib/MailNotify.php");
122         $mail = new MailNotify($page->getName());
123
124         list($args['emails'], $args['moderators']) =
125             $mail->getPageChangeEmails(array($page->getName() => $users));
126
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']);
131         }
132         if ($args['require_level'] !== false) {
133             $args['require_level'] = (integer) $args['require_level'];
134         }
135         unset($args['id']);
136         unset($args['page']);
137         unset($args['pass']);
138         return $args;
139     }
140
141     /**
142      * Handle client-side moderation change request.
143      * Hook called on the lock action, if moderation metadata already exists.
144      */
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"),
151                               E_USER_WARNING);
152                 return false;
153             }
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']));
158         } else {
159             $page->set('moderation', false);
160             return $this->notice(HTML($status,
161                         fmt("'%s' is no ModeratedPage anymore.", $page->getName())));
162         }
163     }
164
165     /**
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
169      */
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"),
176                               E_USER_WARNING);
177                 return false;
178             }
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']));
183         }
184         else { // error
185             return $status;
186         }
187     }
188
189     function notice($msg) {
190             return HTML::div(array('class' => 'wiki-edithelp'), $msg);
191     }
192
193     function generateId() {
194         better_srand();
195         $s = "";
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);
199         }
200         $len = $r = function_exists('mt_rand') ? mt_rand(15, 25) : rand(15,25);
201         return substr(base64_encode($s),3,$len);
202     }
203
204     /**
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.
208      */
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'];
215             else {
216             $action_page = $request->getPage(_("ModeratedPage"));
217             $status = $this->getSiteStatus($request, $action_page);
218             $moderated['status'] = $status;
219             }
220         if (empty($status['emails'])) {
221             trigger_error(_("ModeratedPage: No emails for the moderators defined"),
222                           E_USER_WARNING);
223             return true;
224         }
225         // which action?
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 ),
245                                             );
246             $this->_tokens['CONTENT'] =
247                 HTML::div(array('class' => 'wikitext'),
248                           fmt("%s: action forwarded to moderator %s",
249                               $action,
250                               join(", ", $status['moderators'])
251                               ));
252             // Send email
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
270             } else {
271                 //DELETEME!
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"),
275                               E_USER_ERROR);
276                 return true;
277             }
278             }
279         return false;
280     }
281
282     /**
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.
287      */
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}();
303             }
304             elseif ($page = $this->findActionPage($action)) {
305                 $this->actionpage($page);
306             }
307             else {
308                 $this->finish(fmt("%s: Bad action", $action));
309             }
310             // now we are gone and nobody brings us back here.
311
312             //$moderated['data'][$id]->args->action+edit(array)+...
313             //                              timestamp,user(obj)+userid
314             // handle $moderated['data'][$id]['args']['action']
315         } else {
316             return $this->_approval_form($request, $args, $moderation, 'approve');
317         }
318     }
319
320     /**
321      * Handle admin-side moderation resolve.
322      */
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);
328         } else {
329             return $this->_approval_form($request, $args, $moderation, 'reject');
330         }
331     }
332
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'];
340         $id = $args['id'];
341         unset($moderation['data'][$id]);
342         unset($moderation['id']);
343         $page->set('moderation', $moderation);
344
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']))
355                 ."\n\n"
356                 ."Decision: ".$pass
357                 ."Reason: ".$reason
358                 ."\n<".WikiURL($pagename).">\n";
359             $mailer->emails = $mailer->userids = $email;
360             $mailer->sendMail($subject, $content, "Approval notice");
361         }
362     }
363
364     function _approval_form(&$request, $args, $moderation, $pass='approve') {
365         $header = HTML::h3(_("Please approve or reject this request:"));
366
367         $loader = new WikiPluginLoader();
368         $BackendInfo = $loader->getPlugin("_BackendInfo");
369         $table = HTML::table(array('border' => 1,
370                                      'cellpadding' => 2,
371                                      'cellspacing' => 0));
372         $content = $table;
373         $diff = '';
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);
388         }
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;
396         $myargs  = $args;
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(),
408                                 'method' => 'post'),
409                           $header,
410                           $content, HTML::p(""), $content_dbg,
411                           $reason,
412                           ENABLE_PAGEPERM
413                             ? ''
414                             : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)),
415                           HiddenInputs($args),
416                           $pass == 'approve' ? HTML::p($approve, $reject)
417                                                : HTML::p($reject, $approve));
418     }
419
420     /**
421      * Get the side-wide ModeratedPage status, reading the action-page args.
422      * Who are the moderators? What actions should be moderated?
423      */
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(_("<<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]);
438         } else {
439             return $this->error(sprintf(_("<<ModeratedPage ... >> not found in first line of %s"),
440                                         $action_page->getName()));
441         }
442     }
443
444 };
445
446 // Local Variables:
447 // mode: php
448 // tab-width: 8
449 // c-basic-offset: 4
450 // c-hanging-comment-ender-p: nil
451 // indent-tabs-mode: nil
452 // End:
453 ?>