1<?php
2
3use dokuwiki\Form\Form;
4
5/**
6 * Tagging Plugin (hlper component)
7 *
8 * @license GPL 2
9 */
10class helper_plugin_tagging extends DokuWiki_Plugin {
11
12    /**
13     * Gives access to the database
14     *
15     * Initializes the SQLite helper and register the CLEANTAG function
16     *
17     * @return helper_plugin_sqlite|bool false if initialization fails
18     */
19    public function getDB() {
20        static $db = null;
21        if ($db !== null) {
22            return $db;
23        }
24
25        /** @var helper_plugin_sqlite $db */
26        $db = plugin_load('helper', 'sqlite');
27        if ($db === null) {
28            msg('The tagging plugin needs the sqlite plugin', -1);
29
30            return false;
31        }
32        $db->init('tagging', __DIR__ . '/db/');
33        $db->create_function('CLEANTAG', array($this, 'cleanTag'), 1);
34        $db->create_function('GROUP_SORT',
35            function ($group, $newDelimiter) {
36                $ex = array_filter(explode(',', $group));
37                sort($ex);
38
39                return implode($newDelimiter, $ex);
40            }, 2);
41        $db->create_function('GET_NS', 'getNS', 1);
42
43        return $db;
44    }
45
46    /**
47     * Return the user to use for accessing tags
48     *
49     * Handles the singleuser mode by returning 'auto' as user. Returnes false when no user is logged in.
50     *
51     * @return bool|string
52     */
53    public function getUser() {
54        if (!isset($_SERVER['REMOTE_USER'])) {
55            return false;
56        }
57        if ($this->getConf('singleusermode')) {
58            return 'auto';
59        }
60
61        return $_SERVER['REMOTE_USER'];
62    }
63
64    /**
65     * If plugin elasticsearch is installed, inform it that we have just made changes
66     * to some data relevant to a page. The page should be re-indexed.
67     *
68     * @param string $id
69     */
70    public function updateElasticState($id)
71    {
72        /** @var \helper_plugin_elasticsearch_plugins $elasticHelper */
73        $elasticHelper = plugin_load('helper', 'elasticsearch_plugins');
74        if ($elasticHelper) {
75            $elasticHelper->updateRefreshState($id);
76        }
77    }
78
79    /**
80     * Canonicalizes the tag to its lower case nospace form
81     *
82     * @param $tag
83     *
84     * @return string
85     */
86    public function cleanTag($tag) {
87        $tag = str_replace(array(' ', '-', '_', '#'), '', $tag);
88        $tag = utf8_strtolower($tag);
89
90        return $tag;
91    }
92
93    /**
94     * Canonicalizes the namespace, remove the first colon and add glob
95     *
96     * @param $namespace
97     *
98     * @return string
99     */
100    public function globNamespace($namespace) {
101        return cleanId($namespace) . '*';
102    }
103
104    /**
105     * Create or Update tags of a page
106     *
107     * Uses the translation plugin to store the language of a page (if available)
108     *
109     * @param string $id The page ID
110     * @param string $user
111     * @param array  $tags
112     *
113     * @return bool|SQLiteResult
114     */
115    public function replaceTags($id, $user, $tags) {
116        global $conf;
117        /** @var helper_plugin_translation $trans */
118        $trans = plugin_load('helper', 'translation');
119        if ($trans) {
120            $lang = $trans->realLC($trans->getLangPart($id));
121        } else {
122            $lang = $conf['lang'];
123        }
124
125        $db = $this->getDB();
126        $db->query('BEGIN TRANSACTION');
127        $queries = array(array('DELETE FROM taggings WHERE pid = ? AND tagger = ?', $id, $user));
128        foreach ($tags as $tag) {
129            $queries[] = array('INSERT INTO taggings (pid, tagger, tag, lang) VALUES(?, ?, ?, ?)', $id, $user, $tag, $lang);
130        }
131
132        foreach ($queries as $query) {
133            if (!call_user_func_array(array($db, 'query'), $query)) {
134                $db->query('ROLLBACK TRANSACTION');
135
136                return false;
137            }
138        }
139
140        return $db->query('COMMIT TRANSACTION');
141    }
142
143    /**
144     * Get a list of Tags or Pages matching search criteria
145     *
146     * @param array  $filter What to search for array('field' => 'searchterm')
147     * @param string $type   What field to return 'tag'|'pid'
148     * @param int    $limit  Limit to this many results, 0 for all
149     *
150     * @return array associative array in form of value => count
151     */
152    public function findItems($filter, $type, $limit = 0) {
153
154        global $INPUT;
155
156        /** @var helper_plugin_tagging_querybuilder $queryBuilder */
157        $queryBuilder = new \helper_plugin_tagging_querybuilder();
158
159        $queryBuilder->setField($type);
160        $queryBuilder->setLimit($limit);
161        $queryBuilder->setTags($this->extractFromQuery($filter));
162        if (isset($filter['ns'])) $queryBuilder->includeNS($filter['ns']);
163        if (isset($filter['notns'])) $queryBuilder->excludeNS($filter['notns']);
164        if (isset($filter['tagger'])) $queryBuilder->setTagger($filter['tagger']);
165        if (isset($filter['pid'])) $queryBuilder->setPid($filter['pid']);
166
167        return $this->queryDb($queryBuilder->getQuery());
168
169    }
170
171    /**
172     * Constructs the URL to search for a tag
173     *
174     * @param string $tag
175     * @param string $ns
176     *
177     * @return string
178     */
179    public function getTagSearchURL($tag, $ns = '') {
180        $ret = '?do=search&sf=1&q=' . rawurlencode('#' . $this->cleanTag($tag));
181        if ($ns) {
182            $ret .= rawurlencode(' @' . $ns);
183        }
184
185        return $ret;
186    }
187
188    /**
189     * Calculates the size levels for the given list of clouds
190     *
191     * Automatically determines sensible tresholds
192     *
193     * @param array $tags list of tags => count
194     * @param int   $levels
195     *
196     * @return mixed
197     */
198    public function cloudData($tags, $levels = 10) {
199        $min = min($tags);
200        $max = max($tags);
201
202        // calculate tresholds
203        $tresholds = array();
204        for ($i = 0; $i <= $levels; $i++) {
205            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
206        }
207
208        // assign weights
209        foreach ($tags as $tag => $cnt) {
210            foreach ($tresholds as $tresh => $val) {
211                if ($cnt <= $val) {
212                    $tags[$tag] = $tresh;
213                    break;
214                }
215                $tags[$tag] = $levels;
216            }
217        }
218
219        return $tags;
220    }
221
222    /**
223     * Display a tag cloud
224     *
225     * @param array    $tags   list of tags => count
226     * @param string   $type   'tag'
227     * @param Callable $func   The function to print the link (gets tag and ns)
228     * @param bool     $wrap   wrap cloud in UL tags?
229     * @param bool     $return returnn HTML instead of printing?
230     * @param string   $ns     Add this namespace to search links
231     *
232     * @return string
233     */
234    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
235        global $INFO;
236
237        $hidden_str = $this->getConf('hiddenprefix');
238        $hidden_len = strlen($hidden_str);
239
240        $ret = '';
241        if ($wrap) {
242            $ret .= '<ul class="tagging_cloud clearfix">';
243        }
244        if (count($tags) === 0) {
245            // Produce valid XHTML (ul needs a child)
246            $this->setupLocale();
247            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
248        } else {
249            $tags = $this->cloudData($tags);
250            foreach ($tags as $val => $size) {
251                // skip hidden tags for users that can't edit
252                if ($type === 'tag' and
253                    $hidden_len and
254                    substr($val, 0, $hidden_len) == $hidden_str and
255                    !($this->getUser() && $INFO['writable'])
256                ) {
257                    continue;
258                }
259
260                $ret .= '<li class="t' . $size . '"><div class="li">';
261                $ret .= call_user_func($func, $val, $ns);
262                $ret .= '</div></li>';
263            }
264        }
265        if ($wrap) {
266            $ret .= '</ul>';
267        }
268        if ($return) {
269            return $ret;
270        }
271        echo $ret;
272
273        return '';
274    }
275
276    /**
277     * Display a List of Page Links
278     *
279     * @param array    $pids   list of pids => count
280     * @return string
281     */
282    public function html_page_list($pids) {
283        $ret = '<div class="search_quickresult">';
284        $ret .= '<ul class="search_quickhits">';
285
286        if (count($pids) === 0) {
287            // Produce valid XHTML (ul needs a child)
288            $ret .= '<li><div class="li">' . $this->lang['js']['nopages'] . '</div></li>';
289        } else {
290            foreach (array_keys($pids) as $val) {
291                $ret .= '<li><div class="li">';
292                $ret .= html_wikilink(":$val");
293                $ret .= '</div></li>';
294            }
295        }
296
297        $ret .= '</ul>';
298        $ret .= '</div>';
299        $ret .= '<div class="clearer"></div>';
300
301        return $ret;
302    }
303
304    /**
305     * Get the link to a search for the given tag
306     *
307     * @param string $tag search for this tag
308     * @param string $ns  limit search to this namespace
309     *
310     * @return string
311     */
312    protected function linkToSearch($tag, $ns = '') {
313        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
314    }
315
316    /**
317     * Display the Tags for the current page and prepare the tag editing form
318     *
319     * @param bool $print Should the HTML be printed or returned?
320     *
321     * @return string
322     */
323    public function tpl_tags($print = true) {
324        global $INFO;
325        global $lang;
326
327        $filter = array('pid' => $INFO['id']);
328        if ($this->getConf('singleusermode')) {
329            $filter['tagger'] = 'auto';
330        }
331
332        $tags = $this->findItems($filter, 'tag');
333
334        $ret = '';
335
336        $ret .= '<div class="plugin_tagging_edit">';
337        $ret .= $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'), true, true);
338
339        if ($this->getUser() && $INFO['writable']) {
340            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
341            $ret .= '<div id="tagging__edit_buttons_group">';
342            $ret .= html_btn('tagging_edit', $INFO['id'], '', array());
343            if (auth_isadmin()) {
344                $ret .= '<label>'
345                    . $this->getLang('toggle admin mode')
346                    . '<input type="checkbox" id="tagging__edit_toggle_admin" /></label>';
347            }
348            $ret .= '</div>';
349            $form = new dokuwiki\Form\Form();
350            $form->id('tagging__edit');
351            $form->setHiddenField('tagging[id]', $INFO['id']);
352            $form->setHiddenField('call', 'plugin_tagging_save');
353            $tags = $this->findItems(array(
354                'pid'    => $INFO['id'],
355                'tagger' => $this->getUser(),
356            ), 'tag');
357            $form->addTextarea('tagging[tags]')
358                ->val(implode(', ', array_keys($tags)))
359                ->addClass('edit')
360                ->attr('rows', 4);
361            $form->addButton('', $lang['btn_save'])->id('tagging__edit_save');
362            $form->addButton('', $lang['btn_cancel'])->id('tagging__edit_cancel');
363            $ret .= $form->toHTML();
364        }
365        $ret .= '</div>';
366
367        if ($print) {
368            echo $ret;
369        }
370
371        return $ret;
372    }
373
374    /**
375     * @param string $namespace empty for entire wiki
376     *
377     * @param string $order_by
378     * @param bool $desc
379     * @param array $filters
380     * @return array
381     */
382    public function getAllTags($namespace = '', $order_by = 'tid', $desc = false, $filters = []) {
383        $order_fields = array('pid', 'tid', 'taggers', 'ns', 'count');
384        if (!in_array($order_by, $order_fields)) {
385            msg('cannot sort by ' . $order_by . ' field does not exists', -1);
386            $order_by = 'tag';
387        }
388
389        list($having, $params) = $this->getFilterSql($filters);
390
391        $db = $this->getDB();
392
393        $query = 'SELECT    "pid",
394                            CLEANTAG("tag") AS "tid",
395                            GROUP_SORT(GROUP_CONCAT("tagger"), \', \') AS "taggers",
396                            GROUP_SORT(GROUP_CONCAT(GET_NS("pid")), \', \') AS "ns",
397                            GROUP_SORT(GROUP_CONCAT("pid"), \', \') AS "pids",
398                            COUNT(*) AS "count"
399                        FROM "taggings"
400                        WHERE "pid" GLOB ? AND GETACCESSLEVEL(pid) >= ' . AUTH_READ
401                        . ' GROUP BY "tid"';
402        $query .= $having;
403        $query .=      'ORDER BY ' . $order_by;
404        if ($desc) {
405            $query .= ' DESC';
406        }
407
408        array_unshift($params, $this->globNamespace($namespace));
409        $res = $db->query($query, $params);
410
411        return $db->res2arr($res);
412    }
413
414    /**
415     * Get all pages with tags and their tags
416     *
417     * @return array ['pid' => ['tag1','tag2','tag3']]
418     */
419    public function getAllTagsByPage() {
420        $query = '
421        SELECT pid, GROUP_CONCAT(tag) AS tags
422        FROM taggings
423        GROUP BY pid
424        ';
425        $db = $this->getDb();
426        $res = $db->query($query);
427        return array_map(
428            function ($i) {
429                return explode(',', $i);
430            },
431            array_column($db->res2arr($res), 'tags', 'pid')
432        );
433    }
434
435    /**
436     * Renames a tag
437     *
438     * @param string $formerTagName
439     * @param string $newTagNames
440     */
441    public function renameTag($formerTagName, $newTagNames) {
442
443        if (empty($formerTagName) || empty($newTagNames)) {
444            msg($this->getLang("admin enter tag names"), -1);
445            return;
446        }
447
448        $keepFormerTag = false;
449
450        // enable splitting tags on rename
451        $newTagNames = array_map(function ($tag) {
452            return $this->cleanTag($tag);
453        }, explode(',', $newTagNames));
454
455        $db = $this->getDB();
456
457        // non-admins can rename only their own tags
458        if (!auth_isadmin()) {
459            $queryTagger =' AND tagger = ?';
460            $tagger = $this->getUser();
461        } else {
462            $queryTagger = '';
463            $tagger = '';
464        }
465
466        $insertQuery = 'INSERT INTO taggings ';
467        $insertQuery .= 'SELECT pid, ?, tagger, lang FROM taggings';
468        $where = ' WHERE CLEANTAG(tag) = ?';
469        $where .= ' AND GETACCESSLEVEL(pid) >= ' . AUTH_EDIT;
470        $where .= $queryTagger;
471
472        $db->query('BEGIN TRANSACTION');
473
474        // insert new tags first
475        foreach ($newTagNames as $newTag) {
476            if ($newTag === $this->cleanTag($formerTagName)) {
477                $keepFormerTag = true;
478                continue;
479            }
480            $params = [$newTag, $this->cleanTag($formerTagName)];
481            if ($tagger) array_push($params, $tagger);
482            $res = $db->query($insertQuery . $where, $params);
483            if ($res === false) {
484                $db->query('ROLLBACK TRANSACTION');
485                return;
486            }
487            $db->res_close($res);
488        }
489
490        // finally delete the renamed tags
491        if (!$keepFormerTag) {
492            $deleteQuery = 'DELETE FROM taggings';
493            $params = [$this->cleanTag($formerTagName)];
494            if ($tagger) array_push($params, $tagger);
495            if ($db->query($deleteQuery . $where, $params) === false) {
496                $db->query('ROLLBACK TRANSACTION');
497                return;
498            }
499        }
500
501        $db->query('COMMIT TRANSACTION');
502
503        msg($this->getLang("admin renamed"), 1);
504
505        return;
506    }
507
508    /**
509     * Rename or delete a tag for all users
510     *
511     * @param string $pid
512     * @param string $formerTagName
513     * @param string $newTagName
514     *
515     * @return array
516     */
517    public function modifyPageTag($pid, $formerTagName, $newTagName) {
518
519        $db = $this->getDb();
520
521        $res = $db->query(
522            'SELECT pid FROM taggings WHERE CLEANTAG(tag) = ? AND pid = ?',
523            $this->cleanTag($formerTagName),
524            $pid
525        );
526        $check = $db->res2arr($res);
527
528        if (empty($check)) {
529            return array(true, $this->getLang('admin tag does not exists'));
530        }
531
532        if (empty($newTagName)) {
533            $res = $db->query(
534                'DELETE FROM taggings WHERE pid = ? AND CLEANTAG(tag) = ?',
535                $pid,
536                $this->cleanTag($formerTagName)
537            );
538        } else {
539            $res = $db->query(
540                'UPDATE taggings SET tag = ? WHERE pid = ? AND CLEANTAG(tag) = ?',
541                $newTagName,
542                $pid,
543                $this->cleanTag($formerTagName)
544            );
545        }
546        $db->res2arr($res);
547
548        return array(false, $this->getLang('admin renamed'));
549    }
550
551    /**
552     * Deletes a tag
553     *
554     * @param array  $tags
555     * @param string $namespace current namespace context as in getAllTags()
556     */
557    public function deleteTags($tags, $namespace = '') {
558        if (empty($tags)) {
559            return;
560        }
561
562        $namespace = cleanId($namespace);
563
564        $db = $this->getDB();
565
566        $queryBody = 'FROM taggings WHERE pid GLOB ? AND (' .
567            implode(' OR ', array_fill(0, count($tags), 'CLEANTAG(tag) = ?')) . ')';
568        $args = array_map(array($this, 'cleanTag'), $tags);
569        array_unshift($args, $this->globNamespace($namespace));
570
571        // non-admins can delete only their own tags
572        if (!auth_isadmin()) {
573            $queryBody .= ' AND tagger = ?';
574            array_push($args, $this->getUser());
575        }
576
577        $affectedPagesQuery= 'SELECT DISTINCT pid ' . $queryBody;
578        $resAffectedPages = $db->query($affectedPagesQuery, $args);
579        $numAffectedPages = count($resAffectedPages->fetchAll());
580
581        $deleteQuery = 'DELETE ' . $queryBody;
582        $db->query($deleteQuery, $args);
583
584        msg(sprintf($this->getLang("admin deleted"), count($tags), $numAffectedPages), 1);
585    }
586
587    /**
588     * Delete taggings of nonexistent pages
589     */
590    public function deleteInvalidTaggings()
591    {
592        $db = $this->getDB();
593        $query = 'DELETE    FROM "taggings"
594                            WHERE NOT PAGEEXISTS(pid)
595                 ';
596        $res = $db->query($query);
597        $db->res_close($res);
598    }
599
600    /**
601     * Updates tags with a new page name
602     *
603     * @param string $oldName
604     * @param string $newName
605     */
606    public function renamePage($oldName, $newName) {
607        $db = $this->getDB();
608        $db->query('UPDATE taggings SET pid = ? WHERE pid = ?', $newName, $oldName);
609    }
610
611    /**
612     * Extracts tags from search query
613     *
614     * @param array $parsedQuery
615     * @return array
616     */
617    public function extractFromQuery($parsedQuery)
618    {
619        $tags = [];
620        if (isset($parsedQuery['phrases'][0])) {
621            $tags = $parsedQuery['phrases'];
622        } elseif (isset($parsedQuery['and'][0])) {
623            $tags = $parsedQuery['and'];
624        } elseif (isset($parsedQuery['tag'])) {
625            // handle autocomplete call
626            $tags[] = $parsedQuery['tag'];
627        }
628        return $tags;
629    }
630
631    /**
632     * Search for tagged pages
633     *
634     * @param array $tagFiler
635     * @return array
636     */
637    public function searchPages($tagFiler)
638    {
639        global $INPUT;
640        global $QUERY;
641        $parsedQuery = ft_queryParser(new Doku_Indexer(), $QUERY);
642
643        /** @var helper_plugin_tagging_querybuilder $queryBuilder */
644        $queryBuilder = new \helper_plugin_tagging_querybuilder();
645
646        $queryBuilder->setField('pid');
647        $queryBuilder->setTags($tagFiler);
648        $queryBuilder->setLogicalAnd($INPUT->str('tagging-logic') === 'and');
649        if (isset($parsedQuery['ns'])) $queryBuilder->includeNS($parsedQuery['ns']);
650        if (isset($parsedQuery['notns'])) $queryBuilder->excludeNS($parsedQuery['notns']);
651        if (isset($parsedQuery['tagger'])) $queryBuilder->setTagger($parsedQuery['tagger']);
652        if (isset($parsedQuery['pid'])) $queryBuilder->setPid($parsedQuery['pid']);
653
654        return $this->queryDb($queryBuilder->getPages());
655    }
656
657    /**
658     * Syntax to allow users to manage tags on regular pages, respects ACLs
659     * @param string $ns
660     * @return string
661     */
662    public function manageTags($ns)
663    {
664        global $INPUT;
665
666        $this->setDefaultSort();
667
668        // initially set namespace filter to what is defined in syntax
669        if ($ns && !$INPUT->has('tagging__filters')) {
670            $INPUT->set('tagging__filters', ['ns' => $ns]);
671        }
672
673        return $this->html_table();
674    }
675
676    /**
677     * HTML list of tagged pages
678     *
679     * @param string $tid
680     * @return string
681     */
682    public function getPagesHtml($tid)
683    {
684        $html = '';
685
686        $db = $this->getDB();
687        $sql = 'SELECT pid from taggings where CLEANTAG(tag) = CLEANTAG(?)';
688        $res =  $db->query($sql, $tid);
689        $pages = $db->res2arr($res);
690
691        if ($pages) {
692            $html .= '<ul>';
693            foreach ($pages as $page) {
694                $pid = $page['pid'];
695                $html .= '<li><a href="' . wl($pid) . '" target="_blank">' . $pid . '</li>';
696            }
697            $html .= '</ul>';
698        }
699
700        return $html;
701    }
702
703    /**
704     * Display tag management table
705     */
706    public function html_table() {
707        global $ID, $INPUT;
708
709        $headers = array(
710            array('value' => $this->getLang('admin tag'), 'sort_by' => 'tid'),
711            array('value' => $this->getLang('admin occurrence'), 'sort_by' => 'count')
712        );
713
714        if (!$this->conf['hidens']) {
715            array_push(
716                $headers,
717                ['value' => $this->getLang('admin namespaces'), 'sort_by' => 'ns']
718            );
719        }
720
721        array_push($headers,
722            array('value' => $this->getLang('admin taggers'), 'sort_by' => 'taggers'),
723            array('value' => $this->getLang('admin actions'), 'sort_by' => false)
724        );
725
726        $sort = explode(',', $this->getParam('sort'));
727        $order_by = $sort[0];
728        $desc = false;
729        if (isset($sort[1]) && $sort[1] === 'desc') {
730            $desc = true;
731        }
732        $filters = $INPUT->arr('tagging__filters');
733
734        $tags = $this->getAllTags($INPUT->str('filter'), $order_by, $desc, $filters);
735
736        $form = new \dokuwiki\Form\Form();
737        // required in admin mode
738        $form->setHiddenField('page', 'tagging');
739        $form->setHiddenField('id', $ID);
740        $form->setHiddenField('[tagging]sort', $this->getParam('sort'));
741
742        /**
743         * Actions dialog
744         */
745        $form->addTagOpen('div')->id('tagging__action-dialog')->attr('style', "display:none;");
746        $form->addTagClose('div');
747
748        /**
749         * Tag pages dialog
750         */
751        $form->addTagOpen('div')->id('tagging__taggedpages-dialog')->attr('style', "display:none;");
752        $form->addTagClose('div');
753
754        /**
755         * Tag management table
756         */
757        $form->addTagOpen('table')->addClass('inline plugin_tagging');
758
759        $nscol = $this->conf['hidens'] ? '' : '<col class="wide-col"></col>';
760        $form->addHTML(
761            '<colgroup>
762                <col></col>
763                <col class="narrow-col"></col>'
764                . $nscol .
765                '<col></col>
766                <col class="narrow-col"></col>
767            </colgroup>'
768        );
769
770        /**
771         * Table headers
772         */
773        $form->addTagOpen('tr');
774        foreach ($headers as $header) {
775            $form->addTagOpen('th');
776            if ($header['sort_by'] !== false) {
777                $param = $header['sort_by'];
778                $icon = 'arrow-both';
779                $title = $this->getLang('admin sort ascending');
780                if ($header['sort_by'] === $order_by) {
781                    if ($desc === false) {
782                        $icon = 'arrow-up';
783                        $title = $this->getLang('admin sort descending');
784                        $param .= ',desc';
785                    } else {
786                        $icon = 'arrow-down';
787                    }
788                }
789                $form->addButtonHTML(
790                    "tagging[sort]",
791                    $header['value'] . ' ' . inlineSVG(__DIR__ . "/images/$icon.svg"))
792                    ->addClass('plugin_tagging sort_button')
793                    ->attr('title', $title)
794                    ->val($param);
795            } else {
796                $form->addHTML($header['value']);
797            }
798            $form->addTagClose('th');
799        }
800        $form->addTagClose('tr');
801
802        /**
803         * Table filters for all sortable columns
804         */
805        $form->addTagOpen('tr');
806        foreach ($headers as $header) {
807            $form->addTagOpen('th');
808            if ($header['sort_by'] !== false) {
809                $field = $header['sort_by'];
810                $input = $form->addTextInput("tagging__filters[$field]");
811                $input->addClass('full-col');
812            }
813            $form->addTagClose('th');
814        }
815        $form->addTagClose('tr');
816
817
818        foreach ($tags as $taginfo) {
819            $tagname = $taginfo['tid'];
820            $taggers = $taginfo['taggers'];
821            $ns = $taginfo['ns'];
822            $pids = explode(',',$taginfo['pids']);
823
824            $form->addTagOpen('tr');
825            $form->addHTML('<td>');
826            $form->addHTML('<a class="tagslist" href="#" data-tid="' . $taginfo['tid'] . '">');
827            $form->addHTML( hsc($tagname) . '</a>');
828            $form->addHTML('</td>');
829            $form->addHTML('<td>' . $taginfo['count'] . '</td>');
830            if (!$this->conf['hidens']) {
831                $form->addHTML('<td>' . hsc($ns) . '</td>');
832            }
833            $form->addHTML('<td>' . hsc($taggers) . '</td>');
834
835            /**
836             * action buttons
837             */
838            $form->addHTML('<td>');
839
840            // check ACLs
841            $userEdit = false;
842            foreach ($pids as $pid) {
843                if (auth_quickaclcheck($pid) >= AUTH_EDIT) {
844                    $userEdit = true;
845                    continue;
846                }
847            }
848
849            if ($userEdit) {
850                $form->addButtonHTML(
851                    'tagging[actions][rename][' . $taginfo['tid'] . ']',
852                    inlineSVG(__DIR__ . '/images/edit.svg'))
853                    ->addClass('plugin_tagging action_button')
854                    ->attr('data-action', 'rename')
855                    ->attr('data-tid', $taginfo['tid']);
856                $form->addButtonHTML(
857                    'tagging[actions][delete][' . $taginfo['tid'] . ']',
858                    inlineSVG(__DIR__ . '/images/delete.svg'))
859                    ->addClass('plugin_tagging action_button')
860                    ->attr('data-action', 'delete')
861                    ->attr('data-tid', $taginfo['tid']);
862            }
863
864            $form->addHTML('</td>');
865            $form->addTagClose('tr');
866        }
867
868        $form->addTagClose('table');
869        return '<div class="table">' . $form->toHTML() . '</div>';
870    }
871
872    /**
873     * Display tag cleaner
874     *
875     * @return string
876     */
877    public function html_clean()
878    {
879        $invalid = $this->getInvalidTaggings();
880
881        if (!$invalid) {
882            return '<p><strong>' . $this->getLang('admin no invalid') . '</strong></p>';
883        }
884
885        $form = new Form();
886        $form->setHiddenField('do', 'admin');
887        $form->setHiddenField('page', $this->getPluginName());
888        $form->addButton('cmd[clean]', $this->getLang('admin clean'));
889
890        $html = $form->toHTML();
891
892        $html .= '<div class="table"><table class="inline plugin_tagging">';
893        $html .= '<thead><tr><th>' .
894            $this->getLang('admin nonexistent page') .
895            '</th><th>' .
896            $this->getLang('admin tags') .
897            '</th></tr></thead><tbody>';
898
899        foreach ($invalid as $row) {
900            $html .= '<tr><td>' . $row['pid'] . '</td><td>' . $row['tags'] . '</td></tr>';
901        }
902
903        $html .= '</tbody></table></div>';
904
905        return $html;
906    }
907
908    /**
909     * Returns all tagging parameters from the query string
910     *
911     * @return mixed
912     */
913    public function getParams()
914    {
915        global $INPUT;
916        return $INPUT->param('tagging', []);
917    }
918
919    /**
920     * Get a tagging parameter, empty string if not set
921     *
922     * @param string $name
923     * @return mixed
924     */
925    public function getParam($name)
926    {
927        $params = $this->getParams();
928        if ($params) {
929            return $params[$name] ?: '';
930        }
931    }
932
933    /**
934     * Sets a tagging parameter
935     *
936     * @param string $name
937     * @param string|array $value
938     */
939    public function setParam($name, $value)
940    {
941        global $INPUT;
942        $params = $this->getParams();
943        $params = array_merge($params, [$name => $value]);
944        $INPUT->set('tagging', $params);
945    }
946
947    /**
948     * Default sorting by tag id
949     */
950    public function setDefaultSort()
951    {
952        if (!$this->getParam('sort')) {
953            $this->setParam('sort', 'tid');
954        }
955    }
956
957    /**
958     * Executes the query and returns the results as array
959     *
960     * @param array $query
961     * @return array
962     */
963    protected function queryDb($query)
964    {
965        $db = $this->getDB();
966        if (!$db) {
967            return [];
968        }
969
970        $res = $db->query($query[0], $query[1]);
971        $res = $db->res2arr($res);
972
973        $ret = [];
974        foreach ($res as $row) {
975            $ret[$row['item']] = $row['cnt'];
976        }
977        return $ret;
978    }
979
980    /**
981     * Construct the HAVING part of the search query
982     *
983     * @param array $filters
984     * @return array
985     */
986    protected function getFilterSql($filters)
987    {
988        $having = '';
989        $parts = [];
990        $params = [];
991        $filters = array_filter($filters);
992        if (!empty($filters)) {
993            $having = ' HAVING ';
994            foreach ($filters as $filter => $value) {
995                $parts[] = " $filter LIKE ? ";
996                $params[] = "%$value%";
997            }
998            $having .= implode(' AND ', $parts);
999        }
1000        return [$having, $params];
1001    }
1002
1003    /**
1004     * Returns taggings of nonexistent pages
1005     *
1006     * @return array
1007     */
1008    protected function getInvalidTaggings()
1009    {
1010        $db = $this->getDB();
1011        $query = 'SELECT    "pid",
1012                            GROUP_CONCAT(CLEANTAG("tag")) AS "tags"
1013                            FROM "taggings"
1014                            WHERE NOT PAGEEXISTS(pid)
1015                            GROUP BY pid
1016                 ';
1017        $res = $db->query($query);
1018        return $db->res2arr($res);
1019    }
1020}
1021