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