1<?php 2 3namespace dokuwiki\plugin\struct\meta; 4 5use dokuwiki\plugin\struct\types\Date; 6use dokuwiki\plugin\struct\types\DateTime; 7use dokuwiki\plugin\struct\types\Page; 8 9class Search { 10 /** 11 * This separator will be used to concat multi values to flatten them in the result set 12 */ 13 const CONCAT_SEPARATOR = "\n!_-_-_-_-_!\n"; 14 15 /** 16 * The list of known and allowed comparators 17 * (order matters) 18 */ 19 static public $COMPARATORS = array( 20 '<=', '>=', '=*', '=', '<', '>', '!=', '!~', '~', 21 ); 22 23 /** @var \helper_plugin_sqlite */ 24 protected $sqlite; 25 26 /** @var Schema[] list of schemas to query */ 27 protected $schemas = array(); 28 29 /** @var Column[] list of columns to select */ 30 protected $columns = array(); 31 32 /** @var array the sorting of the result */ 33 protected $sortby = array(); 34 35 /** @var array the filters */ 36 protected $filter = array(); 37 38 /** @var array list of aliases tables can be referenced by */ 39 protected $aliases = array(); 40 41 /** @var int begin results from here */ 42 protected $range_begin = 0; 43 44 /** @var int end results here */ 45 protected $range_end = 0; 46 47 /** @var int the number of results */ 48 protected $count = -1; 49 50 /** 51 * Search constructor. 52 */ 53 public function __construct() { 54 /** @var \helper_plugin_struct_db $plugin */ 55 $plugin = plugin_load('helper', 'struct_db'); 56 $this->sqlite = $plugin->getDB(); 57 } 58 59 /** 60 * Add a schema to be searched 61 * 62 * Call multiple times for multiple schemas. 63 * 64 * @param string $table 65 * @param string $alias 66 */ 67 public function addSchema($table, $alias = '') { 68 $this->schemas[$table] = new Schema($table); 69 if($alias) $this->aliases[$alias] = $table; 70 } 71 72 /** 73 * Add a column to be returned by the search 74 * 75 * Call multiple times for multiple columns. Be sure the referenced tables have been 76 * added before 77 * 78 * @param string $colname may contain an alias 79 */ 80 public function addColumn($colname) { 81 $col = $this->findColumn($colname); 82 if(!$col) return; //FIXME do we really want to ignore missing columns? 83 $this->columns[] = $col; 84 } 85 86 /** 87 * Add sorting options 88 * 89 * Call multiple times for multiple columns. Be sure the referenced tables have been 90 * added before 91 * 92 * @param string $colname may contain an alias 93 * @param bool $asc sort direction (ASC = true, DESC = false) 94 */ 95 public function addSort($colname, $asc = true) { 96 $col = $this->findColumn($colname); 97 if(!$col) return; //FIXME do we really want to ignore missing columns? 98 99 $this->sortby[$col->getFullQualifiedLabel()] = array($col, $asc); 100 } 101 102 /** 103 * Returns all set sort columns 104 * 105 * @return array 106 */ 107 public function getSorts() { 108 return $this->sortby; 109 } 110 111 /** 112 * Adds a filter 113 * 114 * @param string $colname may contain an alias 115 * @param string|string[] $value 116 * @param string $comp @see self::COMPARATORS 117 * @param string $op either 'OR' or 'AND' 118 */ 119 public function addFilter($colname, $value, $comp, $op = 'OR') { 120 /* Convert certain filters into others 121 * this reduces the number of supported filters to implement in types */ 122 if ($comp == '*~') { 123 $value = $this->filterWrapAsterisks($value); 124 $comp = '~'; 125 } elseif ($comp == '<>') { 126 $comp = '!='; 127 } 128 129 if(!in_array($comp, self::$COMPARATORS)) throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS)); 130 if($op != 'OR' && $op != 'AND') throw new StructException('Bad filter type . Only AND or OR allowed'); 131 132 $col = $this->findColumn($colname); 133 if(!$col) return; // ignore missing columns, filter might have been for different schema 134 135 // map filter operators to SQL syntax 136 switch($comp) { 137 case '~': 138 $comp = 'LIKE'; 139 break; 140 case '!~': 141 $comp = 'NOT LIKE'; 142 break; 143 case '=*': 144 $comp = 'REGEXP'; 145 break; 146 } 147 148 // we use asterisks, but SQL wants percents 149 if($comp == 'LIKE' || $comp == 'NOT LIKE') { 150 $value = $this->filterChangeToLike($value); 151 } 152 153 // add the filter 154 $this->filter[] = array($col, $value, $comp, $op); 155 } 156 157 /** 158 * Wrap given value in asterisks 159 * 160 * @param string|string[] $value 161 * @return string|string[] 162 */ 163 protected function filterWrapAsterisks($value) { 164 $map = function ($input) { 165 return "*$input*"; 166 }; 167 168 if(is_array($value)) { 169 $value = array_map($map, $value); 170 } else { 171 $value = $map($value); 172 } 173 return $value; 174 } 175 176 /** 177 * Change given string to use % instead of * 178 * 179 * @param string|string[] $value 180 * @return string|string[] 181 */ 182 protected function filterChangeToLike($value) { 183 $map = function ($input) { 184 return str_replace('*','%',$input); 185 }; 186 187 if(is_array($value)) { 188 $value = array_map($map, $value); 189 } else { 190 $value = $map($value); 191 } 192 return $value; 193 } 194 195 196 /** 197 * Set offset for the results 198 * 199 * @param int $offset 200 */ 201 public function setOffset($offset) { 202 $limit = 0; 203 if($this->range_end) { 204 // if there was a limit set previously, the range_end needs to be recalculated 205 $limit = $this->range_end - $this->range_begin; 206 } 207 $this->range_begin = $offset; 208 if($limit) $this->setLimit($limit); 209 } 210 211 /** 212 * Limit results to this number 213 * 214 * @param int $limit Set to 0 to disable limit again 215 */ 216 public function setLimit($limit) { 217 if($limit) { 218 $this->range_end = $this->range_begin + $limit; 219 } else { 220 $this->range_end = 0; 221 } 222 } 223 224 /** 225 * Return the number of results (regardless of limit and offset settings) 226 * 227 * Use this to implement paging. Important: this may only be called after running @see execute() 228 * 229 * @return int 230 */ 231 public function getCount() { 232 if($this->count < 0) throw new StructException('Count is only accessible after executing the search'); 233 return $this->count; 234 } 235 236 /** 237 * Execute this search and return the result 238 * 239 * The result is a two dimensional array of Value()s. 240 * 241 * This will always query for the full result (not using offset and limit) and then 242 * return the wanted range, setting the count (@see getCount) to the whole result number 243 * 244 * @return Value[][] 245 */ 246 public function execute() { 247 list($sql, $opts) = $this->getSQL(); 248 249 /** @var \PDOStatement $res */ 250 $res = $this->sqlite->query($sql, $opts); 251 if($res === false) throw new StructException("SQL execution failed for\n\n$sql"); 252 253 $result = array(); 254 $cursor = -1; 255 while($row = $res->fetch(\PDO::FETCH_ASSOC)) { 256 if ($this->isRowEmpty($row)) { 257 continue; 258 } 259 $cursor++; 260 if($cursor < $this->range_begin) continue; 261 if($this->range_end && $cursor >= $this->range_end) continue; 262 263 $C = 0; 264 $resrow = array(); 265 foreach($this->columns as $col) { 266 $val = $row["C$C"]; 267 if($col->isMulti()) { 268 $val = explode(self::CONCAT_SEPARATOR, $val); 269 } 270 $resrow[] = new Value($col, $val); 271 $C++; 272 } 273 $result[] = $resrow; 274 } 275 276 $this->sqlite->res_close($res); 277 $this->count = $cursor + 1; 278 return $result; 279 } 280 281 /** 282 * Transform the set search parameters into a statement 283 * 284 * @return array ($sql, $opts) The SQL and parameters to execute 285 */ 286 public function getSQL() { 287 if(!$this->columns) throw new StructException('nocolname'); 288 289 $QB = new QueryBuilder(); 290 291 // basic tables 292 $first_table = ''; 293 foreach($this->schemas as $schema) { 294 $datatable = 'data_'.$schema->getTable(); 295 if($first_table) { 296 // follow up tables 297 $QB->addLeftJoin($first_table, $datatable, $datatable, "$first_table.pid = $datatable.pid"); 298 } else { 299 // first table 300 $QB->addTable('schema_assignments'); 301 $QB->addTable($datatable); 302 $QB->addSelectColumn($datatable, 'pid', 'PID'); 303 $QB->addGroupByColumn($datatable, 'pid'); 304 305 $QB->filters()->whereAnd("$datatable.pid = schema_assignments.pid"); 306 $QB->filters()->whereAnd("schema_assignments.tbl = '{$schema->getTable()}'"); 307 $QB->filters()->whereAnd("schema_assignments.assigned = 1"); 308 $QB->filters()->whereAnd("GETACCESSLEVEL($datatable.pid) > 0"); 309 $QB->filters()->whereAnd("PAGEEXISTS($datatable.pid) = 1"); 310 311 $first_table = $datatable; 312 } 313 $QB->filters()->whereAnd("$datatable.latest = 1"); 314 } 315 316 // columns to select, handling multis 317 $sep = self::CONCAT_SEPARATOR; 318 $n = 0; 319 foreach($this->columns as $col) { 320 $CN = 'C' . $n++; 321 322 if($col->isMulti()) { 323 $datatable = "data_{$col->getTable()}"; 324 $multitable = "multi_{$col->getTable()}"; 325 $MN = 'M' . $col->getColref(); 326 327 $QB->addLeftJoin( 328 $datatable, 329 $multitable, 330 $MN, 331 "$datatable.pid = $MN.pid AND 332 $datatable.rev = $MN.rev AND 333 $MN.colref = {$col->getColref()}" 334 ); 335 336 $col->getType()->select($QB, $MN, 'value' , $CN); 337 $sel = $QB->getSelectStatement($CN); 338 $QB->addSelectStatement("GROUP_CONCAT($sel, '$sep')", $CN); 339 } else { 340 $col->getType()->select($QB, 'data_'.$col->getTable(), $col->getColName() , $CN); 341 $QB->addGroupByStatement($CN); 342 } 343 } 344 345 // where clauses 346 foreach($this->filter as $filter) { 347 list($col, $value, $comp, $op) = $filter; 348 349 $datatable = "data_{$col->getTable()}"; 350 $multitable = "multi_{$col->getTable()}"; 351 352 /** @var $col Column */ 353 if($col->isMulti()) { 354 $MN = 'MN' . $col->getColref(); // FIXME this joins a second time if the column was selected before 355 356 $QB->addLeftJoin( 357 $datatable, 358 $multitable, 359 $MN, 360 "$datatable.pid = $MN.pid AND 361 $datatable.rev = $MN.rev AND 362 $MN.colref = {$col->getColref()}" 363 ); 364 $coltbl = $MN; 365 $colnam = 'value'; 366 } else { 367 $coltbl = $datatable; 368 $colnam = $col->getColName(); 369 } 370 371 $col->getType()->filter($QB, $coltbl, $colnam, $comp, $value, $op); // type based filter 372 } 373 374 // sorting - we always sort by the single val column 375 foreach($this->sortby as $sort) { 376 list($col, $asc) = $sort; 377 /** @var $col Column */ 378 $QB->addOrderBy($col->getFullColName(false) . ' '.(($asc) ? 'ASC' : 'DESC')); 379 } 380 381 return $QB->getSQL(); 382 } 383 384 /** 385 * Returns all the columns that where added to the search 386 * 387 * @return Column[] 388 */ 389 public function getColumns() { 390 return $this->columns; 391 } 392 393 394 /** 395 * Find a column to be used in the search 396 * 397 * @param string $colname may contain an alias 398 * @return bool|Column 399 */ 400 public function findColumn($colname) { 401 if(!$this->schemas) throw new StructException('noschemas'); 402 403 // handling of page and title column is special - we add a "fake" column 404 $schema_list = array_keys($this->schemas); 405 if($colname == '%pageid%') { 406 return new PageColumn(0, new Page(), $schema_list[0]); 407 } 408 if($colname == '%title%') { 409 return new PageColumn(0, new Page(array('usetitles' => true)), $schema_list[0]); 410 } 411 if($colname == '%lastupdate%') { 412 return new RevisionColumn(0, new DateTime(), $schema_list[0]); 413 } 414 415 // resolve the alias or table name 416 list($table, $colname) = explode('.', $colname, 2); 417 if(!$colname) { 418 $colname = $table; 419 $table = ''; 420 } 421 if($table && isset($this->aliases[$table])) { 422 $table = $this->aliases[$table]; 423 } 424 425 if(!$colname) throw new StructException('nocolname'); 426 427 // if table name given search only that, otherwise try all for matching column name 428 if($table) { 429 $schemas = array($table => $this->schemas[$table]); 430 } else { 431 $schemas = $this->schemas; 432 } 433 434 // find it 435 $col = false; 436 foreach($schemas as $schema) { 437 if(empty($schema)) { 438 continue; 439 } 440 $col = $schema->findColumn($colname); 441 if($col) break; 442 } 443 444 return $col; 445 } 446 447 /** 448 * Check if a row is empty / only contains a reference to itself 449 * 450 * @param array $rowColumns an array as returned from the database 451 * @return bool 452 */ 453 private function isRowEmpty($rowColumns) { 454 $C = 0; 455 foreach($this->columns as $col) { 456 $val = $rowColumns["C$C"]; 457 $C += 1; 458 if (blank($val) || is_a($col->getType(),'dokuwiki\plugin\struct\types\Page') && $val == $rowColumns["PID"]) { 459 continue; 460 } 461 return false; 462 } 463 return true; 464 } 465 466} 467 468 469