1<?php
2/**
3 * DokuWiki Plugin extendpage (Action Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Frieder Schrempf <dev@fris.de>
7 */
8
9use dokuwiki\plugin\extendpage\meta\Assignments;
10use dokuwiki\plugin\extendpage\meta\ExtendPageException;
11
12// must be run within Dokuwiki
13if (!defined('DOKU_INC')) {
14    die();
15}
16
17class action_plugin_extendpage extends DokuWiki_Action_Plugin
18{
19
20    /**
21     * Registers a callback function for a given event
22     *
23     * @param Doku_Event_Handler $controller DokuWiki's event controller object
24     *
25     * @return void
26     */
27    public function register(Doku_Event_Handler $controller)
28    {
29        $controller->register_hook('PARSER_WIKITEXT_PREPROCESS', 'AFTER', $this, 'extend_page');
30    }
31
32    /**
33     * [Custom event handler which performs action]
34     *
35     * Called for event:
36     *
37     * @param Doku_Event $event  event object by reference
38     * @param mixed      $param  [the parameters passed as fifth argument to register_hook() when this
39     *                           handler was registered]
40     *
41     * @return void
42     */
43    public function extend_page(Doku_Event $event, $param)
44    {
45        global $ID;
46        $positions = array('replace', 'top', 'bottom');
47
48        if (!page_exists($ID)) return;
49
50        try {
51            $assignments = Assignments::getInstance();
52        } catch (ExtendPageException $e) {
53            return false;
54        }
55
56        foreach ($positions as $pos) {
57            $idx = $pos === 'bottom' ? strlen($event->data):0;
58            $extensions = $assignments->getPageAssignments($ID, $pos);
59            if (!$extensions) return true;
60
61            foreach ($extensions as $ext) {
62                if ($pos === 'replace') {
63                    $event->data = rawWiki($ext['page']);
64                } else {
65                    $event->data = substr_replace($event->data,
66                        ($pos === 'top' ? '':'\\\ ') . rawWiki($ext['page']) . ($pos === 'top' ? '\\\ ':''),
67                        $idx, 0
68                    );
69                }
70            }
71        }
72    }
73}
74
75