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