xref: /plugin/struct/meta/AggregationTable.php (revision d982cb29e593acd2279ea3caa579f82580c2a03b)
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->renderer->tabletbody_open();
116            $this->renderResult();
117            $this->renderer->tabletbody_close();
118
119            // footer (tfoot is develonly currently)
120            if(method_exists($this->renderer, 'tabletfoot_open')) $this->renderer->tabletfoot_open();
121            $this->renderSums();
122            $this->renderPagingControls();
123            if(method_exists($this->renderer, 'tabletfoot_close')) $this->renderer->tabletfoot_close();
124        } else {
125            // nothing found
126            $this->renderEmptyResult();
127        }
128
129        // table close
130        $this->renderer->table_close();
131
132        // export handle
133        $this->renderExportControls();
134        $this->finishScope();
135    }
136
137    /**
138     * Adds additional info to document and renderer in XHTML mode
139     *
140     * @see finishScope()
141     */
142    protected function startScope() {
143        // unique identifier for this aggregation
144        $this->renderer->info['struct_table_hash'] = md5(var_export($this->data, true));
145
146        // wrapping div
147        if($this->mode != 'xhtml') return;
148        $this->renderer->doc .= "<div class=\"structaggregation\">";
149    }
150
151    /**
152     * Closes the table and anything opened in startScope()
153     *
154     * @see startScope()
155     */
156    protected function finishScope() {
157        // remove identifier from renderer again
158        if(isset($this->renderer->info['struct_table_hash'])) {
159            unset($this->renderer->info['struct_table_hash']);
160        }
161
162        // wrapping div
163        if($this->mode != 'xhtml') return;
164        $this->renderer->doc .= '</div>';
165    }
166
167    /**
168     * Displays info about the currently applied filters
169     */
170    protected function renderActiveFilters() {
171        if($this->mode != 'xhtml') return;
172        $dynamic = $this->searchConfig->getDynamicParameters();
173        $filters = $dynamic->getFilters();
174        if(!$filters) return;
175
176        $fltrs = array();
177        foreach($filters as $column => $filter) {
178            list($comp, $value) = $filter;
179
180            // display the filters in a human readable format
181            foreach ($this->columns as $col) {
182                if ($column === $col->getFullQualifiedLabel()) {
183                    $column = $col->getTranslatedLabel();
184                }
185            }
186            $fltrs[] = sprintf('"%s" %s "%s"', $column, $this->helper->getLang("comparator $comp"), $value);
187        }
188
189        $this->renderer->doc .= '<div class="filter">';
190        $this->renderer->doc .= '<h4>' . sprintf($this->helper->getLang('tablefilteredby'), hsc(implode(' & ', $fltrs))) . '</h4>';
191        $this->renderer->doc .= '<div class="resetfilter">';
192        $this->renderer->internallink($this->id, $this->helper->getLang('tableresetfilter'));
193        $this->renderer->doc .= '</div>';
194        $this->renderer->doc .= '</div>';
195    }
196
197    /**
198     * Shows the column headers with links to sort by column
199     */
200    protected function renderColumnHeaders() {
201        $this->renderer->tablerow_open();
202
203        // additional column for row numbers
204        if($this->data['rownumbers']) {
205            $this->renderer->tableheader_open();
206            $this->renderer->cdata('#');
207            $this->renderer->tableheader_close();
208        }
209
210        // show all headers
211        foreach($this->columns as $num => $column) {
212            $header = '';
213            if(isset($this->data['headers'][$num])) {
214                $header = $this->data['headers'][$num];
215            }
216
217            // use field label if no header was set
218            if(blank($header)) {
219                if(is_a($column, 'dokuwiki\plugin\struct\meta\Column')) {
220                    $header = $column->getTranslatedLabel();
221                } else {
222                    $header = 'column ' . $num; // this should never happen
223                }
224            }
225
226            // simple mode first
227            if($this->mode != 'xhtml') {
228                $this->renderer->tableheader_open();
229                $this->renderer->cdata($header);
230                $this->renderer->tableheader_close();
231                continue;
232            }
233
234            // still here? create custom header for more flexibility
235
236            // width setting, widths are prevalidated, no escape needed
237            $width = '';
238            if(isset($this->data['widths'][$num]) && $this->data['widths'][$num] != '-') {
239                $width = ' style="min-width: ' . $this->data['widths'][$num] . ';'.
240                         'max-width: ' . $this->data['widths'][$num] . ';"';
241            }
242
243            // prepare data attribute for inline edits
244            if(!is_a($column, '\dokuwiki\plugin\struct\meta\PageColumn') &&
245                !is_a($column, '\dokuwiki\plugin\struct\meta\RevisionColumn')
246            ) {
247                $data = 'data-field="' . hsc($column->getFullQualifiedLabel()) . '"';
248            } else {
249                $data = '';
250            }
251
252            // sort indicator and link
253            $sortclass = '';
254            $sorts = $this->searchConfig->getSorts();
255            $dynamic = $this->searchConfig->getDynamicParameters();
256            $dynamic->setSort($column, true);
257            if(isset($sorts[$column->getFullQualifiedLabel()])) {
258                list(/*colname*/, $currentSort) = $sorts[$column->getFullQualifiedLabel()];
259                if($currentSort) {
260                    $sortclass = 'sort-down';
261                    $dynamic->setSort($column, false);
262                } else {
263                    $sortclass = 'sort-up';
264                }
265            }
266            $link = wl($this->id, $dynamic->getURLParameters());
267
268            // output XHTML header
269            $this->renderer->doc .= "<th $width $data>";
270            $this->renderer->doc .= '<a href="' . $link . '" class="' . $sortclass . '" title="' . $this->helper->getLang('sort') . '">' . hsc($header) . '</a>';
271            $this->renderer->doc .= '</th>';
272        }
273
274        $this->renderer->tablerow_close();
275    }
276
277    /**
278     * Is the result set currently dynamically filtered?
279     * @return bool
280     */
281    protected function isDynamicallyFiltered() {
282        if($this->mode != 'xhtml') return false;
283        if(!$this->data['dynfilters']) return false;
284
285        $dynamic = $this->searchConfig->getDynamicParameters();
286        return (bool) $dynamic->getFilters();
287    }
288
289    /**
290     * Add input fields for dynamic filtering
291     */
292    protected function renderDynamicFilters() {
293        if($this->mode != 'xhtml') return;
294        if(!$this->data['dynfilters']) return;
295        if (is_a($this->renderer, 'renderer_plugin_dw2pdf')) {
296            return;
297        }
298        global $conf;
299
300        $this->renderer->doc .= '<tr class="dataflt">';
301
302        // add extra column for row numbers
303        if($this->data['rownumbers']) {
304            $this->renderer->doc .= '<th></th>';
305        }
306
307        // each column gets a form
308        foreach($this->columns as $column) {
309            $this->renderer->doc .= '<th>';
310            {
311                $form = new \Doku_Form(array('method' => 'GET', 'action' => wl($this->id)));
312                unset($form->_hidden['sectok']); // we don't need it here
313                if(!$conf['userewrite']) $form->addHidden('id', $this->id);
314
315                // current value
316                $dynamic = $this->searchConfig->getDynamicParameters();
317                $filters = $dynamic->getFilters();
318                if(isset($filters[$column->getFullQualifiedLabel()])) {
319                    list(, $current) = $filters[$column->getFullQualifiedLabel()];
320                    $dynamic->removeFilter($column);
321                } else {
322                    $current = '';
323                }
324
325                // Add current request params
326                $params = $dynamic->getURLParameters();
327                foreach($params as $key => $val) {
328                    $form->addHidden($key, $val);
329                }
330
331                // add input field
332                $key = $column->getFullQualifiedLabel() . $column->getType()->getDefaultComparator();
333                $form->addElement(form_makeField('text', SearchConfigParameters::$PARAM_FILTER . '[' . $key . ']', $current, ''));
334                $this->renderer->doc .= $form->getForm();
335            }
336            $this->renderer->doc .= '</th>';
337        }
338        $this->renderer->doc .= '</tr>';
339
340    }
341
342    /**
343     * Display the actual table data
344     */
345    protected function renderResult() {
346        foreach($this->result as $rownum => $row) {
347            $this->renderResultRow($rownum, $row);
348        }
349    }
350
351    /**
352     * Render a single result row
353     *
354     * @param int $rownum
355     * @param array $row
356     */
357    protected function renderResultRow($rownum, $row) {
358        $this->renderer->tablerow_open();
359
360        // add data attribute for inline edit
361        if($this->mode == 'xhtml') {
362            $pid = $this->resultPIDs[$rownum];
363            $this->renderer->doc = substr(rtrim($this->renderer->doc), 0, -1); // remove closing '>'
364            $this->renderer->doc .= ' data-pid="' . hsc($pid) . '">';
365        }
366
367        // row number column
368        if($this->data['rownumbers']) {
369            $this->renderer->tablecell_open();
370            $searchConfigConf = $this->searchConfig->getConf();
371            $this->renderer->cdata($rownum + $searchConfigConf['offset'] + 1);
372            $this->renderer->tablecell_close();
373        }
374
375        /** @var Value $value */
376        foreach($row as $colnum => $value) {
377            $this->renderer->tablecell_open(1, $this->data['align'][$colnum]);
378            $value->render($this->renderer, $this->mode);
379            $this->renderer->tablecell_close();
380
381            // summarize
382            if($this->data['summarize'] && is_numeric($value->getValue())) {
383                if(!isset($this->sums[$colnum])) {
384                    $this->sums[$colnum] = 0;
385                }
386                $this->sums[$colnum] += $value->getValue();
387            }
388        }
389        $this->renderer->tablerow_close();
390    }
391
392    /**
393     * Renders an information row for when no results were found
394     */
395    protected function renderEmptyResult() {
396        $this->renderer->tablerow_open();
397        $this->renderer->tablecell_open(count($this->columns) + $this->data['rownumbers'], 'center');
398        $this->renderer->cdata($this->helper->getLang('none'));
399        $this->renderer->tablecell_close();
400        $this->renderer->tablerow_close();
401    }
402
403    /**
404     * Add sums if wanted
405     */
406    protected function renderSums() {
407        if(empty($this->data['summarize'])) return;
408
409        $this->renderer->info['struct_table_meta'] = true;
410        if($this->mode == 'xhtml') {
411            /** @noinspection PhpMethodParametersCountMismatchInspection */
412            $this->renderer->tablerow_open('summarize');
413        } else {
414            $this->renderer->tablerow_open();
415        }
416
417        if($this->data['rownumbers']) {
418            $this->renderer->tableheader_open();
419            $this->renderer->tableheader_close();
420        }
421
422        $len = count($this->columns);
423        for($i = 0; $i < $len; $i++) {
424            $this->renderer->tableheader_open(1, $this->data['align'][$i]);
425            if(!empty($this->sums[$i])) {
426                $this->renderer->cdata('∑ ');
427                $this->columns[$i]->getType()->renderValue($this->sums[$i], $this->renderer, $this->mode);
428            } else {
429                if($this->mode == 'xhtml') {
430                    $this->renderer->doc .= '&nbsp;';
431                }
432            }
433            $this->renderer->tableheader_close();
434        }
435        $this->renderer->tablerow_close();
436        $this->renderer->info['struct_table_meta'] = false;
437    }
438
439    /**
440     * Adds paging controls to the table
441     */
442    protected function renderPagingControls() {
443        if(empty($this->data['limit'])) return;
444        if($this->mode != 'xhtml') return;
445
446        $this->renderer->info['struct_table_meta'] = true;
447        $this->renderer->tablerow_open();
448        $this->renderer->tableheader_open((count($this->columns) + ($this->data['rownumbers'] ? 1 : 0)));
449        $offset = $this->data['offset'];
450
451        // prev link
452        if($offset) {
453            $prev = $offset - $this->data['limit'];
454            if($prev < 0) {
455                $prev = 0;
456            }
457
458            $dynamic = $this->searchConfig->getDynamicParameters();
459            $dynamic->setOffset($prev);
460            $link = wl($this->id, $dynamic->getURLParameters());
461            $this->renderer->doc .= '<a href="' . $link . '" class="prev">' . $this->helper->getLang('prev') . '</a>';
462        }
463
464        // next link
465        if($this->resultCount > $offset + $this->data['limit']) {
466            $next = $offset + $this->data['limit'];
467            $dynamic = $this->searchConfig->getDynamicParameters();
468            $dynamic->setOffset($next);
469            $link = wl($this->id, $dynamic->getURLParameters());
470            $this->renderer->doc .= '<a href="' . $link . '" class="next">' . $this->helper->getLang('next') . '</a>';
471        }
472
473        $this->renderer->tableheader_close();
474        $this->renderer->tablerow_close();
475        $this->renderer->info['struct_table_meta'] = true;
476    }
477
478    /**
479     * Adds CSV export controls
480     */
481    protected function renderExportControls() {
482        if($this->mode != 'xhtml') return;
483        if(empty($this->data['csv'])) return;
484        if(!$this->resultCount) return;
485
486        $dynamic = $this->searchConfig->getDynamicParameters();
487        $params = $dynamic->getURLParameters();
488        $params['hash'] = $this->renderer->info['struct_table_hash'];
489
490        // FIXME apply dynamic filters
491        $link = exportlink($this->id, 'struct_csv', $params);
492
493        $this->renderer->doc .= '<a href="' . $link . '" class="export mediafile mf_csv">'.$this->helper->getLang('csvexport').'</a>';
494    }
495}
496