xref: /plugin/struct/meta/AggregationTable.php (revision 9cda58056336545eef9b2a7c7f7e7baea996d624)
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        if (is_a($this->renderer, 'renderer_plugin_dw2pdf')) {
284            return;
285        }
286        global $conf;
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        $col = -1;
366        foreach($row as $colnum => $value) {
367            if(isset($this->data['align'][$col++])) {
368                $align = $this->data['align'][$col++];
369            } else {
370                $align = null;
371            }
372
373            $this->renderer->tablecell_open(1, $align);
374            $value->render($this->renderer, $this->mode);
375            $this->renderer->tablecell_close();
376
377            // summarize
378            if($this->data['summarize'] && is_numeric($value->getValue())) {
379                if(!isset($this->sums[$colnum])) {
380                    $this->sums[$colnum] = 0;
381                }
382                $this->sums[$colnum] += $value->getValue();
383            }
384        }
385        $this->renderer->tablerow_close();
386    }
387
388    /**
389     * Renders an information row for when no results were found
390     */
391    protected function renderEmptyResult() {
392        $this->renderer->tablerow_open();
393        $this->renderer->tablecell_open(count($this->columns) + $this->data['rownumbers'], 'center');
394        $this->renderer->cdata($this->helper->getLang('none'));
395        $this->renderer->tablecell_close();
396        $this->renderer->tablerow_close();
397    }
398
399    /**
400     * Add sums if wanted
401     */
402    protected function renderSums() {
403        if(empty($this->data['summarize'])) return;
404
405        $this->renderer->info['struct_table_meta'] = true;
406        $this->renderer->tablerow_open();
407
408        if($this->data['rownumbers']) {
409            $this->renderer->tablecell_open();
410            $this->renderer->tablecell_close();
411        }
412
413        $len = count($this->columns);
414        for($i = 0; $i < $len; $i++) {
415            $this->renderer->tablecell_open(1, $this->data['align'][$i]);
416            if(!empty($this->sums[$i])) {
417                $this->renderer->cdata('∑ ');
418                $this->columns[$i]->getType()->renderValue($this->sums[$i], $this->renderer, $this->mode);
419            } else {
420                if($this->mode == 'xhtml') {
421                    $this->renderer->doc .= '&nbsp;';
422                }
423            }
424            $this->renderer->tablecell_close();
425        }
426        $this->renderer->tablerow_close();
427        $this->renderer->info['struct_table_meta'] = false;
428    }
429
430    /**
431     * Adds paging controls to the table
432     */
433    protected function renderPagingControls() {
434        if(empty($this->data['limit'])) return;
435        if($this->mode != 'xhtml') return;
436
437        $this->renderer->info['struct_table_meta'] = true;
438        $this->renderer->tablerow_open();
439        $this->renderer->tableheader_open((count($this->columns) + ($this->data['rownumbers'] ? 1 : 0)));
440        $offset = $this->data['offset'];
441
442        // prev link
443        if($offset) {
444            $prev = $offset - $this->data['limit'];
445            if($prev < 0) {
446                $prev = 0;
447            }
448
449            $dynamic = $this->searchConfig->getDynamicParameters();
450            $dynamic->setOffset($prev);
451            $link = wl($this->id, $dynamic->getURLParameters());
452            $this->renderer->doc .= '<a href="' . $link . '" class="prev">' . $this->helper->getLang('prev') . '</a>';
453        }
454
455        // next link
456        if($this->resultCount > $offset + $this->data['limit']) {
457            $next = $offset + $this->data['limit'];
458            $dynamic = $this->searchConfig->getDynamicParameters();
459            $dynamic->setOffset($next);
460            $link = wl($this->id, $dynamic->getURLParameters());
461            $this->renderer->doc .= '<a href="' . $link . '" class="next">' . $this->helper->getLang('next') . '</a>';
462        }
463
464        $this->renderer->tableheader_close();
465        $this->renderer->tablerow_close();
466        $this->renderer->info['struct_table_meta'] = true;
467    }
468
469    /**
470     * Adds CSV export controls
471     */
472    protected function renderExportControls() {
473        if($this->mode != 'xhtml') return;
474        if(empty($this->data['csv'])) return;
475        if(!$this->resultCount) return;
476
477        $dynamic = $this->searchConfig->getDynamicParameters();
478        $params = $dynamic->getURLParameters();
479        $params['hash'] = $this->renderer->info['struct_table_hash'];
480
481        // FIXME apply dynamic filters
482        $link = exportlink($this->id, 'struct_csv', $params);
483
484        $this->renderer->doc .= '<a href="' . $link . '" class="export mediafile mf_csv">'.$this->helper->getLang('csvexport').'</a>';
485    }
486}
487