xref: /plugin/struct/types/User.php (revision c5827bd5f7a5cd577d1cc87ff8229cde791cba65)
1<?php
2namespace plugin\struct\types;
3
4use plugin\struct\meta\StructException;
5use plugin\struct\meta\ValidationException;
6
7class User extends AbstractBaseType {
8
9    protected $config = array(
10        'fullname' => true,
11        'autocomplete' => array(
12            'mininput' => 2,
13            'maxresult' => 5,
14        ),
15    );
16
17    /**
18     * @param string $value the user to validate
19     */
20    public function validate($value) {
21        /** @var \DokuWiki_Auth_Plugin $auth */
22        global $auth;
23        $info = $auth->getUserData($value, false);
24        if($info === false) throw new ValidationException('User not found', $value);
25    }
26
27    /**
28     * @param string $value the user to display
29     * @param \Doku_Renderer $R
30     * @param string $mode
31     * @return bool
32     */
33    public function renderValue($value, \Doku_Renderer $R, $mode) {
34        if($mode == 'xhtml') {
35            $name = userlink($value);
36            $R->doc .= $name;
37        } else {
38            $name = userlink($value, true);
39            $R->cdata($name);
40        }
41        return true;
42    }
43
44    /**
45     * Autocompletion for user names
46     *
47     * @todo should we have any security mechanism? Currently everybody can look up users
48     * @return array
49     */
50    public function handleAjax() {
51        /** @var \DokuWiki_Auth_Plugin $auth */
52        global $auth;
53        global $INPUT;
54
55        if(!$auth->canDo('getUsers')) {
56            throw new StructException('The user backend can not search for users');
57        }
58
59        // check minimum length
60        $lookup = trim($INPUT->str('search'));
61        if(utf8_strlen($lookup) < $this->config['autocomplete']['mininput']) return array();
62
63        // find users by login, fill up with names if wanted
64        $max = $this->config['autocomplete']['maxresult'];
65        $logins = (array) $auth->retrieveUsers(0, $max, array('user' => $lookup));
66        if((count($logins) < $max) && $this->config['fullname']) {
67            $logins = array_merge($logins, (array) $auth->retrieveUsers(0, $max, array('name' => $lookup)));
68        }
69
70        // reformat result for jQuery UI Autocomplete
71        $users = array();
72        foreach($logins as $login => $info) {
73            $users[] = array(
74                'label' => $info['name'] . ' [' . $login . ']',
75                'value' => $login
76            );
77        }
78
79        return $users;
80    }
81
82}
83