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

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

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

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

function getPrmValueByName($cn, $msg, $name, $default = NULL, $val = 'val'){
	$result = $default;
	if (isset($msg) && isset($msg->prm)){
		$size = sizeof($msg->prm);
		for($j=0; $j<$size; $j++) {
			if ($msg->prm[$j]['name'] == $name) {
				$result = mysqli_real_escape_string($cn,$msg->prm[$j][$val]);
				break;
			}
		}
	}
	return $result;
}

function getLanguageID($lang_short){
	$cn = db_connect();
	$idl = db_getLanguageByShortName($cn, $lang_short, -1, "NULL");
	db_disconnect($cn);
	return $idl; 
}

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

$p_guid ='';
$name='';
$url='';
$rguid='';
$oguid='';
$sguid='';
$icon = 0;
$id = 0;
$pos = 0;
$hasr = 0;
$xml = '';
if (isset($_REQUEST['file'])){
	// читаем xml с данными из файла
	$xml = simplexml_load_file(realpath(dirname(__FILE__).'/../').'/'.$_REQUEST['file']);
} else {
	// пришел пост запрос, читаем xml из него
	if (!isset($HTTP_RAW_POST_DATA))
		$HTTP_RAW_POST_DATA = file_get_contents("php://input");
	//$date = new DateTime();
	//file_put_contents("outputfile.".$date->format('Ymd.His').".xml", $HTTP_RAW_POST_DATA);		
	$xml = simplexml_load_string($HTTP_RAW_POST_DATA);

}
clearResource();
$query = 'SET @@session.time_zone = "+00:00"; ';
$cn = db_connect();
db_prepareSQLBIGSELECT($cn);

