<?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/mail.inc'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__).'/../').'/include/mail.inc');
} else {
	include_once(realpath(dirname(__FILE__).'/../').'/include/mail.inc');
}

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

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

if (!isset($_REQUEST['oguid']) || !isset($_REQUEST['rguid']) )
{
	die('not enough parameters - oguid, rguid or languageid');
} 

$oguid = $_REQUEST['oguid'];
$rguid = $_REQUEST['rguid'];
$language = (isset($_REQUEST['language']) ? $_REQUEST['language'] : "");
$idbranch = (isset($_REQUEST['idbranch']) ? $_REQUEST['idbranch'] : "");

include_once(realpath(dirname(__FILE__).'/../').'/include/strip_tags_smart.inc');
if (isset($_REQUEST['create'])){
	$crdate = $_REQUEST['create'];
} else {
	$crdate = -1;
}

if (isset($_REQUEST['expire'])){
	$exp = $_REQUEST['expire'];
} else {
	$exp = -1;
}
if (strlen($oguid) > 0 && strlen($rguid) > 0 ) {
	$cn = db_connect();
	$langid = (strlen($language) > 0 ? db_getLanguageID($cn, $language) : 0);
	$flroot = getSetting('storage','fileroot',realpath(dirname(__FILE__).'/../').'/data/');
	if (strlen($idbranch) > 0) {
		$skbranch = db_getSKBranch($cn,$idbranch);	
	} else {
		$skbranch = db_getMainSKBranch($cn);	
		$idbranch = db_getMainIDBranch($cn);	
	}
	$skbranch = (strlen($idbranch) > 0 ? db_getSKBranch($cn,$idbranch) : db_getMainIDBranch($cn));	
	$ido = db_getIDObjectByGuid($cn, $oguid, $skbranch);
	$idr = db_getIDReportByGuid($cn, $rguid, $langid, $skbranch);
	$lang_short = ($langid != 0 ? db_getLanguageShortByID($cn, $langid): "");
	$fname = nameReportWithBranchAndLanguage($flroot, $oguid, $rguid, $lang_short, $idbranch);

	if (is_readable($fname)){
		$cntnt = file_get_contents($fname);
		$trans = array("'" => "", "&#63;" => '&', "&amp;" => '&', "&gt;" => '>', "&lt;" => '<', "&quot;" => '"',  "&nbsp;" => "", ";" => "", " 1 " => "", " 2 " => "", " 3 " => "", " 4 " => "", " 5 " => "", " 6 " => "", " 7 " => "", " 8 " => "", " 9 " => "");
		$cntnt =  mb_strtolower(
				strip_tags_smart(
				$cntnt,
				null,
				true,
				array('script', 'style', 'map', 'iframe', 'frameset', 'object', 'applet', 'comment', 'button', 'textarea', 'select'),
				array('p', 'td', 'th', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'form', 'title', 'pre')
		),"UTF-8");
		$cntnt = strtr($cntnt, $trans);
		$cntnt = mysqli_real_escape_string($cn, prepareTextToTree(str_replace(';', '', $cntnt)));
		$langid = ''.($lang_short == null ? 'null' : db_getLanguageID($cn, $lang_short));
		if ( $ido > 0 && $idr > 0) {
			db_runQuery($cn, 'SET @@session.time_zone = "+00:00";');
			db_runQuery($cn, "DELETE FROM `reportindex` WHERE `idobject` = ".$ido." AND `idreport` = ".$idr." AND skbranch = ".$skbranch.";");
			$query = "INSERT INTO `reportindex` (`idobject`,`idreport`, `idlanguage`, `skbranch`, `body`,`ri_expirationdate_tmst`, `ri_creationdate_tmst`)";
			$query .= "SELECT ".$ido.",".$idr.",IF (EXISTS(SELECT 1 FROM reports WHERE ifnull(idlanguage,0) <> 0 AND r_guid = '".$rguid."' LIMIT 1), ".$langid.", 0), ".$skbranch.", '".$cntnt."',";
			if($crdate <= 0){
				$query .= "NULL, UNIX_TIMESTAMP(NOW())";
			} else {
				$query .= ($exp <= 0 ? "NULL," : "UNIX_TIMESTAMP(DATE_ADD('".$crdate."',INTERVAL ".$exp." SECOND)),");
				$query .= "UNIX_TIMESTAMP('".$crdate."');";
			}
			db_runQuery($cn, $query);
			if (strlen(trim($cntnt)) > 3) {
				db_runQuery($cn, "DELETE FROM `titleindex` WHERE `idobject` = ".$ido." AND `idreport` = ".$idr." AND skbranch = ".$skbranch.";");
				$ln_arr = db_getLanguages($cn);
				$title = "";
				foreach ($ln_arr as $value){
					$o_title = mb_strtolower(db_getRecourceFromTable($cn, $ido, 1, $value['idlanguage'], $skbranch ),"UTF-8");
					$title = $o_title." ".mb_strtolower(db_getRecourceFromTable($cn, $idr, 2, $value['idlanguage'], $skbranch ),"UTF-8");
					$o_title = mysqli_real_escape_string($cn, prepareTextToTree($o_title));
					$title = mysqli_real_escape_string($cn, prepareTextToTree($title));
					db_runQuery($cn, "INSERT INTO `titleindex` (`idobject`, `idreport`, `idlanguage`, `skbranch`, `title`, `o_title`) VALUES (".$ido.",".$idr.",".$value['idlanguage'].", ".$skbranch.", '".$title."','".$o_title."');");
				}
				db_runQuery($cn, "UPDATE `reportindex` SET `body`= REPLACE(REPLACE(`body`, '\r\n', ' '), '\n\r', ' ') WHERE `idobject` = ".$ido." AND `idreport` = ".$idr." AND skbranch = ".$skbranch.";");
				db_runQuery($cn, "UPDATE `reportindex` SET `body`= REPLACE(REPLACE(`body`, ':', ' '), '&&', '&') WHERE `idobject` = ".$ido." AND `idreport` = ".$idr." AND skbranch = ".$skbranch.";");
				db_runQuery($cn, "UPDATE `reportindex` SET `body`= REPLACE(REPLACE(`body`, '\r', ' '), '\n', ' ') WHERE `idobject` = ".$ido." AND `idreport` = ".$idr." AND skbranch = ".$skbranch.";");
				db_runQuery($cn, "UPDATE `reportindex` SET `body`= REPLACE(REPLACE(`body`, '  ', ' '), '  ', ' ') WHERE `idobject` = ".$ido." AND `idreport` = ".$idr." AND skbranch = ".$skbranch.";");
				db_runQuery($cn, "UPDATE `reportindex` SET `body`= REPLACE(REPLACE(`body`, ';;', ';'), '  ', ' ') WHERE `idobject` = ".$ido." AND `idreport` = ".$idr." AND skbranch = ".$skbranch.";");
			}
		}

		if (isset($_REQUEST['copyrights'])){
			foreach (objectsGuidInReport($fname) as $oguid_to) {
				$ido_to = db_getIDObjectByGuid($cn, $oguid_to, $skbranch);
				if (db_isValidToCopyRightsObjects($cn, $ido_to))
					db_copyRightsObjects($cn, $skbranch, $ido, $ido_to);
			}
		}

		$emarr = db_getReportsUsersQuery($cn, $oguid, $rguid);
		$size = sizeof($emarr);
		echo ' send mails to '.$size.' users ';
		if ($size > 0) {
			$portal_url = GetSetting('portal','url',getCurPageURLWO());
			for($i=0; $i<$size; $i++){
				$userlang = $emarr[$i]['lang_short'];
				$lngid = $emarr[$i]['user_idlanguagecontent'];
				$objname = ' '.db_getObjectName($cn, $oguid, $lngid).' ('.db_getReportName($cn, $rguid, $lngid).') ';
				$url = $portal_url."/businessmodel.php?".(isset($_REQUEST['language']) ? "lang=".$_REQUEST['language']."&" : "" /*66020*/)."oguid=".$oguid."&rguid=".$rguid;
				$usrname = db_getUserNameByID($cn, $emarr[$i]['iduser'], $emarr[$i]['user_idlanguagecontent']);
				if (sendReportUploadedMessage($emarr[$i]['user_email'], str_replace('portal:name', $objname, getResourceByLang('email.reportuploaded.subject', $userlang)), $objname, $url, $userlang, $usrname) ){
					db_deleteReportsUsersQuery($cn, $emarr[$i]['iduser'], $oguid, $rguid);
				} else {
					logmessage( 'Failed to send email to user '.$usrname);
				}

			}
		}
		db_disconnect($cn);
		echo '[done]';
	} else if (strlen($oguid) > 0) {
		$ido = db_getIDObjectByGuid($cn, $oguid, $skbranch);
		db_runQuery($cn, "DELETE FROM `titleindex` WHERE `idobject` = ".$ido." AND `idreport` = 0 AND skbranch=".$skbranch.";");
		$ln_arr = db_getLanguages($cn);
		$title = "";
		foreach ($ln_arr as $value){
			$o_title = mb_strtolower(db_getRecourceFromTable($cn, $ido, 1, $value['idlanguage'], $skbranch ),"UTF-8");
			$r_title = '';
			if ($rguid > 0){
				$idr = db_getIDReportByGuid($cn, $rguid);
				$r_title = mb_strtolower(db_getRecourceFromTable($cn, $idr, 2, $value['idlanguage'], $skbranch ),"UTF-8");
			}
			$title = $o_title + ' ' + $r_title;
			$o_title = mysqli_real_escape_string($cn, $o_title);
			$title = mysqli_real_escape_string($cn, $title);
			db_runQuery($cn, "INSERT INTO `titleindex` (`idobject`, `idreport`, `idlanguage`, `skbranch`, `title`, `o_title`) VALUES (".$ido.",0,".$value['idlanguage'].", ".$skbranch.", '".$title."','".$o_title."');");
		}
		db_disconnect($cn);
		echo '[warning] file "'.$fname.'" was not found! titleindex rebuild only ';
	} else  {
		echo '[error]';
		logmessage("Error: indexreport.php - No such file or directory in ".$fname."!");
	}
}

