でPHPの設定情報を確認(出来ない鯖も有るけど)
・もしもの為の.htaccess (CGI禁止SSI禁止Index表示禁止)
Options -ExecCGI -Includes -Indexes
.txtでも、中身がHTMLだと表示されちゃうので注意
**************************************************************************/
//
/*
* Heyuri's file uploader.
*/
if (!file_exists($configFile)) {
die("Error: Configuration file $configFile is missing.");
}
$conf = require_once $configFile;
date_default_timezone_set($conf['timeZone']);
if(!file_exists($conf['logFile'])) die($conf['logFile']. " is missing. Please create it.");
/* draw functions */
function drawHeader(){
global $conf;
echo '
'.$conf['boardTitle'].'
'.$conf['boardSubTitle'].'
';
}
function drawPageingBar($page=1){
global $conf;
$fileCount = getTotalLogLines();
$pages = ceil($fileCount / $conf['filesPerListing']) + 1;
if($page === "all"){
echo '[Home] [ALL] [1]';
return;
}
echo '[Home] [ALL]';
for($i = 1; $i < $pages; $i++) {
if($i == $page){
echo '['.$i.']';
}else{
echo '['.$i.']';
}
}
}
function drawFileListing($page=1){
global $conf;
$count = $conf['filesPerListing'];
if($page == "all"){
$count = getTotalLogLines();
$page = 0;
}else{
$page = $page - 1;
}
$lineOffset = $count * $page;
$currentLine = 0;
$fileHandle = fopen($conf['logFile'], 'r');
//go to the offest
while ($currentLine < $lineOffset && !feof($fileHandle)) {
fgets($fileHandle);
$currentLine++;
}
$cookie = getSplitCookie();
// Main header (please adjust the width if you change the display items)
echo '
';
if($cookie['showDeleteButton']) echo '| DEL | ';
echo 'NAME | ';
if($cookie['showComment']) echo 'COMMENT | ';
if($cookie['showFileSize']) echo 'SIZE | ';
if($cookie['showMimeType']) echo 'MIME | ';
echo '
';
$lineOffset = $currentLine + $count;
while ($currentLine < $lineOffset && !feof($fileHandle)) {
$line = fgets($fileHandle);
if ($line == false || trim($line) == '') {
continue;
//empty line
}
$data = createDataFromString($line);
$fileName = $conf['prefix'] . getID($data) .'.'. getFileExtension($data);
$thumbName = $conf['prefix'] . getID($data) .'_thumb.'. getFileExtension($data);
$path = $conf['uploadDir'] . $fileName;
$thumbPath = $conf['thumbDir'].$thumbName;
if(!file_exists($thumbPath)) $thumbPath = $path;
if(preg_match('/video/i', getMimeType($data))) $thumbPath = 'static/images/video_overlay.png'; //if file is a video it will use a default image
if(preg_match('/audio/i', getMimeType($data))) $thumbPath = 'static/images/audio_overlay.png'; //if file is an audio it will use a default image
if($cookie['showDeleteButton']) echo '■ | ';
if($cookie['showPreviewImage']) echo ' '.$fileName.' | '; else echo ' '.$fileName.' | ';
if($cookie['showComment']) echo ''. getComment($data) .' | ';
if($cookie['showFileSize']) echo ''. bytesToHumanReadable(getSizeInBytes($data)) .' | ';
if($cookie['showMimeType']) echo ''. getMimeType($data) .' | ';
echo '';
$currentLine = $currentLine + 1;
}
echo "
";
echo 'Used '. bytesToHumanReadable(getTotalUsageInBytes()).'/ '. bytesToHumanReadable($conf['maxTotalSize']).'
';
echo 'Used '.getTotalLogLines().' Files/ '. $conf['maxAmountOfFiles'].' Files
';
}
function drawFooter(){
echo '
';
}
function drawErrorPageAndExit($mes1,$mes2=""){
global $base_php;
drawHeader();
echo '
'.$mes1.'
'.$mes2.'
[Back]';
drawFooter();
exit;
}
function drawMessageAndRedirectHome($mes1,$mes2=""){
drawHeader();
echo '
'.$mes1.'
'.$mes2.'
[Back]
';
drawFooter();
exit;
}
function drawUploadForm(){
// Post form header (Yakuba modification)
// Check if the overall filesize limit for the board has been exceeded
global $conf;
if(getTotalUsageInBytes() >= $conf['maxTotalSize']){
echo '
The total capacity has exceeded the limit and is currently under posting restriction.
Please notify the administrator.
';
}
else{
echo '
';
}
}
function drawDeletionForm($fielID){
echo'
';
}
function drawSettingsForm(){
$cookie = getSplitCookie();
echo '
client Settings
[Back]';
}
function drawActionLinks(){
echo '
settings | reload | image list
';
}
/* data getters */
function getLastID(){
global $conf;
$logFile = $conf['logFile'];
$openFile = fopen($logFile,"r");
$firstLine = fgets($openFile);
$array = explode("<>",$firstLine);
fclose($openFile);
return getID($array) ?? 1;
}
function getDataByID($id){
global $conf;
$logFile = $conf['logFile'];
$openFile = fopen($logFile,"r");
$data = null;
while(!feof($openFile)){
$line = fgets($openFile);
$array = explode("<>",$line);
if($array[0] == $id){
$data = $array;
break;
}
}
fclose($openFile);
return $data;
}
function getID($postData){
return $postData[0];
}
function getFileExtension($postData){
return $postData[1];
}
function getComment($postData){
return $postData[2];
}
function getHost($postData){
return $postData[3];
}
function getDateUploaded($postData){
return $postData[4];
}
function getSizeInBytes($postData){
return $postData[5];
}
function getMimeType($postData){
return $postData[6];
}
function getPassword($postData){
return $postData[7];
}
function getOriginalFileName($postData){
return $postData[8];
}
function createData($id,$fileExtension,$comment,$ip,$time,$size,$mimeType,$password,$orignalFileName){
return array($id,$fileExtension,$comment,$ip,$time,$size,$mimeType,$password,$orignalFileName);
}
function createDataFromString($str){
return explode("<>",$str);
}
function isDataEmpty($data) {
if(count($data) < 8){
return true;
}
return false;
}
/* helper libs */
//generate thumbnail
function thumbnailImage($imagePath, $thumbPath, $w, $h) {
global $conf;
try {
$img = new Imagick(realpath($imagePath));
$img->setbackgroundcolor('rgb(64, 64, 64)');
$img->thumbnailImage($w, $h, true);
$img->writeImage($thumbPath);
} catch (Exception $e) {
drawErrorPageAndExit("There was an error with thumbnailImage() in ".$conf['mainScript'].". Please contact the administrator.", $e->getMessage());
}
}
function writeDataToLogs($data){
global $conf;
$stringData = implode("<>", $data) . "\n";
$fileHandle = fopen($conf['logFile'], "c+");
if ($fileHandle === false) {
// Handle error when file cannot be opened
echo "Failed to open log file.";
return false;
}
// Acquire an exclusive lock
if (!flock($fileHandle, LOCK_EX)) {
echo "Could not lock log file.";
fclose($fileHandle);
return false;
}
// Read the existing contents to prepend new data
$existingData = stream_get_contents($fileHandle);
// Rewind the file pointer to the beginning of the file
rewind($fileHandle);
// Prepend new data and write the existing data back
if (fwrite($fileHandle, $stringData . $existingData) === false) {
echo "Failed to write to log file.";
flock($fileHandle, LOCK_UN);
fclose($fileHandle);
return false;
}
// Unlock the file and close
flock($fileHandle, LOCK_UN);
fclose($fileHandle);
return true;
}
function getTotalUsageInBytes(){
// Total file size calculation
global $conf;
$logFile = $conf['logFile'];
$totalSize=0;
$openFile = fopen($logFile,"r");
//id<>fileExtension<>comment<>host<>dateUploaded<>sizeInBytes<>mimeType<>Password<>orginalFileName
while(!feof($openFile)){
$line = fgets($openFile);
if ($line == false && trim($line) == '') {
continue;
}
$array = explode("<>",$line);
$size = getSizeInBytes($array);
$totalSize = $totalSize + $size;
}
fclose($openFile);
return $totalSize;
}
function getTotalLogLines(){
global $conf;
$lineCount = 0;
$fileHandle = fopen($conf['logFile'], 'r');
while (!feof($fileHandle)) {
$line = fgets($fileHandle);
if ($line !== false && trim($line) !== '') {
$lineCount++;
}
}
fclose($fileHandle);
return $lineCount;
}
function deleteFileByData($data){
global $conf;
$path = $conf['uploadDir'] . $conf['prefix'] . getID($data) . '.' . getFileExtension($data);
unlink($path);
}
function removeLastData(){
global $conf;
$fileHandle = fopen($conf['logFile'], 'r+');
flock($fileHandle, LOCK_EX);
if (!$fileHandle) {
return [false, ""]; // Return false and an empty string if the file cannot be opened
}
$lastLine = '';
$len = 0; // To track the length of the last line
// Move to the end of the file
fseek($fileHandle, 0, SEEK_END);
$fileSize = ftell($fileHandle); // Get the size of the file
// Read backwards to find the beginning of the last line
while ($fileSize > 0) {
fseek($fileHandle, --$fileSize, SEEK_SET);
$char = fgetc($fileHandle);
if ($char == "\n" && $len > 0) {
break;
}
if ($char != "\r") {
$lastLine = $char . $lastLine;
$len++;
}
}
// Truncate the file to remove the last line
if ($fileSize == 0) { // If it's the first and only line in the file
ftruncate($fileHandle, 0);
} else {
ftruncate($fileHandle, $fileSize);
}
// Close the file handle
fclose($fileHandle);
$data = explode("<>", $lastLine);
delteFileByData($data);
return [true, $lastLine]; // Return true and the last line
}
function bytesToHumanReadable($size){
if($size == 0){
$format = "";
}
elseif($size <= 1024){
$format = $size."B";
}
elseif($size <= (1024*1024)){
$format = sprintf ("%dKB",($size/1024));
}
elseif($size <= (1000*1024*1024)){
$format = sprintf ("%.2fMB",($size/(1024*1024)));
}
elseif($size <= (1000*1024*1024*1024)){
$format = sprintf ("%.2fGB",($size/(1024*1024*1024)));
}
elseif($size <= (1000*1024*1024*1024*1024) || $size >= (1000*1024*1024*1024*1024)){
$format = sprintf ("%.2fTB",($size/(1024*1024*1024*1024)));
}
else{
$format = $size."B";
}
return $format;
}
function IsBanned($host){
global $conf;
if($host == "1337"){
return false;
}
if(in_array($host, $conf['denylist'])) {
return true;
}
return false;
}
function isGlobalBanned($host){
global $conf;
if($host == "1337"){
return false;
}
if(in_array($host, $conf['hardBanList'])) {
return true;
}
return false;
}
function deleteDataFromLogByID($id){
global $conf;
$logFile = $conf['logFile'];
$openLogFile = fopen($logFile, "r");
$dataIsFoundInFile = false;
$newFileContent = [];
$foundData = null;
// while not at the end of the file.
while (!feof($openLogFile)) {
$line = fgets($openLogFile);
$data = explode("<>", $line);
if ($data[0] == $id) {
$dataIsFoundInFile = true;
$foundData = $data;
} else {
$newFileContent[] = $line;
}
}
fclose($openLogFile);
// data was not found.
if ($dataIsFoundInFile == false) {
return false;
}
$openLogFile = fopen($logFile, "w");
flock($openLogFile, LOCK_EX);
foreach ($newFileContent as $line) {
fwrite($openLogFile, $line);
}
fclose($openLogFile);
deleteFileByData($foundData);
return true;
}
function loadCookieSettings(){
global $conf;
if(isset($_COOKIE['settings']) == false){
$cookie = implode("<>", $conf['defaultCookieValues']);
}else{
$cookie = $_COOKIE['settings'];
}
if(isset($_POST['action']) && $_POST['action'] == "setUserSettings"){
// the order of this array must be the same order as $conf['defualtCookieValues']
$cookie = implode("<>", array( $_POST['showDeleteButton'] ?? ""
,$_POST['showComment'] ?? ""
,$_POST['showPreviewImage'] ?? ""
,$_POST['showFileSize'] ?? ""
,$_POST['showMimeType'] ?? ""));
}
setcookie("settings", $cookie,time()+365*24*3600);
$_COOKIE['settings'] = $cookie;
}
function getSplitCookie(){
global $conf;
return array_combine(['showDeleteButton', 'showComment', 'showPreviewImage', 'showFileSize', 'showMimeType'], explode("<>",$_COOKIE['settings']));
}
function isBoardBeingFlooded() {
global $conf;
$lastPost = getDataByID(getLastID());
if(isDataEmpty($lastPost)){
// cant flood if there is not even a single post
return false;
}
$lastTime = getDateUploaded($lastPost);
if($lastTime + $conf['coolDownTime'] > time()){
return true;
}else{
return false;
}
}
/* main funcitons */
function userUploadedFile(){
global $conf;
if(IsBanned($_SERVER['REMOTE_ADDR'])){
drawErrorPageAndExit("You are banned from uploading!");
}
if(isBoardBeingFlooded()){
drawErrorPageAndExit("OUCH!!", "I need to wait before acepting another file..");
}
if($_FILES["upfile"]['size'] <= 0){
drawErrorPageAndExit('Please select a file.');
}
if($_FILES["upfile"]['size'] > $conf['maxUploadSize']){
drawErrorPageAndExit('File is too big.');
}
if($_POST['comment'] == "" && $conf['commentRequired']){
drawErrorPageAndExit('Comment is required.');
}
if(strlen($_POST['comment']) > $conf['maxCommentSize']){
drawErrorPageAndExit('Comment is too big.');
}
$fullFileName = $_FILES["upfile"]["name"];
$fileInfo = pathinfo($fullFileName);
$fileName = $fileInfo['filename'];
$fileExtension = strtolower($fileInfo['extension']);
if(!in_array($fileExtension, $conf['allowedExtensions'])){
drawErrorPageAndExit("Invalid extension","file can not be uploaded with that extension");
}
$originalExtension = $fileExtension;
// convert posibly dangerous scripts into text files
if(in_array($fileExtension, $conf['extentionsToBeConvertedToText'])){
$originalExtension = $fileExtension;
$fileExtension = "txt";
}
// get mimetype for this post
$finfo = finfo_open(FILEINFO_MIME_TYPE); // Return MIME type
$realMimeType = finfo_file($finfo, $_FILES['upfile']['tmp_name']);
finfo_close($finfo);
// get a ID for this new post
$newID = sprintf("%03d", (int)getLastID() + 1);
$newname = $conf['prefix'] . $newID . "." . $fileExtension;
rename($_FILES['upfile']['tmp_name'], $conf['uploadDir'].$newname);
chmod($conf['uploadDir'] . $newname, 0644);
// remove line breaks from the comment
$comment = htmlspecialchars(str_replace(array("\0","\t","\r","\n","\r\n"), "", $_POST['comment']));
// check if the extention has been converted to something safe
if($originalExtension != $fileExtension){
//show the converstion
$comment = $comment . '('. $fileExtension .'←'. $originalExtension .')';
}
// get password
if(isset($_POST['password'])){
$password = $_POST['password'];
}else{
$password = '';
}
$data = createData( $newID, $fileExtension, $comment, $_SERVER['REMOTE_ADDR'],
time(), $_FILES['upfile']['size'], $realMimeType, $password,
$fileName);
// if over max. delete last file
if(getTotalLogLines() >= $conf['maxAmountOfFiles']){
if($conf['deleteOldestOnMaxFiles']){
removeLastData(); //remove file if deleteOldestOnMaxFiles is true
}
drawErrorPageAndExit("File limit reached, contact administrator.");
}
writeDataToLogs($data);
//create thumbnail if file type is image and size is above 1mb
if(preg_match('/image/i', getMimeType($data)) && $_FILES["upfile"]['size'] >= 1*1024*1024) {
$imagePath = $conf['uploadDir'].$conf['prefix'].$newID.'.'.$fileExtension;
thumbnailImage($imagePath, $conf['thumbDir'].$conf['prefix'].$newID.'_thumb.'.$fileExtension, 100, 100);
}
drawMessageAndRedirectHome('The process is over. The screen will change automatically.','If this does not change, click "Back".');
}
function userDeletePost(){
global $conf;
$fileID = $_POST['deleteFileID'];
$password = $_POST['password'];
$postData = getDataByID($fileID);
if(is_null($postData)){
drawErrorPageAndExit('Deletion Error','The file cannot be found.');
}
elseif($password == getPassword($postData) || $password == $conf['adminPassword']){
deleteDataFromLogByID($fileID);
$thumbPath = $conf['thumbDir'] . $conf['prefix'] . getID($postData) . '_thumb.' . getFileExtension($postData);
unlink($thumbPath);
drawMessageAndRedirectHome('file has been deleted.','If this page dose not change, click "Back".');
}
elseif(getPassword($postData) == ''){
drawErrorPageAndExit('Deletion Error','There was not a password when this post was created. Contact the administrator to request deletion');
}else{
drawErrorPageAndExit('Deletion Error','The password is incorrect.');
}
}
/*
* Start of the main logic
*/
if($conf['logUserIP'] == false){
$_SERVER['REMOTE_ADDR'] = "1337";
}
// check if user is hard banned (cannot lurk)
if(isGlobalBanned($_SERVER['REMOTE_ADDR'])){
drawErrorPageAndExit("You have been banned by the administrator. ヽ(ー_ー )ノ");
}
loadCookieSettings();
/* deletion form was posted to */
if(isset($_POST['deleteFileID']) && isset($_POST['password'])){
if(is_numeric($_POST['deleteFileID']) == false){
drawErrorPageAndExit("failed to delete", "deleteFileID is not a number");
}
userDeletePost();
die();
}
/* file is uploading */
if(isset($_FILES['upfile'])){
userUploadedFile();
die();
}
/* draw a form when user is attempting to delete a file */
if(isset($_GET['deleteFileID'])){
drawHeader();
drawDeletionForm(htmlspecialchars($_GET['deleteFileID']));
drawFooter();
die();
}
if(isset($_GET['goingto'])){
switch($_GET['goingto']){
case "settings":
drawHeader();
drawSettingsForm();
drawFooter();
die();
}
}
if(isset($_GET['page'])){
$page = $_GET['page'];
drawHeader();
drawUploadForm();
drawPageingBar($page);
drawActionLinks();
drawFileListing($page);
drawFooter();
die();
}
drawHeader();
drawUploadForm();
drawPageingBar(1);
drawActionLinks();
drawFileListing(1);
drawFooter();