1<?php
2
3// must be run within Dokuwiki
4if (!defined('DOKU_INC')) {
5    die();
6}
7
8class action_plugin_authloginapi extends DokuWiki_Action_Plugin
9{
10    protected $active;
11    protected $endpoint;
12    protected $token;
13
14    /**
15     * Constructor
16     */
17    public function __construct()
18    {
19        global $conf;
20
21        $this->active = (
22            $conf['authtype'] == 'authloginapi' ||
23            (
24                $conf['authtype'] == 'authsplit' &&
25                $conf['plugin']['authsplit']['primary_authplugin'] == 'authloginapi'
26            )
27        );
28
29        $this->endpoint = $this->getConf('endpoint');
30        $this->token = $this->getConf('token');
31    }
32    /**
33     * {@inheritDoc}
34     */
35    public function register(Doku_Event_Handler &$controller)
36    {
37        $controller->register_hook('HTML_LOGINFORM_OUTPUT', 'BEFORE', $this, 'handle_login_form');
38    }
39
40    /**
41     * Modify login form to send a request to Login API Server
42     *
43     * @param Doku_Event $event
44     * @param object     $param
45     */
46    public function handle_login_form(Doku_Event &$event, $param)
47    {
48        global $ID;
49
50        if (!$this->active) {
51            return;
52        }
53
54        $form = $event->data;
55        $removedFields = array('textfield', 'passwordfield', 'checkboxfield');
56        foreach ($removedFields as $fieldType) {
57            while (($field = $form->findElementByType($fieldType)) !== false) {
58                $form->replaceElement($field, null);
59            }
60        }
61        $buttonPos = $form->findElementByType('button');
62        $button = $form->getElementAt($buttonPos);
63        $button['value'] = $this->getConf('button');
64        $form->replaceElement($buttonPos, $button);
65
66        $request = array(
67            'time' => time(),
68            'return' => $this->buildReturnUrl(array('do' => 'login')),
69            'action' => 'login',
70            'site' => $this->getSiteName(),
71        );
72
73        $encoded = rtrim(strtr(base64_encode(json_encode($request)), '+/', '-_'), '=');
74        $form->addHidden('r', $encoded);
75
76        $signature = hash('sha256', $encoded.$this->token);
77        $form->addHidden('s', $signature);
78
79        $form->params['action'] = $this->endpoint;
80        $form->params['method'] = 'get';
81    }
82
83    /**
84     * Build a URL which will be the redirection target after login
85     *
86     * @param  array  $params Additional parameters (appended to query)
87     * @return string
88     */
89    protected function buildReturnUrl($params = array())
90    {
91        global $ID;
92
93        return wl($ID, $params, true, '&');
94    }
95
96    /**
97     * Return the wiki name
98     *
99     * @return string
100     */
101    protected function getSiteName()
102    {
103        global $conf;
104
105        return $conf['title'];
106    }
107}
108