<?php
ob_start();
if(!(is_readable(realpath(dirname(__FILE__).'/../').'/include/includesroutines.inc'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__).'/../').'/include/includesroutines.inc');
} else {
	include_once(realpath(dirname(__FILE__).'/../').'/include/includesroutines.inc');
}

if(!(is_readable(realpath(dirname(__FILE__).'/../').'/include/pagination.inc'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__).'/../').'/include/pagination.inc');
} else {
	include_once(realpath(dirname(__FILE__).'/../').'/include/pagination.inc');
}

if(!(is_readable(realpath(dirname(__FILE__).'/../').'/classes/tree.php'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__).'/../').'/classes/tree.php');
} else {
	include_once(realpath(dirname(__FILE__).'/../').'/classes/tree.php');
}

function calcRightsToObject($cn, $ids){
	//build indexed temp rightsmap
	$q_st = "DROP TEMPORARY TABLE IF EXISTS `rightsmap_temp` ;";
	db_runQuery($cn, $q_st);
	$q_st = " CREATE TEMPORARY TABLE rightsmap_temp (
				`idobject` BIGINT NOT NULL,
				PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;
			";
	db_runQuery($cn, $q_st);
	$q_st = " ALTER TABLE `rightsmap_temp` ADD INDEX ( `idobject` ) ;";
	db_runQuery($cn, $q_st);

	//build indexed temp rigthmap to defaultsright
	$query = "DROP TEMPORARY TABLE IF EXISTS `defaultsright` ;";
	db_runQuery($cn, $query);
	$query = " CREATE TEMPORARY TABLE defaultsright (
				`idobject` BIGINT NOT NULL,
				PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;
			";
	db_runQuery($cn, $query);
	$query = " ALTER TABLE `defaultsright` ADD INDEX ( `idobject` ) ;";
	db_runQuery($cn, $query);

	$query = "INSERT IGNORE INTO `defaultsright` SELECT DISTINCT o.idobject FROM `objects` as o
				INNER JOIN `pollingobjects` as po ON o.o_guid = po.o_guid
				INNER JOIN `useranswers` as ua ON po.idpollingobject = ua.idpollingobject
                INNER JOIN `users` as u ON u.`user_hash` = ua.`user_hash` 
                WHERE ua.idpollingobjectstatus = 1
				  AND u.iduser in (".$ids.") AND o.idobject NOT IN (SELECT ro.idobject FROM  `rightsobjects` as ro WHERE  ro.deny_allow = 0);";
	db_runQuery($cn, $query);

	$query = "INSERT IGNORE INTO `defaultsright` SELECT DISTINCT o.idobject FROM `objects` as o
				INNER JOIN `pollingobjects` as po ON o.o_guid = po.o_guid
				INNER JOIN `rightspollingobjects` as rpo ON  rpo.`skpollingobject` = po.`skpollingobject`  
                WHERE rpo.iduser in (".$ids.")  AND rpo.deny_allow = 1 ;";
	db_runQuery($cn, $query);

	$q_st = "INSERT IGNORE INTO `defaultsright` SELECT o.`idobject` FROM `objects` as o INNER JOIN `users` as u ON u.`user_guid` = o.`o_guid` AND u.`iduser` IN (".$ids.") ;";
	db_runQuery($cn, $q_st);

	$q_st = "INSERT IGNORE INTO `rightsmap_temp` SELECT ro.`idobject` FROM `rightsobjects` as ro, `o_temp` as ot WHERE ot.`idobject` = ro.`idobject` AND ro.`iduser` IN (".$ids.") AND ro.`deny_allow` = 0;";
	db_runQuery($cn, $q_st);
	$q_st = "DELETE FROM `srch_temp` WHERE `srch_temp`.`idobject` IN ( SELECT `idobject` FROM `rightsmap_temp` );";
	db_runQuery($cn, $q_st);

	$q_st = "DELETE FROM `rightsmap_temp`;";
	db_runQuery($cn, $q_st);
	$q_st = "INSERT IGNORE INTO `rightsmap_temp` SELECT `idobject` FROM `defaultsright`;";
	db_runQuery($cn, $q_st);
	$q_st = "INSERT IGNORE INTO `rightsmap_temp` SELECT ro.`idobject` FROM `rightsobjects` as ro, `o_temp` as ot WHERE ot.`idobject` = ro.`idobject` AND ro.`iduser` IN (".$ids.") AND ro.`deny_allow` = 1;";
	db_runQuery($cn, $q_st);
	$q_st = "DELETE FROM `srch_temp` WHERE `srch_temp`.`idobject` NOT IN ( SELECT `idobject` FROM `rightsmap_temp` );";
	db_runQuery($cn, $q_st);

	$q_st = "DELETE FROM `rightsmap_temp`;";
	db_runQuery($cn, $q_st);
	$q_st = "INSERT IGNORE INTO `rightsmap_temp` SELECT `idobject` FROM `defaultsright`;";
	db_runQuery($cn, $q_st);
	$q_st = "INSERT IGNORE INTO `rightsmap_temp` SELECT ro.`idobject` FROM `rightsobjects` as ro, `o_temp` as ot WHERE ot.`idobject` = ro.`idobject` AND ro.`iduser` IN (".$ids.") AND ro.`deny_allow` = 2 ;";
	db_runQuery($cn, $q_st);
	$q_st = "DELETE FROM `srch_temp` WHERE `srch_temp`.`idobject` NOT IN ( SELECT `idobject` FROM `rightsmap_temp`);";
	db_runQuery($cn, $q_st);
	$query = "DROP TEMPORARY TABLE IF EXISTS `defaultsright` ;";
	db_runQuery($cn, $query);	

}

