xref: /plugin/struct/meta/AggregationTable.php (revision 1c9ef013f15ea5cae98753d99575ee10a39cd44b)
1<?php
2
3namespace dokuwiki\plugin\struct\meta;
4
5/**
6 * Creates the table aggregation output
7 *
8 * @package dokuwiki\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
83        // abort early if there are no results at all (not filtered)
84        if(!$this->resultCount && !$this->isDynamicallyFiltered()) {
85            $this->startScope();
86            $this->renderer->cdata($this->helper->getLang('none'));
87            $this->finishScope();
88            return;
89        }
90
91        // table open
92        $this->startScope();
93        $this->renderActiveFilters();
94        $this->renderer->table_open();
95
96        // header
97        $this->renderer->tablethead_open();
98        $this->renderColumnHeaders();
99        $this->renderDynamicFilters();
100        $this->renderer->tablethead_close();
101
102        if($this->resultCount) {
103            // actual data
104            $this->renderResult();
105
106            // footer
107            $this->renderSums();
108            $this->renderPagingControls();
109        } else {
110            // nothing found
111            $this->renderEmptyResult();
112        }
113
114        // table close
115        $this->renderer->table_close();
116        $this->finishScope();
117    }
118
119    /**
120     * Adds additional info to document and renderer in XHTML mode
121     *
122     * @see finishScope()
123     */
124    protected function startScope() {
125        if($this->mode != 'xhtml') return;
126
127        // wrapping div
128        $this->renderer->doc .= "<div class=\"structaggregation\">";
129
130        // unique identifier for this aggregation
131        $this->renderer->info['struct_table_hash'] = md5(var_export($this->data, true));
132    }
133
134    /**
135     * Closes the table and anything opened in startScope()
136     *
137     * @see startScope()
138     */
139    protected function finishScope() {
140        if($this->mode != 'xhtml') return;
141
142        // wrapping div
143        $this->renderer->doc .= '</div>';
144
145        // remove identifier from renderer again
146        if(isset($this->renderer->info['struct_table_hash'])) {
147            unset($this->renderer->info['struct_table_hash']);
148        }
149    }
150
151    /**
152     * Displays info about the currently applied filters
153     */
154    protected function renderActiveFilters() {
155        if($this->mode != 'xhtml') return;
156        $dynamic = $this->searchConfig->getDynamicParameters();
157        $filters = $dynamic->getFilters();
158        if(!$filters) return;
159
160        $fltrs = array();
161        foreach($filters as $column => $filter) {
162            list($comp, $value) = $filter;
163            $fltrs[] = $column . ' ' . $comp . ' ' . $value;
164        }
165
166        $this->renderer->doc .= '<div class="filter">';
167        $this->renderer->doc .= '<h4>' . sprintf($this->helper->getLang('tablefilteredby'), hsc(implode(' & ', $fltrs))) . '</h4>';
168        $this->renderer->doc .= '<div class="resetfilter">';
169        $this->renderer->internallink($this->id, $this->helper->getLang('tableresetfilter'));
170        $this->renderer->doc .= '</div>';
171        $this->renderer->doc .= '</div>';
172    }
173
174    /**
175     * Shows the column headers with links to sort by column
176     */
177    protected function renderColumnHeaders() {
178        $this->renderer->tablerow_open();
179
180        // additional column for row numbers
181        if($this->data['rownumbers']) {
182            $this->renderer->tableheader_open();
183            $this->renderer->cdata('#');
184            $this->renderer->tableheader_close();
185        }
186
187        // show all headers
188        foreach($this->data['headers'] as $num => $header) {
189            if(!isset($this->columns[$num])) break; // less columns where available then expected
190            $column = $this->columns[$num];
191
192            // use field label if no header was set
193            if(blank($header)) {
194                if(is_a($column, 'dokuwiki\plugin\struct\meta\PageColumn')) {
195                    $header = $this->helper->getLang('pagelabel'); // @todo this could be part of PageColumn::getTranslatedLabel
196                } else if(is_a($column, 'dokuwiki\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     * Is the result set currently dynamically filtered?
246     * @return bool
247     */
248    protected function isDynamicallyFiltered() {
249        if($this->mode != 'xhtml') return false;
250        if(!$this->data['dynfilters']) return false;
251
252        $dynamic = $this->searchConfig->getDynamicParameters();
253        return (bool) $dynamic->getFilters();
254    }
255
256    /**
257     * Add input fields for dynamic filtering
258     */
259    protected function renderDynamicFilters() {
260        if($this->mode != 'xhtml') return;
261        if(!$this->data['dynfilters']) return;
262        global $conf;
263
264        $this->renderer->doc .= '<tr class="dataflt">';
265
266        // add extra column for row numbers
267        if($this->data['rownumbers']) {
268            $this->renderer->doc .= '<th></th>';
269        }
270
271        // each column gets a form
272        foreach($this->columns as $column) {
273            $this->renderer->doc .= '<th>';
274            {
275                $form = new \Doku_Form(array('method' => 'GET', 'action' => wl($this->id)));
276                unset($form->_hidden['sectok']); // we don't need it here
277                if(!$conf['userewrite']) $form->addHidden('id', $this->id);
278
279                // current value
280                $dynamic = $this->searchConfig->getDynamicParameters();
281                $filters = $dynamic->getFilters();
282                if(isset($filters[$column->getFullQualifiedLabel()])) {
283                    list(, $current) = $filters[$column->getFullQualifiedLabel()];
284                    $dynamic->removeFilter($column);
285                } else {
286                    $current = '';
287                }
288
289                // Add current request params
290                $params = $dynamic->getURLParameters();
291                foreach($params as $key => $val) {
292                    $form->addHidden($key, $val);
293                }
294
295                // add input field
296                $key = $column->getFullQualifiedLabel() . '*~';
297                $form->addElement(form_makeField('text', SearchConfigParameters::$PARAM_FILTER . '[' . $key . ']', $current, ''));
298                $this->renderer->doc .= $form->getForm();
299            }
300            $this->renderer->doc .= '</th>';
301        }
302        $this->renderer->doc .= '</tr>';
303
304    }
305
306    /**
307     * Display the actual table data
308     */
309    protected function renderResult() {
310        $this->renderer->tabletbody_open();
311        foreach($this->result as $rownum => $row) {
312            $this->renderer->tablerow_open();
313
314            // row number column
315            if($this->data['rownumbers']) {
316                $this->renderer->tablecell_open();
317                $this->renderer->doc .= $rownum + 1;
318                $this->renderer->tablecell_close();
319            }
320
321            /** @var Value $value */
322            foreach($row as $colnum => $value) {
323                $this->renderer->tablecell_open();
324                $value->render($this->renderer, $this->mode);
325                $this->renderer->tablecell_close();
326
327                // summarize
328                if($this->data['summarize'] && is_numeric($value->getValue())) {
329                    if(!isset($this->sums[$colnum])) {
330                        $this->sums[$colnum] = 0;
331                    }
332                    $this->sums[$colnum] += $value->getValue();
333                }
334            }
335            $this->renderer->tablerow_close();
336        }
337        $this->renderer->tabletbody_close();
338    }
339
340    /**
341     * Renders an information row for when no results were found
342     */
343    protected function renderEmptyResult() {
344        $this->renderer->tablerow_open();
345        $this->renderer->tablecell_open(count($this->data['cols']) + $this->data['rownumbers'], 'center');
346        $this->renderer->cdata($this->helper->getLang('none'));
347        $this->renderer->tablecell_close();
348        $this->renderer->tablerow_close();
349    }
350
351    /**
352     * Add sums if wanted
353     */
354    protected function renderSums() {
355        if(empty($this->data['summarize'])) return;
356
357        $this->renderer->tablerow_open();
358
359        if($this->data['rownumbers']) {
360            $this->renderer->tablecell_open();
361            $this->renderer->tablecell_close();
362        }
363
364        $len = count($this->columns);
365        for($i = 0; $i < $len; $i++) {
366            $this->renderer->tablecell_open(1, $this->data['align'][$i]);
367            if(!empty($this->sums[$i])) {
368                $this->renderer->cdata('∑ ');
369                $this->columns[$i]->getType()->renderValue($this->sums[$i], $this->renderer, $this->mode);
370            } else {
371                if($this->mode == 'xhtml') {
372                    $this->renderer->doc .= '&nbsp;';
373                }
374            }
375            $this->renderer->tablecell_close();
376        }
377        $this->renderer->tablerow_close();
378    }
379
380    /**
381     * Adds paging controls to the table
382     */
383    protected function renderPagingControls() {
384        if(empty($this->data['limit'])) return;
385        if($this->mode != 'xhtml') ;
386
387        $this->renderer->tablerow_open();
388        $this->renderer->tableheader_open((count($this->data['cols']) + ($this->data['rownumbers'] ? 1 : 0)));
389        $offset = $this->data['offset'];
390
391        // prev link
392        if($offset) {
393            $prev = $offset - $this->data['limit'];
394            if($prev < 0) {
395                $prev = 0;
396            }
397
398            $dynamic = $this->searchConfig->getDynamicParameters();
399            $dynamic->setOffset($prev);
400            $link = wl($this->id, $dynamic->getURLParameters());
401            $this->renderer->doc .= '<a href="' . $link . '" class="prev">' . $this->helper->getLang('prev') . '</a>';
402        }
403
404        // next link
405        if($this->resultCount > $offset + $this->data['limit']) {
406            $next = $offset + $this->data['limit'];
407            $dynamic = $this->searchConfig->getDynamicParameters();
408            $dynamic->setOffset($next);
409            $link = wl($this->id, $dynamic->getURLParameters());
410            $this->renderer->doc .= '<a href="' . $link . '" class="next">' . $this->helper->getLang('next') . '</a>';
411        }
412
413        $this->renderer->tableheader_close();
414        $this->renderer->tablerow_close();
415    }
416}
417