1<?php
2
3namespace dokuwiki\plugin\struct\meta;
4
5/**
6 * Class SearchConfig
7 *
8 * The same as @see Search but can be initialized by a configuration array
9 *
10 * @package dokuwiki\plugin\struct\meta
11 */
12class SearchConfig extends Search
13{
14    /** @var int default aggregation caching (depends on last struct save) */
15    public static $CACHE_DEFAULT = 1;
16    /** @var int caching depends on current user */
17    public static $CACHE_USER = 2;
18    /** @var int caching depends on current date */
19    public static $CACHE_DATE = 4;
20
21    /**
22     * @var array hold the configuration as parsed and extended by dynamic params
23     */
24    protected $config;
25
26    /**
27     * @var SearchConfigParameters manages dynamic parameters
28     */
29    protected $dynamicParameters;
30
31    /**
32     * @var int the cache flag to use (binary flags)
33     */
34    protected $cacheFlag;
35
36    /**
37     * SearchConfig constructor.
38     * @param array $config The parsed configuration for this search
39     */
40    public function __construct($config)
41    {
42        parent::__construct();
43
44        // setup schemas and columns
45        if (!empty($config['schemas'])) foreach ($config['schemas'] as $schema) {
46            $this->addSchema($schema[0], $schema[1]);
47        }
48        if (!empty($config['cols'])) foreach ($config['cols'] as $col) {
49            $this->addColumn($col);
50        }
51
52        // cache flag setting
53        $this->cacheFlag = self::$CACHE_DEFAULT;
54        if (!empty($config['filters'])) $this->cacheFlag = $this->determineCacheFlag($config['filters']);
55
56        // apply dynamic paramters
57        $this->dynamicParameters = new SearchConfigParameters($this);
58        $config = $this->dynamicParameters->updateConfig($config);
59
60        // configure search from configuration
61        if (!empty($config['filter'])) foreach ($config['filter'] as $filter) {
62            $this->addFilter($filter[0], $this->applyFilterVars($filter[2]), $filter[1], $filter[3]);
63        }
64
65        if (!empty($config['sort'])) foreach ($config['sort'] as $sort) {
66            $this->addSort($sort[0], $sort[1]);
67        }
68
69        if (!empty($config['limit'])) {
70            $this->setLimit($config['limit']);
71        }
72
73        if (!empty($config['offset'])) {
74            $this->setOffset($config['offset']);
75        }
76
77        $this->config = $config;
78    }
79
80    /**
81     * Set the cache flag accordingly to the set filter placeholders
82     *
83     * @param array $filters
84     * @return int
85     */
86    protected function determineCacheFlag($filters)
87    {
88        $flags = self::$CACHE_DEFAULT;
89
90        foreach ($filters as $filter) {
91            if (is_array($filter)) $filter = $filter[2]; // this is the format we get fro the config parser
92
93            if (strpos($filter, '$USER$') !== false) {
94                $flags |= self::$CACHE_USER;
95            } elseif (strpos($filter, '$TODAY$') !== false) {
96                $flags |= self::$CACHE_DATE;
97            }
98        }
99
100        return $flags;
101    }
102
103    /**
104     * Replaces placeholders in the given filter value by the proper value
105     *
106     * @param string $filter
107     * @return string|string[] Result may be an array when a multi column placeholder is used
108     */
109    protected function applyFilterVars($filter)
110    {
111        global $INFO;
112        if (is_null($INFO)) {
113            $INFO = ['id' => null];
114        }
115
116        // apply inexpensive filters first
117        $filter = str_replace(
118            array(
119                '$ID$',
120                '$NS$',
121                '$PAGE$',
122                '$USER$',
123                '$TODAY$'
124            ),
125            array(
126                $INFO['id'],
127                getNS($INFO['id']),
128                noNS($INFO['id']),
129                isset($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'] : '',
130                date('Y-m-d')
131            ),
132            $filter
133        );
134
135        // apply struct column placeholder (we support only one!)
136        if (preg_match('/^(.*?)(?:\$STRUCT\.(.*?)\$)(.*?)$/', $filter, $match)) {
137            $filter = $this->applyFilterVarsStruct($match);
138        } elseif (preg_match('/^(.*?)(?:\$USER\.(.*?)\$)(.*?)$/', $filter, $match)) {
139            $filter = $this->applyFilterVarsUser($match);
140        }
141
142        return $filter;
143    }
144
145    /**
146     * Replaces struct placeholders in the given filter value by the proper value
147     *
148     * @param string $match
149     * @return string|string[] Result may be an array when a multi column placeholder is used
150     */
151    protected function applyFilterVarsStruct($match)
152    {
153        global $INFO;
154
155        $key = $match[2];
156
157        // we try to resolve the key via the assigned schemas first, otherwise take it literally
158        $column = $this->findColumn($key, true);
159        if ($column) {
160            $label = $column->getLabel();
161            $table = $column->getTable();
162        } else {
163            list($table, $label) = explode('.', $key);
164        }
165
166        // get the data from the current page
167        if ($table && $label) {
168            $schemaData = AccessTable::getPageAccess($table, $INFO['id']);
169            $data = $schemaData->getData();
170            if (!isset($data[$label])) {
171                throw new StructException("column not in table", $label, $table);
172            }
173            $value = $data[$label]->getCompareValue();
174
175            if (is_array($value) && !count($value)) {
176                $value = '';
177            }
178        } else {
179            $value = '';
180        }
181
182        // apply any pre and postfixes, even when multi value
183        if (is_array($value)) {
184            $filter = array();
185            foreach ($value as $item) {
186                $filter[] = $match[1] . $item . $match[3];
187            }
188        } else {
189            $filter = $match[1] . $value . $match[3];
190        }
191
192        return $filter;
193    }
194
195    /**
196     * Replaces user placeholders in the given filter value by the proper value
197     *
198     * @param string $match
199     * @return string|string[] String for name and mail, array for grps
200     */
201    protected function applyFilterVarsUser($match)
202    {
203        global $INFO;
204
205        $key = strtolower($match[2]);
206
207        if (!in_array($key, array('name', 'mail', 'grps'))) {
208            throw new StructException('"%s" is not a valid USER key', $key);
209        }
210
211        if (empty($INFO['userinfo'])) {
212            $filter = '';
213        } else {
214            $filter = $INFO['userinfo'][$key];
215        }
216
217        return $filter;
218    }
219
220    /**
221     * @return int cacheflag for this search
222     */
223    public function getCacheFlag()
224    {
225        return $this->cacheFlag;
226    }
227
228    /**
229     * Access the dynamic paramters of this search
230     *
231     * Note: This call returns a clone of the parameters as they were initialized
232     *
233     * @return SearchConfigParameters
234     */
235    public function getDynamicParameters()
236    {
237        return clone $this->dynamicParameters;
238    }
239
240    /**
241     * @return array the current config
242     */
243    public function getConf()
244    {
245        return $this->config;
246    }
247}
248