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

if ( getSetting('portal','useRights',0) == 0 || getSetting('portal','polls.createarchive',0) != 1){
	$url = getCurPageURLWO()."/personal.php";
   header("Location: ".$url); 
   ob_end_flush();
   exit;
   
}

checkUserAndRedirectToLogin();
$cn = db_connect();
if (isset($_REQUEST['lang']))
{
	$lng = 'lang='.$_REQUEST['lang'];
	$contlngid = db_getLanguageID($cn, $_REQUEST['lang']);
	$contlng = $lng;
	$contlngid = $contlngid;
} else {
	$contlng = 'lang='.db_getLanguageShortByID($cn, $_SESSION['user_idlanguagecontent']);
	$contlngid = $_SESSION['user_idlanguagecontent'];
}

if (!isset($_REQUEST['idpollingobjectarchive']) || !isset($_REQUEST['skpolltype']) || !is_numeric($_REQUEST['idpollingobjectarchive']) || !is_numeric($_REQUEST['skpolltype'])) {
	header("Location: ".getCurPageURLWO()."/pagenotfound.php?url=".getCurPageWithEncodeParams());
	ob_end_flush();
	exit;
}

function bsreportParser($buff){
	$lpos = strpos($buff, '<bsportal:report');
	while(!($lpos === FALSE )){
		$rpos = strpos($buff, '</bsportal:report>', $lpos + 16); // slide from start tag <bsportal:report
		$linksource = substr($buff, $lpos, $rpos - $lpos + 18);
		$link = str_replace('&', '&amp;', $linksource );
		$linkHtml = "";
		$patern = substr($link, 0, 4);
		$xmlstr = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'.str_replace('bsportal:report', 'bsrep', $link);
		$xml = simplexml_load_string($xmlstr);
		$title = $xml;
		$elem = $xml->xpath('//bsrep');
		$i_guid = '' ;
		if (isset($elem[0]["oguid"])) {
			$i_guid = $elem[0]["oguid"];
		}
		$i_rguid = '';
		if ( isset ($elem[0]["rguid"])){
			$i_rguid = $elem[0]["rguid"];
		}
		$linkHtml .= $title;

		if (strpos($link, 'coords="') === FALSE){
				$linkHtml .= $title;
		} else {
				$linkHtml .= '<area shape="rect" coords="';
				$linkHtml .= $elem[0]["coords"].'" ';
				$linkHtml .= ' href="javascript:void()"';
				$linkHtml .= 'alt=" ';
				$linkHtml .= $title;
				$linkHtml .= '" /> ';
			}
		$buff = str_replace($linksource, $linkHtml, $buff);
		$lpos = strpos($buff, '<bsportal:report');
	}
	return $buff;
}