checkLanguage();
$cn = db_connect();

$lng = 'lang='.db_getLanguageShortByID($cn, $_SESSION['user_idlanguageinterface'], true);
$lngid = $_SESSION['user_idlanguageinterface'];
$contlng = 'lang='.db_getLanguageShortByID($cn, $_SESSION['user_idlanguagecontent']);
$contlngid = $_SESSION['user_idlanguagecontent'];

//Task 61628 - only main branch
$skbranch = db_getMainSKBranch($cn);
$idbranch = db_getMainIDBranch($cn);	
$mainskbranch = $skbranch;// db_getMainSKBranch($cn);
$mainlngID = db_getMainIDLanguage($cn);

$u_ids = GetUserIDs();
$url = getCurPageURL();
$hideheader = (isset($_COOKIE['hideheader']) ?  $_COOKIE['hideheader'] : 0);
$urlWO = getCurPageURLWO();
mb_internal_encoding('UTF-8');
$st = '';
function mb_str_replace($search, $replace, $string)
{
    $charset = mb_detect_encoding($string);
    $unicodeString = iconv($charset, "UTF-8", $string);
    return str_replace($search, $replace, $unicodeString);
}

if (isset($_REQUEST['search']) && strlen(trim($_REQUEST['search']))>0) {
	$st = mb_str_replace('','',$_REQUEST['search']);
	$st = mb_str_replace('','',mysqli_real_escape_string($cn, mysqli_real_escape_string($cn, trim( prepareTextToTree(mb_strtolower($st,'UTF-8'))))));
}

if (!isset($_REQUEST['searchop'])) { $_REQUEST['searchop'] = 'so_full';}
if (!isset($_REQUEST['searchin'])) { $_REQUEST['searchin'] = 's_all'; }
$ids = implode(",", $u_ids);
?>
<h2><?php getResource("title.searchResult");?></h2>
<?php
$query = "SET SQL_BIG_SELECTS=1;";
db_runQuery($cn, $query);
$q_st = "set @@tmp_table_size=2147483648";
db_runQuery($cn, $q_st);
$q_st = "set @@max_heap_table_size=2147483648";
db_runQuery($cn, $q_st);

$bq_st = ''; 
$tq_st = ''; 

$trans = array("  " => " ");
$st = strtr(strtr($st, $trans), $trans);
$hlw = explode(" ",$st);

$oper = 'AND';

$searchinalllang = isset($_REQUEST['searchinalllanguages']);
if (isset($_REQUEST['searchop'])){
	if ($_REQUEST['searchop'] == 'so_all'){
		$oper = 'AND';
	} else 	if ($_REQUEST['searchop'] == 'so_any'){
		$oper = 'OR';
	} else 	if ($_REQUEST['searchop'] == 'so_full'){
		$oper = '';
	}
}

$trans2 = array(" " => "%' ".$oper." ri.body LIKE '%");
$trans3 = array(" " => "%' ".$oper." o_title LIKE '%");
if (isset($_REQUEST['searchop']) && $_REQUEST['searchop'] == 'so_full'){
	$bq_st =  " ri.body LIKE '%".$st."%'  ";
	$tq_st =  " concat(' ',ti.o_title,' ')  LIKE '% ".$st." %'  ";
} else {
	$bq_st =  strtr($st, $trans2);
	$bq_st =  " ri.body LIKE '%".$bq_st."%'  ";

	$tq_st =  strtr($st, $trans3);
	$tq_st =  " ti.o_title LIKE '%".$tq_st."%' ";

	if ($_REQUEST['searchin'] == 's_title' ) {
		$tq_st =  strtr(strtr($st, $trans), $trans);
		$tq_st =  strtr($tq_st, $trans3);
		$tq_st =  "  ti.o_title  LIKE '%".$tq_st."%'  ";
	}
}

if ($_REQUEST['searchop'] !== 'so_full'){
	if (isset($_REQUEST['searchin'])){
		if ($_REQUEST['searchin'] == 's_all' ) {

		} else if ($_REQUEST['searchin'] == 's_body' ) {
			$bq_st =  strtr(strtr($st, $trans), $trans);
			$bq_st =  strtr($bq_st, $trans2);
			$bq_st =  " ri.body LIKE '%".$bq_st."%'  ";
		} else if ($_REQUEST['searchin'] == 's_title' ) {
			$tq_st =  strtr(strtr($st, $trans), $trans);
			$tq_st =  strtr($tq_st, $trans3);
			$tq_st =  "  ti.o_title  LIKE '%".$tq_st."%'  ";
		}
	}
}



