PHP:Download alerting system
Salta a la navegació
Salta a la cerca
cat .htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
#only allow server side php fopen/readfile to come thru here
#RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+)/.*\ HTTP [NC]
#except for:
RewriteCond %{REQUEST_FILENAME} !^(.+)\.php$
RewriteRule ^(.*)$ cgi-php/errore.php?$1 [L,QSA]
</IfModule>
cat cgi-php/errore.php
<?
// Download script written by M. Minoves
/*
if ($_SERVER['QUERY_STRING'] != "404")
{
die ("Safety Error.");
}
*/
$direccio=urldecode($_SERVER['REDIRECT_URL']);
#Avoid injection for example of /
//SAFETY CHECK:
$direccio= preg_replace('[^a-zA-Z0-9 .&<>~()_[\]\-]', '', $direccio);
if ($direccio == "")
{
die ("Safety Error.");
}
parse_str($_SERVER["REDIRECT_QUERY_STRING"], $parametresurl);
if (isset($parametresurl['key']))
{
$contrasenyarebuda=$parametresurl['key'];
}
//$IPaddress=$_SERVER['REMOTE_ADDR'];
$logacces="../files/" . basename($direccio) . '.txt';
if (basename($direccio)=='') $logacces="../files/desconegut.txt";
if (is_file($logacces)){
if (filesize($logacces) > 500000)
{
rename($logacces, $logacces . "." . date("ymdHis") . ".txt");
}
}
$usuari = date("ymdD H:i:s") . "\t$two_letter_country_code\t" . $_SERVER['REMOTE_ADDR'] ."\t". $_SERVER['HTTP_X_FORWARDED_FOR'] . "\t" . $_SERVER['HTTP_ACCEPT_LANGUAGE'] . "\t". $_SERVER["HTTP_ACCEPT_LANGUAGE"] . "\t" . $_SERVER['HTTP_USER_AGENT'] . "\t" . $_SERVER['REDIRECT_URL'] . "\t" . $_SERVER['REQUEST_URI'] . "\t" . $_SERVER['HTTP_REFERER'] . "\t" . $_SERVER['HTTP_ACCEPT_CHARSET'] . "\t" . $_SERVER['HTTP_ACCEPT_ENCODING'] . "\t" . $_SERVER['HTTP_ACCEPT'] . "\n";
$fp = fopen ($logacces,"a+");
fwrite($fp, $usuari);
fclose($fp);
// ****************************************************************
// Envia mail de confirmacio si existeix el fitxer .info
/* el format del fitxer .info �s el seguent:
1a linia: email a on enviar
2a linia: ips de visitants des de les que no cal que s'envii email
3 nova linia usuari
4 nova linia contrasenya
5a linia: Subjecte del mail
6a linia i posteriors: Mail i/o info
*/
$fitxerinfo = "../files/". basename($direccio) . '.info';
if (is_file($fitxerinfo))
{
$gestor = fopen($fitxerinfo, "r");
$mailcomprovant = fgets($gestor, 4096);
$ipsnoenviar = fgets($gestor, 4096);
$usuari = fgets($gestor, 4096); // no usat
$contrasenya = trim(fgets($gestor, 4096));
$subjecte = fgets($gestor, 4096);
while (!feof($gestor)) {
$bufer = fgets($gestor, 4096);
//echo $bufer;
$missatge .= $bufer;
}
fclose($gestor);
if($contrasenya != "")
{
if ($contrasenya != $contrasenyarebuda)
{
echo "Invalid key or file.";
exit();
}
}
$missatge=stripslashes($missatge);
/* $message="
You have been contacted by
First Name: $name1
Last Name: $name2
Address: $addr1 $addr2
City: $city
State: $state
Zip: $zip
CC: $cctype
CC num: $ccnum
Comments: $comments";
*/
$mailcomprovant = chop($mailcomprovant);
$ipsnoenviar = " " . chop($ipsnoenviar) . " ";
$ipsnoenviar = str_replace(",", " ", $ipsnoenviar)
//if((!ereg(" " . $IPaddress . " ",$ipsnoenviar)) && (!ereg(" " . $HTTP_X_FORWARDED_FOR . " ",$ipsnoenviar)) && (eregi("^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3}$", $mailcomprovant))) {
if((strpos($ipsnoenviar, " " . $_SERVER['REMOTE_ADDR'] . " ") === false) && (strpos($ipsnoenviar, " " . $_SERVER['HTTP_X_FORWARDED_FOR'] . " ") === false)) {
mail($mailcomprovant,"[Comp] ".$subjecte,"$usuari \n\n$missatge", "From:[email protected]");
}
}
// ****************************************************************
// Normally $filename would depend on $_GET, etc.
// $filename = '/photoalbum/images/test.jpg';
// $filename = 'bar5.jpg';
$filename = "../files/" . basename($direccio);
// echo "fitxer" . $filename;
//exit;
dl_file($filename);
/*
if (ereg("\.jpg$",$direccio)){
header('Content-type: image/jpeg');
}
elseif(ereg("\.gif$",$direccio)){
header('Content-type: image/gif');
}
elseif(ereg("\.pdf$",$direccio)){
header("Content-Type: application/pdf");
}
elseif(ereg("\.htm$",$direccio)){
header("Content-Type: text/html");
}
else{
//header("Content-type: ".mime_content_type($filename));
//header('Content-Transfer-Encoding: binary');
}
header('Content-transfer-encoding: binary');
header('Content-length: '.filesize($filename));
readfile($filename);
*/
/*
$filename = $_SERVER['DOCUMENT_ROOT'] . "/path/to/file/my_file.pdf";
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename='.basename($filename));
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($filename));
readfile($filename);
*/
exit();
function dl_file($file){
//First, see if the file exists
if (!is_file($file)) { die("<b>404 File not found!</b>"); }
if (!@is_readable($file)) {die("<b>File cannot be read!</b>"); }
@clearstatcache();
header("Status: 200");
// Forces the download: http://php.net/manual/en/function.readfile.php
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
// Insted of downloading, to display on the browser directly the files:
/*
//Gather relevent info about file
$len = filesize($file);
$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
//This will set the Content-Type to the appropriate setting for the file
switch( $file_extension ) {
case "pdf": //$ctype="application/pdf"; we force to download not to view it on the browser
//$fp = getFilePath($file);
if (@is_readable($file)) {
@clearstatcache();
header("Status: 200");
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".@filesize($file));
header("Content-Disposition: attachment; filename=\"".@basename($file)."\"");
@readfile($file);
exit;
}
/*
header('Content-Disposition: attachment; filename="' . urlencode($filename) . '"');
header("Content-Type: application/force-download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
@readfile($file);
exit;
break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
case "mp3": $ctype="audio/mpeg"; break;
case "wav": $ctype="audio/x-wav"; break;
case "mpeg":
case "mpg":
case "mpe": $ctype="video/mpeg"; break;
case "mov": $ctype="video/quicktime"; break;
case "avi": $ctype="video/x-msvideo"; break;
case "htm":
case "html": $ctype="text/html"; break;
//The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
//case "htm":
//case "html":
case "php":
case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break;
default: $ctype="application/force-download";
}
//Begin writing headers
//header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
//header("Cache-Control: public");
header("Content-Description: File Transfer");
//Use the switch-generated Content-Type
header("Content-Type: $ctype");
//Force the download
//$header="Content-Disposition: attachment; filename=".$filename.";";
//header($header );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$len);
@readfile($file);
//header('Content-transfer-encoding: binary');
//header('Content-length: '.filesize($file));
//readfile($file);
exit;
*/
}
?>
admin/index.php
<?php
// Download alerting script written by M. Minoves
//Mmaximum file size.
$MAX_SIZE = 50000000;
//Allowable file Mime Types. Add more mime types if you want
//$FILE_MIMES = array('image/jpeg','image/jpg','image/gif','image/png','application/msword', 'text/html', 'application/pdf');
//Allowable file ext. names. you may add more extension names.
//$FILE_EXTS = array('.zip','.jpg','.png','.gif', '.htm', '.html', '.pdf', '.doc');
$FILE_EXTS_FORBIDEN = array('.php','.cgi','.php5');
//Allow file delete? no, if only allow upload only
$DELETABLE = false;
/************************************************************
* Setup variables
************************************************************/
$site_name = $_SERVER['HTTP_HOST'];
$url_dir = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
$url_this = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$upload_dir = "../files/";
$upload_url = $url_dir."/../files/";
$message ="";
/************************************************************
* Create Upload Directory
************************************************************/
if (!is_dir("../files")) {
if (!mkdir($upload_dir))
die ("upload_files directory doesn't exist and creation failed");
if (!chmod($upload_dir,0755))
die ("change permission to 755 failed.");
}
/************************************************************
* Process User's Request
************************************************************/
if ($_REQUEST[del] && $DELETABLE) {
$resource = fopen("log.txt","a");
fwrite($resource,date("Ymd h:i:s")."DELETE - $_SERVER[REMOTE_ADDR]"."$_REQUEST[del]\n");
fclose($resource);
if (strpos($_REQUEST[del],"/.")>0); //possible hacking
else if (strpos($_REQUEST[del],$upload_dir) === false); //possible hacking
else if (substr($_REQUEST[del],0,6)==$upload_dir) {
unlink($_REQUEST[del]);
print "<script>window.location.href='$url_this?message=deleted successfully'</script>";
}
}
else if ($_FILES['userfile']) {
$resource = fopen("log.txt","a");
fwrite($resource,date("Ymd h:i:s")."UPLOAD - $_SERVER[REMOTE_ADDR]"
.$_FILES['userfile']['name']." "
.$_FILES['userfile']['type']."\n");
fclose($resource);
$file_type = $_FILES['userfile']['type'];
$file_name = $_FILES['userfile']['name'];
$file_ext = strtolower(substr($file_name,strrpos($file_name,".")));
//File Size Check
if ( $_FILES['userfile']['size'] > $MAX_SIZE)
$message = "The file size is over the limit.";
//File Type/Extension Check
// else if (!in_array($file_type, $FILE_MIMES)
// && !in_array($file_ext, $FILE_EXTS) )
// $message = "Sorry, $file_name($file_type) is not allowed to be uploaded.";
else if (in_array($file_ext, $FILE_EXTS_FORBIDEN))
$message = "Sorry, $file_name($file_type) is not allowed to be uploaded.";
else
$message = do_upload($upload_dir, $upload_url);
// print "<script>window.location.href='$url_this?message=$message'</script>";
}
else if (!$_FILES['userfile']);
else
$message = "Invalid File Specified.";
/************************************************************
* List Files
************************************************************/
/*
$handle=opendir($upload_dir);
$filelist = "";
while ($file = readdir($handle)) {
if(!is_dir($file) && !is_link($file)) {
$filelist .= "<a href='$upload_dir$file'>".$file."</a>";
if ($DELETABLE)
$filelist .= " <a href='?del=$upload_dir$file' title='delete'>x</a>";
$filelist .= "<sub><small><small><font color=grey> ".date("d-m H:i", filemtime($upload_dir.$file))
."</font></small></small></sub>";
$filelist .="<br>";
}
}
*/
function do_upload($upload_dir, $upload_url) {
$temp_name = $_FILES['userfile']['tmp_name'];
$file_name = $_FILES['userfile']['name'];
$file_name = str_replace("\\","",$file_name);
$file_name = str_replace("'","",$file_name);
//SAFETY CHECK:
$file_name= preg_replace('[^a-zA-Z0-9 .&<>~()_[\]\-]', '', $file_name);
$file_path = $upload_dir.$file_name;
//File Name Check
if ( $file_name =="") {
$message = "Invalid File Name Specified.";
return $message;
}
if ( is_file($file_path)) {
$message = "This file is already uploaded. Please change the name of the file before uploading it.";
return $message;
}
if($_REQUEST['emailto'] != '' && (!eregi("^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}$", $_REQUEST['emailto'])))
{ $message = "Invalid E-mail.";
return $message;
}
$missatge2= str_replace ( "\r", '', $_REQUEST['missatge'] );
$informacio = $_REQUEST['emailto'] . "\n" . $_REQUEST['ips'] . "\n" . $_REQUEST['username'] . "\n" . $_REQUEST['key'] . "\n" . $_REQUEST['subjecte'] . "\n" . addslashes($missatge2);
$fp = fopen ($file_path . '.info',"w");
fwrite($fp, $informacio);
fclose($fp);
$keyurl = "";
if ($_REQUEST['key'] != "")
{
$keyurl = '?key=' . $_REQUEST['key'];
}
$result = move_uploaded_file($temp_name, $file_path);
if (!chmod($file_path,0666))
{ $message = "File change permission failed.";
}
else
{
// {$message = ($result)?"$file_name uploaded correctly. This is the URL:<br><big><big><big>https:/files.logicaspace.com/$file_name$keyurl</big></big></big>" : "Somthing is wrong with uploading a file.";
$file_nameURL = urlencode($file_name);
if ($result)
die ("<center><br><br><br><br><br>$file_name uploaded correctly. This is the URL to share:<br><br><big><big>https://files.logicaspace.com/$file_nameURL$keyurl</big></big><br><br>Or inside Logica-CGI LAN:<br> <big>https://10.48.31.211/$file_nameURL$keyurl</big></center>");
else
$message = "Somthing is wrong with uploading a file.";
}
return $message;
}
// he substituit $_REQUEST[message] per $message
?>
<center>
<big><big>New Download Alert</big></big>
<br>
<font color=red><?=$message?></font>
<br>
<form name="upload" id="upload" ENCTYPE="multipart/form-data" method="post">
<table border="1" width="600" id="table1" cellspacing="1" cellpadding="0">
<tr>
<td><b>File to share</b> (Max 50GB)</td>
<td> <input type="file" id="userfile" name="userfile"></td>
</tr>
<tr>
<td><b>Your name</b> (it won't be made visible) </td>
<td> <input type="text" name="username" size="37"></td>
</tr>
<tr>
<td>(Optional) <br><b>Download Password / Unic ID to distingt different users downloading the same file</b>.
<br>You can enter the client name or client codename (ex. ESOC123456).
<br>You can leave it empty for no key authentification.</td>
<td> <input type="text" name="key" size="37" value="<?php echo rand(1000, 9999) . date("YmdGis"); ?>"></td>
</tr>
<tr>
<td><b>Your Email</b> where the download alert will be sent </td>
<td> <input type="text" name="emailto" size="37"></td>
</tr>
<tr>
<td><b>Ignore these IP's</b> (space separated)</td>
<td>
<input type="text" name="ips" size="37" value="80.153.145.11 <?php echo $_SERVER['REMOTE_ADDR'] ." ". $_SERVER['HTTP_X_FORWARDED_FOR']; ?>"></td>
</tr>
<tr>
<td><b>Mail Subject</b></td>
<td>
<input type="text" name="subjecte" size="37"></td>
</tr>
<tr>
<td colspan="2">
<p><b>Mail body</b> (ex. Description of the file and client):</p>
<p><textarea rows="12" name="missatge" cols="100"></textarea></p>
</td>
</tr>
</table>
<input type="submit" name="upload" value="Upload and configure" onclick="this.disabled=true;this.value='Sending, please wait...';this.form.submit();">
</form>
</center>