Files
Task-Management/db.php

97 lines
3.2 KiB
PHP

<?php
require_once 'config.php';
try {
$pdo = new PDO('sqlite:' . DB_FILE);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
function query($sql, $params = []) {
global $pdo;
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
return $stmt;
}
function get_user($id) {
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch();
}
function get_user_groups($user_id) {
global $pdo;
$stmt = $pdo->prepare("SELECT g.* FROM groups g JOIN user_groups ug ON g.id = ug.group_id WHERE ug.user_id = ?");
$stmt->execute([$user_id]);
return $stmt->fetchAll();
}
function notify_user($user_id, $message) {
global $pdo;
$stmt = $pdo->prepare("INSERT INTO notifications (user_id, message) VALUES (?, ?)");
$stmt->execute([$user_id, $message]);
// Virtual hook for Email/Telegram/WhatsApp based on user features
$user = get_user($user_id);
if($user && isset($user['notify_channels'])) {
$channels = explode(',', $user['notify_channels']);
// Here we would actually send the message to the third party API.
// For MVP we just assume it's sent.
}
}
function notify_group($group_id, $message) {
global $pdo;
$stmt = $pdo->prepare("SELECT user_id FROM user_groups WHERE group_id = ?");
$stmt->execute([$group_id]);
$users = $stmt->fetchAll();
foreach ($users as $u) {
notify_user($u['user_id'], $message);
}
}
function notify_waha($action, $module, $item_name) {
global $pdo;
try {
$u_id = $_SESSION['user_id'] ?? 0;
$current_user_name = "System";
if($u_id) {
$u = get_user($u_id);
if($u) $current_user_name = $u['username'];
}
$stmt = $pdo->query("SELECT waha_endpoint, waha_chat_id, waha_template FROM users WHERE notify_channels LIKE '%whatsapp%' AND waha_endpoint IS NOT NULL AND waha_endpoint != ''");
while ($user = $stmt->fetch()) {
$endpoint = $user['waha_endpoint'];
$chat_id = $user['waha_chat_id'];
$template = $user['waha_template'] ?: "*Update:* {action} on {module} '{item}' by {user}";
if(!$endpoint || !$chat_id) continue;
$text = str_replace(
['{action}', '{module}', '{item}', '{user}'],
[$action, $module, $item_name, $current_user_name],
$template
);
$payload = json_encode([
"chatId" => $chat_id,
"text" => $text,
"session" => "default"
]);
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_exec($ch);
curl_close($ch);
}
} catch(Exception $e) {}
}