xref: /plugin/struct/types/User.php (revision 650e9493401c8f9f1230c886e395fd0eafde9638)
1<?php
2namespace plugin\struct\types;
3
4use plugin\struct\meta\StructException;
5use plugin\struct\meta\ValidationException;
6
7class User extends AbstractMultiBaseType {
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        // results wanted?
64        $max = $this->config['autocomplete']['maxresult'];
65        if($max <= 0) return array();
66
67        // find users by login, fill up with names if wanted
68        $logins = (array) $auth->retrieveUsers(0, $max, array('user' => $lookup));
69        if((count($logins) < $max) && $this->config['fullname']) {
70            $logins = array_merge($logins, (array) $auth->retrieveUsers(0, $max, array('name' => $lookup)));
71        }
72
73        // reformat result for jQuery UI Autocomplete
74        $users = array();
75        foreach($logins as $login => $info) {
76            $users[] = array(
77                'label' => $info['name'] . ' [' . $login . ']',
78                'value' => $login
79            );
80        }
81
82        return $users;
83    }
84
85}
86