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