if ( isset($_POST['searchinobjlast']) || isset($_POST['searchinobj']) ) {
	$searchinobj = array();
	$searchinobjlasl = array();

	if (isset($_POST['searchinobj'])) {
		$searchinobj = $_POST['searchinobj'];
	}

	if (isset($_POST['searchinobjlast'])) {
		$searchinobjlasl = $_POST['searchinobjlast'];
	}

	$q_st = " DROP TEMPORARY TABLE IF EXISTS `o_usein`;";
	db_runQuery($cn, $q_st);

 	$q_st = " CREATE TEMPORARY TABLE `o_usein` (
				`idobject` BIGINT NOT NULL,
				 PRIMARY KEY (`idobject`)
			)ENGINE=MEMORY;";
	db_runQuery($cn, $q_st);
	$il = 0;
	$ir = 0;
	$size=sizeof($searchinobj);
 	for($i=0; $i<$size; $i++){
 		$q_st = "INSERT IGNORE INTO `o_usein` VALUES (".$searchinobj[$i].");";
 		db_runQuery($cn, $q_st);
 		$q_st = "INSERT IGNORE INTO `o_usein` SELECT obj1.`idobject` FROM `objects` as obj1,  `objects` as obj2
 				 WHERE  obj2.`idobject` = ".$searchinobj[$i]." AND obj1.`parent_idobject` =  obj2.`idobject` and obj2.`o_iright` AND (obj1.o_iright - obj1.o_ileft) = 1;";
 		db_runQuery($cn, $q_st);
	}
	unset($searchinobj);

	$size=sizeof($searchinobjlasl);
 	for($i=0; $i<$size; $i++){
 		$q_st = "INSERT IGNORE INTO `o_usein` VALUES (".$searchinobjlasl[$i].");";
 		db_runQuery($cn, $q_st);
 		$q_st = "INSERT IGNORE INTO `o_usein` SELECT obj1.`idobject` FROM `objects` as obj1,  `objects` as obj2
 				 WHERE obj2.`idobject` = ".$searchinobjlasl[$i]." AND obj1.`o_iright` between obj2.`o_ileft` and obj2.`o_iright`;";
 		db_runQuery($cn, $q_st);
	}
	unset($searchinobjlasl);

}

