1<?php 2 3namespace dokuwiki\plugin\struct\meta; 4 5use dokuwiki\plugin\struct\types\AutoSummary; 6use dokuwiki\plugin\struct\types\DateTime; 7use dokuwiki\plugin\struct\types\Decimal; 8use dokuwiki\plugin\struct\types\Page; 9use dokuwiki\plugin\struct\types\User; 10 11class Search 12{ 13 /** 14 * This separator will be used to concat multi values to flatten them in the result set 15 */ 16 public const CONCAT_SEPARATOR = "\n!_-_-_-_-_!\n"; 17 18 /** 19 * The list of known and allowed comparators 20 * (order matters) 21 */ 22 public static $COMPARATORS = array( 23 '<=', '>=', '=*', '=', '<', '>', '!=', '!~', '~', ' IN ' 24 ); 25 26 /** @var \helper_plugin_struct_db */ 27 protected $dbHelper; 28 29 /** @var \helper_plugin_sqlite */ 30 protected $sqlite; 31 32 /** @var Schema[] list of schemas to query */ 33 protected $schemas = array(); 34 35 /** @var Column[] list of columns to select */ 36 protected $columns = array(); 37 38 /** @var array the sorting of the result */ 39 protected $sortby = array(); 40 41 /** @var array the filters */ 42 protected $filter = array(); 43 44 /** @var array list of aliases tables can be referenced by */ 45 protected $aliases = array(); 46 47 /** @var int begin results from here */ 48 protected $range_begin = 0; 49 50 /** @var int end results here */ 51 protected $range_end = 0; 52 53 /** @var int the number of results */ 54 protected $count = -1; 55 /** @var string[] the PIDs of the result rows */ 56 protected $result_pids = null; 57 /** @var array the row ids of the result rows */ 58 protected $result_rids = []; 59 /** @var array the revisions of the result rows */ 60 protected $result_revs = []; 61 62 /** 63 * Search constructor. 64 */ 65 public function __construct() 66 { 67 /** @var $dbHelper */ 68 $this->dbHelper = plugin_load('helper', 'struct_db'); 69 $this->sqlite = $this->dbHelper->getDB(); 70 } 71 72 public function getDb() 73 { 74 return $this->sqlite; 75 } 76 77 /** 78 * Add a schema to be searched 79 * 80 * Call multiple times for multiple schemas. 81 * 82 * @param string $table 83 * @param string $alias 84 */ 85 public function addSchema($table, $alias = '') 86 { 87 $schema = new Schema($table); 88 if (!$schema->getId()) { 89 throw new StructException('schema missing', $table); 90 } 91 92 $this->schemas[$schema->getTable()] = $schema; 93 if ($alias) $this->aliases[$alias] = $schema->getTable(); 94 } 95 96 /** 97 * Add a column to be returned by the search 98 * 99 * Call multiple times for multiple columns. Be sure the referenced tables have been 100 * added before 101 * 102 * @param string $colname may contain an alias 103 */ 104 public function addColumn($colname) 105 { 106 if ($this->processWildcard($colname)) return; // wildcard? 107 if ($colname[0] == '-') { // remove column from previous wildcard lookup 108 $colname = substr($colname, 1); 109 foreach ($this->columns as $key => $col) { 110 if ($col->getLabel() == $colname) unset($this->columns[$key]); 111 } 112 return; 113 } 114 115 $col = $this->findColumn($colname); 116 if (!$col) return; //FIXME do we really want to ignore missing columns? 117 $this->columns[] = $col; 118 } 119 120 /** 121 * Add sorting options 122 * 123 * Call multiple times for multiple columns. Be sure the referenced tables have been 124 * added before 125 * 126 * @param string $colname may contain an alias 127 * @param bool $asc sort direction (ASC = true, DESC = false) 128 * @param bool $nc set true for caseinsensitivity 129 */ 130 public function addSort($colname, $asc = true, $nc = true) 131 { 132 $col = $this->findColumn($colname); 133 if (!$col) return; //FIXME do we really want to ignore missing columns? 134 135 $this->sortby[$col->getFullQualifiedLabel()] = array($col, $asc, $nc); 136 } 137 138 /** 139 * Returns all set sort columns 140 * 141 * @return array 142 */ 143 public function getSorts() 144 { 145 return $this->sortby; 146 } 147 148 /** 149 * Adds a filter 150 * 151 * @param string $colname may contain an alias 152 * @param string|string[] $value 153 * @param string $comp @see self::COMPARATORS 154 * @param string $op either 'OR' or 'AND' 155 */ 156 public function addFilter($colname, $value, $comp, $op = 'OR') 157 { 158 /* Convert certain filters into others 159 * this reduces the number of supported filters to implement in types */ 160 if ($comp == '*~') { 161 $value = $this->filterWrapAsterisks($value); 162 $comp = '~'; 163 } elseif ($comp == '<>') { 164 $comp = '!='; 165 } 166 167 if (!in_array($comp, self::$COMPARATORS)) 168 throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS)); 169 if ($op != 'OR' && $op != 'AND') 170 throw new StructException('Bad filter type . Only AND or OR allowed'); 171 172 $col = $this->findColumn($colname); 173 if (!$col) return; // ignore missing columns, filter might have been for different schema 174 175 // map filter operators to SQL syntax 176 switch ($comp) { 177 case '~': 178 $comp = 'LIKE'; 179 break; 180 case '!~': 181 $comp = 'NOT LIKE'; 182 break; 183 case '=*': 184 $comp = 'REGEXP'; 185 break; 186 } 187 188 // we use asterisks, but SQL wants percents 189 if ($comp == 'LIKE' || $comp == 'NOT LIKE') { 190 $value = $this->filterChangeToLike($value); 191 } 192 193 if ($comp == ' IN ' && !is_array($value)) { 194 $value = $this->parseFilterValueList($value); 195 //col IN ('a', 'b', 'c') is equal to col = 'a' OR 'col = 'b' OR col = 'c' 196 $comp = '='; 197 } 198 199 // add the filter 200 $this->filter[] = array($col, $value, $comp, $op); 201 } 202 203 /** 204 * Parse SQLite row value into array 205 * 206 * @param string $value 207 * @return string[] 208 */ 209 protected function parseFilterValueList($value) 210 { 211 $Handler = new FilterValueListHandler(); 212 $LexerClass = class_exists('\Doku_Lexer') ? '\Doku_Lexer' : '\dokuwiki\Parsing\Lexer\Lexer'; 213 $isLegacy = $LexerClass === '\Doku_Lexer'; 214 /** @var \Doku_Lexer|\dokuwiki\Parsing\Lexer\Lexer $Lexer */ 215 $Lexer = new $LexerClass($Handler, 'base', true); 216 217 218 $Lexer->addEntryPattern('\(', 'base', 'row'); 219 $Lexer->addPattern('\s*,\s*', 'row'); 220 $Lexer->addExitPattern('\)', 'row'); 221 222 $Lexer->addEntryPattern('"', 'row', 'double_quote_string'); 223 $Lexer->addSpecialPattern('\\\\"', 'double_quote_string', 'escapeSequence'); 224 $Lexer->addExitPattern('"', 'double_quote_string'); 225 226 $Lexer->addEntryPattern("'", 'row', 'singleQuoteString'); 227 $Lexer->addSpecialPattern("\\\\'", 'singleQuoteString', 'escapeSequence'); 228 $Lexer->addExitPattern("'", 'singleQuoteString'); 229 230 $Lexer->mapHandler('double_quote_string', 'singleQuoteString'); 231 232 $Lexer->addSpecialPattern('[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?', 'row', 'number'); 233 234 $res = $Lexer->parse($value); 235 236 $currentMode = $isLegacy ? $Lexer->_mode->getCurrent() : $Lexer->getModeStack()->getCurrent(); 237 if (!$res || $currentMode != 'base') { 238 throw new StructException('invalid row value syntax'); 239 } 240 241 return $Handler->getRow(); 242 } 243 244 /** 245 * Wrap given value in asterisks 246 * 247 * @param string|string[] $value 248 * @return string|string[] 249 */ 250 protected function filterWrapAsterisks($value) 251 { 252 $map = function ($input) { 253 return "*$input*"; 254 }; 255 256 if (is_array($value)) { 257 $value = array_map($map, $value); 258 } else { 259 $value = $map($value); 260 } 261 return $value; 262 } 263 264 /** 265 * Change given string to use % instead of * 266 * 267 * @param string|string[] $value 268 * @return string|string[] 269 */ 270 protected function filterChangeToLike($value) 271 { 272 $map = function ($input) { 273 return str_replace('*', '%', $input); 274 }; 275 276 if (is_array($value)) { 277 $value = array_map($map, $value); 278 } else { 279 $value = $map($value); 280 } 281 return $value; 282 } 283 284 /** 285 * Set offset for the results 286 * 287 * @param int $offset 288 */ 289 public function setOffset($offset) 290 { 291 $limit = 0; 292 if ($this->range_end) { 293 // if there was a limit set previously, the range_end needs to be recalculated 294 $limit = $this->range_end - $this->range_begin; 295 } 296 $this->range_begin = $offset; 297 if ($limit) $this->setLimit($limit); 298 } 299 300 /** 301 * Limit results to this number 302 * 303 * @param int $limit Set to 0 to disable limit again 304 */ 305 public function setLimit($limit) 306 { 307 if ($limit) { 308 $this->range_end = $this->range_begin + $limit; 309 } else { 310 $this->range_end = 0; 311 } 312 } 313 314 /** 315 * Return the number of results (regardless of limit and offset settings) 316 * 317 * Use this to implement paging. Important: this may only be called after running @return int 318 * @see execute() 319 * 320 */ 321 public function getCount() 322 { 323 if ($this->count < 0) throw new StructException('Count is only accessible after executing the search'); 324 return $this->count; 325 } 326 327 /** 328 * Returns the PID associated with each result row 329 * 330 * Important: this may only be called after running @return \string[] 331 * @see execute() 332 * 333 */ 334 public function getPids() 335 { 336 if ($this->result_pids === null) 337 throw new StructException('PIDs are only accessible after executing the search'); 338 return $this->result_pids; 339 } 340 341 /** 342 * Returns the rid associated with each result row 343 * 344 * Important: this may only be called after running @return array 345 * @see execute() 346 * 347 */ 348 public function getRids() 349 { 350 if ($this->result_rids === null) 351 throw new StructException('rids are only accessible after executing the search'); 352 return $this->result_rids; 353 } 354 355 /** 356 * Returns the rid associated with each result row 357 * 358 * Important: this may only be called after running @return array 359 * @see execute() 360 * 361 */ 362 public function getRevs() 363 { 364 if ($this->result_revs === null) 365 throw new StructException('revs are only accessible after executing the search'); 366 return $this->result_revs; 367 } 368 369 /** 370 * Execute this search and return the result 371 * 372 * The result is a two dimensional array of Value()s. 373 * 374 * This will always query for the full result (not using offset and limit) and then 375 * return the wanted range, setting the count (@return Value[][] 376 * @see getCount) to the whole result number 377 * 378 */ 379 public function execute() 380 { 381 list($sql, $opts) = $this->getSQL(); 382 383 /** @var \PDOStatement $res */ 384 $res = $this->sqlite->query($sql, $opts); 385 if ($res === false) throw new StructException("SQL execution failed for\n\n$sql"); 386 387 $this->result_pids = array(); 388 $result = array(); 389 $cursor = -1; 390 $pageidAndRevOnly = array_reduce($this->columns, function ($pageidAndRevOnly, Column $col) { 391 return $pageidAndRevOnly && ($col->getTid() == 0); 392 }, true); 393 while ($row = $res->fetch(\PDO::FETCH_ASSOC)) { 394 $cursor++; 395 if ($cursor < $this->range_begin) continue; 396 if ($this->range_end && $cursor >= $this->range_end) continue; 397 398 $C = 0; 399 $resrow = array(); 400 $isempty = true; 401 foreach ($this->columns as $col) { 402 $val = $row["C$C"]; 403 if ($col->isMulti()) { 404 $val = explode(self::CONCAT_SEPARATOR, $val); 405 } 406 $value = new Value($col, $val); 407 $isempty &= $this->isEmptyValue($value); 408 $resrow[] = $value; 409 $C++; 410 } 411 412 // skip empty rows 413 if ($isempty && !$pageidAndRevOnly) { 414 $cursor--; 415 continue; 416 } 417 418 $this->result_pids[] = $row['PID']; 419 $this->result_rids[] = $row['rid']; 420 $this->result_revs[] = $row['rev']; 421 $result[] = $resrow; 422 } 423 424 $this->sqlite->res_close($res); 425 $this->count = $cursor + 1; 426 return $result; 427 } 428 429 /** 430 * Transform the set search parameters into a statement 431 * 432 * @return array ($sql, $opts) The SQL and parameters to execute 433 */ 434 public function getSQL() 435 { 436 if (!$this->columns) throw new StructException('nocolname'); 437 438 $QB = new QueryBuilder(); 439 440 // basic tables 441 $first_table = ''; 442 foreach ($this->schemas as $schema) { 443 $datatable = 'data_' . $schema->getTable(); 444 if ($first_table) { 445 // follow up tables 446 $QB->addLeftJoin($first_table, $datatable, $datatable, "$first_table.pid = $datatable.pid"); 447 } else { 448 // first table 449 $QB->addTable($datatable); 450 451 // add conditional page clauses if pid has a value 452 $subAnd = $QB->filters()->whereSubAnd(); 453 $subAnd->whereAnd("$datatable.pid = ''"); 454 $subOr = $subAnd->whereSubOr(); 455 $subOr->whereAnd("GETACCESSLEVEL($datatable.pid) > 0"); 456 $subOr->whereAnd("PAGEEXISTS($datatable.pid) = 1"); 457 $subOr->whereAnd('(ASSIGNED = 1 OR ASSIGNED IS NULL)'); 458 459 // add conditional schema assignment check 460 $QB->addLeftJoin( 461 $datatable, 462 'schema_assignments', 463 '', 464 "$datatable.pid != '' 465 AND $datatable.pid = schema_assignments.pid 466 AND schema_assignments.tbl = '{$schema->getTable()}'" 467 ); 468 469 $QB->addSelectColumn($datatable, 'rid'); 470 $QB->addSelectColumn($datatable, 'pid', 'PID'); 471 $QB->addSelectColumn($datatable, 'rev'); 472 $QB->addSelectColumn('schema_assignments', 'assigned', 'ASSIGNED'); 473 $QB->addGroupByColumn($datatable, 'pid'); 474 $QB->addGroupByColumn($datatable, 'rid'); 475 476 $first_table = $datatable; 477 } 478 // phpcs:ignore 479 $QB->filters()->whereAnd("( (IS_PUBLISHER($datatable.pid) AND $datatable.latest = 1) OR (IS_PUBLISHER($datatable.pid) !=1 AND $datatable.published = 1) )"); 480 } 481 482 // columns to select, handling multis 483 $sep = self::CONCAT_SEPARATOR; 484 $n = 0; 485 foreach ($this->columns as $col) { 486 $CN = 'C' . $n++; 487 488 if ($col->isMulti()) { 489 $datatable = "data_{$col->getTable()}"; 490 $multitable = "multi_{$col->getTable()}"; 491 $MN = $QB->generateTableAlias('M'); 492 493 $QB->addLeftJoin( 494 $datatable, 495 $multitable, 496 $MN, 497 "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND 498 $datatable.rev = $MN.rev AND 499 $MN.colref = {$col->getColref()}" 500 ); 501 502 $col->getType()->select($QB, $MN, 'value', $CN); 503 $sel = $QB->getSelectStatement($CN); 504 $QB->addSelectStatement("GROUP_CONCAT($sel, '$sep')", $CN); 505 } else { 506 $col->getType()->select($QB, 'data_' . $col->getTable(), $col->getColName(), $CN); 507 $QB->addGroupByStatement($CN); 508 } 509 } 510 511 // where clauses 512 if (!empty($this->filter)) { 513 $userWHERE = $QB->filters()->where('AND'); 514 } 515 foreach ($this->filter as $filter) { 516 /** @var Column $col */ 517 list($col, $value, $comp, $op) = $filter; 518 519 $datatable = "data_{$col->getTable()}"; 520 $multitable = "multi_{$col->getTable()}"; 521 522 /** @var $col Column */ 523 if ($col->isMulti()) { 524 $MN = $QB->generateTableAlias('MN'); 525 526 $QB->addLeftJoin( 527 $datatable, 528 $multitable, 529 $MN, 530 "$datatable.pid = $MN.pid AND $datatable.rid = $MN.rid AND 531 $datatable.rev = $MN.rev AND 532 $MN.colref = {$col->getColref()}" 533 ); 534 $coltbl = $MN; 535 $colnam = 'value'; 536 } else { 537 $coltbl = $datatable; 538 $colnam = $col->getColName(); 539 } 540 541 $col->getType()->filter($userWHERE, $coltbl, $colnam, $comp, $value, $op); // type based filter 542 } 543 544 // sorting - we always sort by the single val column 545 foreach ($this->sortby as $sort) { 546 list($col, $asc, $nc) = $sort; 547 /** @var $col Column */ 548 $colname = $col->getColName(false); 549 if ($nc) $colname .= ' COLLATE NOCASE'; 550 $col->getType()->sort($QB, 'data_' . $col->getTable(), $colname, $asc ? 'ASC' : 'DESC'); 551 } 552 553 return $QB->getSQL(); 554 } 555 556 /** 557 * Returns all the columns that where added to the search 558 * 559 * @return Column[] 560 */ 561 public function getColumns() 562 { 563 return $this->columns; 564 } 565 566 /** 567 * All the schemas currently added 568 * 569 * @return Schema[] 570 */ 571 public function getSchemas() 572 { 573 return array_values($this->schemas); 574 } 575 576 /** 577 * Checks if the given column is a * wildcard 578 * 579 * If it's a wildcard all matching columns are added to the column list, otherwise 580 * nothing happens 581 * 582 * @param string $colname 583 * @return bool was wildcard? 584 */ 585 protected function processWildcard($colname) 586 { 587 list($colname, $table) = $this->resolveColumn($colname); 588 if ($colname !== '*') return false; 589 590 // no table given? assume the first is meant 591 if ($table === null) { 592 $schema_list = array_keys($this->schemas); 593 $table = $schema_list[0]; 594 } 595 596 $schema = $this->schemas[$table] ?? null; 597 if (!$schema) return false; 598 $this->columns = array_merge($this->columns, $schema->getColumns(false)); 599 return true; 600 } 601 602 /** 603 * Split a given column name into table and column 604 * 605 * Handles Aliases. Table might be null if none given. 606 * 607 * @param $colname 608 * @return array (colname, table) 609 */ 610 protected function resolveColumn($colname) 611 { 612 if (!$this->schemas) throw new StructException('noschemas'); 613 614 // resolve the alias or table name 615 @list($table, $colname) = array_pad(explode('.', $colname, 2), 2, ''); 616 if (!$colname) { 617 $colname = $table; 618 $table = null; 619 } 620 if ($table && isset($this->aliases[$table])) { 621 $table = $this->aliases[$table]; 622 } 623 624 if (!$colname) throw new StructException('nocolname'); 625 626 return array($colname, $table); 627 } 628 629 /** 630 * Find a column to be used in the search 631 * 632 * @param string $colname may contain an alias 633 * @return bool|Column 634 */ 635 public function findColumn($colname, $strict = false) 636 { 637 if (!$this->schemas) throw new StructException('noschemas'); 638 $schema_list = array_keys($this->schemas); 639 640 // add "fake" column for special col 641 if ($colname == '%pageid%') { 642 return new PageColumn(0, new Page(), $schema_list[0]); 643 } 644 if ($colname == '%title%') { 645 return new PageColumn(0, new Page(array('usetitles' => true)), $schema_list[0]); 646 } 647 if ($colname == '%lastupdate%') { 648 return new RevisionColumn(0, new DateTime(), $schema_list[0]); 649 } 650 if ($colname == '%lasteditor%') { 651 return new UserColumn(0, new User(), $schema_list[0]); 652 } 653 if ($colname == '%lastsummary%') { 654 return new SummaryColumn(0, new AutoSummary(), $schema_list[0]); 655 } 656 if ($colname == '%rowid%') { 657 return new RowColumn(0, new Decimal(), $schema_list[0]); 658 } 659 if ($colname == '%published%') { 660 return new PublishedColumn(0, new Decimal(), $schema_list[0]); 661 } 662 663 list($colname, $table) = $this->resolveColumn($colname); 664 665 /* 666 * If table name is given search only that, otherwise if no strict behavior 667 * is requested by the caller, try all assigned schemas for matching the 668 * column name. 669 */ 670 if ($table !== null && isset($this->schemas[$table])) { 671 $schemas = array($table => $this->schemas[$table]); 672 } elseif ($table === null || !$strict) { 673 $schemas = $this->schemas; 674 } else { 675 return false; 676 } 677 678 // find it 679 $col = false; 680 foreach ($schemas as $schema) { 681 if (empty($schema)) { 682 continue; 683 } 684 $col = $schema->findColumn($colname); 685 if ($col) break; 686 } 687 688 return $col; 689 } 690 691 /** 692 * Check if the given row is empty or references our own row 693 * 694 * @param Value $value 695 * @return bool 696 */ 697 protected function isEmptyValue(Value $value) 698 { 699 if ($value->isEmpty()) return true; 700 if ($value->getColumn()->getTid() == 0) return true; 701 return false; 702 } 703} 704