xref: /plugin/tagging/helper.php (revision 59cd4311f7d53edb162642d462a695727af21e1e)
1<?php
2
3if(!defined('DOKU_INC')) die();
4
5class helper_plugin_tagging extends DokuWiki_Plugin {
6
7    /**
8     * Gives access to the database
9     *
10     * Initializes the SQLite helper and register the CLEANTAG function
11     *
12     * @return helper_plugin_sqlite|bool false if initialization fails
13     */
14    public function getDB() {
15        static $db = null;
16        if(!is_null($db)) {
17            return $db;
18        }
19
20        /** @var helper_plugin_sqlite $db */
21        $db = plugin_load('helper', 'sqlite');
22        if(is_null($db)) {
23            msg('The tagging plugin needs the sqlite plugin', -1);
24            return false;
25        }
26        $db->init('tagging', dirname(__FILE__) . '/db/');
27        $db->create_function('CLEANTAG', array($this, 'cleanTag'), 1);
28        return $db;
29    }
30
31    /**
32     * Return the user to use for accessing tags
33     *
34     * Handles the singleuser mode by returning 'auto' as user. Returnes false when no user is logged in.
35     *
36     * @return bool|string
37     */
38    public function getUser() {
39        if(!isset($_SERVER['REMOTE_USER'])) return false;
40        if($this->getConf('singleusermode')) return 'auto';
41        return $_SERVER['REMOTE_USER'];
42    }
43
44    /**
45     * Canonicalizes the tag to its lower case nospace form
46     *
47     * @param $tag
48     * @return string
49     */
50    public function cleanTag($tag) {
51        $tag = str_replace(' ', '', $tag);
52        $tag = utf8_strtolower($tag);
53        return $tag;
54    }
55
56    /**
57     * Create or Update tags of a page
58     *
59     * Uses the translation plugin to store the language of a page (if available)
60     *
61     * @param string $id The page ID
62     * @param string $user
63     * @param array $tags
64     * @return bool|SQLiteResult
65     */
66    public function replaceTags($id, $user, $tags) {
67        global $conf;
68        /** @var helper_plugin_translation $trans */
69        $trans = plugin_load('helper', 'translation');
70        if($trans) {
71            $lang = $trans->realLC($trans->getLangPart($id));
72        } else {
73            $lang = $conf['lang'];
74        }
75
76        $db = $this->getDB();
77        $db->query('BEGIN TRANSACTION');
78        $queries = array(array('DELETE FROM taggings WHERE pid = ? AND tagger = ?', $id, $user));
79        foreach($tags as $tag) {
80            $queries[] = array('INSERT INTO taggings (pid, tagger, tag, lang) VALUES(?, ?, ?, ?)', $id, $user, $tag, $lang);
81        }
82
83        foreach($queries as $query) {
84            if(!call_user_func_array(array($db, 'query'), $query)) {
85                $db->query('ROLLBACK TRANSACTION');
86                return false;
87            }
88        }
89        return $db->query('COMMIT TRANSACTION');
90    }
91
92    /**
93     * Get a list of Tags or Pages matching search criteria
94     *
95     * @param array $filter What to search for array('field' => 'searchterm')
96     * @param string $type What field to return 'tag'|'pid'
97     * @param int $limit Limit to this many results, 0 for all
98     * @return array associative array in form of value => count
99     */
100    public function findItems($filter, $type, $limit = 0) {
101        $db = $this->getDB();
102        if(!$db) return array();
103
104        // create WHERE clause
105        $where = '1=1';
106        foreach($filter as $field => $value) {
107            // compare clean tags only
108            if($field === 'tag') {
109                $field = 'CLEANTAG(tag)';
110                $q     = 'CLEANTAG(?)';
111            } else {
112                $q = '?';
113            }
114
115            if (substr($field,0,6) === 'notpid') {
116                $field = 'pid';
117
118                // detect LIKE filters
119                if($this->useLike($value)) {
120                    $where .= " AND $field NOT LIKE $q";
121                } else {
122                    $where .= " AND $field != $q";
123                }
124            } else {
125                // detect LIKE filters
126                if($this->useLike($value)) {
127                    $where .= " AND $field LIKE $q";
128                } else {
129                    $where .= " AND $field = $q";
130                }
131            }
132        }
133        // group and order
134        if($type == 'tag') {
135            $groupby = 'CLEANTAG(tag)';
136            $orderby = 'CLEANTAG(tag)';
137        } else {
138            $groupby = $type;
139            $orderby = "cnt DESC, $type";
140        }
141
142        // limit results
143        if($limit) {
144            $limit = " LIMIT $limit";
145        } else {
146            $limit = '';
147        }
148
149        // create SQL
150        $sql = "SELECT $type AS item, COUNT(*) AS cnt
151                  FROM taggings
152                 WHERE $where
153              GROUP BY $groupby
154              ORDER BY $orderby
155                $limit
156              ";
157
158        // run query and turn into associative array
159        $res = $db->query($sql, array_values($filter));
160        $res = $db->res2arr($res);
161
162        $ret = array();
163        foreach($res as $row) {
164            if (!isHiddenPage($row['item']) && auth_quickaclcheck($row['item']) >= AUTH_READ) {
165                $ret[$row['item']] = $row['cnt'];
166            }
167        }
168        return $ret;
169    }
170
171    /**
172     * Check if the given string is a LIKE statement
173     *
174     * @param string $value
175     * @return bool
176     */
177    private function useLike($value) {
178        return strpos($value, '%') === 0 || strrpos($value, '%') === strlen($value) - 1;
179    }
180
181    /**
182     * Constructs the URL to search for a tag
183     *
184     * @param string $tag
185     * @param string $ns
186     * @return string
187     */
188    public function getTagSearchURL($tag, $ns = '') {
189        // wrap tag in quotes if non clean
190        $ctag = utf8_stripspecials($this->cleanTag($tag));
191        if($ctag != utf8_strtolower($tag)) $tag = '"' . $tag . '"';
192
193        $ret = '?do=search&id=' . rawurlencode($tag);
194        if($ns) $ret .= rawurlencode(' @' . $ns);
195
196        return $ret;
197    }
198
199    /**
200     * Calculates the size levels for the given list of clouds
201     *
202     * Automatically determines sensible tresholds
203     *
204     * @param array $tags list of tags => count
205     * @param int $levels
206     * @return mixed
207     */
208    public function cloudData($tags, $levels = 10) {
209        $min = min($tags);
210        $max = max($tags);
211
212        // calculate tresholds
213        $tresholds = array();
214        for($i = 0; $i <= $levels; $i++) {
215            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
216        }
217
218        // assign weights
219        foreach($tags as $tag => $cnt) {
220            foreach($tresholds as $tresh => $val) {
221                if($cnt <= $val) {
222                    $tags[$tag] = $tresh;
223                    break;
224                }
225                $tags[$tag] = $levels;
226            }
227        }
228        return $tags;
229    }
230
231    /**
232     * Display a tag cloud
233     *
234     * @param array $tags list of tags => count
235     * @param string $type 'tag'
236     * @param Callable $func The function to print the link (gets tag and ns)
237     * @param bool $wrap wrap cloud in UL tags?
238     * @param bool $return returnn HTML instead of printing?
239     * @param string $ns Add this namespace to search links
240     * @return string
241     */
242    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
243        global $INFO;
244
245        $hidden_str = $this->getConf('hiddenprefix');
246        $hidden_len = strlen($hidden_str);
247
248        $ret = '';
249        if($wrap) $ret .= '<ul class="tagging_cloud clearfix">';
250        if(count($tags) === 0) {
251            // Produce valid XHTML (ul needs a child)
252            $this->setupLocale();
253            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
254        } else {
255            $tags = $this->cloudData($tags);
256            foreach($tags as $val => $size) {
257                // skip hidden tags for users that can't edit
258                if($type == 'tag' and
259                    $hidden_len and
260                    substr($val, 0, $hidden_len) == $hidden_str and
261                    !($this->getUser() && $INFO['writable'])
262                ) {
263                    continue;
264                }
265
266                $ret .= '<li class="t' . $size . '"><div class="li">';
267                $ret .= call_user_func($func, $val, $ns);
268                $ret .= '</div></li>';
269            }
270        }
271        if($wrap) $ret .= '</ul>';
272        if($return) return $ret;
273        echo $ret;
274        return '';
275    }
276
277    /**
278     * Get the link to a search for the given tag
279     *
280     * @param string $tag search for this tag
281     * @param string $ns limit search to this namespace
282     * @return string
283     */
284    protected function linkToSearch($tag, $ns = '') {
285        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
286    }
287
288    /**
289     * Display the Tags for the current page and prepare the tag editing form
290     *
291     * @param bool $print Should the HTML be printed or returned?
292     * @return string
293     */
294    public function tpl_tags($print = true) {
295        global $INFO;
296        global $lang;
297        $tags = $this->findItems(array('pid' => $INFO['id']), 'tag');
298
299        $ret = '';
300
301        $ret .= '<div class="plugin_tagging_edit">';
302        $ret .= $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'), true, true);
303
304        if($this->getUser() && $INFO['writable']) {
305            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
306            $ret .= html_btn('tagging_edit', $INFO['id'], '', array());
307            $form = new Doku_Form(array('id' => 'tagging__edit'));
308            $form->addHidden('tagging[id]', $INFO['id']);
309            $form->addHidden('call', 'plugin_tagging_save');
310            $form->addElement(form_makeTextField('tagging[tags]', implode(', ', array_keys($this->findItems(array('pid' => $INFO['id'], 'tagger' => $this->getUser()), 'tag')))));
311            $form->addElement(form_makeButton('submit', 'save', $lang['btn_save'], array('id' => 'tagging__edit_save')));
312            $form->addElement(form_makeButton('submit', 'cancel', $lang['btn_cancel'], array('id' => 'tagging__edit_cancel')));
313            $ret .= $form->getForm();
314        }
315        $ret .= '</div>';
316
317        if($print) echo $ret;
318        return $ret;
319    }
320
321    /**
322     * @return array
323     */
324    public function getAllTags() {
325
326        $db  = $this->getDb();
327        $res = $db->query('SELECT pid, tag, tagger FROM taggings ORDER BY tag');
328
329        $tags_tmp = $db->res2arr($res);
330        $tags     = array();
331        foreach($tags_tmp as $tag) {
332            $tid = $this->cleanTag($tag['tag']);
333
334            if(!isset($tags[$tid]['orig'])) $tags[$tid]['orig'] = array();
335            $tags[$tid]['orig'][] = $tag['tag'];
336
337            if(isset($tags[$tid]['count'])) {
338                $tags[$tid]['count']++;
339                $tags[$tid]['tagger'][] = $tag['tagger'];
340            } else {
341                $tags[$tid]['count']  = 1;
342                $tags[$tid]['tagger'] = array($tag['tagger']);
343            }
344        }
345        return $tags;
346    }
347
348    /**
349     * Renames a tag
350     *
351     * @param string $formerTagName
352     * @param string $newTagName
353     */
354    public function renameTag($formerTagName, $newTagName) {
355
356        if(empty($formerTagName) || empty($newTagName)) {
357            msg($this->getLang("admin enter tag names"), -1);
358            return;
359        }
360
361        $db = $this->getDb();
362
363        $res   = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ?', $this->cleanTag($formerTagName));
364        $check = $db->res2arr($res);
365
366        if(empty($check)) {
367            msg($this->getLang("admin tag does not exists"), -1);
368            return;
369        }
370
371        $res = $db->query("UPDATE taggings SET tag = ? WHERE CLEANTAG(tag) = ?", $newTagName, $this->cleanTag($formerTagName));
372        $db->res2arr($res);
373
374        msg($this->getLang("admin renamed"), 1);
375        return;
376    }
377
378}
379