if (trim($st) != "") {

	$q_st = "DROP TEMPORARY TABLE IF EXISTS `srch_temp` ;";
	db_runQuery($cn, $q_st);
	$q_st = "    CREATE TEMPORARY TABLE `srch_temp` (
		`idobject` BIGINT NOT NULL,
		`idreport` INT NOT NULL,
		`ti_idreport` INT NOT NULL,
		`o_name` varchar(1100) NOT NULL,
		`o_guid` CHAR(40) NOT NULL,
		`r_name` varchar(1100) NOT NULL,
		`r_guid` CHAR(40) NOT NULL,
		`o_icon` varchar(800) NOT NULL,
		`lang_short` CHAR(10) NOT NULL,
		PRIMARY KEY (`idobject`,`idreport`)
		)ENGINE=MEMORY;";

	db_runQuery($cn, $q_st);

	$q_st = " ALTER TABLE `srch_temp` ADD INDEX ( `idobject` ) ;";
	db_runQuery($cn, $q_st);

	$q_st = " ALTER TABLE `srch_temp` ADD INDEX ( `idreport` ) ;";
	db_runQuery($cn, $q_st);

	if (isset($_REQUEST['searchin']) && $_REQUEST['searchin'] == 's_title' ) {

		$q_st = "  ALTER TABLE `srch_temp` DROP PRIMARY KEY, ADD PRIMARY KEY(`idobject`,`idreport`);";
		db_runQuery($cn, $q_st);

		$q_st = "    CREATE TEMPORARY TABLE srch_temp_ido (
			`idobject` BIGINT NOT NULL,
			PRIMARY KEY (`idobject`)
			)ENGINE=MEMORY;";

		db_runQuery($cn, $q_st);

		$q_st = " ALTER TABLE `srch_temp_ido` ADD INDEX ( `idobject` ) ;";
		db_runQuery($cn, $q_st);

		$q_st = " INSERT IGNORE INTO `srch_temp_ido` SELECT DISTINCT idobject FROM `srch_temp`;";
		db_runQuery($cn, $q_st);

		//68321
        $q_st = " INSERT IGNORE INTO `srch_temp` SELECT DISTINCT ti.idobject, 0, 0, res_o.rft_columnname_text as o_name, obj.o_guid, '' as r_name, '' as r_guid, obj.o_icon, lng.lang_short";
		$q_st .= " FROM titleindex ti INNER JOIN branches ON ti.skbranch = branches.skbranch AND branches.iscomplete = 1 LEFT JOIN `languages` lng ON ti.idlanguage = lng.idlanguage , objects AS obj, reports AS rep, resourcefromtables res_o ";
		$q_st .= " WHERE ti.idobject = obj.idobject ";
		$q_st .= " AND ti.skbranch = ".$skbranch;
		$q_st .= " AND obj.skbranch = ".$skbranch;
		$q_st .= " AND obj.o_hidefortree <> 1 ";

		$q_st .= " AND obj.idobject = res_o.idrecord ";
		$q_st .= " AND res_o.idtable = 1 ";
		$q_st .= " AND res_o.idlanguage = ".$contlngid." ";

		//$q_st .= " AND ti.idobject NOT IN ( SELECT idobject FROM `srch_temp_ido`)";

		if (!$searchinalllang) {
			$q_st .= " AND (ti.idlanguage = ".$contlngid." OR IFNULL(ti.idlanguage,0) = 0)";
		}

		$q_st .= ' and ( '.$tq_st.')';

		db_runQuery($cn, $q_st);

		if ( getSetting('portal','useRights', 0) == 1 ) {
			$q_st = "DROP TEMPORARY TABLE IF EXISTS `o_temp` ;";
			db_runQuery($cn, $q_st);

			$q_st = " CREATE TEMPORARY TABLE o_temp (
						`idobject` BIGINT NOT NULL,
						 PRIMARY KEY (`idobject`)
						)ENGINE=MEMORY;
					";
			db_runQuery($cn, $q_st);

			$q_st = "INSERT IGNORE INTO `o_temp` SELECT `srch_temp`.`idobject` FROM `srch_temp`;";
			db_runQuery($cn, $q_st);

			$q_st = " ALTER TABLE `o_temp` ADD INDEX ( `idobject` ) ;";
			db_runQuery($cn, $q_st);
			calcRightsToObject($cn, $ids);
		}
	} else {
			$q_st = "DROP TEMPORARY TABLE IF EXISTS `srch_distinct_obj` ;";
			db_runQuery($cn, $q_st);
			$q_st = "    CREATE TEMPORARY TABLE `srch_distinct_obj` (
				`idobject` BIGINT NOT NULL,
				`idreport` INT NOT NULL,
				`ti_idreport` INT NOT NULL,
				`o_name` varchar(1100) NOT NULL,
				`o_guid` CHAR(40) NOT NULL,
				`r_name` varchar(1100) NOT NULL,
				`r_guid` CHAR(40) NOT NULL,
				`o_icon` varchar(800) NOT NULL,
				`lang_short` CHAR(10) NOT NULL,
				PRIMARY KEY (`idobject`,`idreport`)
				)ENGINE=MEMORY;";

			db_runQuery($cn, $q_st);

			$q_st = " ALTER TABLE `srch_distinct_obj` ADD INDEX ( `idobject` ) ;";
			db_runQuery($cn, $q_st);

	        if ($_REQUEST['searchin'] == 's_all' ) {
				$q_st = " INSERT IGNORE INTO `srch_distinct_obj` SELECT DISTINCT ti.idobject, 0 as idreport, 0 as ti_idreport, res_o.rft_columnname_text as o_name, obj.o_guid, '' as r_name, '' as r_guid, obj.o_icon, lng.lang_short ";
				$q_st .= " FROM titleindex ti LEFT JOIN `languages` lng ON ti.idlanguage = lng.idlanguage, objects AS obj, resourcefromtables res_o ";
				$q_st .= " WHERE ti.idobject = obj.idobject ";
				$q_st .= " AND ti.skbranch = ".$skbranch;
				$q_st .= " AND obj.skbranch = ".$skbranch;
				$q_st .= " AND obj.o_hidefortree <> 1 ";

				$q_st .= " AND obj.idobject = res_o.idrecord ";
				$q_st .= " AND res_o.idtable = 1 ";
				$q_st .= " AND res_o.idlanguage = ".$contlngid." ";

				if (!$searchinalllang) {
					$q_st .= " AND (ti.idlanguage = ".$contlngid." OR IFNULL(ti.idlanguage,0) = 0)";
				}
				$q_st .= ' and ( '.$tq_st.')';
				db_runQuery($cn, $q_st);
			}

			$q_st = " INSERT IGNORE INTO `srch_temp` SELECT * FROM `srch_distinct_obj`";
   			db_runQuery($cn, $q_st);

			$q_st = " INSERT IGNORE INTO `srch_temp` SELECT DISTINCT ri.idobject, ri.idreport, ti.idreport, res_o.rft_columnname_text as o_name, obj.o_guid, res_r.rft_columnname_text as r_name, rep.r_guid, obj.o_icon, lng.lang_short ";
			$q_st .= " FROM `reportindex` AS ri 
				INNER JOIN branches ON ri.skbranch = branches.skbranch AND branches.iscomplete = 1 
				LEFT JOIN `languages` lng ON ri.idlanguage = lng.idlanguage, titleindex ti, objects AS obj, reports AS rep, resourcefromtables res_o, resourcefromtables res_r ";
			$q_st .= " WHERE ri.idobject = ti.idobject ";
			$q_st .= " AND (ri.idreport = ti.idreport )";
			$q_st .= " AND ri.idobject = obj.idobject ";
			$q_st .= " AND ri.idreport = rep.idreport ";
			$q_st .= " AND ri.skbranch = ".$skbranch;
			$q_st .= " AND obj.skbranch = ".$skbranch;

			$q_st .= " AND obj.o_hidefortree <> 1 ";

			$q_st .= " AND obj.idobject = res_o.idrecord ";
			$q_st .= " AND res_o.idtable = 1 ";
			$q_st .= " AND res_o.idlanguage = ".$contlngid." ";

			$q_st .= " AND rep.idreport = res_r.idrecord ";
			$q_st .= " AND res_r.idtable = 2 ";

			if (!$searchinalllang) {
				$q_st .= " AND ( res_r.idlanguage = ".$contlngid." OR IFNULL(rep.idlanguage,0) = 0) ";
				$q_st .= " AND (rep.idlanguage = ".$contlngid." OR IFNULL(rep.idlanguage,0) = 0 ) "; 
				$q_st .= " AND (ti.idlanguage = ".$contlngid." OR IFNULL(ti.idlanguage,0) = 0 )";
			} else {
				$q_st .= " AND ( res_r.idlanguage = ".$contlngid." OR res_r.idlanguage = rep.idlanguage OR IFNULL(rep.idlanguage,0) = 0) ";
			}

			if ($_REQUEST['searchin'] == 's_all' ) {
				$q_st .= 'and ( ('.$tq_st.') OR ( '.$bq_st.' ))';
			} else if ($_REQUEST['searchin'] == 's_body' ) {
				$q_st .= 'and ( '.$bq_st.' )';
			} else if ($_REQUEST['searchin'] == 's_title' ) {
				$q_st .= 'and ( '.$tq_st.')';
			}
			db_runQuery($cn, $q_st);

		// add main lang 48913
		if ($mainlngID != $contlngid && !$searchinalllang ) {
			$q_st = "CREATE INDEX ix2 ON `srch_temp`(`r_guid`);";
			db_runQuery($cn, $q_st);

			$q_st = "CREATE INDEX ix1 ON `srch_temp`(`idobject`)";
			db_runQuery($cn, $q_st);
	
			$q_st = "DROP TEMPORARY TABLE IF EXISTS `repguids`;";
			db_runQuery($cn, $q_st);
			$q_st = "    CREATE TEMPORARY TABLE `repguids` (
				`idobject` BIGINT NOT NULL,
				`r_guid` CHAR(40) NOT NULL,
				PRIMARY KEY (`idobject`,`r_guid`)
				)ENGINE=MEMORY;";
	
			db_runQuery($cn, $q_st);
			// 63935
			$q_st = " INSERT INTO `repguids` SELECT DISTINCT `objectsreports`.`idobject`, reports.`r_guid` 
				FROM `objectsreports` 
				INNER JOIN srch_temp ON `objectsreports`.`idobject` = srch_temp.`idobject`
				INNER JOIN reports ON reports.`idreport` = objectsreports.`idreport`
				WHERE `objectsreports`.idlanguage IN (0, ".$contlngid."); ";
			db_runQuery($cn, $q_st);
	
			$q_st = " INSERT IGNORE INTO `srch_temp` SELECT DISTINCT ri.idobject, ri.idreport, ti.idreport, res_o.rft_columnname_text as o_name, obj.o_guid, res_r.rft_columnname_text as r_name, rep.r_guid, obj.o_icon, lng.lang_short ";
			$q_st .= " FROM `reportindex` AS ri 
				INNER JOIN branches ON ri.skbranch = branches.skbranch AND branches.iscomplete = 1 
				LEFT JOIN `languages` lng ON ri.idlanguage = lng.idlanguage, titleindex ti, objects AS obj, reports AS rep, resourcefromtables res_o, resourcefromtables res_r ";
			$q_st .= " WHERE ri.idobject = ti.idobject ";
			$q_st .= " AND (ri.idreport = ti.idreport )";
			$q_st .= " AND ri.idobject = obj.idobject ";
			$q_st .= " AND ri.idreport = rep.idreport ";
			$q_st .= " AND ri.skbranch = ".$skbranch;
			$q_st .= " AND obj.skbranch = ".$skbranch;
	
			$q_st .= " AND obj.o_hidefortree <> 1 ";
	
			$q_st .= " AND obj.idobject = res_o.idrecord ";
			$q_st .= " AND res_o.idtable = 1 ";
			$q_st .= " AND res_o.idlanguage = ".$contlngid." ";
	
			$q_st .= " AND rep.idreport = res_r.idrecord ";
			$q_st .= " AND res_r.idtable = 2 ";

			$q_st .= " AND ( res_r.idlanguage = ".$contlngid." OR res_r.idlanguage = rep.idlanguage OR IFNULL(rep.idlanguage,0) = 0) ";
		    $q_st .= " AND (rep.idlanguage = ".$mainlngID." ) "; 
			$q_st .= " AND (ti.idlanguage = ".$contlngid." )";
	
			if ($_REQUEST['searchin'] == 's_all' ) {
				$q_st .= 'and ( ('.$tq_st.') OR ( '.$bq_st.' ))';
			} else if ($_REQUEST['searchin'] == 's_body' ) {
				$q_st .= 'and ( '.$bq_st.' )';
			} else if ($_REQUEST['searchin'] == 's_title' ) {
				$q_st .= 'and ( '.$tq_st.')';
			}
			$q_st .= ' and CONCAT (ri.idobject, rep.r_guid) NOT IN ( SELECT CONCAT (idobject, r_guid) FROM `repguids`)';
			db_runQuery($cn, $q_st);
		}

		

		if ($_REQUEST['searchin'] == 's_all' ) {

			$q_st = "    CREATE TEMPORARY TABLE srch_temp_ido (
				`idobject` BIGINT NOT NULL,
				PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;";

			db_runQuery($cn, $q_st);

			$q_st = " ALTER TABLE `srch_temp_ido` ADD INDEX ( `idobject` ) ;";
			db_runQuery($cn, $q_st);

			$q_st = " INSERT IGNORE INTO `srch_temp_ido` SELECT DISTINCT idobject FROM `srch_temp`;";
			db_runQuery($cn, $q_st);

			$q_st = " INSERT IGNORE INTO `srch_temp` SELECT DISTINCT ti.idobject, ti.idreport, ti.idreport, res_o.rft_columnname_text as o_name, obj.o_guid, '' as r_name, '' as r_guid, obj.o_icon, lng.lang_short ";
			$q_st .= " FROM titleindex ti INNER JOIN branches ON ti.skbranch = branches.skbranch AND branches.iscomplete = 1 LEFT JOIN `languages` lng ON ti.idlanguage = lng.idlanguage, objects AS obj, reports AS rep, resourcefromtables res_o ";
			$q_st .= " WHERE ti.idobject = obj.idobject ";
			$q_st .= " AND ti.skbranch = ".$skbranch;
			$q_st .= " AND obj.skbranch = ".$skbranch;
			$q_st .= " AND obj.idobject = res_o.idrecord ";
			$q_st .= " AND res_o.idtable = 1 ";
			$q_st .= " AND res_o.idlanguage = ".$contlngid." ";

			$q_st .= " AND obj.o_hidefortree <> 1 ";

			$q_st .= " AND ti.idobject NOT IN ( SELECT idobject FROM `srch_temp_ido`)";

			if (!$searchinalllang) {
				$q_st .= " AND (ti.idlanguage = ".$contlngid." OR IFNULL(ti.idlanguage,0) = 0)";
			}

			$q_st .= ' and ( '.$tq_st.')';
			db_runQuery($cn, $q_st);
		}

	 	if ( getSetting('portal','useRights',0) == 1 ) {

			$q_st = "DROP TEMPORARY TABLE IF EXISTS `o_temp` ;";
			db_runQuery($cn, $q_st);

			$q_st = " CREATE TEMPORARY TABLE o_temp (
						`idobject` BIGINT NOT NULL,
						 PRIMARY KEY (`idobject`)
						)ENGINE=MEMORY;
					";
			db_runQuery($cn, $q_st);

	   		$q_st = " ALTER TABLE `o_temp` ADD INDEX ( `idobject` ) ;";
			db_runQuery($cn, $q_st);
			$q_st = "INSERT IGNORE INTO `o_temp` SELECT `srch_temp`.`idobject` FROM `srch_temp`;";
			db_runQuery($cn, $q_st);

			calcRightsToObject($cn, $ids);

			$q_st = "DROP TEMPORARY TABLE IF EXISTS `r_temp` ;";
			db_runQuery($cn, $q_st);

			$q_st = " CREATE TEMPORARY TABLE r_temp (
						`idreport` INT NOT NULL,
						 PRIMARY KEY (`idreport`)
						)ENGINE=MEMORY;
					";
			db_runQuery($cn, $q_st);
	        $q_st = " ALTER TABLE `r_temp` ADD INDEX ( `idreport` ) ;";
			db_runQuery($cn, $q_st);

			//build indexed temp rigthmap
			$q_st = "DROP TEMPORARY TABLE IF EXISTS `rightsmap_temp` ;";
			db_runQuery($cn, $q_st);
			$q_st = " CREATE TEMPORARY TABLE rightsmap_temp (
						`idreport` INT NOT NULL,
						 PRIMARY KEY (`idreport`)
						)ENGINE=MEMORY;
					";
			db_runQuery($cn, $q_st);
	   		$q_st = " ALTER TABLE `rightsmap_temp` ADD INDEX ( `idreport` ) ;";
			db_runQuery($cn, $q_st);

			$q_st = "INSERT IGNORE INTO `r_temp` SELECT `srch_temp`.`idreport` FROM `srch_temp`;";
			db_runQuery($cn, $q_st);

			//build indexed temp rigthmap to user guids
			$query = "DROP TEMPORARY TABLE IF EXISTS `defaultsright` ;";
			db_runQuery($cn, $query);
			$query = " CREATE TEMPORARY TABLE defaultsright (
						`idreport` INT NOT NULL,
						 PRIMARY KEY (`idreport`)
						)ENGINE=MEMORY;
					";
			db_runQuery($cn, $query);
	   		$query = " ALTER TABLE `defaultsright` ADD INDEX ( `idreport` ) ;";
			db_runQuery($cn, $query);

			$query = "INSERT IGNORE INTO `defaultsright` SELECT DISTINCT orts.idreport FROM `objectsreports` as orts
				LEFT JOIN `objects` as o ON orts.`idobject` = o.`idobject`
				LEFT JOIN `users` as u ON u.`user_guid` = o.`o_guid`
				WHERE u.iduser in (".$ids.") AND orts.idreport NOT IN (SELECT rr.idreport FROM  `rightsreports` as rr WHERE  rr.deny_allow = 0);";
			db_runQuery($cn, $query);


	    	$q_st = "INSERT IGNORE INTO `rightsmap_temp` SELECT rr.`idreport` FROM `rightsreports` as rr, `r_temp` as rt WHERE rt.`idreport` = rr.`idreport` AND rr.`iduser` IN (".$ids.") AND rr.`deny_allow` = 0 ;";
			db_runQuery($cn, $q_st);
			$q_st = "DELETE FROM `srch_temp` WHERE `srch_temp`.`idreport` IN ( SELECT `idreport` FROM `rightsmap_temp`  );";
			db_runQuery($cn, $q_st);

			$q_st = "DELETE FROM `rightsmap_temp`;";
			db_runQuery($cn, $q_st);
	    	$q_st = "INSERT IGNORE INTO `rightsmap_temp` SELECT rr.`idreport` FROM `rightsreports` as rr, `r_temp` as rt WHERE rt.`idreport` = rr.`idreport` AND rr.`iduser` IN (".$ids.") AND rr.`deny_allow` = 1 ;";
			db_runQuery($cn, $q_st);
			$q_st = "DELETE FROM `srch_temp` WHERE `srch_temp`.`idreport` <> 0 AND (`srch_temp`.`idreport` NOT IN ( SELECT `idreport` FROM `rightsmap_temp` UNION SELECT `idreport` FROM `defaultsright`));";
			db_runQuery($cn, $q_st);

			$q_st = "DELETE FROM `rightsmap_temp`;";
			db_runQuery($cn, $q_st);
	    	$q_st = "INSERT IGNORE INTO `rightsmap_temp` SELECT rr.`idreport` FROM `rightsreports` as rr, `r_temp` as rt WHERE rt.`idreport` = rr.`idreport` AND rr.`iduser` IN (".$ids.") AND rr.`deny_allow` = 2 ;";
			db_runQuery($cn, $q_st);
			$q_st = "DELETE FROM `srch_temp` WHERE `srch_temp`.`idreport` <> 0 AND (`srch_temp`.`idreport` NOT IN ( SELECT `idreport` FROM `rightsmap_temp` UNION SELECT `idreport` FROM `defaultsright`));";
			db_runQuery($cn, $q_st);
		}
	}

	if ( isset($_POST['searchinobjlast']) || isset($_POST['searchinobj']) ) {
		$q_st = "DELETE FROM `srch_temp` WHERE `srch_temp`.`idobject` NOT IN ( SELECT `o_usein`.`idobject` FROM `o_usein`);";
		db_runQuery($cn, $q_st);
	}

	if ( isset($_POST['userepfilter'])) {
		$rids = $_POST['userepfilter'];
	 	$q_st = " DROP TEMPORARY TABLE IF EXISTS `r_usein`;";
		db_runQuery($cn, $q_st);
		$q_st = " CREATE TEMPORARY TABLE `r_usein` (
				`idobject` BIGINT NOT NULL,
				`idreport` INT NOT NULL,
				 PRIMARY KEY (`idobject`,`idreport`)
			)ENGINE=MEMORY;";
		db_runQuery($cn, $q_st);


		foreach ($rids as $rid) {
		    $id = explode("_", $rid);
		    if (isset($id[0]) && isset($id[1])) {
		    	$q_st = "INSERT IGNORE INTO r_usein
		    		SELECT obj1.`idobject`, ".$id[1]."  FROM `objects` as obj1,  `objects` as obj2
 				 	 WHERE obj2.`idobject` = ".$id[0]." AND obj1.`o_iright` between obj2.`o_ileft` and obj2.`o_iright`;";
		    	db_runQuery($cn, $q_st);
			}
		}

		$q_st = "DELETE tm.* FROM `srch_temp` tm WHERE tm.`idreport` <> 0 AND tm.`idobject` NOT IN (SELECT `idobject` FROM r_usein);";
		db_runQuery($cn, $q_st);

		$q_st = "DELETE tm.* FROM `srch_temp` tm WHERE tm.`idreport` <> 0 AND tm.`idreport` NOT IN (SELECT `idreport` FROM r_usein) ;";
		db_runQuery($cn, $q_st);
		unset($rids);
	}

	$resarr = array();
	$result = null;

	$q_st = "SELECT COUNT(*) as cnt FROM `srch_temp`";
	$resarr = db_runQueryAndReturnArray($cn,$q_st);
	$total = $resarr[0]['cnt'];

} else {
	$resarr = array();
	$result = null;
	$total = 0;
}

