<?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');
}

checkUserAndRedirectToLogin();
checkLanguage();
$cn = db_connect();
$lng = ( isset($_REQUEST['lang']) ? 'lang='.$_REQUEST['lang'] : '');
$lngid = db_getLanguageID($cn, getLanguage());
$contlng = 'lang='.db_getLanguageShortByID($cn, $_SESSION['user_idlanguagecontent']);
$contlngid = $_SESSION['user_idlanguagecontent'];
$onpage = getSetting('page', 'discussions.pagesize', 20);

$default_order_column = getCookieForPage('order_column','o_name'); 
$default_order_val = getCookieForPage('order_val','asc');

$order_column = isset( $_GET[ "order_column" ] ) ? $_GET[ "order_column" ] : $default_order_column;
$order_val = isset( $_GET[ "order_val" ] ) ? $_GET[ "order_val" ] : $default_order_val;
setCookieForPage("order_column", $order_column);
setCookieForPage("order_val", $order_val);

$page = isset( $_REQUEST[ "page" ] ) ? $_REQUEST[ "page" ] : 1;
$search = (( isset($_REQUEST['search']) && strlen(trim($_REQUEST['search']))>0 ) ? trim($_REQUEST['search']) : "");

$u_ids = GetUserIDs();
$url = getCurPageURL();
$hideheader = (isset($_COOKIE['hideheader']) ?  $_COOKIE['hideheader'] : 0);
$urlWO = getCurPageURLWO();
if (!isset($_REQUEST['searchin'])) { $_REQUEST['searchin'] = 's_all'; }
$ids = implode(",", $u_ids);
?>
<?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);

	$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,
		`o_ileft` BIGINT NOT NULL,
		`o_iright` BIGINT NOT NULL,
		`o_guid` CHAR(40) NOT NULL,
		`o_icon` varchar(800) NOT NULL,
		`skbranch`  INT NOT NULL,
		PRIMARY KEY (`idobject`),
		INDEX `o_guid` (`o_guid`,`skbranch`)
		)ENGINE=MEMORY;";
	db_runQuery($cn, $q_st);
		
	db_createObjectsFullRightsMap($cn, $u_ids);


	if ( isset($_REQUEST['searchinobjlast']) || isset($_REQUEST['searchinobj']) ) {
		$searchinobj = array();
		$searchinobjlasl = array();
	
		if (isset($_REQUEST['searchinobj'])) {
			$searchinobj = $_REQUEST['searchinobj'];
		}
	
		if (isset($_REQUEST['searchinobjlast'])) {
			$searchinobjlasl = $_REQUEST['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);
		$q_st = "DELETE FROM `rightsmap_temp` WHERE `idobject` NOT IN (SELECT `idobject` FROM `o_usein`);";
		db_runQuery($cn, $q_st);			
	}

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

	$q_st = "CREATE TEMPORARY TABLE `msgs_temp` (
		`o_guid` CHAR(40) NOT NULL,
		`iduser` INT NULL,
		`idforummessage` BIGINT NULL,
		`frmm_datechange_tmst` INT NULL,
		`skbranch` INT NOT NULL,
		PRIMARY KEY (`o_guid`,`skbranch`)
		)ENGINE=MEMORY;";
	db_runQuery($cn, $q_st);

	$q_st = "INSERT IGNORE INTO `msgs_temp` 
	SELECT fm.`o_guid`, iduser, MAX(idforummessage), MAX(fm.frmm_datechange_tmst), fm.`skbranch` 
	  FROM `forummessages` as fm
	  INNER JOIN `objects` as o ON o.`o_guid` COLLATE utf8mb4_general_ci = fm.`o_guid`  COLLATE utf8mb4_general_ci AND o.`skbranch` = fm.`skbranch`
 	  INNER JOIN `rightsmap_temp` as ro ON ro.`idobject` = o.`idobject` 
	  WHERE frmm_isdelete = 0
	  GROUP BY fm.`o_guid`,  iduser,  fm.`skbranch` ORDER BY MAX(fm.frmm_datechange_tmst) DESC ;";
	db_runQuery($cn, $q_st);

	$q_st = "DROP TEMPORARY TABLE IF EXISTS `msgs_new` ;";
	db_runQuery($cn, $q_st);
	$q_st = "CREATE TEMPORARY TABLE `msgs_new` (
		`o_guid` CHAR(40) NOT NULL,
		`new_cnt` INT NULL,
		`frmm_datechange_tmst` INT NULL,
		`skbranch` INT NOT NULL,
		PRIMARY KEY (`o_guid`,`skbranch`)
		)ENGINE=MEMORY;";
	db_runQuery($cn, $q_st);

	$q_st = "INSERT IGNORE INTO `msgs_new` 
	SELECT fm.`o_guid`, 0, MAX(`frmm_datechange_tmst`) ,fm.`skbranch` 
	  	FROM `forummessages` as fm
	  	INNER JOIN `objects` as o ON o.`o_guid` COLLATE utf8mb4_general_ci = fm.`o_guid`  COLLATE utf8mb4_general_ci AND o.`skbranch` = fm.`skbranch`
		INNER JOIN `rightsmap_temp` as ro ON ro.`idobject` = o.`idobject` 
	  WHERE frmm_isdelete = 0 AND fm.`iduser` NOT IN (".$ids.") 
	  GROUP BY fm.`o_guid`,fm.`skbranch`  ;";
	db_runQuery($cn, $q_st);

	$q_st = "UPDATE `msgs_new` INNER JOIN (
				SELECT fm.`o_guid`, fm.`skbranch`,count(fm.idforummessage) as cnt
				FROM `forummessages` as fm
				LEFT JOIN `forummessagessaw` as frmsw ON frmsw.iduser IN (".$ids.") AND fm.iduser <> frmsw.iduser AND fm.skbranch = frmsw.skbranch AND fm.o_guid = frmsw.o_guid AND /* frmsw.`frmsw_sessionhash` = '".getSessionSSKEY()."' AND */ from_unixtime(frmsw.frmsw_datesaw_tmst) <= from_unixtime(fm.frmm_datechange_tmst)
				WHERE IF(frmsw.iduser IS NOT NULL, 1 , 0) = 1 AND fm.frmm_isdelete = 0
				GROUP BY fm.`o_guid`, fm.`skbranch` ) q ON `msgs_new`.`o_guid` COLLATE utf8mb4_general_ci = q.`o_guid`  COLLATE utf8mb4_general_ci AND `msgs_new`.`skbranch` = q.`skbranch`
			 SET `msgs_new`.`new_cnt` = q.cnt;";	
	db_runQuery($cn, $q_st);

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

	$q_st = "    CREATE TEMPORARY TABLE `dsc_temp` (
		`idobject` BIGINT NOT NULL,
		`o_ileft` BIGINT NOT NULL,
		`o_iright` BIGINT NOT NULL,
		`idobject_root` BIGINT NULL,
		`root_name` varchar(2500) NOT NULL,
		`location_name` varchar(2500) NOT NULL,
		`o_guid` CHAR(40) NOT NULL,
		`o_name` varchar(2500) NOT NULL,
		`iduser` INT NOT NULL,
		`user_name` varchar(2500) NOT NULL,
		`o_icon` varchar(800) NOT NULL,
		`idforummessage` BIGINT NOT NULL,
		`frmm_datechange_tmst` DATETIME NOT NULL,
		`frmm_newmsgcnt` INT NOT NULL,
		`skbranch` INT NOT NULL,
		PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;";
	db_runQuery($cn, $q_st);

	
	db_setTimeZone($cn);
	$q_st = "INSERT IGNORE INTO `dsc_temp` 
				SELECT ro.`idobject`, o.`o_ileft`, o.`o_iright`, NULL, '' as `root_name`, '' as `location_name` , o.`o_guid`, res_o.rft_columnname_text as o_name, lstmsg.`iduser`, '' as `user_name`, o.`o_icon` ,lstmsg.`idforummessage`,   from_unixtime(lstmsg.frmm_datechange_tmst), `msgs_new`.`new_cnt`, o.`skbranch`
				  FROM `rightsmap_temp` as ro
				  INNER JOIN `objects` as o ON ro.`idobject` = o.`idobject`
				  INNER JOIN `resourcefromtables` as res_o ON ro.`idobject` = res_o.`idrecord` AND res_o.`skbranch` = o.`skbranch` 
				  INNER JOIN `msgs_temp` as lstmsg ON o.`o_guid`COLLATE utf8mb4_general_ci = lstmsg.`o_guid`COLLATE utf8mb4_general_ci AND o.`skbranch` = lstmsg.`skbranch`
				  LEFT JOIN `msgs_new` ON o.`o_guid` COLLATE utf8mb4_general_ci = `msgs_new`.`o_guid`  COLLATE utf8mb4_general_ci AND o.`skbranch` = msgs_new.`skbranch` 
				  WHERE res_o.idtable = 1 
				    AND res_o.idlanguage = ".$contlngid.";";
	db_runQuery($cn, $q_st);

	$q_st = "UPDATE `dsc_temp` INNER JOIN `resourcefromtables` as res_u ON res_u.idtable = 6 AND res_u.idrecord = `dsc_temp`.iduser
				SET `dsc_temp`.`user_name` = res_u.rft_columnname_text
			  WHERE res_u.idlanguage = ".$contlngid.";";
	db_runQuery($cn, $q_st);

	$q_st = "UPDATE `dsc_temp` SET `dsc_temp`.idobject_root = (SELECT idobject FROM `objects` as o  WHERE o.o_ileft < `dsc_temp`.o_ileft AND o.o_iright > `dsc_temp`.o_iright AND o.parent_idobject <> 0 AND o.o_useinsearch = 1  ORDER BY o.o_ileft DESC LIMIT 1 );";
	db_runQuery($cn, $q_st);

    $q_st = "UPDATE `dsc_temp` INNER JOIN `resourcefromtables` as res_o ON res_o.idtable = 1 AND res_o.idrecord = `dsc_temp`.idobject_root
				SET `dsc_temp`.`root_name` = res_o.rft_columnname_text
			  WHERE res_o.idlanguage = ".$contlngid.";";
	db_runQuery($cn, $q_st);

	//61945:6
    $q_st = "UPDATE `dsc_temp` INNER JOIN `resourcefromtables` as res_o ON res_o.idtable = 7 AND res_o.idrecord = `dsc_temp`.skbranch
				SET `dsc_temp`.`location_name` = res_o.rft_columnname_text
			  WHERE res_o.idlanguage = ".$contlngid."
			  AND `dsc_temp`.skbranch = (SELECT skbranch FROM branches WHERE ismain = 1 LIMIT 1);";
	db_runQuery($cn, $q_st);

	$q_st = "UPDATE `dsc_temp` 
	         INNER JOIN 
			 	(SELECT DISTINCT `polltypes`.skpolltype, `useranswers`.idpollingobject, `pollingobjects`.skbranch 
				   FROM `useranswers` 
				   INNER JOIN `pollingobjects` ON `useranswers`.idpollingobject = `pollingobjects`.idpollingobject 
				   INNER JOIN `polltypes` ON `polltypes`.idpolltype = `useranswers`.idpolltype WHERE IFNULL(`pollingobjects`.skproject,0) = 0 ) as polldetails ON polldetails.skbranch = `dsc_temp`.skbranch 
	         INNER JOIN `resourcefromtables` as res_o ON res_o.idtable = 8 AND res_o.idrecord = `polldetails`.skpolltype
			 INNER JOIN `resourcefromtables` as res_branch ON res_branch.idtable = 7 AND res_branch.idrecord = `dsc_temp`.skbranch
				SET `dsc_temp`.`location_name` = concat(res_o.rft_columnname_text, ': ', res_branch.rft_columnname_text)
			  WHERE res_o.idlanguage = ".$contlngid."
			  AND `dsc_temp`.`location_name` = '' AND `dsc_temp`.skbranch <> (SELECT skbranch FROM branches WHERE ismain = 1 LIMIT 1) ;";
	db_runQuery($cn, $q_st);

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

	$q_st = " CREATE TEMPORARY TABLE `projects_temp` (
		`skproject` INT NOT NULL,
		`skbranch` INT NOT NULL,
		`branch_count` INT,
		PRIMARY KEY (`skproject`)
		)ENGINE=MEMORY;";
	db_runQuery($cn, $q_st);
	
	$q_st = "INSERT IGNORE INTO `projects_temp` 
				SELECT `skproject`, `skbranch`, 1 FROM `pollingobjects` WHERE IFNULL(`pollingobjects`.skproject,0) <> 0;";
	db_runQuery($cn, $q_st);
	
	$q_st = "UPDATE `projects_temp` SET branch_count = (SELECT COUNT(DISTINCT `skbranch`) FROM pollingobjects WHERE pollingobjects.`skproject` = `projects_temp`.`skproject`);";
	db_runQuery($cn, $q_st);

	$q_st = "UPDATE `dsc_temp` 
	         INNER JOIN 
			 	(SELECT DISTINCT `polltypes`.skpolltype, `pollingobjects`.skproject, `pollingobjects`.skbranch  
				   FROM `useranswers` 
				   INNER JOIN `pollingobjects` ON `useranswers`.idpollingobject = `pollingobjects`.idpollingobject 
				   INNER JOIN `polltypes` ON `polltypes`.idpolltype = `useranswers`.idpolltype WHERE IFNULL(`pollingobjects`.skproject,0) <> 0 ) as polldetails ON polldetails.skbranch = `dsc_temp`.skbranch 
			 INNER JOIN `projects_temp` ON `projects_temp`.`skproject` = polldetails.`skproject`
	         INNER JOIN `resourcefromtables` as res_o ON res_o.idtable = 8 AND res_o.idrecord = `polldetails`.skpolltype
			 INNER JOIN `resourcefromtables` as res_project ON res_project.idtable = 10 AND res_project.idrecord = `projects_temp`.skproject
				SET `dsc_temp`.`location_name` = concat(res_o.rft_columnname_text, ': ', res_project.rft_columnname_text)
			  WHERE res_o.idlanguage = ".$contlngid."
			  AND `dsc_temp`.`location_name` = '' AND `dsc_temp`.skbranch <> (SELECT skbranch FROM branches WHERE ismain = 1 LIMIT 1) ;";
	db_runQuery($cn, $q_st);


	$q_st = "UPDATE `dsc_temp` 
	INNER JOIN 
		(SELECT DISTINCT `polltypes`.skpolltype, `useranswers`.idpollingobject, `pollingobjects`.skproject, `pollingobjects`.skbranch 
		  FROM `useranswers` 
		  INNER JOIN `pollingobjects` ON `useranswers`.idpollingobject = `pollingobjects`.idpollingobject 
		  INNER JOIN `polltypes` ON `polltypes`.idpolltype = `useranswers`.idpolltype WHERE IFNULL(`pollingobjects`.skproject,0) <> 0 ) as polldetails ON polldetails.skbranch = `dsc_temp`.skbranch 
    INNER JOIN `projects_temp` ON `projects_temp`.`skproject` = polldetails.`skproject` AND `projects_temp`.branch_count > 1
	INNER JOIN `resourcefromtables` as res_o ON res_o.idtable = 8 AND res_o.idrecord = `polldetails`.skpolltype
	INNER JOIN `resourcefromtables` as res_branch ON res_branch.idtable = 7 AND res_branch.idrecord = `dsc_temp`.skbranch
	   SET `dsc_temp`.`location_name` = concat(`dsc_temp`.`location_name`, '<br/><br/>', '".getResourceByLang("title.polls.source.branch")."', ': ', res_branch.rft_columnname_text)
	 WHERE res_o.idlanguage = ".$contlngid." ;";
	db_runQuery($cn, $q_st);	

	if ($search != ""){
		$q_st = "DELETE FROM `dsc_temp` WHERE o_name NOT LIKE '%".$search."%' AND root_name NOT LIKE '%".$search."%' AND location_name NOT LIKE '%".$search."%' AND user_name NOT LIKE '%".$search."%' ;";
		db_runQuery($cn, $q_st);
	}

	$resarr = array();

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

	$total = ceil($total/$onpage); 
	$total = $total == 0 ? 1 : $total;
	$page = (($page > $total) ? $total : $page);

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

	$q_st = "SELECT * FROM `dsc_temp` ";
	if ($order_column != "") {
		$q_st.= " ORDER BY ".$order_column."  ".$order_val." ";
	}
	$q_st.= "LIMIT ".(($page - 1) * $onpage).",".$onpage.";";
	
	$resarr = db_runQueryAndReturnArray($cn,$q_st);
	$size=sizeof($resarr);

