summaryrefslogtreecommitdiff
path: root/inc/actions.php
blob: 709c19dddcd3383c0d58a89166098513dcf8f088 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
<?php
/**
 * DokuWiki Actions
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Andreas Gohr <andi@splitbrain.org>
 */

if(!defined('DOKU_INC')) die('meh.');

/**
 * Call the needed action handlers
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @triggers ACTION_ACT_PREPROCESS
 * @triggers ACTION_HEADERS_SEND
 */
function act_dispatch(){
    global $ACT;
    global $ID;
    global $INFO;
    global $QUERY;
    /* @var Input $INPUT */
    global $INPUT;
    global $lang;
    global $conf;

    $preact = $ACT;

    // give plugins an opportunity to process the action
    $evt = new Doku_Event('ACTION_ACT_PREPROCESS',$ACT);
    if ($evt->advise_before()) {

        //sanitize $ACT
        $ACT = act_validate($ACT);

        //check if searchword was given - else just show
        $s = cleanID($QUERY);
        if($ACT == 'search' && empty($s)){
            $ACT = 'show';
        }

        //login stuff
        if(in_array($ACT,array('login','logout'))){
            $ACT = act_auth($ACT);
        }

        //check if user is asking to (un)subscribe a page
        if($ACT == 'subscribe') {
            try {
                $ACT = act_subscription($ACT);
            } catch (Exception $e) {
                msg($e->getMessage(), -1);
            }
        }

        //display some info
        if($ACT == 'check'){
            check();
            $ACT = 'show';
        }

        //check permissions
        $ACT = act_permcheck($ACT);

        //sitemap
        if ($ACT == 'sitemap'){
            act_sitemap($ACT);
        }

        //recent changes
        if ($ACT == 'recent'){
            $show_changes = $INPUT->str('show_changes');
            if (!empty($show_changes)) {
                set_doku_pref('show_changes', $show_changes);
            }
        }

        //diff
        if ($ACT == 'diff'){
            $difftype = $INPUT->str('difftype');
            if (!empty($difftype)) {
                set_doku_pref('difftype', $difftype);
            }
        }

        //register
        if($ACT == 'register' && $INPUT->post->bool('save') && register()){
            $ACT = 'login';
        }

        if ($ACT == 'resendpwd' && act_resendpwd()) {
            $ACT = 'login';
        }

        // user profile changes
        if (in_array($ACT, array('profile','profile_delete'))) {
            if(!$INPUT->server->str('REMOTE_USER')) {
                $ACT = 'login';
            } else {
                switch ($ACT) {
                    case 'profile' :
                        if(updateprofile()) {
                            msg($lang['profchanged'],1);
                            $ACT = 'show';
                        }
                        break;
                    case 'profile_delete' :
                        if(auth_deleteprofile()){
                            msg($lang['profdeleted'],1);
                            $ACT = 'show';
                        } else {
                            $ACT = 'profile';
                        }
                        break;
                }
            }
        }

        //revert
        if($ACT == 'revert'){
            if(checkSecurityToken()){
                $ACT = act_revert($ACT);
            }else{
                $ACT = 'show';
            }
        }

        //save
        if($ACT == 'save'){
            if(checkSecurityToken()){
                $ACT = act_save($ACT);
            }else{
                $ACT = 'preview';
            }
        }

        //cancel conflicting edit
        if($ACT == 'cancel')
            $ACT = 'show';

        //draft deletion
        if($ACT == 'draftdel')
            $ACT = act_draftdel($ACT);

        //draft saving on preview
        if($ACT == 'preview')
            $ACT = act_draftsave($ACT);

        //edit
        if(in_array($ACT, array('edit', 'preview', 'recover'))) {
            $ACT = act_edit($ACT);
        }else{
            unlock($ID); //try to unlock
        }

        //handle export
        if(substr($ACT,0,7) == 'export_')
            $ACT = act_export($ACT);

        //handle admin tasks
        if($ACT == 'admin'){
            // retrieve admin plugin name from $_REQUEST['page']
            if (($page = $INPUT->str('page', '', true)) != '') {
                $pluginlist = plugin_list('admin');
                if (in_array($page, $pluginlist)) {
                    // attempt to load the plugin

                    if (($plugin = plugin_load('admin',$page)) !== null){
                        /** @var DokuWiki_Admin_Plugin $plugin */
                        if($plugin->forAdminOnly() && !$INFO['isadmin']){
                            // a manager tried to load a plugin that's for admins only
                            $INPUT->remove('page');
                            msg('For admins only',-1);
                        }else{
                            $plugin->handle();
                        }
                    }
                }
            }
        }

        // check permissions again - the action may have changed
        $ACT = act_permcheck($ACT);
    }  // end event ACTION_ACT_PREPROCESS default action
    $evt->advise_after();
    // Make sure plugs can handle 'denied'
    if($conf['send404'] && $ACT == 'denied') {
        http_status(403);
    }
    unset($evt);

    // when action 'show', the intial not 'show' and POST, do a redirect
    if($ACT == 'show' && $preact != 'show' && strtolower($INPUT->server->str('REQUEST_METHOD')) == 'post'){
        act_redirect($ID,$preact);
    }

    global $INFO;
    global $conf;
    global $license;

    //call template FIXME: all needed vars available?
    $headers = array();
    $headers[] = 'Content-Type: text/html; charset=utf-8';
    trigger_event('ACTION_HEADERS_SEND',$headers,'act_sendheaders');

    include(template('main.php'));
    // output for the commands is now handled in inc/templates.php
    // in function tpl_content()
}

