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