xref: /dokuwiki/inc/actions.php (revision 86228f109464404b30ea74164e855ef146c87249)
1<?php
2/**
3 * DokuWiki Actions
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9if(!defined('DOKU_INC')) die('meh.');
10
11/**
12 * Call the needed action handlers
13 *
14 * @author Andreas Gohr <andi@splitbrain.org>
15 * @triggers ACTION_ACT_PREPROCESS
16 * @triggers ACTION_HEADERS_SEND
17 */
18function act_dispatch(){
19    global $INFO;
20    global $ACT;
21    global $ID;
22    global $QUERY;
23    global $lang;
24    global $conf;
25    global $license;
26
27    $preact = $ACT;
28
29    // give plugins an opportunity to process the action
30    $evt = new Doku_Event('ACTION_ACT_PREPROCESS',$ACT);
31    if ($evt->advise_before()) {
32
33        //sanitize $ACT
34        $ACT = act_clean($ACT);
35
36        //check if searchword was given - else just show
37        $s = cleanID($QUERY);
38        if($ACT == 'search' && empty($s)){
39            $ACT = 'show';
40        }
41
42        //login stuff
43        if(in_array($ACT,array('login','logout'))){
44            $ACT = act_auth($ACT);
45        }
46
47        //check if user is asking to (un)subscribe a page
48        if($ACT == 'subscribe') {
49            try {
50                $ACT = act_subscription($ACT);
51            } catch (Exception $e) {
52                msg($e->getMessage(), -1);
53            }
54        }
55
56        //check permissions
57        $ACT = act_permcheck($ACT);
58
59        //register
60        $nil = array();
61        if($ACT == 'register' && $_POST['save'] && register()){
62            $ACT = 'login';
63        }
64
65        if ($ACT == 'resendpwd' && act_resendpwd()) {
66            $ACT = 'login';
67        }
68
69        //update user profile
70        if ($ACT == 'profile') {
71            if(!$_SERVER['REMOTE_USER']) {
72                $ACT = 'login';
73            } else {
74                if(updateprofile()) {
75                    msg($lang['profchanged'],1);
76                    $ACT = 'show';
77                }
78            }
79        }
80
81        //revert
82        if($ACT == 'revert'){
83            if(checkSecurityToken()){
84                $ACT = act_revert($ACT);
85            }else{
86                $ACT = 'show';
87            }
88        }
89
90        //save
91        if($ACT == 'save'){
92            if(checkSecurityToken()){
93                $ACT = act_save($ACT);
94            }else{
95                $ACT = 'show';
96            }
97        }
98
99        //cancel conflicting edit
100        if($ACT == 'cancel')
101            $ACT = 'show';
102
103        //draft deletion
104        if($ACT == 'draftdel')
105            $ACT = act_draftdel($ACT);
106
107        //draft saving on preview
108        if($ACT == 'preview')
109            $ACT = act_draftsave($ACT);
110
111        //edit
112        if(in_array($ACT, array('edit', 'preview', 'recover'))) {
113            $ACT = act_edit($ACT);
114        }else{
115            unlock($ID); //try to unlock
116        }
117
118        //handle export
119        if(substr($ACT,0,7) == 'export_')
120            $ACT = act_export($ACT);
121
122        //display some infos
123        if($ACT == 'check'){
124            check();
125            $ACT = 'show';
126        }
127
128        //handle admin tasks
129        if($ACT == 'admin'){
130            // retrieve admin plugin name from $_REQUEST['page']
131            if (!empty($_REQUEST['page'])) {
132                $pluginlist = plugin_list('admin');
133                if (in_array($_REQUEST['page'], $pluginlist)) {
134                    // attempt to load the plugin
135                    if ($plugin =& plugin_load('admin',$_REQUEST['page']) !== null)
136                        $plugin->handle();
137                }
138            }
139        }
140
141        // check permissions again - the action may have changed
142        $ACT = act_permcheck($ACT);
143    }  // end event ACTION_ACT_PREPROCESS default action
144    $evt->advise_after();
145    unset($evt);
146
147    // when action 'show', the intial not 'show' and POST, do a redirect
148    if($ACT == 'show' && $preact != 'show' && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){
149        act_redirect($ID,$preact);
150    }
151
152    //call template FIXME: all needed vars available?
153    $headers[] = 'Content-Type: text/html; charset=utf-8';
154    trigger_event('ACTION_HEADERS_SEND',$headers,'act_sendheaders');
155
156    include(template('main.php'));
157    // output for the commands is now handled in inc/templates.php
158    // in function tpl_content()
159}
160
161function act_sendheaders($headers) {
162    foreach ($headers as $hdr) header($hdr);
163}
164
165/**
166 * Sanitize the action command
167 *
168 * Add all allowed commands here.
169 *
170 * @author Andreas Gohr <andi@splitbrain.org>
171 */
172function act_clean($act){
173    global $lang;
174    global $conf;
175
176    // check if the action was given as array key
177    if(is_array($act)){
178        list($act) = array_keys($act);
179    }
180
181    //remove all bad chars
182    $act = strtolower($act);
183    $act = preg_replace('/[^1-9a-z_]+/','',$act);
184
185    if($act == 'export_html') $act = 'export_xhtml';
186    if($act == 'export_htmlbody') $act = 'export_xhtmlbody';
187
188    // check if action is disabled
189    if(!actionOK($act)){
190        msg('Command disabled: '.htmlspecialchars($act),-1);
191        return 'show';
192    }
193
194    //disable all acl related commands if ACL is disabled
195    if(!$conf['useacl'] && in_array($act,array('login','logout','register','admin',
196                    'subscribe','unsubscribe','profile','revert',
197                    'resendpwd','subscribens','unsubscribens',))){
198        msg('Command unavailable: '.htmlspecialchars($act),-1);
199        return 'show';
200    }
201
202    if(!in_array($act,array('login','logout','register','save','cancel','edit','draft',
203                    'preview','search','show','check','index','revisions',
204                    'diff','recent','backlink','admin','subscribe','revert',
205                    'unsubscribe','profile','resendpwd','recover',
206                    'draftdel','subscribens','unsubscribens',)) && substr($act,0,7) != 'export_' ) {
207        msg('Command unknown: '.htmlspecialchars($act),-1);
208        return 'show';
209    }
210    return $act;
211}
212
213/**
214 * Run permissionchecks
215 *
216 * @author Andreas Gohr <andi@splitbrain.org>
217 */
218function act_permcheck($act){
219    global $INFO;
220    global $conf;
221
222    if(in_array($act,array('save','preview','edit','recover'))){
223        if($INFO['exists']){
224            if($act == 'edit'){
225                //the edit function will check again and do a source show
226                //when no AUTH_EDIT available
227                $permneed = AUTH_READ;
228            }else{
229                $permneed = AUTH_EDIT;
230            }
231        }else{
232            $permneed = AUTH_CREATE;
233        }
234    }elseif(in_array($act,array('login','search','recent','profile'))){
235        $permneed = AUTH_NONE;
236    }elseif($act == 'revert'){
237        $permneed = AUTH_ADMIN;
238        if($INFO['ismanager']) $permneed = AUTH_EDIT;
239    }elseif($act == 'register'){
240        $permneed = AUTH_NONE;
241    }elseif($act == 'resendpwd'){
242        $permneed = AUTH_NONE;
243    }elseif($act == 'admin'){
244        if($INFO['ismanager']){
245            // if the manager has the needed permissions for a certain admin
246            // action is checked later
247            $permneed = AUTH_READ;
248        }else{
249            $permneed = AUTH_ADMIN;
250        }
251    }else{
252        $permneed = AUTH_READ;
253    }
254    if($INFO['perm'] >= $permneed) return $act;
255
256    return 'denied';
257}
258
259/**
260 * Handle 'draftdel'
261 *
262 * Deletes the draft for the current page and user
263 */
264function act_draftdel($act){
265    global $INFO;
266    @unlink($INFO['draft']);
267    $INFO['draft'] = null;
268    return 'show';
269}
270
271/**
272 * Saves a draft on preview
273 *
274 * @todo this currently duplicates code from ajax.php :-/
275 */
276function act_draftsave($act){
277    global $INFO;
278    global $ID;
279    global $conf;
280    if($conf['usedraft'] && $_POST['wikitext']){
281        $draft = array('id'     => $ID,
282                'prefix' => $_POST['prefix'],
283                'text'   => $_POST['wikitext'],
284                'suffix' => $_POST['suffix'],
285                'date'   => $_POST['date'],
286                'client' => $INFO['client'],
287                );
288        $cname = getCacheName($draft['client'].$ID,'.draft');
289        if(io_saveFile($cname,serialize($draft))){
290            $INFO['draft'] = $cname;
291        }
292    }
293    return $act;
294}
295
296/**
297 * Handle 'save'
298 *
299 * Checks for spam and conflicts and saves the page.
300 * Does a redirect to show the page afterwards or
301 * returns a new action.
302 *
303 * @author Andreas Gohr <andi@splitbrain.org>
304 */
305function act_save($act){
306    global $ID;
307    global $DATE;
308    global $PRE;
309    global $TEXT;
310    global $SUF;
311    global $SUM;
312    global $lang;
313    global $INFO;
314
315    //spam check
316    if(checkwordblock()) {
317        msg($lang['wordblock'], -1);
318        return 'edit';
319    }
320    //conflict check
321    if($DATE != 0 && $INFO['meta']['date']['modified'] > $DATE )
322        return 'conflict';
323
324    //save it
325    saveWikiText($ID,con($PRE,$TEXT,$SUF,1),$SUM,$_REQUEST['minor']); //use pretty mode for con
326    //unlock it
327    unlock($ID);
328
329    //delete draft
330    act_draftdel($act);
331    session_write_close();
332
333    // when done, show page
334    return 'show';
335}
336
337/**
338 * Revert to a certain revision
339 *
340 * @author Andreas Gohr <andi@splitbrain.org>
341 */
342function act_revert($act){
343    global $ID;
344    global $REV;
345    global $lang;
346    // FIXME $INFO['writable'] currently refers to the attic version
347    // global $INFO;
348    // if (!$INFO['writable']) {
349    //     return 'show';
350    // }
351
352    // when no revision is given, delete current one
353    // FIXME this feature is not exposed in the GUI currently
354    $text = '';
355    $sum  = $lang['deleted'];
356    if($REV){
357        $text = rawWiki($ID,$REV);
358        if(!$text) return 'show'; //something went wrong
359        $sum  = $lang['restored'];
360    }
361
362    // spam check
363
364    if (checkwordblock($text)) {
365        msg($lang['wordblock'], -1);
366        return 'edit';
367    }
368
369    saveWikiText($ID,$text,$sum,false);
370    msg($sum,1);
371
372    //delete any draft
373    act_draftdel($act);
374    session_write_close();
375
376    // when done, show current page
377    $_SERVER['REQUEST_METHOD'] = 'post'; //should force a redirect
378    $REV = '';
379    return 'show';
380}
381
382/**
383 * Do a redirect after receiving post data
384 *
385 * Tries to add the section id as hash mark after section editing
386 */
387function act_redirect($id,$preact){
388    global $PRE;
389    global $TEXT;
390    global $MSG;
391
392    //are there any undisplayed messages? keep them in session for display
393    //on the next page
394    if(isset($MSG) && count($MSG)){
395        //reopen session, store data and close session again
396        @session_start();
397        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
398        session_write_close();
399    }
400
401    $opts = array(
402            'id'       => $id,
403            'preact'   => $preact
404            );
405    //get section name when coming from section edit
406    if($PRE && preg_match('/^\s*==+([^=\n]+)/',$TEXT,$match)){
407        $check = false; //Byref
408        $opts['fragment'] = sectionID($match[0], $check);
409    }
410
411    trigger_event('ACTION_SHOW_REDIRECT',$opts,'act_redirect_execute');
412}
413
414function act_redirect_execute($opts){
415    $go = wl($opts['id'],'',true);
416    if(isset($opts['fragment'])) $go .= '#'.$opts['fragment'];
417
418    //show it
419    send_redirect($go);
420}
421
422/**
423 * Handle 'login', 'logout'
424 *
425 * @author Andreas Gohr <andi@splitbrain.org>
426 */
427function act_auth($act){
428    global $ID;
429    global $INFO;
430
431    //already logged in?
432    if(isset($_SERVER['REMOTE_USER']) && $act=='login'){
433        return 'show';
434    }
435
436    //handle logout
437    if($act=='logout'){
438        $lockedby = checklock($ID); //page still locked?
439        if($lockedby == $_SERVER['REMOTE_USER'])
440            unlock($ID); //try to unlock
441
442        // do the logout stuff
443        auth_logoff();
444
445        // rebuild info array
446        $INFO = pageinfo();
447
448        act_redirect($ID,'login');
449    }
450
451    return $act;
452}
453
454/**
455 * Handle 'edit', 'preview', 'recover'
456 *
457 * @author Andreas Gohr <andi@splitbrain.org>
458 */
459function act_edit($act){
460    global $ID;
461    global $INFO;
462
463    global $TEXT;
464    global $RANGE;
465    global $PRE;
466    global $SUF;
467    global $REV;
468    global $SUM;
469    global $lang;
470    global $DATE;
471
472    if (!isset($TEXT)) {
473        if ($INFO['exists']) {
474            if ($RANGE) {
475                list($PRE,$TEXT,$SUF) = rawWikiSlices($RANGE,$ID,$REV);
476            } else {
477                $TEXT = rawWiki($ID,$REV);
478            }
479        } else {
480            $TEXT = pageTemplate($ID);
481        }
482    }
483
484    //set summary default
485    if(!$SUM){
486        if($REV){
487            $SUM = $lang['restored'];
488        }elseif(!$INFO['exists']){
489            $SUM = $lang['created'];
490        }
491    }
492
493    // Use the date of the newest revision, not of the revision we edit
494    // This is used for conflict detection
495    if(!$DATE) $DATE = $INFO['meta']['date']['modified'];
496
497    //check if locked by anyone - if not lock for my self
498    $lockedby = checklock($ID);
499    if($lockedby) return 'locked';
500
501    lock($ID);
502    return $act;
503}
504
505/**
506 * Export a wiki page for various formats
507 *
508 * Triggers ACTION_EXPORT_POSTPROCESS
509 *
510 *  Event data:
511 *    data['id']      -- page id
512 *    data['mode']    -- requested export mode
513 *    data['headers'] -- export headers
514 *    data['output']  -- export output
515 *
516 * @author Andreas Gohr <andi@splitbrain.org>
517 * @author Michael Klier <chi@chimeric.de>
518 */
519function act_export($act){
520    global $ID;
521    global $REV;
522    global $conf;
523    global $lang;
524
525    $pre = '';
526    $post = '';
527    $output = '';
528    $headers = array();
529
530    // search engines: never cache exported docs! (Google only currently)
531    $headers['X-Robots-Tag'] = 'noindex';
532
533    $mode = substr($act,7);
534    switch($mode) {
535        case 'raw':
536            $headers['Content-Type'] = 'text/plain; charset=utf-8';
537            $headers['Content-Disposition'] = 'attachment; filename='.noNS($ID).'.txt';
538            $output = rawWiki($ID,$REV);
539            break;
540        case 'xhtml':
541            $pre .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' . DOKU_LF;
542            $pre .= ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' . DOKU_LF;
543            $pre .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.$conf['lang'].'"' . DOKU_LF;
544            $pre .= ' lang="'.$conf['lang'].'" dir="'.$lang['direction'].'">' . DOKU_LF;
545            $pre .= '<head>' . DOKU_LF;
546            $pre .= '  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . DOKU_LF;
547            $pre .= '  <title>'.$ID.'</title>' . DOKU_LF;
548
549            // get metaheaders
550            ob_start();
551            tpl_metaheaders();
552            $pre .= ob_get_clean();
553
554            $pre .= '</head>' . DOKU_LF;
555            $pre .= '<body>' . DOKU_LF;
556            $pre .= '<div class="dokuwiki export">' . DOKU_LF;
557
558            // get toc
559            $pre .= tpl_toc(true);
560
561            $headers['Content-Type'] = 'text/html; charset=utf-8';
562            $output = p_wiki_xhtml($ID,$REV,false);
563
564            $post .= '</div>' . DOKU_LF;
565            $post .= '</body>' . DOKU_LF;
566            $post .= '</html>' . DOKU_LF;
567            break;
568        case 'xhtmlbody':
569            $headers['Content-Type'] = 'text/html; charset=utf-8';
570            $output = p_wiki_xhtml($ID,$REV,false);
571            break;
572        default:
573            $output = p_cached_output(wikiFN($ID,$REV), $mode);
574            $headers = p_get_metadata($ID,"format $mode");
575            break;
576    }
577
578    // prepare event data
579    $data = array();
580    $data['id'] = $ID;
581    $data['mode'] = $mode;
582    $data['headers'] = $headers;
583    $data['output'] =& $output;
584
585    trigger_event('ACTION_EXPORT_POSTPROCESS', $data);
586
587    if(!empty($data['output'])){
588        if(is_array($data['headers'])) foreach($data['headers'] as $key => $val){
589            header("$key: $val");
590        }
591        print $pre.$data['output'].$post;
592        exit;
593    }
594    return 'show';
595}
596
597/**
598 * Handle page 'subscribe'
599 *
600 * Throws exception on error.
601 *
602 * @author Adrian Lang <lang@cosmocode.de>
603 */
604function act_subscription($act){
605    global $lang;
606    global $INFO;
607    global $ID;
608
609    // get and preprocess data.
610    $params = array();
611    foreach(array('target', 'style', 'action') as $param) {
612        if (isset($_REQUEST["sub_$param"])) {
613            $params[$param] = $_REQUEST["sub_$param"];
614        }
615    }
616
617    // any action given? if not just return and show the subscription page
618    if(!$params['action'] || !checkSecurityToken()) return $act;
619
620    // Handle POST data, may throw exception.
621    trigger_event('ACTION_HANDLE_SUBSCRIBE', $params, 'subscription_handle_post');
622
623    $target = $params['target'];
624    $style  = $params['style'];
625    $data   = $params['data'];
626    $action = $params['action'];
627
628    // Perform action.
629    if (!subscription_set($_SERVER['REMOTE_USER'], $target, $style, $data)) {
630        throw new Exception(sprintf($lang["subscr_{$action}_error"],
631                                    hsc($INFO['userinfo']['name']),
632                                    prettyprint_id($target)));
633    }
634    msg(sprintf($lang["subscr_{$action}_success"], hsc($INFO['userinfo']['name']),
635                prettyprint_id($target)), 1);
636    act_redirect($ID, $act);
637
638    // Assure that we have valid data if act_redirect somehow fails.
639    $INFO['subscribed'] = get_info_subscribed();
640    return 'show';
641}
642
643/**
644 * Validate POST data
645 *
646 * Validates POST data for a subscribe or unsubscribe request. This is the
647 * default action for the event ACTION_HANDLE_SUBSCRIBE.
648 *
649 * @author Adrian Lang <lang@cosmocode.de>
650 */
651function subscription_handle_post(&$params) {
652    global $INFO;
653    global $lang;
654
655    // Get and validate parameters.
656    if (!isset($params['target'])) {
657        throw new Exception('no subscription target given');
658    }
659    $target = $params['target'];
660    $valid_styles = array('every', 'digest');
661    if (substr($target, -1, 1) === ':') {
662        // Allow “list” subscribe style since the target is a namespace.
663        $valid_styles[] = 'list';
664    }
665    $style  = valid_input_set('style', $valid_styles, $params,
666                              'invalid subscription style given');
667    $action = valid_input_set('action', array('subscribe', 'unsubscribe'),
668                              $params, 'invalid subscription action given');
669
670    // Check other conditions.
671    if ($action === 'subscribe') {
672        if ($INFO['userinfo']['mail'] === '') {
673            throw new Exception($lang['subscr_subscribe_noaddress']);
674        }
675    } elseif ($action === 'unsubscribe') {
676        $is = false;
677        foreach($INFO['subscribed'] as $subscr) {
678            if ($subscr['target'] === $target) {
679                $is = true;
680            }
681        }
682        if ($is === false) {
683            throw new Exception(sprintf($lang['subscr_not_subscribed'],
684                                        $_SERVER['REMOTE_USER'],
685                                        prettyprint_id($target)));
686        }
687        // subscription_set deletes a subscription if style = null.
688        $style = null;
689    }
690
691    $data = in_array($style, array('list', 'digest')) ? time() : null;
692    $params = compact('target', 'style', 'data', 'action');
693}
694
695//Setup VIM: ex: et ts=2 enc=utf-8 :
696