$sz = sizeof($xml);
if ($sz >= 1){
	$excludeBranches = db_getExcludeBranchesToImport($cn); //59959
	for($i=0; $i<$sz; $i++) {
		// команда удалить опции языков
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'clearAllowLanguages'){
			db_clearAllowLanguages($cn);
		}
		
		// команда удалить все данные портала
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'clearPortal'){
			db_clearPortal($cn);
		}
		
		// 60080
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'clearBranch'){
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch', '-empty-');
			$skbranch = db_getSKBranch($cn, $idbranch);
			if (isset($skbranch) && $skbranch > 0)
				db_clearBranch($cn, $skbranch);
		}

    	//8472
		// команда удалить все персональные страницы
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'clearPersonalPages'){
		      db_clearPersonalPages($cn);
		}

		// команда остановить портал
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'stopPortal'){
			stopPortal();
		}

		// команда остановить портал
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'StopPortalOnError'){
			stopPortalOnError();
		}

		// команда запустить портал
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'startPortal'){
			startPortal();
		}

		// команда удалить пользователя
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'deleteUser'){
			db_deleteUser($cn, getPrmValueByName($cn, $xml->msg[$i], 'uhash'));
		}

		// команда удалить персональную страницу пользователя
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'deletePersonalPage'){
		    db_deletePersonalPage($cn, getPrmValueByName($cn, $xml->msg[$i], 'uhash'));
		}

		// команда удалить все записи в таблице по названию
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'deleteAllRowsinTable'){
			db_deleteAllRowsinTable($cn, getPrmValueByName($cn, $xml->msg[$i], 'table'));
		}

		// команда удалить отчет по guid
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'deleteReport'){
			db_deleteReportByGuid($cn, getPrmValueByName($cn, $xml->msg[$i], 'guid'));
		}

		// команда удалить права на отчет по guid и uhash
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'deleteRightsReports'){
			db_deleteRightsReports($cn, getPrmValueByName($cn, $xml->msg[$i], 'uhash'), getPrmValueByName($cn, $xml->msg[$i], 'guid'));
		}

		// команда удалить права на объект по guid и uhash
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'deleteRightsObjects'){
			db_deleteRightsObjects($cn, getPrmValueByName($cn, $xml->msg[$i], 'uhash'), getPrmValueByName($cn, $xml->msg[$i], 'guid'));
		}

		//8472
		// команда удалить права на объект по guid
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'deleteAllRightsObjects'){
			db_deleteAllRightsObjects($cn, getPrmValueByName($cn, $xml->msg[$i], 'guid'));
		}

		// команда удалить права на объект опроса для пользователя 
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'deleteRightsPollingObjects'){
			db_deleteRightsPollingObjects($cn, getPrmValueByName($cn, $xml->msg[$i], 'uhash'), getPrmValueByName($cn, $xml->msg[$i], 'idpollingobject'));
		}		

		//данные портала
		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'portal'){
			$pguid = getPrmValueByName($cn, $xml->msg[$i], 'guid');
			db_setPortalGuid($cn, $pguid);
		}

		//удалить данные индекса
		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'deleteReportIndex'){
			$oguid = getPrmValueByName($cn, $xml->msg[$i], 'oguid');
			$rguid = getPrmValueByName($cn, $xml->msg[$i], 'rguid');
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch', 'NULL');
			$query .= " DELETE ri FROM `reportindex` as ri 
						INNER JOIN `objects` as o ON ri.idobject = o.idobject
						INNER JOIN `reports` as r ON ri.idreport = r.idreport
						INNER JOIN `branches` as br ON ri.skbranch = br.skbranch AND o.skbranch = br.skbranch AND r.skbranch = br.skbranch 
						WHERE  o.o_guid='".$oguid."'
						AND r.r_guid='".$rguid."'
						AND (br.idbranch = '".$idbranch."' OR 'NULL' = '".$idbranch."');";			
		}

		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'deleteReportIndexes'){
			$oguid = getPrmValueByName($cn, $xml->msg[$i], 'oguid');
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch', '-1');
			$query .= " DELETE ri FROM `reportindex` as ri 
						INNER JOIN `objects` as o ON ri.idobject = o.idobject
						INNER JOIN `branches` as br ON ri.skbranch = br.skbranch AND o.skbranch = br.skbranch
						WHERE  o.o_guid='".$oguid."'
						AND (br.idbranch = '".$idbranch."' OR IFNULL(".$idbranch.",-1) = -1);";			
		}

		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'calcfullfolders'){
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch', '-1');
			$query .= " SELECT @skbranch := NULL; SELECT @skbranch := skbranch FROM branches WHERE idbranch= '".$idbranch."';";	
			$query .= " DROP TEMPORARY TABLE IF EXISTS `fullfoldernames` ;
						CREATE TEMPORARY TABLE `fullfoldernames` (
										`idobject` BIGINT NOT NULL,
										`skbranch` INT NOT NULL,
										`o_ileft` BIGINT NOT NULL,
										`o_iright` BIGINT NOT NULL,
										`idlanguage` INT NOT NULL,
										`folder` varchar(2500)  COLLATE utf8mb4_unicode_ci 
						)ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
						
						DROP TEMPORARY TABLE IF EXISTS `object_to_path` ;
						CREATE TEMPORARY TABLE `object_to_path` (
										`idobject` BIGINT NOT NULL PRIMARY KEY,
										`skbranch` INT NOT NULL,
										`o_ileft` BIGINT NOT NULL,
										`o_iright` BIGINT NOT NULL
						)ENGINE=InnoDB AUTO_INCREMENT=22;
						
						INSERT INTO `object_to_path`
								SELECT `idobject`, `skbranch`, `o_ileft`, `o_iright` FROM objects WHERE o_useinsearch = 1 OR (o_icon = '0.svg' OR o_icon = '0_reused.svg') AND parent_idobject != 0
								AND `skbranch` = @skbranch;
								
						CREATE INDEX ix1 ON 	`object_to_path`(`skbranch`);
						CREATE INDEX ix2 ON 	`object_to_path`(`o_ileft`);
						CREATE INDEX ix3 ON 	`object_to_path`(`o_iright`);
						CREATE INDEX ix4 ON 	`object_to_path`(`o_ileft`,`o_iright`);
						
						INSERT IGNORE INTO `fullfoldernames`
								SELECT o.`idobject`, o.`skbranch`, o.`o_ileft`, o.`o_iright`, lng.idlanguage, '' 
								FROM objects as o, (SELECT DISTINCT idlanguage FROM resourcefromtables WHERE idtable = 1) as lng
								WHERE o.`skbranch` = @skbranch AND o.`parent_idobject` != 0;   
						CREATE INDEX ix1 ON `fullfoldernames` (idobject, idlanguage);
						
						UPDATE `fullfoldernames` SET `folder` = (SELECT GROUP_CONCAT(rft_columnname_text ORDER by `o_ileft` SEPARATOR ' &bsol; ')
								FROM object_to_path as o INNER JOIN `resourcefromtables` r ON 
								o.idobject = r.`idrecord` AND r.idtable = 1  
								WHERE  r.idlanguage = `fullfoldernames`.idlanguage AND 
										o.`o_ileft` < `fullfoldernames`.`o_ileft` AND o.`o_iright` > `fullfoldernames`.`o_iright` AND o.skbranch = `fullfoldernames`.skbranch  );
						DELETE FROM `fullfolders` WHERE `skbranch` = @skbranch;
						INSERT INTO `fullfolders`
						SELECT idobject, idlanguage, skbranch, folder FROM `fullfoldernames` WHERE folder IS NOT NULL;";			
		}

		$deleteold = (isset($xml->msg[$i]['deleteold']) && mb_strtolower($xml->msg[$i]['deleteold']) == 'true');

 		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'users'){
			$iduser = db_getIDUserByHash($cn, getPrmValueByName($cn, $xml->msg[$i], 'uhash'));
			$uhash = getPrmValueByName($cn, $xml->msg[$i], 'uhash');
			$email = getPrmValueByName($cn, $xml->msg[$i], 'email');
			$isGroup = getPrmValueByName($cn, $xml->msg[$i], 'isGroup');			
			$isAdmin = getPrmValueByName($cn, $xml->msg[$i], 'isAdmin', 0);
		    $isActive = getPrmValueByName($cn, $xml->msg[$i], 'isActive', 1);
			$guid =  getPrmValueByName($cn, $xml->msg[$i], 'guid', '');
			//64799
			$user_notification_answer = getSetting('portal','defualt.user_notification_answer',0);
			$user_notification_allallow = getSetting('portal','defualt.user_notification_allallow',0);

			if ($iduser == 0) {
				$query .= " INSERT IGNORE INTO `users` ( `user_hash`, `user_guid`, `user_email`, `user_isgroup` , `user_isadmin`, `user_idlanguageinterface`, `user_idlanguagecontent`, `user_notification_answer`, `user_notification_allallow`, `user_isactive`)  ";
				$query .= " VALUES ( '".$uhash."', '".$guid."', '".$email."', ".$isGroup.", ".$isAdmin.", 0, 0, ".$user_notification_answer.", ".$user_notification_allallow.", ".$isActive.");";
			} else {
				$query .= "   UPDATE     `users`    SET  ";
				$query .= " user_email = '".$email."', user_guid = '".$guid."', user_isadmin = ".$isAdmin.", user_isactive = ".$isActive." ";
				$query .= " WHERE user_hash = '".$uhash."' ;";
			}
		}

   		 if ($xml->msg[$i]['type'] == 'delete' && $xml->msg[$i]['name'] == 'users'){
			$iduser = db_getIDUserByHash($cn, getPrmValueByName($cn, $xml->msg[$i], 'uhash'));
			if ($iduser == 0) {
			} else {
				$query .= "   UPDATE     `users`    SET  ";
				$query .= " user_isactive = 0 ";
				$query .= " WHERE user_hash = '".getPrmValueByName($cn, $xml->msg[$i], 'uhash')."' ;";

        //8472 удаляем ссылки персональной страницы пользователя
				$query .= "   DELETE FROM `userslinks` ";
				$query .= " WHERE iduser = ".$iduser." ;";

        //8472 удаляем права пользователя
				$query .= "   DELETE FROM `rightsobjects` ";
				$query .= " WHERE iduser = ".$iduser." ;";

        // удаляем связь с группой
				$query .= "   DELETE FROM `usersgroups`  ";
				$query .= " WHERE iduser = ".$iduser." ;";

		// удаляем права на объект опроса
				$query .= "   DELETE FROM `rightspollingobjects`  ";
				$query .= " WHERE iduser = ".$iduser." ;";

		// delete prepare tree
				$query .= "DELETE FROM prepared_tree WHERE `usersidsarr` = '".$iduser."' OR `usersidsarr` LIKE '%,".$iduser."' OR `usersidsarr` LIKE '".$iduser.",%' OR `usersidsarr` LIKE '%,".$iduser.",%';";
			}
		}

		// usersgroup section
		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'usersgroups'){
			$query .= " set @idgorup = NULL;  set @idu = NULL;";
			$query .= " SELECT @idu := iduser FROM `users` WHERE user_hash='".getPrmValueByName($cn, $xml->msg[$i], 'uhash')."' AND user_isgroup = 0; ";
			$query .= " SELECT @idgorup := iduser FROM `users` WHERE user_hash='".getPrmValueByName($cn, $xml->msg[$i], 'ghash')."' AND user_isgroup = 1;";
			$query .= " DELETE FROM `usersgroups` WHERE iduser = @idu AND idgroup = @idgorup; ";
			$query .= " INSERT IGNORE INTO `usersgroups`(`iduser`, `idgroup`, `user_hash`, `group_hash`) ";
			$query .= " VALUES (@idu, @idgorup, '".getPrmValueByName($cn, $xml->msg[$i], 'uhash')."', '".getPrmValueByName($cn, $xml->msg[$i], 'ghash')."' ); ";
		}

		if ($xml->msg[$i]['type'] == 'delete' && $xml->msg[$i]['name'] == 'usersgroups'){
			$query .= " set @idgorup = NULL;  set @idu = NULL;";
			$query .= " SELECT @idu := iduser FROM `users` WHERE user_hash='".getPrmValueByName($cn, $xml->msg[$i], 'uhash')."' AND user_isgroup = 0; ";
			$query .= " SELECT @idgorup := iduser FROM `users` WHERE user_hash='".getPrmValueByName($cn, $xml->msg[$i], 'ghash')."' AND user_isgroup = 1;";
			$query .= " DELETE FROM `usersgroups` WHERE iduser = @idu AND idgroup = @idgorup; ";
		}

		if ($xml->msg[$i]['type'] == 'command' && $xml->msg[$i]['name'] == 'deleteallUsersgroups'){
			$query .= " DELETE FROM `usersgroups`; ";
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'branch'){
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch');
			$ismain = (mb_strtolower(getPrmValueByName($cn, $xml->msg[$i], 'ismain')) == 'true' ? 1 : 0);
			$iscomplete = (mb_strtolower(getPrmValueByName($cn, $xml->msg[$i], 'iscomplete')) == 'true' ? 1 : 0); //60081
			if ($deleteold) {
				$query .= " DELETE FROM `branches` WHERE idbranch = '".$idbranch."';";
			} else {
				$query .= " UPDATE `branches` SET `ismain` = ".$ismain.", `iscomplete` = ".$iscomplete."  WHERE idbranch = '".$idbranch."';";
			}
			if ($ismain == 1) {
				$query .= " UPDATE `branches` SET `ismain` = 0 WHERE idbranch <> '".$idbranch."';";
			}
			$query .= " INSERT IGNORE INTO `branches` (`idbranch`, `ismain`, `iscomplete`) ";
			$query .= " SELECT * FROM (SELECT '".$idbranch."' as `idbranch`, ".$ismain." as `ismain`, ".$iscomplete." as `iscomplete`) as tmp WHERE NOT EXISTS (SELECT 1 FROM `branches` WHERE idbranch = '".$idbranch."' LIMIT 1); ";
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'objects'){
			$oguid = getPrmValueByName($cn, $xml->msg[$i], 'guid');
			$p_guid = getPrmValueByName($cn, $xml->msg[$i], 'parent', '00000000-0000-0000-0000-000000000000');
			$icon = str_replace('\\','/',getPrmValueByName($cn, $xml->msg[$i], 'icon')); 
			$size = sizeof($xml->msg[$i]->prm);
			$hr = (mb_strtolower(getPrmValueByName($cn, $xml->msg[$i], 'hasreport', 'false')) == 'false') ? 1 : 0 ;
			$uis = getPrmValueByName($cn, $xml->msg[$i], 'useInSearch', 0);
	  	$datever = getPrmValueByName($cn, $xml->msg[$i], 'datever', '0000-00-00');
	  	$ver = getPrmValueByName($cn, $xml->msg[$i], 'ver', '0');
	  	$statever = getPrmValueByName($cn, $xml->msg[$i], 'statever', 0);
			$hidefortree = getPrmValueByName($cn, $xml->msg[$i], 'hide', 0);
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch'); 
			$bct = getPrmValueByName($cn, $xml->msg[$i], 'bct', 0); 
			$src_guid = getPrmValueByName($cn, $xml->msg[$i], 'srcGuid', ''); //71970
			if(!in_array($idbranch, $excludeBranches)){
				$query .= " call add_objects('".$p_guid."','".$oguid."','".$icon."','".getPrmValueByName($cn, $xml->msg[$i], 'datechange')."', '".$ver."' , '".$datever."' , ".$statever.", ".$hr.",".$uis.", ".$hidefortree.", '".$idbranch."', '".$src_guid."');";
				if ($bct == 1){
					$query .= " INSERT IGNORE INTO objectsprohibitionrightscopy SELECT o.idobject, 1 FROM objects as o INNER JOIN branches as b USING(skbranch) WHERE o.o_guid = '".$oguid."' AND b.idbranch = '".$idbranch."';";
				}
			}
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'reports'){
			$rguid = getPrmValueByName($cn, $xml->msg[$i], 'guid'); 
			$pos = getPrmValueByName($cn, $xml->msg[$i], 'pos'); 
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch'); 
			$langValue = str_replace(' ', '', getPrmValueByName($cn, $xml->msg[$i], 'language'));
			$manyLangs = (strpos($langValue, ',') !== false);
			$singleLang = strlen($langValue) > 0;
			if ($manyLangs || $singleLang) {
				$langValue = "'".str_replace(",", "','", $langValue)."'";
			}
			$langQueryPart = ($manyLangs ? $langValue : getLanguageID(getPrmValueByName($cn, $xml->msg[$i], 'language'))); 
			if(!in_array($idbranch, $excludeBranches)){
				$query .= " DELETE orr FROM `objectsreports` orr  
							INNER JOIN `reports` r ON orr.idreport = r.idreport  
							INNER JOIN `branches` as br ON orr.skbranch = br.skbranch AND r.skbranch = br.skbranch  
							WHERE r.r_guid = '".$rguid."'
							".($manyLangs || $singleLang ? "AND r.`idlanguage` IN (SELECT `idlanguage` FROM `languages` WHERE `lang_short` IN (".$langValue.")) " : "")." 
							AND br.idbranch = '".$idbranch."';"; 
				
				$query .= " DELETE rr FROM `rightsreports` rr  
							INNER JOIN `reports` r ON rr.idreport = r.idreport  
							INNER JOIN `branches` as br ON rr.skbranch = br.skbranch AND r.skbranch = br.skbranch  
							WHERE r.r_guid = '".$rguid."' 
							".($manyLangs || $singleLang ? "AND r.`idlanguage` IN (SELECT `idlanguage` FROM `languages` WHERE `lang_short` IN (".$langValue.")) " : "")." 
							AND br.idbranch = '".$idbranch."';"; 

				if ($manyLangs || $singleLang) {
					$query .= " DELETE FROM `reports` WHERE `r_guid`= '".$rguid."' AND  `idlanguage` IN (SELECT `idlanguage` FROM `languages` WHERE `lang_short` IN (".$langValue.")) 
								AND skbranch = (SELECT skbranch FROM `branches` WHERE idbranch = '".$idbranch."'); "; 
					$query .= " INSERT IGNORE INTO `reports` (`r_guid` ,`r_position` , `idlanguage`, `skbranch`) "; 
					$query .= " SELECT '".$rguid."', ".$pos.", `languages`.`idlanguage`, skbranch FROM `branches`, `languages` 
								WHERE idbranch = '".$idbranch."' AND `languages`.`lang_short` IN (".$langValue.");"; 
				}else{
					$query .= " DELETE FROM `reports` WHERE `r_guid`= '".$rguid."' AND  IFNULL(`idlanguage`,0) = IFNULL(".$langQueryPart.",0) 
								AND skbranch = (SELECT skbranch FROM `branches` WHERE idbranch = '".$idbranch."'); "; 
					$query .= " INSERT IGNORE INTO `reports` (`r_guid` ,`r_position` , `idlanguage`, `skbranch`) "; 
					$query .= " SELECT '".$rguid."', ".$pos.", ".$langQueryPart.", skbranch FROM `branches` WHERE idbranch = '".$idbranch."' ;"; 
				}
			}
		} 

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'sections'){
			if ($deleteold) {
				$query .= " DELETE FROM `sections` WHERE sct_guid = '".getPrmValueByName($cn, $xml->msg[$i], 'guid')."';";
			}
			$query .= " INSERT IGNORE INTO `sections` (`idsection`, `sct_guid`, `sct_icon`, `sct_pos`) ";
			$query .= " VALUES (NULL,'".getPrmValueByName($cn, $xml->msg[$i], 'guid')."', '".getPrmValueByName($cn, $xml->msg[$i], 'icon')."', '".getPrmValueByName($cn, $xml->msg[$i], 'pos')."'); ";
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'links'){
			$query .= " set @idlink = NULL;  set @idsection = NULL;";
			$query .= " SELECT @idsection := null; SELECT @idsection := idsection FROM sections WHERE sct_guid='".getPrmValueByName($cn, $xml->msg[$i], 'sguid')."';";
			$query .= " SELECT @idlink := null; SELECT @idlink := idlink FROM `links` WHERE idsection = @idsection AND lnk_guid = '".getPrmValueByName($cn, $xml->msg[$i], 'guid')."';";

			if ($deleteold) {
				$query .= " DELETE FROM `links` WHERE idsection = @idsection AND lnk_guid = '".getPrmValueByName($cn, $xml->msg[$i], 'guid')."';";
			}
			$query .= " INSERT IGNORE INTO `links` (`idlink`, `idsection`, `lnk_guid`, `lnk_pos`, `lnk_type`) ";
			$query .= " VALUES (@idlink, @idsection, '".getPrmValueByName($cn, $xml->msg[$i], 'guid')."', ".getPrmValueByName($cn, $xml->msg[$i], 'pos').", ".getPrmValueByName($cn, $xml->msg[$i], 'type')."); ";
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'userslinks'){
			$query .= " set @idlink = NULL;  set @iduserlink = NULL; set @idu = NULL;";
			$query .= " SELECT @idlink := idlink FROM links WHERE lnk_guid='".getPrmValueByName($cn, $xml->msg[$i], 'lguid')."';";
			$query .= " SELECT @idu := iduser FROM `users` WHERE user_hash='".getPrmValueByName($cn, $xml->msg[$i], 'uhash')."'; ";
			$query .= " SELECT @iduserlink := iduserlink FROM `userslinks` WHERE iduser = @idu AND idlink = @idlink; ";
			if ($deleteold) {
				$query .= " DELETE FROM `userslinks` WHERE iduser = @idu AND idlink = @idlink; ";
			}
			$query .= " INSERT IGNORE INTO `userslinks` (`iduserlink`, `iduser`, `idlink`, `ul_url`) ";
			$url = getPrmValueByName($cn, $xml->msg[$i], 'url', '') ;
			$query .= " VALUES (@iduserlink, @idu, @idlink, '".$url."'); ";
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'objectsreports'){
			$oguid = getPrmValueByName($cn, $xml->msg[$i], 'oguid');
			$rguid = getPrmValueByName($cn, $xml->msg[$i], 'rguid');
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch');

			if(!in_array($idbranch, $excludeBranches)){
				$query .= " SELECT @ido := NULL; SELECT @ido := idobject 
							FROM objects as o
							INNER JOIN `branches` as br ON o.skbranch = br.skbranch  
							WHERE o_guid='".$oguid."' AND br.idbranch = '".$idbranch."'; ";

				if ($deleteold) {
					$query .= " DELETE orr FROM `objectsreports` orr 
								INNER JOIN `reports` r ON orr.idreport = r.idreport 
								INNER JOIN `branches` as br ON orr.skbranch = br.skbranch AND r.skbranch = br.skbranch 
								WHERE r.r_guid = '".$rguid."'
								AND br.idbranch = '".$idbranch."';";
				}
				$query .= " INSERT IGNORE INTO `objectsreports` (`idobject` ,`idreport`, `idlanguage`, `skbranch`)";
				$query .= " 	SELECT DISTINCT @ido, idreport, IFNULL(idlanguage,0), br.skbranch 
								FROM `reports` as r
								INNER JOIN `branches` as br ON r.skbranch = br.skbranch  
								WHERE r_guid = '".$rguid."' AND br.idbranch = '".$idbranch."'; ";							  
			}
		}

	    if ($xml->msg[$i]['type'] == 'delete' && $xml->msg[$i]['name'] == 'objectsreports'){
			$query .= " DELETE orr FROM `objectsreports` as orr 
						INNER JOIN `objects` as o ON orr.idobject = o.idobject
						INNER JOIN `reports` as r ON orr.idreport = r.idreport
						INNER JOIN `branches` as br ON orr.skbranch = br.skbranch AND o.skbranch = br.skbranch AND r.skbranch = br.skbranch 
						WHERE  o.o_guid='".getPrmValueByName($cn, $xml->msg[$i], 'oguid')."'
						AND r.r_guid='".getPrmValueByName($cn, $xml->msg[$i], 'rguid')."'
						AND br.idbranch = '".getPrmValueByName($cn, $xml->msg[$i], 'idbranch')."';";
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'rightsreports'){
			$langValue = str_replace(' ', '', getPrmValueByName($cn, $xml->msg[$i], 'language'));
			$langValue = (strlen($langValue) > 0 ? "'".str_replace(",", "','", $langValue)."'" : $langValue);
			$langQueryPart = (strlen($langValue) > 0 ? "AND reports.`idlanguage` IN (SELECT `idlanguage` FROM `languages` WHERE `lang_short` IN (".$langValue.")) " : ""); 
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch');
			if(!in_array($idbranch, $excludeBranches)){
				$query .= " INSERT IGNORE INTO `rightsreports` (`iduser` , `idreport`, `deny_allow`, `skbranch`) ";
				$query .= " SELECT iduser, idreport, ".getPrmValueByName($cn, $xml->msg[$i], 'deny_allow').", br.skbranch 
							FROM reports, users, branches as br 
							WHERE r_guid = '".getPrmValueByName($cn, $xml->msg[$i], 'rguid')."' AND user_hash = '".getPrmValueByName($cn, $xml->msg[$i], 'uhash')."' AND br.idbranch = '".$idbranch."'
							".$langQueryPart."; ";
			}
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'rightsobjects'){
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch');
			if(!in_array($idbranch, $excludeBranches)){
				$query .= " INSERT IGNORE INTO `rightsobjects` (`iduser` , `idobject`, `deny_allow`, `skbranch`, `isCopied`)  ";
				$query .= " SELECT iduser, idobject, ".getPrmValueByName($cn, $xml->msg[$i], 'deny_allow').", br.skbranch, 0 
							FROM objects, users, branches as br  
							WHERE o_guid = '".getPrmValueByName($cn, $xml->msg[$i], 'oguid')."' AND user_hash = '".getPrmValueByName($cn, $xml->msg[$i], 'uhash')."' AND br.idbranch = '".$idbranch."'; ";
			}
		}
		
		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'rightspollingobjects'){
			$query .= " INSERT IGNORE INTO `rightspollingobjects` (`iduser` , `skpollingobject`, `deny_allow`)  ";
			$query .= " SELECT iduser, skpollingobject, ".getPrmValueByName($cn, $xml->msg[$i], 'deny_allow')." 
						FROM `users`, `pollingobjects`
						WHERE idpollingobject = '".getPrmValueByName($cn, $xml->msg[$i], 'idpollingobject')."' AND user_hash = '".getPrmValueByName($cn, $xml->msg[$i], 'uhash')."' ; ";
		}

		// 61795
		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'pollstatus'){
			$pollingobjectstatus_active = 1;
			$idpolltype = getPrmValueByName($cn, $xml->msg[$i], 'idpolltype', '-');
			$idpollingobject = getPrmValueByName($cn, $xml->msg[$i], 'idpollingobject', '-');
			$idproject = getPrmValueByName($cn, $xml->msg[$i], 'idproject', '-');
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch', '-');
			$status = getPrmValueByName($cn, $xml->msg[$i], 'status', '-');
			if ($idproject != '-') {
				$query .= "UPDATE  `useranswers` SET idpollingobjectstatus = ".$status." WHERE idpollingobject in (SELECT idpollingobject FROM `pollingobjects` WHERE skproject = (SELECT skproject FROM `projects` WHERE idproject = '".$idproject."')) AND idpolltype = '".$idpolltype."';";
			} else if ($idbranch != '-') {
				$query .= "UPDATE  `useranswers` SET idpollingobjectstatus = ".$status." WHERE idpollingobject in (SELECT idpollingobject FROM `pollingobjects` WHERE skbranch = (SELECT skbranch FROM `branches` WHERE idbranch = '".$idbranch."')) AND idpolltype = '".$idpolltype."';";
			} else if ($idpollingobject != '-') {
				$query .= "UPDATE  `useranswers` SET idpollingobjectstatus = ".$status." WHERE idpollingobject = '".$idpollingobject."' AND idpolltype = '".$idpolltype."';";
			}	
			// 63532					
			if($status == $pollingobjectstatus_active){
				if ($idproject != '-') {
					$query .= " DROP TEMPORARY TABLE IF EXISTS `pollingobjects_st_tmp` ;";
				
					$query .= " CREATE TEMPORARY TABLE pollingobjects_st_tmp (
						`idpollingobject` VARCHAR(250) NOT NULL PRIMARY KEY
						)ENGINE=MEMORY, COLLATE = utf8mb4_general_ci;";

					$query .= " INSERT INTO `pollingobjects_st_tmp` SELECT DISTINCT idpollingobject FROM `pollingobjects` WHERE skproject = (SELECT skproject FROM `projects` WHERE idproject = '".$idproject."');";

					$query .= "UPDATE pollingobjects as po
						INNER JOIN objects as o ON po.o_guid = o.o_guid AND po.skbranch = o.skbranch
						INNER JOIN `pollingobjects_st_tmp` st_t ON st_t.idpollingobject = po.idpollingobject
						SET po.idobject = o.idobject;";
				
					$query .= "UPDATE useranswers as ua
						INNER JOIN pollingobjects as po ON po.idpollingobject = ua.idpollingobject
						INNER JOIN `pollingobjects_st_tmp` st_t ON st_t.idpollingobject = ua.idpollingobject
						SET ua.skpollingobject = po.skpollingobject WHERE ua.idpolltype = '".$idpolltype."';";
					
					$query .= "UPDATE useranswers as ua
						INNER JOIN polltypes as pt ON pt.idpolltype = ua.idpolltype
						INNER JOIN `pollingobjects_st_tmp` st_t ON st_t.idpollingobject = ua.idpollingobject
						SET ua.skpolltype = pt.skpolltype WHERE ua.idpolltype = '".$idpolltype."';";
					
					$query .= "UPDATE useranswers as ua
						INNER JOIN users as u ON u.user_hash = ua.user_hash
						INNER JOIN `pollingobjects_st_tmp` st_t ON st_t.idpollingobject = ua.idpollingobject
						SET ua.iduser = u.iduser WHERE ua.idpolltype = '".$idpolltype."';";

				} else if ($idbranch != '-') {
					$query .= " DROP TEMPORARY TABLE IF EXISTS `pollingobjects_st_tmp` ;";
				
					$query .= " CREATE TEMPORARY TABLE pollingobjects_st_tmp (
						`idpollingobject` VARCHAR(250) NOT NULL PRIMARY KEY
						)ENGINE=MEMORY, COLLATE = utf8mb4_general_ci;";

					$query .= " INSERT INTO `pollingobjects_st_tmp` SELECT DISTINCT idpollingobject FROM `pollingobjects` WHERE skbranch = (SELECT skbranch FROM `branches` WHERE idbranch = '".$idbranch."');";

					$query .= "UPDATE pollingobjects as po
						INNER JOIN objects as o ON po.o_guid = o.o_guid AND po.skbranch = o.skbranch
						INNER JOIN `pollingobjects_st_tmp` st_t ON st_t.idpollingobject = po.idpollingobject
						SET po.idobject = o.idobject;";
				
					$query .= "UPDATE useranswers as ua
						INNER JOIN pollingobjects as po ON po.idpollingobject = ua.idpollingobject
						INNER JOIN `pollingobjects_st_tmp` st_t ON st_t.idpollingobject = ua.idpollingobject
						SET ua.skpollingobject = po.skpollingobject WHERE ua.idpolltype = '".$idpolltype."';";
					
					$query .= "UPDATE useranswers as ua
						INNER JOIN polltypes as pt ON pt.idpolltype = ua.idpolltype
						INNER JOIN `pollingobjects_st_tmp` st_t ON st_t.idpollingobject = ua.idpollingobject
						SET ua.skpolltype = pt.skpolltype WHERE ua.idpolltype = '".$idpolltype."';";
					
					$query .= "UPDATE useranswers as ua
						INNER JOIN users as u ON u.user_hash = ua.user_hash
						INNER JOIN `pollingobjects_st_tmp` st_t ON st_t.idpollingobject = ua.idpollingobject
						SET ua.iduser = u.iduser WHERE ua.idpolltype = '".$idpolltype."';";

				} else if ($idpollingobject != '-') {
					$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
						WHERE idpollingobject = '".$idpollingobject."';";
				
					$query .= "UPDATE useranswers as ua
						INNER JOIN pollingobjects as po ON po.idpollingobject = ua.idpollingobject
						SET ua.skpollingobject = po.skpollingobject WHERE ua.idpollingobject = '".$idpollingobject."' AND ua.idpolltype = '".$idpolltype."';";
					
					$query .= "UPDATE useranswers as ua
						INNER JOIN polltypes as pt ON pt.idpolltype = ua.idpolltype
						SET ua.skpolltype = pt.skpolltype WHERE ua.idpollingobject = '".$idpollingobject."' AND ua.idpolltype = '".$idpolltype."';";
					
					$query .= "UPDATE useranswers as ua
						INNER JOIN users as u ON u.user_hash = ua.user_hash
						SET ua.iduser = u.iduser WHERE ua.idpollingobject = '".$idpollingobject."' AND ua.idpolltype = '".$idpolltype."';";
				}	
			
			}
		}

		// 62359
		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'pollfinishdate'){
			$idpolltype = getPrmValueByName($cn, $xml->msg[$i], 'idpolltype', '-');
			$idproject = getPrmValueByName($cn, $xml->msg[$i], 'idproject', '-');
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch', '-');
			$finishdate = getPrmValueByName($cn, $xml->msg[$i], 'finishdate', '-');
			if ($idproject != '-') {
				$query .= "DELETE FROM  `pollfinishdate` WHERE skpolltype = (SELECT skpolltype FROM `polltypes` WHERE `idpolltype` = '".$idpolltype."') AND skproject IS NOT NULL AND skproject = (SELECT skproject FROM `projects` WHERE `idproject` = '".$idproject."') ;";
			} else if ($idbranch != '-') {
				$query .= "DELETE FROM  `pollfinishdate` WHERE skpolltype = (SELECT skpolltype FROM `polltypes` WHERE `idpolltype` = '".$idpolltype."') AND skproject IS NULL AND skbranch = (SELECT skbranch FROM `branches` WHERE `idbranch` = '".$idbranch."' ) ;";
			}						

			if ($finishdate != '-') {
				$query .= " SELECT @skpolltype := NULL; SELECT @skpolltype  := skpolltype  FROM `polltypes` WHERE `idpolltype` = '".$idpolltype."';";
				if ($idproject != '-') {
					$query .= " SELECT @skproject := NULL; SELECT @skproject := skproject FROM `projects` WHERE `idproject` = '".$idproject."'; ";
					$query .= "INSERT IGNORE INTO `pollfinishdate` 
						SELECT @skpolltype, 0, @skproject, '".$finishdate."';";
				} else if ($idbranch != '-') {
					$query .= " SELECT @skbranch := NULL; SELECT @skbranch := skbranch FROM `branches` WHERE `idbranch` = '".$idbranch."'; ";
					$query .= "INSERT IGNORE INTO `pollfinishdate` 
						SELECT @skpolltype, @skbranch, NULL, '".$finishdate."';";
				} 						
			}
		}

		// 60922
		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'rightsadminpollingobjects'){
			$uhash = getPrmValueByName($cn, $xml->msg[$i], 'uhash', '-');
			$idpolltype = getPrmValueByName($cn, $xml->msg[$i], 'idpolltype', '-');
			$idproject = getPrmValueByName($cn, $xml->msg[$i], 'idproject', '-');
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch', '-');
			$deny_allow = getPrmValueByName($cn, $xml->msg[$i], 'deny_allow', '-');

			if ($idbranch != '-') {
				$query .= " SELECT @skbranch := NULL; SELECT @skbranch := skbranch FROM branches WHERE idbranch= '".$idbranch."';";							
			}
			if ($uhash != '-') {
				$query .= " SELECT @idu := NULL; SELECT @idu := iduser FROM users WHERE user_hash = '".$uhash."' ;";
			}						
			if ($idproject != '-') {
				$query .= "SELECT @skproject := NULL; SELECT @skproject := skproject FROM projects WHERE idproject = '".$idproject."';";
			}						
			

			if ($idpolltype != '-') {
				$query .= " SELECT @skpolltype := NULL;  SELECT @skpolltype := skpolltype FROM polltypes WHERE idpolltype = '".$idpolltype."';";
				//clear rights to polltype
				$query .= " DELETE FROM `rightsadminpollingobjects` WHERE `skpolltype` = @skpolltype ";
				if ($uhash != '-') {
					$query .= " AND `iduser` = @idu ";
				}
				if ($idbranch != '-') {
					$query .= " AND `skbranch` = @skbranch ";
				}
				if ($idproject != '-') {
					$query .= " AND `skproject` = @skproject ";
				}
				$query .= ";";
				//insert rigths
				if ($deny_allow != '-' && $uhash != '-') {
					$query .= " INSERT IGNORE INTO `rightsadminpollingobjects` (`iduser`, `skpolltype`, `skbranch`, `skproject`, `deny_allow`) ";
					$query .= " SELECT DISTINCT @idu, @skpolltype, `skbranch`, ".($idproject != '-' ? '`skproject`' : 'NULL').", ".$deny_allow." 
						FROM `pollingobjects` 
						WHERE ".($idproject != '-' ? '`skproject` = @skproject' : '`skbranch` = @skbranch').";"; 
				}
			}
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'languages'){
			$language = getPrmValueByName($cn, $xml->msg[$i], 'language');
			$allow = getPrmValueByName($cn, $xml->msg[$i], 'allow');
			$main = getPrmValueByName($cn, $xml->msg[$i], 'main');
			if ($main == '1') {
				$query .= " UPDATE `languages` SET main = 0 ; ";
			}
			$query .= " UPDATE `languages` SET allow = ".$allow.", main = ".$main." WHERE lang_short like '".$language."'; ";
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'objectlinks' && !in_array(getPrmValueByName($cn, $xml->msg[$i], 'idbranch'), $excludeBranches)){
			$oguid = getPrmValueByName($cn, $xml->msg[$i], 'oguid');
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch');
			$query .= " SELECT @skbranch := NULL; SELECT @skbranch := skbranch FROM branches WHERE idbranch= '".getPrmValueByName($cn, $xml->msg[$i], 'idbranch')."';";
			$query .= " SELECT @ido := NULL; SELECT @ido := idobject FROM objects WHERE o_guid='".$oguid."' AND skbranch = @skbranch;";
			$query .= " SELECT @idu := NULL; SELECT @idu := iduser FROM users WHERE user_hash = '".getPrmValueByName($cn, $xml->msg[$i], 'uhash')."' ;";
			$query .= " INSERT IGNORE INTO `objectlinks` ( `iduser` , `idobject` , `skbranch`, `ol_type`, `ol_notificate` ) ";
			$query .= " VALUES ( @idu, @ido, @skbranch, ".getPrmValueByName($cn, $xml->msg[$i], 'type')." , null );";
		}
	
		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'polltype'){
			$allcmt = getPrmValueByName($cn, $xml->msg[$i], 'AllowComment');
			$allcmt = (mb_strtolower($allcmt) == "true" ? "1" : "0");
			$allchansw = getPrmValueByName($cn, $xml->msg[$i], 'AllowToChangeAnswer', '1'); //62359
			$query .= " INSERT IGNORE INTO `polltypes` (`idpolltype` , `AllowComment`, `AllowToChangeAnswer`) ";
			$query .= " 	SELECT '".getPrmValueByName($cn, $xml->msg[$i], 'idpolltype')."', ".$allcmt." , ".$allchansw."; ";
			$query .= " UPDATE `polltypes` SET `AllowComment` =	".$allcmt." , `AllowToChangeAnswer` = ".$allchansw." WHERE `idpolltype` = '".getPrmValueByName($cn, $xml->msg[$i], 'idpolltype')."'; ";
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'polltypequestion'){
			$plqtp = getPrmValueByName($cn, $xml->msg[$i], 'idpolltypequestiontype');
			$query .= " SELECT @skpolltype := NULL;  SELECT @skpolltype := skpolltype FROM polltypes WHERE idpolltype = '".getPrmValueByName($cn, $xml->msg[$i], 'idpolltype')."';";
			$query .= " INSERT IGNORE INTO `polltypequestions` (`idpolltypequestion` , `skpolltype`, `idpolltypequestiontype`) ";
			$query .= " 	SELECT '".getPrmValueByName($cn, $xml->msg[$i], 'idpolltypequestion')."', @skpolltype, ".$plqtp."; ";
			$query .= " UPDATE `polltypequestions` SET `idpolltypequestiontype` =	".$plqtp.", skpolltype = @skpolltype WHERE `idpolltypequestion` = '".getPrmValueByName($cn, $xml->msg[$i], 'idpolltypequestion')."'; ";
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'polltypequestionselectvalue'){
			$query .= " SELECT @skpolltypequestion := NULL;  SELECT @skpolltypequestion := skpolltypequestion FROM polltypequestions WHERE idpolltypequestion = '".getPrmValueByName($cn, $xml->msg[$i], 'idpolltypequestion')."';";
			$idpq_sv = getPrmValueByName($cn, $xml->msg[$i], 'idpolltypequestionselectvalue');
			$query .= " INSERT IGNORE INTO `polltypequestionselectvalues` (`idpolltypequestionselectvalue`, `skpolltypequestion` ) ";
			$query .= " 	SELECT '".$idpq_sv."', @skpolltypequestion; ";
			$query .= " UPDATE `polltypequestionselectvalues` SET `skpolltypequestion` = @skpolltypequestion WHERE `idpolltypequestionselectvalue` = '".$idpq_sv."'; ";
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'project'){
			$idproject = getPrmValueByName($cn, $xml->msg[$i], 'idproject');
			$startdate = getPrmValueByName($cn, $xml->msg[$i], 'startdate');
			$enddate = getPrmValueByName($cn, $xml->msg[$i], 'enddate');
			$query .= " INSERT IGNORE INTO  `projects`  (`idproject`, `startdate`, `enddate`) ";
			$query .= " 	SELECT * FROM ( SELECT '".$idproject."' as idproject, '".$startdate."' as startdate, '".$enddate."' as enddate) q WHERE NOT EXISTS (SELECT 1 FROM `projects` WHERE `idproject` = '".$idproject."' LIMIT 1); ";
			$query .= " UPDATE `projects` SET `startdate` = '".$startdate."', `enddate` = '".$enddate."'  WHERE `idproject` = '".$idproject."';";
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'useranswer'){
			$idproject = getPrmValueByName($cn, $xml->msg[$i], 'idproject');
			$idpollingobject = getPrmValueByName($cn, $xml->msg[$i], 'idpollingobject');
			$idpolltype = getPrmValueByName($cn, $xml->msg[$i], 'idpolltype');
			$query .= " INSERT IGNORE INTO `useranswers` (`idpollingobject`, `skpollingobject`, `idpolltype`, `skpolltype`, `user_hash`, `iduser`, `idpollingobjectstatus`, `hasanswer`) ";
			$query .= " 	SELECT '".$idpollingobject."',  0, '".$idpolltype."', 0, '".getPrmValueByName($cn, $xml->msg[$i], 'uhash', 0)."', 0, 10, 0; "; // status 10 for new pollobjects
				
			$query .= " UPDATE useranswers as ua
				INNER JOIN pollingobjects as po ON po.idpollingobject = ua.idpollingobject
				SET ua.skpollingobject = po.skpollingobject WHERE ua.skpollingobject = 0 AND ua.idpollingobject = '".$idpollingobject."' AND ua.idpolltype = '".$idpolltype."'; ";
					
			$query .=  "UPDATE useranswers as ua
				INNER JOIN polltypes as pt ON pt.idpolltype = ua.idpolltype
				SET ua.skpolltype = pt.skpolltype WHERE ua.skpolltype = 0 AND ua.idpollingobject = '".$idpollingobject."' AND ua.idpolltype = '".$idpolltype."'; ";
					
			$query .= " UPDATE useranswers as ua
				INNER JOIN users as u ON u.user_hash = ua.user_hash
				SET ua.iduser = u.iduser WHERE ua.iduser = 0 AND ua.idpollingobject = '".$idpollingobject."' AND ua.idpolltype = '".$idpolltype."'; ";

			// 64305
			$query .= " UPDATE useranswers as ua
				INNER JOIN useranswersvalues as uav ON ua.iduser = uav.iduser AND ua.skpolltype = uav.skpolltype AND ua.skpollingobject = uav.skpollingobject AND IFNULL(uav.uav_value,0) > 0
				SET ua.hasanswer = 1 WHERE ua.hasanswer = 0 AND ua.idpollingobject = '".$idpollingobject."' AND ua.idpolltype = '".$idpolltype."'; ";
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'pollingobject' && !in_array(getPrmValueByName($cn, $xml->msg[$i], 'idbranch'), $excludeBranches)){
			$idproject = getPrmValueByName($cn, $xml->msg[$i], 'idproject', '');
			$query .= "SELECT @skproject := NULL;"; 
			if ($idproject != '') {
				$query .= " SELECT @skproject := skproject FROM projects WHERE idproject = '".$idproject."';";
			}

			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch', '');
			$query .= "SELECT @skbranch := NULL;"; 
			if ($idbranch != '') {
				$query .= "SELECT @skbranch := skbranch FROM branches WHERE idbranch = '".$idbranch."';";
			}

			$objectversion = getPrmValueByName($cn, $xml->msg[$i], 'objectversion');
			$objectversiondate = getPrmValueByName($cn, $xml->msg[$i], 'objectversiondate');
			$objectversionuhash = getPrmValueByName($cn, $xml->msg[$i], 'objectversionuhash'); 
      		$objectversionhash = getPrmValueByName($cn, $xml->msg[$i], 'objectversionhash'); 
			$reportversion = getPrmValueByName($cn, $xml->msg[$i], 'reportversion');
			$reportversiondate = getPrmValueByName($cn, $xml->msg[$i], 'reportversiondate');
			$reportversionuhash  = getPrmValueByName($cn, $xml->msg[$i], 'reportversionuhash');
      		$reportversionhash  = getPrmValueByName($cn, $xml->msg[$i], 'reportversionhash');
			$oguid = getPrmValueByName($cn, $xml->msg[$i], 'oguid');
			$rguid = getPrmValueByName($cn, $xml->msg[$i], 'rguid'); 
			$idpollingobject = getPrmValueByName($cn, $xml->msg[$i], 'idpollingobject');
			$versionhash = hash('sha1', $objectversionhash.$reportversionhash); //STU - сделал реакцию не на хеш пользователя, а на хеш версии// objectversionhash или reportversionhash триггер к смене состояния опроса
			$conditionChange = "`objectversionhash` <> '".$versionhash."'
				AND (objectversiondate_tmst< UNIX_TIMESTAMP(DATE_FORMAT('".$objectversiondate."', GET_FORMAT(DATETIME,'ISO')))
				OR reportversiondate_tmst< UNIX_TIMESTAMP(DATE_FORMAT('".$reportversiondate."', GET_FORMAT(DATETIME,'ISO'))))";
			if (getSetting('portal','polls.createarchive',0) != 0) {
				// 64088
				db_createPollingObjectsArchiveByOldVersion($cn, $idpollingobject,  $conditionChange, FALSE, TRUE);
			} else {
				db_deletePollingObjectsAnswersForNewVersion($cn, $idpollingobject,  $conditionChange );
			}

			$query .= " UPDATE `pollingobjects` SET
				`objectversion` = '".$objectversion."',
				`objectversionhash` = '".$versionhash."',
				`objectversiondate_tmst` = UNIX_TIMESTAMP(DATE_FORMAT('".$objectversiondate."', GET_FORMAT(DATETIME,'ISO'))),
			    `objectversionuhash` = '".$objectversionuhash."',
				`reportversion` = '".$reportversion."',
				`reportversiondate_tmst` = UNIX_TIMESTAMP(DATE_FORMAT('".$reportversiondate."', GET_FORMAT(DATETIME,'ISO'))),
			    `reportversionuhash`  = '".$reportversionuhash."',
				`skbranch` = @skbranch,
				`skproject` = @skproject,
				`o_guid` = '".$oguid."',
				`r_guid` = '".$rguid."' 
				WHERE `idpollingobject` = '".$idpollingobject."' AND ".$conditionChange.";";

			$query .= " INSERT INTO `pollingobjects` (`idpollingobject`, `objectversion`, `objectversionhash`, `objectversiondate_tmst`, `objectversionuhash`, `reportversion`, `reportversiondate_tmst`, `reportversionuhash`, `skbranch`, `skproject`, `o_guid`, `idobject`,  `r_guid`)
				SELECT * FROM (SELECT '".$idpollingobject."' as `idpollingobject`, 
				'".$objectversion."' as objectversion, '".$versionhash."' as objectversionhash, UNIX_TIMESTAMP(DATE_FORMAT('".$objectversiondate."', GET_FORMAT(DATETIME,'ISO'))) as objectversiondate_tmst,
				'".$objectversionuhash."' as objectversionuhash, '".$reportversion."' as reportversion, UNIX_TIMESTAMP(DATE_FORMAT('".$reportversiondate."', GET_FORMAT(DATETIME,'ISO'))) as reportversiondate_tmst,
				'".$reportversionuhash."' as reportversionuhash, @skbranch as skbranch, @skproject as skproject, '".$oguid."' as oguid, 0 as `idobject`, '".$rguid."' as rguid) prepare 
				WHERE NOT EXISTS (SELECT 1 FROM `pollingobjects` WHERE `idpollingobject` = '".$idpollingobject."' LIMIT 1);";

		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'linkuserposition'){
			$uhash = getPrmValueByName($cn, $xml->msg[$i], 'uhash');
			$query .= " DELETE up FROM userpositions up INNER JOIN users u ON up.iduser = u.iduser WHERE u.user_hash = '".$uhash."'; ";
			$positions = $xml->msg[$i]->positions;
			foreach ($positions as $key => $value) {
				foreach ($value as $object => $oguid) {
					$query .= " INSERT IGNORE INTO userpositions SELECT u.iduser,'".$oguid."' FROM users u WHERE u.user_hash = '".$uhash."'; ";
				}
			}
		}

		if ($xml->msg[$i]['type'] == 'update' && $xml->msg[$i]['name'] == 'ressourcefromtables' && !in_array(getPrmValueByName($cn, $xml->msg[$i], 'idbranch'), $excludeBranches)){
			$tablename = getPrmValueByName($cn, $xml->msg[$i], 'tablename');
			$lngid = getLanguageID(getPrmValueByName($cn, $xml->msg[$i], 'language'));
			//61467 (trimmed)
			$rfttext = nl2br(trim(getPrmValueByName($cn, $xml->msg[$i], 'text', ''))) /* 62395 */;
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch');
			$column =  getPrmValueByName($cn, $xml->msg[$i], 'columnname', '');

			if ($tablename == 'objects') {
				$oguid = getPrmValueByName($cn, $xml->msg[$i], 'guid');
				//60772
				if ($column == "objectversionfullname") {
					$table = 1111;
					$query .= " DELETE rft FROM `resourcefromtables` as rft 
						INNER JOIN `objects` as o ON rft.idrecord = o.idobject
						INNER JOIN `branches` as br ON rft.skbranch = br.skbranch AND o.skbranch = br.skbranch 
						WHERE  o.o_guid='".$oguid."' AND rft.idlanguage = ".$lngid."
						AND br.idbranch = '".$idbranch."'AND rft.idtable = ".$table." ;";
					$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `skbranch`, `rft_columnname_text`) ";
					$query .= " 	SELECT o.idobject, ".$table.", ".$lngid.", o.skbranch, '".$rfttext."' 
									FROM `objects` as o
									INNER JOIN `branches` as br ON  o.skbranch = br.skbranch 
									WHERE o.o_guid='".$oguid."' 
									AND br.idbranch = '".$idbranch."';";
				}
				if ($column == "objectversiondescription"){
					$table = 1101;
					$query .= " DELETE rft FROM `resourcefromtables` as rft 
						INNER JOIN `objects` as o ON rft.idrecord = o.idobject
						INNER JOIN `branches` as br ON rft.skbranch = br.skbranch AND o.skbranch = br.skbranch 
						WHERE  o.o_guid='".$oguid."' AND rft.idlanguage = ".$lngid."
						AND br.idbranch = '".$idbranch."'AND rft.idtable = ".$table." ;";
					$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `skbranch`, `rft_columnname_long`) ";
					$query .= " 	SELECT o.idobject, ".$table.", ".$lngid.", o.skbranch, '".$rfttext."' 
									FROM `objects` as o
									INNER JOIN `branches` as br ON  o.skbranch = br.skbranch 
									WHERE o.o_guid='".$oguid."' 
									AND br.idbranch = '".$idbranch."';";

				}
				if ($column == "name") {
					$table = 1;
					$query .= " DELETE rft FROM `resourcefromtables` as rft 
						INNER JOIN `objects` as o ON rft.idrecord = o.idobject
						INNER JOIN `branches` as br ON rft.skbranch = br.skbranch AND o.skbranch = br.skbranch 
						WHERE o.o_guid='".$oguid."' AND rft.idlanguage = ".$lngid."
						AND br.idbranch = '".$idbranch."'AND rft.idtable = ".$table." ;";

					$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `skbranch`, `rft_columnname_text`) ";
					$query .= " 	SELECT o.idobject, ".$table.", ".$lngid.", o.skbranch, '".$rfttext."' 
									FROM `objects` as o
									INNER JOIN `branches` as br ON  o.skbranch = br.skbranch 
									WHERE o.o_guid='".$oguid."' 
									AND br.idbranch = '".$idbranch."';";

					$query .= " DELETE ti FROM `titleindex` as ti 
								INNER JOIN `objects` as o ON ti.idobject = o.idobject
								INNER JOIN `branches` as br ON ti.skbranch = br.skbranch AND o.skbranch = br.skbranch 
								WHERE o.o_guid='".$oguid."' 
								AND br.idbranch = '".$idbranch."'AND `idreport` = 0 AND `idlanguage` = ".$lngid." ;";

					$query .=" INSERT INTO `titleindex` (`idobject`, `idreport`, `idlanguage`, `skbranch`, `title`, `o_title`) 
							SELECT o.idobject,0,".$lngid.", o.skbranch, '".$rfttext."','".$rfttext."' FROM `objects` as o
									INNER JOIN `branches` as br ON  o.skbranch = br.skbranch 
									WHERE o.o_guid='".$oguid."'
									AND br.idbranch = '".$idbranch."';";
				}
			}

			if ($tablename == 'reports') {
				$rguid = getPrmValueByName($cn, $xml->msg[$i], 'guid');
				//61426 
				if ($column == "reportversionfullname") {
					$table = 2111;
					$query .= " DELETE rft FROM `resourcefromtables` as rft 
						INNER JOIN `reports` as r ON rft.idrecord = r.idreport
						INNER JOIN `branches` as br ON rft.skbranch = br.skbranch AND r.skbranch = br.skbranch 
						WHERE  r.r_guid='".$rguid."' AND rft.idlanguage = ".$lngid."
						AND br.idbranch = '".$idbranch."'AND rft.idtable = ".$table." ;";
					$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `skbranch`, `rft_columnname_text`) ";
					$query .= " 	SELECT r.idreport, ".$table.", ".$lngid.", r.skbranch, '".$rfttext."' 
									FROM `reports` as r
									INNER JOIN `branches` as br ON r.skbranch = br.skbranch 
									WHERE r.r_guid='".$rguid."' 
									AND br.idbranch = '".$idbranch."';";
				}
				//60772
				if ($column == "reportversiondescription"){
					$table = 1102;
					$query .= " DELETE rft FROM `resourcefromtables` as rft 
								INNER JOIN `reports` as r ON rft.idrecord = r.idreport
								INNER JOIN `branches` as br ON rft.skbranch = br.skbranch AND r.skbranch = br.skbranch 
								WHERE r.r_guid='".$rguid."' AND rft.idlanguage = ".$lngid."
								AND br.idbranch = '".$idbranch."'AND rft.idtable = ".$table." ;";					
					$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `skbranch`, `rft_columnname_long`) ";
					$query .= " SELECT r.idreport, ".$table.", ".$lngid.", r.skbranch, '".$rfttext."' 
									FROM `reports` as r
									INNER JOIN `branches` as br ON  r.skbranch = br.skbranch 
									WHERE r.r_guid='".$rguid."' AND (r.idlanguage = ".$lngid." OR ifnull(r.idlanguage,0)=0)
									AND br.idbranch = '".$idbranch."';";
				}
				if ($column == "name") {				
					$table = 2;
					$query .= " DELETE rft FROM `resourcefromtables` as rft 
								INNER JOIN `reports` as r ON rft.idrecord = r.idreport
								INNER JOIN `branches` as br ON rft.skbranch = br.skbranch AND r.skbranch = br.skbranch 
								WHERE r.r_guid='".$rguid."' AND rft.idlanguage = ".$lngid."
								AND br.idbranch = '".$idbranch."'AND rft.idtable = ".$table." ;";					

					$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `skbranch`, `rft_columnname_text`) ";
					$query .= " SELECT r.idreport, ".$table.", ".$lngid.", r.skbranch, '".$rfttext."' 
									FROM `reports` as r
									INNER JOIN `branches` as br ON  r.skbranch = br.skbranch 
									WHERE r.r_guid='".$rguid."' AND (r.idlanguage = ".$lngid." OR ifnull(r.idlanguage,0)=0)
									AND br.idbranch = '".$idbranch."';";
				}
			}

			if ($tablename == 'sections') {
				$sguid = getPrmValueByName($cn, $xml->msg[$i], 'guid');

				$query .= "SELECT @ids := NULL; SELECT @ids := idsection FROM sections WHERE sct_guid='".$sguid."';";
				if ($deleteold) {
					$query .= " DELETE FROM `resourcefromtables` WHERE idrecord = @ids AND idtable = 3 AND idlanguage = ".$lngid.";";
				}
				$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_text`) ";
				$query .= " VALUES (@ids, 3, ".$lngid.", '".$rfttext."');";
			}

			if ($tablename == 'links') {
				$query .= " SELECT @idlink := NULL;  SELECT @idlink := idlink FROM links WHERE lnk_guid='".getPrmValueByName($cn, $xml->msg[$i], 'guid')."';";
				if ($deleteold) {
					$query .= " DELETE FROM `resourcefromtables` WHERE idrecord = @idlink AND idtable = 4 AND idlanguage = ".$lngid.";";
				}
				$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_text`) ";
				$query .= " VALUES (@idlink, 4, ".$lngid.", '".$rfttext."');";
			}

			if ($tablename == 'statever') {
				if ($deleteold) {
					$query .= " DELETE FROM `resourcefromtables` WHERE idrecord = ".getPrmValueByName($cn, $xml->msg[$i], 'guid')." AND idtable = 5 AND idlanguage = ".$lngid.";";
				}
				$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_text`) ";
				$query .= " VALUES (".getPrmValueByName($cn, $xml->msg[$i], 'guid').", 5, ".$lngid.", '".$rfttext."');";
			}

			if ($tablename == 'languages') {
				$id  = getLanguageID(getPrmValueByName($cn, $xml->msg[$i], 'id'));
				$query .= " DELETE FROM `resourcefromtables` WHERE idrecord = ".$id." AND idtable = 0 AND idlanguage = ".$lngid.";";
				$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_text`) ";
				$query .= " VALUES (".$id.", 0, ".$lngid.", '".$rfttext."');";
			}

			if ($tablename == 'users') {
				$query .= " SELECT @iduser := NULL;  SELECT @iduser := iduser FROM users WHERE user_hash = '".getPrmValueByName($cn, $xml->msg[$i], 'uhash')."';";
				$query .= " DELETE FROM `resourcefromtables` WHERE idrecord = @iduser AND idtable = 6 AND idlanguage = ".$lngid.";";
				$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_text`) ";
				$query .= " VALUES (@iduser, 6, ".$lngid.", '".$rfttext."');";
			}	

			if ($tablename == 'branch') {
				$query .= " SELECT @skbranch := NULL;  SELECT @skbranch := skbranch FROM branches WHERE idbranch = '".getPrmValueByName($cn, $xml->msg[$i], 'idbranch')."';";
				$query .= " DELETE FROM `resourcefromtables` WHERE idrecord = @skbranch AND idtable = 7 AND idlanguage = ".$lngid.";";
				$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_text`) ";
				$query .= " VALUES (@skbranch, 7, ".$lngid.", '".$rfttext."');";
			}	

			if ($tablename == 'polltype') {
				$column =  getPrmValueByName($cn, $xml->msg[$i], 'columnname', '');
				$table = (mb_strtolower($column) == "description" ? 801 : 8);
				$query .= " SELECT @skpolltype := NULL;  SELECT @skpolltype := skpolltype FROM polltypes WHERE idpolltype = '".getPrmValueByName($cn, $xml->msg[$i], 'idpolltype')."';";
				$query .= " DELETE FROM `resourcefromtables` WHERE idrecord = @skpolltype AND idtable = ".$table." AND idlanguage = ".$lngid.";";
				if (mb_strtolower($column) == "description") {
					$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_long`) ";
				} else {
					$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_text`) ";
				}
				$query .= " VALUES (@skpolltype, ".$table.", ".$lngid.", '".$rfttext."');";
			}
				
			if ($tablename == 'polltypequestion') {
				$query .= " SELECT @skpolltypequestion := NULL;  SELECT @skpolltypequestion := skpolltypequestion FROM polltypequestions WHERE idpolltypequestion = '".getPrmValueByName($cn, $xml->msg[$i], 'idpolltypequestion')."';";
				$query .= " DELETE FROM `resourcefromtables` WHERE idrecord = @skpolltypequestion AND idtable = 9 AND idlanguage = ".$lngid.";";
				$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_text`) ";
				$query .= " VALUES (@skpolltypequestion, 9, ".$lngid.", '".$rfttext."');";
			}

			if ($tablename == 'polltypequestionselectvalue') {
				$query .= " SELECT @skpolltypequestionselectvalue := NULL;  SELECT @skpolltypequestionselectvalue := skpolltypequestionselectvalue FROM polltypequestionselectvalues WHERE idpolltypequestionselectvalue = '".getPrmValueByName($cn, $xml->msg[$i], 'idpolltypequestionselectvalue')."';";
				$query .= " DELETE FROM `resourcefromtables` WHERE idrecord = @skpolltypequestionselectvalue AND idtable = 90 AND idlanguage = ".$lngid.";";
				$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_text`) ";
				$query .= " VALUES (@skpolltypequestionselectvalue, 90, ".$lngid.", '".$rfttext."');";
			}

			if ($tablename == 'project') {
				$column = getPrmValueByName($cn, $xml->msg[$i], 'columnname', '');
				$table = (mb_strtolower($column) == "description" ? 1001 : 10);
				$query .= " SELECT @skproject := NULL;  SELECT @skproject := skproject FROM projects WHERE idproject = '".getPrmValueByName($cn, $xml->msg[$i], 'idproject')."';";
				$query .= " DELETE FROM `resourcefromtables` WHERE idrecord = @skproject AND idtable = ".$table." AND idlanguage = ".$lngid.";";
				if (mb_strtolower($column) == "description") {
					$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_long`) ";
				} else {
					$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_text`) ";
				}

				$query .= " VALUES (@skproject, ".$table.", ".$lngid.", '".$rfttext."');";
			}

			if ($tablename == 'pollingobject') {
				if ($column == 'name'){
					$table = 11;
					$query .= " SELECT @skpollingobject := NULL;  SELECT @skpollingobject := skpollingobject FROM pollingobjects WHERE idpollingobject = '".getPrmValueByName($cn, $xml->msg[$i], 'idpollingobject')."';";
					$query .= " DELETE FROM `resourcefromtables` WHERE idrecord = @skpollingobject AND idtable = ".$table." AND idlanguage = ".$lngid.";";
					$query .= " INSERT IGNORE INTO `resourcefromtables` (`idrecord`, `idtable`, `idlanguage`, `rft_columnname_text`) ";
					$query .= " VALUES (@skpollingobject, ".$table.", ".$lngid.", '".$rfttext."');";
				}
			}

		}
		//mail
		if ($xml->msg[$i]['type'] == 'createmail' ){ 
			$type = getPrmValueByName($cn, $xml->msg[$i], 'type', NULL);
			$idpolltype = getPrmValueByName($cn, $xml->msg[$i], 'idpolltype', '-'); 
			// 61490
			$idproject = getPrmValueByName($cn, $xml->msg[$i], 'idproject', '-');
			$idbranch = getPrmValueByName($cn, $xml->msg[$i], 'idbranch', '0');			
			if(strcasecmp($type, 'pollNew') == 0){
				db_createMailQueue_NewPoll($cn, $idpolltype, $idbranch, ($idproject == '-' ? NULL : $idproject));
			} else if(strcasecmp($type, 'pollNewAnalyst') == 0){
				$uhash = getPrmValueByName($cn, $xml->msg[$i], 'uhash');
				db_createMailQueue_NewPollAnalyst($cn, $idpolltype, $idbranch, ($idproject == '-' ? NULL : $idproject), $uhash);
			} else if(strcasecmp($type, 'pollNewAdmin') == 0){
				db_createMailQueue_NewPollAdmin($cn, $idpolltype, $idbranch, ($idproject == '-' ? NULL : $idproject));
			} else if(strcasecmp($type, 'pollContainsErrors') == 0){
				$uhash = getPrmValueByName($cn, $xml->msg[$i], 'uhash');
				db_createMailQueue_pollContainsErrorsAnalyst($cn, $idpolltype, $idbranch, ($idproject == '-' ? NULL : $idproject), $uhash);
			} else if(strcasecmp($type, 'pollContainsErrorsAdmin') == 0){
				db_createMailQueue_pollContainsErrorsAnalystAdmin($cn, $idpolltype, $idbranch, ($idproject == '-' ? NULL : $idproject));
			}
		}		
		if ($xml->msg[$i]['type'] == 'sendmail' ){ 
			$type = getPrmValueByName($cn, $xml->msg[$i], 'type', NULL);
			$limit = getPrmValueByName($cn, $xml->msg[$i], 'limit', NULL);
			sendMailsFromQueue(db_getMailQueueType($cn, $type), $limit);
		}		
	}
}
$query .= " SELECT 'ok' as result;";

