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 /** 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[] = array($col, $asc); 97 } 98 99 /** 100 * Adds a filter 101 * 102 * @param string $colname may contain an alias 103 * @param string $value 104 * @param string $comp @see self::COMPARATORS 105 * @param string $type either 'OR' or 'AND' 106 */ 107 public function addFilter($colname, $value, $comp, $type = 'OR') { 108 if(!in_array($comp, self::$COMPARATORS)) throw new StructException("Bad comperator. Use " . join(',', self::$COMPARATORS)); 109 if($type != 'OR' && $type != 'AND') throw new StructException('Bad filter type . Only AND or OR allowed'); 110 111 $col = $this->findColumn($colname); 112 if(!$col) return; //FIXME do we really want to ignore missing columns? 113 $value = str_replace('*','%',$value); 114 $this->filter[] = array($col, $value, $comp, $type); 115 } 116 117 /** 118 * Set offset for the results 119 * 120 * @param int $offset 121 */ 122 public function setOffset($offset) { 123 $limit = 0; 124 if($this->range_end) { 125 // if there was a limit set previously, the range_end needs to be recalculated 126 $limit = $this->range_end - $this->range_begin; 127 } 128 $this->range_begin = $offset; 129 if($limit) $this->setLimit($limit); 130 } 131 132 /** 133 * Limit results to this number 134 * 135 * @param int $limit Set to 0 to disable limit again 136 */ 137 public function setLimit($limit) { 138 if($limit) { 139 $this->range_end = $this->range_begin + $limit; 140 } else { 141 $this->range_end = 0; 142 } 143 } 144 145 /** 146 * Return the number of results (regardless of limit and offset settings) 147 * 148 * Use this to implement paging. Important: this may only be called after running @see execute() 149 * 150 * @return int 151 */ 152 public function getCount() { 153 if($this->count < 0) throw new StructException('Count is only accessible after executing the search'); 154 return $this->count; 155 } 156 157 /** 158 * Execute this search and return the result 159 * 160 * The result is a two dimensional array of Value()s. 161 * 162 * This will always query for the full result (not using offset and limit) and then 163 * return the wanted range, setting the count (@see getCount) to the whole result number 164 * 165 * @return Value[][] 166 */ 167 public function execute() { 168 list($sql, $opts) = $this->getSQL(); 169 170 /** @var \PDOStatement $res */ 171 $res = $this->sqlite->query($sql, $opts); 172 173 $result = array(); 174 $cursor = -1; 175 while($row = $res->fetch(\PDO::FETCH_ASSOC)) { 176 $cursor++; 177 if($cursor < $this->range_begin) continue; 178 if($this->range_end && $cursor >= $this->range_end) continue; 179 180 $C = 0; 181 $resrow = array(); 182 foreach($this->columns as $col) { 183 $val = $row["C$C"]; 184 if($col->isMulti()) { 185 $val = explode(self::CONCAT_SEPARATOR, $val); 186 } 187 $resrow[] = new Value($col, $val); 188 $C++; 189 } 190 $result[] = $resrow; 191 } 192 193 $this->sqlite->res_close($res); 194 $this->count = $cursor + 1; 195 return $result; 196 } 197 198 /** 199 * Transform the set search parameters into a statement 200 * 201 * @return array ($sql, $opts) The SQL and parameters to execute 202 */ 203 public function getSQL() { 204 if(!$this->columns) throw new StructException('nocolname'); 205 206 $from = ''; 207 $select = ''; 208 $order = ''; 209 $grouping = array(); 210 $opts = array(); 211 $where = '1 = 1'; 212 213 // basic tables 214 $first = ''; 215 foreach($this->schemas as $schema) { 216 if($first) { 217 // follow up tables 218 $from .= "\nLEFT OUTER JOIN data_{$schema->getTable()} ON data_$first.pid = data_{$schema->getTable()}.pid"; 219 } else { 220 // first table 221 $select .= "data_{$schema->getTable()}.pid as PID, "; 222 223 $from .= 'schema_assignments, '; 224 $where .= "\nAND data_{$schema->getTable()}.pid = schema_assignments.pid"; 225 $where .= "\nAND schema_assignments.assigned = 1"; 226 227 $from .= "data_{$schema->getTable()}"; 228 $where .= "\nAND GETACCESSLEVEL(data_{$schema->getTable()}.pid) > 0"; 229 $first = $schema->getTable(); 230 } 231 232 $where .= "\nAND data_{$schema->getTable()}.latest = 1"; 233 } 234 235 // columns to select, handling multis 236 $sep = self::CONCAT_SEPARATOR; 237 $n = 0; 238 foreach($this->columns as $col) { 239 $CN = 'C' . $n++; 240 241 if($col->isMulti()) { 242 $tn = 'M' . $col->getColref(); 243 $select .= "GROUP_CONCAT($tn.value, '$sep') AS $CN, "; 244 $from .= "\nLEFT OUTER JOIN multi_{$col->getTable()} AS $tn"; 245 $from .= " ON data_{$col->getTable()}.pid = $tn.pid AND data_{$col->getTable()}.rev = $tn.rev"; 246 $from .= " AND $tn.colref = {$col->getColref()}\n"; 247 } else { 248 $select .= "{$col->getColName()} AS $CN, "; 249 $grouping[] = $CN; 250 } 251 } 252 $select = rtrim($select, ', '); 253 254 // where clauses 255 foreach($this->filter as $filter) { 256 list($col, $value, $comp, $type) = $filter; 257 258 /** @var $col Column */ 259 if($col->isMulti()) { 260 $tn = 'MN' . $col->getColref(); // FIXME this joins a second time if the column was selected before 261 $from .= "\nLEFT OUTER JOIN multi_{$col->getTable()} AS $tn"; 262 $from .= " ON data_{$col->getTable()}.pid = $tn.pid AND data_{$col->getTable()}.rev = $tn.rev"; 263 $from .= " AND $tn.colref = {$col->getColref()}\n"; 264 265 $column = "$tn.value"; 266 } else { 267 $column = $col->getColName(); 268 } 269 270 list($wsql, $wopt) = $col->getType()->compare($column, $comp, $value); 271 $opts = array_merge($opts, $wopt); 272 273 $where .= "\n$type $wsql"; 274 } 275 276 // sorting 277 foreach($this->sortby as $sort) { 278 list($col, $asc) = $sort; 279 280 /** @var $col Column */ 281 if($col->isMulti()) { 282 // FIXME how to sort by multival? 283 // FIXME what if sort by non merged multival? 284 } else { 285 $order .= $col->getColName() . ' '; 286 $order .= ($asc) ? 'ASC' : 'DESC'; 287 $order .= ', '; 288 } 289 } 290 $order = rtrim($order, ', '); 291 292 $sql = "SELECT $select\n FROM $from\nWHERE $where\nGROUP BY " . join(', ', $grouping); 293 if($order) $sql .= "\nORDER BY $order"; 294 295 return array($sql, $opts); 296 } 297 298 /** 299 * Returns all the columns that where added to the search 300 * 301 * @return Column[] 302 */ 303 public function getColumns() { 304 return $this->columns; 305 } 306 307 308 /** 309 * Find a column to be used in the search 310 * 311 * @param string $colname may contain an alias 312 * @return bool|Column 313 */ 314 protected function findColumn($colname) { 315 if(!$this->schemas) throw new StructException('noschemas'); 316 317 // handling of page column is special 318 if($colname == '%pageid%') { 319 $schema_list = array_keys($this->schemas); 320 return new PageColumn(0, new Page(), array_shift($schema_list)); 321 } 322 // FIXME %title% needs to be handled here, too (later) 323 324 // resolve the alias or table name 325 list($table, $colname) = explode('.', $colname, 2); 326 if(!$colname) { 327 $colname = $table; 328 $table = ''; 329 } 330 if($table && isset($this->aliases[$table])) { 331 $table = $this->aliases[$table]; 332 } 333 334 if(!$colname) throw new StructException('nocolname'); 335 336 // if table name given search only that, otherwiese try all for matching column name 337 if($table) { 338 $schemas = array($table => $this->schemas[$table]); 339 } else { 340 $schemas = $this->schemas; 341 } 342 343 // find it 344 $col = false; 345 foreach($schemas as $schema) { 346 $col = $schema->findColumn($colname); 347 if($col) break; 348 } 349 350 return $col; 351 } 352 353} 354 355 356