From 35141c66e9ec00186754c6bc7a28753b6f3a1ba9 Mon Sep 17 00:00:00 2001
From: Lucifer <hrv111201@gmail.com>
Date: Tue, 5 Dec 2023 17:48:49 +0000
Subject: [PATCH] post.class,php traits,login changes,uploads feature

---
 htdocs/__templates/index/__calltact.php       | 24 ++++++---
 htdocs/__templates/login.php                  | 33 +++++++++---
 htdocs/__templates/settings.php               |  7 +++
 .../post.class.php => app/like.class.php}     |  0
 htdocs/libs/app/post.class.php                | 45 ++++++++++++++++
 htdocs/libs/includes/sessions.class.php       |  6 ++-
 htdocs/libs/includes/user.class.php           |  5 +-
 htdocs/libs/load.php                          |  3 +-
 htdocs/libs/traits/SQLGetterSetter.trait.php  | 51 +++++++++++++++++++
 htdocs/settings.php                           |  5 ++
 htdocs/testuser.php                           | 41 ++-------------
 project/photogramconfig.json                  |  3 +-
 12 files changed, 163 insertions(+), 60 deletions(-)
 create mode 100644 htdocs/__templates/settings.php
 rename htdocs/libs/{includes/post.class.php => app/like.class.php} (100%)
 create mode 100644 htdocs/libs/app/post.class.php
 create mode 100644 htdocs/libs/traits/SQLGetterSetter.trait.php
 create mode 100644 htdocs/settings.php

diff --git a/htdocs/__templates/index/__calltact.php b/htdocs/__templates/index/__calltact.php
index 2960896..961c350 100644
--- a/htdocs/__templates/index/__calltact.php
+++ b/htdocs/__templates/index/__calltact.php
@@ -1,12 +1,20 @@
 <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">Wanna To Get Started</h1>
-			<p class="lead text-muted">We took an oauth preserve your memories with unique snaps and you...?</p>
-			<p>
-				<a href="#" class="btn btn-success my-2">upload</a>
-				<a href="#" class="btn btn-danger my-2">clear</a>
-			</p>
-		</div>
+		<form method="post" action="/testuser.php" enctype="multipart/form-data">
+			<div class="col-lg-6 col-md-8 mx-auto">
+				<h1 class="fw-light">Wanna Get Started</h1>
+				<p class="lead text-muted">We took an oath to preserve your memories with unique snaps and you...?</p>
+				<textarea id="post_text" name="post_text" class="form-control" placeholder="Wanna Get Started"
+					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">upload</button>
+					<!-- <a href="#" class="btn btn-danger my-2">clear</a> -->
+				</p>
+			</div>
+		</form>
 	</div>
 </section>
