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

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


checkUserAndRedirectToLogin();

$cn = db_connect();
$lng = ( isset($_REQUEST['lang']) ? 'lang='.$_REQUEST['lang'] : '');
$lngid = db_getLanguageID($cn, getLanguage());
$lngshort = db_getLanguageShortByID($cn, $lngid);
$contlng = $lng;
$contlngid = $lngid;
if (getSetting('portal','useRights',0) == 1){
	$contlng = 'lang='.db_getLanguageShortByID($cn, $_SESSION['user_idlanguagecontent']);
	$contlngid = $_SESSION['user_idlanguagecontent'];
}

$usr_arr = GetUserIDs();
if ( GetSetting('portal','useRights',0) == 0 ){
	if( !IsUserLogin() ){
		header("Location: ".getCurPageURLWO()."/businessmodel.php");
		ob_end_flush();
		exit;
	}
} else {
	if( !IsUserLogin() ){
		header("Location: ".getCurPageURLWO()."/login.php?returl=adminpollobject.php");
		ob_end_flush();
		exit;
	}
	$cn = db_connect();
	if (!isUserAdmin() && !db_isUserAdminToPolls($cn, $usr_arr)){ 
		header("Location: ".getCurPageURLWO()."/personal.php");
		ob_end_flush();
		exit;
	}
}

$id = 0;

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

if (!db_isUserAdminToPollBySKpollingobject($cn, $usr_arr, $_REQUEST['skpolltype'], $_REQUEST['skpollingobject'])){
	header("Location: ".getCurPageURLWO()."/notenoughrights.php?url=".getCurPageWithEncodeParams());
	ob_end_flush();
	$oguid = null;
	exit;
}

$pollingobject = db_getPollingObject($cn, $_REQUEST['skpollingobject']);

if (!is_array($pollingobject) || sizeof($pollingobject) == 0 || sizeof($pollingobject[0]) == 0) {
	header("Location: ".getCurPageURLWO()."/pagenotfound.php?url=".getCurPageWithEncodeParams());
	ob_end_flush();
	$oguid = null;
	exit;
}

$objectName = db_getObjectName($cn, $pollingobject[0]['o_guid'], $contlngid, $pollingobject[0]['skbranch']);
$reportName = ''.$pollingobject[0]['r_guid'];
if ($pollingobject[0]['o_guid'] !== $pollingobject[0]['r_guid']) {
	$reportName = db_getReportName($cn, $pollingobject[0]['r_guid'], $contlngid, $pollingobject[0]['skbranch']);
}

