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