$lng_shot_interface = db_getLanguageShortByID($cn, $_SESSION['user_idlanguageinterface'], true);
?>
<div class="tbldata-wide"> 
				<table class="tbldata self-binding-width" cellspacing="0">
					<tr>
						<th class="<? if( $order_column == "o_name" ) echo "tbldata-cell-sortable" ?> tblinput-cell-name"><? echo buildSortColumnTitle( getResourceByLang('field.discussions.object', $lng_shot_interface), ( $order_column == "o_name" ? true : false ), "o_name", $order_val ) ?></th>
						<th class="<? if( $order_column == "root_name" ) echo "tbldata-cell-sortable" ?> tblinput-cell-input"><? echo buildSortColumnTitle( getResourceByLang('field.discussions.dictionary', $lng_shot_interface), ( $order_column == "root_name" ? true : false ),"root_name", $order_val ) ?></th>
						<th class="<? if( $order_column == "location_name" ) echo "tbldata-cell-sortable" ?> tblinput-cell-input"><? echo buildSortColumnTitle( getResourceByLang('field.discussions.location', $lng_shot_interface), ( $order_column == "location_name" ? true : false ),"location_name", $order_val ) ?></th>
						<th class="<? if( $order_column == "frmm_datechange_tmst" ) echo "tbldata-cell-sortable" ?> tblinput-cell-input"><? echo buildSortColumnTitle( getResourceByLang('field.discussions.lastmessage', $lng_shot_interface), ( $order_column == "frmm_datechange_tmst" ? true : false ),"frmm_datechange_tmst", $order_val ) ?></th>
						<th class="<? if( $order_column == "frmm_newmsgcnt" ) echo "tbldata-cell-sortable" ?> tblinput-cell-input"><? echo buildSortColumnTitle( getResourceByLang('field.discussions.cntofnewmessages', $lng_shot_interface), ( $order_column == "frmm_newmsgcnt" ? true : false ), "frmm_newmsgcnt", $order_val ) ?></th>
					</tr>