/**
 * Send the given headers using header()
 *
 * @param array $headers The headers that shall be sent
 */
function act_sendheaders($headers) {
    foreach ($headers as $hdr) header($hdr);
}

/**
 * Sanitize the action command
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param array|string $act
 * @return string
 */
function act_clean($act){
    // check if the action was given as array key
    if(is_array($act)){
        list($act) = array_keys($act);
    }

    //remove all bad chars
    $act = strtolower($act);
    $act = preg_replace('/[^1-9a-z_]+/','',$act);

    if($act == 'export_html') $act = 'export_xhtml';
    if($act == 'export_htmlbody') $act = 'export_xhtmlbody';

    if($act === '') $act = 'show';
    return $act;
}

/**
 * Sanitize and validate action commands.
 *
 * Add all allowed commands here.
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param array|string $act
 * @return string
 */
function act_validate($act) {
    global $conf;
    global $INFO;

    $act = act_clean($act);

    // check if action is disabled
    if(!actionOK($act)){
        msg('Command disabled: '.htmlspecialchars($act),-1);
        return 'show';
    }

    //disable all acl related commands if ACL is disabled
    if(!$conf['useacl'] && in_array($act,array('login','logout','register','admin',
                    'subscribe','unsubscribe','profile','revert',
                    'resendpwd','profile_delete'))){
        msg('Command unavailable: '.htmlspecialchars($act),-1);
        return 'show';
    }

    //is there really a draft?
    if($act == 'draft' && !file_exists($INFO['draft'])) return 'edit';

    if(!in_array($act,array('login','logout','register','save','cancel','edit','draft',
                    'preview','search','show','check','index','revisions',
                    'diff','recent','backlink','admin','subscribe','revert',
                    'unsubscribe','profile','profile_delete','resendpwd','recover',
                    'draftdel','sitemap','media')) && substr($act,0,7) != 'export_' ) {
        msg('Command unknown: '.htmlspecialchars($act),-1);
        return 'show';
    }
    return $act;
}

/**
 * Run permissionchecks
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param string $act action command
 * @return string action command
 */
function act_permcheck($act){
    global $INFO;

    if(in_array($act,array('save','preview','edit','recover'))){
        if($INFO['exists']){
            if($act == 'edit'){
                //the edit function will check again and do a source show
                //when no AUTH_EDIT available
                $permneed = AUTH_READ;
            }else{
                $permneed = AUTH_EDIT;
            }
        }else{
            $permneed = AUTH_CREATE;
        }
    }elseif(in_array($act,array('login','search','recent','profile','profile_delete','index', 'sitemap'))){
        $permneed = AUTH_NONE;
    }elseif($act == 'revert'){
        $permneed = AUTH_ADMIN;
        if($INFO['ismanager']) $permneed = AUTH_EDIT;
    }elseif($act == 'register'){
        $permneed = AUTH_NONE;
    }elseif($act == 'resendpwd'){
        $permneed = AUTH_NONE;
    }elseif($act == 'admin'){
        if($INFO['ismanager']){
            // if the manager has the needed permissions for a certain admin
            // action is checked later
            $permneed = AUTH_READ;
        }else{
            $permneed = AUTH_ADMIN;
        }
    }else{
        $permneed = AUTH_READ;
    }
    if($INFO['perm'] >= $permneed) return $act;

    return 'denied';
}

/**
 * Handle 'draftdel'
 *
 * Deletes the draft for the current page and user
 *
 * @param string $act action command
 * @return string action command
 */
function act_draftdel($act){
    global $INFO;
    @unlink($INFO['draft']);
    $INFO['draft'] = null;
    return 'show';
}

