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