git commit all base code

This commit is contained in:
2026-06-30 21:34:42 -04:00
parent 11fdf7b164
commit 1a643d7935
1452 changed files with 433360 additions and 0 deletions
+392
View File
@@ -0,0 +1,392 @@
<?php
// ============
// Alerts Class
// ============
class Alerts extends Base {
// Variables.
private $current_user_id = "";
private $current_user_name = "";
private $current_user_email = "";
private $pagination_size = 20;
private $pagination_page = 1;
// ==================
// Class Constructor.
// ==================
public function __construct() {
set_error_handler(array($this, "displayError"));
date_default_timezone_set(self::TIMEZONE);
$this->current_user_id = $_SESSION[self::USER_ID] ?? "";
$this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
$this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
$this->pagination_page = $_SESSION[self::PAGINATION_PAGE] ?? 1;
}
// ============
// Setup Alerts
// ============
public function setupAlerts() {
$alerts = $this->getAlertsPage();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($alerts, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$content = $this->applyXSL($XML, $this->getXSL("setupAlerts"));
$this->displayContent($content);
}
// =========
// Add Alert
// =========
public function addAlert() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$content = $this->applyXSL("", $this->getXSL("addAlert"));
$this->displayContent($content);
break;
case "add":
$alert_title = filter_input(INPUT_POST, "alert_title") ?: "";
$alert_starts_date = filter_input(INPUT_POST, "alert_starts_date") ?: "";
$alert_starts_time = filter_input(INPUT_POST, "alert_starts_time") ?: "";
$alert_expires_date = filter_input(INPUT_POST, "alert_expires_date") ?: "";
$alert_expires_time = filter_input(INPUT_POST, "alert_expires_time") ?: "";
$alert_message = filter_input(INPUT_POST, "alert_message") ?: "";
$alert_starts = date("Y-m-d H:i", strtotime("{$alert_starts_date} {$alert_starts_time}"));
$alert_expires = date("Y-m-d H:i", strtotime("{$alert_expires_date} {$alert_expires_time}"));
$SQL = "insert into alerts
( alert_title,
alert_started,
alert_expired,
alert_message,
alert_creator,
alert_created )
VALUES ( :alert_title,
:alert_started,
:alert_expired,
:alert_message,
:alert_creator,
:alert_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":alert_title", $alert_title);
$statement->bindValue(":alert_started", $alert_starts);
$statement->bindValue(":alert_expired", $alert_expires);
$statement->bindValue(":alert_message", $alert_message);
$statement->bindValue(":alert_creator", $this->current_user_name);
$statement->bindValue(":alert_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ============
// Delete Alert
// ============
public function deleteAlert() {
$alert_serial = filter_input(INPUT_POST, "alert_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$alert = $this->getAlert($alert_serial);
if ($alert->count() == 0) {
$this->logError("Invalid Alert ({$alert_serial}). " . __METHOD__);
}
$SQL = "delete from alerts
where alert_serial = {$alert_serial}";
$this->executeSQL($SQL);
}
// ==========
// Edit Alert
// ==========
public function editAlert() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$alert_serial = filter_input(INPUT_POST, "alert_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$alert = $this->getAlert($alert_serial);
if ($alert->count() == 0) {
$this->logError("Invalid Alert ({$alert_serial}): " . __METHOD__);
}
$content = $this->applyXSL($alert, $this->getXSL("editAlert"));
$this->displayContent($content);
break;
case "update":
$alert_serial = filter_input(INPUT_POST, "alert_serial") ?: 0;
$alert_title = filter_input(INPUT_POST, "alert_title") ?: "";
$alert_starts_date = filter_input(INPUT_POST, "alert_starts_date") ?: "";
$alert_starts_time = filter_input(INPUT_POST, "alert_starts_time") ?: "";
$alert_expires_date = filter_input(INPUT_POST, "alert_expires_date") ?: "";
$alert_expires_time = filter_input(INPUT_POST, "alert_expires_time") ?: "";
$alert_message = filter_input(INPUT_POST, "alert_message") ?: "";
$alert_starts = date("Y-m-d H:i", strtotime("{$alert_starts_date} {$alert_starts_time}"));
$alert_expires = date("Y-m-d H:i", strtotime("{$alert_expires_date} {$alert_expires_time}"));
$alert = $this->getAlert($alert_serial);
if ($alert->count() === 0) {
$this->logError("Invalid Alert ({$alert_serial}). " . __METHOD__);
}
$connection = $this->connect();
$SQL = "update alerts
set alert_title = :alert_title,
alert_started = :alert_started,
alert_expired = :alert_expired,
alert_message = :alert_message
where alert_serial = :alert_serial";
$statement = $connection->prepare($SQL);
$statement->bindValue(":alert_serial", $alert_serial);
$statement->bindValue(":alert_title", $alert_title);
$statement->bindValue(":alert_started", $alert_starts);
$statement->bindValue(":alert_expired", $alert_expires);
$statement->bindValue(":alert_message", $alert_message);
$statement->execute();
break;
default:
$this->displayHome();
}
}
// =====================
// Return a Alert Object
// =====================
public function getAlert($alert_serial = 0) {
$SQL = "select *,
date_format(alert_started, '%Y') as alert_started_year,
date_format(alert_started, '%m') as alert_started_month,
date_format(alert_started, '%b') as alert_started_month_abbreviated,
date_format(alert_started, '%M') as alert_started_month_verbose,
date_format(alert_started, '%d') as alert_started_day,
date_format(alert_started, '%a') as alert_started_day_abbreviated,
date_format(alert_started, '%W') as alert_started_day_verbose,
date_format(alert_started, '%Y-%m-%d') as alert_started_date,
date_format(alert_started, '%W, %M %D') as alert_started_date_verbose,
date_format(alert_started, '%H:%i') as alert_started_time,
date_format(alert_started, '%l:%i %p') as alert_started_time_verbose,
date_format(alert_started, '%Y-%m-%d %l:%i %p') as alert_started_verbose,
date_format(alert_expired, '%Y') as alert_expired_year,
date_format(alert_expired, '%m') as alert_expired_month,
date_format(alert_expired, '%b') as alert_expired_month_abbreviated,
date_format(alert_expired, '%M') as alert_expired_month_verbose,
date_format(alert_expired, '%d') as alert_expired_day,
date_format(alert_expired, '%a') as alert_expired_day_abbreviated,
date_format(alert_expired, '%W') as alert_expired_day_verbose,
date_format(alert_expired, '%Y-%m-%d') as alert_expired_date,
date_format(alert_expired, '%W, %M %D') as alert_expired_date_verbose,
date_format(alert_expired, '%H:%i') as alert_expired_time,
date_format(alert_expired, '%l:%i %p') as alert_expired_time_verbose,
date_format(alert_expired, '%Y-%m-%d %l:%i %p') as alert_expired_verbose
from alerts
where alert_serial = {$alert_serial}";
return $this->getTable("alerts", $SQL);
}
// ========================
// Return a Alerts Object
// ========================
public function getAlerts() {
$SQL = "select view_alerts.*
from view_alerts";
return $this->getTable("alerts", $SQL);
}
// ===========================
// Return a Alerts Page Object
// ===========================
public function getAlertsPage() {
// Find Criteria
$find_alert = filter_input(INPUT_POST, "find_alert") ?: "";
$find_words = $this->sanitizeString($find_alert);
// Show Per Page
$this->pagination_size = filter_input(INPUT_POST, "alerts_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_alerts
where alert_title regexp :alert_title";
$statement = $connection->prepare($SQL);
$statement->bindValue(":alert_title", $find_words);
$statement->execute();
$recordset = $statement->fetch(PDO::FETCH_ASSOC);
$count = (count($recordset) > 0) ? (integer) $recordset["count"] : (integer) 0;
// Pagination
$pagination = filter_input(INPUT_POST, "pagination") ?: "";
switch ($pagination) {
case "first" : $this->pagination_page = 1;
break;
case "previous" : $this->pagination_page = max(($this->pagination_page - 1), 1);
break;
case "next" : $this->pagination_page = ($this->pagination_page + 1);
break;
case "last" : $this->pagination_page = ($count / $this->pagination_size);
break;
}
$offset = (($this->pagination_page * $this->pagination_size) - $this->pagination_size);
$start = ($offset + 1);
$end = min($count, (($start + $this->pagination_size) - 1));
// Data
$SQL = "select view_alerts.*
from view_alerts
where alert_title regexp :alert_title
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":alert_title", $find_words);
$statement->execute();
$alerts = $this->getTableXML("alerts", $statement);
// Insert Pagination Attributes
$alerts->addAttribute("count", $count);
$alerts->addAttribute("start", $start);
$alerts->addAttribute("end", $end);
$alerts->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $alerts;
}
// ===============================
// Return an Active Alerts Object.
// ===============================
public function getActiveAlerts() {
$SQL = "select *,
date_format(alert_started, '%Y') as alert_started_year,
date_format(alert_started, '%m') as alert_started_month,
date_format(alert_started, '%b') as alert_started_month_abbreviated,
date_format(alert_started, '%M') as alert_started_month_verbose,
date_format(alert_started, '%d') as alert_started_day,
date_format(alert_started, '%a') as alert_started_day_abbreviated,
date_format(alert_started, '%W') as alert_started_day_verbose,
date_format(alert_started, '%Y-%m-%d') as alert_started_date,
date_format(alert_started, '%W, %M %D') as alert_started_date_verbose,
date_format(alert_started, '%H:%i') as alert_started_time,
date_format(alert_started, '%l:%i %p') as alert_started_time_verbose,
date_format(alert_started, '%Y-%m-%d %l:%i %p') as alert_started_verbose,
date_format(alert_expired, '%Y') as alert_expired_year,
date_format(alert_expired, '%m') as alert_expired_month,
date_format(alert_expired, '%b') as alert_expired_month_abbreviated,
date_format(alert_expired, '%M') as alert_expired_month_verbose,
date_format(alert_expired, '%d') as alert_expired_day,
date_format(alert_expired, '%a') as alert_expired_day_abbreviated,
date_format(alert_expired, '%W') as alert_expired_day_verbose,
date_format(alert_expired, '%Y-%m-%d') as alert_expired_date,
date_format(alert_expired, '%W, %M %D') as alert_expired_date_verbose,
date_format(alert_expired, '%H:%i') as alert_expired_time,
date_format(alert_expired, '%l:%i %p') as alert_expired_time_verbose,
date_format(alert_expired, '%Y-%m-%d %l:%i %p') as alert_expired_verbose
from alerts
where (alert_started < now() and alert_expired > now())
order by alert_expired";
$alerts = $this->getTable("alerts", $SQL);
foreach ($alerts as $alert) {
$alert->alert_time_elapsed = $this->getTimeElapsed((string) $alert->alert_started);
}
return $alerts;
}
}
?>
+393
View File
@@ -0,0 +1,393 @@
<?php
// ====================
// Authentication Class
// ====================
require_once "vendor/autoload.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class Authentication {
// Variables
private $settings = "";
private $ghrconnection = "";
// =================
// Class Constructor
// =================
public function __construct() {
// Get Settings
$this->settings = new SimpleXMLElement((file_exists("xml/settings.xml") ? file_get_contents("xml/settings.xml") : "<settings/>"));
if ($this->settings->count() === 0) {
error_log("GHR Authentication Class : Unable to initialize settings");
exit();
}
// Open Database Connections
$this->ghrconnection = $this->connect();
}
// ======================================
// Return a GHR MySQL Database Connection
// ======================================
public function connect() {
if ($this->settings->Environment == 'Production') {
$host = 'localhost';
} else {
$host = '192.168.1.190';
$host = '100.67.215.67';
}
try {
$database = (string) ($this->settings->DatabaseName ?? "");
$user = (string) ($this->settings->DatabaseUser ?? "");
$password = (string) ($this->settings->DatabasePassword ?? "");
$connection = new PDO("mysql:host={$host};dbname={$database};charset=utf8", $user, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException | Exception $e) {
$this->debug($e->getMessage());
exit();
}
return $connection;
}
// ========================
// Generate Random Password
// ========================
private function generateRandomPassword($length = 12) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()-_+=';
$password = '';
for ($i = 0; $i < $length; $i++) {
$index = rand(0, strlen($characters) - 1);
$password .= $characters[$index];
}
return $password;
}
// ===============
// Debug an Object
// ===============
private function debug($object = "") {
echo "<pre>";
print_r($object);
exit();
}
// ==============
// Reset Password
// ==============
public function resetPassword() {
$username = filter_input(INPUT_POST, "user_name") ?: "";
if (empty($username)) {
return false;
}
$exists = $this->userExists($username);
if (!$exists) {
return false;
}
$user = $this->getUser($username);
$password = $this->resetUsersPassword($user->record->user_serial);
$this->emailUserPasswordResetLink($user, $password);
$this->journalEntry("{$username} reset their password.");
return true;
}
// ===========
// User Exists
// ===========
private function userExists($username) {
$SQL = 'select user_name from view_users where user_name = :username';
$statement = $this->ghrconnection->prepare($SQL);
$statement->bindValue(':username', $username, PDO::PARAM_STR);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
return ($user !== false);
}
// =================
// Get a User Object
// =================
private function getUser($username) {
$SQL = 'select user_serial, user_name, user_email from view_users where user_name = :username';
$statement = $this->ghrconnection->prepare($SQL);
$statement->bindValue(':username', $username, PDO::PARAM_STR);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
$xml = new SimpleXMLElement('<users/>');
$record = $xml->addChild('record');
$this->arrayToXml($user, $record);
return $xml;
}
private function arrayToXml(array $data, SimpleXMLElement $xml): void {
foreach ($data as $key => $value) {
$key = is_numeric($key) ? 'item' : $key;
if (is_array($value)) {
$child = $xml->addChild($key);
$this->arrayToXml($value, $child);
} else {
$xml->addChild($key, htmlspecialchars((string) $value));
}
}
}
// ========================
// Reset the Users Password
// ========================
private function resetUsersPassword($user_serial) {
$user_random_password = $this->generateRandomPassword();
$user_temp_password = password_hash($user_random_password, PASSWORD_DEFAULT);
$SQL = "update users
set user_password = :user_password,
user_change_password = :user_change_password
where user_serial = :user_serial";
$statement = $this->ghrconnection->prepare($SQL);
$statement->bindValue(":user_serial", $user_serial);
$statement->bindValue(":user_password", $user_temp_password);
$statement->bindValue(":user_change_password", 1);
$statement->execute();
return $user_random_password;
}
// =================================
// Email a users Password Reset Link
// =================================
public function emailUserPasswordResetLink($user, $password) {
if (!$user instanceof SimpleXMLElement) {
return;
}
// Prepare the email.
$XSLParms['USER-TEMP-PASSWORD'] = $password;
$to = $user->record->user_email;
$subject = "DEC International DMS - Password Reset Request";
$message = $this->applyXSL($user, $this->getXSL("emailPasswordResetLink"), $XSLParms);
// Send the Email
$this->sendEmail($to, $subject, $message);
}
// =======================================
// Send an email with optional attachments
// =======================================
public function sendEmail($to = "", $subject = "", $message = "", $attachments = "", $attachment_names = "unknown") {
if (empty($to) or empty($subject) or empty($message)) {
return false;
}
$SmtpHost = $this->settings->SmtpServer;
$SmtpUsername = $this->settings->SmtpUserName;
$SmtpPassword = $this->settings->SmtpPassword;
$SmtpPort = $this->settings->SmtpPort;
$email = new PHPMailer(true);
// Only for development
$message = "<span style='font-family: Calibri, Arial, sans-serif;'>" . $message . "</span>";
try {
//Server settings
$email->isSMTP();
$email->Host = $SmtpHost;
$email->SMTPAuth = true;
$email->Username = $SmtpUsername; // Your Gmail address
$email->Password = $SmtpPassword; // App password from Google
// $email->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // or 'tls'
$email->Port = $SmtpPort;
$email->isHTML(true);
$email->SetFrom("info@dec-international.com", "DEC-International");
if (is_array($to)) {
foreach ($to as $address) {
$address = trim(str_replace(" ", "", $address));
if (empty($address)) {
continue;
}
$email->addAddress($address);
}
} else {
$email->addAddress($to);
}
$email->Subject = $subject;
$email->Body = $message;
if (is_array($attachments)) {
foreach ($attachments as $index => $item) {
if (!empty($item)) {
$email->addStringAttachment($item, ($attachment_names[$index] ?? "unknown"));
}
}
} else {
if (!empty($attachments)) {
$email->addStringAttachment($attachments, $attachment_names);
}
}
$success = $email->Send();
} catch (phpMailerException $e) {
$this->journalEntry($e->errorMessage());
$success = false;
} catch (Exception $e) {
$this->journalEntry($e->getMessage());
$success = false;
}
return $success;
}
// ======================
// Create a Journal Entry
// ======================
public function journalEntry($journal_entry = "") {
if (empty($journal_entry)) {
return;
}
$SQL = "insert into journal
( journal_origin,
journal_ip,
journal_entry )
VALUES ( :journal_origin,
:journal_ip,
:journal_entry )";
$statement = $this->ghrconnection->prepare($SQL);
$statement->bindValue(":journal_origin", "Authentication Class");
$statement->bindValue(":journal_ip", $_SERVER["REMOTE_ADDR"] ?? "");
$statement->bindValue(":journal_entry", $journal_entry);
$statement->execute();
}
// ==========================================
// Apply an XSL Stylesheet to an XML Document
// ==========================================
public function applyXSL($XMLString = "", $XSLString = "", $XSLParms = "") {
if ($XMLString instanceof SimpleXMLElement) {
$XMLString = $XMLString->asXML();
}
if (empty($XSLString)) {
trigger_error("No XSL Stylesheet provided.");
}
if (!is_array($XSLParms)) {
$XSLParms = array();
}
$XSLParms["RANDOM_NUMBER"] = rand();
$XSLParms["TODAY_YYYYMMDD"] = date("Y-m-d");
$XSLParms["TODAY_MMDDYYYY"] = date("m/d/Y");
$XSLParms["TODAY_HHMM"] = date("Hi");
$XSLParms["COPYRIGHT"] = date("Y");
$XML = new DOMDocument();
$XSL = new DOMDocument();
$XSLT = new XSLTProcessor();
if ($XMLString) {
$XML->loadXML($XMLString);
}
if ($XSLString) {
$XSL->loadXML($XSLString);
}
$XSLT->importStylesheet($XSL);
if ($XSLParms) {
$XSLT->setParameter("", $XSLParms);
}
$document = $XSLT->transformToXml($XML);
return $document;
}
// ========================
// Return an XSL Stylesheet
// ========================
public function getXSL($document = "") {
if (trim($document) == "") {
return "";
}
$document = "xsl/" . trim($document) . ".xsl";
$XSL = (file_exists($document) ? file_get_contents($document) : "");
return $XSL;
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
Base_Autoloader::Register();
// ================
// Autoloader Class
// ================
class Base_Autoloader {
public static function Register() {
if (function_exists("__autoload")) {
spl_autoload_register("__autoload");
}
return spl_autoload_register(array("Base_Autoloader", "Load"), true, true);
}
public static function Load($pClassName) {
if (class_exists($pClassName, false)) {
return false;
}
// Try for a "classes" Class first, then a "reports" Class.
$pClassFilePath = "classes/{$pClassName}.php";
if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) {
$pClassFilePath = "reports/{$pClassName}.php";
if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) {
return false;
}
}
require($pClassFilePath);
}
}
?>
+816
View File
@@ -0,0 +1,816 @@
<?php
// ==========
// Base Class
// ==========
require_once "vendor/autoload.php";
require_once "classes/Autoloader.php";
class Base {
// =========
// Constants
// =========
const APPLICATION_NAME = "DEC Data Manager";
const APPLICATION_MNEMONIC = "DECDATA";
const VERSION = "1.00";
const TIMEZONE = "America/New_York";
// =================
// Session Variables
// =================
const ENVIRONMENT = "DECDATA_ENVIRONMENT";
const ACTIVE_SESSION = "DECDATA_ACTIVE_SESSION";
const USER_ID = "DECDATA_USER_ID";
const USER_SERIAL = "DECDATA_USER_SERIAL";
const USER_NAME = "DECDATA_USER_NAME";
const USER_EMAIL = "DECDATA_USER_EMAIL";
const USER_ROLE = "DECDATA_USER_ROLE";
const USER_AUTHENTICATED = "DECDATA_USER_AUTHENTICATED";
const REPORTS_GET = "DECDATA_REPORTS_GET";
const REPORTS_POST = "DECDATA_REPORTS_POST";
const THEME = "DECDATA_THEME";
const AJAX = "DECDATA_AJAX";
const TODAY = "DECDATA_TODAY";
const COPYRIGHT = "DECDATA_COPYRIGHT";
const PAGE = "DECDATA_PAGE";
const PAGINATION_PAGE = "DECDATA_PAGINATION_PAGE";
// =================
// Class Constructor
// =================
public function __construct() {
set_error_handler(array($this, "displayError"));
date_default_timezone_set(self::TIMEZONE);
}
// ===============================================
// Append a SimpleXMLElement to a SimpleXMLElememt
// ===============================================
public function appendSXE(SimpleXMLElement $from, SimpleXMLElement $to) {
$toDOM = dom_import_simplexml($to);
$fromDOM = dom_import_simplexml($from);
$toDOM->appendChild($toDOM->ownerDocument->importNode($fromDOM, true));
}
// ==========================================
// Apply an XSL Stylesheet to an XML Document
// ==========================================
public function applyXSL($XMLString = "", $XSLString = "", $XSLParms = "") {
if ($XMLString instanceof SimpleXMLElement) {
$XMLString = $XMLString->asXML();
}
if (empty($XSLString)) {
trigger_error("No XSL Stylesheet provided.");
}
if (!is_array($XSLParms)) {
$XSLParms = array();
}
$XSLParms["APPLICATION_NAME"] = self::APPLICATION_NAME;
$XSLParms["APPLICATION_MNEMONIC"] = self::APPLICATION_MNEMONIC;
$XSLParms["VERSION"] = self::VERSION;
$XSLParms["THEME"] = $_SESSION[self::THEME] ?? self::THEME;
$XSLParms["ENVIRONMENT"] = $_SESSION[self::ENVIRONMENT] ?? "Production";
$XSLParms["USER_NAME"] = $_SESSION[self::USER_NAME] ?? "";
$XSLParms["USER_ROLE"] = $_SESSION[self::USER_ROLE] ?? "Guest";
$XSLParms["RANDOM_NUMBER"] = rand();
$XSLParms["TODAY_YYYYMMDD"] = date("Y-m-d");
$XSLParms["TODAY_MMDDYYYY"] = date("m/d/Y");
$XSLParms["TODAY_HHMM"] = date("Hi");
$XSLParms["COPYRIGHT"] = date("Y");
$XML = new DOMDocument();
$XSL = new DOMDocument();
$XSLT = new XSLTProcessor();
if ($XMLString) {
$XML->loadXML($XMLString);
}
if ($XSLString) {
$XSL->loadXML($XSLString);
}
$XSLT->importStylesheet($XSL);
if ($XSLParms) {
$XSLT->setParameter("", $XSLParms);
}
$document = $XSLT->transformToXml($XML);
return $document;
}
// ============================
// Return a Database Connection
// ============================
public function connect(): PDO {
$settings = $this->getSettings();
$host = ((string) $settings->Environment === 'Production') ? 'localhost' : '192.168.1.190';
$database = (string) $settings->DatabaseName;
$username = (string) $settings->DatabaseUser;
$password = (string) $settings->DatabasePassword;
try {
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8mb4', $host, $database);
return new PDO($dsn, $username, $password,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_PERSISTENT => false,]);
} catch (PDOException $e) {
$this->logError("Database Connection Failed: " . $e->getMessage());
throw new Exception("Unable to connect to the database.", 0, $e);
}
}
// ===============
// Debug an Object
// ===============
public function debug($object = "") {
if ($_SESSION[self::AJAX]) {
error_log(print_r($object, true));
} else {
echo "<pre>";
print_r($object);
}
exit();
}
// =========================
// Return a decrypted string
// =========================
protected function decrypt($encrypted = "", $key = "") {
$key = (empty($key)) ? __CLASS__ : $key;
$decoded = base64_decode($encrypted);
$ivlen = openssl_cipher_iv_length($cipher = "AES-128-CBC");
$iv = substr($decoded, 0, $ivlen);
$hmac = substr($decoded, $ivlen, $sha2len = 32);
$raw = substr($decoded, $ivlen + $sha2len);
$decrypted = openssl_decrypt($raw, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac("sha256", $raw, $key, $as_binary = true);
if (($hmac === false) or ($calcmac === false)) {
return "";
}
return (hash_equals($hmac, $calcmac)) ? $decrypted : "";
}
// ======================
// Display a Content Page
// ======================
public function displayContent($content = "") {
$html = $this->applyXSL("", $this->getXSL("content"));
$html = str_replace("$$$-CONTENT-$$$", $content, $html);
echo $html;
exit();
}
// ======================================================
// Custom error handler to display informative error page
// ======================================================
public function displayError($error_number = "", $error_message = "", $error_file = "", $error_line = "") {
echo $error_message;
die();
if (error_reporting() == 0) {
return;
}
$error_file = explode("/", $error_file);
$error_file = end($error_file);
$error_message = str_replace("'", '"', $error_message);
(new Journal())->journalEntry("{$error_file} | {$error_line} | {$error_message}");
if (($_SESSION[self::ENVIRONMENT] ?? "Production") == "Production") {
(new Email())->sendErrorEmail($error_message, $error_file, $error_line);
}
$XSLParms["FILE_NAME"] = $error_file;
$XSLParms["LINE_NUMBER"] = $error_line;
$XSLParms["ERROR_MESSAGE"] = $error_message;
$XSLParms["ERROR_NUMBER"] = $error_number;
$content = $this->applyXSL("", $this->getXSL("error"), $XSLParms);
$this->displayContent($content);
exit(); // Exit so that only one error is presented.
}
// =====================
// Display a Notice Page
// =====================
public function displayNotice($messgae = "") {
$XSLParms["MESSAGE"] = $messgae;
$content = $this->applyXSL("", $this->getXSL("notice"), $XSLParms);
$this->displayContent($content);
exit();
}
// =====================
// Display the Home Page
// =====================
public function displayHome() {
$content = $this->applyXSL("", $this->getXSL("home"));
$this->displayContent($content);
}
// =======================
// Do the requested Action
// =======================
public function do() {
$_SESSION[self::TODAY] = date("Y-m-d");
// Get the requested Action
$action = filter_input(INPUT_POST, "action") ?: "";
$Xaction = filter_input(INPUT_GET, "Xaction") ?: "";
$action = (empty($Xaction) ? $action : $Xaction);
if ($Xaction == 'resetpassword') {
$this->resetpassword();
}
// Login
if (($_SESSION[self::USER_AUTHENTICATED] ?? false) === false) {
(new SignIn())->login();
}
// Determine if user needs a password change
if ($this->userChangePassword() === true) {
(new Users())->changePassword();
exit();
}
// Determine if this is an AJAX request.
$_SESSION[self::AJAX] = (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) and strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest");
// Get the requested Action
$action = filter_input(INPUT_POST, "action") ?: "";
$Xaction = filter_input(INPUT_GET, "Xaction") ?: "";
$action = (empty($Xaction) ? $action : $Xaction);
// Sign Out if requested.
if (strtolower(trim($action)) === "signout") {
$this->initializeSession();
}
// Process the requested Action.
list($class, $method) = array_pad(explode('.', $action), 2, "");
if (empty($method)) {
$method = $class;
if (method_exists(__CLASS__, $method)) {
$this->$method();
return;
}
} else {
if (method_exists($class, $method)) {
(new $class())->$method();
return;
}
}
// Default to the Home Page.
$this->displayHome();
}
// ==========================
// Return an encrypted string
// ==========================
protected function encrypt($string = "", $key = "") {
$key = (empty($key)) ? __CLASS__ : $key;
$ivlen = openssl_cipher_iv_length($cipher = "AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$raw = openssl_encrypt($string, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac("sha256", $raw, $key, $as_binary = true);
$encrypted = base64_encode($iv . $hmac . $raw);
return $encrypted;
}
// ========================
// Execute an SQL Statement
// ========================
public function executeSQL($SQL = "") {
if (trim($SQL) == "") {
return false;
}
return $this->connect()->query($SQL);
}
// ======================
// Format an XML document
// ======================
public function formatXML($XML = "") {
if (!$XML) {
return false;
}
if ($XML instanceof SimpleXMLElement) {
$XML = $XML->asXML();
}
$dom = new DOMDocument("1.0");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($XML);
return $dom->saveXML();
}
// =====================================
// Return an Application Settings Object
// =====================================
public function getSettings() {
$settings = new SimpleXMLElement($this->getXML("settings"));
return $settings;
}
// ==================================================================
// Return Age in Years based on given Birthdate ("yyyy-mm-dd" format)
// ==================================================================
public function getAge($birthdate = "", $date = "") {
$birthdate = filter_input(INPUT_POST, "birthdate", FILTER_UNSAFE_RAW) ?: $birthdate;
$date = filter_input(INPUT_POST, "date", FILTER_UNSAFE_RAW) ?: $date;
$age = 0;
$date = (empty($date)) ? new Datetime() : new DateTime($date);
$birthdate = (empty($birthdate)) ? new Datetime() : new DateTime($birthdate);
$age = $birthdate->diff($date)->format("%y");
if ($_SESSION[self::AJAX]) {
echo json_encode($age);
} else {
return $age;
}
}
// =========================
// Return a Constants Object
// =========================
public function getConstants() {
$Constants = new SimpleXMLElement($this->getXML("constants"));
return $Constants;
}
// ==================
// Return a Recordset
// ==================
public function getRecordset($SQL = "") {
if (empty($SQL)) {
return false;
}
$recordSet = $this->connect()->query($SQL);
return $recordSet;
}
// =======================================
// Return Table Data as a SimpleXMLElement
// =======================================
public function getTable($table = "", $SQL = "") {
if (empty($table)) {
return new SimpleXMLElement("<unknown/>");
}
$SXE = new SimpleXMLElement("<{$table}/>");
$recordset = $this->getRecordset(empty($SQL) ? "select * from {$table}" : $SQL);
if ($recordset) {
while ($row = $recordset->fetch(PDO::FETCH_ASSOC)) {
$record = $SXE->addChild("record");
foreach ($row as $name => $value) {
$record->$name = $value;
}
}
}
return $SXE;
}
// =======================================
// Return Table Data as a SimpleXMLElement
// =======================================
public function getTableXML($table = "", $statement = "") {
if (empty($table)) {
return new SimpleXMLElement("<unknown/>");
}
$SXE = new SimpleXMLElement("<{$table}/>");
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$record = $SXE->addChild("record");
foreach ($row as $name => $value) {
$record->$name = $value;
}
}
return $SXE;
}
// =================================
// Return the Time Elapsed since now
// =================================
public function getTimeElapsed($timestamp = "") {
$now = new DateTime;
$then = new DateTime($timestamp);
$diff = (array) $now->diff($then);
$diff["w"] = floor($diff["d"] / 7);
$diff["d"] -= $diff["w"] * 7;
$string = array(
"y" => "year",
"m" => "month",
"w" => "week",
"d" => "day",
"h" => "hour",
"i" => "minute",
"s" => "second",
);
foreach ($string as $k => & $v) {
if ($diff[$k]) {
$v = $diff[$k] . " " . $v . ($diff[$k] > 1 ? "s" : "");
} else {
unset($string[$k]);
}
}
$string = array_slice($string, 0, 1);
return $string ? implode(", ", $string) . " ago" : "just now";
}
// ===================
// Return a Time Stamp
// ===================
public function getTimestamp() {
return date("Y-m-d H:i:s");
}
// ======================
// Return an XML Document
// ======================
public function getXML($document = "") {
if (trim($document) == "") {
return "";
}
$document = "xml/" . trim($document) . ".xml";
$XML = (file_exists($document) ? file_get_contents($document) : "");
return $XML;
}
// ========================
// Return an XSL Stylesheet
// ========================
public function getXSL($document = "") {
if (trim($document) == "") {
return "";
}
$document = "xsl/" . trim($document) . ".xsl";
$XSL = (file_exists($document) ? file_get_contents($document) : "");
return $XSL;
}
// =======================================
// Return a Zip Code Detail Object (Array)
// =======================================
public function getZipcode($zip_code = 0) {
$zip_code = filter_input(INPUT_POST, "zip_code", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$zip_code = (integer) substr((string) $zip_code, 0, 5);
$zipCodeDetail = null;
$SQL = "select *
from zipcodes
where zipcode_code = {$zip_code}";
$zipcodes = $this->getTable("zipcodes", $SQL);
if ($zipcodes->count() > 0) {
$zipCodeDetail["ZipCode"] = $zip_code;
$zipCodeDetail["City"] = (string) $zipcodes->record->zipcode_city;
$zipCodeDetail["State"] = (string) $zipcodes->record->zipcode_state;
$zipCodeDetail["County"] = (string) $zipcodes->record->zipcode_county;
$zipCodeDetail["Country"] = (string) $zipcodes->record->zipcode_country;
}
if ($_SESSION[self::AJAX]) {
echo json_encode($zipCodeDetail);
} else {
return $zipCodeDetail;
}
}
// ======================
// Initialize the Session
// ======================
public function initializeSession() {
$settings = $this->getSettings();
$_SESSION[self::ACTIVE_SESSION] = true;
$_SESSION[self::THEME] = "light";
$_SESSION[self::ENVIRONMENT] = (string) ($settings->Environment ?? "Production");
$_SESSION[self::USER_AUTHENTICATED] = false;
$_SESSION[self::USER_SERIAL] = 0;
$_SESSION[self::USER_ID] = "";
$_SESSION[self::USER_NAME] = "";
$_SESSION[self::USER_EMAIL] = "";
$_SESSION[self::USER_ROLE] = "Guest";
$_SESSION[self::REPORTS_GET] = "";
$_SESSION[self::REPORTS_POST] = "";
$_SESSION[self::AJAX] = false;
}
// ============
// Log an Error
// ============
public function logError($error_message = "") {
(new Journal())->journalEntry($error_message);
$this->displayHome();
exit();
}
// ==========================
// Merge thisXML with thatXML
// ==========================
public function mergeXML($thisXML = "", $thatXML = "") {
if ($thisXML instanceof SimpleXMLElement) {
$thisXML = $thisXML->asXML();
}
if ($thatXML instanceof SimpleXMLElement) {
$thatXML = $thatXML->asXML();
}
if (trim($thisXML) == "") {
return $thatXML;
}
if (trim($thatXML) == "") {
return $thisXML;
}
$thisDOM = new DOMDocument();
$thisDOM->loadXML($thisXML);
$thatDOM = new DOMDocument();
$thatDOM->loadXML($thatXML);
$xpath = new DOMXpath($thisDOM);
$xpathQuery = $xpath->query("/*");
for ($i = 0; $i < $xpathQuery->length; $i++) {
$thatDOM->documentElement->appendChild($thatDOM->importNode($xpathQuery->item($i), true));
}
$thatSXE = simplexml_import_dom($thatDOM);
return $thatSXE->asXML();
}
// ==============
// Print a Report
// ==============
public function print() {
$_SESSION[self::REPORTS_GET] = $_GET;
$_SESSION[self::REPORTS_POST] = $_POST;
$report = filter_input(INPUT_POST, "report") ?: "";
(new $report())->print();
}
// =================
// Sanitize a string
// =================
public function sanitizeString($string = "") {
return trim(preg_replace("/\s+/", " ", htmlspecialchars($string, ENT_NOQUOTES | ENT_HTML5)));
}
// ========================
// Toggle the current Theme
// ========================
public function toggleTheme() {
$_SESSION[self::THEME] = (($_SESSION[self::THEME] ?? "light") === "dark") ? "light" : "dark";
}
// ===============================
// Validate a Date (local or AJAX)
// ===============================
public function validateDate($date = "", $format = "Y-m-d") {
$date = filter_input(INPUT_POST, "date") ?: $date;
$datetime = DateTime::createFromFormat($format, $date);
$valid = $datetime && $datetime->format($format) === $date;
if ($_SESSION[self::AJAX]) {
echo json_encode($valid);
} else {
return $valid;
}
}
// ========================
// Generate Random Password
// ========================
public function generateRandomPassword($length = 12) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()-_+=';
$password = '';
for ($i = 0; $i < $length; $i++) {
$index = rand(0, strlen($characters) - 1);
$password .= $characters[$index];
}
return $password;
}
// ====================
// User Change Password
// ====================
public function userChangePassword() {
$user = (new Users())->getUserByUserName($_SESSION[self::USER_NAME]);
if ($user->record->user_change_password == 1) {
return true;
}
return false;
}
// ==============================
// Alter Sting to Parahgraph Case
// ==============================
public function toParagraphCase($text) {
$text = ucwords(strtolower($text));
return $text;
}
// ==========================
// Developer Testing Function
// ==========================
public function testing() {
$to = "james.richie@onesourceits.com";
$subject = "Test Subject";
$message = "Test Message";
$email = (new Email())->sendEmail($to, $subject, $message);
$this->debug($email);
exit();
}
// =====================
// Forgot/Reset Password
// =====================
public function resetPassword() {
require_once 'classes/Authentication.php';
$XSLParms = [
"BTN_SUBMIT" => "main.php?action=Users.signIn&step=authenticate",
"RESET_PASSWORD_SUCCESSFUL" => (new Authentication())->resetPassword() ? "TRUE" : "FALSE"
];
echo $this->applyXSL("", $this->getXSL("signIn"), $XSLParms);
exit;
}
}
?>
+733
View File
@@ -0,0 +1,733 @@
<?php
// ===============
// Dropdowns Class
// ===============
class Dropdowns extends Base {
// Variables.
private $current_user_id = "";
private $current_user_name = "";
private $current_user_email = "";
private $pagination_size = 20;
private $pagination_page = 1;
// ==================
// Class Constructor.
// ==================
public function __construct() {
set_error_handler(array($this, "displayError"));
date_default_timezone_set(self::TIMEZONE);
$this->current_user_id = $_SESSION[self::USER_ID] ?? "";
$this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
$this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
$this->pagination_page = $_SESSION[self::PAGINATION_PAGE] ?? 1;
}
// ============
// Add Dropdown
// ============
public function addDropdown() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$dropdowntype_serial = filter_input(INPUT_POST, "dropdowntype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdowntype = $this->getDropdowntype($dropdowntype_serial);
if ($dropdowntype->count() == 0) {
$this->logError("Invalid Dropdowntype ({$dropdowntype_serial}). " . __METHOD__);
}
$XML = $this->mergeXML($dropdowntype, "<XML/>");
$content = $this->applyXSL($XML, $this->getXSL("addDropdown"));
$this->displayContent($content);
break;
case "add":
$dropdowntype_serial = filter_input(INPUT_POST, "dropdowntype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdown_value = filter_input(INPUT_POST, "dropdown_value") ?: "";
$SQL = "insert into dropdowns
( dropdown_dropdowntype,
dropdown_value,
dropdown_creator,
dropdown_created )
VALUES ( :dropdown_dropdowntype,
:dropdown_value,
:dropdown_creator,
:dropdown_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":dropdown_dropdowntype", $dropdowntype_serial);
$statement->bindValue(":dropdown_value", $dropdown_value);
$statement->bindValue(":dropdown_creator", $this->current_user_name);
$statement->bindValue(":dropdown_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ================
// Add Dropdowntype
// ================
public function addDropdowntype() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$content = $this->applyXSL("", $this->getXSL("addDropdowntype"));
$this->displayContent($content);
break;
case "add":
$dropdowntype_name = filter_input(INPUT_POST, "dropdowntype_name") ?: "";
$dropdowntype_title = filter_input(INPUT_POST, "dropdowntype_title") ?: "";
$dropdowntype_table = filter_input(INPUT_POST, "dropdowntype_table") ?: "";
$dropdowntype_column = filter_input(INPUT_POST, "dropdowntype_column") ?: "";
$SQL = "insert into dropdowntypes
( dropdowntype_name,
dropdowntype_title,
dropdowntype_table,
dropdowntype_column,
dropdowntype_creator,
dropdowntype_created )
VALUES ( :dropdowntype_name,
:dropdowntype_title,
:dropdowntype_table,
:dropdowntype_column,
:dropdowntype_creator,
:dropdowntype_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":dropdowntype_name", $dropdowntype_name);
$statement->bindValue(":dropdowntype_title", $dropdowntype_title);
$statement->bindValue(":dropdowntype_table", $dropdowntype_table);
$statement->bindValue(":dropdowntype_column", $dropdowntype_column);
$statement->bindValue(":dropdowntype_creator", $this->current_user_name);
$statement->bindValue(":dropdowntype_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ===============
// Delete Dropdown
// ===============
public function deleteDropdown() {
$dropdown_serial = filter_input(INPUT_POST, "dropdown_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdown = $this->getDropdown($dropdown_serial);
if ($dropdown->count() == 0) {
$this->logError("Invalid Dropdown ({$dropdown_serial}). " . __METHOD__);
}
$SQL = "delete from dropdowns
where dropdown_serial = {$dropdown_serial}";
$this->executeSQL($SQL);
}
// ===================
// Delete Dropdowntype
// ===================
public function deleteDropdowntype() {
$dropdowntype_serial = filter_input(INPUT_POST, "dropdowntype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdowntype = $this->getDropdowntype($dropdowntype_serial);
if ($dropdowntype->count() == 0) {
$this->logError("Invalid Dropdowntype ({$dropdowntype_serial}). " . __METHOD__);
}
$SQL = "delete from dropdowntypes
where dropdowntype_serial = {$dropdowntype_serial}";
$this->executeSQL($SQL);
}
// ==============================
// Determine if a Dropdown exists
// ==============================
public function dropdownExists() {
$dropdowntype_serial = filter_input(INPUT_POST, "dropdowntype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdown_serial = filter_input(INPUT_POST, "dropdown_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdown_value = filter_input(INPUT_POST, "dropdown_value") ?: "";
$dropdown_value = strtolower($dropdown_value);
$SQL = "select dropdown_serial
from view_dropdowns
where dropdown_serial != :dropdown_serial
and dropdown_dropdowntype = :dropdown_dropdowntype
and lower(dropdown_value) = :dropdown_value";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":dropdown_serial", $dropdown_serial);
$statement->bindValue(":dropdown_dropdowntype", $dropdowntype_serial);
$statement->bindValue(":dropdown_value", $dropdown_value);
$statement->execute();
$recordset = $statement->fetchAll(PDO::FETCH_ASSOC);
$exists = (count($recordset) > 0) ? true : false;
echo json_encode($exists);
}
// ==================================
// Determine if a Dropdowntype exists
// ==================================
public function dropdowntypeExists() {
$dropdowntype_serial = filter_input(INPUT_POST, "dropdowntype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdowntype_name = filter_input(INPUT_POST, "dropdowntype_name") ?: "";
$dropdowntype_name = strtolower($dropdowntype_name);
$SQL = "select dropdowntype_serial
from view_dropdowntypes
where dropdowntype_serial != :dropdowntype_serial
and lower(dropdowntype_name) = :dropdowntype_name";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":dropdowntype_serial", $dropdowntype_serial);
$statement->bindValue(":dropdowntype_name", $dropdowntype_name);
$statement->execute();
$recordset = $statement->fetchAll(PDO::FETCH_ASSOC);
$exists = (count($recordset) > 0) ? true : false;
echo json_encode($exists);
}
// ========================================
// Determine if a Dropdowntype Title exists
// ========================================
public function dropdowntypetitleExists() {
$dropdowntype_serial = filter_input(INPUT_POST, "dropdowntype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdowntype_title = filter_input(INPUT_POST, "dropdowntype_title") ?: "";
$dropdowntype_title = strtolower($dropdowntype_title);
$SQL = "select dropdowntype_serial
from view_dropdowntypes
where dropdowntype_serial != :dropdowntype_serial
and lower(dropdowntype_title) = :dropdowntype_title";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":dropdowntype_serial", $dropdowntype_serial);
$statement->bindValue(":dropdowntype_title", $dropdowntype_title);
$statement->execute();
$recordset = $statement->fetchAll(PDO::FETCH_ASSOC);
$exists = (count($recordset) > 0) ? true : false;
echo json_encode($exists);
}
// =================================
// Determine if a Dropdown is Active
// =================================
public function dropdownActive() {
$dropdown_serial = filter_input(INPUT_POST, "dropdown_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdown = $this->getDropdown($dropdown_serial);
if ($dropdown->count() == 0) {
$this->logError("Invalid Dropdown ({$dropdown_serial}). " . __METHOD__);
}
$table = (string) $dropdown->record->dropdowntype_table;
$column = (string) $dropdown->record->dropdowntype_column;
$active = false;
switch ($table) {
case "*none": // No table, never Active.
break;
case "*function": // Requires it's own function to determine if Active.
if (method_exists(__CLASS__, $column)) {
$active = $this->$column($dropdown_serial);
}
break;
default: // All others, test the Column in the Table.
$SQL = "select {$column}
from {$table}
where {$column} = {$dropdown_serial}";
$results = $this->getTable("results", $SQL);
$active = ($results->count() > 0) ? true : false;
break;
}
echo json_encode($active);
}
// =====================================
// Determine if a Dropdowntype is Active
// =====================================
public function dropdowntypeActive() {
$dropdowntype_serial = (integer) filter_input(INPUT_POST, "dropdowntype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$SQL = "select dropdown_serial
from view_dropdowns
where dropdown_dropdowntype = {$dropdowntype_serial}";
$dropdowns = $this->getTable("dropdowns", $SQL);
$active = ($dropdowns->count() > 0) ? true : false;
echo json_encode($active);
}
// ===============
// Edit a Dropdown
// ===============
public function editDropdown() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$dropdown_serial = filter_input(INPUT_POST, "dropdown_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdown = $this->getDropdown($dropdown_serial);
if ($dropdown->count() == 0) {
$this->logError("Invalid Dropdown ({$dropdown_serial}). " . __METHOD__);
}
$XML = $this->mergeXML($dropdown, "<XML/>");
$content = $this->applyXSL($XML, $this->getXSL("editDropdown"));
$this->displayContent($content);
break;
case "update":
$dropdown_serial = filter_input(INPUT_POST, "dropdown_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdown_value = filter_input(INPUT_POST, "dropdown_value") ?: "";
$dropdown = $this->getDropdown($dropdown_serial);
if ($dropdown->count() == 0) {
$this->logError("Invalid Dropdown ({$dropdown_serial}). " . __METHOD__);
}
$SQL = "update dropdowns
set dropdown_value = :dropdown_value,
dropdown_changer = :dropdown_changer,
dropdown_changed = :dropdown_changed
where dropdown_serial = :dropdown_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":dropdown_serial", $dropdown_serial);
$statement->bindValue(":dropdown_value", $dropdown_value);
$statement->bindValue(":dropdown_changer", $this->current_user_name);
$statement->bindValue(":dropdown_changed", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ===================
// Edit a Dropdowntype
// ===================
public function editDropdowntype() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$dropdowntype_serial = filter_input(INPUT_POST, "dropdowntype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdowntype = $this->getDropdowntype($dropdowntype_serial);
if ($dropdowntype->count() == 0) {
$this->logError("Invalid Dropdowntype ({$dropdowntype_serial}). " . __METHOD__);
}
$XML = $this->mergeXML($dropdowntype, "<XML/>");
$content = $this->applyXSL($XML, $this->getXSL("editDropdowntype"));
$this->displayContent($content);
break;
case "update":
$dropdowntype_serial = filter_input(INPUT_POST, "dropdowntype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdowntype_name = filter_input(INPUT_POST, "dropdowntype_name") ?: "";
$dropdowntype_title = filter_input(INPUT_POST, "dropdowntype_title") ?: "";
$dropdowntype_table = filter_input(INPUT_POST, "dropdowntype_table") ?: "";
$dropdowntype_column = filter_input(INPUT_POST, "dropdowntype_column") ?: "";
$dropdowntype = $this->getDropdowntype($dropdowntype_serial);
if ($dropdowntype->count() == 0) {
$this->logError("Invalid Dropdowntype ({$dropdowntype_serial}). " . __METHOD__);
}
$SQL = "update dropdowntypes
set dropdowntype_name = :dropdowntype_name,
dropdowntype_title = :dropdowntype_title,
dropdowntype_table = :dropdowntype_table,
dropdowntype_column = :dropdowntype_column,
dropdowntype_changer = :dropdowntype_changer,
dropdowntype_changed = :dropdowntype_changed
where dropdowntype_serial = :dropdowntype_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":dropdowntype_serial", $dropdowntype_serial);
$statement->bindValue(":dropdowntype_name", $dropdowntype_name);
$statement->bindValue(":dropdowntype_title", $dropdowntype_title);
$statement->bindValue(":dropdowntype_table", $dropdowntype_table);
$statement->bindValue(":dropdowntype_column", $dropdowntype_column);
$statement->bindValue(":dropdowntype_changer", $this->current_user_name);
$statement->bindValue(":dropdowntype_changed", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// =================================
// Return an Active Dropdowns Object
// =================================
public function getActiveDropdowns() {
$SQL = "select view_dropdowns.*
from view_dropdowns
where dropdown_active is true";
return $this->getTable("dropdowns", $SQL);
}
// ========================
// Return a Dropdown Object
// ========================
public function getDropdown($dropdown_serial = 0) {
$SQL = "select view_dropdowns.*
from view_dropdowns
where dropdown_serial = {$dropdown_serial}";
return $this->getTable("dropdowns", $SQL);
}
// =========================
// Return a Dropdowns Object
// =========================
public function getDropdowns() {
$SQL = "select view_dropdowns.*
from view_dropdowns";
return $this->getTable("dropdowns", $SQL);
}
// ============================
// Return a Dropdowntype Object
// ============================
public function getDropdowntype($dropdowntype_serial = 0) {
$SQL = "select view_dropdowntypes.*
from view_dropdowntypes
where dropdowntype_serial = {$dropdowntype_serial}";
return $this->getTable("dropdowntypes", $SQL);
}
// =============================
// Return a Dropdowntypes Object
// =============================
public function getDropdowntypes() {
$SQL = "select view_dropdowntypes.*
from view_dropdowntypes";
return $this->getTable("dropdowntypes", $SQL);
}
// ==================================
// Return a Dropdowntypes Page Object
// ==================================
public function getDropdowntypesPage() {
// Find Criteria
$find_dropdowntype = filter_input(INPUT_POST, "find_dropdowntype") ?: "";
$find_words = $this->sanitizeString($find_dropdowntype);
// Show Per Page
$this->pagination_size = filter_input(INPUT_POST, "users_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_dropdowntypes
where (dropdowntype_name regexp :dropdowntype_name
or dropdowntype_title regexp :dropdowntype_title
or dropdowntype_table regexp :dropdowntype_table
or dropdowntype_column regexp :dropdowntype_column)";
$statement = $connection->prepare($SQL);
$statement->bindValue(":dropdowntype_name", $find_words);
$statement->bindValue(":dropdowntype_title", $find_words);
$statement->bindValue(":dropdowntype_table", $find_words);
$statement->bindValue(":dropdowntype_column", $find_words);
$statement->execute();
$recordset = $statement->fetch(PDO::FETCH_ASSOC);
$count = (count($recordset) > 0) ? (integer) $recordset["count"] : (integer) 0;
// Pagination
$pagination = filter_input(INPUT_POST, "pagination") ?: "";
switch ($pagination) {
case "first" : $this->pagination_page = 1;
break;
case "previous" : $this->pagination_page = max(($this->pagination_page - 1), 1);
break;
case "next" : $this->pagination_page = ($this->pagination_page + 1);
break;
case "last" : $this->pagination_page = ($count / $this->pagination_size);
break;
}
$offset = (($this->pagination_page * $this->pagination_size) - $this->pagination_size);
$start = ($offset + 1);
$end = min($count, (($start + $this->pagination_size) - 1));
// Data
$SQL = "select view_dropdowntypes.*
from view_dropdowntypes
where (dropdowntype_name regexp :dropdowntype_name
or dropdowntype_title regexp :dropdowntype_title
or dropdowntype_table regexp :dropdowntype_table
or dropdowntype_column regexp :dropdowntype_column)
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":dropdowntype_name", $find_words);
$statement->bindValue(":dropdowntype_title", $find_words);
$statement->bindValue(":dropdowntype_table", $find_words);
$statement->bindValue(":dropdowntype_column", $find_words);
$statement->execute();
$dropdowntypes = $this->getTableXML("dropdowntypes", $statement);
// Insert Pagination Attributes
$dropdowntypes->addAttribute("count", $count);
$dropdowntypes->addAttribute("start", $start);
$dropdowntypes->addAttribute("end", $end);
$dropdowntypes->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $dropdowntypes;
}
// ===============
// Setup Dropdowns
// ===============
public function setupDropdowns() {
$dropdowntypes = $this->getDropdowntypes();
$dropdowns = $this->getDropdowns();
$XML = $this->mergeXML($dropdowntypes, "<XML/>");
$XML = $this->mergeXML($dropdowns, $XML);
$content = $this->applyXSL($XML, $this->getXSL("setupDropdowns"));
$this->displayContent($content);
}
// ===================
// Setup Dropdowntypes
// ===================
public function setupDropdowntypes() {
$dropdowntypes = $this->getDropdowntypesPage();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($dropdowntypes, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$content = $this->applyXSL($XML, $this->getXSL("setupDropdowntypes"));
$this->displayContent($content);
}
// ======================
// Update Dropdown Active
// ======================
public function updateDropdownActive() {
$dropdown_serial = filter_input(INPUT_POST, "dropdown_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdown_checked = filter_input(INPUT_POST, "dropdown_checked", FILTER_VALIDATE_BOOLEAN) ?: false;
$SQL = "update dropdowns
set dropdown_active = :dropdown_active,
dropdown_changer = :dropdown_changer,
dropdown_changed = :dropdown_changed
where dropdown_serial = :dropdown_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":dropdown_serial", $dropdown_serial);
$statement->bindValue(":dropdown_active", $dropdown_checked, PDO::PARAM_BOOL);
$statement->bindValue(":dropdown_changer", $this->current_user_name);
$statement->bindValue(":dropdown_changed", $this->getTimestamp());
$statement->execute();
}
// =======================
// Update Dropdown Default
// =======================
public function updateDropdownDefault() {
$dropdown_serial = filter_input(INPUT_POST, "dropdown_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdown_dropdowntype = filter_input(INPUT_POST, "dropdown_dropdowntype", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$dropdown_checked = filter_input(INPUT_POST, "dropdown_checked") ?: "false";
// Unset the Default for the Dropdown Type.
$SQL = "update dropdowns
set dropdown_default = false
where dropdown_dropdowntype = {$dropdown_dropdowntype}";
$this->executeSQL($SQL);
// Set the Default for the clicked Dropdown.
$SQL = "update dropdowns
set dropdown_default = {$dropdown_checked}
where dropdown_serial = {$dropdown_serial}";
$this->executeSQL($SQL);
}
}
?>
+186
View File
@@ -0,0 +1,186 @@
<?php
// ===========
// Email Class
// ===========
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class Email extends Base {
// Variables.
private $current_user_name = "";
private $current_user_email = "";
// ==================
// Class Constructor.
// ==================
public function __construct() {
set_error_handler(array($this, "displayError"));
date_default_timezone_set(self::TIMEZONE);
$this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
$this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
}
// =============================
// Email a new users credentials
// =============================
public function emailNewUserCredentials($user, $password) {
if (!$user instanceof SimpleXMLElement) {
return;
}
// Prepare the email
$to = (string) $user->record->user_email;
$XSLParms['USER-TEMP-PASSWORD'] = $password;
$subject = "DEC International DMS - New User Credentials";
$message = $this->applyXSL($user, $this->getXSL("emailNewUserCredentials"), $XSLParms);
// Send the Email
$this->sendEmail($to, $subject, $message);
}
// =================================
// Email a users Password Reset Link
// =================================
public function emailUserPasswordResetLink($user, $password) {
if (!$user instanceof SimpleXMLElement) {
return;
}
// Prepare the email.
$XSLParms['USER-TEMP-PASSWORD'] = $password;
$to = (string) $user->record->user_email;
$subject = "DEC International DMS - Password Reset Request";
$message = $this->applyXSL($user, $this->getXSL("emailPasswordResetLink"), $XSLParms);
// Send the Email
$this->sendEmail($to, $subject, $message);
}
// =======================================
// Send an email with optional attachments
// =======================================
public function sendEmail($to = "", $subject = "", $message = "", $attachments = "", $attachment_names = "unknown") {
if (empty($to) or empty($subject) or empty($message)) {
return false;
}
$settings = $this->getSettings();
$SmtpHost = $settings->SmtpServer;
$SmtpUsername = $settings->SmtpUserName;
$SmtpPassword = $settings->SmtpPassword;
$SmtpPort = $settings->SmtpPort;
$email = new PHPMailer(true);
// Only for development
$message = "<span style='font-family: Calibri, Arial, sans-serif;'>" . $message . "</span>";
try {
//Server settings
$email->isSMTP();
$email->Host = $SmtpHost;
$email->SMTPAuth = true;
$email->Username = $SmtpUsername; // Your Gmail address
$email->Password = $SmtpPassword; // App password from Google
// $email->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // or 'tls'
$email->Port = $SmtpPort;
$email->isHTML(true);
$email->SetFrom("info@onesourceits.com", "OneSource IT Solutions LLC");
if (is_array($to)) {
foreach ($to as $address) {
$address = trim(str_replace(" ", "", $address));
if (empty($address)) {
continue;
}
$email->addAddress($address);
}
} else {
$email->addAddress($to);
}
$email->Subject = $subject;
$email->Body = $message;
if (is_array($attachments)) {
foreach ($attachments as $index => $item) {
if (!empty($item)) {
$email->addStringAttachment($item, ($attachment_names[$index] ?? "unknown"));
}
}
} else {
if (!empty($attachments)) {
$email->addStringAttachment($attachments, $attachment_names);
}
}
$success = $email->Send();
} catch (phpMailerException $e) {
(new Journal())->journalEntry($e->errorMessage());
$success = false;
} catch (Exception $e) {
(new Journal())->journalEntry($e->getMessage());
$success = false;
}
return $success;
}
// ==============================
// Send an Error Email to Support
// ==============================
public function sendErrorEmail($error_message = "", $error_file = "", $error_line = "") {
$settings = $this->getSettings();
$Environment = (string) $settings->Environment;
$SupportEmail = (string) $settings->SupportEmail;
if ($Environment == "Development") {
return;
}
$application_name = self::APPLICATION_NAME;
$message = "";
$message .= "<p>An application error has occurred in the {$application_name} application.<br/><br/></p>";
$message .= "<p>File: {$error_file}</p>";
$message .= "<p>Line: {$error_line}</p>";
$message .= "<p>Error: {$error_message}</p>";
$to = $SupportEmail;
$subject = "{$application_name} Application Error";
$this->sendEmail($to, $subject, $message);
}
}
?>
+207
View File
@@ -0,0 +1,207 @@
<?php
// =============
// Journal Class
// =============
class Journal extends Base {
// Variables.
private $current_user_id = "";
private $current_user_name = "";
private $current_user_email = "";
private $pagination_page = 1;
private $pagination_size = 20;
// ==================
// Class Constructor.
// ==================
public function __construct() {
set_error_handler(array($this, "displayError"));
date_default_timezone_set(self::TIMEZONE);
$this->current_user_id = $_SESSION[self::USER_ID] ?? "";
$this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
$this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
$this->pagination_page = $_SESSION[self::PAGINATION_PAGE] ?? 1;
}
// =================
// Clear the Journal
// =================
public function clearJournal() {
$SQL = "truncate journal";
$this->executeSQL($SQL);
$this->journalEntry("Journal was Cleared.");
}
// =======================
// Return a Journal Object
// =======================
public function getJournal($limit = 500) {
$SQL = "select journal.*,
date_format(journal.journal_timestamp, '%Y-%m-%d %h:%i %p') as journal_timestamp_verbose
from journal
order by journal.journal_timestamp desc
limit {$limit}";
return $this->getTable("journal", $SQL);
}
// ============================
// Return a Journal Page Object
// ============================
public function getJournalPage() {
// Find Criteria
$find_journal = filter_input(INPUT_POST, "find_journal") ?: "";
$find_words = $this->sanitizeString($find_journal);
// Show Per Page
$this->pagination_size = filter_input(INPUT_POST, "journals_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_journal
where journal_timestamp regexp :journal_timestamp
or journal_origin regexp :journal_origin
or journal_ip regexp :journal_ip
or journal_entry regexp :journal_entry";
$statement = $connection->prepare($SQL);
$statement->bindValue(":journal_timestamp", $find_words);
$statement->bindValue(":journal_origin", $find_words);
$statement->bindValue(":journal_ip", $find_words);
$statement->bindValue(":journal_entry", $find_words);
$statement->execute();
$recordset = $statement->fetch(PDO::FETCH_ASSOC);
$count = (count($recordset) > 0) ? (integer) $recordset["count"] : (integer) 0;
// Pagination
$pagination = filter_input(INPUT_POST, "pagination") ?: "";
switch ($pagination) {
case "first" : $this->pagination_page = 1; break;
case "previous" : $this->pagination_page = max(($this->pagination_page - 1), 1); break;
case "next" : $this->pagination_page = ($this->pagination_page + 1); break;
case "last" : $this->pagination_page = ($count / $this->pagination_size); break;
}
$offset = (($this->pagination_page * $this->pagination_size) - $this->pagination_size);
$start = ($offset + 1);
$end = min($count, (($start + $this->pagination_size) - 1));
// Data
$SQL = "select view_journal.*
from view_journal
where journal_timestamp regexp :journal_timestamp
or journal_origin regexp :journal_origin
or journal_ip regexp :journal_ip
or journal_entry regexp :journal_entry
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":journal_timestamp", $find_words);
$statement->bindValue(":journal_origin", $find_words);
$statement->bindValue(":journal_ip", $find_words);
$statement->bindValue(":journal_entry", $find_words);
$statement->execute();
$journal = $this->getTableXML("journal", $statement);
// Insert Pagination Attributes
$journal->addAttribute("count", $count);
$journal->addAttribute("start", $start);
$journal->addAttribute("end", $end);
$journal->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $journal;
}
// ======================
// Create a Journal Entry
// ======================
public function journalEntry($journal_entry = "") {
if (empty($journal_entry)) {
return;
}
$SQL = "insert into journal
( journal_origin,
journal_ip,
journal_entry )
VALUES ( :journal_origin,
:journal_ip,
:journal_entry )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":journal_origin", $this->current_user_name);
$statement->bindValue(":journal_ip", $_SERVER["REMOTE_ADDR"] ?? "");
$statement->bindValue(":journal_entry", $journal_entry);
$statement->execute();
}
// ============
// View Journal
// ============
public function viewJournal() {
$journal = $this->getJournalPage();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($journal, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$content = $this->applyXSL($XML, $this->getXSL("viewJournal"));
$this->displayContent($content);
}
}
?>
+96
View File
@@ -0,0 +1,96 @@
<?php
// =============
// Metrics Class
// =============
class Metrics extends Base {
// ==================
// Class Constructor.
// ==================
public function __construct() {
set_error_handler(array($this,"displayError"));
date_default_timezone_set(self::TIMEZONE);
}
// ========================================
// Return a Daily Work Order Metrics Object
// ========================================
private function getDailyWorkOrderMetrics() {
$SQL = "select dayname(workorder_created) as day,
count(*) as count
from view_workorders
where date(workorder_created) >= (date(now()) - interval 6 day)
group by day
order by workorder_created desc";
return $this->getTable("dailymetrics", $SQL);
}
// =====================================
// Return a Monthly Call Metrics Object.
// =====================================
private function getMonthlyWorkOrderMetrics() {
$SQL = "select monthname(workorder_created) as month,
count(*) as count
from view_workorders
where date(workorder_created) >= (date(now()) - interval 6 month)
group by month
order by workorder_created desc";
return $this->getTable("monthlymetrics", $SQL);
}
// =========================================
// Return a Weekly Work Order Metrics Object
// =========================================
private function getWeeklyWorkOrderMetrics() {
$SQL = "select week(workorder_created) as week,
count(*) as count
from view_workorders
where date(workorder_created) >= (date(now()) - interval 6 week)
group by week
order by workorder_created desc";
return $this->getTable("weeklymetrics", $SQL);
}
// =======================
// View Work Order Metrics
// =======================
public function viewWorkOrderMetrics() {
$dailymetrics = $this->getDailyWorkOrderMetrics();
$weeklymetrics = $this->getWeeklyWorkOrderMetrics();
$monthlymetrics = $this->getMonthlyWorkorderMetrics();
$XSLParms["DAILYMETRICS"] = $dailymetrics->asXML();
$XSLParms["WEEKLYMETRICS"] = $weeklymetrics->asXML();
$XSLParms["MONTHLYMETRICS"] = $monthlymetrics->asXML();
$content = $this->applyXSL("", $this->getXSL("viewWorkOrderMetrics"), $XSLParms);
$this->displayContent($content);
exit();
}
}
?>
+244
View File
@@ -0,0 +1,244 @@
<?php
// ===========
// Notes Class
// ===========
class Notes extends Base {
// Constants
const VALID_TYPES = array("User");
// Variables
private $current_user_id = "";
private $current_user_name = "";
private $current_user_email = "";
// =================
// Class Constructor
// =================
public function __construct() {
set_error_handler(array($this, "displayError"));
date_default_timezone_set(self::TIMEZONE);
$this->current_user_id = $_SESSION[self::USER_ID] ?? "";
$this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
$this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
}
// ========
// Add Note
// ========
public function addNote() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$note_type = filter_input(INPUT_POST, "note_type") ?: "";
$note_reference = filter_input(INPUT_POST, "note_reference", FILTER_SANITIZE_NUMBER_INT) ?: 0;
if (!in_array($note_type, self::VALID_TYPES) or empty($note_reference)) {
$this->logError("Invalid Note Type ({$note_type} or Reference {$note_reference} " . __METHOD__);
}
$XSLParms["NOTE_TYPE"] = $note_type;
$XSLParms["NOTE_REFERENCE"] = $note_reference;
$content = $this->applyXSL("", $this->getXSL("addNote"), $XSLParms);
$this->displayContent($content);
break;
case "add":
$note_type = filter_input(INPUT_POST, "note_type") ?: "";
$note_reference = filter_input(INPUT_POST, "note_reference", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$note_text = filter_input(INPUT_POST, "note_text") ?: "";
$SQL = "insert into notes
( note_type,
note_reference,
note_text,
note_origin )
VALUES ( :note_type,
:note_reference,
:note_text,
:note_origin )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":note_type", $note_type);
$statement->bindValue(":note_reference", $note_reference);
$statement->bindValue(":note_text", $note_text);
$statement->bindValue(":note_origin", $this->current_user_name);
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ===========
// Delete Note
// ===========
public function deleteNote() {
$note_serial = filter_input(INPUT_POST, "note_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$note = $this->getNote($note_serial);
if ($note->count() == 0) {
$this->logError("Invalid Note ({$note_serial}). " . __METHOD__);
}
$SQL = "delete from notes
where note_serial = {$note_serial}";
$this->executeSQL($SQL);
}
// =========
// Edit Note
// =========
public function editNote() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$note_serial = filter_input(INPUT_POST, "note_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$note = $this->getNote($note_serial);
if ($note->count() == 0) {
$this->logError("Invalid Note ({$note_serial}). " . __METHOD__);
}
$XML = $this->mergeXML($note, "<XML/>");
$content = $this->applyXSL($XML, $this->getXSL("editNote"));
$this->displayContent($content);
break;
case "update":
$note_serial = filter_input(INPUT_POST, "note_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$note_text = filter_input(INPUT_POST, "note_text") ?: "";
$SQL = "update notes
set note_text = :note_text,
note_origin = :note_origin
where note_serial = :note_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":note_serial", $note_serial);
$statement->bindValue(":note_text", $note_text);
$statement->bindValue(":note_origin", $this->current_user_name);
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ====================
// Return a Note Object
// ====================
public function getNote($note_serial = 0) {
$SQL = "select view_notes.*
from view_notes
where note_serial = {$note_serial}";
return $this->getTable("notes", $SQL);
}
// =====================
// Return a Notes Object
// =====================
public function getNotes($note_type = "", $note_reference = 0) {
$SQL = "select view_notes.*
from view_notes
where note_type = '{$note_type}'
and note_reference = {$note_reference}
order by note_timestamp asc";
return $this->getTable("notes", $SQL);
}
// =====================
// Return a Notes Object
// =====================
public function getAllNotes($note_reference = 0) {
$SQL = "select view_notes.*
from view_notes
where note_reference = {$note_reference}
order by note_timestamp asc";
// $this->debug($SQL);
return $this->getTable("notes", $SQL);
}
// ==============
// Add Note Quick
// ==============
public function addNoteQuick($note_type = "", $note_reference = 0, $note_text = "") {
$SQL = "insert into notes
( note_type,
note_reference,
note_text,
note_origin )
VALUES ( :note_type,
:note_reference,
:note_text,
:note_origin )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":note_type", $note_type);
$statement->bindValue(":note_reference", $note_reference);
$statement->bindValue(":note_text", $note_text);
$statement->bindValue(":note_origin", $this->current_user_name);
$statement->execute();
}
}
?>
+352
View File
@@ -0,0 +1,352 @@
<?php
// ==============
// Popovers Class
// ==============
class Popovers extends Base {
// Variables.
private $current_user_id = "";
private $current_user_name = "";
private $current_user_email = "";
private $pagination_size = 20;
private $pagination_page = 1;
// ==================
// Class Constructor.
// ==================
public function __construct() {
set_error_handler(array($this, "displayError"));
date_default_timezone_set(self::TIMEZONE);
$this->current_user_id = $_SESSION[self::USER_ID] ?? "";
$this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
$this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
$this->pagination_page = $_SESSION[self::PAGINATION_PAGE] ?? 1;
}
// ===========
// Add Popover
// ===========
public function addPopover() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$content = $this->applyXSL("", $this->getXSL("addPopover"));
$this->displayContent($content);
break;
case "add":
$popover_name = filter_input(INPUT_POST, "popover_name") ?: "";
$popover_title = filter_input(INPUT_POST, "popover_title") ?: "";
$popover_placeholder = filter_input(INPUT_POST, "popover_placeholder") ?: "";
$popover_text = filter_input(INPUT_POST, "popover_text") ?: "";
$SQL = "insert into popovers
( popover_name,
popover_title,
popover_placeholder,
popover_text,
popover_creator,
popover_created )
VALUES ( :popover_name,
:popover_title,
:popover_placeholder,
:popover_text,
:popover_creator,
:popover_created)";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":popover_name", $popover_name);
$statement->bindValue(":popover_title", $popover_title);
$statement->bindValue(":popover_placeholder", $popover_placeholder);
$statement->bindValue(":popover_text", $popover_text);
$statement->bindValue(":popover_creator", $this->current_user_name);
$statement->bindValue(":popover_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ==============
// Delete Popover
// ==============
public function deletePopover() {
$popover_serial = filter_input(INPUT_POST, "popover_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$popover = $this->getPopover($popover_serial);
if ($popover->count() == 0) {
$this->logError("Invalid Popover ({$popover_serial}). " . __METHOD__);
}
$SQL = "delete from popovers
where popover_serial = {$popover_serial}";
$this->executeSQL($SQL);
}
// ============
// Edit Popover
// ============
public function editPopover() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$popover_serial = filter_input(INPUT_POST, "popover_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$popover = $this->getPopover($popover_serial);
if ($popover->count() == 0) {
$this->logError("Invalid Popover ({$popover_serial}): " . __METHOD__);
}
$XML = $this->mergeXML($popover, "<XML/>");
$content = $this->applyXSL($XML, $this->getXSL("editPopover"));
$this->displayContent($content);
break;
case "update":
$popover_serial = filter_input(INPUT_POST, "popover_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$popover_name = filter_input(INPUT_POST, "popover_name") ?: "";
$popover_title = filter_input(INPUT_POST, "popover_title") ?: "";
$popover_placeholder = filter_input(INPUT_POST, "popover_placeholder") ?: "";
$popover_text = filter_input(INPUT_POST, "popover_text") ?: "";
$popover = $this->getPopover($popover_serial);
if ($popover->count() == 0) {
$this->logError("Invalid Popover ({$popover_serial}): " . __METHOD__);
}
$SQL = "update popovers
set popover_name = :popover_name,
popover_title = :popover_title,
popover_placeholder = :popover_placeholder,
popover_text = :popover_text,
popover_changer = :popover_changer,
popover_changed = :popover_changed
where popover_serial = :popover_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":popover_serial", $popover_serial);
$statement->bindValue(":popover_name", $popover_name);
$statement->bindValue(":popover_title", $popover_title);
$statement->bindValue(":popover_placeholder", $popover_placeholder);
$statement->bindValue(":popover_text", $popover_text);
$statement->bindValue(":popover_changer", $this->current_user_name);
$statement->bindValue(":popover_changed", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// =======================
// Return a Popover Object
// =======================
public function getPopover($popover_serial = 0) {
$SQL = "select view_popovers.*
from view_popovers
where popover_serial = {$popover_serial}";
return $this->getTable("popovers", $SQL);
}
// =======================
// Return a Popover Object
// =======================
public function getPopoverByName($popover_name = "") {
$SQL = "select view_popovers.*
from view_popovers
where popover_name = '{$popover_name}'";
return $this->getTable("popovers", $SQL);
}
// ========================
// Return a Popovers Object
// ========================
public function getPopovers() {
$SQL = "select view_popovers.*
from view_popovers";
return $this->getTable("popovers", $SQL);
}
// =============================
// Return a Popovers Page Object
// =============================
public function getPopoversPage() {
// Find Criteria
$find_popover = filter_input(INPUT_POST, "find_popover") ?: "";
$find_words = $this->sanitizeString($find_popover);
// Show Per Page
$this->pagination_size = filter_input(INPUT_POST, "popovers_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_popovers
where popover_name regexp :popover_name
or popover_title regexp :popover_title";
$statement = $connection->prepare($SQL);
$statement->bindValue(":popover_name", $find_words);
$statement->bindValue(":popover_title", $find_words);
$statement->execute();
$recordset = $statement->fetch(PDO::FETCH_ASSOC);
$count = (count($recordset) > 0) ? (integer) $recordset["count"] : (integer) 0;
// Pagination
$pagination = filter_input(INPUT_POST, "pagination") ?: "";
switch ($pagination) {
case "first" : $this->pagination_page = 1;
break;
case "previous" : $this->pagination_page = max(($this->pagination_page - 1), 1);
break;
case "next" : $this->pagination_page = ($this->pagination_page + 1);
break;
case "last" : $this->pagination_page = ($count / $this->pagination_size);
break;
}
$offset = (($this->pagination_page * $this->pagination_size) - $this->pagination_size);
$start = ($offset + 1);
$end = min($count, (($start + $this->pagination_size) - 1));
// Data
$SQL = "select view_popovers.*
from view_popovers
where popover_name regexp :popover_name
or popover_title regexp :popover_title
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":popover_name", $find_words);
$statement->bindValue(":popover_title", $find_words);
$statement->execute();
$popovers = $this->getTableXML("popovers", $statement);
// Insert Pagination Attributes
$popovers->addAttribute("count", $count);
$popovers->addAttribute("start", $start);
$popovers->addAttribute("end", $end);
$popovers->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $popovers;
}
// =============================
// Determine if a Popover exists
// =============================
public function popoverExists() {
$popover_serial = filter_input(INPUT_POST, "popover_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$popover_name = filter_input(INPUT_POST, "popover_name") ?: "";
$popover_name = strtolower($popover_name);
$SQL = "select popover_serial
from view_popovers
where popover_serial != :popover_serial
and lower(popover_name) = :popover_name";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":popover_serial", $popover_serial);
$statement->bindValue(":popover_name", $popover_name);
$statement->execute();
$popovers = $statement->fetchAll(PDO::FETCH_ASSOC);
$exists = (count($popovers) > 0) ? true : false;
echo json_encode($exists);
}
// ==============
// Setup Popovers
// ==============
public function setupPopovers() {
$popovers = $this->getPopoversPage();
$XML = $this->mergeXML($popovers, "<XML/>");
$content = $this->applyXSL($XML, $this->getXSL("setupPopovers"));
$this->displayContent($content);
}
}
?>
+479
View File
@@ -0,0 +1,479 @@
<?php
// =============
// Reports Class
// =============
class Reports extends Base {
// Variables.
private $current_user_id = "";
private $current_user_name = "";
private $current_user_email = "";
private $pagination_size = 20;
private $pagination_page = 1;
// =================
// Class Constructor
// =================
public function __construct() {
set_error_handler(array($this, "displayError"));
date_default_timezone_set(self::TIMEZONE);
$this->current_user_id = $_SESSION[self::USER_ID] ?? "";
$this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
$this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
$this->pagination_page = $_SESSION[self::PAGINATION_PAGE] ?? 1;
}
// ==========
// Add Report
// ==========
public function addReport() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$constants = $this->getConstants();
$XML = $this->mergeXML($constants, "<XML/>");
$content = $this->applyXSL($XML, $this->getXSL("addReport"));
$this->displayContent($content);
break;
case "add":
$report_name = filter_input(INPUT_POST, "report_name") ?: "";
$report_class = filter_input(INPUT_POST, "report_class") ?: "";
$report_type = filter_input(INPUT_POST, "report_type") ?: "Report";
$report_description = filter_input(INPUT_POST, "report_description") ?: "";
$report_target = filter_input(INPUT_POST, "report_target") ?: "";
$report_class = trim(preg_replace("/\s+/", " ", $report_class));
$SQL = "insert into reports
( report_class,
report_type,
report_name,
report_description,
report_target )
VALUES ( :report_class,
:report_type,
:report_name,
:report_description,
:report_target)";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":report_class", $report_class);
$statement->bindValue(":report_type", $report_type);
$statement->bindValue(":report_name", $report_name);
$statement->bindValue(":report_description", $report_description);
$statement->bindValue(":report_target", $report_target);
$statement->execute();
break;
default:
$this->displayHome();
}
}
// =============
// Delete Report
// =============
public function deleteReport() {
$report_serial = filter_input(INPUT_POST, "report_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$reports = $this->getReport($report_serial);
if ($reports->count() == 0) {
$this->logError("Invalid Report ({$report_serial}): " . __METHOD__);
}
$SQL = "delete from reports
where report_serial = {$report_serial}";
$this->executeSQL($SQL);
}
// ===========
// Edit Report
// ===========
public function editReport() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$report_serial = filter_input(INPUT_POST, "report_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$reports = $this->getReport($report_serial);
if ($reports->count() == 0) {
$this->logError("Invalid Report ({$report_serial}): " . __METHOD__);
}
$constants = $this->getConstants();
$XML = $this->mergeXML($reports, "<XML/>");
$XML = $this->mergeXML($constants, $XML);
$content = $this->applyXSL($XML, $this->getXSL("editReport"));
$this->displayContent($content);
break;
case "update":
$report_serial = filter_input(INPUT_POST, "report_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$report_name = filter_input(INPUT_POST, "report_name") ?: "";
$report_class = filter_input(INPUT_POST, "report_class") ?: "";
$report_type = filter_input(INPUT_POST, "report_type") ?: "Report";
$report_description = filter_input(INPUT_POST, "report_description") ?: "";
$report_target = filter_input(INPUT_POST, "report_target") ?: "";
$report_class = trim(preg_replace("/\s+/", " ", $report_class));
$reports = $this->getReport($report_serial);
if ($reports->count() == 0) {
$this->logError("Invalid Report ({$report_serial}): " . __METHOD__);
}
$SQL = "update reports
set report_class = :report_class,
report_type = :report_type,
report_name = :report_name,
report_description = :report_description,
report_target = :report_target
where report_serial = :report_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":report_serial", $report_serial);
$statement->bindValue(":report_class", $report_class);
$statement->bindValue(":report_type", $report_type);
$statement->bindValue(":report_name", $report_name);
$statement->bindValue(":report_description", $report_description);
$statement->bindValue(":report_target", $report_target);
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ======================
// Return a Report Object
// ======================
public function getReport($report_serial = 0) {
$SQL = "select view_reports.*
from view_reports
where report_serial = {$report_serial}";
return $this->getTable("reports", $SQL);
}
// ===========================================
// Return the report_serial for a report_class
// ===========================================
public function getReportSerial($report_class = "") {
$SQL = "select view_reports.report_serial
from view_reports
where report_class = '{$report_class}'";
$reports = $this->getTable("reports", $SQL);
return (integer) ($reports->record->report_serial ?? 0);
}
// =======================
// Return a Reports Object
// =======================
public function getReports() {
$SQL = "select view_reports.*
from view_reports";
return $this->getTable("reports", $SQL);
}
// ============================
// Return a Reports Page Object
// ============================
public function getReportsPage() {
// Find Criteria
$find_report = filter_input(INPUT_POST, "find_report") ?: "";
$find_words = $this->sanitizeString($find_report);
// $find_words = implode("|", explode(" ", $find_report));
// Show Per Page
$this->pagination_size = filter_input(INPUT_POST, "reports_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_reports
where (report_class regexp :report_class
or report_name regexp :report_name
or report_type regexp :report_type
or report_description regexp :report_description)";
$statement = $connection->prepare($SQL);
$statement->bindValue(":report_class", $find_words);
$statement->bindValue(":report_name", $find_words);
$statement->bindValue(":report_type", $find_words);
$statement->bindValue(":report_description", $find_words);
$statement->execute();
$recordset = $statement->fetch(PDO::FETCH_ASSOC);
$count = (count($recordset) > 0) ? (integer) $recordset["count"] : (integer) 0;
// Pagination
$pagination = filter_input(INPUT_POST, "pagination") ?: "";
switch ($pagination) {
case "first" : $this->pagination_page = 1;
break;
case "previous" : $this->pagination_page = max(($this->pagination_page - 1), 1);
break;
case "next" : $this->pagination_page = ($this->pagination_page + 1);
break;
case "last" : $this->pagination_page = ($count / $this->pagination_size);
break;
}
$offset = (($this->pagination_page * $this->pagination_size) - $this->pagination_size);
$start = ($offset + 1);
$end = min($count, (($start + $this->pagination_size) - 1));
// Data
$SQL = "select view_reports.*
from view_reports
where (report_class regexp :report_class
or report_name regexp :report_name
or report_type regexp :report_type
or report_description regexp :report_description)
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":report_class", $find_words);
$statement->bindValue(":report_name", $find_words);
$statement->bindValue(":report_type", $find_words);
$statement->bindValue(":report_description", $find_words);
$statement->execute();
$reports = $this->getTableXML("reports", $statement);
// Insert Pagination Attributes
$reports->addAttribute("count", $count);
$reports->addAttribute("start", $start);
$reports->addAttribute("end", $end);
$reports->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $reports;
}
// ==================================
// Return a Select Report Page Object
// ==================================
public function getSelectReportPage() {
// Find Criteria
$select_report = filter_input(INPUT_POST, "select_report") ?: "";
$find_words = $this->sanitizeString($select_report);
// Show Per Page
$this->pagination_size = filter_input(INPUT_POST, "reports_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_reports
where report_name regexp :report_name
or report_description regexp :report_description";
$statement = $connection->prepare($SQL);
$statement->bindValue(":report_name", $find_words);
$statement->bindValue(":report_description", $find_words);
$statement->execute();
$recordset = $statement->fetch(PDO::FETCH_ASSOC);
$count = (count($recordset) > 0) ? (integer) $recordset["count"] : (integer) 0;
// Pagination
$pagination = filter_input(INPUT_POST, "pagination") ?: "";
switch ($pagination) {
case "first" : $this->pagination_page = 1;
break;
case "previous" : $this->pagination_page = max(($this->pagination_page - 1), 1);
break;
case "next" : $this->pagination_page = ($this->pagination_page + 1);
break;
case "last" : $this->pagination_page = ($count / $this->pagination_size);
break;
}
$offset = (($this->pagination_page * $this->pagination_size) - $this->pagination_size);
$start = ($offset + 1);
$end = min($count, (($start + $this->pagination_size) - 1));
// Data
$SQL = "select view_reports.*
from view_reports
where report_name regexp :report_name
or report_description regexp :report_description
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":report_name", $find_words);
$statement->bindValue(":report_description", $find_words);
$statement->execute();
$reports = $this->getTableXML("reports", $statement);
// Insert Pagination Attributes
$reports->addAttribute("count", $count);
$reports->addAttribute("start", $start);
$reports->addAttribute("end", $end);
$reports->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $reports;
}
// ====================================
// Determine if the Report Class Exists
// ====================================
public function reportExists() {
$exists = false;
$report_serial = filter_input(INPUT_POST, "report_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$report_class = filter_input(INPUT_POST, "report_class") ?: "";
$report_class = trim(preg_replace("/\s+/", " ", $report_class));
$SQL = "select report_serial
from view_reports
where report_serial != :report_serial
and lower(report_class) = :report_class";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":report_serial", $report_serial);
$statement->bindValue(":report_class", $report_class);
$statement->execute();
$recordset = $statement->fetchAll(PDO::FETCH_ASSOC);
$exists = (count($recordset) > 0) ? true : false;
echo json_encode($exists);
}
// ================
// Select a Report.
// ================
public function selectReport() {
$reports = $this->getSelectReportPage();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($reports, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$content = $this->applyXSL($XML, $this->getXSL("selectReport"));
$this->displayContent($content);
}
// =============
// Setup Reports
// =============
public function setupReports() {
$reports = $this->getReportsPage();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($reports, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$content = $this->applyXSL($XML, $this->getXSL("setupReports"));
$this->displayContent($content);
}
}
?>
+119
View File
@@ -0,0 +1,119 @@
<?php
// =============
// Sign In Class
// =============
class SignIn extends Base {
// Variables
private $current_user_id = "";
private $current_user_serial = "";
private $current_user_name = "";
private $current_user_email = "";
// ================================
// __construct : Class Constructor.
// ================================
public function __construct() {
set_error_handler(array($this, "displayError"));
date_default_timezone_set(self::TIMEZONE);
$this->current_user_id = $_SESSION[self::USER_ID] ?? "";
$this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
$this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
}
// ========================
// Login to the application
// ========================
public function login() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$XSLParms["BTN_SUBMIT"] = "main.php?action=SignIn.login&step=authenticate";
$XSLParms["INVALID_SIGNIN"] = "FALSE";
echo $this->applyXSL("", $this->getXSL("signIn"), $XSLParms);
exit();
break;
case "authenticate":
$user_name = trim(filter_input(INPUT_POST, "user_name") ?: "");
$user_password = filter_input(INPUT_POST, "user_password") ?: "";
$XSLParms["BTN_SUBMIT"] = "main.php?action=SignIn.login&step=authenticate";
$XSLParms["INVALID_SIGNIN"] = "TRUE";
$user = (new Users())->getUserByUserName($user_name);
if ($user->count() == 0) {
echo $this->applyXSL("", $this->getXSL("signIn"), $XSLParms);
die();
}
if ((integer) $user->record->user_active === 0) {
echo $this->applyXSL("", $this->getXSL("signIn"), $XSLParms);
die();
}
$stored_hashed_password = $user->record->user_password;
if (!password_verify($user_password, $stored_hashed_password)) {
echo $this->applyXSL("", $this->getXSL("signIn"), $XSLParms);
die();
}
session_regenerate_id(true);
$_SESSION[self::USER_AUTHENTICATED] = true;
$_SESSION[self::USER_SERIAL] = (integer) $user->record->user_serial;
$_SESSION[self::USER_ID] = (string) $user->record->user_id;
$_SESSION[self::USER_NAME] = (string) $user->record->user_name;
$_SESSION[self::USER_EMAIL] = (string) $user->record->user_email;
$_SESSION[self::USER_ROLE] = (string) $user->record->user_role;
$this->current_user_id = $_SESSION[self::USER_ID] ?? "";
$this->current_user_serial = $_SESSION[self::USER_SERIAL] ?? 0;
$this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
$this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
$system_admins = $this->getSettings()->xpath("//SystemAdministrator");
foreach ($system_admins as $admin) {
if ((string) $admin === $user_name) {
$_SESSION[self::USER_ROLE] = "System Administrator";
break;
}
}
(new Journal())->journalEntry("{$_SESSION[self::USER_NAME]} logged in ({$_SESSION[self::USER_ROLE]}).");
(new Users())->updateLogin();
header("Location: ./");
exit();
break;
default:
// User NOT Validated.
header("Location: ./");
exit();
}
}
}
?>
+384
View File
@@ -0,0 +1,384 @@
<?php
class Statuses extends Base {
// Variables.
private $current_user_serial = 0;
private $current_user_id = "";
private $current_user_name = "";
private $current_user_email = "";
private $pagination_size = 20;
private $pagination_page = 1;
// =================
// Class Constructor
// =================
public function __construct() {
set_error_handler(array($this, "displayError"));
date_default_timezone_set(self::TIMEZONE);
$this->current_user_serial = $_SESSION[self::USER_SERIAL] ?? 0;
$this->current_user_id = $_SESSION[self::USER_ID] ?? "";
$this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
$this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
$this->pagination_page = $_SESSION[self::PAGINATION_PAGE] ?? 1;
}
// ==========
// Add Status
// ==========
public function addStatus() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$content = $this->applyXSL("", $this->getXSL("addStatus"));
$this->displayContent($content);
break;
case "add":
$status_name = filter_input(INPUT_POST, "status_name") ?: "";
$status_classes = filter_input(INPUT_POST, "status_classes") ?: "";
$status_active = filter_input(INPUT_POST, "status_active", FILTER_VALIDATE_BOOLEAN) ?: false;
$SQL = "insert into statuses
( status_name,
status_classes,
status_active,
status_creator,
status_created )
VALUES ( :status_name,
:status_classes,
:status_active,
:status_creator,
:status_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":status_name", $status_name);
$statement->bindValue(":status_classes", $status_classes);
$statement->bindValue(":status_active", $status_active, PDO::PARAM_BOOL);
$statement->bindValue(":status_creator", $this->current_user_name);
$statement->bindValue(":status_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// =============
// Delete Status
// =============
public function deleteStatus() {
$status_serial = filter_input(INPUT_POST, "status_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$status = $this->getStatus($status_serial);
if ($status->count() == 0) {
$this->logError("Invalid Status ({$status_serial}). " . __METHOD__);
}
$SQL = "delete from statuses
where status_serial = {$status_serial}";
$this->executeSQL($SQL);
}
// ============================
// Determine if a Status exists
// ============================
public function statusExists() {
$status_serial = filter_input(INPUT_POST, "status_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$status_name = filter_input(INPUT_POST, "status_name") ?: "";
$SQL = "select status_serial
from view_statuses
where status_serial != :status_serial
and lower(status_name) = :status_name";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":status_serial", $status_serial);
$statement->bindValue(":status_name", strtolower($status_name));
$statement->execute();
$recordset = $statement->fetchAll(PDO::FETCH_ASSOC);
$exists = (count($recordset) > 0) ? true : false;
echo json_encode($exists);
}
// ======================================
// Determine if a Status is Active (AJAX)
// ======================================
public function statusActive() {
$status_serial = filter_input(INPUT_POST, "status_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$active = false;
$SQL = "select workorder_status
from workorders
where workorder_status = {$status_serial}
limit 1";
$workorders = $this->getTable("workorders", $SQL);
$active = ($workorders->count() > 0) ? true : false;
echo json_encode($active);
}
// =============
// Edit a Status
// =============
public function editStatus() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$status_serial = filter_input(INPUT_POST, "status_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$status = $this->getStatus($status_serial);
if ($status->count() == 0) {
$this->logError("Invalid Status ({$status_serial}). " . __METHOD__);
}
$XML = $this->mergeXML($status, "<XML/>");
$content = $this->applyXSL($XML, $this->getXSL("editStatus"));
$this->displayContent($content);
break;
case "update":
$status_serial = filter_input(INPUT_POST, "status_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$status_name = filter_input(INPUT_POST, "status_name") ?: "";
$status_classes = filter_input(INPUT_POST, "status_classes") ?: "";
$status_active = filter_input(INPUT_POST, "status_active", FILTER_VALIDATE_BOOLEAN) ?: false;
$status_default = filter_input(INPUT_POST, "status_default", FILTER_VALIDATE_BOOLEAN) ?: false;
// Verify the Status
$status = $this->getStatus($status_serial);
if ($status->count() == 0) {
$this->logError("Invalid Status ({$status_serial}). " . __METHOD__);
}
$SQL = "update statuses
set status_name = :status_name,
status_classes = :status_classes,
status_active = :status_active,
status_default = :status_default,
status_changer = :status_changer,
status_changed = :status_changed
where status_serial = :status_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":status_serial", $status_serial);
$statement->bindValue(":status_name", $status_name);
$statement->bindValue(":status_classes", $status_classes);
$statement->bindValue(":status_active", $status_active, PDO::PARAM_BOOL);
$statement->bindValue(":status_default", $status_default, PDO::PARAM_BOOL);
$statement->bindValue(":status_changer", $this->current_user_name);
$statement->bindValue(":status_changed", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ================================
// Return an Active Statuses Object
// ================================
public function getActiveStatuses() {
$SQL = "select view_statuses.*
from view_statuses
where status_active is true";
return $this->getTable("statuses", $SQL);
}
// -------------------------
// Return the Default Status
// -------------------------
public function getDefaultStatus() {
$SQL = "select status_serial
from view_statuses
where status_default is true";
return $this->getTable("statuses", $SQL);
}
// =======================
// Return an Status Object
// =======================
public function getStatus($status_serial = 0) {
$SQL = "select view_statuses.*
from view_statuses
where status_serial = {$status_serial}";
return $this->getTable("statuses", $SQL);
}
// ===========================
// Return a Statuss Object
// ===========================
public function getStatuses() {
$SQL = "select view_statuses.*
from view_statuses";
return $this->getTable("statuses", $SQL);
}
// ============================
// Return a Statuss Page Object
// ============================
public function getStatusesPage() {
// Find Criteria
$find_status = filter_input(INPUT_POST, "find_status") ?: "";
$find_status = $this->sanitizeString($find_status);
$find_words = implode("|", explode(" ", $find_status));
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_statuses
where status_name regexp :status_name
or status_classes regexp :status_classes";
$statement = $connection->prepare($SQL);
$statement->bindValue(":status_name", $find_words);
$statement->bindValue(":status_classes", $find_words);
$statement->execute();
$recordset = $statement->fetch(PDO::FETCH_ASSOC);
$count = (count($recordset) > 0) ? (integer) $recordset["count"] : (integer) 0;
// Pagination
$pagination = filter_input(INPUT_POST, "pagination") ?: "";
switch ($pagination) {
case "first" : $this->pagination_page = 1;
break;
case "previous" : $this->pagination_page = max(($this->pagination_page - 1), 1);
break;
case "next" : $this->pagination_page = ($this->pagination_page + 1);
break;
case "last" : $this->pagination_page = ($count / $this->pagination_size);
break;
}
$offset = (($this->pagination_page * $this->pagination_size) - $this->pagination_size);
$start = ($offset + 1);
$end = min($count, (($start + $this->pagination_size) - 1));
// Data
$SQL = "select view_statuses.*
from view_statuses
where status_name regexp :status_name
or status_classes regexp :status_classes
order by status_name
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":status_name", $find_words);
$statement->bindValue(":status_classes", $find_words);
$statement->execute();
$statuses = $this->getTableXML("statuses", $statement);
// Insert Pagination Attributes
$statuses->addAttribute("count", $count);
$statuses->addAttribute("start", $start);
$statuses->addAttribute("end", $end);
$statuses->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $statuses;
}
// ==============
// Setup Statuses
// ==============
public function setupStatuses() {
$statuses = $this->getStatusesPage();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($statuses, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$content = $this->applyXSL($XML, $this->getXSL("setupStatuses"));
$this->displayContent($content);
}
}
?>
+686
View File
@@ -0,0 +1,686 @@
<?php
class Subscriptions extends Base {
// Variables.
private $current_user_serial = 0;
private $current_user_id = "";
private $current_user_name = "";
private $current_user_email = "";
private $pagination_size = 20;
private $pagination_page = 1;
// =================
// Class Constructor
// =================
public function __construct() {
set_error_handler(array($this, "displayError"));
date_default_timezone_set(self::TIMEZONE);
$this->current_user_serial = $_SESSION[self::USER_SERIAL] ?? 0;
$this->current_user_id = $_SESSION[self::USER_ID] ?? "";
$this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
$this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
$this->pagination_page = $_SESSION[self::PAGINATION_PAGE] ?? 1;
}
// ===================
// Setup Subscriptions
// ===================
public function setupSubscriptions() {
$subscriptions = $this->getSubscriptionsPage();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($subscriptions, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$content = $this->applyXSL($XML, $this->getXSL("setupSubscriptions"));
$this->displayContent($content);
}
// =========================
// Go To Subscription Driver
// =========================
public function goToSubscription($subscription_serial = 0) {
$subscription_serial = (integer) filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription = $this->getSubscription($subscription_serial);
if ($subscription->count() === 0) {
$this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
}
switch ($subscription_serial) {
case 5:
$_SESSION['subscription_serial'] = $subscription_serial;
(new PermitsByBuilder())->searchPermits($subscription_serial);
break;
case 7:
$_SESSION['subscription_serial'] = $subscription_serial;
(new PermitsBySubdivision())->searchPermits($subscription_serial);
break;
case 9:
$project_type = "SingleFamily";
$area = "South";
(new PermitsByBuilder())->searchPermits($project_type, $area);
break;
case 10:
$project_type = "SingleFamily";
$area = "South";
(new PermitsBySubdivision())->searchPermits($project_type, $area);
break;
case 11:
$project_type = "SingleFamily";
$area = "All";
(new PermitsByBuilder())->searchPermits($project_type, $area);
break;
case 12:
$project_type = "SingleFamily";
$area = "All";
(new PermitsBySubdivision())->searchPermits($project_type, $area);
break;
case 13:
$project_type = "MultiFamily";
$area = "South";
(new PermitsByBuilder())->searchPermits($project_type, $area);
break;
case 14:
$project_type = "MultiFamily";
$area = "South";
(new PermitsBySubdivision())->searchPermits($project_type, $area);
break;
case 15:
$project_type = "MultiFamily";
$area = "North";
(new PermitsByBuilder())->searchPermits($project_type, $area);
break;
case 16:
$project_type = "MultiFamily";
$area = "North";
(new PermitsBySubdivision())->searchPermits($project_type, $area);
break;
}
}
// ================
// Add Subscription
// ================
public function addSubscription() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$constants = $this->getConstants();
$content = $this->applyXSL($constants, $this->getXSL("addSubscription"));
$this->displayContent($content);
break;
case "add":
$subscription_title = filter_input(INPUT_POST, "subscription_title") ?: "";
$subscription_description = filter_input(INPUT_POST, "subscription_description") ?: "";
$subscription_projecttype = filter_input(INPUT_POST, "subscription_projecttype") ?: "";
$subscription_area = filter_input(INPUT_POST, "subscription_area") ?: "";
$SQL = "insert into subscriptions
( subscription_title,
subscription_description,
subscription_projecttype,
subscription_area,
subscription_creator,
subscription_created )
VALUES ( :subscription_title,
:subscription_description,
:subscription_projecttype,
:subscription_area,
:subscription_creator,
:subscription_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":subscription_title", $subscription_title);
$statement->bindValue(":subscription_description", $subscription_description);
$statement->bindValue(":subscription_projecttype", $subscription_projecttype);
$statement->bindValue(":subscription_area", $subscription_area);
$statement->bindValue(":subscription_creator", $this->current_user_name);
$statement->bindValue(":subscription_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// =================
// Edit Subscription
// =================
public function editSubscription() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$subscription_serial = (integer) filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription = $this->getSubscription($subscription_serial);
if ($subscription->count() === 0) {
$this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
}
$constants = $this->getConstants();
$XML = $this->mergeXML($constants, "<XML/>");
$XML = $this->mergeXML($subscription, $XML);
$content = $this->applyXSL($XML, $this->getXSL("editSubscription"));
$this->displayContent($content);
break;
case "update":
$subscription_serial = filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription_title = filter_input(INPUT_POST, "subscription_title") ?: "";
$subscription_description = filter_input(INPUT_POST, "subscription_description") ?: "";
$subscription_projecttype = filter_input(INPUT_POST, "subscription_projecttype") ?: "";
$subscription_area = filter_input(INPUT_POST, "subscription_area") ?: "";
$subscriptions = $this->getSubscription($subscription_serial);
if ($subscriptions->count() == 0) {
$this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
}
// Update the Subscription
$SQL = "update subscriptions
set subscription_title = :subscription_title,
subscription_description = :subscription_description,
subscription_projecttype = :subscription_projecttype,
subscription_area = :subscription_area
where subscription_serial = :subscription_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":subscription_serial", $subscription_serial);
$statement->bindValue(":subscription_title", $subscription_title);
$statement->bindValue(":subscription_description", $subscription_description);
$statement->bindValue(":subscription_projecttype", $subscription_projecttype);
$statement->bindValue(":subscription_area", $subscription_area);
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ===================
// Delete Subscription
// ===================
public function deleteSubscription() {
$subscription_serial = filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription = $this->getSubscription($subscription_serial);
if ($subscription->count() == 0) {
$this->logError("Invalid Subscription ({$subscription_serial}). " . __METHOD__);
}
$SQL = "delete from subscriptions
where subscription_serial = {$subscription_serial}";
$this->executeSQL($SQL);
}
// ========================
// Add Subscription to User
// ========================
public function addSubscriptionToUser() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$user_serial = filter_input(INPUT_POST, "user_reference", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$user = (new Users())->getUser($user_serial);
$usersubscriptions = $this->getUsersActiveSubscriptions($user_serial);
$subscriptions = $this->getSubscriptions();
$XML = $this->mergeXML($user, "<XML/>");
$XML = $this->mergeXML($subscriptions, $XML);
$XML = $this->mergeXML($usersubscriptions, $XML);
$content = $this->applyXSL($XML, $this->getXSL("addSubscriptionToUser"));
$this->displayContent($content);
break;
case "add":
$user_serial = filter_input(INPUT_POST, "user_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription_serials = filter_input(INPUT_POST, "subscriptions", FILTER_SANITIZE_NUMBER_INT, FILTER_REQUIRE_ARRAY) ?: array();
$subscription_end_dates = filter_input(INPUT_POST, "subscription_end_date", FILTER_DEFAULT, FILTER_REQUIRE_ARRAY) ?: array();
$subscriptions = array();
foreach ($subscription_serials as $index => $subscription_serial) {
$subscriptions[] = array(
"usersubscription_subscription" => $subscription_serial,
"usersubscription_end_date" => date("Y-m-d", strtotime($subscription_end_dates[$index] ?? ""))
);
}
$SQL = "insert into usersubscriptions
( usersubscription_user_serial,
usersubscription_subscription_serial,
usersubscription_stop_date,
usersubscription_origin,
usersubscription_timestamp )
VALUES ( :usersubscription_user_serial,
:usersubscription_subscription_serial,
:usersubscription_stop_date,
:usersubscription_origin,
:usersubscription_timestamp )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":usersubscription_user_serial", $user_serial);
$statement->bindValue(":usersubscription_timestamp", $this->getTimestamp());
$statement->bindValue(":usersubscription_origin", $this->current_user_name);
foreach ($subscriptions as $subscription) {
$subscription_serial = $subscription['usersubscription_subscription'];
$subscription_stop_date = $subscription['usersubscription_end_date'];
$statement->bindValue(":usersubscription_subscription_serial", $subscription_serial);
$statement->bindValue(":usersubscription_stop_date", $subscription_stop_date);
$statement->execute();
}
break;
default:
$this->displayHome();
}
}
// =========================
// Edit a Users Subscription
// =========================
public function editUsersSubscription() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$user_serial = filter_input(INPUT_POST, "user_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$usersubscription_serial = filter_input(INPUT_POST, "usersubscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$user = (new Users())->getUser($user_serial);
$usersubscription = $this->getUsersSubscription($usersubscription_serial);
$subscriptions = $this->getSubscriptions();
$XML = $this->mergeXML($user, "<XML/>");
$XML = $this->mergeXML($usersubscription, $XML);
$XML = $this->mergeXML($subscriptions, $XML);
$content = $this->applyXSL($XML, $this->getXSL("editUsersSubscription"));
$this->displayContent($content);
break;
case "update":
$subscription_serial = filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$usersubscription_serial = filter_input(INPUT_POST, "usersubscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription_stop_date = filter_input(INPUT_POST, "subscription_stop_date") ?: "";
$subscription_stop_date = date("Y-m-d", strtotime($subscription_stop_date));
$SQL = "update usersubscriptions
set usersubscription_stop_date = :usersubscription_stop_date,
usersubscription_subscription_serial = :usersubscription_subscription_serial,
usersubscription_origin = :usersubscription_origin,
usersubscription_timestamp = :usersubscription_timestamp
where usersubscription_serial = :usersubscription_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":usersubscription_stop_date", $subscription_stop_date);
$statement->bindValue(":usersubscription_subscription_serial", $subscription_serial);
$statement->bindValue(":usersubscription_origin", $this->current_user_name);
$statement->bindValue(":usersubscription_timestamp", $this->getTimestamp());
$statement->bindValue(":usersubscription_serial", $usersubscription_serial);
$statement->execute();
break;
default:
$this->displayHome();
}
}
// =========================
// Delete Users Subscription
// =========================
public function deleteUsersSubscription() {
$usersubscription_serial = filter_input(INPUT_POST, "usersubscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription = $this->getUsersSubscription($usersubscription_serial);
if ($subscription->count() == 0) {
$this->logError("Invalid Subscription ({$usersubscription_serial}). " . __METHOD__);
}
$SQL = "delete from usersubscriptions
where usersubscription_serial = {$usersubscription_serial}";
$this->executeSQL($SQL);
}
// ============================
// Return a Subscription Object
// ============================
public function getSubscription($subscription_serial = 0) {
$SQL = "select view_subscriptions.*
from view_subscriptions
where subscription_serial = {$subscription_serial}";
return $this->getTable("subscriptions", $SQL);
}
// ============================
// Return a Subscription Object
// ============================
public function getSubscriptions() {
$SQL = "select view_subscriptions.*
from view_subscriptions";
return $this->getTable("subscriptions", $SQL);
}
// ==================================
// Return a Subscriptions Page Object
// ==================================
public function getSubscriptionsPage() {
// Find Criteria
$find_subscription = filter_input(INPUT_POST, "find_subscription") ?: "";
$find_subscription = $this->sanitizeString($find_subscription);
$find_words = implode("|", explode(" ", $find_subscription));
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_subscriptions
where subscription_title regexp :subscription_title
or subscription_description regexp :subscription_description
or subscription_projecttype regexp :subscription_projecttype
or subscription_area regexp :subscription_area";
$statement = $connection->prepare($SQL);
$statement->bindValue(":subscription_title", $find_words);
$statement->bindValue(":subscription_description", $find_words);
$statement->bindValue(":subscription_projecttype", $find_words);
$statement->bindValue(":subscription_area", $find_words);
$statement->execute();
$recordset = $statement->fetch(PDO::FETCH_ASSOC);
$count = (count($recordset) > 0) ? (integer) $recordset["count"] : (integer) 0;
// Pagination
$pagination = filter_input(INPUT_POST, "pagination") ?: "";
switch ($pagination) {
case "first" : $this->pagination_page = 1;
break;
case "previous" : $this->pagination_page = max(($this->pagination_page - 1), 1);
break;
case "next" : $this->pagination_page = ($this->pagination_page + 1);
break;
case "last" : $this->pagination_page = ($count / $this->pagination_size);
break;
}
$offset = (($this->pagination_page * $this->pagination_size) - $this->pagination_size);
$start = ($offset + 1);
$end = min($count, (($start + $this->pagination_size) - 1));
// Data
$SQL = "select view_subscriptions.*
from view_subscriptions
where subscription_title regexp :subscription_title
or subscription_description regexp :subscription_description
or subscription_projecttype regexp :subscription_projecttype
or subscription_area regexp :subscription_area
order by subscription_title
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":subscription_title", $find_words);
$statement->bindValue(":subscription_description", $find_words);
$statement->bindValue(":subscription_projecttype", $find_words);
$statement->bindValue(":subscription_area", $find_words);
$statement->execute();
$subscriptions = $this->getTableXML("subscriptions", $statement);
// Insert Pagination Attributes
$subscriptions->addAttribute("count", $count);
$subscriptions->addAttribute("start", $start);
$subscriptions->addAttribute("end", $end);
$subscriptions->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $subscriptions;
}
// ==================
// User Subscriptions
// ==================
public function userSubscriptions() {
$subscriptions = $this->getUsersActiveSubscriptions($this->current_user_serial);
$alerts = (new Alerts())->getActiveAlerts();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($subscriptions, "<XML/>");
$XML = $this->mergeXML($alerts, $XML);
$XML = $this->mergeXML($popovers, $XML);
$content = $this->applyXSL($XML, $this->getXSL("userSubscriptions"));
$this->displayContent($content);
}
// ============================
// Return a Users Subscriptions
// ============================
public function getUsersActiveSubscriptions($user_serial) {
$SQL = "SELECT view_usersubscriptions.*
FROM view_usersubscriptions
WHERE usersubscription_user_serial = '{$user_serial}'
AND view_usersubscriptions.usersubscription_status = 'ACTIVE'
AND view_usersubscriptions.usersubscription_stop_date >= NOW()
ORDER BY
CASE
WHEN view_usersubscriptions.subscription_area = 'All' THEN 0
ELSE 1
END,
view_usersubscriptions.subscription_title,
view_usersubscriptions.usersubscription_status";
return $this->getTable("usersubscriptions", $SQL);
}
// ============================
// Return a Users Subscriptions
// ============================
public function getAllUsersSubscriptions($user_serial) {
$SQL = "select view_usersubscriptions.*
from view_usersubscriptions
where usersubscription_user_serial = {$user_serial}
order by view_usersubscriptions.usersubscription_status, view_usersubscriptions.subscription_title";
return $this->getTable("usersubscriptions", $SQL);
}
// ===========================
// Return a Users Subscription
// ===========================
public function getUsersSubscription($usersubscription_serial) {
$SQL = "select view_usersubscriptions.*
from view_usersubscriptions
where usersubscription_serial = {$usersubscription_serial}";
return $this->getTable("usersubscription", $SQL);
}
// ==================================
// Determine if a Subscription exists
// ==================================
public function subscriptionExists() {
$subscription_serial = filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription_title = filter_input(INPUT_POST, "subscription_title") ?: "";
$SQL = "select subscription_serial
from view_subscriptions
where subscription_serial != :subscription_serial
and lower(subscription_title) = :subscription_title";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":subscription_serial", $subscription_serial);
$statement->bindValue(":subscription_title", strtolower($subscription_title));
$statement->execute();
$recordset = $statement->fetchAll(PDO::FETCH_ASSOC);
$exists = (count($recordset) > 0) ? true : false;
echo json_encode($exists);
}
}
?>
+657
View File
@@ -0,0 +1,657 @@
<?php
// ===========
// Users Class
// ===========
class Users extends Base {
// Variables
private $current_user_id = "";
private $current_user_serial = "";
private $current_user_name = "";
private $current_user_email = "";
private $pagination_size = 20;
private $pagination_page = 1;
// ================================
// __construct : Class Constructor.
// ================================
public function __construct() {
set_error_handler(array($this, "displayError"));
date_default_timezone_set(self::TIMEZONE);
$this->current_user_id = $_SESSION[self::USER_ID] ?? "";
$this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
$this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";
$this->pagination_page = $_SESSION[self::PAGINATION_PAGE] ?? 1;
}
// ===========
// Setup Users
// ===========
public function setupUsers() {
$users = $this->getUsersPage();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($users, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$html = $this->applyXSL($XML, $this->getXSL("setupUsers"));
$this->displayContent($html);
}
// ============
// User Summary
// ============
public function userSummary() {
$user_serial = filter_input(INPUT_POST, "user_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$user = $this->getUser($user_serial);
if ($user->count() == 0) {
$this->logError("Invalid User ({$user_serial}). " . __METHOD__);
}
$notes = (new Notes())->getAllNotes($user_serial);
$subscriptions = (new Subscriptions())->getAllUsersSubscriptions($user_serial);
$XML = $this->mergeXML($user, "<XML/>");
$XML = $this->mergeXML($subscriptions, $XML);
$XML = $this->mergeXML($notes, $XML);
$content = $this->applyXSL($XML, $this->getXSL("userSummary"));
$this->displayContent($content);
}
// ========
// Add User
// ========
public function addUser() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$popovers = (new Popovers())->getPopovers();
$constants = $this->getConstants();
$XML = $this->mergeXML($popovers, "<XML/>");
$XML = $this->mergeXML($constants, $XML);
$content = $this->applyXSL($XML, $this->getXSL("addUser"));
$this->displayContent($content);
break;
case "add":
$user_name = filter_input(INPUT_POST, "user_name") ?: "";
$user_client_name = filter_input(INPUT_POST, "user_client_name") ?: "";
$user_email = filter_input(INPUT_POST, "user_email") ?: "";
$user_role = filter_input(INPUT_POST, "user_role") ?: "";
$user_name = strtoupper(preg_replace("/\s+/", " ", $user_name));
$user_random_password = $this->generateRandomPassword();
$user_temp_password = password_hash($user_random_password, PASSWORD_DEFAULT);
$user_change_password = (boolean) true;
$user_active = (boolean) true;
// Add the User
$connection = $this->connect();
$SQL = "insert into users
( user_name,
user_email,
user_client_name,
user_password,
user_role,
user_change_password,
user_active,
user_creator,
user_created )
values ( :user_name,
:user_email,
:user_client_name,
:user_password,
:user_role,
:user_change_password,
:user_active,
:user_creator,
:user_created )";
$statement = $connection->prepare($SQL);
$statement->bindValue(":user_name", $user_name);
$statement->bindValue(":user_email", $user_email);
$statement->bindValue(":user_client_name", $user_client_name);
$statement->bindValue(":user_password", $user_temp_password);
$statement->bindValue(":user_role", $user_role);
$statement->bindValue(":user_change_password", $user_change_password, PDO::PARAM_BOOL);
$statement->bindValue(":user_active", $user_active, PDO::PARAM_BOOL);
$statement->bindValue(":user_creator", $this->current_user_name);
$statement->bindValue(":user_created", $this->getTimestamp());
if (!$statement->execute()) {
trigger_error($statement->errorInfo()[2]);
}
$user = $this->getUserByUserName($user_name);
// Send User Credentials
(new Email())->emailNewUserCredentials($user, $user_random_password);
break;
default:
$this->displayHome();
}
}
// ===========
// Delete User
// ===========
public function deleteUser() {
$user_serial = filter_input(INPUT_POST, "user_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$users = $this->getUser($user_serial);
if ($users->count() == 0) {
$this->logError("Invalid User ({$user_serial}): " . __METHOD__);
}
$SQL = "delete from users
where user_serial = {$user_serial}";
$this->executeSQL($SQL);
}
// =========
// Edit User
// =========
public function editUser() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$user_serial = (integer) filter_input(INPUT_POST, "user_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$user = $this->getUser($user_serial);
if ($user->count() === 0) {
$this->logError("Invalid User ({$user_serial}): " . __METHOD__);
}
$popovers = (new Popovers())->getPopovers();
$constants = $this->getConstants();
$XML = $this->mergeXML($user, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$XML = $this->mergeXML($constants, $XML);
$content = $this->applyXSL($XML, $this->getXSL("editUser"));
$this->displayContent($content);
break;
case "update":
$user_serial = filter_input(INPUT_POST, "user_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$user_name = filter_input(INPUT_POST, "user_name") ?: "";
$user_email = filter_input(INPUT_POST, "user_email") ?: "";
$user_client_name = filter_input(INPUT_POST, "user_client_name") ?: "";
$user_role = filter_input(INPUT_POST, "user_role") ?: "";
$user_active = filter_input(INPUT_POST, "user_active", FILTER_VALIDATE_BOOLEAN) ?: false;
$users = $this->getUser($user_serial);
if ($users->count() == 0) {
$this->logError("Invalid User ({$user_serial}): " . __METHOD__);
}
// Update the User
$SQL = "update users
set user_name = :user_name,
user_email = :user_email,
user_client_name = :user_client_name,
user_role = :user_role,
user_active = :user_active,
user_changer = :user_changer,
user_changed = :user_changed
where user_serial = :user_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":user_serial", $user_serial);
$statement->bindValue(":user_name", $user_name);
$statement->bindValue(":user_email", $user_email);
$statement->bindValue(":user_client_name", $user_client_name);
$statement->bindValue(":user_role", $user_role);
$statement->bindValue(":user_active", $user_active, PDO::PARAM_BOOL);
$statement->bindValue(":user_changer", $this->current_user_name);
$statement->bindValue(":user_changed", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ====================
// Return a User Object
// ====================
public function getUser($user_serial = 0) {
$SQL = "select view_users.*
from view_users
where user_serial = {$user_serial}";
return $this->getTable("users", $SQL);
}
// ====================
// Return a User Object
// ====================
public function getUserByUserName($user_name) {
$SQL = "select view_users.*
from view_users
where user_id = '{$user_name}'";
return $this->getTable("user", $SQL);
}
// ======================
// Return a User's Serial
// ======================
public function getUserSerial($user_id = "") {
$users = $this->getUserByUserId($user_id);
return ($users->count() === 0) ? 0 : (integer) $users->record->user_serial;
}
// =====================
// Return a Users Object
// =====================
public function getUsers() {
$SQL = "select view_users.* from view_users";
return $this->getTable("users", $SQL);
}
// ==========================
// Return a Users Page Object
// ==========================
public function getUsersPage() {
// Find Criteria
$find_user = filter_input(INPUT_POST, "find_user") ?: "";
$find_user = $this->sanitizeString($find_user);
$find_words = implode("|", explode(" ", $find_user));
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_users
where user_name regexp :user_name
or user_client_name regexp :user_client_name
or user_email regexp :user_email
or user_role regexp :user_role";
$statement = $connection->prepare($SQL);
$statement->bindValue(":user_name", $find_words);
$statement->bindValue(":user_client_name", $find_words);
$statement->bindValue(":user_email", $find_words);
$statement->bindValue(":user_role", $find_words);
$statement->execute();
$recordset = $statement->fetch(PDO::FETCH_ASSOC);
$count = (count($recordset) > 0) ? (integer) $recordset["count"] : (integer) 0;
// Pagination
$pagination = filter_input(INPUT_POST, "pagination") ?: "";
switch ($pagination) {
case "first" : $this->pagination_page = 1;
break;
case "previous" : $this->pagination_page = max(($this->pagination_page - 1), 1);
break;
case "next" : $this->pagination_page = ($this->pagination_page + 1);
break;
case "last" : $this->pagination_page = ($count / $this->pagination_size);
break;
}
$offset = (($this->pagination_page * $this->pagination_size) - $this->pagination_size);
$start = ($offset + 1);
$end = min($count, (($start + $this->pagination_size) - 1));
// Data
$SQL = "select view_users.*
from view_users
where user_name regexp :user_name
or user_client_name regexp :user_client_name
or user_email regexp :user_email
or user_role regexp :user_role
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":user_name", $find_words);
$statement->bindValue(":user_client_name", $find_words);
$statement->bindValue(":user_email", $find_words);
$statement->bindValue(":user_role", $find_words);
$statement->execute();
$users = $this->getTableXML("users", $statement);
// Insert Pagination Attributes
$users->addAttribute("count", $count);
$users->addAttribute("start", $start);
$users->addAttribute("end", $end);
$users->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $users;
}
// ===========================
// Return an User Object(AJAX)
// ===========================
public function getUser_AJAX($user_name = "") {
$user_name = filter_input(INPUT_POST, "user_name") ?: $user_name;
$users = $this->getUserByUserName($user_name);
// Create the User Object.
$User = array();
$User["exists"] = ($users->count() > 0) ? true : false;
if ($_SESSION[self::AJAX]) {
echo json_encode($User);
} else {
return $User;
}
}
// ==========================
// Determine if a User Exists
// ==========================
public function userExists() {
$user_serial = filter_input(INPUT_POST, "user_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$user_id = filter_input(INPUT_POST, "user_id") ?: "";
$user_id = strtolower(trim(preg_replace("/\s+/", " ", $user_id)));
$SQL = "select user_id
from view_users
where user_serial != :user_serial
and user_id = :user_id";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":user_serial", $user_serial);
$statement->bindValue(":user_id", $user_id);
$statement->execute();
$recordset = $statement->fetchAll(PDO::FETCH_ASSOC);
$exists = (count($recordset) > 0) ? true : false;
echo json_encode($exists);
}
// =============================
// Determine if a User is Active
// =============================
public function userActive() {
$user_serial = (integer) filter_input(INPUT_POST, "user_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$SQL = "select request_serial
from requests
where request_user = {$user_serial}";
$requests = $this->getTable("requests", $SQL);
$active = ($requests->count() > 0) ? true : $active;
echo json_encode($active);
}
// ===============
// Change Password
// ===============
public function changePassword() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($popovers, "<XML/>");
$content = $this->applyXSL($XML, $this->getXSL("changePassword"));
$this->displayContent($content);
break;
case "change":
$user_serial = $_SESSION[self::USER_SERIAL];
$user_new_password = filter_input(INPUT_POST, "user_new_password") ?: "";
$user_verify_password = filter_input(INPUT_POST, "user_verify_password") ?: "";
if (!$user_new_password == $user_verify_password) {
$this->initializeSession();
}
$user_new_hashed_password = password_hash($user_new_password, PASSWORD_DEFAULT);
// Update User Password
$connection = $this->connect();
$SQL = "update users
set user_password = :user_password,
user_change_password = :user_change_password,
user_changer = :user_changer,
user_changed = :user_changed
where user_serial = :user_serial";
$statement = $connection->prepare($SQL);
$statement->bindValue(":user_serial", $user_serial);
$statement->bindValue(":user_password", $user_new_hashed_password);
$statement->bindValue(":user_change_password", 0);
$statement->bindValue(":user_changer", $this->current_user_name);
$statement->bindValue(":user_changed", $this->getTimestamp());
if (!$statement->execute()) {
$this->debug($statement->errorInfo()[2]);
}
(new Journal())->journalEntry("{$_SESSION[self::USER_NAME]} changed their password.");
break;
default:
$this->displayHome();
}
}
// ==============
// Reset Password
// ==============
public function resetPassword() {
$reset = false;
$user_serial = filter_input(INPUT_POST, "user_serial") ?: "";
$user = $this->getUser($user_serial);
$user_name = $user->record->user_name;
$user_random_password = $this->generateRandomPassword();
$user_temp_password = password_hash($user_random_password, PASSWORD_DEFAULT);
// Update User Password
$connection = $this->connect();
$SQL = "update users
set user_password = :user_password,
user_change_password = :user_change_password
where user_serial = :user_serial";
$statement = $connection->prepare($SQL);
$statement->bindValue(":user_serial", $user_serial);
$statement->bindValue(":user_password", $user_temp_password);
$statement->bindValue(":user_change_password", 1);
if (!$statement->execute()) {
$this->debug($statement->errorInfo()[2]);
} else {
$reset = true;
}
// Send User Credentials
(new Email())->emailUserPasswordResetLink($user, $user_random_password);
(new Journal())->journalEntry("{$_SESSION[self::USER_NAME]} reset {$user_name}'s password.");
echo json_encode($reset);
}
// ===============================================
// Update the Login timestamp for the current User
// ===============================================
public function updateLogin() {
$SQL = "update users
set user_login = :user_login
where user_serial = :user_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":user_login", $this->getTimestamp());
$statement->bindValue(":user_serial", $this->current_user_serial);
$statement->execute();
}
// ====================
// Update Active Status
// ====================
public function updateActiveStatus() {
$user_serial = filter_input(INPUT_POST, "user_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$user_active = filter_input(INPUT_POST, "user_active", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$SQL = "update users
set user_active = :user_active,
user_changed = :user_changed,
user_changer = :user_changer
where user_serial = :user_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":user_serial", $user_serial);
$statement->bindValue(":user_active", $user_active);
$statement->bindValue(":user_changed", $this->getTimestamp());
$statement->bindValue(":user_changer", $this->current_user_name);
if (!$statement->execute()) {
error_log($statement->errorInfo()[2]);
}
}
// ====================================
// Return a Users Login Activity Object
// ====================================
public function getLoginActivity($userserial) {
$SQL = "select view_journal.journal_timestamp_verbose, view_journal.journal_ip
from view_journal
where view_journal.journal_origin = '{$userserial}'
and view_journal.journal_entry like '{$userserial} %logged in%'";
return $this->getTable("loginactivity", $SQL);
}
}
?>