<?php					


$mainskbranch = db_getMainSKBranch($cn);
for($i=0; $i<$size; $i++){
	if ( $resarr[$i]['skbranch'] == $mainskbranch) {
		$target = (isset($_COOKIE['mobilemode']) && $_COOKIE['mobilemode'] == 1) ? "mforum.php?": "businessmodel.php?";
	} else {
		$poll = db_getFirstPollObjectBySearch($cn, $u_ids, $resarr[$i]['o_guid'], NULL, $resarr[$i]['skbranch']);
		if (sizeof($poll) > 0 ){
			$target = "pollobject.php?skpollingobject=".$poll[0]['skpollingobject']."&skpolltype=".$poll[0]['skpolltype']."&skbranch=".$resarr[$i]['skbranch']."&rguid=".$poll[0]['r_guid']."&";  
		} else {
			continue;
		}
	}
	$newMsgId = db_getNewForumMessages($cn, $resarr[ $i ][ "o_guid" ], $u_ids[0], $resarr[$i]['skbranch'], 1, FALSE );
?>
	<tr>
		<td valign="top"><? echo '<a target="_parent" class="link-fav-search" style="background-image: url( '.getImgIcon($resarr[$i]['o_icon']).' );"  href="./'.$target.'oguid='.$resarr[ $i ][ "o_guid" ].((is_array($newMsgId) && sizeof($newMsgId) > 0) ? '&forumid='.$newMsgId[0]['idforummessage'].'' : '').'&page=last">'.$resarr[ $i ][ "o_name" ].'</a>'; ?> </td>
		<td valign="top"><? echo $resarr[ $i ][ "root_name" ] ?></td>		
		<td valign="top"><? echo $resarr[ $i ][ "location_name" ] ?></td>
		<td valign="top"><a target="_parent" href="./<?php echo $target.'oguid='.$resarr[ $i ][ "o_guid" ].'&forumid='.$resarr[ $i ][ "idforummessage" ].'"><nobr>'.$resarr[ $i ][ "frmm_datechange_tmst" ]." ".$resarr[ $i ][ "user_name" ].'</nobr>';?></a></td>
		<td valign="top"><? echo $resarr[ $i ][ "frmm_newmsgcnt" ] ?></td>
	</tr>
<?php
}
unset($resarr);
?>
				</table>
</div>

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

				</section><br/>

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