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