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