xref: /dokuwiki/inc/actions.php (revision 9a2cec2e934b77a311cf21d5822dfd0146d5140b)
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    if($act === '') $act = 'show';
189
190    // check if action is disabled
191    if(!actionOK($act)){
192        msg('Command disabled: '.htmlspecialchars($act),-1);
193        return 'show';
194    }
195
196    //disable all acl related commands if ACL is disabled
197    if(!$conf['useacl'] && in_array($act,array('login','logout','register','admin',
198                    'subscribe','unsubscribe','profile','revert',
199                    'resendpwd','subscribens','unsubscribens',))){
200        msg('Command unavailable: '.htmlspecialchars($act),-1);
201        return 'show';
202    }
203
204    if(!in_array($act,array('login','logout','register','save','cancel','edit','draft',
205                    'preview','search','show','check','index','revisions',
206                    'diff','recent','backlink','admin','subscribe','revert',
207                    'unsubscribe','profile','resendpwd','recover',
208                    'draftdel','subscribens','unsubscribens',)) && substr($act,0,7) != 'export_' ) {
209        msg('Command unknown: '.htmlspecialchars($act),-1);
210        return 'show';
211    }
212    return $act;
213}
214
215/**
216 * Run permissionchecks
217 *
218 * @author Andreas Gohr <andi@splitbrain.org>
219 */
220function act_permcheck($act){
221    global $INFO;
222    global $conf;
223
224    if(in_array($act,array('save','preview','edit','recover'))){
225        if($INFO['exists']){
226            if($act == 'edit'){
227                //the edit function will check again and do a source show
228                //when no AUTH_EDIT available
229                $permneed = AUTH_READ;
230            }else{
231                $permneed = AUTH_EDIT;
232            }
233        }else{
234            $permneed = AUTH_CREATE;
235        }
236    }elseif(in_array($act,array('login','search','recent','profile','index'))){
237        $permneed = AUTH_NONE;
238    }elseif($act == 'revert'){
239        $permneed = AUTH_ADMIN;
240        if($INFO['ismanager']) $permneed = AUTH_EDIT;
241    }elseif($act == 'register'){
242        $permneed = AUTH_NONE;
243    }elseif($act == 'resendpwd'){
244        $permneed = AUTH_NONE;
245    }elseif($act == 'admin'){
246        if($INFO['ismanager']){
247            // if the manager has the needed permissions for a certain admin
248            // action is checked later
249            $permneed = AUTH_READ;
250        }else{
251            $permneed = AUTH_ADMIN;
252        }
253    }else{
254        $permneed = AUTH_READ;
255    }
256    if($INFO['perm'] >= $permneed) return $act;
257
258    return 'denied';
259}
260
261/**
262 * Handle 'draftdel'
263 *
264 * Deletes the draft for the current page and user
265 */
266function act_draftdel($act){
267    global $INFO;
268    @unlink($INFO['draft']);
269    $INFO['draft'] = null;
270    return 'show';
271}
272
273/**
274 * Saves a draft on preview
275 *
276 * @todo this currently duplicates code from ajax.php :-/
277 */
278function act_draftsave($act){
279    global $INFO;
280    global $ID;
281    global $conf;
282    if($conf['usedraft'] && $_POST['wikitext']){
283        $draft = array('id'     => $ID,
284                'prefix' => $_POST['prefix'],
285                'text'   => $_POST['wikitext'],
286                'suffix' => $_POST['suffix'],
287                'date'   => $_POST['date'],
288                'client' => $INFO['client'],
289                );
290        $cname = getCacheName($draft['client'].$ID,'.draft');
291        if(io_saveFile($cname,serialize($draft))){
292            $INFO['draft'] = $cname;
293        }
294    }
295    return $act;
296}
297
298/**
299 * Handle 'save'
300 *
301 * Checks for spam and conflicts and saves the page.
302 * Does a redirect to show the page afterwards or
303 * returns a new action.
304 *
305 * @author Andreas Gohr <andi@splitbrain.org>
306 */
307function act_save($act){
308    global $ID;
309    global $DATE;
310    global $PRE;
311    global $TEXT;
312    global $SUF;
313    global $SUM;
314    global $lang;
315    global $INFO;
316
317    //spam check
318    if(checkwordblock()) {
319        msg($lang['wordblock'], -1);
320        return 'edit';
321    }
322    //conflict check
323    if($DATE != 0 && $INFO['meta']['date']['modified'] > $DATE )
324        return 'conflict';
325
326    //save it
327    saveWikiText($ID,con($PRE,$TEXT,$SUF,1),$SUM,$_REQUEST['minor']); //use pretty mode for con
328    //unlock it
329    unlock($ID);
330
331    //delete draft
332    act_draftdel($act);
333    session_write_close();
334
335    // when done, show page
336    return 'show';
337}
338
339/**
340 * Revert to a certain revision
341 *
342 * @author Andreas Gohr <andi@splitbrain.org>
343 */
344function act_revert($act){
345    global $ID;
346    global $REV;
347    global $lang;
348    // FIXME $INFO['writable'] currently refers to the attic version
349    // global $INFO;
350    // if (!$INFO['writable']) {
351    //     return 'show';
352    // }
353
354    // when no revision is given, delete current one
355    // FIXME this feature is not exposed in the GUI currently
356    $text = '';
357    $sum  = $lang['deleted'];
358    if($REV){
359        $text = rawWiki($ID,$REV);
360        if(!$text) return 'show'; //something went wrong
361        $sum  = $lang['restored'];
362    }
363
364    // spam check
365
366    if (checkwordblock($text)) {
367        msg($lang['wordblock'], -1);
368        return 'edit';
369    }
370
371    saveWikiText($ID,$text,$sum,false);
372    msg($sum,1);
373
374    //delete any draft
375    act_draftdel($act);
376    session_write_close();
377
378    // when done, show current page
379    $_SERVER['REQUEST_METHOD'] = 'post'; //should force a redirect
380    $REV = '';
381    return 'show';
382}
383
384/**
385 * Do a redirect after receiving post data
386 *
387 * Tries to add the section id as hash mark after section editing
388 */
389function act_redirect($id,$preact){
390    global $PRE;
391    global $TEXT;
392
393    $opts = array(
394            'id'       => $id,
395            'preact'   => $preact
396            );
397    //get section name when coming from section edit
398    if($PRE && preg_match('/^\s*==+([^=\n]+)/',$TEXT,$match)){
399        $check = false; //Byref
400        $opts['fragment'] = sectionID($match[0], $check);
401    }
402
403    trigger_event('ACTION_SHOW_REDIRECT',$opts,'act_redirect_execute');
404}
405
406function act_redirect_execute($opts){
407    $go = wl($opts['id'],'',true);
408    if(isset($opts['fragment'])) $go .= '#'.$opts['fragment'];
409
410    //show it
411    send_redirect($go);
412}
413
414/**
415 * Handle 'login', 'logout'
416 *
417 * @author Andreas Gohr <andi@splitbrain.org>
418 */
419function act_auth($act){
420    global $ID;
421    global $INFO;
422
423    //already logged in?
424    if(isset($_SERVER['REMOTE_USER']) && $act=='login'){
425        return 'show';
426    }
427
428    //handle logout
429    if($act=='logout'){
430        $lockedby = checklock($ID); //page still locked?
431        if($lockedby == $_SERVER['REMOTE_USER'])
432            unlock($ID); //try to unlock
433
434        // do the logout stuff
435        auth_logoff();
436
437        // rebuild info array
438        $INFO = pageinfo();
439
440        act_redirect($ID,'login');
441    }
442
443    return $act;
444}
445
446/**
447 * Handle 'edit', 'preview', 'recover'
448 *
449 * @author Andreas Gohr <andi@splitbrain.org>
450 */
451function act_edit($act){
452    global $ID;
453    global $INFO;
454
455    global $TEXT;
456    global $RANGE;
457    global $PRE;
458    global $SUF;
459    global $REV;
460    global $SUM;
461    global $lang;
462    global $DATE;
463
464    if (!isset($TEXT)) {
465        if ($INFO['exists']) {
466            if ($RANGE) {
467                list($PRE,$TEXT,$SUF) = rawWikiSlices($RANGE,$ID,$REV);
468            } else {
469                $TEXT = rawWiki($ID,$REV);
470            }
471        } else {
472            $TEXT = pageTemplate($ID);
473        }
474    }
475
476    //set summary default
477    if(!$SUM){
478        if($REV){
479            $SUM = $lang['restored'];
480        }elseif(!$INFO['exists']){
481            $SUM = $lang['created'];
482        }
483    }
484
485    // Use the date of the newest revision, not of the revision we edit
486    // This is used for conflict detection
487    if(!$DATE) $DATE = $INFO['meta']['date']['modified'];
488
489    //check if locked by anyone - if not lock for my self
490    $lockedby = checklock($ID);
491    if($lockedby) return 'locked';
492
493    lock($ID);
494    return $act;
495}
496
497/**
498 * Export a wiki page for various formats
499 *
500 * Triggers ACTION_EXPORT_POSTPROCESS
501 *
502 *  Event data:
503 *    data['id']      -- page id
504 *    data['mode']    -- requested export mode
505 *    data['headers'] -- export headers
506 *    data['output']  -- export output
507 *
508 * @author Andreas Gohr <andi@splitbrain.org>
509 * @author Michael Klier <chi@chimeric.de>
510 */
511function act_export($act){
512    global $ID;
513    global $REV;
514    global $conf;
515    global $lang;
516
517    $pre = '';
518    $post = '';
519    $output = '';
520    $headers = array();
521
522    // search engines: never cache exported docs! (Google only currently)
523    $headers['X-Robots-Tag'] = 'noindex';
524
525    $mode = substr($act,7);
526    switch($mode) {
527        case 'raw':
528            $headers['Content-Type'] = 'text/plain; charset=utf-8';
529            $headers['Content-Disposition'] = 'attachment; filename='.noNS($ID).'.txt';
530            $output = rawWiki($ID,$REV);
531            break;
532        case 'xhtml':
533            $pre .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' . DOKU_LF;
534            $pre .= ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' . DOKU_LF;
535            $pre .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.$conf['lang'].'"' . DOKU_LF;
536            $pre .= ' lang="'.$conf['lang'].'" dir="'.$lang['direction'].'">' . DOKU_LF;
537            $pre .= '<head>' . DOKU_LF;
538            $pre .= '  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . DOKU_LF;
539            $pre .= '  <title>'.$ID.'</title>' . DOKU_LF;
540
541            // get metaheaders
542            ob_start();
543            tpl_metaheaders();
544            $pre .= ob_get_clean();
545
546            $pre .= '</head>' . DOKU_LF;
547            $pre .= '<body>' . DOKU_LF;
548            $pre .= '<div class="dokuwiki export">' . DOKU_LF;
549
550            // get toc
551            $pre .= tpl_toc(true);
552
553            $headers['Content-Type'] = 'text/html; charset=utf-8';
554            $output = p_wiki_xhtml($ID,$REV,false);
555
556            $post .= '</div>' . DOKU_LF;
557            $post .= '</body>' . DOKU_LF;
558            $post .= '</html>' . DOKU_LF;
559            break;
560        case 'xhtmlbody':
561            $headers['Content-Type'] = 'text/html; charset=utf-8';
562            $output = p_wiki_xhtml($ID,$REV,false);
563            break;
564        default:
565            $output = p_cached_output(wikiFN($ID,$REV), $mode);
566            $headers = p_get_metadata($ID,"format $mode");
567            break;
568    }
569
570    // prepare event data
571    $data = array();
572    $data['id'] = $ID;
573    $data['mode'] = $mode;
574    $data['headers'] = $headers;
575    $data['output'] =& $output;
576
577    trigger_event('ACTION_EXPORT_POSTPROCESS', $data);
578
579    if(!empty($data['output'])){
580        if(is_array($data['headers'])) foreach($data['headers'] as $key => $val){
581            header("$key: $val");
582        }
583        print $pre.$data['output'].$post;
584        exit;
585    }
586    return 'show';
587}
588
589/**
590 * Handle page 'subscribe'
591 *
592 * Throws exception on error.
593 *
594 * @author Adrian Lang <lang@cosmocode.de>
595 */
596function act_subscription($act){
597    global $lang;
598    global $INFO;
599    global $ID;
600
601    // subcriptions work for logged in users only
602    if(!$_SERVER['REMOTE_USER']) return 'show';
603
604    // get and preprocess data.
605    $params = array();
606    foreach(array('target', 'style', 'action') as $param) {
607        if (isset($_REQUEST["sub_$param"])) {
608            $params[$param] = $_REQUEST["sub_$param"];
609        }
610    }
611
612    // any action given? if not just return and show the subscription page
613    if(!$params['action'] || !checkSecurityToken()) return $act;
614
615    // Handle POST data, may throw exception.
616    trigger_event('ACTION_HANDLE_SUBSCRIBE', $params, 'subscription_handle_post');
617
618    $target = $params['target'];
619    $style  = $params['style'];
620    $data   = $params['data'];
621    $action = $params['action'];
622
623    // Perform action.
624    if (!subscription_set($_SERVER['REMOTE_USER'], $target, $style, $data)) {
625        throw new Exception(sprintf($lang["subscr_{$action}_error"],
626                                    hsc($INFO['userinfo']['name']),
627                                    prettyprint_id($target)));
628    }
629    msg(sprintf($lang["subscr_{$action}_success"], hsc($INFO['userinfo']['name']),
630                prettyprint_id($target)), 1);
631    act_redirect($ID, $act);
632
633    // Assure that we have valid data if act_redirect somehow fails.
634    $INFO['subscribed'] = get_info_subscribed();
635    return 'show';
636}
637
638/**
639 * Validate POST data
640 *
641 * Validates POST data for a subscribe or unsubscribe request. This is the
642 * default action for the event ACTION_HANDLE_SUBSCRIBE.
643 *
644 * @author Adrian Lang <lang@cosmocode.de>
645 */
646function subscription_handle_post(&$params) {
647    global $INFO;
648    global $lang;
649
650    // Get and validate parameters.
651    if (!isset($params['target'])) {
652        throw new Exception('no subscription target given');
653    }
654    $target = $params['target'];
655    $valid_styles = array('every', 'digest');
656    if (substr($target, -1, 1) === ':') {
657        // Allow “list” subscribe style since the target is a namespace.
658        $valid_styles[] = 'list';
659    }
660    $style  = valid_input_set('style', $valid_styles, $params,
661                              'invalid subscription style given');
662    $action = valid_input_set('action', array('subscribe', 'unsubscribe'),
663                              $params, 'invalid subscription action given');
664
665    // Check other conditions.
666    if ($action === 'subscribe') {
667        if ($INFO['userinfo']['mail'] === '') {
668            throw new Exception($lang['subscr_subscribe_noaddress']);
669        }
670    } elseif ($action === 'unsubscribe') {
671        $is = false;
672        foreach($INFO['subscribed'] as $subscr) {
673            if ($subscr['target'] === $target) {
674                $is = true;
675            }
676        }
677        if ($is === false) {
678            throw new Exception(sprintf($lang['subscr_not_subscribed'],
679                                        $_SERVER['REMOTE_USER'],
680                                        prettyprint_id($target)));
681        }
682        // subscription_set deletes a subscription if style = null.
683        $style = null;
684    }
685
686    $data = in_array($style, array('list', 'digest')) ? time() : null;
687    $params = compact('target', 'style', 'data', 'action');
688}
689
690//Setup VIM: ex: et ts=2 enc=utf-8 :
691