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