<commit_before><?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
// 
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

$force_no_compression = true;
$skip = false;
$thumbnail_format = 'jpeg';

if ( isset($_GET['fileId']) && isset($_GET['thumbnail']) && isset($_COOKIE[ session_name() ]) && count($_GET) == 2 ) {

	$tikiroot = dirname($_SERVER['PHP_SELF']);
	$session_params = session_get_cookie_params();
	session_set_cookie_params($session_params['lifetime'], $tikiroot);
	unset($session_params);
	session_start();

	if ( isset($_SESSION['allowed'][$_GET['fileId']]) ) {
		require_once 'tiki-setup_base.php';

		$query = "select * from `tiki_files` where `fileId`=?";
		$result = $tikilib->query($query, array((int)$_GET['fileId']));
		if ( $result ) {
			$info = $result->fetchRow();
			$skip = true;
		} else {
			$info = array();
		}
	} else {
		session_write_close();
	}
}

if (!$skip) {
	require_once('tiki-setup.php');
	include_once('lib/filegals/filegallib.php');
	$access->check_feature('feature_file_galleries');
}

if ($prefs["user_store_file_gallery_picture"] == 'y' && isset($_REQUEST["avatar"])) {
	require_once ('lib/userprefs/userprefslib.php');
	if ($user_picture_id = $userprefslib->get_user_picture_id($_REQUEST["avatar"])) {
		$_REQUEST['fileId'] = $user_picture_id;
	} elseif (!empty($prefs['user_default_picture_id'])) {
		$_REQUEST['fileId'] = $prefs['user_default_picture_id'];
	}
}

if ( ! ini_get('safe_mode') ) {
	@set_time_limit(0);
}

$zip = false;
$error = '';

if (!$skip) {
	if ( isset($_REQUEST['fileId']) && !is_array($_REQUEST['fileId'])) {
		if (isset($_GET['draft'])) {
			$info = $filegallib->get_file_draft($_REQUEST['fileId']);
		} else {
			$info = $filegallib->get_file($_REQUEST['fileId']);
		}
	} elseif ( isset($_REQUEST['galleryId']) && isset($_REQUEST['name']) ) {
		$info = $filegallib->get_file_by_name($_REQUEST['galleryId'], $_REQUEST['name']);
	} elseif ( isset($_REQUEST['fileId']) && is_array($_REQUEST['fileId'])) {
		$info = $filegallib->zip($_REQUEST['fileId'], $error);
		$zip = true;
	} elseif ( !empty($_REQUEST['randomGalleryId'])) {
		$info =  $filegallib->get_file(0, $_REQUEST['randomGalleryId']);
	} else {
		$access->display_error('', tra('Incorrect param'), 400);
	}
	if ( ! is_array($info) ) {
		$access->display_error(NULL, tra('File has been deleted'), 404);
	}

	if ( $prefs['auth_tokens'] == 'n' || !$is_token_access ) {
		// Check permissions except if the user comes with a valid Token

		if ( !$zip && $tiki_p_admin_file_galleries != 'y' && !$userlib->user_has_perm_on_object($user, $info['galleryId'], 'file gallery', 'tiki_p_download_files') && !($info['backlinkPerms'] == 'y' && !$filegallib->hasOnlyPrivateBacklinks($info['fileId']))) {
			if (!$user) $_SESSION['loginfrom'] = $_SERVER['REQUEST_URI'];
			$access->display_error('', tra('Permission denied'), 401);
		}
		if ( isset($_GET['thumbnail']) && is_numeric($_GET['thumbnail'])) { //check also perms on thumb 
			$info_thumb = $filegallib->get_file($_GET['thumbnail']);
			if ( !$zip && $tiki_p_admin_file_galleries != 'y' && !$userlib->user_has_perm_on_object($user, $info_thumb['galleryId'], 'file gallery', 'tiki_p_download_files') && !($info['backlinkPerms'] == 'y' && !$filegallib->hasOnlyPrivateBacklinks($info_thumb['fileId']))) {
				if (!$user) $_SESSION['loginfrom'] = $_SERVER['REQUEST_URI'];
				$access->display_error('', tra('Permission denied'), 401);
			}
		}
	}
}

