<?php
ob_start();

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

/*
проверка на валидный ip передающий данные
*/
checkValidAgentIP();
/*
проверка на валидный ip передающий данные
*/

ini_set('mysql.connect_timeout', 6000);
ini_set('default_socket_timeout', 6000);
set_time_limit(0);

$query = "";
$cn = db_connect();
$ver = db_getDBVersion($cn);
$first = $ver;
$success = true;

$cn->query("SET GLOBAL log_bin_trust_function_creators = 1;");

if ($ver < 4) {
	// update to 4 version
	$query = "SHOW TABLES LIKE 'usersgroups';";
	$resarr = array();
    $result = $cn->query($query);
    if ($result) {
            while ($row = $result->fetch_assoc()) {
                    array_push($resarr, $row);
            }
    }
	$tableExists = count($resarr) > 0;

	if (!$tableExists) {
		$query = "CREATE TABLE IF NOT EXISTS `usersgroups` (
					  `iduser` int(11) NOT NULL,
					  `idgroup` int(11) NOT NULL,
					  `user_hash` varchar(255) NOT NULL,
					  `group_hash` varchar(255) NOT NULL,
					  PRIMARY KEY (`iduser`,`idgroup`)
					) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Relations users and groups';
		";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	}

	$query = "SHOW COLUMNS FROM  users like 'user_notification_allallow'";
	$resarr = array();
    $result = $cn->query($query);
    if ($result) {
            while ($row = $result->fetch_assoc()) {
                    array_push($resarr, $row);
            }
    }
	$columnExists = count($resarr) > 0;

	if (!$columnExists) {
		$query = "ALTER TABLE users ADD user_notification_allallow tinyint(1) AFTER user_notification_newversions;";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
		$query = "UPDATE users  SET user_notification_allallow = 0;";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	}

	$query = "UPDATE `version` SET `version` = 4;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 4) {
	// update to 4 version
	$query = "SHOW TABLES LIKE 'usersgroups'";
	$resarr = array();
    $result = $cn->query($query);
    if ($result) {
            while ($row = $result->fetch_assoc()) {
                    array_push($resarr, $row);
            }
    }
	$tableExists = count($resarr) > 0;

	if (!$tableExists) {
		$query = "CREATE TABLE IF NOT EXISTS `usersgroups` (
					  `iduser` int(11) NOT NULL,
					  `idgroup` int(11) NOT NULL,
					  `user_hash` varchar(255) NOT NULL,
					  `group_hash` varchar(255) NOT NULL,
					  PRIMARY KEY (`iduser`,`idgroup`)
					) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Relations users and groups';
		";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	}

	$query = "SHOW COLUMNS FROM  users like 'user_notification_allallow'";
	$resarr = array();
    $result = $cn->query($query);
    if ($result) {
            while ($row = $result->fetch_assoc()) {
                    array_push($resarr, $row);
            }
    }
	$columnExists = count($resarr) > 0;

	if (!$columnExists) {
		$query = "ALTER TABLE users ADD user_notification_allallow tinyint(1) AFTER user_notification_newversions;";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
		$query = "UPDATE users  SET user_notification_allallow = 0;";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	}

	$query = "UPDATE `version` SET `version` = 4;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 5) {
	// update to 5 version

	$query = "SHOW COLUMNS FROM  users like 'user_guid';";
	$resarr = array();
    $result = $cn->query($query);
    if ($result) {
            while ($row = $result->fetch_assoc()) {
                    array_push($resarr, $row);
            }
    }
	$columnExists = count($resarr) > 0;

	if (!$columnExists) {
		$query = "ALTER TABLE users ADD user_guid varchar(40) AFTER user_hash;";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	}

	$query = "ALTER TABLE `users` ADD INDEX ( `user_guid` ); ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `createtree`; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "	
			CREATE PROCEDURE createtree( users_id VARCHAR(250) )
			BEGIN

			DECLARE l_idobject INT;
			DECLARE l_parent_idobject INT;
			DECLARE l_o_ileft INT;
			DECLARE l_o_iright INT;
			DECLARE done INT default 0;
			DECLARE cursor_roots Cursor for
				SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `o_useinsearch` = 1;

			DECLARE cursor_tree Cursor for
				SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `parent_idobject` = 0 ORDER BY o_ileft DESC;

			DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

				DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp` ;
				CREATE TEMPORARY TABLE chkrt_o_temp (
				`idobject` INT NOT NULL,
				`parent_idobject` INT NOT NULL,
				`ad0` INT NOT NULL,
				`ad1` INT NOT NULL,
				`ad2` INT NOT NULL,
				`root` INT NOT NULL,
				`o_ileft` INT NOT NULL,
				`o_iright` INT NOT NULL,
				`o_useinsearch` INT NOT NULL,
				 PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;

				CREATE INDEX ix_pid ON chkrt_o_temp (parent_idobject);
				CREATE INDEX ix_il ON chkrt_o_temp (o_ileft);
				CREATE INDEX ix_ir ON chkrt_o_temp (o_iright);
				CREATE INDEX ix_uis ON chkrt_o_temp (o_useinsearch);


				INSERT IGNORE INTO `chkrt_o_temp`
					SELECT `idobject`, `parent_idobject`, 0, 0, 0, 1, `o_ileft`, `o_iright`, `o_useinsearch`  FROM `objects` WHERE `parent_idobject` <> 0;


					SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `rightsobjects` ON (chkrt_o_temp.idobject = rightsobjects.idobject) SET  ad0 = 1 WHERE rightsobjects.`iduser` IN (',users_id,') AND rightsobjects.`deny_allow` = 0;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

			    SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `rightsobjects` ON (chkrt_o_temp.idobject = rightsobjects.idobject) SET  ad1 = 1 WHERE rightsobjects.`iduser` IN (',users_id,') AND rightsobjects.`deny_allow` = 1;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

			    SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `rightsobjects` ON (chkrt_o_temp.idobject = rightsobjects.idobject) SET  ad2 = 1 WHERE rightsobjects.`iduser` IN (',users_id,') AND rightsobjects.`deny_allow` = 2;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;


			DELETE FROM chkrt_o_temp WHERE ad0 = 1 AND o_useinsearch = 0;
			DELETE FROM chkrt_o_temp WHERE (ad1 < 1 OR ad2 < 1) AND o_useinsearch = 0;

					SET @query = CONCAT('INSERT IGNORE INTO chkrt_o_temp SELECT o.`idobject`, o.`parent_idobject`, 0, 0, 0, 1, o.`o_ileft`, o.`o_iright`, o.`o_useinsearch`  FROM `objects` as o INNER JOIN  `users` as u ON u.`user_guid` = o.`o_guid` WHERE `parent_idobject` <> 0 AND u.`iduser` IN (',users_id,') ;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

			OPEN cursor_roots;
			WHILE done = 0 DO
			   FETCH cursor_roots INTO l_idobject,l_o_ileft,l_o_iright;
			   SELECT COUNT(*) into @c FROM `chkrt_o_temp` WHERE `o_ileft` BETWEEN l_o_ileft AND l_o_iright AND `o_useinsearch` = 0;
			   IF (@c = 0) THEN
				DELETE FROM chkrt_o_temp WHERE idobject = l_idobject;
			   END IF;
			END WHILE;
			Close cursor_roots;


				DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_id` ;
				CREATE TEMPORARY TABLE chkrt_o_temp_id (
				`idobject` INT NOT NULL,
				 PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;


				INSERT IGNORE INTO `chkrt_o_temp_id`
					SELECT `idobject` FROM chkrt_o_temp;


			UPDATE chkrt_o_temp RIGHT OUTER JOIN `chkrt_o_temp_id` ON (chkrt_o_temp.parent_idobject = chkrt_o_temp_id.idobject)
			SET root = 0;
			UPDATE chkrt_o_temp SET parent_idobject = 0 WHERE root = 1;

			SET done=0;

			OPEN cursor_tree;
			WHILE done = 0 DO
			   FETCH cursor_tree INTO l_idobject,l_o_ileft,l_o_iright;
			      SET l_parent_idobject = 0;
			   SELECT idobject INTO l_parent_idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1;
			   UPDATE `chkrt_o_temp` SET `parent_idobject` = l_parent_idobject WHERE `idobject`= l_idobject;
			END WHILE;
			Close cursor_tree;

			END
			;
	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 5;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 6) {
	// update to 6 version

	$query = "SHOW COLUMNS FROM  objects like 'o_hidefrotree';";
	$resarr = array();
    $result = $cn->query($query);
    if ($result) {
            while ($row = $result->fetch_assoc()) {
                    array_push($resarr, $row);
            }
    }
	$columnExists = count($resarr) > 0;

	if (!$columnExists) {
		$query = "ALTER TABLE `objects` ADD o_hidefortree int(1)  AFTER o_useinsearch;";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	}

	$query = "UPDATE `objects` SET o_hidefortree = 0;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `createtree`; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "	
			CREATE PROCEDURE createtree( users_id VARCHAR(250) )
			BEGIN

			DECLARE l_idobject INT;
			DECLARE l_parent_idobject INT;
			DECLARE l_o_ileft INT;
			DECLARE l_o_iright INT;
			DECLARE done INT default 0;
			DECLARE cursor_roots Cursor for
				SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `o_useinsearch` = 1;

			DECLARE cursor_tree Cursor for
				SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `parent_idobject` = 0 ORDER BY o_ileft DESC;

			DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

				DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp` ;
				CREATE TEMPORARY TABLE chkrt_o_temp (
				`idobject` INT NOT NULL,
				`parent_idobject` INT NOT NULL,
				`ad0` INT NOT NULL,
				`ad1` INT NOT NULL,
				`ad2` INT NOT NULL,
				`root` INT NOT NULL,
				`o_ileft` INT NOT NULL,
				`o_iright` INT NOT NULL,
				`o_useinsearch` INT NOT NULL,
				 PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;

				CREATE INDEX ix_pid ON chkrt_o_temp (parent_idobject);
				CREATE INDEX ix_il ON chkrt_o_temp (o_ileft);
				CREATE INDEX ix_ir ON chkrt_o_temp (o_iright);
				CREATE INDEX ix_uis ON chkrt_o_temp (o_useinsearch);


				INSERT IGNORE INTO `chkrt_o_temp`
					SELECT `idobject`, `parent_idobject`, 0, 0, 0, 1, `o_ileft`, `o_iright`, `o_useinsearch`  FROM `objects` WHERE `parent_idobject` <> 0 AND `o_hidefortree` = 0;


					SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `rightsobjects` ON (chkrt_o_temp.idobject = rightsobjects.idobject) SET  ad0 = 1 WHERE rightsobjects.`iduser` IN (',users_id,') AND rightsobjects.`deny_allow` = 0;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

			    SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `rightsobjects` ON (chkrt_o_temp.idobject = rightsobjects.idobject) SET  ad1 = 1 WHERE rightsobjects.`iduser` IN (',users_id,') AND rightsobjects.`deny_allow` = 1;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

			    SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `rightsobjects` ON (chkrt_o_temp.idobject = rightsobjects.idobject) SET  ad2 = 1 WHERE rightsobjects.`iduser` IN (',users_id,') AND rightsobjects.`deny_allow` = 2;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

			    DELETE FROM chkrt_o_temp WHERE (ad1 < 1 OR ad2 < 1) AND o_useinsearch = 0;

			    SET @query = CONCAT('INSERT IGNORE INTO chkrt_o_temp SELECT o.`idobject`, o.`parent_idobject`, 0, 0, 0, 1, o.`o_ileft`, o.`o_iright`, o.`o_useinsearch`  FROM `objects` as o INNER JOIN  `users` as u ON u.`user_guid` = o.`o_guid` WHERE `parent_idobject` <> 0 AND `o_hidefortree` = 0 AND u.`iduser` IN (',users_id,') ;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

			    DELETE FROM chkrt_o_temp WHERE ad0 = 1 AND o_useinsearch = 0;

			OPEN cursor_roots;
			WHILE done = 0 DO
			   FETCH cursor_roots INTO l_idobject,l_o_ileft,l_o_iright;
			   SELECT COUNT(*) into @c FROM `chkrt_o_temp` WHERE `o_ileft` BETWEEN l_o_ileft AND l_o_iright AND `o_useinsearch` = 0;
			   IF (@c = 0) THEN
				DELETE FROM chkrt_o_temp WHERE idobject = l_idobject;
			   END IF;
			END WHILE;
			Close cursor_roots;


				DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_id` ;
				CREATE TEMPORARY TABLE chkrt_o_temp_id (
				`idobject` INT NOT NULL,
				 PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;


				INSERT IGNORE INTO `chkrt_o_temp_id`
					SELECT `idobject` FROM chkrt_o_temp;


			UPDATE chkrt_o_temp RIGHT OUTER JOIN `chkrt_o_temp_id` ON (chkrt_o_temp.parent_idobject = chkrt_o_temp_id.idobject)
			SET root = 0;
			UPDATE chkrt_o_temp SET parent_idobject = 0 WHERE root = 1;

			SET done=0;

			OPEN cursor_tree;
			WHILE done = 0 DO
			   FETCH cursor_tree INTO l_idobject,l_o_ileft,l_o_iright;
			      SET l_parent_idobject = 0;
			   SELECT idobject INTO l_parent_idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1;
			   UPDATE `chkrt_o_temp` SET `parent_idobject` = l_parent_idobject WHERE `idobject`= l_idobject;
			END WHILE;
			Close cursor_tree;

			END
			;
	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `add_objects` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
			CREATE PROCEDURE add_objects(parent_guid CHAR(36), name VARCHAR(500), guid CHAR(36), icon INT, datechange DATETIME, ver VARCHAR(10), datever DATE, statever INT, hasreports TINYINT, useinsearch TINYINT, hidefortree TINYINT)
				BEGIN
				    declare parent_iright INT DEFAULT null;
				    declare parent_id INT  DEFAULT null;
				    declare parent_depth TINYINT DEFAULT null;

				    SELECT `o_iright`, `o_depth`, `idobject` into parent_iright, parent_depth, parent_id from objects where o_guid=parent_guid;
				    IF ( parent_id IS NOT null ) THEN
					UPDATE objects SET `o_ileft`=`o_ileft`+2,`o_iright`=`o_iright`+2 where `o_ileft`>parent_iright;
				    	UPDATE objects SET `o_iright`=`o_iright`+2 where `o_iright`>=parent_iright AND `o_ileft`<parent_iright;
				    	INSERT INTO `objects` (`parent_idobject`, `o_ileft`, `o_iright`, `o_depth`, `o_name`, `o_guid`, `o_icon`, `o_datechange`, `o_ver` , `o_datever` , `o_statever`, `o_hasreports`, `o_useinsearch`, `o_hidefortree` ) VALUES (parent_id, parent_iright, parent_iright+1, parent_depth+1, name, guid, icon, datechange, ver , datever , statever, hasreports, useinsearch, hidefortree );
				    END IF;
				END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE `version` SET `version` = 6;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}



if ($ver < 7) {
	// update to 7 version

	$query = "DROP PROCEDURE IF EXISTS `createtree`; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "	
			CREATE PROCEDURE createtree( users_id VARCHAR(250) )
			BEGIN

			DECLARE l_idobject INT;
			DECLARE l_parent_idobject INT;
			DECLARE l_o_ileft INT;
			DECLARE l_o_iright INT;
			DECLARE done INT default 0;
			DECLARE cursor_roots Cursor for
				SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `o_useinsearch` = 1;

			DECLARE cursor_tree Cursor for
				SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `parent_idobject` = 0 ORDER BY o_ileft DESC;

			DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

				DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp` ;
				CREATE TEMPORARY TABLE chkrt_o_temp (
				`idobject` INT NOT NULL,
				`parent_idobject` INT NOT NULL,
				`ad0` INT NOT NULL,
				`ad1` INT NOT NULL,
				`ad2` INT NOT NULL,
				`root` INT NOT NULL,
				`o_ileft` INT NOT NULL,
				`o_iright` INT NOT NULL,
				`o_useinsearch` INT NOT NULL,
				 PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;

				CREATE INDEX ix_pid ON chkrt_o_temp (parent_idobject);
				CREATE INDEX ix_il ON chkrt_o_temp (o_ileft);
				CREATE INDEX ix_ir ON chkrt_o_temp (o_iright);
				CREATE INDEX ix_uis ON chkrt_o_temp (o_useinsearch);


				INSERT IGNORE INTO `chkrt_o_temp`
					SELECT `idobject`, `parent_idobject`, 0, 0, 0, 1, `o_ileft`, `o_iright`, `o_useinsearch`  FROM `objects` WHERE `parent_idobject` <> 0 AND `o_hidefortree` = 0 AND `idobject`;
					SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `rightsobjects` ON (chkrt_o_temp.idobject = rightsobjects.idobject) SET  ad0 = 1 WHERE rightsobjects.`iduser` IN (',users_id,') AND rightsobjects.`deny_allow` = 0;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

			    SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `rightsobjects` ON (chkrt_o_temp.idobject = rightsobjects.idobject) SET  ad1 = 1 WHERE rightsobjects.`iduser` IN (',users_id,') AND rightsobjects.`deny_allow` = 1;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

			    SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `rightsobjects` ON (chkrt_o_temp.idobject = rightsobjects.idobject) SET  ad2 = 1 WHERE rightsobjects.`iduser` IN (',users_id,') AND rightsobjects.`deny_allow` = 2;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

			 	 DELETE FROM chkrt_o_temp WHERE (ad1 < 1 OR ad2 < 1) AND o_useinsearch = 0;

			    DELETE FROM chkrt_o_temp WHERE ad0 = 1 AND o_useinsearch = 0;

			    SET @query = CONCAT('INSERT IGNORE INTO chkrt_o_temp SELECT o.`idobject`, o.`parent_idobject`, 1, 1, 0, 1, o.`o_ileft`, o.`o_iright`, o.`o_useinsearch`  FROM `objects` as o INNER JOIN  `users` as u ON u.`user_guid` = o.`o_guid` WHERE `parent_idobject` <> 0 AND  o.`idobject` NOT IN (SELECT idobject FROM `rightsobjects` WHERE `deny_allow` IN (0,1,2)) AND  `o_hidefortree` = 0 AND u.`iduser` IN (',users_id,') ;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

			OPEN cursor_roots;
			WHILE done = 0 DO
			   FETCH cursor_roots INTO l_idobject,l_o_ileft,l_o_iright;
			   SELECT COUNT(*) into @c FROM `chkrt_o_temp` WHERE `o_ileft` BETWEEN l_o_ileft AND l_o_iright AND `o_useinsearch` = 0;
			   IF (@c = 0) THEN
				DELETE FROM chkrt_o_temp WHERE idobject = l_idobject;
			   END IF;
			END WHILE;
			Close cursor_roots;


				DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_id` ;
				CREATE TEMPORARY TABLE chkrt_o_temp_id (
				`idobject` INT NOT NULL,
				 PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;


				INSERT IGNORE INTO `chkrt_o_temp_id`
					SELECT `idobject` FROM chkrt_o_temp;


			UPDATE chkrt_o_temp RIGHT OUTER JOIN `chkrt_o_temp_id` ON (chkrt_o_temp.parent_idobject = chkrt_o_temp_id.idobject)
			SET root = 0;
			UPDATE chkrt_o_temp SET parent_idobject = 0 WHERE root = 1;

			SET done=0;

			OPEN cursor_tree;
			WHILE done = 0 DO
			   FETCH cursor_tree INTO l_idobject,l_o_ileft,l_o_iright;
			      SET l_parent_idobject = 0;
			   SELECT idobject INTO l_parent_idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1;
			   UPDATE `chkrt_o_temp` SET `parent_idobject` = l_parent_idobject WHERE `idobject`= l_idobject;
			END WHILE;
			Close cursor_tree;

			END
			;
	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "DROP PROCEDURE IF EXISTS `load_reports`; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "	
		CREATE PROCEDURE load_reports(o_guid CHAR(36), userights INT, users_id VARCHAR(250))
		BEGIN
			declare idobject INT DEFAULT -1;

		   DROP TEMPORARY TABLE IF EXISTS `r_temp` ;
			CREATE TEMPORARY TABLE `r_temp` (
				`idreport` INT NOT NULL
			)ENGINE=MEMORY;


		   DROP TEMPORARY TABLE IF EXISTS `rr_temp` ;
		   CREATE TEMPORARY TABLE rr_temp (
		   	`idreport` INT NOT NULL,
		     PRIMARY KEY (`idreport`)
		   )ENGINE=MEMORY;

		   SELECT obj.`idobject` into idobject from `objects` as obj where obj.`o_guid` = o_guid;

		   IF ( idobject > 0 ) THEN
			 	INSERT INTO r_temp SELECT rep.`idreport` FROM `reports` as rep, `objectsreports` as orl WHERE orl.`idobject` = idobject AND orl.`idreport` = rep.`idreport`;

				IF ( userights <> 0 ) THEN
			   	INSERT INTO `rr_temp` SELECT `idreport` FROM `r_temp`;
					SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` IN ( SELECT rr.`idreport` FROM `rightsreports` as rr, `r_temp` as rt WHERE rt.`idreport` = rr.`idreport` AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 0 );'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

					SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr, `r_temp` as rt WHERE rt.`idreport` = rr.`idreport` AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 1 );'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

					SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr, `r_temp` as rt WHERE rt.`idreport` = rr.`idreport` AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 2 );'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

			      SET @query = CONCAT('INSERT IGNORE INTO `rr_temp`	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 (',users_id,') and o.o_guid = \"',o_guid,'\" AND orts.idreport NOT IN (SELECT rr.idreport FROM  `rightsreports` as rr WHERE  rr.deny_allow in (0,1,2));'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;

					DELETE FROM r_temp  WHERE r_temp.`idreport` NOT IN ( SELECT rr_temp.`idreport` FROM rr_temp );
				END IF;
		   END IF;
		END;

	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 7;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}



if ($ver < 8) {
	// update to 8 version

	$query = "DROP PROCEDURE IF EXISTS `load_objecttree` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "	
				CREATE PROCEDURE load_objecttree(idobject INT, userights INT, users_id VARCHAR(250))
				BEGIN
				    declare parent_idobject INT DEFAULT idobject;

				    DROP TEMPORARY TABLE IF EXISTS `o_temp_tree` ;
				    CREATE TEMPORARY TABLE o_temp_tree (
					`idpobject` INT NOT NULL,
					`parent_idobject` INT NOT NULL,
					 PRIMARY KEY (`idpobject`)
					)ENGINE=MEMORY;

				  IF ( userights = 0 ) THEN
				    WHILE ( parent_idobject <> 0 ) DO
				        SELECT obj.`parent_idobject` into parent_idobject from `objects` as obj where obj.`idobject` = parent_idobject;
				        INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`parent_idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND  `o_hidefortree` = 0;
				    END WHILE;
				  ELSE
				    CALL createtree(users_id);
				    WHILE ( parent_idobject <> 0 ) DO
				        SELECT obj.`parent_idobject` into parent_idobject from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject;
				        INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, obj.`parent_idobject` FROM `chkrt_o_temp` as obj WHERE obj.`parent_idobject` = parent_idobject AND obj.`parent_idobject` <> 0 ;
				    END WHILE;
				  END IF;

				  CALL load_objects(0, userights, users_id);
				END
				;
	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "DROP PROCEDURE IF EXISTS `load_objects` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

		$query = "	
					CREATE PROCEDURE load_objects(parent_idobject INT, userights INT, users_id VARCHAR(250) )
					BEGIN
					declare root_parent_idobject INT;
					DROP TEMPORARY TABLE IF EXISTS `o_temp` ;
					    CREATE TEMPORARY TABLE o_temp (
						`idobject` INT NOT NULL,
						`parent_idobject` INT NOT NULL,
						 PRIMARY KEY (`idobject`)
						)ENGINE=MEMORY;
					  IF ( userights = 0 ) THEN
					     IF ( parent_idobject = 0 ) THEN
					        SELECT obj.`idobject` into root_parent_idobject from `objects` as obj where obj.`parent_idobject` = 0;
					     ELSE
					        SET root_parent_idobject = parent_idobject;
					     END IF;
					        INSERT IGNORE INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`parent_idobject` = root_parent_idobject AND  `o_hidefortree` = 0;
					  ELSE
					        CALL createtree(users_id);
					        INSERT IGNORE INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `chkrt_o_temp` as obj WHERE obj.`parent_idobject` = parent_idobject ;
					  END IF;
					END
					;

	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 9) {
	// update to 9 version

	$query = "DROP PROCEDURE IF EXISTS `load_objecttree` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
			
			CREATE PROCEDURE `load_objecttree`(IN `idobject` INT, IN `userights` INT, IN `users_id` VARCHAR(250))
			BEGIN
			    declare parent_idobject INT DEFAULT idobject;

			    DROP TEMPORARY TABLE IF EXISTS `o_temp_tree` ;
			    CREATE TEMPORARY TABLE o_temp_tree (
				`idpobject` INT NOT NULL,
				`parent_idobject` INT NOT NULL,
				 PRIMARY KEY (`idpobject`)
				)ENGINE=MEMORY;

			  IF ( userights = 0 ) THEN
			    WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0) DO
			        SELECT IFNULL(obj.`parent_idobject`, 0) into parent_idobject from `objects` as obj where obj.`idobject` = parent_idobject;
			        INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`parent_idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND  `o_hidefortree` = 0;
			    END WHILE;
			  ELSE
			    CALL createtree(users_id);
			    WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0 ) DO
			  		IF EXISTS (SELECT 1 from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject) THEN
			        	SELECT IFNULL(obj.`parent_idobject`, 0) into parent_idobject from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject;
			        	INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, obj.`parent_idobject` FROM `chkrt_o_temp` as obj WHERE obj.`parent_idobject` = parent_idobject AND obj.`parent_idobject` <> 0 ;
			    	ELSE
			    		SELECT 0 into parent_idobject;
			    	END IF;
			    END WHILE;
			  END IF;

			  CALL load_objects(0, userights, users_id);
			END
			;
	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "DROP PROCEDURE IF EXISTS `load_objectpath` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

		$query = "
					
					CREATE PROCEDURE `load_objectpath`(IN `idobject` INT, IN `userights` INT, IN `users_id` VARCHAR(500))
					BEGIN
					    declare parent_idobject INT DEFAULT idobject;

					    DROP TEMPORARY TABLE IF EXISTS `o_temp_tree` ;
					    CREATE TEMPORARY TABLE o_temp_tree (
					        `idpobject` INT NOT NULL,
					        `parent_idobject` INT NOT NULL,
					        `o_ileft` INT NOT NULL,
					        PRIMARY KEY (`idpobject`)
					    )ENGINE=MEMORY;

					  IF ( userights = 0 ) THEN
					    WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0  ) DO
					        INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, IFNULL(obj.`parent_idobject`, 0), obj.`o_ileft` FROM `objects` as obj WHERE obj.`idobject` = parent_idobject AND obj.`parent_idobject` <> 0;
					        SELECT IFNULL(obj.`parent_idobject`, 0) into parent_idobject from `objects` as obj where obj.`idobject` = parent_idobject;
					    END WHILE;
					  ELSE
					    CALL createtree(users_id);
					    WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0 ) DO
					   	IF EXISTS (SELECT 1 FROM `chkrt_o_temp` as obj WHERE obj.`idobject` = parent_idobject AND obj.`parent_idobject` <> 0) THEN
								INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, IFNULL(obj.`parent_idobject`, 0), obj.`o_ileft` FROM `chkrt_o_temp` as obj WHERE obj.`idobject` = parent_idobject AND obj.`parent_idobject` <> 0;
					      	SELECT IFNULL(obj.`parent_idobject`, 0) into parent_idobject from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject;
					    	ELSE
					    		SELECT 0 into parent_idobject;
					    	END IF;
						 END WHILE;
					  END IF;
					END;

	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 9;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 10) {
	// update to 10 version

	$query = "ALTER TABLE forummessages CHANGE frmm_body frmm_body LONGTEXT; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "DROP PROCEDURE IF EXISTS `add_forummessages` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

		$query = "
					
					CREATE PROCEDURE `add_forummessages`(parent_idforummessage INT, o_guid VARCHAR(36), iduser INT, frmm_body LONGTEXT)
					BEGIN

					    declare cnt BIGINT DEFAULT null;
					    declare parent_iright BIGINT;
					    declare parent_depth BIGINT;

					    SELECT COUNT(*) into cnt from `forummessages`;
					    IF (cnt = 0 ) THEN
						INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_datechange`, `frmm_isdelete`) VALUES ('0', '0', '00000000-0000-0000-0000-000000000000', '0', '1', '2', '0', 'root', '2000-01-01 00:00:00', 0);
						UPDATE `forummessages` SET `idforummessage` = 0;
					    END IF;

					    IF (CHAR_LENGTH(o_guid) <= 36 AND iduser > 1) THEN
						select `frmm_iright`, `frmm_depth` into parent_iright, parent_depth from `forummessages` as frmm where frmm.`idforummessage` = parent_idforummessage;
						UPDATE forummessages SET `frmm_ileft`=`frmm_ileft`+2,`frmm_iright`=`frmm_iright`+2 where `frmm_ileft`>parent_iright;
						UPDATE forummessages SET `frmm_iright`=`frmm_iright`+2 where `frmm_iright`>=parent_iright AND `frmm_ileft`<parent_iright;
						INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_datechange`, `frmm_isdelete`) VALUES (NULL, parent_idforummessage, o_guid, iduser, parent_iright, parent_iright+1, parent_depth+1, frmm_body, NOW(), 0);
					    END IF;

					END
					;

	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "DROP FUNCTION  IF EXISTS `get_forummessageroot` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

		$query = "CREATE FUNCTION  get_forummessageroot(idforummessage BIGINT)
			RETURNS BIGINT 
		BEGIN
			DECLARE root_forummessage BIGINT DEFAULT 0;
			 DECLARE cur_idforummessage BIGINT DEFAULT 0;
			 SELECT idforummessage INTO cur_idforummessage;
			 
			WHILE ( cur_idforummessage > 0 ) DO	
				  SELECT cur_idforummessage INTO root_forummessage;	
				SELECT frm.`parent_idforummessage` into cur_idforummessage from `forummessages` as frm where frm.`idforummessage` = cur_idforummessage;
			END WHILE;
			RETURN root_forummessage;
		END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "SHOW COLUMNS FROM forummessages like 'frmm_ischanged';";
	$resarr = array();
    $result = $cn->query($query);
    if ($result) {
            while ($row = $result->fetch_assoc()) {
                    array_push($resarr, $row);
            }
    }
	$columnExists = count($resarr) > 0;

	if (!$columnExists) {
		$query = "ALTER TABLE `forummessages`  ADD frmm_ischanged int(1)  AFTER frmm_isdelete;";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	}

	$query = "UPDATE `forummessages` SET frmm_ischanged = 0;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `clear_forummessages` ;  ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

		$query = "
			CREATE PROCEDURE clear_forummessages()
			BEGIN
				DELETE FROM `forummessages`;
				INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_datechange`, `frmm_isdelete`, `frmm_ischanged`) VALUES ('0', '0', '00000000-0000-0000-0000-000000000000', '0', '1', '2', '1', NULL, NOW(), 0, 0);
				UPDATE `forummessages` SET `idforummessage` = 0;

			END;
	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `add_forummessages` ;  ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

		$query = "
			CREATE PROCEDURE `add_forummessages`(parent_idforummessage INT, o_guid VARCHAR(36), iduser INT, frmm_body LONGTEXT)
			BEGIN

			    declare cnt BIGINT DEFAULT null;
			    declare parent_iright BIGINT;
			    declare parent_depth BIGINT;

			    SELECT COUNT(*) into cnt from `forummessages`;
			    IF (cnt = 0 ) THEN
				INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_datechange`, `frmm_isdelete`, `frmm_ischanged`) VALUES ('0', '0', '00000000-0000-0000-0000-000000000000', '0', '1', '2', '0', 'root', '2000-01-01 00:00:00', 0, 0);
				UPDATE `forummessages` SET `idforummessage` = 0;
			    END IF;

			    IF (CHAR_LENGTH(o_guid) <= 36 AND iduser > 1) THEN
				select `frmm_iright`, `frmm_depth` into parent_iright, parent_depth from `forummessages` as frmm where frmm.`idforummessage` = parent_idforummessage;
				UPDATE forummessages SET `frmm_ileft`=`frmm_ileft`+2,`frmm_iright`=`frmm_iright`+2 where `frmm_ileft`>parent_iright;
				UPDATE forummessages SET `frmm_iright`=`frmm_iright`+2 where `frmm_iright`>=parent_iright AND `frmm_ileft`<parent_iright;
				INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_datechange`, `frmm_isdelete`,  `frmm_ischanged`) VALUES (NULL, parent_idforummessage, o_guid, iduser, parent_iright, parent_iright+1, parent_depth+1, frmm_body, NOW(), 0, 0);
			    END IF;

			END
			;
	";


	$query = "DROP TABLE IF EXISTS `forummessagessaw` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE forummessagessaw (
				`iduser` INT NOT NULL ,
				`o_guid` CHAR(40) NOT NULL,
				`frmsw_sessionhash` VARCHAR(255) NOT NULL,
				`frmsw_datesaw` DATETIME NOT NULL,
				 PRIMARY KEY(iduser, o_guid)
				)ENGINE=InnoDB; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE INDEX forummessagessaw_o_guid
        ON forummessagessaw (`o_guid`); ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "DROP PROCEDURE IF EXISTS `add_forummessages` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE `version` SET `version` = 10;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 11) {
	// update to 11 version

	$query = "DROP PROCEDURE IF EXISTS `load_objecttree_search` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

