<?php

/*
 * Copyright CADMAI Software GmbH.
 * All rights reserved.
 *
 * The redistributor / user does not have the right to change, translate,
 * back-develop, decompile or disassemble the software.
 *
 * Redistributions must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * Neither the name of CADMAI Software GmbH nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

include_once ( 'funcs.php' );

if (isset($_GET['path'])) {
	$filename = $_GET['path'];
	$fileCheck = iCheckFileExistance($filename, true);

	if($fileCheck->exists){
    $globalAccess = false;

	  if($fileCheck->isRemote == true){
      $globalAccess = true;
    }
    else{
  		$ut = $_GET['token'];
  		$userToken = json_decode ( $ut );

  		if (empty ( $userToken->aNm )&&empty ( $userToken->aNm )) { //check for global file access
        $globalAccess = iCheckGlobalAccess($filename);
  		}
    }

		if($globalAccess == false) {
  		if ( !empty ( $userToken->aNm )) {
  			$f = file_get_contents ( 'Poi3dUsers/' . $userToken->aNm . '.json' );
  		}
  		else {
  			$f = file_get_contents ( 'Poi3dUsers/' . $userToken->uNm . '.json' );
  		}

  		$user = json_decode ( $f );

  		// overwrite password if received asymmetrical encrypted
  		if ( !empty( $userToken->vDt ) ) {
  			if ( iDecrypt( $userToken->vDt, $vDt, $errorText ) ) {
  				die( 'decryption error: ' . $errorText );
  			}

  			$date = new DateTime();
  			$unix_seconds = $date->setTimezone(new \DateTimeZone('UTC'))->format('U');
  			$unix_seconds = intval( $unix_seconds / 30 );

  			if ( abs( $unix_seconds - $vDt->time ) >= 2 ) {
  				$t_diff = ($unix_seconds - $vDt->time) * 30;
  				die( 'time does not match by ' . $t_diff . ' seconds. Server: ' . $unix_seconds . ', client: ' . $vDt->time );
  			}

  			$userToken->pWd = $vDt->pwd;
  		}

  		if ( !password_verify ( $userToken->pWd, $user->pWd ) ) {
  			die("");
  		}
    }//$globalAccess == false

		$tgtFileName = basename($filename);
		if (isset($_GET['fName']))
	    $tgtFileName = $_GET['fName'];

		//update log file
		if($globalAccess == false) {
  		if ((strpos($filename, '_pv.') == false)&&( empty ( $userToken->aNm ))) {
  			$pathParts = pathinfo ( $filename );

  			if ( file_exists( $pathParts['dirname'] ) && is_dir ( $pathParts['dirname'] ) ) {
  				$logFileName = $pathParts['dirname'] . "/fileAccess.json";
  				//echo $logFileName. "\n";
  				$accessList = [];

  				if ( file_exists ( $logFileName ) ) {
  					$f = file_get_contents ( $logFileName );
  					$accessList = json_decode ( $f );
  				}
  				$listEntry = (object) [];
  				$listEntry->dT = date('d-M-Y H:i:s');
  				$listEntry->aL = $user->aL;
  				$listEntry->uId = $user->uId;
    			$listEntry->fnm = $tgtFileName;

  				$accessList[] = $listEntry;
  				$json = json_encode ( $accessList );

  				file_put_contents( $logFileName, $json);
  			}
  		}
	  }

		//Define header information
		$contentType = 'Content-Type: application/octet-stream';

	  header("Content-Transfer-Encoding: Binary");
    header('Content-Description: File Transfer');
    header($contentType);
    header('Content-Disposition: attachment; filename="'.$tgtFileName.'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');

    if($fileCheck->isRemote == false)
      header('Content-Length: ' . filesize($filename));

    ob_clean();

		$fp = fopen($filename, 'rb');
		fpassthru($fp);
		exit;

	}//if(file_exists($filename))
	else
	{
		echo("file ".$filename." does not exist");
	}
}//if (isset($_GET['path']))
else
{
	echo("no path given");
}
?>