xref: /plugin/struct/meta/AggregationTable.php (revision 61356325e2c5dbdcb8405fa2eb4c34732d79b65f)
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    /**
14     * @var string the page id of the page this is rendered to
15     */
16    protected $id;
17    /**
18     * @var string the Type of renderer used
19     */
20    protected $mode;
21    /**
22     * @var \Doku_Renderer the DokuWiki renderer used to create the output
23     */
24    protected $renderer;
25    /**
26     * @var SearchConfig the configured search - gives access to columns etc.
27     */
28    protected $searchConfig;
29
30    /**
31     * @var Column[] the list of columns to be displayed
32     */
33    protected $columns;
34
35    /**
36     * @var  Value[][] the search result
37     */
38    protected $result;
39
40    /**
41     * @var int number of all results
42     */
43    protected $resultCount;
44
45    /**
46     * @var string[] the result PIDs for each row
47     */
48    protected $resultPIDs;
49    protected $resultRids;
50    protected $resultRevs;
51
52    /**
53     * @var array for summing up columns
54     */
55    protected $sums;
56
57    /**
58     * @var bool skip full table when no results found
59     */
60    protected $simplenone = true;
61
62    /**
63     * @todo we might be able to get rid of this helper and move this to SearchConfig
64     * @var \helper_plugin_struct_config
65     */
66    protected $helper;
67
68    /**
69     * Initialize the Aggregation renderer and executes the search
70     *
71     * You need to call @see render() on the resulting object.
72     *
73     * @param string $id
74     * @param string $mode
75     * @param \Doku_Renderer $renderer
76     * @param SearchConfig $searchConfig
77     */
78    public function __construct($id, $mode, \Doku_Renderer $renderer, SearchConfig $searchConfig, $idColumn)
79    {
80        $this->id = $id;
81        $this->mode = $mode;
82        $this->renderer = $renderer;
83        $this->searchConfig = $searchConfig;
84        $this->data = $searchConfig->getConf();
85        $this->columns = $searchConfig->getColumns();
86
87        // FIXME detect or get real columnId
88        // for now rid is OK for page data because tables are also joined on rev
89        $this->result = $this->searchConfig->execute($idColumn);
90        $this->resultCount = $this->searchConfig->getCount();
91        $this->resultPIDs = $this->searchConfig->getPids();
92        $this->resultRids = $this->searchConfig->getRids();
93        $this->resultRevs = $this->searchConfig->getRevs();
94        $this->helper = plugin_load('helper', 'struct_config');
95    }
96
97    /**
98     * Create the table on the renderer
99     */
100    public function render()
101    {
102
103        // abort early if there are no results at all (not filtered)
104        if (!$this->resultCount && !$this->isDynamicallyFiltered() && $this->simplenone) {
105            $this->startScope();
106            $this->renderer->cdata($this->helper->getLang('none'));
107            $this->finishScope();
108            return;
109        }
110
111        // table open
112        $this->startScope();
113        $this->renderActiveFilters();
114        $this->renderer->table_open();
115
116        // header
117        $this->renderer->tablethead_open();
118        $this->renderColumnHeaders();
119        $this->renderDynamicFilters();
120        $this->renderer->tablethead_close();
121
122        if ($this->resultCount) {
123            // actual data
124            $this->renderer->tabletbody_open();
125            $this->renderResult();
126            $this->renderer->tabletbody_close();
127
128            // footer (tfoot is develonly currently)
129            if (method_exists($this->renderer, 'tabletfoot_open')) $this->renderer->tabletfoot_open();
130            $this->renderSums();
131            $this->renderPagingControls();
132            if (method_exists($this->renderer, 'tabletfoot_close')) $this->renderer->tabletfoot_close();
133        } else {
134            // nothing found
135            $this->renderEmptyResult();
136        }
137
138        // table close
139        $this->renderer->table_close();
140
141        // export handle
142        $this->renderExportControls();
143        $this->finishScope();
144    }
145
146    /**
147     * Adds additional info to document and renderer in XHTML mode
148     *
149     * @see finishScope()
150     */
151    protected function startScope()
152    {
153        // unique identifier for this aggregation
154        $this->renderer->info['struct_table_hash'] = md5(var_export($this->data, true));
155
156        // wrapping div
157        if ($this->mode != 'xhtml') return;
158        $this->renderer->doc .= "<div class=\"structaggregation\">";
159    }
160
161    /**
162     * Closes the table and anything opened in startScope()
163     *
164     * @see startScope()
165     */
166    protected function finishScope()
167    {
168        // remove identifier from renderer again
169        if (isset($this->renderer->info['struct_table_hash'])) {
170            unset($this->renderer->info['struct_table_hash']);
171        }
172
173        // wrapping div
174        if ($this->mode != 'xhtml') return;
175        $this->renderer->doc .= '</div>';
176    }
177
178    /**
179     * Displays info about the currently applied filters
180     */
181    protected function renderActiveFilters()
182    {
183        if ($this->mode != 'xhtml') return;
184        $dynamic = $this->searchConfig->getDynamicParameters();
185        $filters = $dynamic->getFilters();
186        if (!$filters) return;
187
188        $fltrs = array();
189        foreach ($filters as $column => $filter) {
190            list($comp, $value) = $filter;
191
192            // display the filters in a human readable format
193            foreach ($this->columns as $col) {
194                if ($column === $col->getFullQualifiedLabel()) {
195                    $column = $col->getTranslatedLabel();
196                }
197            }
198            $fltrs[] = sprintf('"%s" %s "%s"', $column, $this->helper->getLang("comparator $comp"), $value);
199        }
200
201        $this->renderer->doc .= '<div class="filter">';
202        $this->renderer->doc .= '<h4>' . sprintf($this->helper->getLang('tablefilteredby'), hsc(implode(' & ', $fltrs))) . '</h4>';
203        $this->renderer->doc .= '<div class="resetfilter">';
204        $this->renderer->internallink($this->id, $this->helper->getLang('tableresetfilter'));
205        $this->renderer->doc .= '</div>';
206        $this->renderer->doc .= '</div>';
207    }
208
209    /**
210     * Shows the column headers with links to sort by column
211     */
212    protected function renderColumnHeaders()
213    {
214        $this->renderer->tablerow_open();
215
216        // additional column for row numbers
217        if ($this->data['rownumbers']) {
218            $this->renderer->tableheader_open();
219            $this->renderer->cdata('#');
220            $this->renderer->tableheader_close();
221        }
222
223        // show all headers
224        foreach ($this->columns as $num => $column) {
225            $header = '';
226            if (isset($this->data['headers'][$num])) {
227                $header = $this->data['headers'][$num];
228            }
229
230            // use field label if no header was set
231            if (blank($header)) {
232                if (is_a($column, 'dokuwiki\plugin\struct\meta\Column')) {
233                    $header = $column->getTranslatedLabel();
234                } else {
235                    $header = 'column ' . $num; // this should never happen
236                }
237            }
238
239            // simple mode first
240            if ($this->mode != 'xhtml') {
241                $this->renderer->tableheader_open();
242                $this->renderer->cdata($header);
243                $this->renderer->tableheader_close();
244                continue;
245            }
246
247            // still here? create custom header for more flexibility
248
249            // width setting, widths are prevalidated, no escape needed
250            $width = '';
251            if (isset($this->data['widths'][$num]) && $this->data['widths'][$num] != '-') {
252                $width = ' style="min-width: ' . $this->data['widths'][$num] . ';' .
253                         'max-width: ' . $this->data['widths'][$num] . ';"';
254            }
255
256            // prepare data attribute for inline edits
257            if (
258                !is_a($column, '\dokuwiki\plugin\struct\meta\PageColumn') &&
259                !is_a($column, '\dokuwiki\plugin\struct\meta\RevisionColumn')
260            ) {
261                $data = 'data-field="' . hsc($column->getFullQualifiedLabel()) . '"';
262            } else {
263                $data = '';
264            }
265
266            // sort indicator and link
267            $sortclass = '';
268            $sorts = $this->searchConfig->getSorts();
269            $dynamic = $this->searchConfig->getDynamicParameters();
270            $dynamic->setSort($column, true);
271            if (isset($sorts[$column->getFullQualifiedLabel()])) {
272                list(/*colname*/, $currentSort) = $sorts[$column->getFullQualifiedLabel()];
273                if ($currentSort) {
274                    $sortclass = 'sort-down';
275                    $dynamic->setSort($column, false);
276                } else {
277                    $sortclass = 'sort-up';
278                }
279            }
280            $link = wl($this->id, $dynamic->getURLParameters());
281
282            // output XHTML header
283            $this->renderer->doc .= "<th $width $data>";
284            $this->renderer->doc .= '<a href="' . $link . '" class="' . $sortclass . '" title="' . $this->helper->getLang('sort') . '">' . hsc($header) . '</a>';
285            $this->renderer->doc .= '</th>';
286        }
287
288        $this->renderer->tablerow_close();
289    }
290
291    /**
292     * Is the result set currently dynamically filtered?
293     * @return bool
294     */
295    protected function isDynamicallyFiltered()
296    {
297        if ($this->mode != 'xhtml') return false;
298        if (!$this->data['dynfilters']) return false;
299
300        $dynamic = $this->searchConfig->getDynamicParameters();
301        return (bool) $dynamic->getFilters();
302    }
303
304    /**
305     * Add input fields for dynamic filtering
306     */
307    protected function renderDynamicFilters()
308    {
309        if ($this->mode != 'xhtml') return;
310        if (!$this->data['dynfilters']) return;
311        if (is_a($this->renderer, 'renderer_plugin_dw2pdf')) {
312            return;
313        }
314        global $conf;
315
316        $this->renderer->doc .= '<tr class="dataflt">';
317
318        // add extra column for row numbers
319        if ($this->data['rownumbers']) {
320            $this->renderer->doc .= '<th></th>';
321        }
322
323        // each column gets a form
324        foreach ($this->columns as $column) {
325            $this->renderer->doc .= '<th>';
326            {
327                $form = new \Doku_Form(array('method' => 'GET', 'action' => wl($this->id)));
328                unset($form->_hidden['sectok']); // we don't need it here
329                if (!$conf['userewrite']) $form->addHidden('id', $this->id);
330
331                // current value
332                $dynamic = $this->searchConfig->getDynamicParameters();
333                $filters = $dynamic->getFilters();
334            if (isset($filters[$column->getFullQualifiedLabel()])) {
335                list(, $current) = $filters[$column->getFullQualifiedLabel()];
336                $dynamic->removeFilter($column);
337            } else {
338                $current = '';
339            }
340
341                // Add current request params
342                $params = $dynamic->getURLParameters();
343            foreach ($params as $key => $val) {
344                $form->addHidden($key, $val);
345            }
346
347                // add input field
348                $key = $column->getFullQualifiedLabel() . $column->getType()->getDefaultComparator();
349                $form->addElement(form_makeField('text', SearchConfigParameters::$PARAM_FILTER . '[' . $key . ']', $current, ''));
350                $this->renderer->doc .= $form->getForm();
351            }
352            $this->renderer->doc .= '</th>';
353        }
354        $this->renderer->doc .= '</tr>';
355    }
356
357    /**
358     * Display the actual table data
359     */
360    protected function renderResult()
361    {
362        foreach ($this->result as $rownum => $row) {
363            $data = array(
364                'id' => $this->id,
365                'mode' => $this->mode,
366                'renderer' => $this->renderer,
367                'searchConfig' => $this->searchConfig,
368                'data' => $this->data,
369                'rownum' => &$rownum,
370                'row' => &$row,
371            );
372            $evt = new \Doku_Event('PLUGIN_STRUCT_AGGREGATIONTABLE_RENDERRESULTROW', $data);
373            if ($evt->advise_before()) {
374                $this->renderResultRow($rownum, $row);
375            }
376            $evt->advise_after();
377        }
378    }
379
380    /**
381     * Render a single result row
382     *
383     * @param int $rownum
384     * @param array $row
385     */
386    protected function renderResultRow($rownum, $row)
387    {
388        $this->renderer->tablerow_open();
389
390        // add data attribute for inline edit
391        if ($this->mode == 'xhtml') {
392            $pid = $this->resultPIDs[$rownum];
393            $rid = $this->resultRids[$rownum];
394            $rev = $this->resultRevs[$rownum];
395            $this->renderer->doc = substr(rtrim($this->renderer->doc), 0, -1); // remove closing '>'
396            $this->renderer->doc .= ' data-pid="' . hsc($pid) . '" data-rev="' . $rev . '" data-rid="' . $rid . '">';
397        }
398
399        // row number column
400        if ($this->data['rownumbers']) {
401            $this->renderer->tablecell_open();
402            $searchConfigConf = $this->searchConfig->getConf();
403            $this->renderer->cdata($rownum + $searchConfigConf['offset'] + 1);
404            $this->renderer->tablecell_close();
405        }
406
407        /** @var Value $value */
408        foreach ($row as $colnum => $value) {
409            $this->renderer->tablecell_open(1, $this->data['align'][$colnum]);
410            $value->render($this->renderer, $this->mode);
411            $this->renderer->tablecell_close();
412
413            // summarize
414            if ($this->data['summarize'] && is_numeric($value->getValue())) {
415                if (!isset($this->sums[$colnum])) {
416                    $this->sums[$colnum] = 0;
417                }
418                $this->sums[$colnum] += $value->getValue();
419            }
420        }
421        $this->renderer->tablerow_close();
422    }
423
424    /**
425     * Renders an information row for when no results were found
426     */
427    protected function renderEmptyResult()
428    {
429        $this->renderer->tablerow_open();
430        $this->renderer->tablecell_open(count($this->columns) + $this->data['rownumbers'], 'center');
431        $this->renderer->cdata($this->helper->getLang('none'));
432        $this->renderer->tablecell_close();
433        $this->renderer->tablerow_close();
434    }
435
436    /**
437     * Add sums if wanted
438     */
439    protected function renderSums()
440    {
441        if (empty($this->data['summarize'])) return;
442
443        $this->renderer->info['struct_table_meta'] = true;
444        if ($this->mode == 'xhtml') {
445            /** @noinspection PhpMethodParametersCountMismatchInspection */
446            $this->renderer->tablerow_open('summarize');
447        } else {
448            $this->renderer->tablerow_open();
449        }
450
451        if ($this->data['rownumbers']) {
452            $this->renderer->tableheader_open();
453            $this->renderer->tableheader_close();
454        }
455
456        $len = count($this->columns);
457        for ($i = 0; $i < $len; $i++) {
458            $this->renderer->tableheader_open(1, $this->data['align'][$i]);
459            if (!empty($this->sums[$i])) {
460                $this->renderer->cdata('∑ ');
461                $this->columns[$i]->getType()->renderValue($this->sums[$i], $this->renderer, $this->mode);
462            } else {
463                if ($this->mode == 'xhtml') {
464                    $this->renderer->doc .= '&nbsp;';
465                }
466            }
467            $this->renderer->tableheader_close();
468        }
469        $this->renderer->tablerow_close();
470        $this->renderer->info['struct_table_meta'] = false;
471    }
472
473    /**
474     * Adds paging controls to the table
475     */
476    protected function renderPagingControls()
477    {
478        if (empty($this->data['limit'])) return;
479        if ($this->mode != 'xhtml') return;
480
481        $this->renderer->info['struct_table_meta'] = true;
482        $this->renderer->tablerow_open();
483        $this->renderer->tableheader_open((count($this->columns) + ($this->data['rownumbers'] ? 1 : 0)));
484        $offset = $this->data['offset'];
485
486        // prev link
487        if ($offset) {
488            $prev = $offset - $this->data['limit'];
489            if ($prev < 0) {
490                $prev = 0;
491            }
492
493            $dynamic = $this->searchConfig->getDynamicParameters();
494            $dynamic->setOffset($prev);
495            $link = wl($this->id, $dynamic->getURLParameters());
496            $this->renderer->doc .= '<a href="' . $link . '" class="prev">' . $this->helper->getLang('prev') . '</a>';
497        }
498
499        // next link
500        if ($this->resultCount > $offset + $this->data['limit']) {
501            $next = $offset + $this->data['limit'];
502            $dynamic = $this->searchConfig->getDynamicParameters();
503            $dynamic->setOffset($next);
504            $link = wl($this->id, $dynamic->getURLParameters());
505            $this->renderer->doc .= '<a href="' . $link . '" class="next">' . $this->helper->getLang('next') . '</a>';
506        }
507
508        $this->renderer->tableheader_close();
509        $this->renderer->tablerow_close();
510        $this->renderer->info['struct_table_meta'] = true;
511    }
512
513    /**
514     * Adds CSV export controls
515     */
516    protected function renderExportControls()
517    {
518        if ($this->mode != 'xhtml') return;
519        if (empty($this->data['csv'])) return;
520        if (!$this->resultCount) return;
521
522        $dynamic = $this->searchConfig->getDynamicParameters();
523        $params = $dynamic->getURLParameters();
524        $params['hash'] = $this->renderer->info['struct_table_hash'];
525
526        // FIXME apply dynamic filters
527        $link = exportlink($this->id, 'struct_csv', $params);
528
529        $this->renderer->doc .= '<a href="' . $link . '" class="export mediafile mf_csv">' . $this->helper->getLang('csvexport') . '</a>';
530    }
531}
532