/**
 * Saves a draft on preview
 *
 * @todo this currently duplicates code from ajax.php :-/
 *
 * @param string $act action command
 * @return string action command
 */
function act_draftsave($act){
    global $INFO;
    global $ID;
    global $INPUT;
    global $conf;
    if($conf['usedraft'] && $INPUT->post->has('wikitext')) {
        $draft = array('id'     => $ID,
                'prefix' => substr($INPUT->post->str('prefix'), 0, -1),
                'text'   => $INPUT->post->str('wikitext'),
                'suffix' => $INPUT->post->str('suffix'),
                'date'   => $INPUT->post->int('date'),
                'client' => $INFO['client'],
                );
        $cname = getCacheName($draft['client'].$ID,'.draft');
        if(io_saveFile($cname,serialize($draft))){
            $INFO['draft'] = $cname;
        }
    }
    return $act;
}

/**
 * Handle 'save'
 *
 * Checks for spam and conflicts and saves the page.
 * Does a redirect to show the page afterwards or
 * returns a new action.
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param string $act action command
 * @return string action command
 */
function act_save($act){
    global $ID;
    global $DATE;
    global $PRE;
    global $TEXT;
    global $SUF;
    global $SUM;
    global $lang;
    global $INFO;
    global $INPUT;

    //spam check
    if(checkwordblock()) {
        msg($lang['wordblock'], -1);
        return 'edit';
    }
    //conflict check
    if($DATE != 0 && $INFO['meta']['date']['modified'] > $DATE )
        return 'conflict';

    //save it
    saveWikiText($ID,con($PRE,$TEXT,$SUF,true),$SUM,$INPUT->bool('minor')); //use pretty mode for con
    //unlock it
    unlock($ID);

    //delete draft
    act_draftdel($act);
    session_write_close();

    // when done, show page
    return 'show';
}

/**
 * Revert to a certain revision
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param string $act action command
 * @return string action command
 */
function act_revert($act){
    global $ID;
    global $REV;
    global $lang;
    /* @var Input $INPUT */
    global $INPUT;
    // FIXME $INFO['writable'] currently refers to the attic version
    // global $INFO;
    // if (!$INFO['writable']) {
    //     return 'show';
    // }

    // when no revision is given, delete current one
    // FIXME this feature is not exposed in the GUI currently
    $text = '';
    $sum  = $lang['deleted'];
    if($REV){
        $text = rawWiki($ID,$REV);
        if(!$text) return 'show'; //something went wrong
        $sum = sprintf($lang['restored'], dformat($REV));
    }

    // spam check

    if (checkwordblock($text)) {
        msg($lang['wordblock'], -1);
        return 'edit';
    }

    saveWikiText($ID,$text,$sum,false);
    msg($sum,1);

    //delete any draft
    act_draftdel($act);
    session_write_close();

    // when done, show current page
    $INPUT->server->set('REQUEST_METHOD','post'); //should force a redirect
    $REV = '';
    return 'show';
}

/**
 * Do a redirect after receiving post data
 *
 * Tries to add the section id as hash mark after section editing
 *
 * @param string $id page id
 * @param string $preact action command before redirect
 */
function act_redirect($id,$preact){
    global $PRE;
    global $TEXT;

    $opts = array(
            'id'       => $id,
            'preact'   => $preact
            );
    //get section name when coming from section edit
    if($PRE && preg_match('/^\s*==+([^=\n]+)/',$TEXT,$match)){
        $check = false; //Byref
        $opts['fragment'] = sectionID($match[0], $check);
    }

    trigger_event('ACTION_SHOW_REDIRECT',$opts,'act_redirect_execute');
}

/**
 * Execute the redirect
 *
 * @param array $opts id and fragment for the redirect and the preact
 */
function act_redirect_execute($opts){
    $go = wl($opts['id'],'',true);
    if(isset($opts['fragment'])) $go .= '#'.$opts['fragment'];

    //show it
    send_redirect($go);
}

/**
 * Handle 'login', 'logout'
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param string $act action command
 * @return string action command
 */
function act_auth($act){
    global $ID;
    global $INFO;
    /* @var Input $INPUT */
    global $INPUT;

    //already logged in?
    if($INPUT->server->has('REMOTE_USER') && $act=='login'){
        return 'show';
    }

    //handle logout
    if($act=='logout'){
        $lockedby = checklock($ID); //page still locked?
        if($lockedby == $INPUT->server->str('REMOTE_USER')){
            unlock($ID); //try to unlock
        }

        // do the logout stuff
        auth_logoff();

        // rebuild info array
        $INFO = pageinfo();

        act_redirect($ID,'login');
    }

    return $act;
}