$onpage = getSetting('page', 'search.pagesize', 20);;
$total = ceil($total/$onpage); 
$total = $total == 0 ? 1 : $total;
$page = (isset($_REQUEST['page']) ? $_REQUEST['page'] : 1 );
$page = (($page > $total) ? $total : $page);

$resarr = array();
$result = null;
echo '<ol start="'.(($page == 1) ? 1 : ($page - 1) * $onpage + 1).'">';

if (trim($st) != "" ) {
	if (isset($_REQUEST['searchin']) && $_REQUEST['searchin'] == 's_title' ) {
		$q_st = "SELECT DISTINCT st.*, '' as body, ri.skbranch FROM `srch_temp` as st
		INNER JOIN `reportindex` AS ri ON st.idobject = ri.idobject ";
		$q_st .= " ORDER BY idobject, idreport LIMIT ".(($page - 1) * $onpage).",".$onpage.";";
	} else {
		$q_st = "SELECT DISTINCT st.*, REPLACE(ri.`body`, '&amp;', '&') as body, ri.skbranch FROM `srch_temp` as st
		INNER JOIN `reportindex` AS ri ON  st.idobject = ri.idobject AND  st.idreport = ri.idreport ".(!$searchinalllang ? " and ri.idlanguage = ".$contlngid." " : "")." ";
		$q_st .= ' WHERE ( '.$bq_st.' )';
		$q_st .= " ORDER BY idobject, idreport
		LIMIT ".(($page - 1) * $onpage).",".$onpage.";";
	}
	$resarr = db_runQueryAndReturnArray($cn,$q_st);
}
if ((!(null === mysqli_error($cn)) && mysqli_errno($cn) > 0)) {
	logError($cn, $q_st);
}