db_disconnect($cn);
$cn = db_connect();
		$query = "
					CREATE PROCEDURE  `load_objecttree_search`()
					BEGIN
					    DROP TEMPORARY TABLE IF EXISTS `o_temp` ;
					    CREATE TEMPORARY TABLE o_temp (
						`idobject` INT NOT NULL,
						`parent_idobject` INT NOT NULL,
						 PRIMARY KEY (`idobject`)
						)ENGINE=MEMORY;

					    INSERT INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`o_useinsearch` = 1 AND obj.`o_hidefortree` = 0;
					END;

	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 11;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}



if ($ver < 12) {
	// update to 12 version

	$query = "SHOW COLUMNS FROM forummessagessaw like 'frmsw_datelastsaw';";
	$resarr = array();
    $result = $cn->query($query);
    if ($result) {
            while ($row = $result->fetch_assoc()) {
                    array_push($resarr, $row);
            }
    }
	$columnExists = count($resarr) > 0;

	if (!$columnExists) {
		$query = "ALTER TABLE `forummessagessaw`  ADD frmsw_datelastsaw DATETIME AFTER frmsw_datesaw;";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	}

	$query = "UPDATE `forummessagessaw` SET frmsw_datelastsaw = frmsw_datesaw;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE `version` SET `version` = 12;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 13) {
	// update to 13 version

	$query = "ALTER TABLE `resourcefromtables` MODIFY `rft_columnname_text` VARCHAR(1100);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "ALTER TABLE `objects` MODIFY `o_name` VARCHAR(1100);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "ALTER TABLE `reports` MODIFY `r_name` VARCHAR(1100);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `add_objects`; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

		$query = "
				CREATE PROCEDURE `add_objects`(IN `parent_guid` CHAR(36), IN `name` VARCHAR(1100), IN `guid` CHAR(36), IN `icon` INT, IN `datechange` DATETIME, IN `ver` VARCHAR(10), IN `datever` DATE, IN `statever` INT, IN `hasreports` TINYINT, IN `useinsearch` TINYINT, IN `hidefortree` TINYINT)
				BEGIN
				    declare parent_iright INT DEFAULT null;
				    declare parent_id INT  DEFAULT null;
				    declare parent_depth TINYINT DEFAULT null;

				    SELECT `o_iright`, `o_depth`, `idobject` into parent_iright, parent_depth, parent_id from objects where o_guid=parent_guid;
				    IF ( parent_id IS NOT null ) THEN
					UPDATE objects SET `o_ileft`=`o_ileft`+2,`o_iright`=`o_iright`+2 where `o_ileft`>parent_iright;
				    	UPDATE objects SET `o_iright`=`o_iright`+2 where `o_iright`>=parent_iright AND `o_ileft`<parent_iright;
				    	INSERT INTO `objects` (`parent_idobject`, `o_ileft`, `o_iright`, `o_depth`, `o_name`, `o_guid`, `o_icon`, `o_datechange`, `o_ver` , `o_datever` , `o_statever`, `o_hasreports`, `o_useinsearch`, `o_hidefortree` ) VALUES (parent_id, parent_iright, parent_iright+1, parent_depth+1, name, guid, icon, datechange, ver , datever , statever, hasreports, useinsearch, hidefortree );
				    END IF;
				END;

	";
db_disconnect($cn);
$cn = db_connect();
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE `version` SET `version` = 13;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 18) {
	// update to 16 version

	$query = "delete from  `languages`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "alter table `languages` ADD native_name VARCHAR(255) after lang_name;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `languages` MODIFY lang_short VARCHAR(25) NOT NULL UNIQUE;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "alter table `languages` ADD allow BIT after lang_short;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "alter table `languages` ADD main BIT after allow; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "insert into `languages` values (1049, 'Russian(Russia)', 'Русский', 'ru-ru', 1, 1), (1033, 'English (United States)', 'English', 'en-us', 1, 0); ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "update `reports` set `idlanguage` = 1049 where `idlanguage` = 419; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "update `resourcefromtables` set `idlanguage` = 1049 where `idlanguage` = 419; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "update `users` set `user_idlanguageinterface` = 1049 where `user_idlanguageinterface` = 419; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "update `users` set `user_idlanguagecontent` = 1049 where `user_idlanguagecontent` = 419;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "update `titleindex` set `idlanguage` = 1049 where `idlanguage` = 419; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

		
	$query = "alter table `reportindex` ADD idlanguage INT after idreport; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "ALTER TABLE `reportindex` ADD COLUMN skbranch int(11) NULL AFTER `idlanguage`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "create index titleindex_idlanguage ON titleindex(idlanguage); ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "create index reportindex_idlanguage ON reportindex(idlanguage); ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "update `reportindex` set `idlanguage` = 1049; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "delete from `resourcefromtables` where `idtable` = 0; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

//	$query = "insert into `resourcefromtables` values (1033, 0, 1033, 'English'),(1033, 0, 1049, 'Английский'),(1049, 0, 1033, 'Russian'),(1049, 0, 1049, 'Русский'); ";
	//if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
			-- Временное решение, т.к. меняем способ отображения уведомлений о выходе новой версии
		ALTER TABLE `objects` CHANGE `o_ver` `o_ver` varchar(312) NOT NULL DEFAULT ' ';";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "

		-- Обновление процедуры добавки объектов, чтобы учитывался вариант с длинной версией
		DROP PROCEDURE IF EXISTS `add_objects`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "


		CREATE PROCEDURE add_objects(parent_guid CHAR(40), name VARCHAR(1100), guid CHAR(40), icon INT, datechange DATETIME, ver VARCHAR(312), datever DATE, statever INT, hasreports TINYINT, useinsearch TINYINT, hidefortree TINYINT)
			BEGIN
				declare parent_iright INT DEFAULT null;
				declare parent_id INT  DEFAULT null;
				declare parent_depth TINYINT DEFAULT null;

				SELECT `o_iright`, `o_depth`, `idobject` into parent_iright, parent_depth, parent_id from objects where o_guid=parent_guid;
				IF ( parent_id IS NOT null ) THEN	
				UPDATE objects SET `o_ileft`=`o_ileft`+2,`o_iright`=`o_iright`+2 where `o_ileft`>parent_iright;
					UPDATE objects SET `o_iright`=`o_iright`+2 where `o_iright`>=parent_iright AND `o_ileft`<parent_iright;
					INSERT INTO `objects` (`parent_idobject`, `o_ileft`, `o_iright`, `o_depth`, `o_name`, `o_guid`, `o_icon`, `o_datechange`, `o_ver` , `o_datever` , `o_statever`, `o_hasreports`, `o_useinsearch`, `o_hidefortree` ) VALUES (parent_id, parent_iright, parent_iright+1, parent_depth+1, name, guid, icon, datechange, ver , datever , statever, hasreports, useinsearch, hidefortree );
				END IF;	      
			END;
	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "UPDATE `version` SET `version` = 18;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 19) {
	// update to 19 version

	$query = "ALTER TABLE `users` CHANGE `user_email` `user_email` varchar(256) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

    $query = "UPDATE `version` SET `version` = 19;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 20) {
	// update to 20 version

	$query = "ALTER TABLE `objectsreports` ADD idlanguage INT(11) NOT NULL AFTER `or_datechange`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objectsreports`
		DROP PRIMARY KEY,
		ADD PRIMARY KEY (`idobject`, `idreport`, `idlanguage`);
		";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `load_reports` ;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "
		CREATE PROCEDURE  `load_reports`(o_guid CHAR(40), userights INT, users_id VARCHAR(500), idlanguage INT)
		BEGIN
			declare idobject INT DEFAULT -1;
		
		DROP TEMPORARY TABLE IF EXISTS `r_temp` ;
			CREATE TEMPORARY TABLE `r_temp` (
				`idreport` INT NOT NULL
			)ENGINE=MEMORY;
		
		
		DROP TEMPORARY TABLE IF EXISTS `rr_temp` ;
		CREATE TEMPORARY TABLE rr_temp (    
			`idreport` INT NOT NULL,
			PRIMARY KEY (`idreport`)
		)ENGINE=MEMORY;
		
		SELECT obj.`idobject` into idobject from `objects` as obj where obj.`o_guid` = o_guid;
		
		IF ( idobject > 0 ) THEN
				INSERT INTO r_temp SELECT rep.`idreport` FROM `reports` as rep INNER JOIN `objectsreports` as orl ON orl.`idreport` = rep.`idreport` WHERE orl.`idobject` = idobject AND ifnull(orl.`idlanguage`,0) = ifnull(idlanguage,0); 
		
				IF ( userights <> 0 ) THEN
				INSERT INTO `rr_temp` SELECT `idreport` FROM `r_temp`; 
					SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` IN ( SELECT rr.`idreport` FROM `rightsreports` as rr, `r_temp` as rt WHERE rt.`idreport` = rr.`idreport` AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 0 );'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;
			
					SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr, `r_temp` as rt WHERE rt.`idreport` = rr.`idreport` AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 1 );'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;
			
					SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr, `r_temp` as rt WHERE rt.`idreport` = rr.`idreport` AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 2 );'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;
			
				SET @query = CONCAT('INSERT IGNORE INTO `rr_temp`	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 (',users_id,') and o.o_guid = \"',o_guid,'\" AND orts.idreport NOT IN (SELECT rr.idreport FROM  `rightsreports` as rr WHERE  rr.deny_allow in (0,1,2));'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;
					
					DELETE FROM r_temp  WHERE r_temp.`idreport` NOT IN ( SELECT rr_temp.`idreport` FROM rr_temp );
				END IF;	  
		END IF;	      
		END;  
	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `load_reportsAdmin` ;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
		CREATE PROCEDURE  `load_reportsAdmin`(o_guid CHAR(40),  idlanguage INT)
		BEGIN
			declare ileft BIGINT DEFAULT -1; 	
			declare iright BIGINT DEFAULT -1;
		
			DROP TEMPORARY TABLE IF EXISTS `r_temp` ;
			CREATE TEMPORARY TABLE `r_temp` (
			`idreport` INT NOT NULL
			)ENGINE=MEMORY;
		
		
			SELECT obj.`o_ileft`, obj.`o_iright` into  ileft, iright from `objects` as obj where CONVERT(obj.`o_guid` USING utf32) = CONVERT( o_guid  USING utf32)  ;
			INSERT INTO r_temp SELECT DISTINCT orl.`idreport` FROM `objects` as obj INNER JOIN `objectsreports` as orl ON obj.`idobject` = orl.`idobject` WHERE obj.`o_ileft` BETWEEN ileft AND iright AND ifnull(orl.`idlanguage`,0) = ifnull(idlanguage,0); 
		END;  
	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

    $query = "UPDATE `version` SET `version` = 20;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 21) {
	// update to 21 version

	$query = "DROP INDEX index_reports_r_guid ON reports;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

    $query = "UPDATE `version` SET `version` = 21;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 22) {
	// update to 22 version

	$query = 'SET @@session.time_zone = "+00:00";';
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "INSERT IGNORE INTO `tables` VALUES (0, 'languages'), (6, 'users'), (7, 'branches'), (8, 'polltypes'), (801, 'polltypes.description'), (9, 'polltypequestions'), (90, 'polltypequestionselectvalues'), (10, 'projects'), (1001, 'projects.description'), (11, 'pollingobjects'), (1101, 'pollingobjects.objectversiondescription'), (1102, 'pollingobjects.reportversiondescription'), (1103, 'pollingobjectsarchive.objectversiondescription'), (1104, 'pollingobjectsarchive.reportversiondescription');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP TABLE IF EXISTS `branches`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `branches` (
		`idbranch` VARCHAR(50) NOT NULL,
		`skbranch` INT(11) NOT NULL AUTO_INCREMENT,
		`ismain` TINYINT(4) NOT NULL,
		UNIQUE INDEX `idbranch` (`idbranch`),
		INDEX `skbranch` (`skbranch`)
	)
	ENGINE=InnoDB  DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "INSERT IGNORE INTO `branches` SELECT '0', 1, 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `polltypes` (
		`idpolltype` VARCHAR(150) NOT NULL,
		`skpolltype` INT NOT NULL AUTO_INCREMENT,
		`AllowComment` TINYINT NULL,
		PRIMARY KEY (`skpolltype`),
		UNIQUE INDEX `idpolltype` (`idpolltype`)
	)
	ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `polltypequestiontypes` (
		`idpolltypequestiontype` INT NOT NULL,
		`description` TINYTEXT NOT NULL,
		PRIMARY KEY (`idpolltypequestiontype`)
	)
	ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `polltypequestions` (
		`idpolltypequestion` VARCHAR(150) NOT NULL,
		`skpolltypequestion` INT NOT NULL AUTO_INCREMENT,
		`skpolltype` INT NOT NULL,
		`idpolltypequestiontype` INT NOT NULL DEFAULT '1',
		UNIQUE INDEX `idpolltypequestion` (`idpolltypequestion`),
		PRIMARY KEY (`skpolltypequestion`)
	)
	ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `polltypequestionselectvalues` (
		`idpolltypequestionselectvalue` VARCHAR(150) NOT NULL,
		`skpolltypequestionselectvalue` INT NOT NULL AUTO_INCREMENT,
		`skpolltypequestion` INT NOT NULL,
		UNIQUE INDEX `idpolltypequestionselectvalue` (`idpolltypequestionselectvalue`),
		PRIMARY KEY (`skpolltypequestionselectvalue`)
	)
	ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "INSERT IGNORE INTO `polltypequestiontypes` SELECT 1, 'CheckBox' UNION SELECT 2, 'List';  ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `projects` (
		`idproject` VARCHAR(150) NOT NULL,
		`skproject` INT NOT NULL AUTO_INCREMENT,
		`startdate` VARCHAR(10) NOT NULL,
		`enddate` VARCHAR(10) NOT NULL,	
		PRIMARY KEY (`skproject`),
		UNIQUE INDEX `idproject` (`idproject`)
	)
	ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `pollingobjectstatus` (
		`idpollingobjectstatus` TINYINT(4) NOT NULL,
		`description` VARCHAR(10) NOT NULL,	
		PRIMARY KEY (`idpollingobjectstatus`)
	)
	ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "INSERT INTO `pollingobjectstatus` VALUES (0,'Остановлен'), (1,'Активен'), (2,'Не активен');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `pollingobjects` (
		`idpollingobject` VARCHAR(150) NOT NULL,
		`skpollingobject` INT NOT NULL AUTO_INCREMENT,
		`objectversion` VARCHAR(250) NOT NULL,
		`objectversionhash` VARCHAR(128) NOT NULL,
		`objectversiondate_tmst` INT NOT NULL,
		`objectversionuhash` VARCHAR(250) NOT NULL,
		`reportversion` VARCHAR(250) NOT NULL,
		`reportversiondate_tmst` INT NOT NULL,
		`reportversionuhash` VARCHAR(250) NOT NULL,
		`skbranch` INT NOT NULL,
		`skproject` INT NULL,
		`o_guid` VARCHAR(40) NOT NULL,
		`r_guid` VARCHAR(40) NOT NULL,
		PRIMARY KEY (`skpollingobject`),
		UNIQUE INDEX `idpollingobject` (`idpollingobject`)
	)
	ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `pollingobjectsarchive` (
		`idpollingobjectarchive` INT NOT NULL AUTO_INCREMENT,
		`skpollingobject` INT NOT NULL,
		`objectversion` VARCHAR(150) NOT NULL,
		`objectversionhash` VARCHAR(128) NOT NULL,
		`objectversiondate_tmst` INT NOT NULL,
		`objectversionuhash` VARCHAR(250) NOT NULL,
		`reportversion` VARCHAR(250) NOT NULL,
		`reportversiondate_tmst` INT NOT NULL,
		`reportversionuhash` VARCHAR(250) NOT NULL,
		`isfileswassave` TINYINT NOT NULL DEFAULT '0',
		`o_guid` VARCHAR(40) NOT NULL,
		`r_guid` VARCHAR(40) NOT NULL,
		PRIMARY KEY (`idpollingobjectarchive`),
		UNIQUE INDEX `objectversion` (`objectversion`)
	)
	ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE IF NOT EXISTS `useranswers` (
			`idpollingobject` VARCHAR(250) NOT NULL,
			`idpolltype` VARCHAR(250) NOT NULL,
			`user_hash` VARCHAR(64) NOT NULL,
			`idpollingobjectstatus` TINYINT NOT NULL DEFAULT '10',
			PRIMARY KEY (`idpollingobject`(91),`idpolltype`(36),`user_hash`(64)) -- STU fix Specified key was too long; max key length is 767 bytes 91(need maximize)+36(guid)+64(hashsid)=191=>191*4=764<767
		)
		ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `useranswersvalues` (
		`skpollingobject` INT NOT NULL,
		`skpolltype` INT NOT NULL,
		`iduser` INT NOT NULL,
		`uav_value` INT NOT NULL,
		`uav_body` LONGTEXT NULL,
		`idforummessage` BIGINT NULL,
		`uav_tmst` INT NULL,
		PRIMARY KEY (`skpollingobject`,`skpolltype`,`iduser`)
	)
	ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `useranswersvaluesarchive` (
		`idpollingobjectarchive` INT NOT NULL,
		`skpolltype` INT NOT NULL,
		`iduser` INT NOT NULL,
		`uav_value` INT NOT NULL,
		`uav_body` LONGTEXT NULL,
		`idforummessage` BIGINT NULL,
		`uav_tmst` INT NULL,
		PRIMARY KEY (`idpollingobjectarchive`,`skpolltype`,`iduser`)
	)
	ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `useranswersvaluesarchivetext` (
		`idpollingobjectarchive` INT NOT NULL,
		`skpolltype` INT NOT NULL,
		`iduser` INT NOT NULL,
		`idlanguage` INT NOT NULL,
		`text` VARCHAR(2500) NULL,
		PRIMARY KEY (`idpollingobjectarchive`,`skpolltype`,`iduser`,`idlanguage`)
	)
	ENGINE=InnoDB DEFAULT CHARSET=utf8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `personallinks` ADD COLUMN skbranch INT(11) NOT NULL AFTER `r_guid`, 
		ADD COLUMN addurlparams VARCHAR(2000),
		DROP INDEX `o_guid`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `personallinks`  ADD INDEX `o_guid` (`o_guid`, `r_guid`, `skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE personallinks SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reports` 
		DROP COLUMN r_name,
		DROP COLUMN r_expirationdate,
		DROP COLUMN r_creationdate,
		ADD COLUMN skbranch INT;
	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
	UPDATE reports SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE INDEX indx_reports_skbranch ON reports(skbranch);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `rightsreports` ADD COLUMN skbranch INT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE rightsreports SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `rightsreports`
		ALTER `skbranch` DROP DEFAULT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `rightsreports`
		CHANGE COLUMN `skbranch` `skbranch` INT(11) NOT NULL AFTER `deny_allow`,
		DROP PRIMARY KEY,
		ADD PRIMARY KEY (`iduser`, `idreport`, `deny_allow`, `skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE INDEX indx_rightsreports_skbranch ON rightsreports(skbranch);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `rightsobjects` ADD COLUMN skbranch INT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE rightsobjects SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `rightsobjects`
		ALTER `skbranch` DROP DEFAULT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `rightsobjects`
		CHANGE COLUMN `skbranch` `skbranch` INT(11) NOT NULL AFTER `deny_allow`,
		DROP PRIMARY KEY,
		ADD PRIMARY KEY (`iduser`, `idobject`, `deny_allow`, `skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE INDEX indx_rightsobjects_skbranch ON rightsobjects(skbranch);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `resourcefromtables` ADD COLUMN skbranch INT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE resourcefromtables SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `resourcefromtables`
		ALTER `skbranch` DROP DEFAULT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `resourcefromtables`
		CHANGE COLUMN `skbranch` `skbranch` INT(11) NOT NULL AFTER `idlanguage`,
		DROP PRIMARY KEY,
		ADD PRIMARY KEY (`idrecord`, `idtable`, `idlanguage`, `skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `titleindex` ADD COLUMN skbranch INT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE titleindex SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `titleindex`
		ALTER `skbranch` DROP DEFAULT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `titleindex`
		CHANGE COLUMN `skbranch` `skbranch` INT(11) NOT NULL AFTER `idlanguage`,
		DROP PRIMARY KEY,
		ADD PRIMARY KEY (`idobject`, `idreport`, `idlanguage`, `skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportsusersquery` ADD COLUMN skbranch INT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE reportsusersquery SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportsusersquery`
		ALTER `skbranch` DROP DEFAULT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportsusersquery` ADD COLUMN idlanguage INT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "ALTER TABLE `reportsusersquery`
		CHANGE COLUMN `skbranch` `skbranch` INT(11) NOT NULL AFTER `idlanguage`,
		DROP PRIMARY KEY,
		ADD PRIMARY KEY (`o_guid`, `r_guid`, `iduser`, `idlanguage`, `skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE titleindex SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `titleindex`
		ALTER `skbranch` DROP DEFAULT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `titleindex`
		CHANGE COLUMN `skbranch` `skbranch` INT(11) NOT NULL AFTER `idlanguage`,
		DROP PRIMARY KEY,
		ADD PRIMARY KEY (`idobject`, `idreport`, `idlanguage`, `skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objects` DROP COLUMN o_name;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objects` ADD COLUMN skbranch INT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE objects SET skbranch = 1 WHERE parent_idobject != 0;";//o_guid = '00000000-0000-0000-0000-000000000000';
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objects`
		DROP INDEX `index_objects_o_guid`,
		ADD UNIQUE INDEX `index_objects_o_guid` (`o_guid`, `skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE INDEX indx_objects_skbranch ON objects (skbranch);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objectlinks` ADD COLUMN skbranch INT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE objectlinks SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objectlinks`
		ALTER `skbranch` DROP DEFAULT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objectlinks`
		CHANGE COLUMN `skbranch` `skbranch` INT(11) NOT NULL AFTER `idobject`,
		DROP PRIMARY KEY,
		ADD PRIMARY KEY (`iduser`, `idobject`, `skbranch`, `ol_type`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `avgreportdata` ADD COLUMN skbranch INT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE avgreportdata SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `avgreportdata`
		ALTER `skbranch` DROP DEFAULT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `avgreportdata`
		CHANGE COLUMN `skbranch` `skbranch` INT(11) NOT NULL AFTER `r_guid`,
		DROP PRIMARY KEY,
		ADD PRIMARY KEY (`o_guid`, `r_guid`, `skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportdata` ADD COLUMN skbranch INT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE reportdata SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportdata`
		ALTER `skbranch` DROP DEFAULT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportdata`
		DROP INDEX `o_guid`,
		ADD INDEX `o_guid` (`o_guid`, `r_guid`, `skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	//63897
	$query = "INSERT IGNORE INTO resourcefromtables
		SELECT iduser, 6, 1049, 0, CONCAT(IFNULL(user_lastname,''), ' ', IFNULL(user_firstname,''), '', IFNULL(user_middlename,'')) FROM users";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `users` DROP COLUMN user_firstname, DROP COLUMN user_middlename, DROP COLUMN user_lastname;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objectsreports` DROP COLUMN or_datechange;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objectsreports` ADD COLUMN skbranch INT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE objectsreports SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE INDEX indx_objectsreports_skbranch ON objectsreports(skbranch);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "ALTER TABLE `reportsusersquery` 
	 DROP PRIMARY KEY,
	  ADD PRIMARY KEY (o_guid, r_guid, iduser, idlanguage );";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `forummessages` ADD COLUMN frmm_datechange_tmst int(11) NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `forummessages` SET frmm_datechange_tmst = UNIX_TIMESTAMP(frmm_datechange);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `forummessages` MODIFY frmm_datechange_tmst int(11) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `forummessages` DROP COLUMN frmm_datechange;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `forummessages` ADD COLUMN skbranch INT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE forummessages SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE forummessages SET skbranch = 0 WHERE o_guid ='00000000-0000-0000-0000-000000000000';";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE INDEX indx_forummessages_skbranch ON forummessages(skbranch);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `forummessagessaw` ADD COLUMN frmsw_datesaw_tmst int(11) NULL, ADD COLUMN frmsw_datelastsaw_tmst int(11) NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `forummessagessaw` SET frmsw_datesaw_tmst = UNIX_TIMESTAMP(frmsw_datesaw), frmsw_datelastsaw_tmst = UNIX_TIMESTAMP(frmsw_datelastsaw);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `forummessagessaw` MODIFY frmsw_datesaw_tmst int(11) NOT NULL, DROP COLUMN frmsw_datesaw, MODIFY frmsw_datelastsaw_tmst int(11) NOT NULL, DROP COLUMN frmsw_datelastsaw, ADD COLUMN skbranch INT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE forummessagessaw SET skbranch = 1;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `forummessagessaw`
		CHANGE COLUMN `skbranch` `skbranch` INT(11) NOT NULL AFTER `o_guid`,
		DROP PRIMARY KEY,
		ADD PRIMARY KEY (`iduser`, `o_guid`, `skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportindex` ADD COLUMN ri_expirationdate_tmst int(11) NULL, ADD COLUMN ri_creationdate_tmst int(11) NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `reportindex` SET ri_creationdate_tmst = UNIX_TIMESTAMP(ri_creationdate), ri_expirationdate_tmst = UNIX_TIMESTAMP(ri_expirationdate);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportindex` DROP COLUMN ri_creationdate;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportindex` DROP COLUMN ri_expirationdate;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `resourcefromtables`
		CHANGE COLUMN `rft_columnname_text` `rft_columnname_text` VARCHAR(2500) NULL AFTER `skbranch`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `resourcefromtables`
		ADD COLUMN `rft_columnname_long` LONGTEXT NULL DEFAULT NULL AFTER `rft_columnname_text`;
		
	";
	
	
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = 'DROP PROCEDURE IF EXISTS `clear_forummessages` ;';
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE PROCEDURE `clear_forummessages`()
	BEGIN
		SET @@session.time_zone = '+00:00';
		DELETE FROM `forummessages`;
		INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_isdelete`, `frmm_ischanged`, `frmm_datechange_tmst`, `skbranch`) 
		VALUES ('0', '0', '00000000-0000-0000-0000-000000000000', '0', '1', '2', '1', NULL, 0, 0, UNIX_TIMESTAMP(NOW()),0);
		UPDATE `forummessages` SET `idforummessage` = 0;
		ALTER TABLE `forummessages` AUTO_INCREMENT = 1;

	END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = 'DROP PROCEDURE IF EXISTS  `add_forummessages`;';
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = '
CREATE PROCEDURE `add_forummessages`(	IN `parent_idforummessage` INT, IN `o_guid` VARCHAR(40), IN `iduser` INT, IN `frmm_body` LONGTEXT, IN `branch` INT)
BEGIN
    declare cnt BIGINT DEFAULT null;
    declare parent_iright BIGINT;
    declare parent_depth BIGINT;
	declare param_skbranch INT DEFAULT -1;
	IF (branch IS NULL) THEN
		SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
	ELSE 
		SELECT  `branch` into param_skbranch;
	END IF;

    SET @@session.time_zone = "+00:00";
    SELECT COUNT(*) into cnt from `forummessages`;
    IF (cnt = 0 ) THEN
	INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_isdelete`, `frmm_ischanged`, `frmm_datechange_tmst`, `skbranch`) 
	VALUES (\'0\', \'0\', \'00000000-0000-0000-0000-000000000000\', \'0\', \'1\', \'2\', \'0\', \'root\', 0, 0, UNIX_TIMESTAMP(NOW()), 0);	
	UPDATE `forummessages` SET `idforummessage` = 0;
    END IF;
		
    IF (CHAR_LENGTH(o_guid) <= 36 AND iduser > 1) THEN
	select `frmm_iright`, `frmm_depth` into parent_iright, parent_depth from `forummessages` as frmm where frmm.`idforummessage` = parent_idforummessage;
	UPDATE forummessages SET `frmm_ileft`=`frmm_ileft`+2,`frmm_iright`=`frmm_iright`+2 where `frmm_ileft`>parent_iright;
	UPDATE forummessages SET `frmm_iright`=`frmm_iright`+2 where `frmm_iright`>=parent_iright AND `frmm_ileft`<parent_iright;
	INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_isdelete`,  `frmm_ischanged`, `frmm_datechange_tmst`, `skbranch`) VALUES (NULL, parent_idforummessage, o_guid, iduser, parent_iright, parent_iright+1, parent_depth+1, frmm_body, 0, 0, UNIX_TIMESTAMP(NOW()), param_skbranch);
    END IF;

END;';
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = '
	DROP PROCEDURE IF EXISTS `add_objects` ;';
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = '
	CREATE PROCEDURE `add_objects`(IN `parent_guid` CHAR(36), IN `guid` CHAR(36), IN `icon` INT, IN `datechange` DATETIME, IN `ver` VARCHAR(10), IN `datever` DATE, IN `statever` INT, IN `hasreports` TINYINT, IN `useinsearch` TINYINT, IN `hidefortree` TINYINT, `branchid` VARCHAR(50))
	BEGIN
		declare parent_iright INT DEFAULT null;
		declare parent_id INT DEFAULT null;
		declare parent_depth TINYINT DEFAULT null;
		declare parent_skbranch INT DEFAULT null;
	
		 SELECT `skbranch` into parent_skbranch FROM branches WHERE idbranch = branchid;
		SELECT `o_iright`, `o_depth`, `idobject` into parent_iright, parent_depth, parent_id from objects where o_guid=parent_guid AND (skbranch = parent_skbranch OR parent_guid = \'00000000-0000-0000-0000-000000000000\');
		IF ( parent_id IS NOT null ) THEN	
			UPDATE objects SET `o_ileft`=`o_ileft`+2,`o_iright`=`o_iright`+2 where `o_ileft`>parent_iright;
			UPDATE objects SET `o_iright`=`o_iright`+2 where `o_iright`>=parent_iright AND `o_ileft`<parent_iright;
			INSERT INTO `objects` (`parent_idobject`, `o_ileft`, `o_iright`, `o_depth`, `o_guid`, `o_icon`, `o_datechange`, `o_ver` , `o_datever` , `o_statever`, `o_hasreports`, `o_useinsearch`, `o_hidefortree`, `skbranch` ) VALUES (parent_id, parent_iright, parent_iright+1, parent_depth+1, guid, icon, datechange, ver , datever , statever, hasreports, useinsearch, hidefortree, parent_skbranch );
		END IF;	      
	END;';
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = 'DROP PROCEDURE IF EXISTS `load_reports` ;';
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = 'CREATE PROCEDURE  `load_reports`(
		IN `o_guid` VARCHAR(1000),
		IN `userights` INT,
		IN `users_id` VARCHAR(1000),
		IN `idlanguage` INT,
		IN `branch` INT
	
	)
	LANGUAGE SQL
	NOT DETERMINISTIC
	CONTAINS SQL
	SQL SECURITY DEFINER
	COMMENT \'\'
	BEGIN
		declare idobject INT DEFAULT -1;
		declare param_skbranch INT DEFAULT -1;
		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;
	
	   DROP TEMPORARY TABLE IF EXISTS `r_temp` ;
		CREATE TEMPORARY TABLE `r_temp` (
			`idreport` INT NOT NULL
		)ENGINE=MEMORY;
	
	
	   DROP TEMPORARY TABLE IF EXISTS `rr_temp` ;
	   CREATE TEMPORARY TABLE rr_temp (    
		   `idreport` INT NOT NULL,
		 PRIMARY KEY (`idreport`)
	   )ENGINE=MEMORY;
	
	   SELECT obj.`idobject` into idobject from `objects` as obj where obj.`o_guid` = SUBSTRING(o_guid, 1, 40)  AND  obj.`skbranch` = param_skbranch;
	
	   IF ( idobject > 0 ) THEN
			 INSERT INTO r_temp SELECT rep.`idreport` FROM `reports` as rep INNER JOIN `objectsreports` as orl ON orl.`idreport` = rep.`idreport` AND  orl.`skbranch` = param_skbranch  WHERE orl.`idobject` = idobject AND  rep.`skbranch` = param_skbranch AND (ifnull(orl.`idlanguage`,0) = ifnull(idlanguage,0) OR  ifnull(orl.`idlanguage`,0) = 0); 
	
			IF ( userights <> 0 ) THEN
			   INSERT INTO `rr_temp` SELECT `idreport` FROM `r_temp`; 
				SET @query = CONCAT(\'DELETE FROM rr_temp WHERE rr_temp.`idreport` IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = \',param_skbranch,\' AND rr.`iduser` IN (\',users_id,\') AND rr.`deny_allow` = 0 );\'  );
				PREPARE zxc FROM @query;
				EXECUTE zxc;
		
				SET @query = CONCAT(\'DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = \',param_skbranch,\' AND rr.`iduser` IN (\',users_id,\') AND rr.`deny_allow` = 1 );\'  );
				PREPARE zxc FROM @query;
				EXECUTE zxc;
		
				SET @query = CONCAT(\'DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = \',param_skbranch,\' AND rr.`iduser` IN (\',users_id,\') AND rr.`deny_allow` = 2 );\'  );
				PREPARE zxc FROM @query;
				EXECUTE zxc;
		
			  SET @query = CONCAT(\'INSERT IGNORE INTO `rr_temp`	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 (\',users_id,\') and o.o_guid = "\',o_guid,\'" AND o.`skbranch` = \',param_skbranch,\'  AND orts.idreport NOT IN (SELECT rr.idreport FROM  `rightsreports` as rr WHERE  rr.`skbranch` = \',param_skbranch,\'  AND rr.deny_allow in (0,1,2));\'  );
				PREPARE zxc FROM @query;
				EXECUTE zxc;
				
				DELETE FROM r_temp  WHERE r_temp.`idreport` NOT IN ( SELECT rr_temp.`idreport` FROM rr_temp );
			END IF;	  
	   END IF;	      
	END';
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = 'DROP PROCEDURE IF EXISTS `createtree` ;';
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = 'CREATE PROCEDURE  `createtree`(
		IN `users_id` VARCHAR(1000)  ,
		IN `branch` INT
	)
	LANGUAGE SQL
	NOT DETERMINISTIC
	CONTAINS SQL
	SQL SECURITY DEFINER
	COMMENT \'\'
	BEGIN
	
		DECLARE l_idobject INT;
		DECLARE l_parent_idobject INT;
		DECLARE l_o_ileft INT;
		DECLARE l_o_iright INT;
		DECLARE done INT default 0;
		declare param_skbranch INT DEFAULT -1;
	
		DECLARE cursor_roots Cursor for 
			SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `o_useinsearch` = 1;
	
		DECLARE cursor_tree Cursor for 
			SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `parent_idobject` = 0 ORDER BY o_ileft DESC;
	
		DECLARE CONTINUE HANDLER FOR SQLSTATE \'02000\' SET done=1;
	
		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;
	
		DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp` ;
		CREATE TEMPORARY TABLE chkrt_o_temp (	
		`idobject` INT NOT NULL,
		`parent_idobject` INT NOT NULL,
		`ad0` INT NOT NULL,
		`ad1` INT NOT NULL,
		`ad2` INT NOT NULL,
		`root` INT NOT NULL,
		`o_ileft` INT NOT NULL,
		`o_iright` INT NOT NULL,
		`o_useinsearch` INT NOT NULL,
		`skbranch` INT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;
	
		CREATE INDEX ix_pid ON chkrt_o_temp (parent_idobject);	
		CREATE INDEX ix_il ON chkrt_o_temp (o_ileft);	
		CREATE INDEX ix_ir ON chkrt_o_temp (o_iright);	
		CREATE INDEX ix_uis ON chkrt_o_temp (o_useinsearch);	
	
	
		INSERT IGNORE INTO `chkrt_o_temp` 
			SELECT `idobject`, `parent_idobject`, 0, 0, 0, 1, `o_ileft`, `o_iright`, `o_useinsearch`, `skbranch`  FROM `objects` WHERE `parent_idobject` <> 0 AND `o_hidefortree` = 0 AND `skbranch` = param_skbranch AND `idobject`;
			SET @query = CONCAT(\'UPDATE chkrt_o_temp INNER JOIN `rightsobjects` ON (chkrt_o_temp.idobject = rightsobjects.idobject) SET  ad0 = 1 WHERE rightsobjects.`iduser` IN (\',users_id,\') AND rightsobjects.`deny_allow` = 0 AND rightsobjects.`skbranch` = \',param_skbranch,\';\'  );
			PREPARE zxc FROM @query;
			EXECUTE zxc;
	
		SET @query = CONCAT(\'UPDATE chkrt_o_temp INNER JOIN `rightsobjects` ON (chkrt_o_temp.idobject = rightsobjects.idobject) SET  ad1 = 1 WHERE rightsobjects.`iduser` IN (\',users_id,\') AND rightsobjects.`deny_allow` = 1 AND rightsobjects.`skbranch` = \',param_skbranch,\';\'  ); 
			PREPARE zxc FROM @query;
			EXECUTE zxc;
	
		SET @query = CONCAT(\'UPDATE chkrt_o_temp INNER JOIN `rightsobjects` ON (chkrt_o_temp.idobject = rightsobjects.idobject) SET  ad2 = 1 WHERE rightsobjects.`iduser` IN (\',users_id,\') AND rightsobjects.`deny_allow` = 2 AND rightsobjects.`skbranch` = \',param_skbranch,\';\'  );
			PREPARE zxc FROM @query;
			EXECUTE zxc;
	
		  DELETE FROM chkrt_o_temp WHERE (ad1 < 1 OR ad2 < 1) AND o_useinsearch = 0;
	
		DELETE FROM chkrt_o_temp WHERE ad0 = 1 AND o_useinsearch = 0;
	
		SET @query = CONCAT(\'INSERT IGNORE INTO chkrt_o_temp SELECT o.`idobject`, o.`parent_idobject`, 1, 1, 0, 1, o.`o_ileft`, o.`o_iright`, o.`o_useinsearch`, `skbranch`  FROM `objects` as o INNER JOIN  `users` as u ON u.`user_guid` = o.`o_guid` WHERE `parent_idobject` <> 0 AND o.`skbranch` = \',param_skbranch,\' AND  o.`idobject` NOT IN (SELECT idobject FROM `rightsobjects` WHERE `deny_allow` IN (0,1,2)) AND  `o_hidefortree` = 0 AND u.`iduser` IN (\',users_id,\') ;\'  );
			PREPARE zxc FROM @query;
			EXECUTE zxc;
			
		OPEN cursor_roots;
		WHILE done = 0 DO 
		FETCH cursor_roots INTO l_idobject,l_o_ileft,l_o_iright;
		SELECT COUNT(*) into @c FROM `chkrt_o_temp` WHERE `o_ileft` BETWEEN l_o_ileft AND l_o_iright AND `o_useinsearch` = 0;
		IF (@c = 0) THEN 
			DELETE FROM chkrt_o_temp WHERE idobject = l_idobject;
		END IF;
		END WHILE;
		Close cursor_roots; 
	
	
			DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_id` ;
			CREATE TEMPORARY TABLE chkrt_o_temp_id (	
			`idobject` INT NOT NULL,
			PRIMARY KEY (`idobject`)
			)ENGINE=MEMORY;
	
	
			INSERT IGNORE INTO `chkrt_o_temp_id` 
				SELECT `idobject` FROM chkrt_o_temp;
	
	
		UPDATE chkrt_o_temp RIGHT OUTER JOIN `chkrt_o_temp_id` ON (chkrt_o_temp.parent_idobject = chkrt_o_temp_id.idobject) 
		SET root = 0;
		UPDATE chkrt_o_temp SET parent_idobject = 0 WHERE root = 1;
	
		SET done=0;
	
		OPEN cursor_tree;
		WHILE done = 0 DO 
		FETCH cursor_tree INTO l_idobject,l_o_ileft,l_o_iright;
			SET l_parent_idobject = 0;
		SELECT idobject INTO l_parent_idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1;
		UPDATE `chkrt_o_temp` SET `parent_idobject` = l_parent_idobject WHERE `idobject`= l_idobject;
		END WHILE;
		Close cursor_tree; 
	
	END;';
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = 'DROP PROCEDURE IF EXISTS `load_objects` ;';
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = 'CREATE PROCEDURE  `load_objects`(
		IN `parent_idobject` INT,
		IN `userights` INT,
		IN `users_id` VARCHAR(1000) ,
		IN `branch` INT
	)
	LANGUAGE SQL
	NOT DETERMINISTIC
	CONTAINS SQL
	SQL SECURITY DEFINER
	COMMENT \'\'
	BEGIN
		declare root_parent_idobject INT;
		declare param_skbranch INT DEFAULT -1;
		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;
		DROP TEMPORARY TABLE IF EXISTS `o_temp` ;
			CREATE TEMPORARY TABLE o_temp (	
			`idobject` INT NOT NULL,
			`parent_idobject` INT NOT NULL,
			PRIMARY KEY (`idobject`)
			)ENGINE=MEMORY;
		IF ( userights = 0 ) THEN
			IF ( parent_idobject = 0 ) THEN
				SELECT obj.`idobject` into root_parent_idobject from `objects` as obj where obj.`parent_idobject` = 0;
			ELSE   
				SET root_parent_idobject = parent_idobject;
			END IF;   
				INSERT IGNORE INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`parent_idobject` = root_parent_idobject AND `o_hidefortree` = 0 AND obj.`skbranch` = param_skbranch;
		ELSE
				CALL createtree(users_id, param_skbranch);
				INSERT IGNORE INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `chkrt_o_temp` as obj WHERE obj.`parent_idobject` = parent_idobject ;
		END IF;
	END; ';
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "DROP PROCEDURE IF EXISTS `load_objecttree` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = 'CREATE PROCEDURE  `load_objecttree`(
		IN `idobject` INT,
		IN `userights` INT,
		IN `users_id` VARCHAR(1000),
		IN `branch` INT
	)
	LANGUAGE SQL
	NOT DETERMINISTIC
	CONTAINS SQL
	SQL SECURITY DEFINER
	COMMENT \'\'
	BEGIN
		declare parent_idobject INT DEFAULT idobject;
		declare param_skbranch INT DEFAULT -1;
		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;
	
		DROP TEMPORARY TABLE IF EXISTS `o_temp_tree` ;
		CREATE TEMPORARY TABLE o_temp_tree (	
		`idpobject` INT NOT NULL,
		`parent_idobject` INT NOT NULL,
		 PRIMARY KEY (`idpobject`)
		)ENGINE=MEMORY;
		
	  IF ( userights = 0 ) THEN
		WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0) DO	
			SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `objects` as obj where obj.`idobject` = parent_idobject AND obj.`skbranch` = param_skbranch;
			INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`parent_idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND obj.`skbranch` = param_skbranch AND `o_hidefortree` = 0;
		END WHILE;
	  ELSE
		CALL createtree(users_id, param_skbranch);
		WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0 ) DO	
			  IF EXISTS (SELECT 1 from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject) THEN
				SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject AND obj.`skbranch` = param_skbranch;
				INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, obj.`parent_idobject` FROM `chkrt_o_temp` as obj WHERE obj.`parent_idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND obj.`skbranch` = param_skbranch;
			ELSE
				SELECT 0 into parent_idobject;
			END IF;	    
		END WHILE;
	  END IF;
	
	  CALL load_objects(0, userights, users_id, param_skbranch);
	END;  ';
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = 'DROP PROCEDURE IF EXISTS `add_personallinks` ;';
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = 'CREATE PROCEDURE `add_personallinks`(
		IN `iduser` INT,
		IN `o_guid` varchar(1000),
		IN `r_guid` varchar(1000),
		IN `branch` INT,
		IN `urlparams` varchar(2000)
	)
	LANGUAGE SQL
	NOT DETERMINISTIC
	CONTAINS SQL
	SQL SECURITY DEFINER
	COMMENT \'\'
	BEGIN
		declare pl_pos INT DEFAULT null;
		declare cnt INT DEFAULT null;
		SELECT COUNT(*) into cnt from `personallinks` as pl where pl.`iduser` = iduser AND pl.`o_guid` = SUBSTRING(o_guid, 1, 40) AND pl.`r_guid` = SUBSTRING(r_guid, 1, 40) AND pl.`skbranch` = branch;
		IF (cnt = 0 ) THEN
			SELECT MAX(pl.`pl_pos`) + 1 into pl_pos from `personallinks` as pl where pl.`iduser` = iduser;
			
			IF ( pl_pos is null ) THEN
			INSERT INTO `personallinks` (`idpersonallink`, `iduser`, `o_guid`, `r_guid`, `skbranch`, `pl_pos`, `addurlparams`) VALUES (NULL, iduser, SUBSTRING(o_guid, 1, 40), SUBSTRING(r_guid, 1, 40), branch, 1, urlparams);
			ELSE	
			INSERT INTO `personallinks` (`idpersonallink`, `iduser`, `o_guid`, `r_guid`, `skbranch`, `pl_pos`, `addurlparams`) VALUES (NULL, iduser, SUBSTRING(o_guid, 1, 40), SUBSTRING(r_guid, 1, 40), branch, pl_pos, urlparams);
			END IF;	      
		END IF;	      
	END;';
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = 'DROP PROCEDURE IF EXISTS `load_objectpath` ;';
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = 'CREATE PROCEDURE `load_objectpath`(
		IN `idobject` INT,
		IN `userights` INT,
		IN `users_id` VARCHAR(1000),
		IN `branch` INT
	)
	LANGUAGE SQL
	NOT DETERMINISTIC
	CONTAINS SQL
	SQL SECURITY DEFINER
	COMMENT \'\'
	BEGIN
		declare parent_idobject INT DEFAULT idobject;
		declare param_skbranch INT DEFAULT -1;
	
		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;
	
		DROP TEMPORARY TABLE IF EXISTS `o_temp_tree` ;
		CREATE TEMPORARY TABLE o_temp_tree (	
			`idpobject` INT NOT NULL,
			`parent_idobject` INT NOT NULL,
			`o_ileft` INT NOT NULL,
			PRIMARY KEY (`idpobject`)
		)ENGINE=MEMORY;
		
	  IF ( userights = 0 ) THEN
		WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0  ) DO	
			INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`), obj.`o_ileft` FROM `objects` as obj WHERE obj.`idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND obj.`skbranch` = param_skbranch;
			SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `objects` as obj where obj.`idobject` = parent_idobject AND obj.`skbranch` = param_skbranch;
		END WHILE;
	  ELSE
		CALL createtree(users_id, param_skbranch);
		WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0 ) DO	
		   IF EXISTS (SELECT 1 FROM `chkrt_o_temp` as obj WHERE obj.`idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND obj.`skbranch` = param_skbranch) THEN
				INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`), obj.`o_ileft` FROM `chkrt_o_temp` as obj WHERE obj.`idobject` = parent_idobject AND obj.`parent_idobject` <> 0;
			  SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject;
			ELSE
				SELECT 0 into parent_idobject;
			END IF;	
		 END WHILE;
	  END IF;
	END;';
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "DROP PROCEDURE IF EXISTS `load_reportsAdmin` ;";
	
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = 'CREATE  PROCEDURE `load_reportsAdmin`(
		IN `o_guid` VARCHAR(1000),
		IN `idlanguage` INT,
		IN `branch` INT
	)
	LANGUAGE SQL
	NOT DETERMINISTIC
	CONTAINS SQL
	SQL SECURITY DEFINER
	COMMENT ""
	BEGIN
		declare ileft BIGINT DEFAULT -1; 	
		declare iright BIGINT DEFAULT -1;
		declare param_skbranch INT DEFAULT -1;

		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;

		DROP TEMPORARY TABLE IF EXISTS `r_temp` ;
		CREATE TEMPORARY TABLE `r_temp` (
		`idreport` INT NOT NULL
		)ENGINE=MEMORY;


		SELECT obj.`o_ileft`, obj.`o_iright` into  ileft, iright from `objects` as obj where obj.`skbranch` = param_skbranch AND CONVERT(obj.`o_guid` USING utf32) = SUBSTRING(CONVERT( o_guid  USING utf32), 1, 40)  ;
		INSERT INTO r_temp SELECT DISTINCT orl.`idreport` FROM `objects` as obj INNER JOIN `objectsreports` as orl ON obj.`idobject` = orl.`idobject` WHERE obj.`skbranch` = param_skbranch AND obj.`o_ileft` BETWEEN ileft AND iright AND ifnull(orl.`idlanguage`,0) = ifnull(idlanguage,0); 
	END;';
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "DROP PROCEDURE IF EXISTS `load_objects_admin` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = 'CREATE PROCEDURE `load_objects_admin`(
		IN `parent_id` INT,
		IN `depth` INT,
		IN `r_guid` VARCHAR(1000),
		IN `branch` INT
	)
	LANGUAGE SQL
	NOT DETERMINISTIC
	CONTAINS SQL
	SQL SECURITY DEFINER
	COMMENT \'\'
	BEGIN
		declare ileft INT DEFAULT -1;
		declare iright INT DEFAULT -1;
		declare param_skbranch INT DEFAULT -1;
	
		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;
	
		DROP TEMPORARY TABLE IF EXISTS `admin_temp` ;
		CREATE TEMPORARY TABLE `admin_temp` (
		`idobject` INT NOT NULL,
		`o_guid` VARCHAR(36) NOT NULL,
		`r_guid` VARCHAR(36) NOT NULL,
		`at_rating` INT,
		`at_viewcount` INT,
		`at_msgcnt` INT,
		`at_msglastdate` DATETIME,
		 PRIMARY KEY(idobject)
		)ENGINE=MEMORY;
	
		CREATE INDEX o_guid_admin_temp ON admin_temp (o_guid);
		SELECT obj.`o_ileft`, obj.`o_iright` into ileft, iright from `objects` as obj where obj.`idobject` = parent_id and obj.`skbranch` = param_skbranch;
	
		INSERT INTO admin_temp SELECT obj.idobject, obj.o_guid, SUBSTRING(r_guid, 1, 40), NULL, NULL, NULL, NULL FROM `objects` as obj where obj.`skbranch` = param_skbranch and obj.`o_ileft` BETWEEN ileft+1 AND iright AND o_depth < depth;
	
		UPDATE `admin_temp` as at, `avgreportdata` as ard
		SET `at_rating` =  `ard_rating`,
			`at_viewcount` = `ard_viewcount`
		WHERE ard.`skbranch` = param_skbranch AND CONVERT(at.`o_guid` USING utf32) = CONVERT(ard.`o_guid` USING utf32) AND CONVERT(at.`r_guid` USING utf32) = CONVERT(ard.`r_guid` USING utf32) ;
	
	   UPDATE `admin_temp`
		SET `at_viewcount` = 0
		WHERE `at_viewcount` IS NULL;
	
		UPDATE `admin_temp` as at  
		SET `at_msgcnt` =  (SELECT IFNULL(COUNT(0),0) FROM `forummessages` as frmm WHERE frmm.`skbranch` = param_skbranch AND CONVERT(frmm.`o_guid` USING utf32)  = CONVERT(at.`o_guid` USING utf32)  and frmm.`frmm_isdelete`=0);
	
		UPDATE `admin_temp` as at  
		SET `at_msglastdate` =  (SELECT MAX(from_unixtime(frmm_datechange_tmst)) FROM `forummessages` as frmm WHERE frmm.`skbranch` = param_skbranch AND  CONVERT(frmm.`o_guid` USING utf32)  = CONVERT(at.`o_guid` USING utf32)  and frmm.`frmm_isdelete`=0);
	
	END;';
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "DROP PROCEDURE IF EXISTS `add_rating_reportdata` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = 'CREATE PROCEDURE `add_rating_reportdata`(
		IN `rd_session` CHAR(32),
		IN `o_guid` VARCHAR(1000),
		IN `r_guid` VARCHAR(1000),
		IN `iduser` INT,
		IN `rd_rating` INT,
		IN `branch` INT
	)
	LANGUAGE SQL
	NOT DETERMINISTIC
	CONTAINS SQL
	SQL SECURITY DEFINER
	COMMENT \'\'
	BEGIN
		declare rating FLOAT;
		declare l_idreportdata INT;
		declare l_hasrecord INT default NULL;
		declare param_skbranch INT DEFAULT -1;

		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;

		SELECT rd.`idreportdata` INTO l_idreportdata FROM `reportdata` as rd WHERE rd.`o_guid` = SUBSTRING(o_guid, 1, 40) AND rd.`r_guid` = SUBSTRING(r_guid, 1, 40) AND rd.`iduser` = iduser AND rd.`skbranch` = param_skbranch;
		SELECT 1 INTO l_hasrecord FROM `avgreportdata` as ard WHERE ard.`o_guid` = SUBSTRING(o_guid, 1, 40)  AND ard.`r_guid` = SUBSTRING(r_guid, 1, 40) AND ard.`skbranch` = param_skbranch;

		IF (l_idreportdata) THEN
		UPDATE `reportdata` as rd SET  rd.`rd_rating` = rd_rating WHERE rd.`idreportdata` = l_idreportdata AND rd.`skbranch` = param_skbranch;
		ELSE
		INSERT INTO `reportdata` (`idreportdata`, `rd_session`, `o_guid`, `r_guid`, `iduser`, `rd_rating`, `rd_viewcount`, `skbranch`) VALUES (null, rd_session, SUBSTRING(o_guid, 1, 40), SUBSTRING(r_guid, 1, 40), iduser, rd_rating, 1, param_skbranch);
		END IF;

		SELECT IFNULL(SUM(rd.`rd_rating`) / COUNT(0),0) INTO rating from`reportdata` as rd WHERE  rd.`o_guid` = SUBSTRING(o_guid, 1, 40) AND rd.`r_guid` = SUBSTRING(r_guid, 1, 40) AND rd.`rd_rating` > 0 AND rd.`skbranch` = param_skbranch; 

		IF (l_hasrecord) THEN
		UPDATE `avgreportdata` as ard SET  ard.`ard_rating` = rating WHERE ard.`o_guid` = SUBSTRING(o_guid, 1, 40) AND ard.`r_guid` = SUBSTRING(r_guid, 1, 40) AND ard.`skbranch` = param_skbranch;
		ELSE
		INSERT INTO `avgreportdata` (`o_guid` ,`r_guid`, `skbranch`,`ard_rating` ,`ard_viewcount` ,`ard_msgcount` ) VALUES (SUBSTRING(o_guid, 1, 40), SUBSTRING(r_guid, 1, 40), param_skbranch,  rating, 1, 0);
		END IF;
	END;';
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "DROP PROCEDURE IF EXISTS `add_viewcount_reportdata` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = 'CREATE PROCEDURE `add_viewcount_reportdata`(
		IN `session` CHAR(32),
		IN `o_guid` VARCHAR(1000),
		IN `r_guid` VARCHAR(1000),
		IN `iduser` INT,
		IN `branch` INT
	)
	LANGUAGE SQL
	NOT DETERMINISTIC
	CONTAINS SQL
	SQL SECURITY DEFINER
	COMMENT \'\'
	BEGIN
	
		declare viewcount INT;
		declare ses_viewcount INT;
		declare l_hasrecord INT default NULL;
		declare l_idreportdata INT default null;
		declare ses_idreportdata INT default null;
		declare param_skbranch INT DEFAULT -1;
	
		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;
	
		SELECT 1 INTO l_hasrecord FROM `avgreportdata` as ard WHERE ard.`o_guid` = SUBSTRING(o_guid, 1, 40)  AND ard.`r_guid` = SUBSTRING(r_guid, 1, 40);
		SELECT rd.`idreportdata` INTO l_idreportdata FROM `reportdata` as rd WHERE rd.`o_guid` = SUBSTRING(o_guid, 1, 40) AND rd.`r_guid` = SUBSTRING(r_guid, 1, 40) AND rd.`iduser` = iduser AND rd.`skbranch` = param_skbranch;
	
		IF (l_idreportdata) THEN
		SELECT rd.`idreportdata`, rd.`rd_viewcount` INTO ses_idreportdata, ses_viewcount FROM `reportdata` as rd WHERE rd.idreportdata = l_idreportdata AND rd.`rd_session` = session AND rd.`skbranch` = param_skbranch;
		IF ((ses_idreportdata is null) OR (ses_viewcount = 0)) THEN
			UPDATE `reportdata` as rd SET rd.`rd_viewcount` = rd.`rd_viewcount` + 1, rd.`rd_session` = session WHERE rd.`idreportdata` = l_idreportdata AND rd.`skbranch` = param_skbranch;
		END IF;
		ELSE
		INSERT INTO `reportdata` (`idreportdata`, `rd_session`, `o_guid`, `r_guid`, `iduser`, `rd_rating`, `rd_viewcount`, `skbranch`) VALUES (null, session, SUBSTRING(o_guid, 1, 40), SUBSTRING(r_guid, 1, 40), iduser, 0, 1, param_skbranch);
		END IF;
	
		SELECT IFNULL(SUM(rd.`rd_viewcount`),0) INTO viewcount from`reportdata` as rd WHERE  rd.`o_guid` = SUBSTRING(o_guid, 1, 40) AND rd.`r_guid` = SUBSTRING(r_guid, 1, 40)  AND rd.`skbranch` = param_skbranch;
	
		IF (l_hasrecord) THEN
			UPDATE `avgreportdata` as ard SET ard.`ard_viewcount` = viewcount WHERE ard.`o_guid` = SUBSTRING(o_guid, 1, 40) AND ard.`r_guid` = SUBSTRING(r_guid, 1, 40) AND ard.`skbranch` = param_skbranch;
		ELSE
			INSERT INTO `avgreportdata` (`o_guid` ,`r_guid`, `skbranch` ,`ard_rating` ,`ard_viewcount` ,`ard_msgcount` ) VALUES (SUBSTRING(o_guid, 1, 40), SUBSTRING(r_guid, 1, 40), param_skbranch, 0, viewcount, 0);
		END IF;
	
	END;';
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "DROP PROCEDURE IF EXISTS `load_objecttree_search` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = 'CREATE PROCEDURE `load_objecttree_search`(
		IN `branch` INT
	)
	LANGUAGE SQL
	NOT DETERMINISTIC
	CONTAINS SQL
	SQL SECURITY DEFINER
	COMMENT \'\'
	
	BEGIN
		declare param_skbranch INT DEFAULT -1;
	
		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;
	
		DROP TEMPORARY TABLE IF EXISTS `o_temp` ;
		CREATE TEMPORARY TABLE o_temp (	
		`idobject` INT NOT NULL,
		`parent_idobject` INT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;
	
		INSERT INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`o_useinsearch` = 1 AND obj.`o_hidefortree` = 0  AND obj.`skbranch` = param_skbranch;
	END;';
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE `version` SET `version` = 22;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 23) {
	// update to 23 version

		$query = "DROP PROCEDURE IF EXISTS `createtree` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE  `createtree`(
				IN `users_id` VARCHAR(1000)  ,
				IN `branch` INT
			)
			LANGUAGE SQL
			NOT DETERMINISTIC
			CONTAINS SQL
			SQL SECURITY DEFINER
			COMMENT ''
			BEGIN
			
				DECLARE l_idobject INT;
				DECLARE l_parent_idobject INT;
				DECLARE l_o_ileft INT;
				DECLARE l_o_iright INT;
				DECLARE done INT default 0;
				declare param_skbranch INT DEFAULT -1;
			
				DECLARE cursor_roots Cursor for 
					SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `o_useinsearch` = 1;
			
				DECLARE cursor_tree Cursor for 
					SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `parent_idobject` = 0 ORDER BY o_ileft DESC;
			
				DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
			
				IF (branch IS NULL) THEN
					SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
				ELSE 
					SELECT  `branch` into param_skbranch;
				END IF;
			
				DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp` ;
				CREATE TEMPORARY TABLE chkrt_o_temp (	
				`idobject` INT NOT NULL,
				`parent_idobject` INT NOT NULL,
				`ad0` INT NOT NULL,
				`ad1` INT NOT NULL,
				`ad2` INT NOT NULL,
				`root` INT NOT NULL,
				`o_ileft` INT NOT NULL,
				`o_iright` INT NOT NULL,
				`o_useinsearch` INT NOT NULL,
				`skbranch` INT NOT NULL,
				PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;
			
				INSERT IGNORE INTO `chkrt_o_temp` 
					SELECT `idobject`, `parent_idobject`, 0, 0, 0, 1, `o_ileft`, `o_iright`, `o_useinsearch`, `skbranch`  FROM `objects` WHERE `parent_idobject` <> 0 AND `o_hidefortree` = 0 AND `skbranch` = param_skbranch AND `idobject`;
			
				CREATE INDEX ix_pid ON chkrt_o_temp (parent_idobject);	
			
				DROP TEMPORARY TABLE IF EXISTS `t_rightsobjects` ;
				CREATE TEMPORARY TABLE `t_rightsobjects` (
					`iduser` INT(11) NOT NULL,
					`idobject` INT(11) NOT NULL,
					`deny_allow` TINYINT(1) NOT NULL,
					`skbranch` INT NOT NULL
				)ENGINE=MEMORY;
			
				SET @query = CONCAT('INSERT IGNORE INTO `t_rightsobjects` SELECT `iduser`, `idobject`, `deny_allow`, `skbranch` FROM `rightsobjects` WHERE `iduser` IN (',users_id,') AND `skbranch` = ',param_skbranch,';' );
					PREPARE zxc FROM @query;
					EXECUTE zxc;
			
			
				SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad0 = 1 WHERE t_rightsobjects.`deny_allow` = 0 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;
			
					SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad1 = 1 WHERE  t_rightsobjects.`deny_allow` = 1 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  ); 
					PREPARE zxc FROM @query;
					EXECUTE zxc;
			
					SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad2 = 1 WHERE  t_rightsobjects.`deny_allow` = 2 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;
			
				DELETE FROM chkrt_o_temp WHERE (ad1 < 1 OR ad2 < 1) AND o_useinsearch = 0;
			
					DELETE FROM chkrt_o_temp WHERE ad0 = 1 AND o_useinsearch = 0;
			
					SET @query = CONCAT('INSERT IGNORE INTO chkrt_o_temp SELECT o.`idobject`, o.`parent_idobject`, 1, 1, 0, 1, o.`o_ileft`, o.`o_iright`, o.`o_useinsearch`, `skbranch`  FROM `objects` as o INNER JOIN  `users` as u ON u.`user_guid` = o.`o_guid` WHERE `parent_idobject` <> 0 AND o.`skbranch` = ',param_skbranch,' AND  o.`idobject` NOT IN (SELECT idobject FROM `rightsobjects` WHERE `deny_allow` IN (0,1,2)) AND  `o_hidefortree` = 0 AND u.`iduser` IN (',users_id,') ;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;
					
				OPEN cursor_roots;
				WHILE done = 0 DO 
				FETCH cursor_roots INTO l_idobject,l_o_ileft,l_o_iright;
				SELECT COUNT(*) into @c FROM `chkrt_o_temp` WHERE `o_ileft` BETWEEN l_o_ileft AND l_o_iright AND `o_useinsearch` = 0;
				IF (@c = 0) THEN 
					DELETE FROM chkrt_o_temp WHERE idobject = l_idobject;
				END IF;
				END WHILE;
				Close cursor_roots; 
			
			
					DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_id` ;
					CREATE TEMPORARY TABLE chkrt_o_temp_id (	
					`idobject` INT NOT NULL,
					PRIMARY KEY (`idobject`)
					)ENGINE=MEMORY;
			
			
					INSERT IGNORE INTO `chkrt_o_temp_id` 
						SELECT `idobject` FROM chkrt_o_temp;
			
			
				UPDATE chkrt_o_temp RIGHT OUTER JOIN `chkrt_o_temp_id` ON (chkrt_o_temp.parent_idobject = chkrt_o_temp_id.idobject) 
				SET root = 0;
				UPDATE chkrt_o_temp SET parent_idobject = 0 WHERE root = 1;
			
				SET done=0;
			
				OPEN cursor_tree;
				WHILE done = 0 DO 
				FETCH cursor_tree INTO l_idobject,l_o_ileft,l_o_iright;
					SET l_parent_idobject = 0;
				SELECT idobject INTO l_parent_idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1;
				UPDATE `chkrt_o_temp` SET `parent_idobject` = l_parent_idobject WHERE `idobject`= l_idobject;
				END WHILE;
				Close cursor_tree; 
			
			END;
			";
			
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 23;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 24) {
	// update to 24 version

	$query = "ALTER TABLE `objects` CHANGE COLUMN `o_ver` `o_ver` VARCHAR(800) NOT NULL DEFAULT ' ' ;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `add_objects` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
		
		CREATE PROCEDURE `add_objects`(IN `parent_guid` CHAR(40), IN `guid` CHAR(40), IN `icon` INT, IN `datechange` DATETIME, IN `ver` VARCHAR(800), IN `datever` DATE, IN `statever` INT, IN `hasreports` TINYINT, IN `useinsearch` TINYINT, IN `hidefortree` TINYINT, `branchid` VARCHAR(50))
		BEGIN
			declare parent_iright INT DEFAULT null;
			declare parent_id INT DEFAULT null;
			declare parent_depth TINYINT DEFAULT null;
			declare parent_skbranch INT DEFAULT null;
		
			 SELECT `skbranch` into parent_skbranch FROM branches WHERE idbranch = branchid;
			SELECT `o_iright`, `o_depth`, `idobject` into parent_iright, parent_depth, parent_id from objects where o_guid=parent_guid AND (skbranch = parent_skbranch OR parent_guid = '00000000-0000-0000-0000-000000000000');
			IF ( parent_id IS NOT null ) THEN	
				UPDATE objects SET `o_ileft`=`o_ileft`+2,`o_iright`=`o_iright`+2 where `o_ileft`>parent_iright;
				UPDATE objects SET `o_iright`=`o_iright`+2 where `o_iright`>=parent_iright AND `o_ileft`<parent_iright;
				INSERT INTO `objects` (`parent_idobject`, `o_ileft`, `o_iright`, `o_depth`, `o_guid`, `o_icon`, `o_datechange`, `o_ver` , `o_datever` , `o_statever`, `o_hasreports`, `o_useinsearch`, `o_hidefortree`, `skbranch` ) VALUES (parent_id, parent_iright, parent_iright+1, parent_depth+1, guid, icon, datechange, ver , datever , statever, hasreports, useinsearch, hidefortree, parent_skbranch );
			END IF;	      
		END;

	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 24;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 25) {
	// update to 25 version

	$query = "
			ALTER DATABASE CHARACTER SET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `avgreportdata` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `branches` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `files` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `forummessages` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `forummessagessaw` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `languages` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `links` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objectlinks` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objects` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objectsreports` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `personallinks` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `pollingobjects` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `pollingobjectsarchive` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `pollingobjectstatus` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `polltypequestions` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `polltypequestionselectvalues` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `polltypequestiontypes` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `polltypes` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `portal` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `projects` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `reportdata` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `reportindex` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `reports` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `reportsusersquery` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `resourcefromtables` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `rightsobjects` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `rightsreports` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `sections` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `tables` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `titleindex` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `useranswers` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `useranswersvalues` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `useranswersvaluesarchive` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `useranswersvaluesarchivetext` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `users` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `usersgroups` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `userslinks` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `version` CONVERT TO CHARSET utf8mb4 COLLATE 'utf8mb4_general_ci';";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			UPDATE languages set lang_name = 'Invariant' where native_name like 'Invariant Language (Invariant Country)';
	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 25;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 26) {
	// update to 26 version

	$query = "ALTER TABLE branches AUTO_INCREMENT = 1001;";//Becouse main branch == have id 1000
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE branches SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE avgreportdata SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE forummessages SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE forummessagessaw SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE objectlinks SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE objects SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE objectsreports SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE personallinks SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE pollingobjects SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE reportdata SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE reportindex SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE reports SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE reportsusersquery SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE resourcefromtables SET idrecord = idrecord + 1000 WHERE idtable = 7; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE resourcefromtables SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE rightsobjects SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE rightsreports SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE titleindex SET skbranch = skbranch + 1000; ";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 26;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 27) {
	// update to 27 version

	$query = "
	CREATE TABLE `rightspollingobjects` (
		`iduser` INT(11) NOT NULL,
		`skpollingobject` INT(11) NOT NULL,
		`deny_allow` TINYINT(1) NOT NULL,
		PRIMARY KEY (`iduser`, `skpollingobject`)
	)
	COLLATE='utf8mb4_general_ci'
	ENGINE=InnoDB
	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 27;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 28) {
	// update to 28 version

	$query = "
		CREATE TABLE `mailqueue` (
			`priority` INT(11) NOT NULL DEFAULT '0',
			`mq_recipients` VARCHAR(1000) NOT NULL COLLATE 'utf8mb4_general_ci',
			`mq_copy` VARCHAR(1000) NOT NULL COLLATE 'utf8mb4_general_ci',
			`mq_subject` VARCHAR(1000) NOT NULL COLLATE 'utf8mb4_general_ci',
			`mq_text` LONGTEXT NOT NULL COLLATE 'utf8mb4_general_ci'
		)
		COLLATE='utf8mb4_general_ci'
		ENGINE=InnoDB	;
	
	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 28;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 29) {
	// update to 29 version

	$query = "
		ALTER TABLE `useranswersvalues`
			ADD COLUMN `ss_key` VARCHAR(60) NULL AFTER `uav_tmst`;
	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 29;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 30) {
	// update to 30 version

	$query = "DROP PROCEDURE IF EXISTS `load_objecttree_search` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
			
			CREATE PROCEDURE `load_objecttree_search`(
				IN `branch` INT
			)
			LANGUAGE SQL
			NOT DETERMINISTIC
			CONTAINS SQL
			SQL SECURITY DEFINER
			COMMENT ''
			BEGIN
				declare param_skbranch INT DEFAULT -1;
			
				IF (branch IS NOT NULL) THEN
					SELECT  `branch` into param_skbranch;
				END IF;
			
				DROP TEMPORARY TABLE IF EXISTS `o_temp` ;
				CREATE TEMPORARY TABLE o_temp (	
				`idobject` INT NOT NULL,
				`parent_idobject` INT NOT NULL,
				PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;
			
				INSERT INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`o_useinsearch` = 1 AND obj.`o_hidefortree` = 0  AND (obj.`skbranch` = param_skbranch OR param_skbranch = -1);
			END;

	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 30;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 31) {
	// update to 31 version

	$query = "DROP PROCEDURE IF EXISTS `add_viewcount_reportdata` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
			
			CREATE PROCEDURE `add_viewcount_reportdata`(
				IN `session` CHAR(32),
				IN `o_guid` VARCHAR(1000),
				IN `r_guid` VARCHAR(1000),
				IN `iduser` INT,
				IN `branch` INT
			)
			LANGUAGE SQL
			NOT DETERMINISTIC
			CONTAINS SQL
			SQL SECURITY DEFINER
			COMMENT ''
			BEGIN
			    declare viewcount INT;
				declare ses_viewcount INT;
				declare l_hasrecord INT default NULL;
				declare l_idreportdata INT default null;
				declare ses_idreportdata INT default null;
				declare param_skbranch INT DEFAULT -1;

				IF (branch IS NULL) THEN
					SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
				ELSE 
					SELECT  `branch` into param_skbranch;
				END IF;

				SELECT 1 INTO l_hasrecord FROM `avgreportdata` as ard WHERE ard.`o_guid` = SUBSTRING(o_guid, 1, 40)  AND ard.`r_guid` = SUBSTRING(r_guid, 1, 40) AND `skbranch` = param_skbranch;
				SELECT rd.`idreportdata` INTO l_idreportdata FROM `reportdata` as rd WHERE rd.`o_guid` = SUBSTRING(o_guid, 1, 40) AND rd.`r_guid` = SUBSTRING(r_guid, 1, 40) AND rd.`iduser` = iduser AND rd.`skbranch` = param_skbranch;

				IF (l_idreportdata) THEN
				SELECT rd.`idreportdata`, rd.`rd_viewcount` INTO ses_idreportdata, ses_viewcount FROM `reportdata` as rd WHERE rd.idreportdata = l_idreportdata AND rd.`rd_session` = session AND rd.`skbranch` = param_skbranch;
				IF ((ses_idreportdata is null) OR (ses_viewcount = 0)) THEN
					UPDATE `reportdata` as rd SET rd.`rd_viewcount` = rd.`rd_viewcount` + 1, rd.`rd_session` = session WHERE rd.`idreportdata` = l_idreportdata AND rd.`skbranch` = param_skbranch;
				END IF;
				ELSE
				INSERT INTO `reportdata` (`idreportdata`, `rd_session`, `o_guid`, `r_guid`, `iduser`, `rd_rating`, `rd_viewcount`, `skbranch`) VALUES (null, session, SUBSTRING(o_guid, 1, 40), SUBSTRING(r_guid, 1, 40), iduser, 0, 1, param_skbranch);
				END IF;

				SELECT IFNULL(SUM(rd.`rd_viewcount`),0) INTO viewcount from`reportdata` as rd WHERE  rd.`o_guid` = SUBSTRING(o_guid, 1, 40) AND rd.`r_guid` = SUBSTRING(r_guid, 1, 40)  AND rd.`skbranch` = param_skbranch;

				IF (l_hasrecord) THEN
					UPDATE `avgreportdata` as ard SET ard.`ard_viewcount` = viewcount WHERE ard.`o_guid` = SUBSTRING(o_guid, 1, 40) AND ard.`r_guid` = SUBSTRING(r_guid, 1, 40) AND ard.`skbranch` = param_skbranch;
				ELSE
					INSERT INTO `avgreportdata` (`o_guid` ,`r_guid`, `skbranch` ,`ard_rating` ,`ard_viewcount` ,`ard_msgcount` ) VALUES (SUBSTRING(o_guid, 1, 40), SUBSTRING(r_guid, 1, 40), param_skbranch, 0, viewcount, 0);
				END IF;
				
			END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 31;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 32) {
	// update to 32 version

	$query = "
		CREATE TABLE `userpositions` (
			`userid` INT NOT NULL,
			`oguid` VARCHAR(40) NOT NULL,
			INDEX `userid` (`userid`)
		)
		COLLATE='utf8mb4_general_ci'; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
		DROP TABLE IF EXISTS max_frmm_iright;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "	CREATE TEMPORARY TABLE IF NOT EXISTS max_frmm_iright AS (SELECT MAX(frmm_iright) + 1 as frmm_iright  FROM `forummessages`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "		UPDATE  `forummessages` SET  `forummessages`.frmm_ileft = 1, `forummessages`.frmm_iright = (SELECT IFNULL(frmm_iright,2) FROM max_frmm_iright) WHERE `idforummessage` = 0;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
		DROP TABLE IF EXISTS parents;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "
		CREATE TEMPORARY TABLE IF NOT EXISTS parents AS (SELECT idforummessage, frmm_ileft, frmm_iright, o_guid FROM forummessages WHERE parent_idforummessage = 0 AND idforummessage > 0);";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "
		UPDATE forummessages SET  frmm_depth = 2, parent_idforummessage = (
			SELECT f2.idforummessage FROM parents f2 WHERE  forummessages.frmm_ileft BETWEEN f2.frmm_ileft AND f2.frmm_iright AND f2.o_guid=forummessages.o_guid)
		WHERE forummessages.parent_idforummessage > 0;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
		DROP TABLE IF EXISTS parents;
	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE `add_forummessages`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
		
		CREATE PROCEDURE `add_forummessages`(
			IN `in_parent_idforummessage` INT,
			IN `o_guid` VARCHAR(40),
			IN `iduser` INT,
			IN `frmm_body` LONGTEXT,
			IN `branch` INT
		)
		LANGUAGE SQL
		NOT DETERMINISTIC
		CONTAINS SQL
		SQL SECURITY DEFINER
		COMMENT ''
		BEGIN
		declare cnt BIGINT DEFAULT null;
		declare parent_iright BIGINT;
		declare parent_depth BIGINT;
			declare param_skbranch INT DEFAULT -1;
			declare calc_parent_idforummessage INT;
			
			SELECT CASE WHEN parent_idforummessage = 0 THEN in_parent_idforummessage ELSE parent_idforummessage END into calc_parent_idforummessage FROM `forummessages` WHERE `idforummessage` = in_parent_idforummessage;
			
			IF (branch IS NULL) THEN
				SELECT b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
			ELSE 
				SELECT `branch` into param_skbranch;
			END IF;
		
			SET @@session.time_zone = \"+00:00\";
			SELECT COUNT(*) into cnt from `forummessages`;
			IF (cnt = 0 ) THEN
				INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_isdelete`, `frmm_ischanged`, `frmm_datechange_tmst`, `skbranch`) 
				VALUES ('0', '0', '00000000-0000-0000-0000-000000000000', '0', '1', '2', '0', 'root', 0, 0, UNIX_TIMESTAMP(NOW()), 0);	
				UPDATE `forummessages` SET `idforummessage` = 0;
			END IF;
				
			IF (CHAR_LENGTH(o_guid) <= 40 AND iduser > 1) THEN
				SELECT `frmm_iright`, `frmm_depth` into parent_iright, parent_depth from `forummessages` as frmm where frmm.`idforummessage` = calc_parent_idforummessage;
				UPDATE forummessages SET `frmm_ileft`=`frmm_ileft`+2,`frmm_iright`=`frmm_iright`+2 where `frmm_ileft`>parent_iright;
				UPDATE forummessages SET `frmm_iright`=`frmm_iright`+2 where `frmm_iright`>=parent_iright AND `frmm_ileft`<parent_iright;
				INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_isdelete`,  `frmm_ischanged`, `frmm_datechange_tmst`, `skbranch`) VALUES (NULL, calc_parent_idforummessage, o_guid, iduser, parent_iright, parent_iright+1, parent_depth+1, frmm_body, 0, 0, UNIX_TIMESTAMP(NOW()), param_skbranch);
			END IF;
		END;
	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 32;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 33) {
	// update to 33 version

	$query = "ALTER TABLE `userpositions`
					ALTER `userid` DROP DEFAULT,
					ALTER `oguid` DROP DEFAULT; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `userpositions`
					CHANGE COLUMN `userid` `iduser` INT(11) NOT NULL FIRST,
					CHANGE COLUMN `oguid` `o_guid` VARCHAR(40) NOT NULL COLLATE 'utf8mb4_general_ci' AFTER `iduser`; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 33;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 34) {
	// update to 34 version

	$query = "CREATE TABLE `resourcefromtablespollarchive` (
			`idpollingobjectarchive` INT(11) NOT NULL,
			`guidrecord` VARCHAR(40) NULL,
			`idrecord` INT(11) NOT NULL,
			`idtable` INT(11) NOT NULL,
			`idlanguage` INT(11) NOT NULL,
			`skbranch` INT(11) NOT NULL,
			`rft_columnname_text` VARCHAR(1100) NULL DEFAULT NULL COLLATE 'utf8mb4_general_ci',
			`rft_columnname_long` LONGTEXT NULL COLLATE 'utf8mb4_general_ci',
			PRIMARY KEY (`idpollingobjectarchive`, `idrecord`, `idtable`, `idlanguage`, `skbranch`),
			INDEX ix1 (`guidrecord`)
		)
		COLLATE='utf8mb4_general_ci'
		ENGINE=InnoDB; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 34;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 35) {
	// update to 35 version

	$query = "DROP PROCEDURE `createtree`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
	CREATE PROCEDURE `createtree`(
		IN `users_id` VARCHAR(1000)  ,
		IN `branch` INT
	
	)
	LANGUAGE SQL
	NOT DETERMINISTIC
	CONTAINS SQL
	SQL SECURITY DEFINER
	COMMENT ''
	BEGIN
	
		DECLARE l_idobject INT;
		DECLARE l_parent_idobject INT;
		DECLARE l_o_ileft INT;
		DECLARE l_o_iright INT;
		DECLARE done INT default 0;
		declare param_skbranch INT DEFAULT -1;
	
		DECLARE cursor_roots Cursor for 
			SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `o_useinsearch` = 1;
	
		DECLARE cursor_tree Cursor for 
			SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp_cut WHERE `parent_idobject` = 0 ORDER BY o_ileft DESC;
	
		DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
	
		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;
	
		DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp` ;
		CREATE TEMPORARY TABLE chkrt_o_temp (	
		`idobject` INT NOT NULL,
		`parent_idobject` INT NOT NULL,
		`ad0` INT NOT NULL,
		`ad1` INT NOT NULL,
		`ad2` INT NOT NULL,
		`root` INT NOT NULL,
		`o_ileft` INT NOT NULL,
		`o_iright` INT NOT NULL,
		`o_useinsearch` INT NOT NULL,
		`skbranch` INT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;
	
		DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_cut` ;
		CREATE TEMPORARY TABLE chkrt_o_temp_cut (	
		`idobject` INT NOT NULL,
		`parent_idobject` INT NOT NULL,
		`o_ileft` INT NOT NULL,
		`o_iright` INT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;
	
		INSERT IGNORE INTO `chkrt_o_temp` 
			SELECT `idobject`, `parent_idobject`, 0, 0, 0, 1, `o_ileft`, `o_iright`, `o_useinsearch`, `skbranch`  FROM `objects` WHERE `parent_idobject` <> 0 AND `o_hidefortree` = 0 AND `skbranch` = param_skbranch AND `idobject`;
	
		CREATE INDEX ix_pid ON chkrt_o_temp (parent_idobject);	
	
		DROP TEMPORARY TABLE IF EXISTS `t_rightsobjects` ;
		CREATE TEMPORARY TABLE `t_rightsobjects` (
			`iduser` INT(11) NOT NULL,
			`idobject` INT(11) NOT NULL,
			`deny_allow` TINYINT(1) NOT NULL,
			`skbranch` INT NOT NULL
		)ENGINE=MEMORY;
	
		SET @query = CONCAT('INSERT IGNORE INTO `t_rightsobjects` SELECT `iduser`, `idobject`, `deny_allow`, `skbranch` FROM `rightsobjects` WHERE `iduser` IN (',users_id,') AND `skbranch` = ',param_skbranch,';' );
			PREPARE zxc FROM @query;
			EXECUTE zxc;
	
	
		SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad0 = 1 WHERE t_rightsobjects.`deny_allow` = 0 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  );
			PREPARE zxc FROM @query;
			EXECUTE zxc;
	
		SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad1 = 1 WHERE  t_rightsobjects.`deny_allow` = 1 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  ); 
			PREPARE zxc FROM @query;
			EXECUTE zxc;
	
		SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad2 = 1 WHERE  t_rightsobjects.`deny_allow` = 2 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  );
			PREPARE zxc FROM @query;
			EXECUTE zxc;
	
		 DELETE FROM chkrt_o_temp WHERE (ad1 < 1 OR ad2 < 1) AND o_useinsearch = 0;
	
	   DELETE FROM chkrt_o_temp WHERE ad0 = 1 AND o_useinsearch = 0;
	
	   SET @query = CONCAT('INSERT IGNORE INTO chkrt_o_temp SELECT o.`idobject`, o.`parent_idobject`, 1, 1, 0, 1, o.`o_ileft`, o.`o_iright`, o.`o_useinsearch`, `skbranch`  FROM `objects` as o INNER JOIN  `users` as u ON u.`user_guid` = o.`o_guid` WHERE `parent_idobject` <> 0 AND o.`skbranch` = ',param_skbranch,' AND  o.`idobject` NOT IN (SELECT idobject FROM `rightsobjects` WHERE `deny_allow` IN (0,1,2)) AND  `o_hidefortree` = 0 AND u.`iduser` IN (',users_id,') ;'  );
			PREPARE zxc FROM @query;
			EXECUTE zxc;
			
		OPEN cursor_roots;
		WHILE done = 0 DO 
		FETCH cursor_roots INTO l_idobject,l_o_ileft,l_o_iright;
		SELECT COUNT(*) into @c FROM `chkrt_o_temp` WHERE `o_ileft` BETWEEN l_o_ileft AND l_o_iright AND `o_useinsearch` = 0;
		IF (@c = 0) THEN 
			DELETE FROM chkrt_o_temp WHERE idobject = l_idobject;
		END IF;
		END WHILE;
		Close cursor_roots; 
	
			DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_id` ;
			CREATE TEMPORARY TABLE chkrt_o_temp_id (	
			`idobject` INT NOT NULL,
			PRIMARY KEY (`idobject`)
			)ENGINE=MEMORY;
	
			INSERT IGNORE INTO `chkrt_o_temp_id` 
				SELECT `idobject` FROM chkrt_o_temp;
	
	
		UPDATE chkrt_o_temp RIGHT OUTER JOIN `chkrt_o_temp_id` ON (chkrt_o_temp.parent_idobject = chkrt_o_temp_id.idobject) 
		SET root = 0;
		UPDATE chkrt_o_temp SET parent_idobject = 0 WHERE root = 1;
		INSERT INTO chkrt_o_temp_cut
		SELECT `idobject`, `parent_idobject`,`o_ileft`,`o_iright` FROM chkrt_o_temp;
		
		SET done=0;
		OPEN cursor_tree;
		WHILE done = 0 DO 
			FETCH cursor_tree INTO l_idobject,l_o_ileft,l_o_iright;
			IF( EXISTS( SELECT idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1 )) THEN
				SELECT idobject INTO l_parent_idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1;
				UPDATE `chkrt_o_temp` SET `parent_idobject` = IFNULL(l_parent_idobject,0) WHERE `idobject`= l_idobject;
			ELSE 
				UPDATE `chkrt_o_temp` SET `parent_idobject` = 0 WHERE `idobject`= l_idobject;
			END IF;
		END WHILE;
		Close cursor_tree; 
	
	END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 35;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 36) {
	// update to 36 version

	$query = "ALTER TABLE `mailqueue`
				ADD COLUMN `idmailqueue` INT NOT NULL AUTO_INCREMENT FIRST,
				ADD PRIMARY KEY (`idmailqueue`); ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `mailqueue`
				ALTER `mq_copy` DROP DEFAULT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `mailqueue`
				CHANGE COLUMN `mq_copy` `mq_replyto` VARCHAR(1000) NOT NULL COLLATE 'utf8mb4_general_ci' AFTER `mq_recipients`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "ALTER TABLE `mailqueue`
				CHANGE COLUMN `mq_text` `mq_body` LONGTEXT NOT NULL COLLATE 'utf8mb4_general_ci' AFTER `mq_subject`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `mailqueue`
				ADD COLUMN `idmaitype` INT(11) NOT NULL DEFAULT '0' AFTER `idmailqueue`,
				ADD INDEX `idmaitype` (`idmaitype`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `maitypes` (
					`idmaitype` INT(11) NOT NULL DEFAULT '0',
					`mt_name` VARCHAR(100) NOT NULL COLLATE 'utf8mb4_general_ci',
					`mt_description` VARCHAR(1000) NOT NULL COLLATE 'utf8mb4_general_ci',
					PRIMARY KEY (`idmaitype`)
				)
				COLLATE='utf8mb4_general_ci'
				ENGINE=InnoDB;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "INSERT IGNORE INTO  `maitypes` VALUES( 200, 'pollNew', '');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "INSERT IGNORE INTO  `maitypes` VALUES( 300, 'pollNewAnalyst', '');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "INSERT IGNORE INTO  `maitypes` VALUES( 400, 'pollNewAdmin', '');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "INSERT IGNORE INTO  `maitypes` VALUES( 500, 'pollContainsErrors', '');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "INSERT IGNORE INTO  `maitypes` VALUES( 500, 'pollContainsErrorsAdmin', '');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "INSERT IGNORE INTO  `maitypes` VALUES( 600, 'pollDelete', '');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "INSERT IGNORE INTO  `maitypes` VALUES( 700, 'pollStop', '');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "INSERT IGNORE INTO  `maitypes` VALUES( 800, 'pollContinue', '');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "INSERT IGNORE INTO  `maitypes` VALUES( 900, 'pollHide', '');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
		
	$query = "CREATE TABLE `objectsprohibitionrightscopy` (
				`idobject` INT(11) NOT NULL,
				`obcr_prohibit` TINYINT(1) NOT NULL,
				PRIMARY KEY (`idobject`)
			)
			COLLATE='utf8mb4_general_ci'
			ENGINE=InnoDB
			AUTO_INCREMENT=8;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	

	$query = "ALTER TABLE `users`	DROP COLUMN `user_notification_owner`;	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "ALTER TABLE `users`	DROP COLUMN `user_notification_autor`;	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "ALTER TABLE `users`	DROP COLUMN `user_notification_newversions`;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 36;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 37) {
	// update to 37 version

	$query = "DROP PROCEDURE `load_reports`;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "DROP PROCEDURE `createtree`;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `load_reports`(
				IN `o_guid` VARCHAR(1000),
				IN `userights` INT,
				IN `users_id` VARCHAR(1000),
				IN `idlanguage` INT,
				IN `branch` INT
			
			
			)
			LANGUAGE SQL
			NOT DETERMINISTIC
			CONTAINS SQL
			SQL SECURITY DEFINER
			COMMENT ''
			BEGIN
				declare idobject INT DEFAULT -1;
				declare param_skbranch INT DEFAULT -1;
				IF (branch IS NULL) THEN
					SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
				ELSE 
					SELECT  `branch` into param_skbranch;
				END IF;
			
			DROP TEMPORARY TABLE IF EXISTS `r_temp` ;
				CREATE TEMPORARY TABLE `r_temp` (
					`idreport` INT NOT NULL
				)ENGINE=MEMORY;
			
			
			DROP TEMPORARY TABLE IF EXISTS `rr_temp` ;
			CREATE TEMPORARY TABLE rr_temp (    
				`idreport` INT NOT NULL,
				PRIMARY KEY (`idreport`)
			)ENGINE=MEMORY;
			
			SELECT obj.`idobject` into idobject from `objects` as obj where obj.`o_guid` = SUBSTRING(o_guid, 1, 40)  AND  obj.`skbranch` = param_skbranch;
			
			IF ( idobject > 0 ) THEN
					INSERT INTO r_temp SELECT rep.`idreport` FROM `reports` as rep INNER JOIN `objectsreports` as orl ON orl.`idreport` = rep.`idreport` AND  orl.`skbranch` = param_skbranch  WHERE orl.`idobject` = idobject AND  rep.`skbranch` = param_skbranch AND (ifnull(orl.`idlanguage`,0) = ifnull(idlanguage,0) OR  ifnull(orl.`idlanguage`,0) = 0); 
			
					IF ( userights <> 0 ) THEN
					INSERT INTO `rr_temp` SELECT `idreport` FROM `r_temp`; 
						SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 0 );'  );
						PREPARE zxc FROM @query;
						EXECUTE zxc;
				
						SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 1 );'  );
						PREPARE zxc FROM @query;
						EXECUTE zxc;
				
						SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 2 );'  );
						PREPARE zxc FROM @query;
						EXECUTE zxc;
				
					SET @query = CONCAT('INSERT IGNORE INTO `rr_temp`	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 (',users_id,') and o.o_guid = \"',o_guid,'\" AND o.`skbranch` = ',param_skbranch,'  AND orts.idreport NOT IN (SELECT rr.idreport FROM  `rightsreports` as rr WHERE  rr.`skbranch` = ',param_skbranch,'  AND rr.deny_allow = 0 AND iduser in (',users_id,'));'  );
						PREPARE zxc FROM @query;
						EXECUTE zxc;
						
						DELETE FROM r_temp  WHERE r_temp.`idreport` NOT IN ( SELECT rr_temp.`idreport` FROM rr_temp );
					END IF;	  
			END IF;	      
			END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			CREATE DEFINER=`root`@`localhost` PROCEDURE `createtree`(
				IN `users_id` VARCHAR(1000)  ,
				IN `branch` INT
			
			
			
			)
			LANGUAGE SQL
			NOT DETERMINISTIC
			CONTAINS SQL
			SQL SECURITY DEFINER
			COMMENT ''
			BEGIN
			
				DECLARE l_idobject INT;
				DECLARE l_parent_idobject INT;
				DECLARE l_o_ileft INT;
				DECLARE l_o_iright INT;
				DECLARE done INT default 0;
				declare param_skbranch INT DEFAULT -1;
			
				DECLARE cursor_roots Cursor for 
					SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `o_useinsearch` = 1;
			
				DECLARE cursor_tree Cursor for 
					SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp_cut WHERE `parent_idobject` = 0 ORDER BY o_ileft DESC;
			
				DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
			
				IF (branch IS NULL) THEN
					SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
				ELSE 
					SELECT  `branch` into param_skbranch;
				END IF;
			
				DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp` ;
				CREATE TEMPORARY TABLE chkrt_o_temp (	
				`idobject` INT NOT NULL,
				`parent_idobject` INT NOT NULL,
				`ad0` INT NOT NULL,
				`ad1` INT NOT NULL,
				`ad2` INT NOT NULL,
				`root` INT NOT NULL,
				`o_ileft` INT NOT NULL,
				`o_iright` INT NOT NULL,
				`o_useinsearch` INT NOT NULL,
				`skbranch` INT NOT NULL,
				PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;
			
				DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_cut` ;
				CREATE TEMPORARY TABLE chkrt_o_temp_cut (	
				`idobject` INT NOT NULL,
				`parent_idobject` INT NOT NULL,
				`o_ileft` INT NOT NULL,
				`o_iright` INT NOT NULL,
				PRIMARY KEY (`idobject`)
				)ENGINE=MEMORY;
			
				INSERT IGNORE INTO `chkrt_o_temp` 
					SELECT `idobject`, `parent_idobject`, 0, 0, 0, 1, `o_ileft`, `o_iright`, `o_useinsearch`, `skbranch`  FROM `objects` WHERE `parent_idobject` <> 0 AND `o_hidefortree` = 0 AND `skbranch` = param_skbranch AND `idobject`;
			
				CREATE INDEX ix_pid ON chkrt_o_temp (parent_idobject);	
			
				DROP TEMPORARY TABLE IF EXISTS `t_rightsobjects` ;
				CREATE TEMPORARY TABLE `t_rightsobjects` (
					`iduser` INT(11) NOT NULL,
					`idobject` INT(11) NOT NULL,
					`deny_allow` TINYINT(1) NOT NULL,
					`skbranch` INT NOT NULL
				)ENGINE=MEMORY;
			
				SET @query = CONCAT('INSERT IGNORE INTO `t_rightsobjects` SELECT `iduser`, `idobject`, `deny_allow`, `skbranch` FROM `rightsobjects` WHERE `iduser` IN (',users_id,') AND `skbranch` = ',param_skbranch,';' );
					PREPARE zxc FROM @query;
					EXECUTE zxc;
			
			
				SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad0 = 1 WHERE t_rightsobjects.`deny_allow` = 0 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;
			
				SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad1 = 1 WHERE  t_rightsobjects.`deny_allow` = 1 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  ); 
					PREPARE zxc FROM @query;
					EXECUTE zxc;
			
				SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad2 = 1 WHERE  t_rightsobjects.`deny_allow` = 2 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;
			
				DELETE FROM chkrt_o_temp WHERE (ad1 < 1 OR ad2 < 1) AND o_useinsearch = 0;
			
			DELETE FROM chkrt_o_temp WHERE ad0 = 1 AND o_useinsearch = 0;
			
			SET @query = CONCAT('INSERT IGNORE INTO chkrt_o_temp SELECT o.`idobject`, o.`parent_idobject`, 1, 1, 0, 1, o.`o_ileft`, o.`o_iright`, o.`o_useinsearch`, `skbranch`  FROM `objects` as o INNER JOIN  `users` as u ON u.`user_guid` = o.`o_guid` WHERE `parent_idobject` <> 0 AND o.`skbranch` = ',param_skbranch,' AND  o.`idobject` NOT IN (SELECT idobject FROM `rightsobjects` WHERE `deny_allow` = 0 AND `iduser` IN (',users_id,')) AND  `o_hidefortree` = 0 AND u.`iduser` IN (',users_id,') ;'  );
					PREPARE zxc FROM @query;
					EXECUTE zxc;
					
				OPEN cursor_roots;
				WHILE done = 0 DO 
				FETCH cursor_roots INTO l_idobject,l_o_ileft,l_o_iright;
				SELECT COUNT(*) into @c FROM `chkrt_o_temp` WHERE `o_ileft` BETWEEN l_o_ileft AND l_o_iright AND `o_useinsearch` = 0;
				IF (@c = 0) THEN 
					DELETE FROM chkrt_o_temp WHERE idobject = l_idobject;
				END IF;
				END WHILE;
				Close cursor_roots; 
			
			
					DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_id` ;
					CREATE TEMPORARY TABLE chkrt_o_temp_id (	
					`idobject` INT NOT NULL,
					PRIMARY KEY (`idobject`)
					)ENGINE=MEMORY;
			
			
					INSERT IGNORE INTO `chkrt_o_temp_id` 
						SELECT `idobject` FROM chkrt_o_temp;
			
			
				UPDATE chkrt_o_temp RIGHT OUTER JOIN `chkrt_o_temp_id` ON (chkrt_o_temp.parent_idobject = chkrt_o_temp_id.idobject) 
				SET root = 0;
				UPDATE chkrt_o_temp SET parent_idobject = 0 WHERE root = 1;
				INSERT INTO chkrt_o_temp_cut
				SELECT `idobject`, `parent_idobject`,`o_ileft`,`o_iright` FROM chkrt_o_temp;
				
				SET done=0;
				OPEN cursor_tree;
				WHILE done = 0 DO 
					FETCH cursor_tree INTO l_idobject,l_o_ileft,l_o_iright;
					IF( EXISTS( SELECT idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1 )) THEN
						SELECT idobject INTO l_parent_idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1;
						UPDATE `chkrt_o_temp` SET `parent_idobject` = IFNULL(l_parent_idobject,0) WHERE `idobject`= l_idobject;
					ELSE 
						UPDATE `chkrt_o_temp` SET `parent_idobject` = 0 WHERE `idobject`= l_idobject;
					END IF;
				END WHILE;
				Close cursor_tree; 
			
			END;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 37;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 38) {
	// update to 38 version

	$query = "INSERT IGNORE INTO `tables` VALUES (1111, 'pollingobjects.objectversionfullname'), (1113, 'pollingobjectsarchive.objectversionfullname');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 38;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}
$last = 38;


if ($ver < 39) {
	// update to 38 version

	$query = "
			ALTER TABLE `objects`
			CHANGE COLUMN `idobject` `idobject` BIGINT NOT NULL AUTO_INCREMENT FIRST;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objects`
				ALTER `parent_idobject` DROP DEFAULT;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objects`
				CHANGE COLUMN `parent_idobject` `parent_idobject` BIGINT NOT NULL AFTER `idobject`;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objects`
				ALTER `o_ileft` DROP DEFAULT,
				ALTER `o_iright` DROP DEFAULT,
				ALTER `o_depth` DROP DEFAULT;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objects`
				CHANGE COLUMN `o_ileft` `o_ileft` BIGINT NOT NULL AFTER `parent_idobject`,
				CHANGE COLUMN `o_iright` `o_iright` BIGINT NOT NULL AFTER `o_ileft`,
				CHANGE COLUMN `o_depth` `o_depth` BIGINT NOT NULL AFTER `o_iright`;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `resourcefromtables`
				ALTER `idrecord` DROP DEFAULT;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `resourcefromtables`
				CHANGE COLUMN `idrecord` `idrecord` BIGINT NOT NULL FIRST;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `resourcefromtablespollarchive`
				ALTER `idrecord` DROP DEFAULT;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `resourcefromtablespollarchive`
				CHANGE COLUMN `idrecord` `idrecord` BIGINT NOT NULL AFTER `guidrecord`;
";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objectlinks`
				ALTER `idobject` DROP DEFAULT;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objectlinks`
				CHANGE COLUMN `idobject` `idobject` BIGINT NOT NULL AFTER `iduser`;
";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objectsprohibitionrightscopy`
				ALTER `idobject` DROP DEFAULT;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objectsprohibitionrightscopy`
				CHANGE COLUMN `idobject` `idobject` BIGINT NOT NULL FIRST;
";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objectsreports`
				ALTER `idobject` DROP DEFAULT;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `objectsreports`
				CHANGE COLUMN `idobject` `idobject` BIGINT NOT NULL FIRST;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `reportindex`
				ALTER `idobject` DROP DEFAULT;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `reportindex`
				CHANGE COLUMN `idobject` `idobject` BIGINT NOT NULL FIRST;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `rightsobjects`
				ALTER `idobject` DROP DEFAULT;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `rightsobjects`
				CHANGE COLUMN `idobject` `idobject` BIGINT NOT NULL AFTER `iduser`;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `titleindex`
				ALTER `idobject` DROP DEFAULT;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `titleindex`
				CHANGE COLUMN `idobject` `idobject` BIGINT NOT NULL FIRST;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `branches`
				ALTER `ismain` DROP DEFAULT;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			ALTER TABLE `branches`
				CHANGE COLUMN `ismain` `ismain` TINYINT(4) NOT NULL AFTER `skbranch`,
				ADD COLUMN `iscomplete` TINYINT NOT NULL DEFAULT '0' AFTER `ismain`;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			UPDATE `branches` SET `iscomplete` = 1;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
			DROP PROCEDURE IF EXISTS `add_objects` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `add_objects`(IN `parent_guid` CHAR(40), IN `guid` CHAR(40), IN `icon` INT, IN `datechange` DATETIME, IN `ver` VARCHAR(800), IN `datever` DATE, IN `statever` INT, IN `hasreports` TINYINT, IN `useinsearch` TINYINT, IN `hidefortree` TINYINT, `branchid` VARCHAR(50))
	BEGIN
		declare parent_iright BIGINT DEFAULT null;
		declare parent_id BIGINT DEFAULT null;
		declare parent_depth BIGINT DEFAULT null;
		declare parent_skbranch INT DEFAULT null;
		SELECT `skbranch` into parent_skbranch FROM branches WHERE idbranch = branchid;
		IF(NOT EXISTS( SELECT 1 FROM `objects` WHERE `o_guid` = `guid` AND skbranch = parent_skbranch )) THEN
			SELECT `o_iright`, `o_depth`, `idobject` into parent_iright, parent_depth, parent_id from objects where o_guid=parent_guid AND (skbranch = parent_skbranch OR parent_guid = '00000000-0000-0000-0000-000000000000');
			IF ( parent_id IS NOT null ) THEN	
				UPDATE objects SET `o_ileft`=`o_ileft`+2,`o_iright`=`o_iright`+2 where `o_ileft`>parent_iright;
				UPDATE objects SET `o_iright`=`o_iright`+2 where `o_iright`>=parent_iright AND `o_ileft`<parent_iright;
				INSERT INTO `objects` (`parent_idobject`, `o_ileft`, `o_iright`, `o_depth`, `o_guid`, `o_icon`, `o_datechange`, `o_ver` , `o_datever` , `o_statever`, `o_hasreports`, `o_useinsearch`, `o_hidefortree`, `skbranch` ) VALUES (parent_id, parent_iright, parent_iright+1, parent_depth+1, guid, icon, datechange, ver , datever , statever, hasreports, useinsearch, hidefortree, parent_skbranch );
			END IF;	      
		END IF;	      
	END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
			DROP PROCEDURE IF EXISTS `createtree` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `createtree`(IN `users_id` VARCHAR(2500), IN `branch` INT)
	BEGIN

		DECLARE l_idobject BIGINT;
		DECLARE l_parent_idobject BIGINT;
		DECLARE l_o_ileft BIGINT;
		DECLARE l_o_iright BIGINT;
		DECLARE done INT default 0;
		declare param_skbranch INT DEFAULT -1;

		DECLARE cursor_roots Cursor for 
			SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `o_useinsearch` = 1;

		DECLARE cursor_tree Cursor for 
			SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp_cut WHERE `parent_idobject` = 0 ORDER BY o_ileft DESC;

		DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;

		DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp` ;
		CREATE TEMPORARY TABLE chkrt_o_temp (	
		`idobject` BIGINT NOT NULL,
		`parent_idobject` BIGINT NOT NULL,
		`ad0` INT NOT NULL,
		`ad1` INT NOT NULL,
		`ad2` INT NOT NULL,
		`root` INT NOT NULL,
		`o_ileft` INT NOT NULL,
		`o_iright` INT NOT NULL,
		`o_useinsearch` INT NOT NULL,
		`skbranch` INT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;

		DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_cut` ;
		CREATE TEMPORARY TABLE chkrt_o_temp_cut (	
		`idobject` BIGINT NOT NULL,
		`parent_idobject` BIGINT NOT NULL,
		`o_ileft` BIGINT NOT NULL,
		`o_iright` BIGINT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;

		INSERT IGNORE INTO `chkrt_o_temp` 
			SELECT `idobject`, `parent_idobject`, 0, 0, 0, 1, `o_ileft`, `o_iright`, `o_useinsearch`, `skbranch`  FROM `objects` WHERE `parent_idobject` <> 0 AND `o_hidefortree` = 0 AND `skbranch` = param_skbranch AND `idobject`;

		CREATE INDEX ix_pid ON chkrt_o_temp (parent_idobject);	

		DROP TEMPORARY TABLE IF EXISTS `t_rightsobjects` ;
		CREATE TEMPORARY TABLE `t_rightsobjects` (
			`iduser` INT(11) NOT NULL,
			`idobject` BIGINT NOT NULL,
			`deny_allow` TINYINT(1) NOT NULL,
			`skbranch` INT NOT NULL
		)ENGINE=MEMORY;

		SET @query = CONCAT('INSERT IGNORE INTO `t_rightsobjects` SELECT `iduser`, `idobject`, `deny_allow`, `skbranch` FROM `rightsobjects` WHERE `iduser` IN (',users_id,') AND `skbranch` = ',param_skbranch,';' );
			PREPARE zxc FROM @query;
			EXECUTE zxc;


		SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad0 = 1 WHERE t_rightsobjects.`deny_allow` = 0 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  );
			PREPARE zxc FROM @query;
			EXECUTE zxc;

		SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad1 = 1 WHERE  t_rightsobjects.`deny_allow` = 1 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  ); 
			PREPARE zxc FROM @query;
			EXECUTE zxc;

		SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad2 = 1 WHERE  t_rightsobjects.`deny_allow` = 2 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  );
			PREPARE zxc FROM @query;
			EXECUTE zxc;

		DELETE FROM chkrt_o_temp WHERE (ad1 < 1 OR ad2 < 1) AND o_useinsearch = 0;

	   DELETE FROM chkrt_o_temp WHERE ad0 = 1 AND o_useinsearch = 0;

	   SET @query = CONCAT('INSERT IGNORE INTO chkrt_o_temp SELECT o.`idobject`, o.`parent_idobject`, 1, 1, 0, 1, o.`o_ileft`, o.`o_iright`, o.`o_useinsearch`, `skbranch`  FROM `objects` as o INNER JOIN  `users` as u ON u.`user_guid` = o.`o_guid` WHERE `parent_idobject` <> 0 AND o.`skbranch` = ',param_skbranch,' AND  o.`idobject` NOT IN (SELECT idobject FROM `rightsobjects` WHERE `deny_allow` IN (0,1,2) AND `iduser` IN (',users_id,')) AND  `o_hidefortree` = 0 AND u.`iduser` IN (',users_id,') ;'  );
			PREPARE zxc FROM @query;
			EXECUTE zxc;
			
		OPEN cursor_roots;
		WHILE done = 0 DO 
		FETCH cursor_roots INTO l_idobject,l_o_ileft,l_o_iright;
		SELECT COUNT(*) into @c FROM `chkrt_o_temp` WHERE `o_ileft` BETWEEN l_o_ileft AND l_o_iright AND `o_useinsearch` = 0;
		IF (@c = 0) THEN 
			DELETE FROM chkrt_o_temp WHERE idobject = l_idobject;
		END IF;
		END WHILE;
		Close cursor_roots; 


			DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_id` ;
			CREATE TEMPORARY TABLE chkrt_o_temp_id (	
			`idobject` BIGINT NOT NULL,
			PRIMARY KEY (`idobject`)
			)ENGINE=MEMORY;


			INSERT IGNORE INTO `chkrt_o_temp_id` 
				SELECT `idobject` FROM chkrt_o_temp;


		UPDATE chkrt_o_temp RIGHT OUTER JOIN `chkrt_o_temp_id` ON (chkrt_o_temp.parent_idobject = chkrt_o_temp_id.idobject) 
		SET root = 0;
		UPDATE chkrt_o_temp SET parent_idobject = 0 WHERE root = 1;
		INSERT INTO chkrt_o_temp_cut
		SELECT `idobject`, `parent_idobject`,`o_ileft`,`o_iright` FROM chkrt_o_temp;
		
		SET done=0;
		OPEN cursor_tree;
		WHILE done = 0 DO 
			FETCH cursor_tree INTO l_idobject,l_o_ileft,l_o_iright;
			IF( EXISTS( SELECT idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1 )) THEN
				SELECT idobject INTO l_parent_idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1;
				UPDATE `chkrt_o_temp` SET `parent_idobject` = IFNULL(l_parent_idobject,0) WHERE `idobject`= l_idobject;
			ELSE 
				UPDATE `chkrt_o_temp` SET `parent_idobject` = 0 WHERE `idobject`= l_idobject;
			END IF;
		END WHILE;
		Close cursor_tree;      
	END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			DROP PROCEDURE IF EXISTS `create_objectsrightstmp` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `create_objectsrightstmp`(IN `users_id` VARCHAR(2500) )
	BEGIN
		DROP TEMPORARY TABLE IF EXISTS `or_temp` ;

		CREATE TEMPORARY TABLE or_temp (    
		`idobject` BIGINT NOT NULL,
		`sumr` INT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;

		SET @query = CONCAT('INSERT INTO `or_temp` SELECT `idobject`, SUM(IF( ( `deny_allow` = 0 ) , -3,  `deny_allow` )) FROM `rightsobjects` WHERE `iduser` IN (',users_id,') GROUP BY `idobject`;');
		PREPARE zxc FROM @query;
		EXECUTE zxc;

		DELETE FROM `or_temp` WHERE sumr <> 3;
	END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			DROP PROCEDURE IF EXISTS `create_reportsrightstmp` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `create_reportsrightstmp`(	IN `users_id` VARCHAR(2500), IN `o_guid` VARCHAR(40) )
	BEGIN
		declare idobject BIGINT DEFAULT -1;
		DROP TEMPORARY TABLE IF EXISTS `rr_temp` ;

		CREATE TEMPORARY TABLE rr_temp (    
		`idreport` INT NOT NULL,
		`sumr` INT NOT NULL,
		 PRIMARY KEY (`idreport`)
		)ENGINE=MEMORY;

		SELECT obj.`idobject` into idobject from `objects` as obj where obj.`o_guid` = o_guid;

		SET @query = CONCAT('INSERT INTO `or_temp` SELECT `idobject`, SUM(IF( ( `deny_allow` = 0 ) , -3,  `deny_allow` )) FROM `rightsobjects` WHERE `iduser` IN (',users_id,') AND `idreport` IN (SELECT `idreport` FROM `objectsreports` WHERE `idobject` = ',idobject,') GROUP BY `idobject`;');
		PREPARE zxc FROM @query;
		EXECUTE zxc;

		DELETE FROM `or_temp` WHERE sumr <> 3;
	END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "DROP PROCEDURE IF EXISTS `load_objectpath` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `load_objectpath`(IN `idobject` BIGINT, IN `userights` INT, IN `users_id` VARCHAR(2500), IN `branch` INT)
	BEGIN
		declare parent_idobject BIGINT DEFAULT idobject;
		declare param_skbranch INT DEFAULT -1;

		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;

		DROP TEMPORARY TABLE IF EXISTS `o_temp_tree` ;
		CREATE TEMPORARY TABLE o_temp_tree (	
			`idpobject` BIGINT NOT NULL,
			`parent_idobject` BIGINT NOT NULL,
			`o_ileft` BIGINT NOT NULL,
			PRIMARY KEY (`idpobject`)
		)ENGINE=MEMORY;
		
	  IF ( userights = 0 ) THEN
		WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0  ) DO	
			INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`), obj.`o_ileft` FROM `objects` as obj WHERE obj.`idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND obj.`skbranch` = param_skbranch;
			SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `objects` as obj where obj.`idobject` = parent_idobject AND obj.`skbranch` = param_skbranch;
		END WHILE;
	  ELSE
		CALL createtree(users_id, param_skbranch);
		WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0 ) DO	
		IF EXISTS (SELECT 1 FROM `chkrt_o_temp` as obj WHERE obj.`idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND obj.`skbranch` = param_skbranch) THEN
				INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`), obj.`o_ileft` FROM `chkrt_o_temp` as obj WHERE obj.`idobject` = parent_idobject AND obj.`parent_idobject` <> 0;
			SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject;
			ELSE
				SELECT 0 into parent_idobject;
			END IF;	
		 END WHILE;
	  END IF;
	END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "DROP PROCEDURE IF EXISTS `load_objects` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `load_objects`(IN `parent_idobject` BIGINT, IN `userights` INT, IN `users_id` VARCHAR(2500) ,IN `branch` INT )
	BEGIN
		declare root_parent_idobject BIGINT;
		declare param_skbranch INT DEFAULT -1;
		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;
		DROP TEMPORARY TABLE IF EXISTS `o_temp` ;
			CREATE TEMPORARY TABLE o_temp (	
			`idobject` BIGINT NOT NULL,
			`parent_idobject` BIGINT NOT NULL,
			PRIMARY KEY (`idobject`)
			)ENGINE=MEMORY;
		IF ( userights = 0 ) THEN
			IF ( parent_idobject = 0 ) THEN
				SELECT obj.`idobject` into root_parent_idobject from `objects` as obj where obj.`parent_idobject` = 0;
			ELSE   
				SET root_parent_idobject = parent_idobject;
			END IF;   
				INSERT IGNORE INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`parent_idobject` = root_parent_idobject AND `o_hidefortree` = 0 AND obj.`skbranch` = param_skbranch;
		ELSE
				CALL createtree(users_id, param_skbranch);
				INSERT IGNORE INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `chkrt_o_temp` as obj WHERE obj.`parent_idobject` = parent_idobject ;
		END IF;
	END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "DROP PROCEDURE IF EXISTS `load_objectsAdmin` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `load_objectsAdmin`(IN `parent_idobject` BIGINT  )
	BEGIN
		declare root_parent_idobject BIGINT;
		DROP TEMPORARY TABLE IF EXISTS `o_temp` ;
		CREATE TEMPORARY TABLE o_temp (	
		`idobject` BIGINT NOT NULL,
		`parent_idobject` BIGINT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;

		CREATE TEMPORARY TABLE or_temp (    
		`idobject` BIGINT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;

		DROP TEMPORARY TABLE IF EXISTS `o_temp_clone` ;
		CREATE TEMPORARY TABLE o_temp_clone (	
		`idobject` BIGINT NOT NULL,
		`parent_idobject` BIGINT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;

		DROP TEMPORARY TABLE IF EXISTS `or_temp_clone` ;
		CREATE TEMPORARY TABLE or_temp_clone (	
		`idobject` BIGINT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;

	   IF ( parent_idobject = 0 ) THEN

		SELECT obj.`idobject` into root_parent_idobject from `objects` as obj where obj.`parent_idobject` = 0 AND ((o_iright - o_ileft) > 1);
		INSERT INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`idobject` <> root_parent_idobject AND ((o_iright - o_ileft) > 1);
		INSERT INTO `o_temp_clone` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`idobject` <> root_parent_idobject AND ((o_iright - o_ileft) > 1);
		DELETE FROM `o_temp` WHERE `o_temp`.`parent_idobject` IN ( SELECT `o_temp_clone`.`idobject` FROM `o_temp_clone` );
	   ELSE
		INSERT INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`parent_idobject` = parent_idobject AND ((o_iright - o_ileft) > 1);
	   END IF;	      

	END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "DROP PROCEDURE IF EXISTS `load_objects_admin` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `load_objects_admin`(	IN `parent_id` BIGINT, IN `depth` BIGINT, IN `r_guid` VARCHAR(1000), IN `branch` INT )
	BEGIN
		declare ileft BIGINT DEFAULT -1;
		declare iright BIGINT DEFAULT -1;
		declare param_skbranch INT DEFAULT -1;

		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;

		DROP TEMPORARY TABLE IF EXISTS `admin_temp` ;
		CREATE TEMPORARY TABLE `admin_temp` (
		`idobject` BIGINT NOT NULL,
		`o_guid` VARCHAR(36) NOT NULL,
		`r_guid` VARCHAR(36) NOT NULL,
		`at_rating` INT,
		`at_viewcount` INT,
		`at_msgcnt` INT,
		`at_msglastdate` DATETIME,
		 PRIMARY KEY(idobject)
		)ENGINE=MEMORY;

		CREATE INDEX o_guid_admin_temp ON admin_temp (o_guid);
		SELECT obj.`o_ileft`, obj.`o_iright` into ileft, iright from `objects` as obj where obj.`idobject` = parent_id and obj.`skbranch` = param_skbranch;

		INSERT INTO admin_temp SELECT obj.idobject, obj.o_guid, SUBSTRING(r_guid, 1, 40), NULL, NULL, NULL, NULL FROM `objects` as obj where obj.`skbranch` = param_skbranch and obj.`o_ileft` BETWEEN ileft+1 AND iright AND o_depth < depth;

		UPDATE `admin_temp` as at, `avgreportdata` as ard
		SET `at_rating` =  `ard_rating`,
			`at_viewcount` = `ard_viewcount`
		WHERE ard.`skbranch` = param_skbranch AND CONVERT(at.`o_guid` USING utf32) = CONVERT(ard.`o_guid` USING utf32) AND CONVERT(at.`r_guid` USING utf32) = CONVERT(ard.`r_guid` USING utf32) ;

	   UPDATE `admin_temp`
		SET `at_viewcount` = 0
		WHERE `at_viewcount` IS NULL;

		UPDATE `admin_temp` as at  
		SET `at_msgcnt` =  (SELECT IFNULL(COUNT(0),0) FROM `forummessages` as frmm WHERE frmm.`skbranch` = param_skbranch AND CONVERT(frmm.`o_guid` USING utf32)  = CONVERT(at.`o_guid` USING utf32)  and frmm.`frmm_isdelete`=0);

		UPDATE `admin_temp` as at  
		SET `at_msglastdate` =  (SELECT MAX(from_unixtime(frmm_datechange_tmst)) FROM `forummessages` as frmm WHERE frmm.`skbranch` = param_skbranch AND  CONVERT(frmm.`o_guid` USING utf32)  = CONVERT(at.`o_guid` USING utf32)  and frmm.`frmm_isdelete`=0);

	END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "DROP PROCEDURE IF EXISTS `load_objecttree` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `load_objecttree`(	IN `idobject` BIGINT, IN `userights` INT, IN `users_id` VARCHAR(2500), IN `branch` INT )
	BEGIN
		declare parent_idobject BIGINT DEFAULT idobject;
		declare param_skbranch INT DEFAULT -1;
		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;

		DROP TEMPORARY TABLE IF EXISTS `o_temp_tree` ;
		CREATE TEMPORARY TABLE o_temp_tree (	
		`idpobject` BIGINT NOT NULL,
		`parent_idobject` BIGINT NOT NULL,
		 PRIMARY KEY (`idpobject`)
		)ENGINE=MEMORY;
		
	  IF ( userights = 0 ) THEN
		WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0) DO	
			SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `objects` as obj where obj.`idobject` = parent_idobject AND obj.`skbranch` = param_skbranch;
			INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`parent_idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND obj.`skbranch` = param_skbranch AND `o_hidefortree` = 0;
		END WHILE;
	  ELSE
		CALL createtree(users_id, param_skbranch);
		WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0 ) DO	
			IF EXISTS (SELECT 1 from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject) THEN
				SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject AND obj.`skbranch` = param_skbranch;
				INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, obj.`parent_idobject` FROM `chkrt_o_temp` as obj WHERE obj.`parent_idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND obj.`skbranch` = param_skbranch;
			ELSE
				SELECT 0 into parent_idobject;
			END IF;	    
		END WHILE;
	  END IF;

	  CALL load_objects(0, userights, users_id, param_skbranch);
	END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "DROP PROCEDURE IF EXISTS `load_objecttree_search` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `load_objecttree_search`(	IN `branch` INT )
	BEGIN
		declare param_skbranch INT DEFAULT -1;

		IF (branch IS NOT NULL) THEN
			SELECT  `branch` into param_skbranch;
		END IF;

		DROP TEMPORARY TABLE IF EXISTS `o_temp` ;
		CREATE TEMPORARY TABLE o_temp (	
		`idobject` BIGINT NOT NULL,
		`parent_idobject` BIGINT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;

		INSERT INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`o_useinsearch` = 1 AND obj.`o_hidefortree` = 0  AND (obj.`skbranch` = param_skbranch OR param_skbranch = -1);
	END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "DROP PROCEDURE IF EXISTS `load_reports` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "
			CREATE PROCEDURE `load_reports`(		IN `o_guid` VARCHAR(1000), IN `userights` INT, IN `users_id` VARCHAR(1000), IN `idlanguage` INT, IN `branch` INT )
			BEGIN
				declare idobject BIGINT DEFAULT -1;
				declare param_skbranch INT DEFAULT -1;
				IF (branch IS NULL) THEN
					SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
				ELSE 
					SELECT  `branch` into param_skbranch;
				END IF;

			DROP TEMPORARY TABLE IF EXISTS `r_temp` ;
				CREATE TEMPORARY TABLE `r_temp` (
					`idreport` INT NOT NULL
				)ENGINE=MEMORY;


			DROP TEMPORARY TABLE IF EXISTS `rr_temp` ;
			CREATE TEMPORARY TABLE rr_temp (    
				`idreport` INT NOT NULL,
				PRIMARY KEY (`idreport`)
			)ENGINE=MEMORY;

			SELECT obj.`idobject` into idobject from `objects` as obj where obj.`o_guid` = SUBSTRING(o_guid, 1, 40)  AND  obj.`skbranch` = param_skbranch;

			IF ( idobject > 0 ) THEN
					INSERT INTO r_temp SELECT rep.`idreport` FROM `reports` as rep INNER JOIN `objectsreports` as orl ON orl.`idreport` = rep.`idreport` AND  orl.`skbranch` = param_skbranch  WHERE orl.`idobject` = idobject AND  rep.`skbranch` = param_skbranch AND (ifnull(orl.`idlanguage`,0) = ifnull(idlanguage,0) OR  ifnull(orl.`idlanguage`,0) = 0); 

					IF ( userights <> 0 ) THEN
					INSERT INTO `rr_temp` SELECT `idreport` FROM `r_temp`; 
						SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 0 );'  );
						PREPARE zxc FROM @query;
						EXECUTE zxc;
				
						SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 1 );'  );
						PREPARE zxc FROM @query;
						EXECUTE zxc;
				
						SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 2 );'  );
						PREPARE zxc FROM @query;
						EXECUTE zxc;
				
					SET @query = CONCAT('INSERT IGNORE INTO `rr_temp`	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 (',users_id,') and o.o_guid = \"',o_guid,'\" AND o.`skbranch` = ',param_skbranch,'  AND orts.idreport NOT IN (SELECT rr.idreport FROM  `rightsreports` as rr WHERE  rr.`skbranch` = ',param_skbranch,'  AND rr.deny_allow in (0,1,2) AND iduser in (',users_id,'));'  );
						PREPARE zxc FROM @query;
						EXECUTE zxc;
						
						DELETE FROM r_temp  WHERE r_temp.`idreport` NOT IN ( SELECT rr_temp.`idreport` FROM rr_temp );
					END IF;	  
			END IF;	      
			END;	
	
	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 39;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
}
$last = 39;


if ($ver < 40) {
	// update to 40 version

	$query = "	DROP PROCEDURE IF EXISTS `clear_objects` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `clear_objects`(IN i_skbranch INT)
				BEGIN
				DECLARE lft BIGINT;
				DECLARE rgt BIGINT;
				DECLARE depth BIGINT;

				SELECT MIN(o_ileft) into lft FROM objects WHERE skbranch = i_skbranch;
				SELECT o_iright into rgt  FROM objects WHERE o_ileft = lft;
				SELECT (o_iright - o_ileft + 1) into depth FROM objects WHERE o_ileft = lft;
				DELETE FROM objects WHERE o_ileft BETWEEN lft AND rgt;
				UPDATE objects SET o_iright = o_iright - depth WHERE o_iright > rgt;
				UPDATE objects SET o_ileft = o_ileft - depth WHERE o_ileft > lft;
				
				DELETE FROM objects WHERE o_guid = '00000000-0000-0000-0000-000000000000';
				INSERT IGNORE INTO `objects` (`parent_idobject`, `o_ileft`, `o_iright`, `o_depth`, `o_guid`, `o_icon`, `o_datechange`, `o_hasreports`, `o_useinsearch`, `o_hidefortree`, `skbranch` ) VALUES (0, 1, 2, 0, '00000000-0000-0000-0000-000000000000', 0, NOW(), 0, 0, 0, NULL);
			END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 40;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}
$last = 40;

if ($ver < 41) {
	// update to 41 version

	$query = "	DROP PROCEDURE IF EXISTS `load_reports`;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `load_reports`(IN `o_guid` VARCHAR(1000),IN `userights` INT,IN `users_id` VARCHAR(2500),IN `idlanguage` INT,IN `branch` INT )
	BEGIN
		declare idobject BIGINT DEFAULT -1;
		declare param_skbranch INT DEFAULT -1;
		declare param_lang INT DEFAULT -1;
		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;

	   DROP TEMPORARY TABLE IF EXISTS `r_temp` ;
		CREATE TEMPORARY TABLE `r_temp` (
			`idreport` INT NOT NULL,
		`r_guid` VARCHAR(40),
		 PRIMARY KEY (`idreport`)
		)ENGINE=MEMORY;

	   DROP TEMPORARY TABLE IF EXISTS `r_temp_deflng` ;
		CREATE TEMPORARY TABLE `r_temp_deflng` (
			`idreport` INT NOT NULL,
		`r_guid` VARCHAR(40),
		 PRIMARY KEY (`idreport`)
		)ENGINE=MEMORY;

	   DROP TEMPORARY TABLE IF EXISTS `rr_temp` ;
	   CREATE TEMPORARY TABLE rr_temp (    
		`idreport` INT NOT NULL,
		 PRIMARY KEY (`idreport`)
	   )ENGINE=MEMORY;

	   SELECT obj.`idobject` into idobject from `objects` as obj where obj.`o_guid` = SUBSTRING(o_guid, 1, 40)  AND  obj.`skbranch` = param_skbranch;
	   SELECT languages.idlanguage into param_lang FROM languages WHERE main = 1;

	   IF ( idobject > 0 ) THEN
			INSERT INTO r_temp 
				SELECT rep.`idreport`, rep.`r_guid` FROM `reports` as rep INNER JOIN `objectsreports` as orl ON orl.`idreport` = rep.`idreport` AND  orl.`skbranch` = param_skbranch  
				 WHERE orl.`idobject` = idobject AND  rep.`skbranch` = param_skbranch AND (ifnull(orl.`idlanguage`,0) = ifnull(idlanguage,0) OR ifnull(orl.`idlanguage`,0) = 0); 
			INSERT INTO r_temp_deflng 
				SELECT rep.`idreport`, rep.`r_guid` FROM `reports` as rep INNER JOIN `objectsreports` as orl ON orl.`idreport` = rep.`idreport` AND  orl.`skbranch` = param_skbranch  
				 WHERE orl.`idobject` = idobject AND  rep.`skbranch` = param_skbranch AND orl.`idlanguage` = param_lang
				   AND rep.`r_guid` NOT IN (SELECT r_guid FROM r_temp ); 
		INSERT INTO `r_temp` SELECT `idreport`, `r_guid` FROM `r_temp_deflng`; 

			IF ( userights <> 0 ) THEN
			INSERT INTO `rr_temp` SELECT `idreport` FROM `r_temp`; 
				SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 0 );'  );
				PREPARE zxc FROM @query;
				EXECUTE zxc;
		
				SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 1 );'  );
				PREPARE zxc FROM @query;
				EXECUTE zxc;
		
				SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 2 );'  );
				PREPARE zxc FROM @query;
				EXECUTE zxc;
		
			  SET @query = CONCAT('INSERT IGNORE INTO `rr_temp`	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 (',users_id,') and o.o_guid = \'',o_guid,'\' AND o.`skbranch` = ',param_skbranch,'  AND orts.idreport NOT IN (SELECT rr.idreport FROM  `rightsreports` as rr WHERE  rr.`skbranch` = ',param_skbranch,'  AND rr.deny_allow in (0,1,2) AND iduser in (',users_id,'));'  );
				PREPARE zxc FROM @query;
				EXECUTE zxc;
				
				DELETE FROM r_temp  WHERE r_temp.`idreport` NOT IN ( SELECT rr_temp.`idreport` FROM rr_temp );
			END IF;	  
	   END IF;	      
	END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 41;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}
$last = 41;

if ($ver < 42) {
	// update to 42 version

	$query = "	INSERT IGNORE INTO `tables` (`idtable`, `tbl_name`) VALUES ('11', 'pollobject');";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE `tables` SET `tbl_name`='pollobject' WHERE `idtable`= 11;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE `tables` SET `tbl_name`='object.version.fullname' WHERE  `idtable`=1111;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE `tables` SET `tbl_name`='archive.object.version.fullname' WHERE  `idtable`=1114;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE `tables` SET `tbl_name`='archive.report.version.description' WHERE  `idtable`=1104;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE `tables` SET `tbl_name`='archive.object.version.description' WHERE  `idtable`=1103;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE `tables` SET `tbl_name`='report.version.description' WHERE  `idtable`=1102;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "UPDATE `tables` SET `tbl_name`='object.version.description' WHERE  `idtable`=1101;
	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 42;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}
$last = 42;


if ($ver < 43) {
	// update to 43 version

	$query = "	CREATE TABLE `rightsadminpollingobjects` (
					`iduser` INT(11) NOT NULL,
					`skpolltype` INT(11) NOT NULL,
					`skbranch` INT(11) NULL,
					`skproject` INT(11) NULL, 
					`deny_allow` TINYINT(1) NOT NULL,
					PRIMARY KEY (`iduser`, `skpolltype`, `deny_allow`)
				)
				COLLATE='utf8mb4_general_ci'
				ENGINE=InnoDB
	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 43;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}
$last = 43;


if ($ver < 44) {
	// update to 44 version (Task 61466)

	$query = "DROP PROCEDURE IF EXISTS `add_forummessages` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

		$query = "
					
					CREATE PROCEDURE `add_forummessages`(parent_idforummessage INT, o_guid VARCHAR(36), iduser INT, frmm_body LONGTEXT)
					BEGIN
						declare cnt BIGINT DEFAULT null;
						declare parent_iright BIGINT;
						declare parent_depth BIGINT;
						declare param_skbranch INT DEFAULT -1;
						declare calc_parent_idforummessage INT;
						
						SELECT CASE WHEN in_parent_idforummessage = 0 THEN in_parent_idforummessage ELSE parent_idforummessage END into calc_parent_idforummessage FROM `forummessages` WHERE `idforummessage` = in_parent_idforummessage;
						
						IF (branch IS NULL) THEN
							SELECT b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
						ELSE 
							SELECT `branch` into param_skbranch;
						END IF;
						SET @@session.time_zone = \"+00:00\";
						SELECT COUNT(*) into cnt from `forummessages`;
						IF (cnt = 0 ) THEN
							INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_isdelete`, `frmm_ischanged`, `frmm_datechange_tmst`, `skbranch`) 
							VALUES ('0', '0', '00000000-0000-0000-0000-000000000000', '0', '1', '2', '0', 'root', 0, 0, UNIX_TIMESTAMP(NOW()), 0);	
							UPDATE `forummessages` SET `idforummessage` = 0;
						END IF;
							
						IF (CHAR_LENGTH(o_guid) <= 40 AND iduser > 1) THEN
							SELECT `frmm_iright`, `frmm_depth` into parent_iright, parent_depth from `forummessages` as frmm where frmm.`idforummessage` = calc_parent_idforummessage;
							UPDATE forummessages SET `frmm_ileft`=`frmm_ileft`+2,`frmm_iright`=`frmm_iright`+2 where `frmm_ileft`>parent_iright;
							UPDATE forummessages SET `frmm_iright`=`frmm_iright`+2 where `frmm_iright`>=parent_iright AND `frmm_ileft`<parent_iright;
							INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_isdelete`,  `frmm_ischanged`, `frmm_datechange_tmst`, `skbranch`) VALUES (NULL, calc_parent_idforummessage, o_guid, iduser, parent_iright, parent_iright+1, parent_depth+1, frmm_body, 0, 0, UNIX_TIMESTAMP(NOW()), param_skbranch);
						END IF;
					END;
	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 44;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}
$last = 44;

if ($ver < 45) {
	// update to 45 version (fix add_forummessages)

	$query = "DROP PROCEDURE IF EXISTS `add_forummessages` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

		$query = "CREATE PROCEDURE `add_forummessages`( IN `in_parent_idforummessage` INT, IN `o_guid` VARCHAR(40), IN `iduser` INT, IN `frmm_body` LONGTEXT, IN `branch` INT)
			BEGIN
				declare cnt BIGINT DEFAULT null;
				declare parent_iright BIGINT;
				declare parent_depth BIGINT;
				declare param_skbranch INT DEFAULT -1;
				declare calc_parent_idforummessage INT;

				SELECT CASE WHEN parent_idforummessage = 0 THEN in_parent_idforummessage ELSE parent_idforummessage END into calc_parent_idforummessage FROM `forummessages` WHERE `idforummessage` = in_parent_idforummessage;

				IF (branch IS NULL) THEN
					SELECT b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
				ELSE 
					SELECT `branch` into param_skbranch;
				END IF;

				SET @@session.time_zone = '+00:00';
				SELECT COUNT(*) into cnt from `forummessages`;
				IF (cnt = 0 ) THEN
					INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_isdelete`, `frmm_ischanged`, `frmm_datechange_tmst`, `skbranch`) 
					VALUES ('0', '0', '00000000-0000-0000-0000-000000000000', '0', '1', '2', '0', 'root', 0, 0, UNIX_TIMESTAMP(NOW()), 0); 
					UPDATE `forummessages` SET `idforummessage` = 0;
				END IF;

				IF (CHAR_LENGTH(o_guid) <= 40 AND iduser > 1) THEN
					SELECT `frmm_iright`, `frmm_depth` into parent_iright, parent_depth from `forummessages` as frmm where frmm.`idforummessage` = calc_parent_idforummessage;
					UPDATE forummessages SET `frmm_ileft`=`frmm_ileft`+2,`frmm_iright`=`frmm_iright`+2 where `frmm_ileft`>parent_iright;
					UPDATE forummessages SET `frmm_iright`=`frmm_iright`+2 where `frmm_iright`>=parent_iright AND `frmm_ileft`<parent_iright;
					INSERT INTO `forummessages` (`idforummessage`, `parent_idforummessage`, `o_guid`, `iduser`, `frmm_ileft`, `frmm_iright`, `frmm_depth`, `frmm_body`, `frmm_isdelete`,  `frmm_ischanged`, `frmm_datechange_tmst`, `skbranch`) VALUES (NULL, calc_parent_idforummessage, o_guid, iduser, parent_iright, parent_iright+1, parent_depth+1, frmm_body, 0, 0, UNIX_TIMESTAMP(NOW()), param_skbranch);
				END IF;
			END;
	";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 45;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}
