xref: /plugin/struct/meta/AggregationTable.php (revision 34cffaab96e0c035ff8eca3adbdb149790342062)
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;
284
285        $this->renderer->doc .= '<tr class="dataflt">';
286
287        // add extra column for row numbers
288        if($this->data['rownumbers']) {
289            $this->renderer->doc .= '<th></th>';
290        }
291
292        // each column gets a form
293        foreach($this->columns as $column) {
294            $this->renderer->doc .= '<th>';
295            {
296                $form = new \Doku_Form(array('method' => 'GET', 'action' => wl($this->id)));
297                unset($form->_hidden['sectok']); // we don't need it here
298                if(!$conf['userewrite']) $form->addHidden('id', $this->id);
299
300                // current value
301                $dynamic = $this->searchConfig->getDynamicParameters();
302                $filters = $dynamic->getFilters();
303                if(isset($filters[$column->getFullQualifiedLabel()])) {
304                    list(, $current) = $filters[$column->getFullQualifiedLabel()];
305                    $dynamic->removeFilter($column);
306                } else {
307                    $current = '';
308                }
309
310                // Add current request params
311                $params = $dynamic->getURLParameters();
312                foreach($params as $key => $val) {
313                    $form->addHidden($key, $val);
314                }
315
316                // add input field
317                $key = $column->getFullQualifiedLabel() . '*~';
318                $form->addElement(form_makeField('text', SearchConfigParameters::$PARAM_FILTER . '[' . $key . ']', $current, ''));
319                $this->renderer->doc .= $form->getForm();
320            }
321            $this->renderer->doc .= '</th>';
322        }
323        $this->renderer->doc .= '</tr>';
324
325    }
326
327    /**
328     * Display the actual table data
329     */
330    protected function renderResult() {
331        $this->renderer->tabletbody_open();
332        foreach($this->result as $rownum => $row) {
333            $this->renderResultRow($rownum, $row);
334        }
335        $this->renderer->tabletbody_close();
336    }
337
338    /**
339     * Render a single result row
340     *
341     * @param int $rownum
342     * @param array $row
343     */
344    protected function renderResultRow($rownum, $row) {
345        $this->renderer->tablerow_open();
346
347        // add data attribute for inline edit
348        if($this->mode == 'xhtml') {
349            $pid = $this->resultPIDs[$rownum];
350            $this->renderer->doc = substr(rtrim($this->renderer->doc), 0, -1); // remove closing '>'
351            $this->renderer->doc .= ' data-pid="' . hsc($pid) . '">';
352        }
353
354        // row number column
355        if($this->data['rownumbers']) {
356            $this->renderer->tablecell_open();
357            $this->renderer->cdata($rownum + 1);
358            $this->renderer->tablecell_close();
359        }
360
361        /** @var Value $value */
362        foreach($row as $colnum => $value) {
363            $this->renderer->tablecell_open();
364            $value->render($this->renderer, $this->mode);
365            $this->renderer->tablecell_close();
366
367            // summarize
368            if($this->data['summarize'] && is_numeric($value->getValue())) {
369                if(!isset($this->sums[$colnum])) {
370                    $this->sums[$colnum] = 0;
371                }
372                $this->sums[$colnum] += $value->getValue();
373            }
374        }
375        $this->renderer->tablerow_close();
376    }
377
378    /**
379     * Renders an information row for when no results were found
380     */
381    protected function renderEmptyResult() {
382        $this->renderer->tablerow_open();
383        $this->renderer->tablecell_open(count($this->columns) + $this->data['rownumbers'], 'center');
384        $this->renderer->cdata($this->helper->getLang('none'));
385        $this->renderer->tablecell_close();
386        $this->renderer->tablerow_close();
387    }
388
389    /**
390     * Add sums if wanted
391     */
392    protected function renderSums() {
393        if(empty($this->data['summarize'])) return;
394
395        $this->renderer->info['struct_table_meta'] = true;
396        $this->renderer->tablerow_open();
397
398        if($this->data['rownumbers']) {
399            $this->renderer->tablecell_open();
400            $this->renderer->tablecell_close();
401        }
402
403        $len = count($this->columns);
404        for($i = 0; $i < $len; $i++) {
405            $this->renderer->tablecell_open(1, $this->data['align'][$i]);
406            if(!empty($this->sums[$i])) {
407                $this->renderer->cdata('∑ ');
408                $this->columns[$i]->getType()->renderValue($this->sums[$i], $this->renderer, $this->mode);
409            } else {
410                if($this->mode == 'xhtml') {
411                    $this->renderer->doc .= '&nbsp;';
412                }
413            }
414            $this->renderer->tablecell_close();
415        }
416        $this->renderer->tablerow_close();
417        $this->renderer->info['struct_table_meta'] = false;
418    }
419
420    /**
421     * Adds paging controls to the table
422     */
423    protected function renderPagingControls() {
424        if(empty($this->data['limit'])) return;
425        if($this->mode != 'xhtml') return;
426
427        $this->renderer->info['struct_table_meta'] = true;
428        $this->renderer->tablerow_open();
429        $this->renderer->tableheader_open((count($this->data['cols']) + ($this->data['rownumbers'] ? 1 : 0)));
430        $offset = $this->data['offset'];
431
432        // prev link
433        if($offset) {
434            $prev = $offset - $this->data['limit'];
435            if($prev < 0) {
436                $prev = 0;
437            }
438
439            $dynamic = $this->searchConfig->getDynamicParameters();
440            $dynamic->setOffset($prev);
441            $link = wl($this->id, $dynamic->getURLParameters());
442            $this->renderer->doc .= '<a href="' . $link . '" class="prev">' . $this->helper->getLang('prev') . '</a>';
443        }
444
445        // next link
446        if($this->resultCount > $offset + $this->data['limit']) {
447            $next = $offset + $this->data['limit'];
448            $dynamic = $this->searchConfig->getDynamicParameters();
449            $dynamic->setOffset($next);
450            $link = wl($this->id, $dynamic->getURLParameters());
451            $this->renderer->doc .= '<a href="' . $link . '" class="next">' . $this->helper->getLang('next') . '</a>';
452        }
453
454        $this->renderer->tableheader_close();
455        $this->renderer->tablerow_close();
456        $this->renderer->info['struct_table_meta'] = true;
457    }
458
459    /**
460     * Adds CSV export controls
461     */
462    protected function renderExportControls() {
463        if($this->mode != 'xhtml') return;
464        if(empty($this->data['csv'])) return;
465        if(!$this->resultCount) return;
466
467        $dynamic = $this->searchConfig->getDynamicParameters();
468        $params = $dynamic->getURLParameters();
469        $params['hash'] = $this->renderer->info['struct_table_hash'];
470
471        // FIXME apply dynamic filters
472        $link = exportlink($this->id, 'struct_csv', $params);
473
474        $this->renderer->doc .= '<a href="' . $link . '" class="export mediafile mf_csv">'.$this->helper->getLang('csvexport').'</a>';
475    }
476}
477