// Add hits ( if download or display only ) + lock if set
if ( ! isset($_GET['thumbnail']) && ! isset($_GET['icon']) ) {

	require_once('lib/stats/statslib.php');
	$filegallib = TikiLib::lib('filegal');
	if ( ! $filegallib->add_file_hit($info['fileId']) ) {
		$access->display_error('', tra('You cannot download this file right now. Your score is low or file limit was reached.'), 401);
	}
	$statslib->stats_hit($info['filename'], 'file', $info['fileId']);

	if ( $prefs['feature_actionlog'] == 'y' ) {
		global $logslib; require_once('lib/logs/logslib.php');
		$logslib->add_action('Downloaded', $info['galleryId'], 'file gallery', 'fileId='.$info['fileId']);
	}

	if ( ! empty($_REQUEST['lock']) ) {
		if (!empty($info['lockedby']) && $info['lockedby'] != $user) {
			$access->display_error('', tra(sprintf('The file is locked by %s', $info['lockedby'])), 401);
		}
		$filegallib->lock_file($info['fileId'], $user);
	}
}

session_write_close(); // close the session in case of large downloads to enable further browsing
error_reporting(E_ALL);
if ( ob_get_level() ) while (@ob_end_clean()); // Be sure output buffering is turned off

$content_changed = false;
$content = &$info['data'];

$md5 = '';
$filepath = '';
if ( ! empty($info['path']) ) {
	if (!$skip and $filegallib->isPodCastGallery($info['galleryId'])) {
		$filepath = $prefs['fgal_podcast_dir'].$info['path'];
	} else {
		$filepath = $prefs['fgal_use_dir'].$info['path'];
	}
	if ( is_readable($filepath) ) {
		$file_stats = stat($filepath);
		$last_modified = $file_stats['mtime'];
		$md5 = empty($info['hash']) ?
			md5($file_stats['mtime'].'='.$file_stats['ino'].'='.$file_stats['size'])
			: $info['hash'];
	} else {
		// File missing or not readable
		header("HTTP/1.0 404 Not Found");
		header('Content-Type: text/plain');		
		echo "Unable to access file: " . ($tiki_p_admin == 'y' ? $filepath : $info['path']);
		die;
	}
} elseif ( ! empty($content) ) {
	$last_modified = $info['lastModif'];
	$md5 = empty($info['hash']) ? md5($content) : $info['hash'];
} else {
	// Empty content
	die;
}

// ETag: Entity Tag used for strong cache validation.
if ( ! isset($_GET['display']) || isset($_GET['x']) || isset($_GET['y']) || isset($_GET['scale']) || isset($_GET['max']) || isset($_GET['format']) ) {
  // if image will be modified, emit a different ETag for modifications.
	$str = isset($_GET['x']) ? $_GET['x'] . 'x' : '';
	$str .= isset($_GET['y']) ? $_GET['y'] . 'y' : '';
	$str .= isset($_GET['scale']) ? $_GET['scale'] . 's' : '';
	$str .= isset($_GET['max']) ? $_GET['max'] . 'm' : '';
	$str .= isset($_GET['format']) ? $_GET['format'] . 'f' : '';
	$etag = '"' . $md5 . '-' . crc32($md5) . '-' . crc32($str) . '"';
} else {
  $etag = '"' . $md5 . '-' . crc32($md5) . '"';
}
header('ETag: '.$etag);

$use_client_cache = false;
if ( isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $last_modified == strtotime(current($a = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']))) ) {
	$use_client_cache = true;
} elseif ( isset($_SERVER['HTTP_IF_NONE_MATCH']) ) {
	$tmp = array_map('trim', explode(',', $_SERVER['HTTP_IF_NONE_MATCH']));
	foreach ( $tmp as $v ) {
		if ( $v == '*' || $v == $etag ) {
			$use_client_cache = true;
			break;
		}
	}
	unset($tmp);
}

header("Pragma: ");
header('Expires: ');
header('Cache-Control: '.( !empty($user) ? 'private' : 'public' ).',must-revalidate,post-check=0,pre-check=0');

if ( $use_client_cache ) {
	header('Status: 304 Not Modified', true, 304);
	exit;
} else {
	if ( !empty($last_modified) ) header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_modified). ' GMT');
}