$last = 45;


if ($ver < 20200629) {
	// update to 46 version 

	$query = "INSERT IGNORE INTO `tables` VALUES (2111, 'report.version.fullname'), (2114, 'archive.report.version.fullname');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20200629;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 20200707){//Вернул часть исправлений STU
	$query = "ALTER TABLE `avgreportdata` CHANGE `o_guid` `o_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `avgreportdata` CHANGE `r_guid` `r_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `forummessages` CHANGE `o_guid` `o_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `links` CHANGE `lnk_guid` `lnk_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objects` CHANGE `o_guid` `o_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objects` CHANGE `o_ver` `o_ver` varchar(800) NOT NULL DEFAULT ' ';";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `personallinks` CHANGE `o_guid` `o_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `personallinks` CHANGE `r_guid` `r_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportdata` CHANGE `o_guid` `o_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportdata` CHANGE `r_guid` `r_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reports` CHANGE `r_guid` `r_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportsusersquery` CHANGE `o_guid` `o_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportsusersquery` CHANGE `r_guid` `r_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `sections` CHANGE `sct_guid` `sct_guid` varchar(40) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `users` CHANGE `user_email` `user_email` varchar(256) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE forummessages CHANGE frmm_body frmm_body LONGTEXT;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reportindex` CHANGE `body` `body` LONGTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `reports` SET idlanguage=1049 WHERE idlanguage IS NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "ALTER TABLE `reports` MODIFY idlanguage INT(11) NOT NULL;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "ALTER TABLE `reports` ADD UNIQUE (`r_guid`, `idlanguage`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP INDEX r_guid ON reports;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reports` ADD UNIQUE (`r_guid`, `idlanguage`, `skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "SHOW COLUMNS FROM  portal like 'sessionkey'";
	$resarr = array();
    $result = $cn->query($query);
    if ($result) {
            while ($row = $result->fetch_assoc()) {
                    array_push($resarr, $row);
            }
    }
	$columnExists = count($resarr) > 0;

	if (!$columnExists) {
		$query = "ALTER TABLE portal ADD `sessionkey` varchar(36) NOT NULL;";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
		
		$query = "ALTER TABLE `portal` MODIFY `guid` varchar(40) NOT NULL DEFAULT '-';";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
		
		$query = "TRUNCATE `portal`;";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

		$query = "INSERT INTO `portal` (`guid`, `sessionkey`) VALUES (uuid( ), uuid( ));";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	}



	$query = "SELECT `INDEX_NAME`  FROM `information_schema`.`STATISTICS` WHERE TABLE_NAME = 'rightsobjects' AND INDEX_NAME <> 'PRIMARY' AND TABLE_SCHEMA = (SELECT DATABASE()) AND COLUMN_NAME='idobject';";
	$resarr = array();
    $result = $cn->query($query);
    if ($result) {
            while ($row = $result->fetch_assoc()) {
                    array_push($resarr, $row['INDEX_NAME']);
            }
    }
	for ($i=0; $i<sizeof($resarr); $i++){
		$query = "DROP INDEX `".$resarr[$i]."` ON `rightsobjects`";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	}
	
	if (sizeof($resarr)>0){
		$query = "ALTER TABLE `rightsobjects` ADD INDEX (`idobject`);";
		if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	}
	
	$query = "UPDATE `version` SET `version` = 20200707;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 20200709) {
	// update to 20200709 version 

	$query = "ALTER TABLE `polltypes`
					ADD COLUMN `AllowToChangeAnswer` TINYINT(4) NULL DEFAULT NULL AFTER `AllowComment`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE TABLE `pollfinishdate` (
					`skpolltype` INT(11) NOT NULL,
					`skbranch` INT(11) NOT NULL,
					`skproject` INT(11) NULL DEFAULT NULL,
					`finishdate` DATE NOT NULL,
					UNIQUE INDEX indxu (	`skpolltype`, `skbranch`, `skproject`, `finishdate` )
				)ENGINE=InnoDB;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20200709;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 20200712) {
	// update to 20200712 version 
	$query = "DROP PROCEDURE IF EXISTS `load_reports`; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE PROCEDURE `load_reports`(
					IN `o_guid` VARCHAR(2500),
					IN `userights` INT,
					IN `users_id` VARCHAR(1000),
					IN `idlang` INT,
					IN `branch` INT 
				)
				LANGUAGE SQL
				NOT DETERMINISTIC
				CONTAINS SQL
				SQL SECURITY DEFINER
				COMMENT ''
				BEGIN
						declare idobject BIGINT DEFAULT -1;
						declare param_skbranch INT DEFAULT -1;
						IF (branch IS NULL) THEN
							SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
						ELSE 
							SELECT  `branch` into param_skbranch;
						END IF;
					
					DROP TEMPORARY TABLE IF EXISTS `r_temp` ;
						CREATE TEMPORARY TABLE `r_temp` (
							`idreport` INT NOT NULL,
						`r_guid` VARCHAR(40) ,
						PRIMARY KEY (`idreport`)
						)ENGINE=MEMORY COLLATE = utf8mb4_general_ci;
					
					DROP TEMPORARY TABLE IF EXISTS `r_temp_deflng` ;
						CREATE TEMPORARY TABLE `r_temp_deflng` (
							`idreport` INT NOT NULL,
						`r_guid` VARCHAR(40),
						PRIMARY KEY (`idreport`)
						)ENGINE=MEMORY COLLATE = utf8mb4_general_ci;
					
					DROP TEMPORARY TABLE IF EXISTS `rr_temp` ;
					CREATE TEMPORARY TABLE rr_temp (    
						`idreport` INT NOT NULL,
						PRIMARY KEY (`idreport`)
					)ENGINE=MEMORY;
					
					SELECT obj.`idobject` into idobject from `objects` as obj where obj.`o_guid` = SUBSTRING(o_guid, 1, 40)  AND  obj.`skbranch` = param_skbranch;
					
					IF ( idobject > 0 ) THEN
							INSERT INTO r_temp 
								SELECT rep.`idreport`, rep.`r_guid` FROM `reports` as rep INNER JOIN `objectsreports` as orl ON orl.`idreport` = rep.`idreport` AND  orl.`skbranch` = param_skbranch  
								WHERE orl.`idobject` = idobject AND  rep.`skbranch` = param_skbranch AND (ifnull(orl.`idlanguage`,0) = ifnull(idlang,0) OR ifnull(orl.`idlanguage`,0) = 0); 
							INSERT INTO r_temp_deflng 
								SELECT rep.`idreport`, rep.`r_guid` FROM `reports` as rep INNER JOIN `objectsreports` as orl ON orl.`idreport` = rep.`idreport` AND  orl.`skbranch` = param_skbranch  
								WHERE orl.`idobject` = idobject AND  rep.`skbranch` = param_skbranch AND orl.`idlanguage` = (SELECT `idlanguage` FROM languages WHERE main = 1) 
									AND rep.`r_guid` COLLATE utf8mb4_general_ci NOT IN (SELECT r_guid COLLATE utf8mb4_general_ci FROM r_temp ); 
							INSERT INTO `r_temp` SELECT `idreport`, `r_guid` FROM `r_temp_deflng`; 
					
							IF ( userights <> 0 ) THEN
							INSERT INTO `rr_temp` SELECT `idreport` FROM `r_temp`; 
								SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 0 );'  );
								PREPARE zxc FROM @query;
								EXECUTE zxc;
						
								SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 1 );'  );
								PREPARE zxc FROM @query;
								EXECUTE zxc;
						
								SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 2 );'  );
								PREPARE zxc FROM @query;
								EXECUTE zxc;
						
								SET @query = CONCAT('INSERT IGNORE INTO `rr_temp`	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 (',users_id,') and o.o_guid = \"',o_guid,'\" AND o.`skbranch` = ',param_skbranch,'  AND orts.idreport NOT IN (SELECT rr.idreport FROM  `rightsreports` as rr WHERE  rr.`skbranch` = ',param_skbranch,'  AND rr.deny_allow in (0,1,2) AND iduser in (',users_id,'));'  );
								PREPARE zxc FROM @query;
								EXECUTE zxc;
								
								DELETE FROM r_temp  WHERE r_temp.`idreport` NOT IN ( SELECT rr_temp.`idreport` FROM rr_temp );
							END IF;	  
					END IF;	      
					END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20200712;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 20200724) {
	// update to 20200724 version 
	$query = "DROP PROCEDURE IF EXISTS `clear_objects`; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE objects SET o_ileft = 0, o_iright = 0 where o_guid = '00000000-0000-0000-0000-000000000000'; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `add_objects` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
				CREATE PROCEDURE `add_objects`(
					IN `parent_guid` CHAR(40),
					IN `guid` CHAR(40),
					IN `icon` INT,
					IN `datechange` DATETIME,
					IN `ver` VARCHAR(800),
					IN `datever` DATE,
					IN `statever` INT,
					IN `hasreports` TINYINT,
					IN `useinsearch` TINYINT,
					IN `hidefortree` TINYINT,
					IN `branchid` VARCHAR(50)
				
				)
				LANGUAGE SQL
				NOT DETERMINISTIC
				CONTAINS SQL
				SQL SECURITY DEFINER
				COMMENT ''
				BEGIN
				declare parent_iright BIGINT DEFAULT null;
				declare parent_id BIGINT DEFAULT null;
				declare parent_depth BIGINT DEFAULT null;
				declare parent_skbranch INT DEFAULT null;
					SELECT `skbranch` into parent_skbranch FROM branches WHERE idbranch = branchid;
					IF(NOT EXISTS( SELECT 1 FROM `objects` WHERE `o_guid` = `guid` AND skbranch = parent_skbranch )) THEN
						SELECT `o_iright`, `o_depth`, `idobject` into parent_iright, parent_depth, parent_id from objects where o_guid=parent_guid AND (skbranch = parent_skbranch OR parent_guid = '00000000-0000-0000-0000-000000000000');
						IF ( parent_id IS NOT null ) THEN	
							UPDATE objects SET `o_ileft`=`o_ileft`+2,`o_iright`=`o_iright`+2 where `o_ileft`>parent_iright and o_guid <> '00000000-0000-0000-0000-000000000000';
							UPDATE objects SET `o_iright`=`o_iright`+2 where `o_iright`>=parent_iright AND `o_ileft`<parent_iright and o_guid <> '00000000-0000-0000-0000-000000000000';
							INSERT INTO `objects` (`parent_idobject`, `o_ileft`, `o_iright`, `o_depth`, `o_guid`, `o_icon`, `o_datechange`, `o_ver` , `o_datever` , `o_statever`, `o_hasreports`, `o_useinsearch`, `o_hidefortree`, `skbranch` ) 
									VALUES (parent_id, (CASE WHEN parent_iright = 0 THEN 1 ELSE parent_iright END) , (CASE WHEN parent_iright = 0 THEN 2 ELSE parent_iright+1 END),  (CASE WHEN parent_depth = 0 THEN 1 ELSE parent_depth + 1 END), guid, icon, datechange, ver , datever , statever, hasreports, useinsearch, hidefortree, parent_skbranch );
						END IF;	      
					END IF;	      
				END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20200724;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 20200727) {
	// update to 20200727 version 

	$query = "ALTER TABLE `pollingobjectsarchive`
					DROP INDEX `objectversion`,
					ADD UNIQUE INDEX `objectversionhash` (`objectversionhash`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20200727;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 20200728) {
	// update to 20200728 version 

	$query = "INSERT IGNORE INTO `objects` (`parent_idobject`, `o_ileft`, `o_iright`, `o_depth`, `o_guid`, `o_icon`, `o_datechange`, `o_hasreports`, `o_useinsearch`, `o_hidefortree`) 
				SELECT '0', '0', '0', '0', '00000000-0000-0000-0000-000000000000', '0', '1900-01-01 01:01:01', '0', '0', '0' 
				WHERE NOT EXISTS (SELECT 1 FROM `objects` WHERE `o_guid` = '00000000-0000-0000-0000-000000000000');
			";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE objects SET o_ileft = 0, o_iright = 0 where o_guid = '00000000-0000-0000-0000-000000000000'; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `add_objects` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
				CREATE PROCEDURE `add_objects`(
					IN `parent_guid` CHAR(40),
					IN `guid` CHAR(40),
					IN `icon` INT,
					IN `datechange` DATETIME,
					IN `ver` VARCHAR(800),
					IN `datever` DATE,
					IN `statever` INT,
					IN `hasreports` TINYINT,
					IN `useinsearch` TINYINT,
					IN `hidefortree` TINYINT,
					IN `branchid` VARCHAR(50)
				
				)
				LANGUAGE SQL
				NOT DETERMINISTIC
				CONTAINS SQL
				SQL SECURITY DEFINER
				COMMENT ''
				BEGIN
				declare parent_iright BIGINT DEFAULT null;
				declare parent_id BIGINT DEFAULT null;
				declare parent_depth BIGINT DEFAULT null;
				declare parent_skbranch INT DEFAULT null;
					SELECT `skbranch` into parent_skbranch FROM branches WHERE idbranch = branchid;
					IF(NOT EXISTS( SELECT 1 FROM `objects` WHERE `o_guid` = `guid` AND skbranch = parent_skbranch )) THEN
						SELECT `o_iright`, `o_depth`, `idobject` into parent_iright, parent_depth, parent_id from objects where o_guid=parent_guid AND (skbranch = parent_skbranch OR parent_guid = '00000000-0000-0000-0000-000000000000');
						IF ( parent_id IS NOT null ) THEN	
							UPDATE objects SET `o_ileft`=`o_ileft`+2,`o_iright`=`o_iright`+2 where `o_ileft`>parent_iright and o_guid <> '00000000-0000-0000-0000-000000000000';
							UPDATE objects SET `o_iright`=`o_iright`+2 where `o_iright`>=parent_iright AND `o_ileft`<parent_iright and o_guid <> '00000000-0000-0000-0000-000000000000';
							INSERT INTO `objects` (`parent_idobject`, `o_ileft`, `o_iright`, `o_depth`, `o_guid`, `o_icon`, `o_datechange`, `o_ver` , `o_datever` , `o_statever`, `o_hasreports`, `o_useinsearch`, `o_hidefortree`, `skbranch` ) 
									VALUES (parent_id, (CASE WHEN IFNULL(parent_iright,0) = 0 THEN 1 ELSE parent_iright END) , (CASE WHEN IFNULL(parent_iright,0) = 0 THEN 2 ELSE parent_iright+1 END),  (CASE WHEN parent_depth = 0 THEN 1 ELSE parent_depth + 1 END), guid, icon, datechange, ver , datever , statever, hasreports, useinsearch, hidefortree, parent_skbranch );
						END IF;	      
					END IF;	      
				END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20200728;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 20200730) {
	// update to 20200730 version 

	$query = "DROP PROCEDURE IF EXISTS `load_objectsAdmin` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "	CREATE PROCEDURE `load_objectsAdmin`(
					IN `parent_idobject` BIGINT  
				)
				LANGUAGE SQL
				NOT DETERMINISTIC
				CONTAINS SQL
				SQL SECURITY DEFINER
				COMMENT ''
				BEGIN
					declare root_parent_idobject BIGINT;
					DROP TEMPORARY TABLE IF EXISTS `o_temp` ;
					CREATE TEMPORARY TABLE o_temp (	
					`idobject` BIGINT NOT NULL,
					`parent_idobject` BIGINT NOT NULL,
					PRIMARY KEY (`idobject`)
					)ENGINE=MEMORY;
				
					CREATE TEMPORARY TABLE or_temp (    
					`idobject` BIGINT NOT NULL,
					PRIMARY KEY (`idobject`)
					)ENGINE=MEMORY;
				
					DROP TEMPORARY TABLE IF EXISTS `o_temp_clone` ;
					CREATE TEMPORARY TABLE o_temp_clone (	
					`idobject` BIGINT NOT NULL,
					`parent_idobject` BIGINT NOT NULL,
					PRIMARY KEY (`idobject`)
					)ENGINE=MEMORY;
				
					DROP TEMPORARY TABLE IF EXISTS `or_temp_clone` ;
					CREATE TEMPORARY TABLE or_temp_clone (	
					`idobject` BIGINT NOT NULL,
					PRIMARY KEY (`idobject`)
					)ENGINE=MEMORY;
				
				IF ( parent_idobject = 0 ) THEN
					SELECT obj.`idobject` into root_parent_idobject from `objects` as obj where obj.`o_guid` = '00000000-0000-0000-0000-000000000000';
						INSERT INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`idobject` <> root_parent_idobject AND ((o_iright - o_ileft) > 1);
						INSERT INTO `o_temp_clone` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`idobject` <> root_parent_idobject AND ((o_iright - o_ileft) > 1);
						DELETE FROM `o_temp` WHERE `o_temp`.`parent_idobject` IN ( SELECT `o_temp_clone`.`idobject` FROM `o_temp_clone` );
				ELSE
						INSERT INTO `o_temp` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`parent_idobject` = parent_idobject AND ((o_iright - o_ileft) > 1);
				END IF;	      
				
				END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20200730;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 20200808) {
	// update to 20200808 version 

	$query = "DROP TABLE IF EXISTS `fullfolders`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
			CREATE TABLE `fullfolders` (
				`idobject` BIGINT NOT NULL,
				`idlanguage` INT NOT NULL,
				`skbranch` INT NOT NULL,
				`folder` VARCHAR(2500)  COLLATE utf8mb4_unicode_ci NOT NULL,
				PRIMARY KEY (`idobject`, `idlanguage`)
			)ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
			";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE INDEX ix1 ON 	`fullfolders`(`skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "UPDATE `version` SET `version` = 20200808;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}

if ($ver < 20200810) {
	// update to 20200810 version 

	$query = "UPDATE objects SET o_ileft = 0, o_iright = 0, o_depth = 0, parent_idobject = 0, skbranch = null where o_guid = '00000000-0000-0000-0000-000000000000'; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20200810;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 20200812) {
	// update to 20200812 version 

	$query = "DROP PROCEDURE IF EXISTS `load_objectpath` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "	CREATE PROCEDURE `load_objectpath`(
						IN `idobject` BIGINT,
						IN `userights` INT,
						IN `users_id` VARCHAR(1000),
						IN `branch` INT
					)
					LANGUAGE SQL
					NOT DETERMINISTIC
					CONTAINS SQL
					SQL SECURITY DEFINER
					COMMENT ''
					BEGIN
							declare parent_idobject BIGINT DEFAULT idobject;
							declare param_skbranch INT DEFAULT -1;
					
							IF (branch IS NULL) THEN
								SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
							ELSE 
								SELECT  `branch` into param_skbranch;
							END IF;
					
							DROP TEMPORARY TABLE IF EXISTS `o_temp_tree` ;
							CREATE TEMPORARY TABLE o_temp_tree (	
								`idpobject` BIGINT NOT NULL,
								`parent_idobject` BIGINT NOT NULL,
								`o_ileft` BIGINT NOT NULL,
								PRIMARY KEY (`idpobject`)
							)ENGINE=MEMORY;
							
						IF ( userights = 0 ) THEN
							WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0  ) DO	
								INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`), obj.`o_ileft` FROM `objects` as obj WHERE obj.`idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND ( obj.`skbranch` = param_skbranch OR obj.`skbranch` IS NULL);
								SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `objects` as obj where obj.`idobject` = parent_idobject AND ( obj.`skbranch` = param_skbranch OR obj.`skbranch` IS NULL);
							END WHILE;
						ELSE
							CALL createtree(users_id, param_skbranch);
							WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0 ) DO	
							IF EXISTS (SELECT 1 FROM `chkrt_o_temp` as obj WHERE obj.`idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND ( obj.`skbranch` = param_skbranch OR obj.`skbranch` IS NULL)) THEN
									INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`), obj.`o_ileft` FROM `chkrt_o_temp` as obj WHERE ( obj.`skbranch` = param_skbranch OR obj.`skbranch` IS NULL) AND obj.`parent_idobject` <> 0;
								SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `chkrt_o_temp` as obj where ( obj.`skbranch` = param_skbranch OR obj.`skbranch` IS NULL);
								ELSE
									SELECT 0 into parent_idobject;
								END IF;	
							END WHILE;
						END IF;
						END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `load_objecttree` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "	CREATE PROCEDURE `load_objecttree`(
						IN `idobject` BIGINT,
						IN `userights` INT,
						IN `users_id` VARCHAR(1000),
						IN `branch` INT 
					)
					LANGUAGE SQL
					NOT DETERMINISTIC
					CONTAINS SQL
					SQL SECURITY DEFINER
					COMMENT ''
					BEGIN
							declare parent_idobject BIGINT DEFAULT idobject;
							declare param_skbranch INT DEFAULT -1;
							IF (branch IS NULL) THEN
								SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
							ELSE 
								SELECT  `branch` into param_skbranch;
							END IF;
					
							DROP TEMPORARY TABLE IF EXISTS `o_temp_tree` ;
							CREATE TEMPORARY TABLE o_temp_tree (	
							`idpobject` BIGINT NOT NULL,
							`parent_idobject` BIGINT NOT NULL,
							PRIMARY KEY (`idpobject`)
							)ENGINE=MEMORY;
							
						IF ( userights = 0 ) THEN
							WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0) DO	
								SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `objects` as obj where obj.`idobject` = parent_idobject AND ( obj.`skbranch` = param_skbranch OR obj.`skbranch` IS NULL);
								INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, obj.`parent_idobject` FROM `objects` as obj WHERE obj.`parent_idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND obj.`skbranch` = param_skbranch AND `o_hidefortree` = 0;
							END WHILE;
						ELSE
							CALL createtree(users_id, param_skbranch);
							WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0 ) DO	
								IF EXISTS (SELECT 1 from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject) THEN
									SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject AND ( obj.`skbranch` = param_skbranch OR obj.`skbranch` IS NULL);
									INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, obj.`parent_idobject` FROM `chkrt_o_temp` as obj WHERE obj.`parent_idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND obj.`skbranch` = param_skbranch;
								ELSE
									SELECT 0 into parent_idobject;
								END IF;	    
							END WHILE;
						END IF;
					
						CALL load_objects(0, userights, users_id, param_skbranch);
						END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20200812;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 20200822) {
	// update to 20200822 version 

	$query = "ALTER TABLE `useranswers`
				ADD COLUMN `skpollingobject` INT NOT NULL AFTER `idpollingobject`,
				ADD COLUMN `skpolltype` INT NOT NULL AFTER `idpolltype`,
				ADD COLUMN `iduser` INT NOT NULL AFTER `user_hash`,
				ADD INDEX `skpollingobject` (`skpollingobject`),
				ADD INDEX `skpolltype` (`skpolltype`),
				ADD INDEX `iduser` (`iduser`); 			";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `useranswers`
				ADD INDEX `idpollingobject` (`idpollingobject`),
				ADD INDEX `idpolltype` (`idpolltype`),
				ADD INDEX `user_hash` (`user_hash`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `useranswers`
			ADD COLUMN `hasanswer` TINYINT NOT NULL DEFAULT '0' AFTER `idpollingobjectstatus`;
	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `pollingobjects`
				ADD COLUMN `idobject` BIGINT NOT NULL AFTER `o_guid`,
				ADD INDEX `idobject` (`idobject`),
				ADD INDEX `o_guid` (`o_guid`),
				ADD INDEX `r_guid` (`r_guid`),
				ADD INDEX `objectversionhash` (`objectversionhash`);			";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `rightsobjects`
				ADD INDEX `deny_allow` (`deny_allow`),
				ADD INDEX `iduser` (`iduser`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `rightspollingobjects`
				ADD INDEX `deny_allow` (`deny_allow`),
				ADD INDEX `iduser` (`iduser`),
				ADD INDEX `skpollingobject` (`skpollingobject`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `resourcefromtables`
				ADD INDEX `idtable` (`idtable`),
				ADD INDEX `idrecord` (`idrecord`),
				ADD INDEX `skbranch` (`skbranch`),
				ADD INDEX `idlanguage` (`idlanguage`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `forummessagessaw`
				ADD INDEX `iduser` (`iduser`),
				ADD INDEX `frmsw_sessionhash` (`frmsw_sessionhash`),
				ADD INDEX `skbranch` (`skbranch`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `forummessages`
				ADD INDEX `iduser` (`iduser`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `reports`
				ADD INDEX `r_guid_only` (`r_guid`);
			";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objects`
				ADD INDEX `o_guid_only` (`o_guid`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "ALTER TABLE `objectsreports`
				ADD INDEX `idobject` (`idobject`);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE pollingobjects as po
		INNER JOIN objects as o ON po.o_guid = o.o_guid AND po.skbranch = o.skbranch
		SET po.idobject = o.idobject;
		";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE useranswers as ua
				INNER JOIN  useranswersvalues as uav ON uav.skpollingobject = ua.skpollingobject AND uav.skpolltype = ua.skpolltype AND uav.iduser = ua.iduser
				SET ua.hasanswer = CASE WHEN uav.uav_value != 0 THEN 1 ELSE 0 END;
		";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE useranswers as ua
		INNER JOIN pollingobjects as po ON po.idpollingobject = ua.idpollingobject
		SET ua.skpollingobject = po.skpollingobject;
		";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "UPDATE useranswers as ua
		INNER JOIN polltypes as pt ON pt.idpolltype = ua.idpolltype
		SET ua.skpolltype = pt.skpolltype;
		";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "UPDATE useranswers as ua
		INNER JOIN users as u ON u.user_hash = ua.user_hash
		SET ua.iduser = u.iduser;
		";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20200822;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 20200923) {
	// update to 20200923 version 

	$query = "ALTER TABLE `fullfolders`
				DROP PRIMARY KEY,
				ADD PRIMARY KEY (`idobject`, `idlanguage`, `skbranch`);
		";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20200923;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 20201118) {
	// update to 20201118 version 
	$query = "DROP PROCEDURE IF EXISTS `load_reports`; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE PROCEDURE `load_reports`(
					IN `o_guid` VARCHAR(2500),
					IN `userights` INT,
					IN `users_id` VARCHAR(1000),
					IN `idlang` INT,
					IN `branch` INT 
				)
				LANGUAGE SQL
				NOT DETERMINISTIC
				CONTAINS SQL
				SQL SECURITY DEFINER
				COMMENT ''
				BEGIN
						declare idobject BIGINT DEFAULT -1;
						declare param_skbranch INT DEFAULT -1;
						IF (branch IS NULL) THEN
							SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
						ELSE 
							SELECT  `branch` into param_skbranch;
						END IF;
					
					DROP TEMPORARY TABLE IF EXISTS `r_temp` ;
						CREATE TEMPORARY TABLE `r_temp` (
							`idreport` INT NOT NULL,
						`r_guid` VARCHAR(40) ,
						PRIMARY KEY (`idreport`)
						)ENGINE=MEMORY COLLATE = utf8mb4_general_ci;
					
					DROP TEMPORARY TABLE IF EXISTS `r_temp_deflng` ;
						CREATE TEMPORARY TABLE `r_temp_deflng` (
							`idreport` INT NOT NULL,
						`r_guid` VARCHAR(40),
						PRIMARY KEY (`idreport`)
						)ENGINE=MEMORY COLLATE = utf8mb4_general_ci;
					
					DROP TEMPORARY TABLE IF EXISTS `rr_temp` ;
					CREATE TEMPORARY TABLE rr_temp (    
						`idreport` INT NOT NULL,
						PRIMARY KEY (`idreport`)
					)ENGINE=MEMORY;
					
					SELECT obj.`idobject` into idobject from `objects` as obj where obj.`o_guid` = SUBSTRING(o_guid, 1, 40)  AND  obj.`skbranch` = param_skbranch;
					
					IF ( idobject > 0 ) THEN
							INSERT INTO r_temp 
								SELECT rep.`idreport`, rep.`r_guid` FROM `reports` as rep INNER JOIN `objectsreports` as orl ON orl.`idreport` = rep.`idreport` AND  orl.`skbranch` = param_skbranch  
								WHERE orl.`idobject` = idobject AND  rep.`skbranch` = param_skbranch AND (ifnull(orl.`idlanguage`,0) = ifnull(idlang,0) OR ifnull(orl.`idlanguage`,0) = 0); 
							INSERT INTO r_temp_deflng 
								SELECT rep.`idreport`, rep.`r_guid` FROM `reports` as rep INNER JOIN `objectsreports` as orl ON orl.`idreport` = rep.`idreport` AND  orl.`skbranch` = param_skbranch  
								WHERE orl.`idobject` = idobject AND  rep.`skbranch` = param_skbranch AND orl.`idlanguage` = (SELECT `idlanguage` FROM languages WHERE main = 1) 
									AND rep.`r_guid` COLLATE utf8mb4_general_ci NOT IN (SELECT r_guid COLLATE utf8mb4_general_ci FROM r_temp ); 
							INSERT INTO `r_temp` SELECT `idreport`, `r_guid` FROM `r_temp_deflng`; 
					
							IF ( userights <> 0 ) THEN
							INSERT INTO `rr_temp` SELECT `idreport` FROM `r_temp`; 
								SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 0 );'  );
								PREPARE zxc FROM @query;
								EXECUTE zxc;
						
								SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 1 );'  );
								PREPARE zxc FROM @query;
								EXECUTE zxc;
						
								SET @query = CONCAT('DELETE FROM rr_temp WHERE rr_temp.`idreport` NOT IN ( SELECT rr.`idreport` FROM `rightsreports` as rr INNER JOIN  `r_temp` as rt ON rt.`idreport` = rr.`idreport` WHERE  rr.`skbranch` = ',param_skbranch,' AND rr.`iduser` IN (',users_id,') AND rr.`deny_allow` = 2 );'  );
								PREPARE zxc FROM @query;
								EXECUTE zxc;
						
								SET @query = CONCAT('INSERT IGNORE INTO `rr_temp`	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 (',users_id,') and o.o_guid = \"',o_guid,'\" AND o.`skbranch` = ',param_skbranch,'  AND orts.idreport NOT IN (SELECT rr.idreport FROM  `rightsreports` as rr WHERE  rr.`skbranch` = ',param_skbranch,'  AND rr.deny_allow = 0 AND iduser in (',users_id,'));'  );
								PREPARE zxc FROM @query;
								EXECUTE zxc;
								
								DELETE FROM r_temp  WHERE r_temp.`idreport` NOT IN ( SELECT rr_temp.`idreport` FROM rr_temp );
							END IF;	  
					END IF;	      
					END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}


	$query = "
			DROP PROCEDURE IF EXISTS `createtree` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `createtree`(IN `users_id` VARCHAR(2500), IN `branch` INT)
	BEGIN

		DECLARE l_idobject BIGINT;
		DECLARE l_parent_idobject BIGINT;
		DECLARE l_o_ileft BIGINT;
		DECLARE l_o_iright BIGINT;
		DECLARE done INT default 0;
		declare param_skbranch INT DEFAULT -1;

		DECLARE cursor_roots Cursor for 
			SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `o_useinsearch` = 1;

		DECLARE cursor_tree Cursor for 
			SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp_cut WHERE `parent_idobject` = 0 ORDER BY o_ileft DESC;

		DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

		IF (branch IS NULL) THEN
			SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
		ELSE 
			SELECT  `branch` into param_skbranch;
		END IF;

		DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp` ;
		CREATE TEMPORARY TABLE chkrt_o_temp (	
		`idobject` BIGINT NOT NULL,
		`parent_idobject` BIGINT NOT NULL,
		`ad0` INT NOT NULL,
		`ad1` INT NOT NULL,
		`ad2` INT NOT NULL,
		`root` INT NOT NULL,
		`o_ileft` INT NOT NULL,
		`o_iright` INT NOT NULL,
		`o_useinsearch` INT NOT NULL,
		`skbranch` INT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;

		DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_cut` ;
		CREATE TEMPORARY TABLE chkrt_o_temp_cut (	
		`idobject` BIGINT NOT NULL,
		`parent_idobject` BIGINT NOT NULL,
		`o_ileft` BIGINT NOT NULL,
		`o_iright` BIGINT NOT NULL,
		 PRIMARY KEY (`idobject`)
		)ENGINE=MEMORY;

		INSERT IGNORE INTO `chkrt_o_temp` 
			SELECT `idobject`, `parent_idobject`, 0, 0, 0, 1, `o_ileft`, `o_iright`, `o_useinsearch`, `skbranch`  FROM `objects` WHERE `parent_idobject` <> 0 AND `o_hidefortree` = 0 AND `skbranch` = param_skbranch AND `idobject`;

		CREATE INDEX ix_pid ON chkrt_o_temp (parent_idobject);	

		DROP TEMPORARY TABLE IF EXISTS `t_rightsobjects` ;
		CREATE TEMPORARY TABLE `t_rightsobjects` (
			`iduser` INT(11) NOT NULL,
			`idobject` BIGINT NOT NULL,
			`deny_allow` TINYINT(1) NOT NULL,
			`skbranch` INT NOT NULL
		)ENGINE=MEMORY;

		SET @query = CONCAT('INSERT IGNORE INTO `t_rightsobjects` SELECT `iduser`, `idobject`, `deny_allow`, `skbranch` FROM `rightsobjects` WHERE `iduser` IN (',users_id,') AND `skbranch` = ',param_skbranch,';' );
			PREPARE zxc FROM @query;
			EXECUTE zxc;


		SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad0 = 1 WHERE t_rightsobjects.`deny_allow` = 0 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  );
			PREPARE zxc FROM @query;
			EXECUTE zxc;

		SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad1 = 1 WHERE  t_rightsobjects.`deny_allow` = 1 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  ); 
			PREPARE zxc FROM @query;
			EXECUTE zxc;

		SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad2 = 1 WHERE  t_rightsobjects.`deny_allow` = 2 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  );
			PREPARE zxc FROM @query;
			EXECUTE zxc;

		DELETE FROM chkrt_o_temp WHERE (ad1 < 1 OR ad2 < 1) AND o_useinsearch = 0;

	   DELETE FROM chkrt_o_temp WHERE ad0 = 1 AND o_useinsearch = 0;

	   SET @query = CONCAT('INSERT IGNORE INTO chkrt_o_temp SELECT o.`idobject`, o.`parent_idobject`, 1, 1, 0, 1, o.`o_ileft`, o.`o_iright`, o.`o_useinsearch`, `skbranch`  FROM `objects` as o INNER JOIN  `users` as u ON u.`user_guid` = o.`o_guid` WHERE `parent_idobject` <> 0 AND o.`skbranch` = ',param_skbranch,' AND  o.`idobject` NOT IN (SELECT idobject FROM `rightsobjects` WHERE `deny_allow` = 0 AND `iduser` IN (',users_id,')) AND  `o_hidefortree` = 0 AND u.`iduser` IN (',users_id,') ;'  );
			PREPARE zxc FROM @query;
			EXECUTE zxc;
			
		OPEN cursor_roots;
		WHILE done = 0 DO 
		FETCH cursor_roots INTO l_idobject,l_o_ileft,l_o_iright;
		SELECT COUNT(*) into @c FROM `chkrt_o_temp` WHERE `o_ileft` BETWEEN l_o_ileft AND l_o_iright AND `o_useinsearch` = 0;
		IF (@c = 0) THEN 
			DELETE FROM chkrt_o_temp WHERE idobject = l_idobject;
		END IF;
		END WHILE;
		Close cursor_roots; 


			DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_id` ;
			CREATE TEMPORARY TABLE chkrt_o_temp_id (	
			`idobject` BIGINT NOT NULL,
			PRIMARY KEY (`idobject`)
			)ENGINE=MEMORY;


			INSERT IGNORE INTO `chkrt_o_temp_id` 
				SELECT `idobject` FROM chkrt_o_temp;


		UPDATE chkrt_o_temp RIGHT OUTER JOIN `chkrt_o_temp_id` ON (chkrt_o_temp.parent_idobject = chkrt_o_temp_id.idobject) 
		SET root = 0;
		UPDATE chkrt_o_temp SET parent_idobject = 0 WHERE root = 1;
		INSERT INTO chkrt_o_temp_cut
		SELECT `idobject`, `parent_idobject`,`o_ileft`,`o_iright` FROM chkrt_o_temp;
		
		SET done=0;
		OPEN cursor_tree;
		WHILE done = 0 DO 
			FETCH cursor_tree INTO l_idobject,l_o_ileft,l_o_iright;
			IF( EXISTS( SELECT idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1 )) THEN
				SELECT idobject INTO l_parent_idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1;
				UPDATE `chkrt_o_temp` SET `parent_idobject` = IFNULL(l_parent_idobject,0) WHERE `idobject`= l_idobject;
			ELSE 
				UPDATE `chkrt_o_temp` SET `parent_idobject` = 0 WHERE `idobject`= l_idobject;
			END IF;
		END WHILE;
		Close cursor_tree;      
	END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20201118;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}



if ($ver < 20210115) {
	// update to 20210115 version 
	$query = "
	CREATE TABLE IF NOT EXISTS prepared_tree (	
		`idobject` INT NOT NULL,
		`parent_idobject` INT NOT NULL,
		`ad0` INT NOT NULL,
		`ad1` INT NOT NULL,
		`ad2` INT NOT NULL,
		`root` INT NOT NULL,
		`o_ileft` INT NOT NULL,
		`o_iright` INT NOT NULL,
		`o_useinsearch` INT NOT NULL,
		`skbranch` INT NOT NULL,
		`usersidsarr` VARCHAR(500) NOT NULL,
			PRIMARY KEY (`idobject`, `skbranch`,`usersidsarr`)
		)ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "
			DROP PROCEDURE IF EXISTS `20210115` ;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	$query = "CREATE PROCEDURE `20210115`(IN `users_id` VARCHAR(500), IN `branch` INT)
	BEGIN
			DECLARE l_idobject BIGINT;
			DECLARE l_parent_idobject BIGINT;
			DECLARE l_o_ileft BIGINT;
			DECLARE l_o_iright BIGINT;
			DECLARE done INT default 0;
			DECLARE param_skbranch INT DEFAULT -1;

			DECLARE cursor_roots Cursor for 
				SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp WHERE `o_useinsearch` = 1;

			DECLARE cursor_tree Cursor for 
				SELECT `idobject`, `o_ileft`, `o_iright`  FROM chkrt_o_temp_cut WHERE `parent_idobject` = 0 ORDER BY o_ileft DESC;

			DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

			IF (branch IS NULL) THEN
				SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
			ELSE 
				SELECT  `branch` into param_skbranch;
			END IF;



			DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp` ;
			CREATE TEMPORARY TABLE chkrt_o_temp (	
				`idobject` BIGINT NOT NULL,
				`parent_idobject` BIGINT NOT NULL,
				`ad0` INT NOT NULL,
				`ad1` INT NOT NULL,
				`ad2` INT NOT NULL,
				`root` INT NOT NULL,
				`o_ileft` INT NOT NULL,
				`o_iright` INT NOT NULL,
				`o_useinsearch` INT NOT NULL,
				`skbranch` INT NOT NULL,
					PRIMARY KEY (`idobject`)
			)ENGINE=MEMORY;


			IF NOT EXISTS (SELECT 1 FROM prepared_tree WHERE `usersidsarr` = users_id AND `skbranch` = branch  LIMIT 1) THEN
					DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_cut` ;
					CREATE TEMPORARY TABLE chkrt_o_temp_cut (	
						`idobject` BIGINT NOT NULL,
						`parent_idobject` BIGINT NOT NULL,
						`o_ileft` BIGINT NOT NULL,
						`o_iright` BIGINT NOT NULL,
							PRIMARY KEY (`idobject`)
					)ENGINE=MEMORY;

					INSERT IGNORE INTO `chkrt_o_temp` 
						SELECT `idobject`, `parent_idobject`, 0, 0, 0, 1, `o_ileft`, `o_iright`, `o_useinsearch`, `skbranch`  FROM `objects` WHERE `parent_idobject` <> 0 AND `o_hidefortree` = 0 AND `skbranch` = param_skbranch AND `idobject`;

					CREATE INDEX ix_pid ON chkrt_o_temp (parent_idobject);	

					DROP TEMPORARY TABLE IF EXISTS `t_rightsobjects` ;
					CREATE TEMPORARY TABLE `t_rightsobjects` (
						`iduser` INT(11) NOT NULL,
						`idobject` BIGINT NOT NULL,
						`deny_allow` TINYINT(1) NOT NULL,
						`skbranch` INT NOT NULL
					)ENGINE=MEMORY;


					SET @query = CONCAT('INSERT IGNORE INTO `t_rightsobjects` SELECT `iduser`, `idobject`, `deny_allow`, `skbranch` FROM `rightsobjects` WHERE `iduser` IN (',users_id,') AND `skbranch` = ',param_skbranch,';' );
						PREPARE zxc FROM @query;
						EXECUTE zxc;


					SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad0 = 1 WHERE t_rightsobjects.`deny_allow` = 0 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  );
						PREPARE zxc FROM @query;
						EXECUTE zxc;

					SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad1 = 1 WHERE  t_rightsobjects.`deny_allow` = 1 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  ); 
						PREPARE zxc FROM @query;
						EXECUTE zxc;

					SET @query = CONCAT('UPDATE chkrt_o_temp INNER JOIN `t_rightsobjects` ON (chkrt_o_temp.idobject = t_rightsobjects.idobject) SET  ad2 = 1 WHERE  t_rightsobjects.`deny_allow` = 2 AND t_rightsobjects.`skbranch` = ',param_skbranch,';'  );
						PREPARE zxc FROM @query;
						EXECUTE zxc;

					DELETE FROM chkrt_o_temp WHERE (ad1 < 1 OR ad2 < 1) AND o_useinsearch = 0;
					DELETE FROM chkrt_o_temp WHERE ad0 = 1 AND o_useinsearch = 0;



					SET @query = CONCAT('INSERT IGNORE INTO chkrt_o_temp SELECT o.`idobject`, o.`parent_idobject`, 1, 1, 0, 1, o.`o_ileft`, o.`o_iright`, o.`o_useinsearch`, `skbranch`  FROM `objects` as o INNER JOIN  `users` as u ON u.`user_guid` = o.`o_guid` WHERE `parent_idobject` <> 0 AND o.`skbranch` = ',param_skbranch,' AND  o.`idobject` NOT IN (SELECT idobject FROM `rightsobjects` WHERE `deny_allow` IN (0,1,2) AND `iduser` IN (',users_id,')) AND  `o_hidefortree` = 0 AND u.`iduser` IN (',users_id,') ;'  );
						PREPARE zxc FROM @query;
						EXECUTE zxc;
					

					OPEN cursor_roots;
					WHILE done = 0 DO 
						FETCH cursor_roots INTO l_idobject,l_o_ileft,l_o_iright;
						SELECT COUNT(*) into @c FROM `chkrt_o_temp` WHERE `o_ileft` BETWEEN l_o_ileft AND l_o_iright AND `o_useinsearch` = 0;
						IF (@c = 0) THEN 
							DELETE FROM chkrt_o_temp WHERE idobject = l_idobject;
						END IF;
					END WHILE;

					CLOSE cursor_roots; 

					DROP TEMPORARY TABLE IF EXISTS `chkrt_o_temp_id` ;

					CREATE TEMPORARY TABLE chkrt_o_temp_id (	
						`idobject` BIGINT NOT NULL,
						PRIMARY KEY (`idobject`)
					)ENGINE=MEMORY;


					INSERT IGNORE INTO `chkrt_o_temp_id` 
						SELECT `idobject` FROM chkrt_o_temp;

					UPDATE chkrt_o_temp RIGHT OUTER JOIN `chkrt_o_temp_id` ON (chkrt_o_temp.parent_idobject = chkrt_o_temp_id.idobject) 
					SET root = 0;

					UPDATE chkrt_o_temp SET parent_idobject = 0 WHERE root = 1;

					INSERT INTO chkrt_o_temp_cut
						SELECT `idobject`, `parent_idobject`,`o_ileft`,`o_iright` FROM chkrt_o_temp;

					SET done=0;

					OPEN cursor_tree;
					WHILE done = 0 DO 
						FETCH cursor_tree INTO l_idobject,l_o_ileft,l_o_iright;
						IF( EXISTS( SELECT idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1 )) THEN
							SELECT idobject INTO l_parent_idobject FROM `chkrt_o_temp` WHERE `idobject` <> l_idobject AND l_o_ileft BETWEEN `o_ileft` AND `o_iright` ORDER BY `o_ileft` DESC LIMIT 1;
							UPDATE `chkrt_o_temp` SET `parent_idobject` = IFNULL(l_parent_idobject,0) WHERE `idobject`= l_idobject;
						ELSE 
							UPDATE `chkrt_o_temp` SET `parent_idobject` = 0 WHERE `idobject`= l_idobject;
						END IF;
					END WHILE;

					CLOSE cursor_tree;   
					
					INSERT IGNORE INTO prepared_tree
						SELECT 	`idobject`, `parent_idobject`, `ad0`, `ad1`, `ad2`, `root`, `o_ileft`, `o_iright`, `o_useinsearch`, `skbranch`, users_id FROM `chkrt_o_temp`;
			ELSE 
				INSERT IGNORE INTO `chkrt_o_temp`
					SELECT 	`idobject`, `parent_idobject`, `ad0`, `ad1`, `ad2`, `root`, `o_ileft`, `o_iright`, `o_useinsearch`,`skbranch` FROM prepared_tree WHERE `usersidsarr` = users_id AND `skbranch` = branch;
			END IF;	   
		END;";
    if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20210115;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 20210528) {
	// update to 20210528 version 

	$query = "ALTER TABLE `rightsobjects`
			ADD COLUMN `isCopied` TINYINT NULL DEFAULT '0' AFTER `skbranch`;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}
	
	$query = "INSERT INTO `maitypes` (`idmaitype`, `mt_name`, `mt_description`) VALUES ('1000', 'pollUncompleted', '');";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20210528;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}



if ($ver < 20210924) {
	// update to 20210924 version (Task 70307)

	$query = "DROP PROCEDURE IF EXISTS `load_objectpath` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "	CREATE PROCEDURE `load_objectpath`(
						IN `idobject` BIGINT,
						IN `userights` INT,
						IN `users_id` VARCHAR(1000),
						IN `branch` INT
					)
					LANGUAGE SQL
					NOT DETERMINISTIC
					CONTAINS SQL
					SQL SECURITY DEFINER
					COMMENT ''
					BEGIN
							declare parent_idobject BIGINT DEFAULT idobject;
							declare param_skbranch INT DEFAULT -1;
					
							IF (branch IS NULL) THEN
								SELECT  b.`skbranch` into param_skbranch FROM `branches` as b WHERE b.ismain = 1 LIMIT 1; 
							ELSE 
								SELECT  `branch` into param_skbranch;
							END IF;
					
							DROP TEMPORARY TABLE IF EXISTS `o_temp_tree` ;
							CREATE TEMPORARY TABLE o_temp_tree (	
								`idpobject` BIGINT NOT NULL,
								`parent_idobject` BIGINT NOT NULL,
								`o_ileft` BIGINT NOT NULL,
								PRIMARY KEY (`idpobject`)
							)ENGINE=MEMORY;
							
						IF ( userights = 0 ) THEN
							WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0  ) DO	
								INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`), obj.`o_ileft` FROM `objects` as obj WHERE obj.`idobject` = parent_idobject AND obj.`parent_idobject` <> 0 AND ( obj.`skbranch` = param_skbranch OR obj.`skbranch` IS NULL);
								SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `objects` as obj where obj.`idobject` = parent_idobject AND ( obj.`skbranch` = param_skbranch OR obj.`skbranch` IS NULL);
							END WHILE;
						ELSE
							CALL createtree(users_id, param_skbranch);
							WHILE ( parent_idobject <> 0 AND ISNULL(parent_idobject) = 0 ) DO	
								IF EXISTS (SELECT 1 FROM `chkrt_o_temp` as obj WHERE obj.`idobject` = parent_idobject  AND ( obj.`skbranch` = param_skbranch OR obj.`skbranch` IS NULL)) THEN
									INSERT IGNORE INTO `o_temp_tree` SELECT obj.`idobject`, IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`), obj.`o_ileft` FROM `chkrt_o_temp` as obj WHERE obj.`idobject` = parent_idobject AND ( obj.`skbranch` = param_skbranch OR obj.`skbranch` IS NULL) ;
									SELECT IF(ISNULL(obj.`parent_idobject`) = 1, 0, obj.`parent_idobject`) into parent_idobject from `chkrt_o_temp` as obj where obj.`idobject` = parent_idobject AND ( obj.`skbranch` = param_skbranch OR obj.`skbranch` IS NULL) ;
								ELSE
									SELECT 0 into parent_idobject;
								END IF;	
							END WHILE;
						END IF;
						END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20210924;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}


if ($ver < 20220912) {
	// update to 20220912 version (71970)

  
  $query = "ALTER TABLE `objects`
	  ADD COLUMN `src_guid` VARCHAR(40) NULL DEFAULT NULL AFTER `skbranch`;;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `add_objects` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE PROCEDURE add_objects(
            IN parent_guid CHAR(40),
            IN guid CHAR(40),
            IN icon INT,
            IN datechange DATETIME,
            IN ver VARCHAR(800),
            IN datever DATE,
            IN statever INT,
            IN hasreports TINYINT,
            IN useinsearch TINYINT,
            IN hidefortree TINYINT,
            IN branchid VARCHAR(50),
            IN src_guid CHAR(40)
          
          )
          LANGUAGE SQL
          NOT DETERMINISTIC
          CONTAINS SQL
          SQL SECURITY DEFINER
          COMMENT ''
          BEGIN
          declare parent_iright BIGINT DEFAULT null;
          declare parent_id BIGINT DEFAULT null;
          declare parent_depth BIGINT DEFAULT null;
          declare parent_skbranch INT DEFAULT null;
            SELECT skbranch into parent_skbranch FROM branches WHERE idbranch = branchid;
            IF(NOT EXISTS( SELECT 1 FROM objects WHERE o_guid = guid AND skbranch = parent_skbranch )) THEN
              SELECT o_iright, o_depth, idobject into parent_iright, parent_depth, parent_id from objects where o_guid=parent_guid AND (skbranch = parent_skbranch OR parent_guid = '00000000-0000-0000-0000-000000000000');
              IF ( parent_id IS NOT null ) THEN  
                UPDATE objects SET o_ileft=o_ileft+2,o_iright=o_iright+2 where o_ileft>parent_iright and o_guid <> '00000000-0000-0000-0000-000000000000';
                UPDATE objects SET o_iright=o_iright+2 where o_iright>=parent_iright AND o_ileft<parent_iright and o_guid <> '00000000-0000-0000-0000-000000000000';
                INSERT INTO objects (parent_idobject, o_ileft, o_iright, o_depth, o_guid, o_icon, o_datechange, o_ver , o_datever , o_statever, o_hasreports, o_useinsearch, o_hidefortree, skbranch, src_guid ) 
                    VALUES (parent_id, (CASE WHEN IFNULL(parent_iright,0) = 0 THEN 1 ELSE parent_iright END) , (CASE WHEN IFNULL(parent_iright,0) = 0 THEN 2 ELSE parent_iright+1 END),  (CASE WHEN parent_depth = 0 THEN 1 ELSE parent_depth + 1 END), guid, icon, datechange, ver , datever , statever, hasreports, useinsearch, hidefortree, parent_skbranch, src_guid );
              END IF;        
            END IF;        
          END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20220912;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}




if ($ver < 20231017) {
	// update to 20231017 version (71970)

  
  $query = "ALTER TABLE objects MODIFY o_icon varchar(800);";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE objects SET o_icon=CONCAT('objects/',o_icon,'.png') WHERE o_icon NOT LIKE '%.%';";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "DROP PROCEDURE IF EXISTS `add_objects` ; ";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "CREATE PROCEDURE add_objects(
            IN parent_guid CHAR(40),
            IN guid CHAR(40),
            IN icon VARCHAR(800),
            IN datechange DATETIME,
            IN ver VARCHAR(800),
            IN datever DATE,
            IN statever INT,
            IN hasreports TINYINT,
            IN useinsearch TINYINT,
            IN hidefortree TINYINT,
            IN branchid VARCHAR(50),
            IN src_guid CHAR(40)
          
          )
          LANGUAGE SQL
          NOT DETERMINISTIC
          CONTAINS SQL
          SQL SECURITY DEFINER
          COMMENT ''
          BEGIN
          declare parent_iright BIGINT DEFAULT null;
          declare parent_id BIGINT DEFAULT null;
          declare parent_depth BIGINT DEFAULT null;
          declare parent_skbranch INT DEFAULT null;
            SELECT skbranch into parent_skbranch FROM branches WHERE idbranch = branchid;
            IF(NOT EXISTS( SELECT 1 FROM objects WHERE o_guid = guid AND skbranch = parent_skbranch )) THEN
              SELECT o_iright, o_depth, idobject into parent_iright, parent_depth, parent_id from objects where o_guid=parent_guid AND (skbranch = parent_skbranch OR parent_guid = '00000000-0000-0000-0000-000000000000');
              IF ( parent_id IS NOT null ) THEN  
                UPDATE objects SET o_ileft=o_ileft+2,o_iright=o_iright+2 where o_ileft>parent_iright and o_guid <> '00000000-0000-0000-0000-000000000000';
                UPDATE objects SET o_iright=o_iright+2 where o_iright>=parent_iright AND o_ileft<parent_iright and o_guid <> '00000000-0000-0000-0000-000000000000';
                INSERT INTO objects (parent_idobject, o_ileft, o_iright, o_depth, o_guid, o_icon, o_datechange, o_ver , o_datever , o_statever, o_hasreports, o_useinsearch, o_hidefortree, skbranch, src_guid ) 
                    VALUES (parent_id, (CASE WHEN IFNULL(parent_iright,0) = 0 THEN 1 ELSE parent_iright END) , (CASE WHEN IFNULL(parent_iright,0) = 0 THEN 2 ELSE parent_iright+1 END),  (CASE WHEN parent_depth = 0 THEN 1 ELSE parent_depth + 1 END), guid, icon, datechange, ver , datever , statever, hasreports, useinsearch, hidefortree, parent_skbranch, src_guid );
              END IF;        
            END IF;        
          END;";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	$query = "UPDATE `version` SET `version` = 20231017;	";
	if (!db_runQuery($cn, $query,'updateDB.php')) {logmessage('updateDB.php:('. __LINE__ .')'); die();}

	echo "<hr/>";
	$ver = db_getDBVersion($cn);
	echo "DB update to version ".$ver." ".date('d-m-Y H:i:s');
}



$last = 20231017;

if ($ver == $last) {
	echo "<hr/>";
	echo "DB update completed";
}

if ($ver !== $first){//STU check was updated;
	echo '<br>';
	echo ("DB updated to new version");
}

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