1<?php 2 3namespace plugin\struct\meta; 4 5use 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 /** @var bool only distinct data? */ 48 protected $distinct = false; 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 $value 116 * @param string $comp @see self::COMPARATORS 117 * @param string $type either 'OR' or 'AND' 118 */ 119 public function addFilter($colname, $value, $comp, $type = 'OR') { 120 if(!in_array($comp, self::$COMPARATORS)) throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS)); 121 if($type != 'OR' && $type != 'AND') throw new StructException('Bad filter type . Only AND or OR allowed'); 122 123 $col = $this->findColumn($colname); 124 if(!$col) return; //FIXME do we really want to ignore missing columns? 125 $value = str_replace('*','%',$value); 126 $this->filter[] = array($col, $value, $comp, $type); 127 } 128 129 /** 130 * Set offset for the results 131 * 132 * @param int $offset 133 */ 134 public function setOffset($offset) { 135 $limit = 0; 136 if($this->range_end) { 137 // if there was a limit set previously, the range_end needs to be recalculated 138 $limit = $this->range_end - $this->range_begin; 139 } 140 $this->range_begin = $offset; 141 if($limit) $this->setLimit($limit); 142 } 143 144 /** 145 * Limit results to this number 146 * 147 * @param int $limit Set to 0 to disable limit again 148 */ 149 public function setLimit($limit) { 150 if($limit) { 151 $this->range_end = $this->range_begin + $limit; 152 } else { 153 $this->range_end = 0; 154 } 155 } 156 157 /** 158 * Request distinct data only, no PID column 159 * 160 * @param boolean $distinct 161 */ 162 public function setDistinct($distinct) { 163 $this->distinct = $distinct; 164 } 165 166 /** 167 * Return the number of results (regardless of limit and offset settings) 168 * 169 * Use this to implement paging. Important: this may only be called after running @see execute() 170 * 171 * @return int 172 */ 173 public function getCount() { 174 if($this->count < 0) throw new StructException('Count is only accessible after executing the search'); 175 return $this->count; 176 } 177 178 /** 179 * Execute this search and return the result 180 * 181 * The result is a two dimensional array of Value()s. 182 * 183 * This will always query for the full result (not using offset and limit) and then 184 * return the wanted range, setting the count (@see getCount) to the whole result number 185 * 186 * @return Value[][] 187 */ 188 public function execute() { 189 list($sql, $opts) = $this->getSQL(); 190 191 /** @var \PDOStatement $res */ 192 $res = $this->sqlite->query($sql, $opts); 193 194 $result = array(); 195 $cursor = -1; 196 while($row = $res->fetch(\PDO::FETCH_ASSOC)) { 197 $cursor++; 198 if($cursor < $this->range_begin) continue; 199 if($this->range_end && $cursor >= $this->range_end) continue; 200 201 $C = 0; 202 $resrow = array(); 203 foreach($this->columns as $col) { 204 $val = $row["C$C"]; 205 if($col->isMulti()) { 206 $val = explode(self::CONCAT_SEPARATOR, $val); 207 } 208 $resrow[] = new Value($col, $val); 209 $C++; 210 } 211 $result[] = $resrow; 212 } 213 214 $this->sqlite->res_close($res); 215 $this->count = $cursor + 1; 216 return $result; 217 } 218 219 /** 220 * Transform the set search parameters into a statement 221 * 222 * @return array ($sql, $opts) The SQL and parameters to execute 223 */ 224 public function getSQL() { 225 if(!$this->columns) throw new StructException('nocolname'); 226 227 $from = ''; 228 $select = ''; 229 $order = ''; 230 $grouping = array(); 231 $opts = array(); 232 $where = '1 = 1'; 233 $fwhere = ''; 234 235 // basic tables 236 $first = ''; 237 foreach($this->schemas as $schema) { 238 if($first) { 239 // follow up tables 240 $from .= "\nLEFT OUTER JOIN data_{$schema->getTable()} ON data_$first.pid = data_{$schema->getTable()}.pid"; 241 } else { 242 // first table 243 if($this->distinct) { 244 $select .= 'DISTINCT '; 245 } else { 246 $select .= "data_{$schema->getTable()}.pid as PID, "; 247 } 248 249 $from .= 'schema_assignments, '; 250 $where .= "\nAND data_{$schema->getTable()}.pid = schema_assignments.pid"; 251 $where .= "\nAND schema_assignments.assigned = 1"; 252 253 $from .= "data_{$schema->getTable()}"; 254 $where .= "\nAND GETACCESSLEVEL(data_{$schema->getTable()}.pid) > 0"; 255 $first = $schema->getTable(); 256 } 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 304 foreach($this->sortby as $sort) { 305 list($col, $asc) = $sort; 306 307 /** @var $col Column */ 308 if($col->isMulti()) { 309 // FIXME how to sort by multival? 310 // FIXME what if sort by non merged multival? 311 } else { 312 $order .= $col->getColName() . ' '; 313 $order .= ($asc) ? 'ASC' : 'DESC'; 314 $order .= ', '; 315 } 316 } 317 $order = rtrim($order, ', '); 318 319 $fwhere = trim($fwhere); 320 if($fwhere) { 321 $fwhere = "AND ($fwhere\n)"; 322 } 323 324 $sql = "SELECT $select\n FROM $from\nWHERE $where\n$fwhere\nGROUP BY " . join(', ', $grouping); 325 if($order) $sql .= "\nORDER BY $order"; 326 327 return array($sql, $opts); 328 } 329 330 /** 331 * Returns all the columns that where added to the search 332 * 333 * @return Column[] 334 */ 335 public function getColumns() { 336 return $this->columns; 337 } 338 339 340 /** 341 * Find a column to be used in the search 342 * 343 * @param string $colname may contain an alias 344 * @return bool|Column 345 */ 346 public function findColumn($colname) { 347 if(!$this->schemas) throw new StructException('noschemas'); 348 349 // handling of page column is special 350 if($colname == '%pageid%') { 351 $schema_list = array_keys($this->schemas); 352 return new PageColumn(0, new Page(), array_shift($schema_list)); 353 } 354 // FIXME %title% needs to be handled here, too (later) 355 356 // resolve the alias or table name 357 list($table, $colname) = explode('.', $colname, 2); 358 if(!$colname) { 359 $colname = $table; 360 $table = ''; 361 } 362 if($table && isset($this->aliases[$table])) { 363 $table = $this->aliases[$table]; 364 } 365 366 if(!$colname) throw new StructException('nocolname'); 367 368 // if table name given search only that, otherwiese try all for matching column name 369 if($table) { 370 $schemas = array($table => $this->schemas[$table]); 371 } else { 372 $schemas = $this->schemas; 373 } 374 375 // find it 376 $col = false; 377 foreach($schemas as $schema) { 378 $col = $schema->findColumn($colname); 379 if($col) break; 380 } 381 382 return $col; 383 } 384 385} 386 387 388