if (isset($_REQUEST['search']) && strlen(trim($_REQUEST['search']))>0) {
	$size=sizeof($resarr);
} else {
	$size = 0;
	$total = 0;
}

$f_arr = explode(' ',$st);
$s_f_arr = sizeof($f_arr);
$unqarr = array();

$sinbody = (isset($_REQUEST['searchin']) && $_REQUEST['searchin'] == 's_body');
for($i=0; $i<$size; $i++){
	$idlanguage_t = db_getLanguageID($cn, $resarr[$i]['lang_short']);
	$idr_t = db_getIDReportByGuid($cn, $resarr[$i]['r_guid'], $idlanguage_t, $resarr[$i]['skbranch']);
	if ($idr_t == 0 || db_isObjectsReportsExits($cn, $resarr[$i]['o_guid'], $resarr[$i]['r_guid'], $idlanguage_t, $resarr[$i]['skbranch'])){
		if ( $resarr[$i]['skbranch'] == $mainskbranch) {
			$target = "businessmodel.php?";
		} else {
			$poll = db_getFirstPollObjectBySearch($cn, $u_ids, $resarr[$i]['o_guid'], $resarr[$i]['r_guid'], $resarr[$i]['skbranch']);
			if (sizeof($poll) > 0 ){
				$target = "pollobject.php?skpollingobject=".$poll[0]['skpollingobject']."&skpolltype=".$poll[0]['skpolltype']."&skbranch=".$resarr[$i]['skbranch']."&";  
			} else {
				continue;
			}
		}
	
		$pos = 0;
		echo '						<li>';
		echo '				<div class="box-search-results"> ';
		if ( !$sinbody ) {
			// show highlight-plugin to all elemnts of search results
			echo '					<div id="highlight-plugin" class="highlight-plugin">';
		}
	
	
		$langparam = (($searchinalllang && isset($resarr[$i]['lang_short']) && $resarr[$i]['lang_short'] != NULL) ? '&lang='.$resarr[$i]['lang_short'] : '');
		if ($_REQUEST['searchin'] == 's_title' || $resarr[$i]['ti_idreport'] == '0' ) {
				echo '<a target="_blank" class="link-fav-search" style="background-image: url( '.getImgIcon($resarr[$i]['o_icon']).' );" href="./'.$target.'oguid='.$resarr[$i]['o_guid'].($resarr[$i]['r_name'] == '' ? '' : '&rguid='.$resarr[$i]['r_guid']).$langparam.'">';  
				echo htmlentities($resarr[$i]['o_name']);
				echo ' </a><br/>';
		} else {
			echo '<a target="_blank" class="link-fav-search" style="background-image: url( '.getImgIcon($resarr[$i]['o_icon']).' );" href="./'.$target.'oguid='.$resarr[$i]['o_guid'].($resarr[$i]['r_name'] == '' ? ' ' : '&rguid='.$resarr[$i]['r_guid']).'&hlwords='.(isset($_REQUEST['searchop']) && $_REQUEST['searchop'] == 'so_full' ? trim($st) : htmlentities(urlencode(implode(",", $hlw)))).$langparam.'">';
			echo ' <span class="-off-75546-hide-highlight">'.htmlentities($resarr[$i]['o_name']).' ('.$resarr[$i]['r_name'].')</span>';
			echo '</a>';
	
			if ( $sinbody ) {
				// show highlight-plugin only to preview of search results
				echo '					<div id="highlight-plugin" class="highlight-plugin">';
			}
	
			if (isset($_REQUEST['searchop']) && $_REQUEST['searchop'] == 'so_full'){
				$pos = mb_strpos($resarr[$i]['body'], $st);
				if ($pos > 0) {
					$pos = (($pos - 120) < 0) ? 0 : ($pos - 120);
					$str = mb_substr($resarr[$i]['body'], $pos, mb_strlen($st) + 240 ); 
					echo "<div class=\"box-search-results-abstract\"><p>..".htmlspecialchars($str)."..</p></div>";
				}
			} else {
				$pos = 0;
				for($jj=0; $jj<sizeof($f_arr); $jj++){
					if (strlen($f_arr[$jj]) > 0) {
						$pos = mb_strpos($resarr[$i]['body'], $f_arr[$jj]);
						if ($pos > 0) {
							break;
						}
					}
				}
				$pos = (($pos - 120) < 0) ? 0 : ($pos - 120);
				$str = mb_substr($resarr[$i]['body'], $pos, mb_strlen($st) + 240 ); 
				echo "<div class=\"box-search-results-abstract\"><p>..".htmlspecialchars($str)."..</p></div>";
			}
			if ( $sinbody ) {
				// show highlight-plugin only to preview of search results
				echo '					</div>';
			}
	
		}
	
		if ( !$sinbody ) {
			// show highlight-plugin to all elemnts of search results
			echo '						</div>';
		}
	
		if ( $resarr[$i]['skbranch'] == $mainskbranch) {
			echo '						<div class="box-search-results-path">';
			$p_arr = db_getObjectPathtoUser($cn, $resarr[$i]['idobject'], $u_ids, $contlngid, $resarr[$i]['skbranch'] );
			$pa_size = sizeof($p_arr);
			for($p=0; $p<$pa_size; $p++){
				echo '							<a href="./'.$target.'oguid='.$p_arr[$p]['o_guid'].'">'.htmlentities($p_arr[$p]['o_name']).'</a>';
			}
			unset($p);
			unset($p_arr);
			unset($pa_size);
		
			echo '				</div>';
		}
	
		echo '					</li>';
	}
}
unset($unqarr);
?>
					</ol>
				<!--</section>-->

 				<section id="box-paginator">
<?php if (!(null === $total || $total == 0) && $total > 1) {
	echo_panel_page($total, $page, $url, true);
}?>

				</section>
<?php
db_disconnect($cn);
ob_end_flush();
?>