xref: /plugin/struct/meta/AggregationTable.php (revision aa1247084102774e3fd98ab7a6c053fcf402ff97)
1<?php
2
3namespace plugin\struct\meta;
4
5/**
6 * Creates the table aggregation output
7 *
8 * @package plugin\struct\meta
9 */
10class AggregationTable {
11
12    /**
13     * @var string the page id of the page this is rendered to
14     */
15    protected $id;
16    /**
17     * @var string the Type of renderer used
18     */
19    protected $mode;
20    /**
21     * @var \Doku_Renderer the DokuWiki renderer used to create the output
22     */
23    protected $renderer;
24    /**
25     * @var SearchConfig the configured search - gives access to columns etc.
26     */
27    protected $searchConfig;
28
29    /**
30     * @var Column[] the list of columns to be displayed
31     */
32    protected $columns;
33
34    /**
35     * @var  Value[][] the search result
36     */
37    protected $result;
38
39    /**
40     * @var int number of all results
41     */
42    protected $resultCount;
43
44    /**
45     * @var array for summing up columns
46     */
47    protected $sums;
48
49    /**
50     * @todo we might be able to get rid of this helper and move this to SearchConfig
51     * @var \helper_plugin_struct_config
52     */
53    protected $helper;
54
55    /**
56     * Initialize the Aggregation renderer and executes the search
57     *
58     * You need to call @see render() on the resulting object.
59     *
60     * @param string $id
61     * @param string $mode
62     * @param \Doku_Renderer $renderer
63     * @param SearchConfig $searchConfig
64     */
65    public function __construct($id, $mode, \Doku_Renderer $renderer, SearchConfig $searchConfig) {
66        $this->id = $id;
67        $this->mode = $mode;
68        $this->renderer = $renderer;
69        $this->searchConfig = $searchConfig;
70        $this->data = $searchConfig->getConf();
71        $this->columns = $searchConfig->getColumns();
72
73        $this->result = $this->searchConfig->execute();
74        $this->resultCount = $this->searchConfig->getCount();
75        $this->helper = plugin_load('helper', 'struct_config');
76    }
77
78    /**
79     * Create the table on the renderer
80     */
81    public function render() {
82        // table open
83        $this->startScope();
84        $this->renderActiveFilters();
85        $this->renderer->table_open();
86
87        // header
88        $this->renderer->tablethead_open();
89        $this->renderColumnHeaders();
90        $this->renderDynamicFilters();
91        $this->renderer->tablethead_close();
92
93        if($this->resultCount) {
94            // actual data
95            $this->renderResult();
96
97            // footer
98            $this->renderSums();
99            $this->renderPagingControls();
100        } else {
101            // nothing found
102            $this->renderEmptyResult();
103        }
104
105        // table close
106        $this->renderer->table_close();
107        $this->finishScope();
108    }
109
110    /**
111     * Adds additional info to document and renderer in XHTML mode
112     *
113     * @see finishScope()
114     */
115    protected function startScope() {
116        if($this->mode != 'xhtml') return;
117
118        // wrapping div
119        $this->renderer->doc .= "<div class=\"structaggregation\">";
120
121        // unique identifier for this aggregation
122        $this->renderer->info['struct_table_hash'] = md5(var_export($this->data, true));
123    }
124
125    /**
126     * Closes the table and anything opened in startScope()
127     *
128     * @see startScope()
129     */
130    protected function finishScope() {
131        if($this->mode != 'xhtml') return;
132
133        // wrapping div
134        $this->renderer->doc .= '</div>';
135
136        // remove identifier from renderer again
137        if(isset($this->renderer->info['struct_table_hash'])) {
138            unset($this->renderer->info['struct_table_hash']);
139        }
140    }
141
142    /**
143     * Displays info about the currently applied filters
144     */
145    protected function renderActiveFilters() {
146        if($this->mode != 'xhtml') return;
147        $dynamic = $this->searchConfig->getDynamicParameters();
148        $filters = $dynamic->getFilters();
149        if(!$filters) return;
150
151        $fltrs = array();
152        foreach($filters as $column => $filter) {
153            list($comp, $value) = $filter;
154
155            if(strpos($comp, '~') !== false) {
156                if(strpos($comp, '!~') !== false) {
157                    $comparator_value = '!~' . str_replace('%', '*', $value);
158                } else {
159                    $comparator_value = '~' . str_replace('%', '', $value);
160                }
161                $fltrs[] = $column . $comparator_value;
162            } else {
163                $fltrs[] = $column . $comp . $value;
164            }
165        }
166
167        $this->renderer->doc .= '<div class="filter">';
168        $this->renderer->doc .= '<h4>' . sprintf($this->helper->getLang('tablefilteredby'), hsc(implode(' & ', $fltrs))) . '</h4>';
169        $this->renderer->doc .= '<div class="resetfilter">';
170        $this->renderer->internallink($this->id, $this->helper->getLang('tableresetfilter'));
171        $this->renderer->doc .= '</div>';
172        $this->renderer->doc .= '</div>';
173    }
174
175    /**
176     * Shows the column headers with links to sort by column
177     */
178    protected function renderColumnHeaders() {
179        $this->renderer->tablerow_open();
180
181        // additional column for row numbers
182        if($this->data['rownumbers']) {
183            $this->renderer->tableheader_open();
184            $this->renderer->cdata('#');
185            $this->renderer->tableheader_close();
186        }
187
188        // show all headers
189        foreach($this->data['headers'] as $num => $header) {
190            $column = $this->columns[$num];
191
192            // use field label if no header was set
193            if(blank($header)) {
194                if(is_a($column, 'plugin\struct\meta\PageColumn')) {
195                    $header = $this->helper->getLang('pagelabel'); // @todo this could be part of PageColumn::getTranslatedLabel
196                } else if(is_a($column, 'plugin\struct\meta\Column')) {
197                    $header = $column->getTranslatedLabel();
198                } else {
199                    $header = 'column ' . $num; // this should never happen
200                }
201            }
202
203            // simple mode first
204            if($this->mode != 'xhtml') {
205                $this->renderer->tableheader_open();
206                $this->renderer->cdata($header);
207                $this->renderer->tableheader_close();
208                continue;
209            }
210
211            // still here? create custom header for more flexibility
212
213            // width setting
214            $width = '';
215            if(isset($data['widths'][$num]) && $data['widths'][$num] != '-') {
216                $width = ' style="width: ' . $data['widths'][$num] . ';"';
217            }
218
219            // sort indicator and link
220            $sortclass = '';
221            $sorts = $this->searchConfig->getSorts();
222            $dynamic = $this->searchConfig->getDynamicParameters();
223            $dynamic->setSort($column, true);
224            if(isset($sorts[$column->getFullQualifiedLabel()])) {
225                list(/*colname*/, $currentSort) = $sorts[$column->getFullQualifiedLabel()];
226                if($currentSort) {
227                    $sortclass = 'sort-down';
228                    $dynamic->setSort($column, false);
229                } else {
230                    $sortclass = 'sort-up';
231                }
232            }
233            $link = wl($this->id, $dynamic->getURLParameters());
234
235            // output XHTML header
236            $this->renderer->doc .= "<th $width >";
237            $this->renderer->doc .= '<a href="' . $link . '" class="' . $sortclass . '" title="' . $this->helper->getLang('sort') . '">' . hsc($header) . '</a>';
238            $this->renderer->doc .= '</th>';
239        }
240
241        $this->renderer->tablerow_close();
242    }
243
244    /**
245     * Add input fields for dynamic filtering
246     */
247    protected function renderDynamicFilters() {
248        if($this->mode != 'xhtml') return;
249        if(!$this->data['dynfilters']) return;
250        global $conf;
251
252        $this->renderer->doc .= '<tr class="dataflt">';
253
254        // add extra column for row numbers
255        if($this->data['rownumbers']) {
256            $this->renderer->doc .= '<th></th>';
257        }
258
259        // each column gets a form
260        foreach($this->columns as $column) {
261            $this->renderer->doc .= '<th>';
262            {
263                $form = new \Doku_Form(array('method' => 'GET', 'action' => wl($this->id)));
264                unset($form->_hidden['sectok']); // we don't need it here
265                if(!$conf['userewrite']) $form->addHidden('id', $this->id);
266
267                // current value
268                $dynamic = $this->searchConfig->getDynamicParameters();
269                $filters = $dynamic->getFilters();
270                if(isset($filters[$column->getFullQualifiedLabel()])) {
271                    list(, $current) = $filters[$column->getFullQualifiedLabel()];
272                    $dynamic->removeFilter($column);
273                } else {
274                    $current = '';
275                }
276
277                // Add current request params
278                $params = $dynamic->getURLParameters();
279                foreach($params as $key => $val) {
280                    $form->addHidden($key, $val);
281                }
282
283                // add input field
284                $key = $column->getFullQualifiedLabel() . '*~';
285                $form->addElement(form_makeField('text', SearchConfigParameters::$PARAM_FILTER. '[' . $key . ']', $current, ''));
286                $this->renderer->doc .= $form->getForm();
287            }
288            $this->renderer->doc .= '</th>';
289        }
290        $this->renderer->doc .= '</tr>';
291
292    }
293
294    /**
295     * Display the actual table data
296     */
297    protected function renderResult() {
298        $this->renderer->tabletbody_open();
299        foreach($this->result as $rownum => $row) {
300            $this->renderer->tablerow_open();
301
302            // row number column
303            if($this->data['rownumbers']) {
304                $this->renderer->tablecell_open();
305                $this->renderer->doc .= $rownum + 1;
306                $this->renderer->tablecell_close();
307            }
308
309            /** @var Value $value */
310            foreach($row as $colnum => $value) {
311                $this->renderer->tablecell_open();
312                $value->render($this->renderer, $this->mode);
313                $this->renderer->tablecell_close();
314
315                // summarize
316                if($this->data['summarize'] && is_numeric($value->getValue())) {
317                    if(!isset($this->sums[$colnum])) {
318                        $this->sums[$colnum] = 0;
319                    }
320                    $this->sums[$colnum] += $value->getValue();
321                }
322            }
323            $this->renderer->tablerow_close();
324        }
325        $this->renderer->tabletbody_close();
326    }
327
328    /**
329     * Renders an information row for when no results were found
330     */
331    protected function renderEmptyResult() {
332        $this->renderer->tablerow_open();
333        $this->renderer->tablecell_open(count($this->data['cols']) + $this->data['rownumbers'], 'center');
334        $this->renderer->cdata($this->helper->getLang('none'));
335        $this->renderer->tablecell_close();
336        $this->renderer->tablerow_close();
337    }
338
339    /**
340     * Add sums if wanted
341     */
342    protected function renderSums() {
343        if($this->data['summarize']) return;
344
345        $this->renderer->tablerow_open();
346        $len = count($this->data['cols']);
347
348        if($this->data['rownumbers']) {
349            $this->renderer->tablecell_open();
350            $this->renderer->tablecell_close();
351        }
352
353        for($i = 0; $i < $len; $i++) {
354            $this->renderer->tablecell_open(1, $this->data['align'][$i]);
355            if(!empty($sums[$i])) {
356                $this->renderer->cdata('∑ ' . $sums[$i]);
357            } else {
358                if($this->mode == 'xhtml') {
359                    $this->renderer->doc .= '&nbsp;';
360                }
361            }
362            $this->renderer->tablecell_close();
363        }
364        $this->renderer->tablerow_close();
365    }
366
367    /**
368     * Adds paging controls to the table
369     */
370    protected function renderPagingControls() {
371        if(empty($this->data['limit'])) return;
372        if($this->mode != 'xhtml') ;
373
374        $this->renderer->tablerow_open();
375        $this->renderer->tableheader_open((count($this->data['cols']) + ($this->data['rownumbers'] ? 1 : 0)));
376        $offset = $this->data['offset'];
377
378        // prev link
379        if($offset) {
380            $prev = $offset - $this->data['limit'];
381            if($prev < 0) {
382                $prev = 0;
383            }
384
385            $dynamic = $this->searchConfig->getDynamicParameters();
386            $dynamic->setOffset($prev);
387            $link = wl($this->id, $dynamic->getURLParameters());
388            $this->renderer->doc .= '<a href="' . $link . '" class="prev">' . $this->helper->getLang('prev') . '</a>';
389        }
390
391        // next link
392        if($this->resultCount > $offset + $this->data['limit']) {
393            $next = $offset + $this->data['limit'];
394            $dynamic = $this->searchConfig->getDynamicParameters();
395            $dynamic->setOffset($next);
396            $link = wl($this->id, $dynamic->getURLParameters());
397            $this->renderer->doc .= '<a href="' . $link . '" class="next">' . $this->helper->getLang('next') . '</a>';
398        }
399
400        $this->renderer->tableheader_close();
401        $this->renderer->tablerow_close();
402    }
403}
404