if (isset($_REQUEST['showruntime'])) {
	$start_time = microtime();
	$start_array = explode(" ",$start_time);
	$start_time = $start_array[1] + $start_array[0];
}

if ($cn->multi_query($query)) {
  do {
    // fetch results
    if ($result = $cn->use_result()) {
        while ($row = $result->fetch_row()) {
        	if ($row[0] == 'ok')
            echo 'result=ok';
        }
        $result->close();
    }

    if (!$cn->more_results()) {
      break;
    }
    if (!$cn->next_result()) {
      // report error
      logmessage("Query - ".$query);
      logmessage("Error - ".mysqli_errno($cn));
      logmessage(mysqli_error($cn));
      echo 'error=['.mysqli_errno($cn).'] '.mysqli_error($cn);
      break;
    }
  } while (true);
} else {
  logmessage("Query - ".$query);
  logmessage("Error - ".mysqli_errno($cn));
  logmessage(mysqli_error($cn));
  echo 'error=['.mysqli_errno($cn).'] '.mysqli_error($cn);
}

if (isset($_REQUEST['showruntime'])) {
	$end_time = microtime();
	$end_array = explode(" ",$end_time);
	$end_time = $end_array[1] + $end_array[0];
	$time = $end_time - $start_time;
	printf("Query execute in %f sec",$time);
}

if (isset($_REQUEST['showquery'])) {
	echo "<br/>";
	echo $query;
}

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