$useRht = getSetting('portal','useRights', 0);
if ( $useRht == 1 && !IsUserLogin()){
	header("Location: ".getCurPageURLWO()."/login.php?returl=".getCurPageWithEncodeParams());
	ob_end_flush();
	exit;
} else {
	header("Content-Type: text/html; charset=utf-8"); //9875
	$flroot = getSetting('storage','arcroot',realpath(dirname(__FILE__)).'/arc/');
	$userids = GetUserIDs();
	$arc = db_getPollingObjectsArchive($cn, $_REQUEST['idpollingobjectarchive'], $_REQUEST['skpolltype'], $userids[0], $contlngid);
	if ($arc === NULL || sizeof($arc) == 0 || sizeof($arc[0]) == 0) {
		header("Location: ".getCurPageURLWO()."/pagenotfound.php?url=".getCurPageWithEncodeParams());
		ob_end_flush();
		exit;
	}
	$oguid = $arc[0]['o_guid'];
	$rguid = $arc[0]['r_guid'];
	mb_internal_encoding("UTF-8");
		
	if (db_isLanguageValidByID($cn, $contlngid)){
		$lang_short = db_getLanguageShortByID($cn, $contlngid);
	} else {
		$lang_short = 'falseLang';
	}
	$fname = nameReportWithBranchAndLanguage($flroot, $oguid, $rguid, $lang_short, $arc[0]['objectversionhash']);
	if (!is_readable($fname)){
		$fname = nameReportWithBranchAndLanguage($flroot, $oguid, $rguid, '', $arc[0]['objectversionhash']);
	}
	if (!is_readable($fname)){
		db_disconnect($cn);
		header("Location: ".getCurPageURLWO()."/pagenotfound.php?url=".getCurPageWithEncodeParams());
		ob_end_flush();
		logmessage("Trying read not existsing file : ".$fname);
		exit;
	} else {
		$fhr = fopen($fname,  'r');
			$i_guid = '';
			$patern = '';
			$lpos = 0;
			$fpos = 0;
			$dpos = 0;
			$rpos = 0;
			$elem = null;
			$title = '';
			$modepr = (isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'print' );
			$hlwset = isset($_REQUEST['hlwords']);
			/*proxy for imagies*/
			$img_ext = array('.jpeg','.jpg','.gif','.png','.bmp','.ico','.tiff');
			echo '<style>.inline-report{margin: 0px;} #archive-info {width:100%;height:30px;background: #eef2f7;margin-top: 0px; margin-bottom: 15px; padding-top: 5px; padding-bottom: 5px; font-size: 11px; font-family: Arial, sans-serif;}</style>';
			echo '<div id="archive-info" ><div style="vertical-align: middle;padding-left: 15px;">'.getResourceByLang('field.poll.objectversion').': '.$arc[0]['objectfullversion'].', '.$arc[0]['objectversiondate'].'</div><div style="vertical-align: middle;padding-left: 15px;padding-top: 5px;">'.getResourceByLang('field.poll.answer').': '.$arc[0]['answer'].', '.$arc[0]['answerdate'].'</div></div>';
			echo '<div id="reportarchivecontainer" style="min-height: 100%; position: relative; margin: 10px;">';
			while (!feof($fhr)) {
				$buff = fgets($fhr);
				bsreportParser($buff);
               // add inline-report class to a-proccesor
				if ( strpos($buff, '<body') !== false ){
					$buff = str_replace('<body', '<body class="inline-report" ', $buff );
				}
               // add icon to head
				if ( strpos($buff, '<head>') !== false ){
					$buff = str_replace('<head>', '<head><link rel="shortcut icon" href="favicon.ico" />', $buff );
				}
               // add icon to head
				if ( strpos($buff, '<head>') !== false ){
					$buff = str_replace('<head>', '<head><link rel="shortcut icon" href="favicon.ico" />', $buff );
				}
               				
				/*proxy for imagies*/
				if((preg_match("/src=[^1]data/is", $buff) || preg_match('/src=[^1]\/data/is', $buff)) && preg_match("/(".implode('|', $img_ext).")/is", $buff)){
					$imlpos = strpos($buff, 'src=');
					$folderext = substr($buff, strpos($buff, 'data/') + 5 /* 5 is length of 'data/' */ );
					$folderext = substr($folderext, 0, strpos($folderext, '/') );
					$cntxtfe = explode("_", $folderext);
					if ( sizeof($cntxtfe) == 2 && strpos($folderext, ".") > 0) {
						$cntxtfe = explode(".", $folderext);
						$folderext = ".".$cntxtfe[1];
					} else if ( sizeof($cntxtfe) == 2 && strpos($folderext, "-") > 0) {
						$cntxtfe = explode("-", $folderext);
						$folderext = "-".$cntxtfe[1];
					} else if ( sizeof($cntxtfe) == 3 ) {
						$folderext = "_".$cntxtfe[2];
					} else {
						$folderext = "";
					}
					$imfpos = strpos($buff, $folderext.'/');
					$imglink= 'imgarchive.php?'.$contlng.'&dboguid='.urlencode($oguid).'&oguid='.urlencode($oguid).'&rguid='.urlencode($rguid).'&folderext='.$folderext.'&objectversionhash='.$arc[0]['objectversionhash'].'&name=';
					$newbuff = substr($buff, 0, $imlpos + 5 /* 5 is length of 'src="' */ ).$imglink.substr($buff, $imfpos + strlen($folderext) + 1);
					$buff = $newbuff;
				}
				/*proxy for imagies*/
				$fpos = strpos($buff, '<bsportal:file');
				if (!($fpos === false )) {
					echo substr($buff, 0, $lpos);
					$rpos = strpos($buff, '</bsportal:file>', $lpos + 14); // slide from start tag <bsportal:file
					$link = substr($buff, $fpos, $rpos - $fpos + 16);
					$patern = substr($link, 0, 4);
					$xmlstr = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'.str_replace('bsportal:file', 'bsfile', $link);
					$xml = simplexml_load_string($xmlstr);
					$title = $xml;
					$elem = $xml->xpath('//bsfile');
					$i_guid = $elem[0]["oguid"];
					$i_file = $elem[0]["file"];
					if (( $useRht == 0 && (db_isObjectExits($cn, $i_guid, $skbranch) )) || (  $useRht == 1 && (db_getUserRightsToObject($cn, $userids, $i_guid, $skbranch)))) {
						echo '<a class="self-report-link" href="';
						echo getCurPageSubFolders().'/downloadreportfile.php?'.$contlng.'&oguid='.$i_guid.'&idbranch='.$idbranch.'&file='.$i_file;
						echo '">';
						echo $title;
						echo '</a>';
					} else {
						echo $title; 
					}
				} else 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 );
					echo str_replace('<bsportal:xlinkhref', '<a class="self-report-link" xlink:href = "javascript:void()" onclick="return false" style="cursor: default; text-decoration: none;" ', $buff );
				} else if (strpos($buff, '</bsportal:xlinkhref>') > -1 ) {
					echo str_replace('</bsportal:xlinkhref>', '</a>', $buff );
				} else {
					if ( strpos($buff, '</body>') === false ){
						echo $buff;
					} else {
						echo '<br/>';
						echo '</body>';
					}
				}

			}
			fclose($fhr);
			echo '</div>';

			echo '<script src="js/libs/jquery.js"></script>';
			echo '<script src="js/svgclickarea.js" charset="utf-8"></script>';
			echo '<script src="js/a-processor.js" charset="utf-8"></script>';

			if (
                (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') !== false) ||
                (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false) ||
                (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false)
			)
			{//10235
				echo '<script src="js/svgzoom.js" charset="utf-8"></script>';
			} else {  //9949
				echo '<script src="js/svgzoom_ie.js" charset="utf-8"></script>';
			}
			
			db_disconnect($cn);
			unset($userids);
			ob_end_flush();
			exit;
		}
}
ob_end_flush();
?>