1<?php
2/**
3 * Class helper_plugin_bureaucracyau_fielduser
4 *
5 * Create single user input, with autocompletion
6 */
7class helper_plugin_bureaucracyau_fielduser extends helper_plugin_bureaucracyau_fieldtextbox {
8
9    /**
10     * Arguments:
11     *  - cmd
12     *  - label
13     *  - ^ (optional)
14     *
15     * @param array $args The tokenized definition, only split at spaces
16     */
17    public function initialize($args) {
18        parent::initialize($args);
19        $this->tpl['class'] .= ' userpicker';
20    }
21
22    /**
23     * Allow receiving user attributes by ".". Ex. user.name
24     * You can pass an optional argument to user.grps enclosed in brackets, used as an groups delimiter Ex. user.grps(, )
25     *
26     * @return string
27     */
28    public function getReplacementPattern() {
29        $label = $this->opt['label'];
30
31        return '/(@@|##)' . preg_quote($label, '/') .
32            '(?:\.(.*?))?' .    //match attribute after "."
33            '(?:\((.*?)\))?' .  //match parameter enclosed in "()". Used for grps separator
34            '\1/si';
35    }
36
37    /**
38     * Used as an callback for preg_replace_callback
39     *
40     * @param $matches
41     * @return string
42     */
43    public function replacementValueCallback($matches) {
44        /** @var DokuWiki_Auth_Plugin $auth */
45        global $auth;
46
47        $value = $this->opt['value'];
48        //attr doesn't exists
49        if (!isset($matches[2])) {
50            return is_null($value) || $value === false ? '' : $value;
51        }
52        $attr = $matches[2];
53
54        $udata = $auth->getUserData($value);
55        //no such user
56        if ($udata === false) {
57            return $matches[0];
58        }
59
60        switch($attr) {
61            case 'name':
62            case 'mail':
63                return $udata[$attr];
64            case 'grps':
65                $delitmiter = ', ';
66                if (isset($matches[3])) {
67                    $delitmiter = $matches[3];
68                }
69                return implode($delitmiter, $udata['grps']);
70            default:
71                return $matches[0];
72        }
73    }
74
75    /**
76     * Return the callback for user replacement
77     *
78     * @return array
79     */
80    public function getReplacementValue() {
81        return array($this, 'replacementValueCallback');
82    }
83
84    /**
85     * Validate value of field
86     *
87     * @throws Exception when user not exists
88     */
89    protected function _validate() {
90        parent::_validate();
91
92        /** @var DokuWiki_Auth_Plugin $auth */
93        global $auth;
94        $value = $this->getParam('value');
95        if (!is_null($value) && $auth->getUserData($value) === false) {
96            throw new Exception(sprintf($this->getLang('e_user'),hsc($this->getParam('display'))));
97        }
98    }
99}
100