<?php
/*
Name: Droppy - Online file sharing
Author: Proxibolt
File: action.php
*/

ob_start();

ignore_user_abort(true);

//Including files
require_once dirname(__FILE__) . '/../config/config.php';
require_once dirname(__FILE__) . '/plugins/class.phpmailer.php';
require_once dirname(__FILE__) . '/plugins/class.smtp.php';
require_once dirname(__FILE__) . '/plugins/timeconvert.php';
require_once dirname(__FILE__) . '/../resources/class/upload.class.php';

$upload = new Upload();

//Getting the post "action"
switch ($_POST['action']) {
	case 'login':
		$email = mysqli_real_escape_string($mysqli, $_POST['email']);
		$password = md5(mysqli_real_escape_string($mysqli, $_POST['password']));

		$get_user = $mysqli->query("SELECT * FROM $table_users WHERE email='$email' AND password='$password'");
		if($email != '' || $password != '' || $email != null || $password != null) {
			if($get_user->num_rows == 1) {
				$_SESSION['droppy_user'] = $email;
				header('Location: ../index.php');
			}
			else
			{
				header('Location: ../login.php?login=wrong');
			}
		}
		else
		{
			header('Location: ../login.php?login=fields');
		}
	break;
	//When download
	case 'download':
	    // Set ini settings (When enabled)
        if($set_ini_settings) {
            ini_set('max_execution_time', '0');
            ini_set('max_input_time', '-1');
            ini_set('post_max_size', $max_file_size . 'M');
            ini_set('upload_max_filesize', $max_file_size . 'M');
        }

		//Get some info from the POST
		$download_id = mysqli_real_escape_string($mysqli, $_POST['download_id']);
		$secret_code = mysqli_real_escape_string($mysqli, $_POST['secret_code']);
		$private_id = mysqli_real_escape_string($mysqli, $_POST['private_id']); 
		$get_downloader_info = $mysqli->query("SELECT * FROM $table_receivers WHERE upload_id='$download_id' AND private_id='$private_id'");
		while($get_downloader_email = $get_downloader_info->fetch_assoc()) {
			$download_email = $get_downloader_email['email'];
		}

		//Getting some other data
		$time = time();
		$ip_address = $_SERVER['REMOTE_ADDR'];

		$email_list = '<ul>';
		$get_receivers = $mysqli->query("SELECT * FROM $table_receivers WHERE upload_id='$download_id'");
		while($row = $get_receivers->fetch_assoc()) {
			$email_list .= '<li>' . $row['email'] . '</li>';
		}
		$email_list .= '</ul>';

		$file_list = '<ul>';
		$get_files = $mysqli->query("SELECT * FROM $table_files WHERE upload_id='$download_id'");
		while($row = $get_files->fetch_assoc()) {
			$file_list .= '<li>' . $row['file'] . '</li>';
		}
		$file_list .= '</ul>';

		// Get information about the upload
        $get_info = $mysqli->query("SELECT * FROM $table_uploads WHERE upload_id='$download_id' AND secret_code='$secret_code' AND status='ready'");
        $get_file_info = $mysqli->query("SELECT * FROM $table_files WHERE upload_id='$download_id'");

		while($rows = $get_info->fetch_assoc()) {

			if(empty($rows['lang'])) {
				$upload_language = $language;
			}
			else
			{
				$upload_language = $rows['lang'];
			}

			$tokens = array(
			    'email_from' => $rows['email_from'],
			    'size' => round($rows['size'] / 1048576, 2),
			    'site_name' => $site_name,
			    'upload_id' => $rows['upload_id'],
			    'message' => $rows['message'],
			    'total_files' => $rows['count'],
			    'download_email' => $download_email,
			    'download_btn' => '<a href="' . $site_url . $download_id . '&p=' . $private_id . '" style="text-decoration: none;color: #FFF;background-color: #348eda;border: solid #348eda;border-width: 10px 20px;line-height: 2;font-weight: bold;margin-right: 10px;text-align: center;cursor: pointer;display: inline-block;border-radius: 25px;">' . $text['download'] . '</a>',
	            'download_url' => $site_url . $download_id . '&p=' . $private_id,
	            'file_list' => $file_list,
	            'email_list' => $email_list,
	            'expire_time' => secs_to_h($expire),
			);

			$pattern = '{%s}';

			$map = array();
			foreach($tokens as $var => $value)
			{
			    $map[sprintf($pattern, $var)] = $value;
			}

			$message_destruct = strtr(requestTemplate('destroyed',$upload_language), $map);
			$message_downloaded = strtr(requestTemplate('downloaded',$upload_language), $map);
			$downloaded_subject = strtr(requestTemplate('downloaded_subject',$upload_language), $map);
			$destroyed_subject = strtr(requestTemplate('destroyed_subject',$upload_language), $map);

			if(isset($amazon_plugin) && $amazon_plugin == 'true') {
	    		include_once $amazon_dir . '/download.php';
			}
			elseif(isset($ftp_plugin) && $ftp_plugin == 'true') {
	    		include_once $ftp_dir . '/download.php';
			}
			else
			{
			    // Check if the password has been set and if it's correct
				if((isset($_POST['password']) && $rows['password'] != 'EMPTY' && $rows['password'] == md5($_POST['password'])) || $rows['password'] == 'EMPTY') {
				    // Check if the file is a single file or a zip file
                    if($rows['count'] > 1) {
                        // Some information about the zip file.
                        $zipname = $name_on_file . '-' . $download_id . '.zip';
                        $ziplocation = dirname(__FILE__) . '/../' . $upload_dir . $name_on_file . '-' . $rows['upload_id'] . '.zip';

                        // Stream the download
                        header('Content-Description: File Transfer');
                        header('Content-Type: application/zip');
                        header('Content-Disposition: attachment; filename="'.$zipname.'"');
                        header('Content-Transfer-Encoding: binary');
                        header('Expires: 0');
                        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                        header("Cache-Control: public");
                        header('Pragma: public');
                        header('Content-Length: ' . filesize($ziplocation));

                        ob_clean();
                        ob_end_flush();
                        session_write_close();

                        // Check if the file has beene encrypted, if so then decrypt it.
                        if(!empty($rows['encrypt'])) {
                            require_once dirname(__FILE__) . '/../resources/class/encrypt.class.php';
                            $encrypt = new Encrypt();

                            $file = $encrypt->decryptfile($ziplocation,$rows['encrypt']);
                        }
                        else
                        {
                            $file = @fopen($ziplocation,"rb");
                        }

                        while(!feof($file))
                        {
                            print(@fread($file, 1024*8));
                            ob_flush();
                            flush();
                        }

                        $check_download = $mysqli->query("SELECT * FROM $table_downloads WHERE download_id='$download_id' AND email='$download_email'");
                        if($check_download->num_rows == 0 && $download_email != '') {
                            //Send the download notification email
                            emailSender($message_downloaded,$downloaded_subject,$rows['email_from']);
                        }

                        if(!empty($download_email)) {
                            $mysqli->query("INSERT INTO $table_downloads (download_id, time, ip, email) VALUES ('$download_id','$time','$ip_address','$download_email')");
                        }
                        else
                        {
                            $mysqli->query("INSERT INTO $table_downloads (download_id, time, ip, email) VALUES ('$download_id','$time','$ip_address','')");
                        }

                        if($rows['destruct'] == 'YES') {
                            if($rows['share'] == 'mail' && $download_email != '') {
                                $get_downloads_info = $mysqli->query("SELECT * FROM $table_downloads WHERE download_id='$download_id'");
                                $get_receivers_info = $mysqli->query("SELECT * FROM $table_receivers WHERE upload_id='$download_id'");
                                if($get_downloads_info->num_rows == $get_receivers_info->num_rows) {
                                    //Remove the zip file
                                    unlink('../' . $upload_dir . $name_on_file . '-' . $rows['upload_id'] . '.zip');

                                    //Set status to destroyed
                                    $mysqli->query("UPDATE $table_uploads SET status='destroyed' WHERE upload_id='$download_id' AND secret_code='$secret_code'");

                                    //Send the destructed notification email
                                    emailSender($message_destruct,$destroyed_subject,$rows['email_from']);
                                }
                            }
                            elseif($rows['share'] == 'link')
                            {
                                //Remove the zip file
                                unlink('../' . $upload_dir . $name_on_file . '-' . $rows['upload_id'] . '.zip');

                                //Set status to destroyed
                                $mysqli->query("UPDATE $table_uploads SET status='destroyed' WHERE upload_id='$download_id' AND secret_code='$secret_code'");
                            }
                        }
                    }
                    else {
                        //Get some info about the file.
                        $get_file_info = $mysqli->query("SELECT * FROM $table_files WHERE upload_id='$download_id'");
                        while ($row = $get_file_info->fetch_assoc()) {
                            // Stream the download
                            header('Content-Description: File Transfer');
                            header('Content-Type: application/octet-stream');
                            header('Content-Disposition: attachment; filename="' . $row['file'] . '"');
                            header('Content-Transfer-Encoding: binary');
                            header('Expires: 0');
                            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                            header("Cache-Control: public");
                            header('Pragma: public');
                            header('Content-Length: ' . filesize('../' . $upload_dir . $row['secret_code'] . '-' . $row['file']));

                            ob_clean();
                            ob_end_flush();
                            session_write_close();

                            // Check if the file has beene encrypted, if so then decrypt it.
                            if(!empty($rows['encrypt'])) {
                                require_once dirname(__FILE__) . '/../resources/class/encrypt.class.php';
                                $encrypt = new Encrypt();

                                $file = $encrypt->decryptfile(dirname(__FILE__) . '/../' . $upload_dir . $row['secret_code'] . '-' . $row['file'], $rows['encrypt']);
                            }
                            else
                            {
                                $file = @fopen(dirname(__FILE__) . '/../' . $upload_dir . $row['secret_code'] . '-' . $row['file'], "rb");
                            }

                            while (!feof($file)) {
                                print(@fread($file, 1024 * 8));
                                ob_flush();
                                flush();
                            }

                            $check_download = $mysqli->query("SELECT * FROM $table_downloads WHERE download_id='$download_id' AND email='$download_email'");
                            if ($check_download->num_rows == 0 && $rows['share'] == 'mail' && $download_email != '') {
                                //Sending the downloaded notification email
                                emailSender($message_downloaded, $downloaded_subject, $rows['email_from']);
                            }

                            if (!empty($download_email)) {
                                $mysqli->query("INSERT INTO $table_downloads (download_id, time, ip, email) VALUES ('$download_id','$time','$ip_address','$download_email')");
                            } else {
                                $mysqli->query("INSERT INTO $table_downloads (download_id, time, ip, email) VALUES ('$download_id','$time','$ip_address','')");
                            }

                            if ($rows['destruct'] == 'YES') {
                                if ($rows['share'] == 'mail' && $download_email != '') {
                                    $get_downloads_info = $mysqli->query("SELECT * FROM $table_downloads WHERE download_id='$download_id'");
                                    $get_receivers_info = $mysqli->query("SELECT * FROM $table_receivers WHERE upload_id='$download_id'");
                                    if ($get_downloads_info->num_rows == $get_receivers_info->num_rows) {
                                        //Set status to destroyed
                                        $mysqli->query("UPDATE $table_uploads SET status='destroyed' WHERE upload_id='$download_id'");

                                        //Remove other files from files directory
                                        unlink('../' . $upload_dir . $row['secret_code'] . '-' . $row['file']);

                                        //Sending the destructed notification email
                                        emailSender($message_destruct, $destroyed_subject, $rows['email_from']);
                                    }
                                } elseif ($rows['share'] == 'link') {
                                    //Set status to destroyed
                                    $mysqli->query("UPDATE $table_uploads SET status='destroyed' WHERE upload_id='$download_id'");

                                    unlink('../' . $upload_dir . $row['secret_code'] . '-' . $row['file']);
                                }
                            }
                        }
                    }
                }
                else
                {
                    if(isset($download_email)) {
                        header("Location: ../" . $download_id . "&m=" . $download_email . "&e=wrong");
                    }
                    else
                    {
                        header("Location: ../" . $download_id . "&e=wrong");
                    }
                }
			}	
		}
	break;
	case 'report':
		$id = mysqli_real_escape_string($mysqli, $_POST['id']);
		$get_file_reports = $mysqli->query("SELECT * FROM $table_uploads WHERE upload_id='$id'");
		while($row = $get_file_reports->fetch_assoc()) {
			if($max_file_reports != 0 && $row['flag'] + 1 == $max_file_reports) {
				$upload->delete($id);
			}
			else
			{
				$total_reports = $row['flag'] + 1;
				$mysqli->query("UPDATE $table_uploads SET flag='$total_reports' WHERE upload_id='$id'");
			}
		}

		header('Location: ../' . $id . '?msg=reported');
	break;
	case 'terms':
		setcookie("terms", "accepted");
		header('Location: ../' . $_POST['id']);
	break;
}
switch ($_GET['action']) {
	case 'lang':
		$get_lang = mysqli_real_escape_string($mysqli, $_GET['lang']);
		
		setcookie("language", $get_lang, time()+3600*24*365*10, '/');
		header('Location: ../index.php');
	break;
	case 'logout':
		session_destroy();
		header('Location: ../index.php');
	break;
	case 'acceptterms':
		setcookie('droppy_terms', '1', time() + (10 * 365 * 24 * 60 * 60), "/");
		header('Location: ../index.php');
	break;
}
?>