<?php
Class Search {
	var $tables=array();
	var $keywords="";
	var $start;
	var $page_count;
	var $count=0;
	var $reg="";
	var $res;

	function Search($keywords="") {
		$this->keywords=$keywords;
		$this->reg=$this->get_regular($keywords);
	}

	function get_regular($keywords) {
		function not_empty($val) {
			return (trim($val));
		}
		$keywords=strtolower(trim(strip_tags($keywords)));
		preg_match_all("/\"([^\"]+)\"/", $keywords, $st);
		$keywords=preg_replace("/(\"[^\"]+\")/", "", $keywords);
		$words=preg_split("/[^\w\d]+/", $keywords, -1, PREG_SPLIT_NO_EMPTY);
		$res=implode("|", array_filter(array_merge($st[1], $words), "not_empty"));
		return (!$res ? "" : ".*($res).*");
	}

	function add_table($table="", $fields="", $order_by="") {
		$this->tables[$table]["fields"]=explode(", ", $fields);
		$this->tables[$table]["order_by"]=$order_by;
	}

	function create_where($table) {
		$where="";
		for ($i=0; $i<count($this->tables[$table]["fields"]); $i++) $where.=($where ? " or " : "").$this->tables[$table]["fields"][$i]." REGEXP '".$this->reg."'";
		$where=($where ? "where $where" : "");
		return $where;
	}

	function get($start=0, $count=10) {
		global $db;
		$this->start=$start;
		$this->page_count=$count;
		$this->count=0;
		reset($this->tables);
		while ($table=key($this->tables)) {
			$where=$this->create_where($table);
			$c=get_val($table, "count(*)", $where);
			if ($this->page_count) {
				if ($this->start<$c) {
					$sql="select * from $table $where ".($this->tables[$table]["order_by"] ? "order by ".$this->tables[$table]["order_by"] : "")." limit ".$this->start.", ".$this->page_count;
					$rs=$db->execute($sql);
					while ($row=$db->get_row($rs)) {
						$row["table"]=$table;
						$this->res[]=$row;
						$this->page_count--;
					}
					$this->start=0;
				} else {
					$this->start-=$c;
				}
			}
			$this->count+=$c;
			next($this->tables);			
		}
		return $this->res;
	}

	function get_count() {
		global $db;
		$this->count=0;
		reset($this->tables);
		while ($table=key($this->tables)) {
			$where=$this->create_where($table);
			$c=get_val($table, "count(*)", $where);
			$this->count+=$c;
			next($this->tables);			
		}
		return $this->count;
	}
}
?>