xref: /plugin/struct/meta/AggregationTable.php (revision 4e7c197c54680a0baeda39ea66a502b5b5255c5c)
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     * @todo we might be able to get rid of this helper and move this to SearchConfig
56     * @var \helper_plugin_struct_config
57     */
58    protected $helper;
59
60    /**
61     * Initialize the Aggregation renderer and executes the search
62     *
63     * You need to call @see render() on the resulting object.
64     *
65     * @param string $id
66     * @param string $mode
67     * @param \Doku_Renderer $renderer
68     * @param SearchConfig $searchConfig
69     */
70    public function __construct($id, $mode, \Doku_Renderer $renderer, SearchConfig $searchConfig) {
71        $this->id = $id;
72        $this->mode = $mode;
73        $this->renderer = $renderer;
74        $this->searchConfig = $searchConfig;
75        $this->data = $searchConfig->getConf();
76        $this->columns = $searchConfig->getColumns();
77
78        $this->result = $this->searchConfig->execute();
79        $this->resultCount = $this->searchConfig->getCount();
80        $this->resultPIDs = $this->searchConfig->getPids();
81        $this->helper = plugin_load('helper', 'struct_config');
82    }
83
84    /**
85     * Create the table on the renderer
86     */
87    public function render() {
88
89        // abort early if there are no results at all (not filtered)
90        if(!$this->resultCount && !$this->isDynamicallyFiltered()) {
91            $this->startScope();
92            $this->renderer->cdata($this->helper->getLang('none'));
93            $this->finishScope();
94            return;
95        }
96
97        // table open
98        $this->startScope();
99        $this->renderActiveFilters();
100        $this->renderer->table_open();
101
102        // header
103        $this->renderer->tablethead_open();
104        $this->renderColumnHeaders();
105        $this->renderDynamicFilters();
106        $this->renderer->tablethead_close();
107
108        if($this->resultCount) {
109            // actual data
110            $this->renderResult();
111
112            // footer
113            $this->renderSums();
114            $this->renderPagingControls();
115        } else {
116            // nothing found
117            $this->renderEmptyResult();
118        }
119
120        // table close
121        $this->renderer->table_close();
122        $this->finishScope();
123    }
124
125    /**
126     * Adds additional info to document and renderer in XHTML mode
127     *
128     * @see finishScope()
129     */
130    protected function startScope() {
131        if($this->mode != 'xhtml') return;
132
133        // wrapping div
134        $this->renderer->doc .= "<div class=\"structaggregation\">";
135
136        // unique identifier for this aggregation
137        $this->renderer->info['struct_table_hash'] = md5(var_export($this->data, true));
138    }
139
140    /**
141     * Closes the table and anything opened in startScope()
142     *
143     * @see startScope()
144     */
145    protected function finishScope() {
146        if($this->mode != 'xhtml') return;
147
148        // wrapping div
149        $this->renderer->doc .= '</div>';
150
151        // remove identifier from renderer again
152        if(isset($this->renderer->info['struct_table_hash'])) {
153            unset($this->renderer->info['struct_table_hash']);
154        }
155    }
156
157    /**
158     * Displays info about the currently applied filters
159     */
160    protected function renderActiveFilters() {
161        if($this->mode != 'xhtml') return;
162        $dynamic = $this->searchConfig->getDynamicParameters();
163        $filters = $dynamic->getFilters();
164        if(!$filters) return;
165
166        $fltrs = array();
167        foreach($filters as $column => $filter) {
168            list($comp, $value) = $filter;
169            $fltrs[] = $column . ' ' . $comp . ' ' . $value;
170        }
171
172        $this->renderer->doc .= '<div class="filter">';
173        $this->renderer->doc .= '<h4>' . sprintf($this->helper->getLang('tablefilteredby'), hsc(implode(' & ', $fltrs))) . '</h4>';
174        $this->renderer->doc .= '<div class="resetfilter">';
175        $this->renderer->internallink($this->id, $this->helper->getLang('tableresetfilter'));
176        $this->renderer->doc .= '</div>';
177        $this->renderer->doc .= '</div>';
178    }
179
180    /**
181     * Shows the column headers with links to sort by column
182     */
183    protected function renderColumnHeaders() {
184        $this->renderer->tablerow_open();
185
186        // additional column for row numbers
187        if($this->data['rownumbers']) {
188            $this->renderer->tableheader_open();
189            $this->renderer->cdata('#');
190            $this->renderer->tableheader_close();
191        }
192
193        // show all headers
194        foreach($this->columns as $num => $column) {
195            $header = '';
196            if(isset($this->data['headers'][$num])) {
197                $header = $this->data['headers'][$num];
198            }
199
200            // use field label if no header was set
201            if(blank($header)) {
202                if(is_a($column, 'dokuwiki\plugin\struct\meta\Column')) {
203                    $header = $column->getTranslatedLabel();
204                } else {
205                    $header = 'column ' . $num; // this should never happen
206                }
207            }
208
209            // simple mode first
210            if($this->mode != 'xhtml') {
211                $this->renderer->tableheader_open();
212                $this->renderer->cdata($header);
213                $this->renderer->tableheader_close();
214                continue;
215            }
216
217            // still here? create custom header for more flexibility
218
219            // width setting
220            $width = '';
221            if(isset($data['widths'][$num]) && $data['widths'][$num] != '-') {
222                $width = ' style="width: ' . $data['widths'][$num] . ';"'; // widths are prevalidated, no escape needed
223            }
224
225            // prepare data attribute for inline edits
226            if(!is_a($column, '\dokuwiki\plugin\struct\meta\PageColumn') &&
227                !is_a($column, '\dokuwiki\plugin\struct\meta\RevisionColumn')
228            ) {
229                $data = 'data-field="' . hsc($column->getFullQualifiedLabel()) . '"';
230            } else {
231                $data = '';
232            }
233
234            // sort indicator and link
235            $sortclass = '';
236            $sorts = $this->searchConfig->getSorts();
237            $dynamic = $this->searchConfig->getDynamicParameters();
238            $dynamic->setSort($column, true);
239            if(isset($sorts[$column->getFullQualifiedLabel()])) {
240                list(/*colname*/, $currentSort) = $sorts[$column->getFullQualifiedLabel()];
241                if($currentSort) {
242                    $sortclass = 'sort-down';
243                    $dynamic->setSort($column, false);
244                } else {
245                    $sortclass = 'sort-up';
246                }
247            }
248            $link = wl($this->id, $dynamic->getURLParameters());
249
250            // output XHTML header
251            $this->renderer->doc .= "<th $width $data>";
252            $this->renderer->doc .= '<a href="' . $link . '" class="' . $sortclass . '" title="' . $this->helper->getLang('sort') . '">' . hsc($header) . '</a>';
253            $this->renderer->doc .= '</th>';
254        }
255
256        $this->renderer->tablerow_close();
257    }
258
259    /**
260     * Is the result set currently dynamically filtered?
261     * @return bool
262     */
263    protected function isDynamicallyFiltered() {
264        if($this->mode != 'xhtml') return false;
265        if(!$this->data['dynfilters']) return false;
266
267        $dynamic = $this->searchConfig->getDynamicParameters();
268        return (bool) $dynamic->getFilters();
269    }
270
271    /**
272     * Add input fields for dynamic filtering
273     */
274    protected function renderDynamicFilters() {
275        if($this->mode != 'xhtml') return;
276        if(!$this->data['dynfilters']) return;
277        global $conf;
278
279        $this->renderer->doc .= '<tr class="dataflt">';
280
281        // add extra column for row numbers
282        if($this->data['rownumbers']) {
283            $this->renderer->doc .= '<th></th>';
284        }
285
286        // each column gets a form
287        foreach($this->columns as $column) {
288            $this->renderer->doc .= '<th>';
289            {
290                $form = new \Doku_Form(array('method' => 'GET', 'action' => wl($this->id)));
291                unset($form->_hidden['sectok']); // we don't need it here
292                if(!$conf['userewrite']) $form->addHidden('id', $this->id);
293
294                // current value
295                $dynamic = $this->searchConfig->getDynamicParameters();
296                $filters = $dynamic->getFilters();
297                if(isset($filters[$column->getFullQualifiedLabel()])) {
298                    list(, $current) = $filters[$column->getFullQualifiedLabel()];
299                    $dynamic->removeFilter($column);
300                } else {
301                    $current = '';
302                }
303
304                // Add current request params
305                $params = $dynamic->getURLParameters();
306                foreach($params as $key => $val) {
307                    $form->addHidden($key, $val);
308                }
309
310                // add input field
311                $key = $column->getFullQualifiedLabel() . '*~';
312                $form->addElement(form_makeField('text', SearchConfigParameters::$PARAM_FILTER . '[' . $key . ']', $current, ''));
313                $this->renderer->doc .= $form->getForm();
314            }
315            $this->renderer->doc .= '</th>';
316        }
317        $this->renderer->doc .= '</tr>';
318
319    }
320
321    /**
322     * Display the actual table data
323     */
324    protected function renderResult() {
325        $this->renderer->tabletbody_open();
326        foreach($this->result as $rownum => $row) {
327            $this->renderer->tablerow_open();
328
329            // add data attribute for inline edit
330            if($this->mode == 'xhtml') {
331                $pid = $this->resultPIDs[$rownum];
332                $this->renderer->doc = substr(rtrim($this->renderer->doc), 0, -1); // remove closing '>'
333                $this->renderer->doc .= ' data-pid="' . hsc($pid) . '">';
334            }
335
336            // row number column
337            if($this->data['rownumbers']) {
338                $this->renderer->tablecell_open();
339                $this->renderer->doc .= $rownum + 1;
340                $this->renderer->tablecell_close();
341            }
342
343            /** @var Value $value */
344            foreach($row as $colnum => $value) {
345                $this->renderer->tablecell_open();
346                $value->render($this->renderer, $this->mode);
347                $this->renderer->tablecell_close();
348
349                // summarize
350                if($this->data['summarize'] && is_numeric($value->getValue())) {
351                    if(!isset($this->sums[$colnum])) {
352                        $this->sums[$colnum] = 0;
353                    }
354                    $this->sums[$colnum] += $value->getValue();
355                }
356            }
357            $this->renderer->tablerow_close();
358        }
359        $this->renderer->tabletbody_close();
360    }
361
362    /**
363     * Renders an information row for when no results were found
364     */
365    protected function renderEmptyResult() {
366        $this->renderer->tablerow_open();
367        $this->renderer->tablecell_open(count($this->data['cols']) + $this->data['rownumbers'], 'center');
368        $this->renderer->cdata($this->helper->getLang('none'));
369        $this->renderer->tablecell_close();
370        $this->renderer->tablerow_close();
371    }
372
373    /**
374     * Add sums if wanted
375     */
376    protected function renderSums() {
377        if(empty($this->data['summarize'])) return;
378
379        $this->renderer->tablerow_open();
380
381        if($this->data['rownumbers']) {
382            $this->renderer->tablecell_open();
383            $this->renderer->tablecell_close();
384        }
385
386        $len = count($this->columns);
387        for($i = 0; $i < $len; $i++) {
388            $this->renderer->tablecell_open(1, $this->data['align'][$i]);
389            if(!empty($this->sums[$i])) {
390                $this->renderer->cdata('∑ ');
391                $this->columns[$i]->getType()->renderValue($this->sums[$i], $this->renderer, $this->mode);
392            } else {
393                if($this->mode == 'xhtml') {
394                    $this->renderer->doc .= '&nbsp;';
395                }
396            }
397            $this->renderer->tablecell_close();
398        }
399        $this->renderer->tablerow_close();
400    }
401
402    /**
403     * Adds paging controls to the table
404     */
405    protected function renderPagingControls() {
406        if(empty($this->data['limit'])) return;
407        if($this->mode != 'xhtml') ;
408
409        $this->renderer->tablerow_open();
410        $this->renderer->tableheader_open((count($this->data['cols']) + ($this->data['rownumbers'] ? 1 : 0)));
411        $offset = $this->data['offset'];
412
413        // prev link
414        if($offset) {
415            $prev = $offset - $this->data['limit'];
416            if($prev < 0) {
417                $prev = 0;
418            }
419
420            $dynamic = $this->searchConfig->getDynamicParameters();
421            $dynamic->setOffset($prev);
422            $link = wl($this->id, $dynamic->getURLParameters());
423            $this->renderer->doc .= '<a href="' . $link . '" class="prev">' . $this->helper->getLang('prev') . '</a>';
424        }
425
426        // next link
427        if($this->resultCount > $offset + $this->data['limit']) {
428            $next = $offset + $this->data['limit'];
429            $dynamic = $this->searchConfig->getDynamicParameters();
430            $dynamic->setOffset($next);
431            $link = wl($this->id, $dynamic->getURLParameters());
432            $this->renderer->doc .= '<a href="' . $link . '" class="next">' . $this->helper->getLang('next') . '</a>';
433        }
434
435        $this->renderer->tableheader_close();
436        $this->renderer->tablerow_close();
437    }
438}
439