Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

merge with main #15

Merged
merged 9 commits into from
Dec 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .htaccess
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Enable PHP error reporting
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_value error_log /home/student/iee/2020/iee2020202/logs/PHP_errors.log

# Access control for this directory
<Files "users.php">
Require all granted
</Files>

# URL Rewriting to handle dynamic routes for users.php
RewriteEngine On
RewriteRule ^users$ /ADISE24_DreamTeam/lib/users.php [L]

# Only rewrite if the requested URL is not an existing file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all requests to users.php with the original requested path as a query parameter
RewriteRule ^(.*)$ /~iee2020202/ADISE24_DreamTeam/lib/users.php?path=$1 [QSA,L]

17 changes: 17 additions & 0 deletions ADISE24_DreamTeam.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot /home/student/iee/2020/iee2020202/public_html/ADISE24_DreamTeam
ServerName users.iee.ihu.gr
ServerAlias www.users.iee.ihu.gr

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory /home/student/iee/2020/iee2020202/public_html/ADISE24_DreamTeam>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

</VirtualHost>

4 changes: 3 additions & 1 deletion README.md
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# README: Blokus Online Game

https://iee-ihu-gr-course1941.github.io/ADISE24_DreamTeam/

Αυτό το έργο αφορά την ανάπτυξη ενός online παιχνιδιού **Blokus** σύμφωνα με τις απαιτήσεις που έχουν καθοριστεί από την εργασία της πανεπιστημιακής μας ομάδας. Το παιχνίδι επιτρέπει στους χρήστες να παίξουν έναντι άλλου μέσω ενός GUI (Graphical User Interface) με την υποστήριξη Web API και χρήσης τεχνολογιών όπως PHP, MySQL, AJAX και jQuery.