/**
 * Handle 'edit', 'preview', 'recover'
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param string $act action command
 * @return string action command
 */
function act_edit($act){
    global $ID;
    global $INFO;

    global $TEXT;
    global $RANGE;
    global $PRE;
    global $SUF;
    global $REV;
    global $SUM;
    global $lang;
    global $DATE;

    if (!isset($TEXT)) {
        if ($INFO['exists']) {
            if ($RANGE) {
                list($PRE,$TEXT,$SUF) = rawWikiSlices($RANGE,$ID,$REV);
            } else {
                $TEXT = rawWiki($ID,$REV);
            }
        } else {
            $TEXT = pageTemplate($ID);
        }
    }

    //set summary default
    if(!$SUM){
        if($REV){
            $SUM = sprintf($lang['restored'], dformat($REV));
        }elseif(!$INFO['exists']){
            $SUM = $lang['created'];
        }
    }

    // Use the date of the newest revision, not of the revision we edit
    // This is used for conflict detection
    if(!$DATE) $DATE = @filemtime(wikiFN($ID));

    //check if locked by anyone - if not lock for my self
    //do not lock when the user can't edit anyway
    if ($INFO['writable']) {
        $lockedby = checklock($ID);
        if($lockedby) return 'locked';

        lock($ID);
    }

    return $act;
}

/**
 * Export a wiki page for various formats
 *
 * Triggers ACTION_EXPORT_POSTPROCESS
 *
 *  Event data:
 *    data['id']      -- page id
 *    data['mode']    -- requested export mode
 *    data['headers'] -- export headers
 *    data['output']  -- export output
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Michael Klier <chi@chimeric.de>
 *
 * @param string $act action command
 * @return string action command
 */
function act_export($act){
    global $ID;
    global $REV;
    global $conf;
    global $lang;

    $pre = '';
    $post = '';
    $headers = array();

    // search engines: never cache exported docs! (Google only currently)
    $headers['X-Robots-Tag'] = 'noindex';

    $mode = substr($act,7);
    switch($mode) {
        case 'raw':
            $headers['Content-Type'] = 'text/plain; charset=utf-8';
            $headers['Content-Disposition'] = 'attachment; filename='.noNS($ID).'.txt';
            $output = rawWiki($ID,$REV);
            break;
        case 'xhtml':
            $pre .= '<!DOCTYPE html>' . DOKU_LF;
            $pre .= '<html lang="'.$conf['lang'].'" dir="'.$lang['direction'].'">' . DOKU_LF;
            $pre .= '<head>' . DOKU_LF;
            $pre .= '  <meta charset="utf-8" />' . DOKU_LF;
            $pre .= '  <title>'.$ID.'</title>' . DOKU_LF;

            // get metaheaders
            ob_start();
            tpl_metaheaders();
            $pre .= ob_get_clean();

            $pre .= '</head>' . DOKU_LF;
            $pre .= '<body>' . DOKU_LF;
            $pre .= '<div class="dokuwiki export">' . DOKU_LF;

            // get toc
            $pre .= tpl_toc(true);

            $headers['Content-Type'] = 'text/html; charset=utf-8';
            $output = p_wiki_xhtml($ID,$REV,false);

            $post .= '</div>' . DOKU_LF;
            $post .= '</body>' . DOKU_LF;
            $post .= '</html>' . DOKU_LF;
            break;
        case 'xhtmlbody':
            $headers['Content-Type'] = 'text/html; charset=utf-8';
            $output = p_wiki_xhtml($ID,$REV,false);
            break;
        default:
            $output = p_cached_output(wikiFN($ID,$REV), $mode, $ID);
            $headers = p_get_metadata($ID,"format $mode");
            break;
    }

    // prepare event data
    $data = array();
    $data['id'] = $ID;
    $data['mode'] = $mode;
    $data['headers'] = $headers;
    $data['output'] =& $output;

    trigger_event('ACTION_EXPORT_POSTPROCESS', $data);

    if(!empty($data['output'])){
        if(is_array($data['headers'])) foreach($data['headers'] as $key => $val){
            header("$key: $val");
        }
        print $pre.$data['output'].$post;
        exit;
    }
    return 'show';
}

/**
 * Handle sitemap delivery
 *
 * @author Michael Hamann <michael@content-space.de>
 *
 * @param string $act action command
 */