// Handle images display, files thumbnails and icons
if ( isset($_GET['preview']) || isset($_GET['thumbnail']) || isset($_GET['display']) || isset($_GET['icon']) ) {
	$use_cache = false;

	// Cache only thumbnails to avoid DOS attacks
	$cacheName = '';
	$cacheType = '';
	if ( ( isset($_GET['thumbnail']) || isset($_GET['preview']) ) && ! isset($_GET['display']) && ! isset($_GET['icon']) && ! isset($_GET['scale']) && ! isset($_GET['x']) && ! isset($_GET['y']) && ! isset($_GET['format']) && ! isset($_GET['max']) ) {
		global $cachelib; include_once('lib/cache/cachelib.php');<commit_msg>[FIX] mobile: 304 doesn't seem to agree with mobile_mode<commit_after><?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
// 
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

$force_no_compression = true;
$skip = false;
$thumbnail_format = 'jpeg';

if ( isset($_GET['fileId']) && isset($_GET['thumbnail']) && isset($_COOKIE[ session_name() ]) && count($_GET) == 2 ) {

	$tikiroot = dirname($_SERVER['PHP_SELF']);
	$session_params = session_get_cookie_params();
	session_set_cookie_params($session_params['lifetime'], $tikiroot);
	unset($session_params);
	session_start();

	if ( isset($_SESSION['allowed'][$_GET['fileId']]) ) {
		require_once 'tiki-setup_base.php';

		$query = "select * from `tiki_files` where `fileId`=?";
		$result = $tikilib->query($query, array((int)$_GET['fileId']));
		if ( $result ) {
			$info = $result->fetchRow();
			$skip = true;
		} else {
			$info = array();
		}
	} else {
		session_write_close();
	}
}

if (!$skip) {
	require_once('tiki-setup.php');
	include_once('lib/filegals/filegallib.php');
	$access->check_feature('feature_file_galleries');
}

if ($prefs["user_store_file_gallery_picture"] == 'y' && isset($_REQUEST["avatar"])) {
	require_once ('lib/userprefs/userprefslib.php');
	if ($user_picture_id = $userprefslib->get_user_picture_id($_REQUEST["avatar"])) {
		$_REQUEST['fileId'] = $user_picture_id;
	} elseif (!empty($prefs['user_default_picture_id'])) {
		$_REQUEST['fileId'] = $prefs['user_default_picture_id'];
	}
}

if ( ! ini_get('safe_mode') ) {
	@set_time_limit(0);
}

$zip = false;
$error = '';

if (!$skip) {
	if ( isset($_REQUEST['fileId']) && !is_array($_REQUEST['fileId'])) {
		if (isset($_GET['draft'])) {
			$info = $filegallib->get_file_draft($_REQUEST['fileId']);
		} else {
			$info = $filegallib->get_file($_REQUEST['fileId']);
		}
	} elseif ( isset($_REQUEST['galleryId']) && isset($_REQUEST['name']) ) {
		$info = $filegallib->get_file_by_name($_REQUEST['galleryId'], $_REQUEST['name']);
	} elseif ( isset($_REQUEST['fileId']) && is_array($_REQUEST['fileId'])) {
		$info = $filegallib->zip($_REQUEST['fileId'], $error);
		$zip = true;
	} elseif ( !empty($_REQUEST['randomGalleryId'])) {
		$info =  $filegallib->get_file(0, $_REQUEST['randomGalleryId']);
	} else {
		$access->display_error('', tra('Incorrect param'), 400);
	}
	if ( ! is_array($info) ) {
		$access->display_error(NULL, tra('File has been deleted'), 404);
	}

	if ( $prefs['auth_tokens'] == 'n' || !$is_token_access ) {
		// Check permissions except if the user comes with a valid Token

		if ( !$zip && $tiki_p_admin_file_galleries != 'y' && !$userlib->user_has_perm_on_object($user, $info['galleryId'], 'file gallery', 'tiki_p_download_files') && !($info['backlinkPerms'] == 'y' && !$filegallib->hasOnlyPrivateBacklinks($info['fileId']))) {
			if (!$user) $_SESSION['loginfrom'] = $_SERVER['REQUEST_URI'];
			$access->display_error('', tra('Permission denied'), 401);
		}
		if ( isset($_GET['thumbnail']) && is_numeric($_GET['thumbnail'])) { //check also perms on thumb 
			$info_thumb = $filegallib->get_file($_GET['thumbnail']);
			if ( !$zip && $tiki_p_admin_file_galleries != 'y' && !$userlib->user_has_perm_on_object($user, $info_thumb['galleryId'], 'file gallery', 'tiki_p_download_files') && !($info['backlinkPerms'] == 'y' && !$filegallib->hasOnlyPrivateBacklinks($info_thumb['fileId']))) {
				if (!$user) $_SESSION['loginfrom'] = $_SERVER['REQUEST_URI'];
				$access->display_error('', tra('Permission denied'), 401);
			}
		}
	}
}

// Add hits ( if download or display only ) + lock if set
if ( ! isset($_GET['thumbnail']) && ! isset($_GET['icon']) ) {

	require_once('lib/stats/statslib.php');
	$filegallib = TikiLib::lib('filegal');
	if ( ! $filegallib->add_file_hit($info['fileId']) ) {
		$access->display_error('', tra('You cannot download this file right now. Your score is low or file limit was reached.'), 401);
	}
	$statslib->stats_hit($info['filename'], 'file', $info['fileId']);

	if ( $prefs['feature_actionlog'] == 'y' ) {
		global $logslib; require_once('lib/logs/logslib.php');
		$logslib->add_action('Downloaded', $info['galleryId'], 'file gallery', 'fileId='.$info['fileId']);
	}

	if ( ! empty($_REQUEST['lock']) ) {
		if (!empty($info['lockedby']) && $info['lockedby'] != $user) {
			$access->display_error('', tra(sprintf('The file is locked by %s', $info['lockedby'])), 401);
		}
		$filegallib->lock_file($info['fileId'], $user);
	}
}

session_write_close(); // close the session in case of large downloads to enable further browsing
error_reporting(E_ALL);
if ( ob_get_level() ) while (@ob_end_clean()); // Be sure output buffering is turned off

$content_changed = false;
$content = &$info['data'];

$md5 = '';
$filepath = '';
if ( ! empty($info['path']) ) {
	if (!$skip and $filegallib->isPodCastGallery($info['galleryId'])) {
		$filepath = $prefs['fgal_podcast_dir'].$info['path'];
	} else {
		$filepath = $prefs['fgal_use_dir'].$info['path'];
	}
	if ( is_readable($filepath) ) {
		$file_stats = stat($filepath);
		$last_modified = $file_stats['mtime'];
		$md5 = empty($info['hash']) ?
			md5($file_stats['mtime'].'='.$file_stats['ino'].'='.$file_stats['size'])
			: $info['hash'];
	} else {
		// File missing or not readable
		header("HTTP/1.0 404 Not Found");
		header('Content-Type: text/plain');		
		echo "Unable to access file: " . ($tiki_p_admin == 'y' ? $filepath : $info['path']);
		die;
	}
} elseif ( ! empty($content) ) {
	$last_modified = $info['lastModif'];
	$md5 = empty($info['hash']) ? md5($content) : $info['hash'];
} else {
	// Empty content
	die;
}

// ETag: Entity Tag used for strong cache validation.
if ( ! isset($_GET['display']) || isset($_GET['x']) || isset($_GET['y']) || isset($_GET['scale']) || isset($_GET['max']) || isset($_GET['format']) ) {
  // if image will be modified, emit a different ETag for modifications.
	$str = isset($_GET['x']) ? $_GET['x'] . 'x' : '';
	$str .= isset($_GET['y']) ? $_GET['y'] . 'y' : '';
	$str .= isset($_GET['scale']) ? $_GET['scale'] . 's' : '';
	$str .= isset($_GET['max']) ? $_GET['max'] . 'm' : '';
	$str .= isset($_GET['format']) ? $_GET['format'] . 'f' : '';
	$etag = '"' . $md5 . '-' . crc32($md5) . '-' . crc32($str) . '"';
} else {
  $etag = '"' . $md5 . '-' . crc32($md5) . '"';
}
header('ETag: '.$etag);

$use_client_cache = false;
if ( isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $last_modified == strtotime(current($a = explode(';', $_SERVER['HTTP_IF_MODIFIED_SINCE']))) ) {
	$use_client_cache = true;
} elseif ( isset($_SERVER['HTTP_IF_NONE_MATCH']) ) {
	$tmp = array_map('trim', explode(',', $_SERVER['HTTP_IF_NONE_MATCH']));
	foreach ( $tmp as $v ) {
		if ( $v == '*' || $v == $etag ) {
			$use_client_cache = true;
			break;
		}
	}
	unset($tmp);
}

header("Pragma: ");
header('Expires: ');
header('Cache-Control: '.( !empty($user) ? 'private' : 'public' ).',must-revalidate,post-check=0,pre-check=0');

if ( $use_client_cache && $prefs['mobile_mode'] !== 'y') {
	header('Status: 304 Not Modified', true, 304);
	exit;
} else {
	if ( !empty($last_modified) ) header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_modified). ' GMT');
}

// Handle images display, files thumbnails and icons
if ( isset($_GET['preview']) || isset($_GET['thumbnail']) || isset($_GET['display']) || isset($_GET['icon']) ) {
	$use_cache = false;

	// Cache only thumbnails to avoid DOS attacks
	$cacheName = '';
	$cacheType = '';
	if ( ( isset($_GET['thumbnail']) || isset($_GET['preview']) ) && ! isset($_GET['display']) && ! isset($_GET['icon']) && ! isset($_GET['scale']) && ! isset($_GET['x']) && ! isset($_GET['y']) && ! isset($_GET['format']) && ! isset($_GET['max']) ) {
		global $cachelib; include_once('lib/cache/cachelib.php');
{'fraction_non_alphanumeric': 0.23145591163059534, 'fraction_numerical': 0.007513968274356175, 'mean_word_length': 5.340390879478828, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 53, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7184364', 'n_tokens_mistral': 5887, 'n_tokens_neox': 5635, 'n_words': 1049}