xref: /dokuwiki/inc/actions.php (revision c2a6d81662045023bdf1617b6b49f71c274d55ca)
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(($ACT == 'edit' || $ACT == 'preview') && $INFO['editable']){
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','wordblock',
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
313    //spam check
314    if(checkwordblock())
315        return 'wordblock';
316    //conflict check //FIXME use INFO
317    if($DATE != 0 && @filemtime(wikiFN($ID)) > $DATE )
318        return 'conflict';
319
320    //save it
321    saveWikiText($ID,con($PRE,$TEXT,$SUF,1),$SUM,$_REQUEST['minor']); //use pretty mode for con
322    //unlock it
323    unlock($ID);
324
325    //delete draft
326    act_draftdel($act);
327    session_write_close();
328
329    // when done, show page
330    return 'show';
331}
332
333/**
334 * Revert to a certain revision
335 *
336 * @author Andreas Gohr <andi@splitbrain.org>
337 */
338function act_revert($act){
339    global $ID;
340    global $REV;
341    global $lang;
342
343    // when no revision is given, delete current one
344    // FIXME this feature is not exposed in the GUI currently
345    $text = '';
346    $sum  = $lang['deleted'];
347    if($REV){
348        $text = rawWiki($ID,$REV);
349        if(!$text) return 'show'; //something went wrong
350        $sum  = $lang['restored'];
351    }
352
353    // spam check
354    if(checkwordblock($Text))
355        return 'wordblock';
356
357    saveWikiText($ID,$text,$sum,false);
358    msg($sum,1);
359
360    //delete any draft
361    act_draftdel($act);
362    session_write_close();
363
364    // when done, show current page
365    $_SERVER['REQUEST_METHOD'] = 'post'; //should force a redirect
366    $REV = '';
367    return 'show';
368}
369
370/**
371 * Do a redirect after receiving post data
372 *
373 * Tries to add the section id as hash mark after section editing
374 */
375function act_redirect($id,$preact){
376    global $PRE;
377    global $TEXT;
378    global $MSG;
379
380    //are there any undisplayed messages? keep them in session for display
381    //on the next page
382    if(isset($MSG) && count($MSG)){
383        //reopen session, store data and close session again
384        @session_start();
385        $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
386        session_write_close();
387    }
388
389    $opts = array(
390            'id'       => $id,
391            'preact'   => $preact
392            );
393    //get section name when coming from section edit
394    if($PRE && preg_match('/^\s*==+([^=\n]+)/',$TEXT,$match)){
395        $check = false; //Byref
396        $opts['fragment'] = sectionID($match[0], $check);
397    }
398
399    trigger_event('ACTION_SHOW_REDIRECT',$opts,'act_redirect_execute');
400}
401
402function act_redirect_execute($opts){
403    $go = wl($opts['id'],'',true);
404    if(isset($opts['fragment'])) $go .= '#'.$opts['fragment'];
405
406    //show it
407    send_redirect($go);
408}
409
410/**
411 * Handle 'login', 'logout'
412 *
413 * @author Andreas Gohr <andi@splitbrain.org>
414 */
415function act_auth($act){
416    global $ID;
417    global $INFO;
418
419    //already logged in?
420    if(isset($_SERVER['REMOTE_USER']) && $act=='login'){
421        return 'show';
422    }
423
424    //handle logout
425    if($act=='logout'){
426        $lockedby = checklock($ID); //page still locked?
427        if($lockedby == $_SERVER['REMOTE_USER'])
428            unlock($ID); //try to unlock
429
430        // do the logout stuff
431        auth_logoff();
432
433        // rebuild info array
434        $INFO = pageinfo();
435
436        act_redirect($ID,'login');
437    }
438
439    return $act;
440}
441
442/**
443 * Handle 'edit', 'preview'
444 *
445 * @author Andreas Gohr <andi@splitbrain.org>
446 */
447function act_edit($act){
448    global $ID;
449    global $INFO;
450
451    //check if locked by anyone - if not lock for my self
452    $lockedby = checklock($ID);
453    if($lockedby) return 'locked';
454
455    lock($ID);
456    return $act;
457}
458
459/**
460 * Export a wiki page for various formats
461 *
462 * Triggers ACTION_EXPORT_POSTPROCESS
463 *
464 *  Event data:
465 *    data['id']      -- page id
466 *    data['mode']    -- requested export mode
467 *    data['headers'] -- export headers
468 *    data['output']  -- export output
469 *
470 * @author Andreas Gohr <andi@splitbrain.org>
471 * @author Michael Klier <chi@chimeric.de>
472 */
473function act_export($act){
474    global $ID;
475    global $REV;
476    global $conf;
477    global $lang;
478
479    $pre = '';
480    $post = '';
481    $output = '';
482    $headers = array();
483
484    // search engines: never cache exported docs! (Google only currently)
485    $headers['X-Robots-Tag'] = 'noindex';
486
487    $mode = substr($act,7);
488    switch($mode) {
489        case 'raw':
490            $headers['Content-Type'] = 'text/plain; charset=utf-8';
491            $headers['Content-Disposition'] = 'attachment; filename='.noNS($ID).'.txt';
492            $output = rawWiki($ID,$REV);
493            break;
494        case 'xhtml':
495            $pre .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' . DOKU_LF;
496            $pre .= ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' . DOKU_LF;
497            $pre .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.$conf['lang'].'"' . DOKU_LF;
498            $pre .= ' lang="'.$conf['lang'].'" dir="'.$lang['direction'].'">' . DOKU_LF;
499            $pre .= '<head>' . DOKU_LF;
500            $pre .= '  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . DOKU_LF;
501            $pre .= '  <title>'.$ID.'</title>' . DOKU_LF;
502
503            // get metaheaders
504            ob_start();
505            tpl_metaheaders();
506            $pre .= ob_get_clean();
507
508            $pre .= '</head>' . DOKU_LF;
509            $pre .= '<body>' . DOKU_LF;
510            $pre .= '<div class="dokuwiki export">' . DOKU_LF;
511
512            // get toc
513            $pre .= tpl_toc(true);
514
515            $headers['Content-Type'] = 'text/html; charset=utf-8';
516            $output = p_wiki_xhtml($ID,$REV,false);
517
518            $post .= '</div>' . DOKU_LF;
519            $post .= '</body>' . DOKU_LF;
520            $post .= '</html>' . DOKU_LF;
521            break;
522        case 'xhtmlbody':
523            $headers['Content-Type'] = 'text/html; charset=utf-8';
524            $output = p_wiki_xhtml($ID,$REV,false);
525            break;
526        default:
527            $output = p_cached_output(wikiFN($ID,$REV), $mode);
528            $headers = p_get_metadata($ID,"format $mode");
529            break;
530    }
531
532    // prepare event data
533    $data = array();
534    $data['id'] = $ID;
535    $data['mode'] = $mode;
536    $data['headers'] = $headers;
537    $data['output'] =& $output;
538
539    trigger_event('ACTION_EXPORT_POSTPROCESS', $data);
540
541    if(!empty($data['output'])){
542        if(is_array($data['headers'])) foreach($data['headers'] as $key => $val){
543            header("$key: $val");
544        }
545        print $pre.$data['output'].$post;
546        exit;
547    }
548    return 'show';
549}
550
551/**
552 * Handle page 'subscribe'
553 *
554 * Throws exception on error.
555 *
556 * @author Adrian Lang <lang@cosmocode.de>
557 */
558function act_subscription($act){
559    global $lang;
560    global $INFO;
561    global $ID;
562
563    // get and preprocess data.
564    $params = array();
565    foreach(array('target', 'style', 'action') as $param) {
566        if (isset($_REQUEST["sub_$param"])) {
567            $params[$param] = $_REQUEST["sub_$param"];
568        }
569    }
570
571    // any action given? if not just return and show the subscription page
572    if(!$params['action']) return $act;
573
574    // Handle POST data, may throw exception.
575    trigger_event('ACTION_HANDLE_SUBSCRIBE', $params, 'subscription_handle_post');
576
577    $target = $params['target'];
578    $style  = $params['style'];
579    $data   = $params['data'];
580    $action = $params['action'];
581
582    // Perform action.
583    if (!subscription_set($_SERVER['REMOTE_USER'], $target, $style, $data)) {
584        throw new Exception(sprintf($lang["subscr_{$action}_error"],
585                                    hsc($INFO['userinfo']['name']),
586                                    prettyprint_id($target)));
587    }
588    msg(sprintf($lang["subscr_{$action}_success"], hsc($INFO['userinfo']['name']),
589                prettyprint_id($target)), 1);
590    act_redirect($ID, $act);
591
592    // Assure that we have valid data if act_redirect somehow fails.
593    $INFO['subscribed'] = get_info_subscribed();
594    return 'show';
595}
596
597/**
598 * Validate POST data
599 *
600 * Validates POST data for a subscribe or unsubscribe request. This is the
601 * default action for the event ACTION_HANDLE_SUBSCRIBE.
602 *
603 * @author Adrian Lang <lang@cosmocode.de>
604 */
605function subscription_handle_post(&$params) {
606    global $INFO;
607    global $lang;
608
609    // Get and validate parameters.
610    if (!isset($params['target'])) {
611        throw new Exception('no subscription target given');
612    }
613    $target = $params['target'];
614    $valid_styles = array('every', 'digest');
615    if (substr($target, -1, 1) === ':') {
616        // Allow “list” subscribe style since the target is a namespace.
617        $valid_styles[] = 'list';
618    }
619    $style  = valid_input_set('style', $valid_styles, $params,
620                              'invalid subscription style given');
621    $action = valid_input_set('action', array('subscribe', 'unsubscribe'),
622                              $params, 'invalid subscription action given');
623
624    // Check other conditions.
625    if ($action === 'subscribe') {
626        if ($INFO['userinfo']['mail'] === '') {
627            throw new Exception($lang['subscr_subscribe_noaddress']);
628        }
629    } elseif ($action === 'unsubscribe') {
630        $is = false;
631        foreach($INFO['subscribed'] as $subscr) {
632            if ($subscr['target'] === $target) {
633                $is = true;
634            }
635        }
636        if ($is === false) {
637            throw new Exception(sprintf($lang['subscr_not_subscribed'],
638                                        $_SERVER['REMOTE_USER'],
639                                        prettyprint_id($target)));
640        }
641        // subscription_set deletes a subscription if style = null.
642        $style = null;
643    }
644
645    $data = in_array($style, array('list', 'digest')) ? time() : null;
646    $params = compact('target', 'style', 'data', 'action');
647}
648
649//Setup VIM: ex: et ts=2 enc=utf-8 :
650