$objectfullname = $objectName.' ('.$reportName.')';
$version = db_getObjectFullVersion($cn, $pollingobject[0]['o_guid'], $pollingobject[0]['skbranch'], $contlngid);
$versiondescription = db_getObjectVersionDescription($cn, $pollingobject[0]['o_guid'], $pollingobject[0]['skbranch'], $contlngid);
$versiondescription = str_replace("</p>", "", str_replace("<p>", "", $versiondescription));
$versiondescription = str_replace("</P>", "", str_replace("<P>", "", $versiondescription));
$idbranch = db_getIDBranch($cn, $pollingobject[0]['skbranch']);
?>
			<?php echo ''.db_getPolltypeNameBySK($cn, $_REQUEST['skpolltype'], $contlngid).': '; if (isset($pollingobject[0]['skproject']) && $pollingobject[0]['skproject'] !== '0') { echo db_getProjectName($cn, $pollingobject[0]['skproject'], $contlngid);} else { echo db_getBranchName($cn, $pollingobject[0]['skbranch'], $contlngid);} ?> \ <span class="box-poll-bread-crumbs-objectfullname-span"> <?php echo $objectfullname;?></span> 
			<br/>
			<br/>
			<div id="box-frame-header-left">        
                <div>
                    <div class="objectversion-float-left"><?php echo $version ?></div> 
                </div>
                <div id="box-frame-description-title"><?php getResource("title.pollobjectanswer.objectversion");?>:</div>
                <div id="box-frame-description-versiondescription" class="objectversion-description">
                	<?php echo $versiondescription; ?>
                </div>
        	</div>
			<br/>
			<br/>
			<style>
				.c1a-1a-1a-1_fix_fdw--q {
					background-color: #568fe2;
					color: #ffffff;
					text-shadow: #416dac 1px 1px 0px;
					border: 1px solid black;
					padding: 9px 20px 9px 20px;
					font-weight: normal;
					text-align: left;
				}
				.c1a-1a-1a-1_fix_fdw--q--t {
					border-collapse: collapse;
					font-family: Arial, sans-serif !important;
					font-size: 11px !important;
					vertical-align: top;
				}

				.c1a-1a-1a-1_fix_fdw--q--t-e {
					padding: 9px 20px 9px 20px;
					border: 1px solid black;
				}
				.c1a-1a-1a-1_fix_fdw--q--t-e p {
					margin-left: 0px;
				}

			</style>
            <table cellspacing="0" style="width: 100%" class="c1a-1a-1a-1_fix_fdw--q--t">
				<tr>
					<th class="c1a-1a-1a-1_fix_fdw--q" style="width:30%"><? echo getResourceByLang('field.poll.user'); ?></th>
					<th class="c1a-1a-1a-1_fix_fdw--q" style="width:20%"><? echo getResourceByLang('field.poll.answer'); ?></th>
					<th class="c1a-1a-1a-1_fix_fdw--q" style="width:50%"><? echo getResourceByLang('field.poll.remark'); ?></th>
                </tr>
                        <?php 
							$answersvals = [];
							$answers = db_getPolltypeQuestionAnswers($cn, $_REQUEST[ "skpollingobject" ], $_REQUEST[ "skpolltype" ] );
							for($j=0; $j<sizeof($answers); $j++){
								$question = db_getPolltypeQuestion($cn, $_REQUEST[ "skpollingobject" ], $_REQUEST[ "skpolltype" ], $answers[ $j ]['iduser'], $contlngid );
								$ansval = '';
							if ($question[0]['idpolltypequestiontype'] == 1){
									$ansval = $question[0]['rft_columnname_text'];
							} else if ($question[0]['idpolltypequestiontype'] == 2 && is_array($answers[$j]) && sizeof($answers[$j]) > 0 && isset($answers[$j]['uav_value']) && $answers[$j]['uav_value'] !== NULL && $answers[$j]['uav_value'] > 0  ){
								$ansval = db_getQuestionSelectValueByID($cn, $question[0]['skpolltypequestion'], $answers[$j]['uav_value'], $contlngid );
                            }
                                echo "<tr class='c1a-1a-1a-1_fix_fdw--q--t'>";
                                echo "<td class='c1a-1a-1a-1_fix_fdw--q--t-e'>";
                                echo "".db_getUserNameByID($cn, $answers[ $j ]['iduser'], $contlngid);
                                echo "</td>";
                                echo "<td class='c1a-1a-1a-1_fix_fdw--q--t-e'>";
                                echo $ansval;
                                echo "</td>";
                                echo "<td class='c1a-1a-1a-1_fix_fdw--q--t-e'>" ;
                                echo (isset($answers[ $j ]['uav_body']) && mb_strlen($answers[ $j ]['uav_body']) > 0 ? $answers[ $j ]['uav_body'] : "&nbsp;");
                                echo "</td>";
                                echo "</tr>";
						}?>      
        	</table>                                  
<?php

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','fileroot',realpath(dirname(__FILE__)).'/data/');
	$userids = GetUserIDs();
	$oguid = $pollingobject[0]['o_guid'];
	$rguid = $pollingobject[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, $idbranch);
	if (!is_readable($fname)){
		$fname = nameReportWithBranchAndLanguage($flroot, $oguid, $rguid, '', $idbranch);
	}
	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');
			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= 'img.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);
			db_disconnect($cn);
			unset($userids);
			ob_end_flush();
			exit;
		}
}
ob_end_flush();
?>