\ No newline at end of file
diff --git a/htdocs/__templates/login.php b/htdocs/__templates/login.php
index 8de44cc..fbb0a6b 100644
--- a/htdocs/__templates/login.php
+++ b/htdocs/__templates/login.php
@@ -9,24 +9,32 @@ if(isset($_POST['password']) and isset($_POST['Username'])) {
 }?>
 <?php
 if($login) {
-    if($result) {?>
+    if($result) {
+        $should_redirect = sessions::get('_redirect');
+        $redirect_usual = get_config('base_path');
+        if (isset($should_redirect)) {
+            $redirect_usual = $should_redirect;
+            sessions::set('_redirect', false);
+        }?>
 <script>
-	window.location.href = "<?=get_config('base_path')?>"
+	window.location.href = "<?=$redirect_usual?>"
 	/* just a simple rerdirection via javascript */
 </script>
 <?php } else {?>
-<div class="my-5">
+<!-- <div class="my-5">
 	<div class="p-5 text-center bg-body-tertiary">
 		<div class="container py-5">
 			<h1 class="text-body-emphasis">Oops Login Failed incorrect username or password</h1>
 			<p class="col-lg-8 mx-auto lead">
-			<p>please<a
-					href="<?php get_config("base_path")?>login.php">tryagain</a>
+			<p>please<a href="/login.php">tryagain</a>
 				by clicking</p>
 			</p>
 		</div>
 	</div>
-</div>
+</div> -->
+<script>
+	window.location.href = "/login.php?error=1"
+</script><!--good in user experience point of view-->
 <?php }
 } else {?>
 <main class="form-signin w-100 m-auto">
@@ -35,7 +43,15 @@ if($login) {
 			src="<?php get_config("base_path")?>assets/img/logo.png"
 			alt="poke img" width="300" height="150">
 		<h1 class="h3 mb-3 fw-normal">Please Log in</h1>
-
+		<?php
+        if($_GET["error"]) {
+            ?>
+		<div class="alert alert-danger" role="alert">
+			Invalid Credentials
+		</div>
+		<?php
+        }
+    ?>
 		<div class="form-floating">
 			<input name="Username" type="text" class="form-control" id="floatingInput" placeholder="Username" width="40"
 				height="60">
@@ -60,7 +76,8 @@ if($login) {
 		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/hover.css/2.3.1/css/hover-min.css"
 			integrity="sha512-csw0Ma4oXCAgd/d4nTcpoEoz4nYvvnk21a8VA2h2dzhPAvjbUIK6V3si7/g/HehwdunqqW18RwCJKpD7rL67Xg=="
 			crossorigin="anonymous" referrerpolicy="no-referrer" />
-		<button class="btn btn-primary w-100 py-2 hvr-bounce-out" type="submit">login</button>
+		<button class="btn btn-primary w-100 py-2 hvr-bounce-out" type="submit">Login</button>
+		<a href="/signup.php" class="w-100 btn-link">create account</a>
 
 		<!--<p class="mt-5 mb-3 text-body-secondary">&copy; 2017–2023</p>-->
 	</form>
diff --git a/htdocs/__templates/settings.php b/htdocs/__templates/settings.php
new file mode 100644
index 0000000..13098b5
--- /dev/null
+++ b/htdocs/__templates/settings.php
@@ -0,0 +1,7 @@
+<?php
+
+if (sessions::isAuthenticated()) {
+    echo 'yes';
+} else {
+    echo 'No';
+}
diff --git a/htdocs/libs/includes/post.class.php b/htdocs/libs/app/like.class.php
similarity index 100%
rename from htdocs/libs/includes/post.class.php
rename to htdocs/libs/app/like.class.php
diff --git a/htdocs/libs/app/post.class.php b/htdocs/libs/app/post.class.php
new file mode 100644
index 0000000..76d3fe4
--- /dev/null
+++ b/htdocs/libs/app/post.class.php
@@ -0,0 +1,45 @@
+<?php
+
+include_once __DIR__ . "/../traits/SQLGetterSetter.trait.php";
+class posts
+{
+    use SQLGetterSetter;
+    private $conn;
+    public $id;
+    private $table;
+    public static function registerpost($text, $image_tmp)
+    {
+        if (isset($_FILES['post_image'])) {
+            $author = sessions::getUser()->getEmail();
+            $image_name = md5($author . time()) . ".jpg" ;#TODO:change hash algo
+            $image_path = get_config('upload_path') . $image_name;
+            if (move_uploaded_file($image_tmp, $image_path)) {
+                //move_uploaded_file() moves files from specific path to the desired location.
+                $insert_command = "INSERT INTO `posts` (`post_text`, `image_uri`, `like_count`, `time_stamp`, `owner`)
+                VALUES ('$text', 'https://images.pexels.com/photos/462118/pexels-photo-462118.jpeg?cs=srgb&dl=bloom-blooming-blossom-462118.jpg&fm=jpg', '0', now(), '$author')";
+                $db = database::getconnetion();
+                if($db->query($insert_command)) {
+                    $id = mysqli_insert_id($db);
+                    return new posts($id);
+                } else {
+                    return false;
+                }
+
+            }
+        } else {
+            throw new Exception("no image available");
+        }
+
+    }
+
+
+    public function __construct($id)
+    {
+        $this->id = $id;
+        $this->conn = database::getconnetion();
+        $this->table = 'posts';
+
+    }
+
+
+}
diff --git a/htdocs/libs/includes/sessions.class.php b/htdocs/libs/includes/sessions.class.php
index f9557b0..73a7d07 100644
--- a/htdocs/libs/includes/sessions.class.php
+++ b/htdocs/libs/includes/sessions.class.php
@@ -60,7 +60,7 @@ class sessions
     }
     public static function currentScript()
     {
-        return basename($_SERVER['SCRIPT_NAME'], '.php');
+        return basename($_SERVER['SCRIPT_NAME'], ".php");
     }
     public static function getUser()
     {
@@ -83,8 +83,10 @@ class sessions
     public static function ensureLogin()
     {
         if(!sessions::isAuthenticated()) {
+            sessions::set('_redirect', $_SERVER['REQUEST_URI']);//reuest_uri gives the exact page that we are trying to load
             header("Location: /login.php");
+            die();
         }
-        die();
+
     }
 }
diff --git a/htdocs/libs/includes/user.class.php b/htdocs/libs/includes/user.class.php
index a995254..d8ed673 100644
--- a/htdocs/libs/includes/user.class.php
+++ b/htdocs/libs/includes/user.class.php
@@ -68,6 +68,7 @@ class user
     //in __construct we are fetching the username using username and the Id allotted to that user from the userSession
     public function __construct($username)
     {
+        $this->table = 'user_data';
         $this->conn = database::getconnetion();
         $this->username = $username;
         $sql = "SELECT*FROM user_data WHERE `Username`='$username'OR`ID`='$username'";
@@ -91,7 +92,7 @@ class user
             $this->conn = database::getconnetion();
         }
         TODO:/* They have replaced user_personal with users if needed that change has to be done*/
-        $sql = "UPDATE user_personal SET $variable ='$data[0]' WHERE ID ='$this->id' " ;
+        $sql = "UPDATE '$this->table' SET $variable ='$data[0]' WHERE ID ='$this->id' " ;
         if($this->conn->query($sql)) {
             return true;
         } else {
@@ -104,7 +105,7 @@ class user
         {
             $this->conn = database::getconnetion();
         }
-        $sql = "SELECT $variable FROM user_personal WHERE ID='$this->id'";
+        $sql = "SELECT $variable FROM '$this->table' WHERE ID='$this->id'";
         $result = $this->conn->query($sql);
         if($result->num_rows === 1) {
             $row = $result->fetch_assoc();
diff --git a/htdocs/libs/load.php b/htdocs/libs/load.php
index c739ae0..b92a1c7 100644
--- a/htdocs/libs/load.php
+++ b/htdocs/libs/load.php
@@ -6,7 +6,8 @@ include_once 'includes/user.class.php';
 include_once 'includes/sessions.class.php';
 include_once  'includes/userSession.class.php';
 include_once 'includes/webApi.class.php';
-
+include_once 'app/post.class.php';
+include_once 'traits/SQLGetterSetter.trait.php';
 /*we include each and every single classes and files in load.php inorder to make sure everthing is imported to the
 file we are working just by including the load.php.............that's main idea over here. */
 
diff --git a/htdocs/libs/traits/SQLGetterSetter.trait.php b/htdocs/libs/traits/SQLGetterSetter.trait.php
new file mode 100644
index 0000000..af84b6a
--- /dev/null
+++ b/htdocs/libs/traits/SQLGetterSetter.trait.php
@@ -0,0 +1,51 @@
+<?php
+
+trait SQLGetterSetter
+{
+    public function __call($name, $arguments)/* here this $arguments is of default enumarated array function which
+    consists of the passed parameters so if you wanted to call a value where this is saved just call or use like
+    exactly how you treat the array $arguments[0],[1] and soooo onnnn */
+    {
+        //$name = "getBio";
+        $property = preg_replace("/[^0-9a-zA-Z]/", "", substr($name, 3));
+        //this regex removes the get and returns the remaining with the help of substr function which actually
+        //has to be provided with a string input,offset(where to start),length in our func above it removes first three letters
+        $property = strtolower(preg_replace('/\B([A-Z])/', '_$1', $property));
+        //this regex converts camelcase to sanke case eg HarishRagavenDhar=>harish_ragaven_dhar;
+        if(substr($name, 0, 3) == "get") {
+            return $this->_get_data($property);
+        } elseif(substr($name, 0, 3) == "set") {
+            return $this->_set_data($property, $arguments);
+        } else {
+            throw new Exception("No such function is available");
+        }
+    }
+
+    private function _set_data($variable, $data)
+    {
+        if(!$this->conn) {
+            $this->conn = database::getconnetion();
+        }
+        TODO:/* They have replaced user_personal with users if needed that change has to be done*/
+        $sql = "UPDATE $this->table SET $variable ='$data[0]' WHERE ID ='$this->id' " ;
+        if($this->conn->query($sql)) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+    private function _get_data($variable)
+    {
+        if(!$this->conn);
+        {
+            $this->conn = database::getconnetion();
+        }
+        $sql = "SELECT $variable FROM $this->table WHERE ID='$this->id' ";
+        $result = $this->conn->query($sql);
+        if($result->num_rows === 1) {
+            $row = $result->fetch_assoc();
+            return $row[$variable];
+        }
+
+    }
+}
diff --git a/htdocs/settings.php b/htdocs/settings.php
new file mode 100644
index 0000000..52704b2
--- /dev/null
+++ b/htdocs/settings.php
@@ -0,0 +1,5 @@
+<?php
+
+include "libs/load.php";
+sessions::ensureLogin();
+sessions::renderPage();
diff --git a/htdocs/testuser.php b/htdocs/testuser.php
index 349dd32..d0d5bca 100644
--- a/htdocs/testuser.php
+++ b/htdocs/testuser.php
@@ -1,40 +1,5 @@
-<pre>
 <?php
 
-include "libs/load.php";
-
-$user = 'Sasuke_uchiha';
-$password = 'Chidori';
-
-//userSession::Authenticate($user, $password);
-//userSession::authorize();
-$conn = database::getconnetion();
-$sql = "SELECT*FROM `session` WHERE `id`='12' ";
-
-$fingerprint = $_POST['fingerprint'];
-print($fingerprint);
-/* if ($conn->query($sql)->num_rows === 1) {
-    $row = $conn->query($sql)->fetch_assoc();
-    $ip = $row['ip'];
-    print($ip."<br>\n");
-    $useragent = $row['user_agent'];
-    print($useragent."<br>\n");
-
-} *///print_r($_COOKIE['fingerprint'])
-?><br><?php
-
-// print_r($_SERVER['REMOTE_ADDR'].'<br>');
-// print_r($_SERVER['HTTP_USER_AGENT']);
-// print_r($fingerprint);
-?>
-</pre><?php
-// $user1 = new user("Sasuke_uchiha");
-// $avatar = 8888;
-// $user1->setAvatar($avatar);
-// print_r($user1->getAvatar());
-//print_r($_SERVER);
-
-// $sess = new userSession(null);
-// $newtime = time() + 3600;
-// print(time());
-// print($newtime);?>
\ No newline at end of file
+include 'libs/load.php';
+$a = new posts(1);
+echo $a->getOwner();
diff --git a/project/photogramconfig.json b/project/photogramconfig.json
index 60552d1..fc193bf 100644
--- a/project/photogramconfig.json
+++ b/project/photogramconfig.json
@@ -3,5 +3,6 @@
 "db_user":"HarishRaghav",
 "db_pass":"@7532159$",
 "db_name":"HarishRaghav_Photogram",
-"base_path":"/"
+"base_path":"/",
+"upload_path":"/home/Lucifer/photogram_uploads"
 }
-- 
GitLab