function act_sitemap($act) {
    global $conf;

    if ($conf['sitemap'] < 1 || !is_numeric($conf['sitemap'])) {
        http_status(404);
        print "Sitemap generation is disabled.";
        exit;
    }

    $sitemap = Sitemapper::getFilePath();
    if (Sitemapper::sitemapIsCompressed()) {
        $mime = 'application/x-gzip';
    }else{
        $mime = 'application/xml; charset=utf-8';
    }

    // Check if sitemap file exists, otherwise create it
    if (!is_readable($sitemap)) {
        Sitemapper::generate();
    }

    if (is_readable($sitemap)) {
        // Send headers
        header('Content-Type: '.$mime);
        header('Content-Disposition: attachment; filename='.utf8_basename($sitemap));

        http_conditionalRequest(filemtime($sitemap));

        // Send file
        //use x-sendfile header to pass the delivery to compatible webservers
        http_sendfile($sitemap);

        readfile($sitemap);
        exit;
    }

    http_status(500);
    print "Could not read the sitemap file - bad permissions?";
    exit;
}

/**
 * Handle page 'subscribe'
 *
 * Throws exception on error.
 *
 * @author Adrian Lang <lang@cosmocode.de>
 *
 * @param string $act action command
 * @return string action command
 * @throws Exception if (un)subscribing fails
 */
function act_subscription($act){
    global $lang;
    global $INFO;
    global $ID;
    /* @var Input $INPUT */
    global $INPUT;

    // subcriptions work for logged in users only
    if(!$INPUT->server->str('REMOTE_USER')) return 'show';

    // get and preprocess data.
    $params = array();
    foreach(array('target', 'style', 'action') as $param) {
        if ($INPUT->has("sub_$param")) {
            $params[$param] = $INPUT->str("sub_$param");
        }
    }

    // any action given? if not just return and show the subscription page
    if(empty($params['action']) || !checkSecurityToken()) return $act;

    // Handle POST data, may throw exception.
    trigger_event('ACTION_HANDLE_SUBSCRIBE', $params, 'subscription_handle_post');

    $target = $params['target'];
    $style  = $params['style'];
    $action = $params['action'];

    // Perform action.
    $sub = new Subscription();
    if($action == 'unsubscribe'){
        $ok = $sub->remove($target, $INPUT->server->str('REMOTE_USER'), $style);
    }else{
        $ok = $sub->add($target, $INPUT->server->str('REMOTE_USER'), $style);
    }

    if($ok) {
        msg(sprintf($lang["subscr_{$action}_success"], hsc($INFO['userinfo']['name']),
                    prettyprint_id($target)), 1);
        act_redirect($ID, $act);
    } else {
        throw new Exception(sprintf($lang["subscr_{$action}_error"],
                                    hsc($INFO['userinfo']['name']),
                                    prettyprint_id($target)));
    }

    // Assure that we have valid data if act_redirect somehow fails.
    $INFO['subscribed'] = $sub->user_subscription();
    return 'show';
}

/**
 * Validate POST data
 *
 * Validates POST data for a subscribe or unsubscribe request. This is the
 * default action for the event ACTION_HANDLE_SUBSCRIBE.
 *
 * @author Adrian Lang <lang@cosmocode.de>
 *
 * @param array &$params the parameters: target, style and action
 * @throws Exception
 */
function subscription_handle_post(&$params) {
    global $INFO;
    global $lang;
    /* @var Input $INPUT */
    global $INPUT;

    // Get and validate parameters.
    if (!isset($params['target'])) {
        throw new Exception('no subscription target given');
    }
    $target = $params['target'];
    $valid_styles = array('every', 'digest');
    if (substr($target, -1, 1) === ':') {
        // Allow “list” subscribe style since the target is a namespace.
        $valid_styles[] = 'list';
    }
    $style  = valid_input_set('style', $valid_styles, $params,
                              'invalid subscription style given');
    $action = valid_input_set('action', array('subscribe', 'unsubscribe'),
                              $params, 'invalid subscription action given');

    // Check other conditions.
    if ($action === 'subscribe') {
        if ($INFO['userinfo']['mail'] === '') {
            throw new Exception($lang['subscr_subscribe_noaddress']);
        }
    } elseif ($action === 'unsubscribe') {
        $is = false;
        foreach($INFO['subscribed'] as $subscr) {
            if ($subscr['target'] === $target) {
                $is = true;
            }
        }
        if ($is === false) {
            throw new Exception(sprintf($lang['subscr_not_subscribed'],
                                        $INPUT->server->str('REMOTE_USER'),
                                        prettyprint_id($target)));
        }
        // subscription_set deletes a subscription if style = null.
        $style = null;
    }

    $params = compact('target', 'style', 'action');
}

//Setup VIM: ex: et ts=2 :