## 1. Εισαγωγή
Expand Down Expand Up @@ -63,4 +65,4 @@
### 5.2. Εγκατάσταση
1. **Κλωνοποιήστε το έργο από το GitHub (ή κατεβάστε το zip αρχείο).**
```bash
git clone https://github.com/iee-ihu-gr-course1941/ADISE24_DreamTeam.git
git clone https://github.com/iee-ihu-gr-course1941/ADISE24_DreamTeam.git
45 changes: 45 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const API_URL = "https://users.iee.ihu.gr/~iee2020202/ADISE24_DreamTeam/blokus.php/users/";

// Handle login
$("#loginForm").on("submit", function (event) {
event.preventDefault();

const userId = $("#userId").val();

$.ajax({
url: API_URL + userId,
method: "GET",
success: function (response) {
if (response && response.id) {
// Save user info in sessionStorage
sessionStorage.setItem("loggedInUser", JSON.stringify(response));
window.location.href = "stats.html"; // Redirect to stats page
} else {
$("#errorMessage").text("Invalid User ID").show();
}
},
error: function () {
$("#errorMessage").text("Unable to fetch user data. Please try again.").show();
},
});
});

// Redirect to login if not logged in
if (window.location.pathname.endsWith("stats.html")) {
const loggedInUser = sessionStorage.getItem("loggedInUser");
if (!loggedInUser) {
window.location.href = "login.html";
} else {
const user = JSON.parse(loggedInUser);
$("#userId").text(user.id);
$("#username").text(user.username);
$("#email").text(user.email);
$("#createdAt").text(user.created_at);
}
}

// Logout functionality
$("#logoutBtn").on("click", function () {
sessionStorage.removeItem("loggedInUser");
});

76 changes: 76 additions & 0 deletions blokus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php
require_once "lib/dbconnect.php";
require_once "lib/users.php"; // Assuming you have user-related functions

$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'), true);
if ($input == null) {
$input = [];
}

if (isset($_SERVER['HTTP_X_TOKEN'])) {
$input['token'] = $_SERVER['HTTP_X_TOKEN'];
} else {
$input['token'] = '';
}

// Main routing logic
switch ($r = array_shift($request)) {
case 'users':
// Handle 'users' path
switch ($b = array_shift($request)) {
case '':
// Show all users
handle_users($method, $input);
break;
default:
// Show user by a specific identifier (e.g., color or ID)
handle_user($method, $b, $input);
break;
}
break;

case 'status':
// Handle 'status' path
if (sizeof($request) == 0) {
handle_status($method);
} else {
header("HTTP/1.1 404 Not Found");
}
break;

default:
// Return 404 if no valid endpoint is matched
header("HTTP/1.1 404 Not Found");
echo json_encode(['errormesg' => "Endpoint not found."]);
exit;
}

// Handler for 'users' endpoint (show all users)
function handle_users($method, $input) {
if ($method == 'GET') {
show_users(); // Assuming you have a function to show users
} else {
header('HTTP/1.1 405 Method Not Allowed');
}
}

// Handler for 'user' endpoint (show a specific user)
function handle_user($method, $identifier, $input) {
if ($method == 'GET') {
getUserProfile($identifier); // Assuming you have a function to show a specific user
} else {
header('HTTP/1.1 405 Method Not Allowed');
}
}

// Handler for 'status' endpoint
function handle_status($method) {
if ($method == 'GET') {
show_status(); // Assuming you have a function to show status
} else {
header('HTTP/1.1 405 Method Not Allowed');
}
}
?>
Empty file modified dump-blokus-202412101843.sql
100644 → 100755
Empty file.
Empty file modified index.html
100644 → 100755
Empty file.
51 changes: 35 additions & 16 deletions lib/dbconnect.php
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,25 +1,44 @@
<?php

// Include the db_upass.php file to use the connection variables
require_once "db_upass.php";

// no need fro you to see our hosr or db hehehe
$host=$DB_HOST;
$db = $DB;

$user=$DB_USER;
$pass=$DB_PASS;
/**
* Establishes a MySQL database connection using PDO.
*
* @return PDO
*/
function getDatabaseConnection() {
// Use the variables defined in db_upass.php
global $DB_HOST, $DB, $DB_USER, $DB_PASS, $UNI_HOSTNAME, $UNI_SOCKET;

// Define the custom port
$port = 3333;

// Check if we are on the university server
if (gethostname() == $UNI_HOSTNAME) {
// Use the socket path for the university server connection
$dsn = "mysql:unix_socket=$UNI_SOCKET;dbname=$DB;charset=utf8mb4";
// print "Connected to the remote server successfully.<br>";
} else {
// Standard connection string for local connection with custom port
$dsn = "mysql:host=$DB_HOST;port=$port;dbname=$DB;charset=utf8mb4";
// print "Connected to the local server successfully.<br>";
}

if(gethostname()== $UNI_HOSTNAME ) {
$mysqli = new mysqli($host, $user, $pass, $db,null,$UNI_SOCKET);
} else {
$pass=null;
$mysqli = new mysqli($host, $user, $pass, $db);
try {
// Create a new PDO instance and set error mode to exceptions
$pdo = new PDO($dsn, $DB_USER, $DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "Connected to the database successfully.<br>"; // Confirmation message
return $pdo; // Return the PDO instance
} catch (PDOException $e) {
// Handle connection failure and show an error message
die(json_encode(['success' => false, 'error' => 'Database connection failed: ' . $e->getMessage()]));
}
}

if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" .
$mysqli->connect_errno . ") " . $mysqli->connect_error;

}?>
// Call the function to establish the connection
getDatabaseConnection();
?>

139 changes: 131 additions & 8 deletions lib/users.php
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,13 +1,136 @@
<?php

require_once 'dbconnect.php';

header('Content-Type: application/json');

// Function to parse the URL (path parameter from query string)
function getPathSegments() {
$path = isset($_GET['path']) ? $_GET['path'] : '';
$segments = explode('/', trim($path, '/'));
return $segments;
}



/**
* Retrieve user profile details
*/
function getUserProfile($userId) {
$pdo = getDatabaseConnection(); // Get the PDO connection here
try {
$sql = "SELECT id, username, email, created_at FROM users WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
echo json_encode($user, JSON_PRETTY_PRINT); // Return the user's profile data as JSON
} else {
echo json_encode(['error' => 'User not found']);
}
} catch (PDOException $e) {
echo json_encode(['error' => 'Error in getUserProfile: ' . $e->getMessage()]);
}
}

/**
* Update user profile details
*/
function updateUserProfile($userId, $username, $email) {
$pdo = getDatabaseConnection(); // Get the PDO connection here
try {
$sql = "UPDATE users SET username = ?, email = ? WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$username, $email, $userId]);
return ['success' => $stmt->rowCount() > 0];
} catch (PDOException $e) {
return ['error' => 'Error in updateUserProfile: ' . $e->getMessage()];
}
}

/**
* Delete user account
*/
function deleteUser($userId) {
$pdo = getDatabaseConnection(); // Get the PDO connection here
try {
$sql = "DELETE FROM users WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$userId]);
return ['success' => $stmt->rowCount() > 0];
} catch (PDOException $e) {
return ['error' => 'Error in deleteUser: ' . $e->getMessage()];
}
}

/**
* Retrieve user's game statistics
*/
function getUserGameStats($userId) {
$pdo = getDatabaseConnection(); // Get the PDO connection here
try {
$sql = "SELECT
COUNT(CASE WHEN player1_id = ? AND winner_id = player1_id THEN 1 END) AS wins,
COUNT(CASE WHEN player2_id = ? AND winner_id = player2_id THEN 1 END) AS losses,
COUNT(game_id) AS total_games
FROM games
WHERE player1_id = ? OR player2_id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$userId, $userId, $userId, $userId]);
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
return ['error' => 'Error in getUserGameStats: ' . $e->getMessage()];
}
}

// RESTful Functions
function show_users() {
global $mysqli;
$sql = 'select username,piece_color from players';
$st = $mysqli->prepare($sql);
$st->execute();
$res = $st->get_result();
header('Content-type: application/json');
print json_encode($res->fetch_all(MYSQLI_ASSOC), JSON_PRETTY_PRINT);
$pdo = getDatabaseConnection();
$sql = 'SELECT username, piece_color FROM players';
$stmt = $pdo->prepare($sql);
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($res, JSON_PRETTY_PRINT);
}

function show_user($piece_color) {
$pdo = getDatabaseConnection();
$sql = 'SELECT username, piece_color FROM players WHERE piece_color = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$piece_color]);
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($res, JSON_PRETTY_PRINT);
}

?>
// Main Controller
$method = $_SERVER['REQUEST_METHOD'];
$segments = getPathSegments();

// Adjust paths for your directory structure
$basePath = 'ADISE24_DreamTeam/lib/users';

// Check if the request matches the base path
if ($segments[0] === 'users') {
if ($method === 'GET') {
if (count($segments) === 1) {
// If no additional segment, call show_users()
show_users();
} elseif (count($segments) === 2) {
// If additional segment, call getUserProfile($userId)
$userId = $segments[1];
getUserProfile($userId);
} else {
http_response_code(404);
echo json_encode(["error" => "Invalid endpoint"]);
}
} else {
http_response_code(405);
echo json_encode(["error" => "Method not allowed"]);
}
} else {
http_response_code(404);
echo json_encode(["error" => "Endpoint not found"]);
}

?>

Loading