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