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