xref: /plugin/tagging/helper.php (revision 56d82720a486d9d1075b8cd0f5aa740fb85f9e56)
1<?php
2
3if(!defined('DOKU_INC')) die();
4class helper_plugin_tagging extends DokuWiki_Plugin {
5
6    /**
7     * Gives access to the database
8     *
9     * Initializes the SQLite helper and register the CLEANTAG function
10     *
11     * @return helper_plugin_sqlite|bool false if initialization fails
12     */
13    public function getDB() {
14        static $db = null;
15        if(!is_null($db)) {
16            return $db;
17        }
18
19        /** @var helper_plugin_sqlite $db */
20        $db = plugin_load('helper', 'sqlite');
21        if(is_null($db)) {
22            msg('The tagging plugin needs the sqlite plugin', -1);
23            return false;
24        }
25        $db->init('tagging', dirname(__FILE__) . '/db/');
26        $db->create_function('CLEANTAG', array($this, 'cleanTag'), 1);
27        return $db;
28    }
29
30    /**
31     * Return the user to use for accessing tags
32     *
33     * Handles the singleuser mode by returning 'auto' as user. Returnes false when no user is logged in.
34     *
35     * @return bool|string
36     */
37    public function getUser() {
38        if(!isset($_SERVER['REMOTE_USER'])) return false;
39        if($this->getConf('singleusermode')) return 'auto';
40        return $_SERVER['REMOTE_USER'];
41    }
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            // detect LIKE filters
115            if($this->useLike($value)) {
116                $where .= " AND $field LIKE $q";
117            } else {
118                $where .= " AND $field = $q";
119            }
120        }
121        // group and order
122        if($type == 'tag') {
123            $groupby = 'CLEANTAG(tag)';
124            $orderby = 'CLEANTAG(tag)';
125        } else {
126            $groupby = $type;
127            $orderby = "cnt DESC, $type";
128        }
129
130        // limit results
131        if($limit) {
132            $limit = " LIMIT $limit";
133        }else{
134            $limit = '';
135        }
136
137        // create SQL
138        $sql = "SELECT $type AS item, COUNT(*) AS cnt
139                  FROM taggings
140                 WHERE $where
141              GROUP BY $groupby
142              ORDER BY $orderby
143                $limit
144              ";
145
146        // run query and turn into associative array
147        $res = $db->query($sql, array_values($filter));
148        $res = $db->res2arr($res);
149
150        $ret = array();
151        foreach($res as $row) {
152            $ret[$row['item']] = $row['cnt'];
153        }
154        return $ret;
155    }
156
157    /**
158     * Check if the given string is a LIKE statement
159     *
160     * @param string $value
161     * @return bool
162     */
163    private function useLike($value) {
164        return strpos($value, '%') === 0 || strrpos($value, '%') === strlen($value) - 1;
165    }
166
167    /**
168     * Constructs the URL to search for a tag
169     *
170     * @param string $tag
171     * @param string $ns
172     * @return string
173     */
174    public function getTagSearchURL($tag, $ns = '') {
175        // wrap tag in quotes if non clean
176        $ctag = utf8_stripspecials($this->cleanTag($tag));
177        if($ctag != utf8_strtolower($tag)) $tag = '"'.$tag.'"';
178
179        $ret = '?do=search&id=' . rawurlencode($tag);
180        if($ns) $ret .= rawurlencode(' @' . $ns);
181
182        return $ret;
183    }
184
185    /**
186     * Calculates the size levels for the given list of clouds
187     *
188     * Automatically determines sensible tresholds
189     *
190     * @param array $tags list of tags => count
191     * @param int   $levels
192     * @return mixed
193     */
194    public function cloudData($tags, $levels = 10) {
195        $min = min($tags);
196        $max = max($tags);
197
198        // calculate tresholds
199        $tresholds = array();
200        for($i = 0; $i <= $levels; $i++) {
201            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
202        }
203
204        // assign weights
205        foreach($tags as $tag => $cnt) {
206            foreach($tresholds as $tresh => $val) {
207                if($cnt <= $val) {
208                    $tags[$tag] = $tresh;
209                    break;
210                }
211                $tags[$tag] = $levels;
212            }
213        }
214        return $tags;
215    }
216
217    /**
218     * Display a tag cloud
219     *
220     * @param array $tags list of tags => count
221     * @param string $type 'tag'
222     * @param Callable $func The function to print the link (gets tag and ns)
223     * @param bool $wrap wrap cloud in UL tags?
224     * @param bool $return returnn HTML instead of printing?
225     * @param string $ns Add this namespace to search links
226     * @return string
227     */
228    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
229        global $INFO;
230
231        $hidden_str = $this->getConf('hiddenprefix');
232        $hidden_len = strlen($hidden_str);
233
234        $ret = '';
235        if($wrap) $ret .= '<ul class="tagging_cloud clearfix">';
236        if(count($tags) === 0) {
237            // Produce valid XHTML (ul needs a child)
238            $this->setupLocale();
239            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
240        } else {
241            $tags = $this->cloudData($tags);
242            foreach($tags as $val => $size) {
243                // skip hidden tags for users that can't edit
244                if($type == 'tag' and
245                    $hidden_len and
246                    substr($val, 0, $hidden_len) == $hidden_str and
247                    !($this->getUser() && $INFO['writable'])
248                ) {
249                    continue;
250                }
251
252                $ret .= '<li class="t' . $size . '"><div class="li">';
253                $ret .= call_user_func($func, $val, $ns);
254                $ret .= '</div></li>';
255            }
256        }
257        if($wrap) $ret .= '</ul>';
258        if($return) return $ret;
259        echo $ret;
260        return '';
261    }
262
263    /**
264     * Get the link to a search for the given tag
265     *
266     * @param string $tag search for this tag
267     * @param string $ns  limit search to this namespace
268     * @return string
269     */
270    protected function linkToSearch($tag, $ns = '') {
271        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
272    }
273
274
275    public function tpl_tags() {
276        global $INFO;
277        global $lang;
278        $tags = $this->findItems(array('pid' => $INFO['id']), 'tag');
279        echo '<div class="plugin_tagging_edit">';
280        $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'));
281
282        if($this->getUser() && $INFO['writable']) {
283            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
284            echo html_btn('tagging_edit', $INFO['id'], '', array());
285            $form = new Doku_Form(array('id' => 'tagging__edit'));
286            $form->addHidden('tagging[id]', $INFO['id']);
287            $form->addHidden('call', 'plugin_tagging_save');
288            $form->addElement(form_makeTextField('tagging[tags]', implode(', ', array_keys($this->findItems(array('pid' => $INFO['id'], 'tagger' => $this->getUser()), 'tag')))));
289            $form->addElement(form_makeButton('submit', 'save', $lang['btn_save'], array('id' => 'tagging__edit_save')));
290            $form->addElement(form_makeButton('submit', 'cancel', $lang['btn_cancel'], array('id' => 'tagging__edit_cancel')));
291            $form->printForm();
292        }
293        echo '</div>';
294    }
295
296    /**
297     * @return array
298     */
299    public function getAllTags() {
300
301        $db  = $this->getDb();
302        $res = $db->query('SELECT pid, tag, tagger FROM taggings ORDER BY tag');
303
304        $tags_tmp = $db->res2arr($res);
305        $tags     = array();
306        foreach($tags_tmp as $tag) {
307            $tid = $this->cleanTag($tag['tag']);
308
309            //$tags[$tid]['pid'][] = $tag['pid'];
310
311            if(isset($tags[$tid]['count'])) {
312                $tags[$tid]['count']++;
313                $tags[$tid]['tagger'][] = $tag['tagger'];
314            } else {
315                $tags[$tid]['count']  = 1;
316                $tags[$tid]['tagger'] = array($tag['tagger']);
317            }
318        }
319        return $tags;
320    }
321
322    /**
323     * Renames a tag
324     *
325     * @param string $formerTagName
326     * @param string $newTagName
327     */
328    public function renameTag($formerTagName, $newTagName) {
329
330        if(empty($formerTagName) || empty($newTagName)) {
331            msg($this->getLang("admin enter tag names"), -1);
332            return;
333        }
334
335        $db = $this->getDb();
336
337        $res   = $db->query('SELECT pid FROM taggings WHERE tag= ?', $formerTagName);
338        $check = $db->res2arr($res);
339
340        if(empty($check)) {
341            msg($this->getLang("admin tag does not exists"), -1);
342            return;
343        }
344
345        $res = $db->query("UPDATE taggings SET tag = ? WHERE tag = ?", $newTagName, $formerTagName);
346        $db->res2arr($res);
347
348        msg($this->getLang("admin saved"), 1);
349        return;
350    }
351
352}
353