function objectsGuidInReport($file){
	//return all oguids from report file	
	$result = [];
	try {
		if ($fhr = fopen($file,  'r')){
			while (!feof($fhr)) {
				$buff = fgets($fhr);
				$lpos = strpos($buff, '<bsportal:report');
				$fpos = strpos($buff, '<bsportal:file');
				$xlinkrefpos = strpos($buff, 'bsportal:xlinkhref');
				if (!($lpos === false )) {
					$rpos = strpos($buff, '</bsportal:report>', $lpos + 16); // slide from start tag <bsportal:report
					$link = str_replace('&', '&amp;', substr($buff, $lpos, $rpos - $lpos + 18) );
					$xmlstr = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'.str_replace('bsportal:report', 'bsrep', $link);
					$xml = simplexml_load_string($xmlstr);
					$elem = $xml->xpath('//bsrep');
					$i_guid = '' ;
					if (isset($elem[0]["oguid"])) {
						$i_guid = ''.$elem[0]["oguid"];
					}
					if ( $i_guid != '' ) array_push($result, $i_guid);
					
				} 
				if (strpos($buff, '<bsportal:xlinkhref') > -1) {
					$ogpos = strpos($buff, 'oguid="') + 7 /* leng of 'oguid="' */;
					$ogpos_end = strpos($buff, '"', $ogpos );
					$i_guid = substr($buff, $ogpos,  $ogpos_end - $ogpos );
					if ( $i_guid != '' ) array_push($result, $i_guid);
				} 
			}
		}
	} catch (Exception $e) {
		logmessage("objectsGuidInReport error - ".$e->getMessage());
	} finally {
		if (isset($fhr)) fclose($fhr);	
		return array_unique($result);	
	}	
}

ob_end_flush();
?>