xref: /plugin/tagging/helper.php (revision 0b6fad272ca40ee78c62da769a0f0cf26ad44b6f)
1<?php
2/**
3 * Tagging Plugin (hlper component)
4 *
5 * @license GPL 2
6 */
7class helper_plugin_tagging extends DokuWiki_Plugin {
8
9    /**
10     * Gives access to the database
11     *
12     * Initializes the SQLite helper and register the CLEANTAG function
13     *
14     * @return helper_plugin_sqlite|bool false if initialization fails
15     */
16    public function getDB() {
17        static $db = null;
18        if ($db !== null) {
19            return $db;
20        }
21
22        /** @var helper_plugin_sqlite $db */
23        $db = plugin_load('helper', 'sqlite');
24        if ($db === null) {
25            msg('The tagging plugin needs the sqlite plugin', -1);
26
27            return false;
28        }
29        $db->init('tagging', __DIR__ . '/db/');
30        $db->create_function('CLEANTAG', array($this, 'cleanTag'), 1);
31        $db->create_function('GROUP_SORT',
32            function ($group, $newDelimiter) {
33                $ex = explode(',', $group);
34                sort($ex);
35
36                return implode($newDelimiter, $ex);
37            }, 2);
38
39        return $db;
40    }
41
42    /**
43     * Return the user to use for accessing tags
44     *
45     * Handles the singleuser mode by returning 'auto' as user. Returnes false when no user is logged in.
46     *
47     * @return bool|string
48     */
49    public function getUser() {
50        if (!isset($_SERVER['REMOTE_USER'])) {
51            return false;
52        }
53        if ($this->getConf('singleusermode')) {
54            return 'auto';
55        }
56
57        return $_SERVER['REMOTE_USER'];
58    }
59
60    /**
61     * Canonicalizes the tag to its lower case nospace form
62     *
63     * @param $tag
64     *
65     * @return string
66     */
67    public function cleanTag($tag) {
68        $tag = str_replace(array(' ', '-', '_'), '', $tag);
69        $tag = utf8_strtolower($tag);
70
71        return $tag;
72    }
73
74    /**
75     * Canonicalizes the namespace, remove the first colon and add glob
76     *
77     * @param $namespace
78     *
79     * @return string
80     */
81    public function globNamespace($namespace) {
82        return cleanId($namespace) . '%';
83    }
84
85    /**
86     * Create or Update tags of a page
87     *
88     * Uses the translation plugin to store the language of a page (if available)
89     *
90     * @param string $id The page ID
91     * @param string $user
92     * @param array  $tags
93     *
94     * @return bool|SQLiteResult
95     */
96    public function replaceTags($id, $user, $tags) {
97        global $conf;
98        /** @var helper_plugin_translation $trans */
99        $trans = plugin_load('helper', 'translation');
100        if ($trans) {
101            $lang = $trans->realLC($trans->getLangPart($id));
102        } else {
103            $lang = $conf['lang'];
104        }
105
106        $db = $this->getDB();
107        $db->query('BEGIN TRANSACTION');
108        $queries = array(array('DELETE FROM taggings WHERE pid = ? AND tagger = ?', $id, $user));
109        foreach ($tags as $tag) {
110            $queries[] = array('INSERT INTO taggings (pid, tagger, tag, lang) VALUES(?, ?, ?, ?)', $id, $user, $tag, $lang);
111        }
112
113        foreach ($queries as $query) {
114            if (!call_user_func_array(array($db, 'query'), $query)) {
115                $db->query('ROLLBACK TRANSACTION');
116
117                return false;
118            }
119        }
120
121        return $db->query('COMMIT TRANSACTION');
122    }
123
124    /**
125     * Get a list of Tags or Pages matching search criteria
126     *
127     * @param array  $filter What to search for array('field' => 'searchterm')
128     * @param string $type   What field to return 'tag'|'pid'
129     * @param int    $limit  Limit to this many results, 0 for all
130     *
131     * @return array associative array in form of value => count
132     */
133    public function findItems($filter, $type, $limit = 0) {
134        $db = $this->getDB();
135        if (!$db) {
136            return array();
137        }
138
139        // create WHERE clause
140        $where = '1=1';
141        foreach ($filter as $field => $value) {
142            // compare clean tags only
143            if ($field === 'tag') {
144                $field = 'CLEANTAG(tag)';
145                $q = 'CLEANTAG(?)';
146            } else {
147                $q = '?';
148            }
149
150            if (substr($field, 0, 6) === 'notpid') {
151                $field = 'pid';
152
153                // detect LIKE filters
154                if ($this->useLike($value)) {
155                    $where .= " AND $field NOT LIKE $q";
156                } else {
157                    $where .= " AND $field != $q";
158                }
159            } else {
160                // detect LIKE filters
161                if ($this->useLike($value)) {
162                    $where .= " AND $field LIKE $q";
163                } else {
164                    $where .= " AND $field = $q";
165                }
166            }
167        }
168        $where .= ' AND GETACCESSLEVEL(pid) >= ' . AUTH_READ;
169
170        // group and order
171        if ($type === 'tag') {
172            $groupby = 'CLEANTAG(tag)';
173            $orderby = 'CLEANTAG(tag)';
174        } else {
175            $groupby = $type;
176            $orderby = "cnt DESC, $type";
177        }
178
179        // limit results
180        if ($limit) {
181            $limit = " LIMIT $limit";
182        } else {
183            $limit = '';
184        }
185
186        // create SQL
187        $sql = "SELECT $type AS item, COUNT(*) AS cnt
188                  FROM taggings
189                 WHERE $where
190              GROUP BY $groupby
191              ORDER BY $orderby
192                $limit
193              ";
194
195        // run query and turn into associative array
196        $res = $db->query($sql, array_values($filter));
197        $res = $db->res2arr($res);
198
199        $ret = array();
200        foreach ($res as $row) {
201            $ret[$row['item']] = $row['cnt'];
202        }
203
204        return $ret;
205    }
206
207    /**
208     * Check if the given string is a LIKE statement
209     *
210     * @param string $value
211     *
212     * @return bool
213     */
214    private function useLike($value) {
215        return strpos($value, '%') === 0 || strrpos($value, '%') === strlen($value) - 1;
216    }
217
218    /**
219     * Constructs the URL to search for a tag
220     *
221     * @param string $tag
222     * @param string $ns
223     *
224     * @return string
225     */
226    public function getTagSearchURL($tag, $ns = '') {
227        // wrap tag in quotes if non clean
228        $ctag = utf8_stripspecials($this->cleanTag($tag));
229        if ($ctag != utf8_strtolower($tag)) {
230            $tag = '"' . $tag . '"';
231        }
232
233        $ret = '?do=search&id=' . rawurlencode($tag);
234        if ($ns) {
235            $ret .= rawurlencode(' @' . $ns);
236        }
237
238        return $ret;
239    }
240
241    /**
242     * Calculates the size levels for the given list of clouds
243     *
244     * Automatically determines sensible tresholds
245     *
246     * @param array $tags list of tags => count
247     * @param int   $levels
248     *
249     * @return mixed
250     */
251    public function cloudData($tags, $levels = 10) {
252        $min = min($tags);
253        $max = max($tags);
254
255        // calculate tresholds
256        $tresholds = array();
257        for ($i = 0; $i <= $levels; $i++) {
258            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
259        }
260
261        // assign weights
262        foreach ($tags as $tag => $cnt) {
263            foreach ($tresholds as $tresh => $val) {
264                if ($cnt <= $val) {
265                    $tags[$tag] = $tresh;
266                    break;
267                }
268                $tags[$tag] = $levels;
269            }
270        }
271
272        return $tags;
273    }
274
275    /**
276     * Display a tag cloud
277     *
278     * @param array    $tags   list of tags => count
279     * @param string   $type   'tag'
280     * @param Callable $func   The function to print the link (gets tag and ns)
281     * @param bool     $wrap   wrap cloud in UL tags?
282     * @param bool     $return returnn HTML instead of printing?
283     * @param string   $ns     Add this namespace to search links
284     *
285     * @return string
286     */
287    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
288        global $INFO;
289
290        $hidden_str = $this->getConf('hiddenprefix');
291        $hidden_len = strlen($hidden_str);
292
293        $ret = '';
294        if ($wrap) {
295            $ret .= '<ul class="tagging_cloud clearfix">';
296        }
297        if (count($tags) === 0) {
298            // Produce valid XHTML (ul needs a child)
299            $this->setupLocale();
300            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
301        } else {
302            $tags = $this->cloudData($tags);
303            foreach ($tags as $val => $size) {
304                // skip hidden tags for users that can't edit
305                if ($type === 'tag' and
306                    $hidden_len and
307                    substr($val, 0, $hidden_len) == $hidden_str and
308                    !($this->getUser() && $INFO['writable'])
309                ) {
310                    continue;
311                }
312
313                $ret .= '<li class="t' . $size . '"><div class="li">';
314                $ret .= call_user_func($func, $val, $ns);
315                $ret .= '</div></li>';
316            }
317        }
318        if ($wrap) {
319            $ret .= '</ul>';
320        }
321        if ($return) {
322            return $ret;
323        }
324        echo $ret;
325
326        return '';
327    }
328
329    /**
330     * Display a List of Page Links
331     *
332     * @param array    $pids   list of pids => count
333     * @return string
334     */
335    public function html_page_list($pids) {
336        global $INFO;
337
338        $ret = '<div class="search_quickresult">';
339        $ret .= '<ul class="search_quickhits">';
340
341        if (count($pids) === 0) {
342            // Produce valid XHTML (ul needs a child)
343            $this->setupLocale();
344            $ret .= '<li><div class="li">' . $this->lang['js']['nopages'] . '</div></li>';
345        } else {
346            foreach ($pids as $val => $size) {
347                $ret .= '<li><div class="li">';
348                $ret .= html_wikilink($val);
349                $ret .= '</div></li>';
350            }
351        }
352
353        $ret .= '</ul>';
354        $ret .= '</div>';
355        $ret .= '<div class="clearer"></div>';
356
357        return $ret;
358    }
359
360    /**
361     * Get the link to a search for the given tag
362     *
363     * @param string $tag search for this tag
364     * @param string $ns  limit search to this namespace
365     *
366     * @return string
367     */
368    protected function linkToSearch($tag, $ns = '') {
369        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
370    }
371
372    /**
373     * Display the Tags for the current page and prepare the tag editing form
374     *
375     * @param bool $print Should the HTML be printed or returned?
376     *
377     * @return string
378     */
379    public function tpl_tags($print = true) {
380        global $INFO;
381        global $lang;
382
383        $filter = array('pid' => $INFO['id']);
384        if ($this->getConf('singleusermode')) {
385            $filter['tagger'] = 'auto';
386        }
387
388        $tags = $this->findItems($filter, 'tag');
389
390        $ret = '';
391
392        $ret .= '<div class="plugin_tagging_edit">';
393        $ret .= $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'), true, true);
394
395        if ($this->getUser() && $INFO['writable']) {
396            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
397            $ret .= '<div id="tagging__edit_buttons_group">';
398            $ret .= html_btn('tagging_edit', $INFO['id'], '', array());
399            if (auth_isadmin()) {
400                $ret .= '<label>' . $this->getLang('toggle admin mode') . '<input type="checkbox" id="tagging__edit_toggle_admin" /></label>';
401            }
402            $ret .= '</div>';
403            $form = new dokuwiki\Form\Form();
404            $form->id('tagging__edit');
405            $form->setHiddenField('tagging[id]', $INFO['id']);
406            $form->setHiddenField('call', 'plugin_tagging_save');
407            $tags = $this->findItems(array(
408                'pid'    => $INFO['id'],
409                'tagger' => $this->getUser(),
410            ), 'tag');
411            $form->addTextarea('tagging[tags]')->val(implode(', ', array_keys($tags)))->addClass('edit')->attr('rows', 4);
412            $form->addButton('', $lang['btn_save'])->id('tagging__edit_save');
413            $form->addButton('', $lang['btn_cancel'])->id('tagging__edit_cancel');
414            $ret .= $form->toHTML();
415        }
416        $ret .= '</div>';
417
418        if ($print) {
419            echo $ret;
420        }
421
422        return $ret;
423    }
424
425    /**
426     * @param string $namespace empty for entire wiki
427     *
428     * @return array
429     */
430    public function getAllTags($namespace = '', $order_by = 'tag', $desc = false) {
431        $order_fields = array('pid', 'tid', 'orig', 'taggers', 'count');
432        if (!in_array($order_by, $order_fields)) {
433            msg('cannot sort by ' . $order_by . ' field does not exists', -1);
434            $order_by = 'tag';
435        }
436
437        $db = $this->getDb();
438
439        $query = 'SELECT    "pid",
440                            CLEANTAG("tag") AS "tid",
441                            GROUP_SORT(GROUP_CONCAT("tag"), \', \') AS "orig",
442                            GROUP_SORT(GROUP_CONCAT("tagger"), \', \') AS "taggers",
443                            COUNT(*) AS "count"
444                        FROM "taggings"
445                        WHERE "pid" LIKE ?
446                        GROUP BY "tid"
447                        ORDER BY ' . $order_by;
448        if ($desc) {
449            $query .= ' DESC';
450        }
451
452        $res = $db->query($query, $this->globNamespace($namespace));
453
454        return $db->res2arr($res);
455    }
456
457    /**
458     * Get all pages with tags and their tags
459     *
460     * @return array ['pid' => ['tag1','tag2','tag3']]
461     */
462    public function getAllTagsByPage() {
463        $query = '
464        SELECT pid, GROUP_CONCAT(tag) AS tags
465        FROM taggings
466        GROUP BY pid
467        ';
468        $db = $this->getDb();
469        $res = $db->query($query);
470        return array_map(
471            function ($i) {
472                return explode(',', $i);
473            },
474            array_column($db->res2arr($res), 'tags', 'pid')
475        );
476    }
477
478    /**
479     * Renames a tag
480     *
481     * @param string $formerTagName
482     * @param string $newTagName
483     */
484    public function renameTag($formerTagName, $newTagName) {
485
486        if (empty($formerTagName) || empty($newTagName)) {
487            msg($this->getLang("admin enter tag names"), -1);
488
489            return;
490        }
491
492        $db = $this->getDb();
493
494        $res = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ?', $this->cleanTag($formerTagName));
495        $check = $db->res2arr($res);
496
497        if (empty($check)) {
498            msg($this->getLang("admin tag does not exists"), -1);
499
500            return;
501        }
502
503        $res = $db->query("UPDATE taggings SET tag = ? WHERE CLEANTAG(tag) = ?", $newTagName, $this->cleanTag($formerTagName));
504        $db->res2arr($res);
505
506        msg($this->getLang("admin renamed"), 1);
507
508        return;
509    }
510
511    /**
512     * Rename or delete a tag for all users
513     *
514     * @param string $pid
515     * @param string $formerTagName
516     * @param string $newTagName
517     *
518     * @return array
519     */
520    public function modifyPageTag($pid, $formerTagName, $newTagName) {
521
522        $db = $this->getDb();
523
524        $res = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ? AND pid = ?', $this->cleanTag($formerTagName), $pid);
525        $check = $db->res2arr($res);
526
527        if (empty($check)) {
528            return array(true, $this->getLang('admin tag does not exists'));
529        }
530
531        if (empty($newTagName)) {
532            $res = $db->query('DELETE FROM taggings WHERE pid = ? AND CLEANTAG(tag) = ?', $pid, $this->cleanTag($formerTagName));
533        } else {
534            $res = $db->query('UPDATE taggings SET tag = ? WHERE pid = ? AND CLEANTAG(tag) = ?', $newTagName, $pid, $this->cleanTag($formerTagName));
535        }
536        $db->res2arr($res);
537
538        return array(false, $this->getLang('admin renamed'));
539    }
540
541    /**
542     * Deletes a tag
543     *
544     * @param array  $tags
545     * @param string $namespace current namespace context as in getAllTags()
546     */
547    public function deleteTags($tags, $namespace = '') {
548        if (empty($tags)) {
549            return;
550        }
551
552        $namespace = cleanId($namespace);
553
554        $db = $this->getDB();
555
556        $queryBody = 'FROM taggings WHERE pid LIKE ? AND (' .
557            implode(' OR ', array_fill(0, count($tags), 'CLEANTAG(tag) = ?')) . ')';
558        $args = array_map(array($this, 'cleanTag'), $tags);
559        array_unshift($args, $this->globNamespace($namespace));
560
561
562        $affectedPagesQuery= 'SELECT DISTINCT pid ' . $queryBody;
563        $resAffectedPages = $db->query($affectedPagesQuery, $args);
564        $numAffectedPages = count($resAffectedPages->fetchAll());
565
566        $deleteQuery = 'DELETE ' . $queryBody;
567        $db->query($deleteQuery, $args);
568
569        msg(sprintf($this->getLang("admin deleted"), count($tags), $numAffectedPages), 1);
570    }
571}
572