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