First git push to github

This commit is contained in:
2026-05-29 14:52:16 -04:00
commit 94bc6117f2
1576 changed files with 455304 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, PDO::PARAM_STR);
$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 $connection = "";
// =================
// 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->connection = $this->connect();
}
// ==================================
// Return a 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->connection->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->connection->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->connection->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->connection->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);
}
}
?>
+904
View File
@@ -0,0 +1,904 @@
<?php
// ==========
// Base Class
// ==========
require_once "vendor/autoload.php";
require_once "classes/Autoloader.php";
class Base {
// =========
// Constants
// =========
const APPLICATION_NAME = "DEC Data Repository";
const APPLICATION_MNEMONIC = "DECDR";
const VERSION = "2.00";
const TIMEZONE = "America/New_York";
// =================
// Session Variables
// =================
const ENVIRONMENT = "DECDR_ENVIRONMENT";
const ACTIVE_SESSION = "DECDR_ACTIVE_SESSION";
const USER_ID = "DECDR_USER_ID";
const USER_SERIAL = "DECDR_USER_SERIAL";
const USER_NAME = "DECDR_USER_NAME";
const USER_CLIENT_NAME = "DECDR_USER_CLIENT_NAME";
const USER_EMAIL = "DECDR_USER_EMAIL";
const USER_ROLE = "DECDR_USER_ROLE";
const USER_AUTHENTICATED = "DECDR_USER_AUTHENTICATED";
const REPORTS_GET = "DECDR_REPORTS_GET";
const REPORTS_POST = "DECDR_REPORTS_POST";
const THEME = "DECDR_THEME";
const AJAX = "DECDR_AJAX";
const TODAY = "DECDR_TODAY";
const COPYRIGHT = "DECDR_COPYRIGHT";
const PAGE = "DECDR_PAGE";
const PAGINATION_PAGE = "DECDR_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_CLIENT_NAME"] = $_SESSION[self::USER_CLIENT_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() {
$Settings = $this->getSettings();
if ($Settings->Environment == 'Production') {
$host = 'localhost';
} else {
$host = '192.168.1.190';
}
try {
$database = (string) $Settings->DatabaseName;
$user = (string) $Settings->DatabaseUser;
$password = (string) $Settings->DatabasePassword;
$connection = new PDO("mysql:host={$host};dbname={$database};charset=utf8", $user, $password);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException | Exception $e) {
trigger_error($e->getMessage());
}
return $connection;
}
// ===============
// 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();
}
// =====================
// Display a Notice Page
// =====================
public function displayNotice($messgae = "") {
$XSLParms["MESSAGE"] = $messgae;
$content = $this->applyXSL("", $this->getXSL("notice"), $XSLParms);
$this->displayContent($content);
exit();
}
// ======================================================
// Custom error handler to display informative error page
// ======================================================
public function displayError($error_number = "", $error_message = "", $error_file = "", $error_line = "") {
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 the Home Page
// =====================
public function displayHome() {
(new Subscriptions())->usersSubscriptions();
}
// =======================
// 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 Users())->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_orig($SQL = "") {
if (empty($SQL)) {
return false;
}
$recordSet = $this->connect()->query($SQL);
return $recordSet;
}
// =======================================
// Return Table Data as a SimpleXMLElement
// =======================================
public function getTable_orig($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 a Recordset
// ==================
public function getRecordset($SQL = "", $params = array()) {
if (empty($SQL)) {
return false;
}
$statement = $this->connect()->prepare($SQL);
foreach ($params as $key => $value) {
$parameter = is_int($key) ? $key + 1 : ":" . ltrim($key, ":");
if (is_int($value)) {
$type = PDO::PARAM_INT;
} elseif (is_bool($value)) {
$type = PDO::PARAM_BOOL;
} elseif (is_null($value)) {
$type = PDO::PARAM_NULL;
} else {
$type = PDO::PARAM_STR;
}
$statement->bindValue($parameter, $value, $type);
}
$statement->execute();
return $statement;
}
// =======================================
// Return Table Data as a SimpleXMLElement
// =======================================
public function getTable($table = "", $SQL = "", $params = array()) {
if (empty($table)) {
return new SimpleXMLElement("<unknown/>");
}
$SXE = new SimpleXMLElement("<{$table}/>");
$recordset = $this->getRecordset(empty($SQL) ? "select * from {$table}" : $SQL, $params);
if ($recordset) {
while ($row = $recordset->fetch(PDO::FETCH_ASSOC)) {
$record = $SXE->addChild("record");
foreach ($row as $name => $value) {
$record->$name = (string) $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_CLIENT_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() {
$SQL = "select count(*) as notify
from view_exportjobs
where view_exportjobs.exportjob_creator = 19
and view_exportjobs.exportjob_status = 'complete'
and view_exportjobs.exportjob_notified = 0";
$exportjobs = $this->getTable("exportjobs", $SQL);
$this->debug($exportjobs->asXML());
}
// =======================
// Format Raw Phone Number
// =======================
public function formatPhoneNumber(string $phonenumber): string {
// Remove everything except digits
$digits = preg_replace('/\D+/', '', $phonenumber);
// Handle leading country code (US)
if (strlen($digits) === 11 && str_starts_with($digits, '1')) {
$digits = substr($digits, 1);
}
// // Must be exactly 10 digits to format
// if (strlen($digits) !== 10) {
// return $phone; // return original if invalid
// }
return substr($digits, 0, 3) . '-' .
substr($digits, 3, 3) . '-' .
substr($digits, 6, 4);
}
// =====================
// Forgot/Reset Password
// =====================
public function resetpassword() {
include_once 'classes/Authentication.php';
$reset = (new Authentication())->resetPassword() ? true : false;
$XSLParms["BTN_SUBMIT"] = "main.php?action=Users.signIn&step=authenticate";
$XSLParms["RESET_PASSWORD_SUCCESSFUL"] = "TRUE";
echo $this->applyXSL("", $this->getXSL("signIn"), $XSLParms);
die();
}
}
?>
+554
View File
@@ -0,0 +1,554 @@
<?php
class BusinessFacts 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;
}
// =====================
// Search Business Facts
// =====================
public function searchBusinessFacts() {
$subscription_serial = $_SESSION['subscription_serial'];
$usersubscription_serial = $_SESSION['usersubscription_serial'];
$subscription = (new Subscriptions())->getSubscription($subscription_serial);
if ($subscription->count() === 0) {
$this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
}
$userssubscription = (new Users())->getUserSubscription($usersubscription_serial);
$user_subscription_start_date = $userssubscription->record->usersubscription_start_date;
$user_subscription_end_date = $userssubscription->record->usersubscription_end_date;
$searchhistory = (new SearchHistory())->getUsersPreviousSearchParameters($this->current_user_serial, $subscription_serial);
// Update Search History Record
if (empty($searchhistory)) {
(new SearchHistory())->saveUserSearchParameters($_POST);
} else {
(new SearchHistory())->updateUserSearchParameters($_POST);
}
$businessfacts = $this->getBusinessFactsPage($user_subscription_start_date, $user_subscription_end_date,);
$searchhistory = (new SearchHistory())->getUsersPreviousSearchParameters($this->current_user_serial, $subscription_serial);
// Populate Entry Dates with what was searched for if provided or users entry dates if no entry dates were provided
$searchhistory->record->searchhistory_parameters->businessfact_entry_date_from = $businessfacts->record->businessfact_entry_date_from;
$searchhistory->record->searchhistory_parameters->businessfact_entry_date_to = $businessfacts->record->businessfact_entry_date_to;
$popovers = (new Popovers())->getPopovers();
$dropdowns = (new Dropdowns())->getDropdowns();
$siccodes = (new SICCodes())->getSICCodes();
$cities = (new Cities())->getSubscriptionCities($subscription_serial);
$counties = (new Counties())->getSubscriptionCounties($subscription_serial);
$availablerecordcount = $this->userTotalAvailableRecordCount($user_subscription_start_date, $user_subscription_end_date);
$XML = $this->mergeXML($businessfacts, "<XML/>");
$XML = $this->mergeXML($subscription, $XML);
$XML = $this->mergeXML($popovers, $XML);
$XML = $this->mergeXML($dropdowns, $XML);
$XML = $this->mergeXML($cities, $XML);
$XML = $this->mergeXML($counties, $XML);
$XML = $this->mergeXML($siccodes, $XML);
$XML = $this->mergeXML($searchhistory, $XML);
$XML = $this->mergeXML($availablerecordcount, $XML);
$content = $this->applyXSL($XML, $this->getXSL("searchBusinessFacts"));
$this->displayContent($content);
}
// ===================================
// Return a Business Facts Page Object
// ===================================
public function getBusinessFactsPage($user_subscription_start_date, $user_subscription_end_date) {
// Pagination settings
$pagination = filter_input(INPUT_POST, "pagination") ?: "";
$this->pagination_size = filter_input(INPUT_POST, "businessfacts_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
// Connect to DB
$connection = $this->connect();
$filters = $this->buildBusinessFactsFilters($user_subscription_start_date, $user_subscription_end_date);
// Record Count
$SQL = "select count(*) as count
from view_businessfacts
{$filters['where']}";
$statement = $connection->prepare($SQL);
$this->bindBusinessFactsParams($statement, $filters['params']);
$statement->execute();
$recordset = $statement->fetch(PDO::FETCH_ASSOC);
$count = $recordset ? (int) $recordset["count"] : 0;
// === PAGINATION LOGIC ===
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 = min($this->pagination_page + 1, ceil($count / $this->pagination_size));
break;
case "last": $this->pagination_page = (int) ceil($count / $this->pagination_size);
break;
}
$offset = max(0, ($this->pagination_page - 1) * $this->pagination_size);
$start = $offset + 1;
$end = min($count, $start + $this->pagination_size - 1);
// === DATA QUERY ===
$SQL = "select view_businessfacts.*
from view_businessfacts
{$filters['where']}";
if ($pagination !== 'off') {
$SQL .= " limit :limit
offset :offset";
}
// echo $SQL;
// die();
$statement = $connection->prepare($SQL);
$this->bindBusinessFactsParams($statement, $filters['params']);
if ($pagination !== 'off') {
$statement->bindValue(":limit", $this->pagination_size, PDO::PARAM_INT);
$statement->bindValue(":offset", $offset, PDO::PARAM_INT);
}
$statement->execute();
$businessfacts = $this->getTableXML("businessfacts", $statement);
// Add searched entry_dates for search history
$businessfacts->record->businessfact_entry_date_from = !empty($filters['entry_from']) ? date('m/d/Y', strtotime($filters['entry_from'])) : date('m/d/Y', strtotime($filters['subscription_start']));
$businessfacts->record->businessfact_entry_date_to = !empty($filters['entry_to']) ? date('m/d/Y', strtotime($filters['entry_to'])) : date('m/d/Y', strtotime($filters['subscription_end']));
// Insert Pagination Attributes
$businessfacts->addAttribute("count", $count);
$businessfacts->addAttribute("start", $start);
$businessfacts->addAttribute("end", $end);
$businessfacts->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $businessfacts;
}
private function buildBusinessFactsFilters($user_subscription_start_date, $user_subscription_end_date) {
$businessfact_company = trim((string) filter_input(INPUT_POST, "businessfact_company")) ?: "";
$businessfact_zip = trim((string) filter_input(INPUT_POST, "businessfact_zip")) ?: "";
$businessfact_home_based_business = trim((string) filter_input(INPUT_POST, "businessfact_home_based_business")) ?: "";
$businessfact_employee_count_from = trim((string) filter_input(INPUT_POST, "businessfact_employee_count_from")) ?: "";
$businessfact_employee_count_to = trim((string) filter_input(INPUT_POST, "businessfact_employee_count_to")) ?: "";
$businessfact_entry_date_from = trim((string) filter_input(INPUT_POST, "businessfact_entry_date_from")) ?: "";
$businessfact_entry_date_to = trim((string) filter_input(INPUT_POST, "businessfact_entry_date_to")) ?: "";
$businessfact_lease_end_from = trim((string) filter_input(INPUT_POST, "businessfact_lease_end_from")) ?: "";
$businessfact_lease_end_to = trim((string) filter_input(INPUT_POST, "businessfact_lease_end_to")) ?: "";
// Determine real date range based upon users subscription start date
$oneYearAgo = date('Y-m-d', strtotime('-1 year'));
if ($user_subscription_start_date <= $oneYearAgo) {
$user_subscription_start_date = $oneYearAgo;
}
if ($user_subscription_end_date < $user_subscription_start_date) {
$this->displayNotice("Your authorized access period is invalid (end date is before start date).");
return;
}
$entryFrom = $this->normalizeBusinessFactsDate($businessfact_entry_date_from);
$entryTo = $this->normalizeBusinessFactsDate($businessfact_entry_date_to);
$leaseEndFrom = $this->normalizeBusinessFactsDate($businessfact_lease_end_from);
$leaseEndTo = $this->normalizeBusinessFactsDate($businessfact_lease_end_to);
$clauses = [];
$params = [];
$clauses[] = "view_businessfacts.businessfact_entry_date BETWEEN :subscription_start AND :subscription_end";
$params[':subscription_start'] = $user_subscription_start_date;
$params[':subscription_end'] = $user_subscription_end_date;
$allowedCountyIds = $this->getBusinessFactsSubscriptionCountyIds();
$requestedCountyIds = $this->getBusinessFactsPostIds("businessfact_county");
$countyIds = $requestedCountyIds ? array_values(array_intersect($requestedCountyIds, $allowedCountyIds)) : $allowedCountyIds;
$this->addBusinessFactsInClause($clauses, $params, "view_businessfacts.businessfact_county", $countyIds, "county_");
if ($businessfact_company !== '') {
$clauses[] = "view_businessfacts.businessfact_company REGEXP :businessfact_company";
$params[':businessfact_company'] = $businessfact_company;
}
if ($businessfact_zip !== '') {
$clauses[] = "view_businessfacts.businessfact_zip REGEXP :businessfact_zip";
$params[':businessfact_zip'] = $businessfact_zip;
}
$this->addBusinessFactsInClause($clauses, $params, "view_businessfacts.businessfact_city", $this->getBusinessFactsPostIds("businessfact_city"), "city_");
$this->addBusinessFactsInClause($clauses, $params, "view_businessfacts.businessfact_business_class", $this->getBusinessFactsPostIds("businessfact_business_class"), "class_");
$this->addBusinessFactsInClause($clauses, $params, "view_businessfacts.businessfact_action", $this->getBusinessFactsPostIds("businessfact_action"), "action_");
$this->addBusinessFactsInClause($clauses, $params, "view_businessfacts.businessfact_sic_code", $this->getBusinessFactsPostValues("businessfact_sic_code"), "sic_");
if ($businessfact_home_based_business === 'Y' || $businessfact_home_based_business === 'N') {
$clauses[] = "view_businessfacts.businessfact_home_based_business = :businessfact_home_based_business";
$params[':businessfact_home_based_business'] = $businessfact_home_based_business;
}
if ($businessfact_employee_count_from !== '' && ctype_digit($businessfact_employee_count_from)) {
$businessfact_employee_count_from = (int) $businessfact_employee_count_from;
} else {
$businessfact_employee_count_from = null;
}
if ($businessfact_employee_count_to !== '' && ctype_digit($businessfact_employee_count_to)) {
$businessfact_employee_count_to = (int) $businessfact_employee_count_to;
} else {
$businessfact_employee_count_to = null;
}
if ($businessfact_employee_count_from !== null && $businessfact_employee_count_to !== null) {
if ($businessfact_employee_count_from > $businessfact_employee_count_to) {
$tmp = $businessfact_employee_count_from;
$businessfact_employee_count_from = $businessfact_employee_count_to;
$businessfact_employee_count_to = $tmp;
}
$clauses[] = "view_businessfacts.businessfact_employee_count BETWEEN :employee_count_from AND :employee_count_to";
$params[':employee_count_from'] = $businessfact_employee_count_from;
$params[':employee_count_to'] = $businessfact_employee_count_to;
} elseif ($businessfact_employee_count_from !== null) {
$clauses[] = "view_businessfacts.businessfact_employee_count = :employee_count";
$params[':employee_count'] = $businessfact_employee_count_from;
} elseif ($businessfact_employee_count_to !== null) {
$clauses[] = "view_businessfacts.businessfact_employee_count = :employee_count";
$params[':employee_count'] = $businessfact_employee_count_to;
}
if ($entryFrom !== null || $entryTo !== null) {
if ($entryFrom !== null && $entryTo === null) {
$entryTo = $entryFrom;
}
if ($entryTo !== null && $entryFrom === null) {
$entryFrom = $entryTo;
}
if ($entryFrom > $entryTo) {
$tmp = $entryFrom;
$entryFrom = $entryTo;
$entryTo = $tmp;
}
if ($entryFrom < $user_subscription_start_date || $entryTo > $user_subscription_end_date) {
$this->displayNotice("The Entry date or date range {$this->current_user_name} selected is outside your authorized access period.");
return;
}
$clauses[] = "view_businessfacts.businessfact_entry_date BETWEEN :entry_from AND :entry_to";
$params[':entry_from'] = $entryFrom;
$params[':entry_to'] = $entryTo;
}
if ((string) ($_SESSION['subscription_serial'] ?? '') === '10' && ($leaseEndFrom !== null || $leaseEndTo !== null)) {
if ($leaseEndFrom !== null && $leaseEndTo === null) {
$leaseEndTo = $leaseEndFrom;
}
if ($leaseEndTo !== null && $leaseEndFrom === null) {
$leaseEndFrom = $leaseEndTo;
}
if ($leaseEndFrom > $leaseEndTo) {
$tmp = $leaseEndFrom;
$leaseEndFrom = $leaseEndTo;
$leaseEndTo = $tmp;
}
$clauses[] = "view_businessfacts.businessfact_lease_end BETWEEN :lease_end_from AND :lease_end_to";
$params[':lease_end_from'] = $leaseEndFrom;
$params[':lease_end_to'] = $leaseEndTo;
}
return [
'where' => "where " . implode(" and ", $clauses),
'params' => $params,
'entry_from' => $entryFrom,
'entry_to' => $entryTo,
'subscription_start' => $user_subscription_start_date,
'subscription_end' => $user_subscription_end_date,
];
}
private function getBusinessFactsSubscriptionCountyIds() {
$counties = (new Counties())->getSubscriptionCounties($_SESSION['subscription_serial']);
$countyIds = [];
foreach ($counties as $county) {
$countyId = trim((string) $county->subscriptioncounty_county);
if (ctype_digit($countyId)) {
$countyIds[] = (int) $countyId;
}
}
return array_values(array_unique($countyIds));
}
private function getBusinessFactsPostIds($name) {
$values = $this->getBusinessFactsPostValues($name);
$ids = [];
foreach ($values as $value) {
if (ctype_digit((string) $value)) {
$ids[] = (int) $value;
}
}
return array_values(array_unique($ids));
}
private function getBusinessFactsPostValues($name) {
$value = $_POST[$name] ?? $_POST[$name . "_"] ?? "";
if (is_array($value)) {
$values = $value;
} else {
$values = explode(',', (string) $value);
}
$clean = [];
foreach ($values as $item) {
$item = trim((string) $item);
if ($item !== '' && preg_match('/^[A-Za-z0-9_-]+$/', $item)) {
$clean[] = $item;
}
}
return array_values(array_unique($clean));
}
private function addBusinessFactsInClause(&$clauses, &$params, $field, $values, $paramPrefix) {
if (!$values) {
if ($field === "view_businessfacts.businessfact_county") {
$clauses[] = "1 = 0";
}
return;
}
$placeholders = [];
foreach ($values as $index => $value) {
$placeholder = ":{$paramPrefix}{$index}";
$placeholders[] = $placeholder;
$params[$placeholder] = $value;
}
$clauses[] = "{$field} IN (" . implode(',', $placeholders) . ")";
}
private function bindBusinessFactsParams($statement, $params) {
foreach ($params as $name => $value) {
$type = is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR;
$statement->bindValue($name, $value, $type);
}
}
private function normalizeBusinessFactsDate($date) {
if ($date === '') {
return null;
}
$timestamp = strtotime($date);
return $timestamp === false ? null : date("Y-m-d", $timestamp);
}
// ==================================
// Users Total Available Record Count
// ==================================
public function userTotalAvailableRecordCount($user_subscription_start_date, $user_subscription_end_date) {
// determine real date range based upon users subscription start date
if ($user_subscription_start_date <= date('Y-m-d', strtotime('-1 year'))) {
$user_subscription_start_date = date('Y-m-d', strtotime('-1 year'));
}
$clauses = [
"view_businessfacts.businessfact_entry_date between :subscription_start and :subscription_end",
];
$params = [
':subscription_start' => $user_subscription_start_date,
':subscription_end' => $user_subscription_end_date,
];
$this->addBusinessFactsInClause($clauses, $params, "view_businessfacts.businessfact_county", $this->getBusinessFactsSubscriptionCountyIds(), "county_");
$SQL = "select count(*) as count
from view_businessfacts
where " . implode(" and ", $clauses);
$statement = $this->connect()->prepare($SQL);
$this->bindBusinessFactsParams($statement, $params);
$statement->execute();
return $this->getTableXML("userstotalavailablerecords", $statement);
}
// =====================
// Search Business Facts
// =====================
public function businessFactsBasic() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$dateranges = $this->getDateRangeXML();
$content = $this->applyXSL($dateranges, $this->getXSL("businessFactsBasic"));
$this->displayContent($content);
break;
case "results":
$week_start_raw = trim((string) filter_input(INPUT_POST, 'week_start'));
$week_end_raw = trim((string) filter_input(INPUT_POST, 'week_end'));
$week_start_db = $week_start_raw !== '' ? date('Y-m-d', strtotime($week_start_raw)) : null;
$week_end_db = $week_end_raw !== '' ? date('Y-m-d', strtotime($week_end_raw)) : null;
$businessfacts = $this->getBusinessFactsBasic($week_start_db, $week_end_db);
$dateranges = $this->getDateRangeXML();
$searched = $dateranges->addChild('searchedranges');
$searched->addChild('week_start', $week_start_db ? date('m/d/Y', strtotime($week_start_db)) : '');
$searched->addChild('week_end', $week_end_db ? date('m/d/Y', strtotime($week_end_db)) : '');
$xml = $this->mergeXML($businessfacts, '<XML/>');
$xml = $this->mergeXML($dateranges, $xml);
$content = $this->applyXSL($xml, $this->getXSL("businessFactsBasic"));
$this->displayContent($content);
break;
default:
$this->displayHome();
}
}
public function getDateRangeXML() {
$ranges = $this->getFridayThursdayRanges(2, new DateTimeImmutable('today'));
$xml = new SimpleXMLElement('<ranges/>');
$labels = [
0 => 'week_prior',
1 => 'two_weeks_prior',
];
foreach ($ranges as $i => $range) {
$name = $labels[$i] ?? 'prior_' . ($i + 1);
$node = $xml->addChild($name);
$start = date('m/d/Y', strtotime($range['start']));
$end = date('m/d/Y', strtotime($range['end']));
$node->addChild('start', $start);
$node->addChild('end', $end);
}
$xml->subscription_serial = $_SESSION['subscription_serial'];
return $xml;
}
public function getFridayThursdayRanges(int $weeks = 2, ?DateTimeInterface $today = null): array {
$today = $today ? DateTimeImmutable::createFromInterface($today) : new DateTimeImmutable('today');
// "last thursday" gives the most recent Thursday strictly before today.
// If today IS Thursday, we want today as the end date.
$end = ($today->format('N') === '4') ? $today : $today->modify('last thursday');
$ranges = [];
for ($i = 0; $i < $weeks; $i++) {
$start = $end->modify('-6 days');
$ranges[] = [
'start' => $start->format('Y-m-d'),
'end' => $end->format('Y-m-d'),
];
$end = $start->modify('-1 day'); // move to previous block
}
return $ranges;
}
// ===============================
// Return an Business Facts Object
// ===============================
public function getBusinessFactsBasic($week_start, $week_end) {
$SQL = "select view_businessfacts.*
from view_businessfacts
where view_businessfacts.businessfact_entry_date between '{$week_start}' and '{$week_end}'
order by view_businessfacts.businessfact_county_name_verbose, view_businessfacts.businessfact_zip, view_businessfacts.businessfact_company";
return $this->getTable("businessfacts", $SQL);
}
}
?>
+393
View File
@@ -0,0 +1,393 @@
<?php
class Cities 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 City
// ========
public function addCity() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$constants = $this->getConstants();
$content = $this->applyXSL($constants, $this->getXSL("addCity"));
$this->displayContent($content);
break;
case "add":
$city_name = filter_input(INPUT_POST, "city_name") ?: "";
$SQL = "insert into cities
( city_name,
city_creator,
city_created )
VALUES ( :city_name,
:city_creator,
:city_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":city_name", $city_name);
$statement->bindValue(":city_creator", $this->current_user_name);
$statement->bindValue(":city_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// =============
// Delete City
// =============
public function deleteCity() {
$city_serial = filter_input(INPUT_POST, "city_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$city = $this->getCity($city_serial);
if ($city->count() == 0) {
$this->logError("Invalid City ({$city_serial}). " . __METHOD__);
}
$SQL = "delete from cities
where city_serial = {$city_serial}";
$this->executeSQL($SQL);
}
// ============================
// Determine if a City exists
// ============================
public function cityExists() {
$city_serial = filter_input(INPUT_POST, "city_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$city_name = filter_input(INPUT_POST, "city_name") ?: "";
$SQL = "select city_serial
from view_cities
where city_serial != :city_serial
and lower(city_name) = :city_name";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":city_serial", $city_serial);
$statement->bindValue(":city_name", strtolower($city_name));
$statement->execute();
$recordset = $statement->fetchAll(PDO::FETCH_ASSOC);
$exists = (count($recordset) > 0) ? true : false;
echo json_encode($exists);
}
// ======================================
// Determine if a City is Active (AJAX)
// ======================================
public function cityActive() {
$rdi_city = filter_input(INPUT_POST, "rdi_city") ?: "";
$active = false;
$SQL = "select rdi_city
from rdis
where rdi_city = {$rdi_city}
limit 1";
$workorders = $this->getTable("city", $SQL);
$active = ($workorders->count() > 0) ? true : false;
echo json_encode($active);
}
// =============
// Edit a City
// =============
public function editCity() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$city_serial = filter_input(INPUT_POST, "city_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$city = $this->getCity($city_serial);
if ($city->count() == 0) {
$this->logError("Invalid City ({$city_serial}). " . __METHOD__);
}
$constants = $this->getConstants();
$XML = $this->mergeXML($city, "<XML/>");
$XML = $this->mergeXML($constants, $XML);
$content = $this->applyXSL($XML, $this->getXSL("editCity"));
$this->displayContent($content);
break;
case "update":
$city_serial = filter_input(INPUT_POST, "city_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$city_name = filter_input(INPUT_POST, "city_name") ?: "";
// Verify the City
$city = $this->getCity($city_serial);
if ($city->count() == 0) {
$this->logError("Invalid City ({$city_serial}). " . __METHOD__);
}
$SQL = "update cities
set city_name = :city_name,
city_creator = :city_creator,
city_created = :city_created
where city_serial = :city_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":city_serial", $city_serial);
$statement->bindValue(":city_name", $city_name);
$statement->bindValue(":city_creator", $this->current_user_name);
$statement->bindValue(":city_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ================================
// Return an Active Cities Object
// ================================
public function getActiveCities() {
$SQL = "select view_cities.*
from view_cities
where city_active is true";
return $this->getTable("cities", $SQL);
}
// =======================
// Return an City Object
// =======================
public function getCity($city_serial = 0) {
$SQL = "select view_cities.*
from view_cities
where city_serial = {$city_serial}";
return $this->getTable("cities", $SQL);
}
// ========================
// Return a Cities Object
// ========================
public function getCities() {
$SQL = "select view_cities.*
from view_cities";
return $this->getTable("cities", $SQL);
}
// ========================
// Return a Cities Object
// ========================
public function getCitiesByArea($area) {
$SQL = "select view_cities.*
from view_cities
where view_cities.city_area = '{$area}'";
return $this->getTable("cities", $SQL);
}
// ========================
// Return a Cities Object
// ========================
public function getCitiesByName($city_name) {
$SQL = "select view_cities.*
from view_cities
where view_cities.city_name = '{$city_name}'";
return $this->getTable("cities", $SQL);
}
// =============================
// Return a Cities Page Object
// =============================
public function getCitiesPage() {
// Find Criteria
$find_city = filter_input(INPUT_POST, "find_city") ?: "";
$find_city = $this->sanitizeString($find_city);
$find_words = implode("|", explode(" ", $find_city));
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_cities
where city_name regexp :city_name";
$statement = $connection->prepare($SQL);
$statement->bindValue(":city_name", $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_cities.*
from view_cities
where city_name regexp :city_name
order by city_name
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":city_name", $find_words);
$statement->execute();
$cities = $this->getTableXML("cities", $statement);
// Insert Pagination Attributes
$cities->addAttribute("count", $count);
$cities->addAttribute("start", $start);
$cities->addAttribute("end", $end);
$cities->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $cities;
}
// ==============
// Setup Cities
// ==============
public function setupCities() {
$cities = $this->getCitiesPage();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($cities, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$content = $this->applyXSL($XML, $this->getXSL("setupCities"));
$this->displayContent($content);
}
// ======================
// Return a Cities Object
// ======================
public function getSubscriptionCities($subscription_serial) {
$SQL = "select view_subscriptioncities.*
from view_subscriptioncities
where view_subscriptioncities.subscriptioncity_subscription = '{$subscription_serial}'";
return $this->getTable("subscriptioncities", $SQL);
}
}
?>
+396
View File
@@ -0,0 +1,396 @@
<?php
class Counties 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 County
// ==========
public function addCounty() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$constants = $this->getConstants();
$content = $this->applyXSL($constants, $this->getXSL("addCounty"));
$this->displayContent($content);
break;
case "add":
$county_name = filter_input(INPUT_POST, "county_name") ?: "";
$SQL = "insert into counties
( county_name,
county_creator,
county_created )
VALUES ( :county_name,
:county_creator,
:county_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":county_name", $county_name);
$statement->bindValue(":county_creator", $this->current_user_name);
$statement->bindValue(":county_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// =============
// Delete County
// =============
public function deleteCounty() {
$county_serial = filter_input(INPUT_POST, "county_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$county = $this->getCounty($county_serial);
if ($county->count() == 0) {
$this->logError("Invalid County ({$county_serial}). " . __METHOD__);
}
$SQL = "delete from counties
where county_serial = {$county_serial}";
$this->executeSQL($SQL);
}
// ============================
// Determine if a County exists
// ============================
public function countyExists() {
$county_serial = filter_input(INPUT_POST, "county_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$county_name = filter_input(INPUT_POST, "county_name") ?: "";
$SQL = "select county_serial
from view_counties
where county_serial != :county_serial
and lower(county_name) = :county_name";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":county_serial", $county_serial);
$statement->bindValue(":county_name", strtolower($county_name));
$statement->execute();
$recordset = $statement->fetchAll(PDO::FETCH_ASSOC);
$exists = (count($recordset) > 0) ? true : false;
echo json_encode($exists);
}
// ======================================
// Determine if a County is Active (AJAX)
// ======================================
public function countyActive() {
$rdi_county = filter_input(INPUT_POST, "rdi_county") ?: "";
$active = false;
$SQL = "select rdi_county
from rdis
where rdi_county = {$rdi_county}
limit 1";
$workorders = $this->getTable("county", $SQL);
$active = ($workorders->count() > 0) ? true : false;
echo json_encode($active);
}
// =============
// Edit a County
// =============
public function editCounty() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$county_serial = filter_input(INPUT_POST, "county_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$county = $this->getCounty($county_serial);
if ($county->count() == 0) {
$this->logError("Invalid County ({$county_serial}). " . __METHOD__);
}
$constants = $this->getConstants();
$XML = $this->mergeXML($county, "<XML/>");
$XML = $this->mergeXML($constants, $XML);
$content = $this->applyXSL($XML, $this->getXSL("editCounty"));
$this->displayContent($content);
break;
case "update":
$county_serial = filter_input(INPUT_POST, "county_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$county_name = filter_input(INPUT_POST, "county_name") ?: "";
$county_area = filter_input(INPUT_POST, "county_area") ?: "";
// Verify the County
$county = $this->getCounty($county_serial);
if ($county->count() == 0) {
$this->logError("Invalid County ({$county_serial}). " . __METHOD__);
}
$SQL = "update counties
set county_name = :county_name,
county_area = :county_area,
county_creator = :county_creator,
county_created = :county_created
where county_serial = :county_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":county_serial", $county_serial);
$statement->bindValue(":county_name", $county_name);
$statement->bindValue(":county_area", $county_area);
$statement->bindValue(":county_creator", $this->current_user_name);
$statement->bindValue(":county_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ================================
// Return an Active Counties Object
// ================================
public function getActiveCounties() {
$SQL = "select view_counties.*
from view_counties
where county_active is true";
return $this->getTable("counties", $SQL);
}
// =======================
// Return an County Object
// =======================
public function getCounty($county_serial = 0) {
$SQL = "select view_counties.*
from view_counties
where county_serial = {$county_serial}";
return $this->getTable("counties", $SQL);
}
// ========================
// Return a Counties Object
// ========================
public function getCounties() {
$SQL = "select view_counties.*
from view_counties";
return $this->getTable("counties", $SQL);
}
// ========================
// Return a Counties Object
// ========================
public function getCountiesByArea($area) {
$SQL = "select view_counties.*
from view_counties
where view_counties.county_area = '{$area}'";
return $this->getTable("counties", $SQL);
}
// ========================
// Return a Counties Object
// ========================
public function getCountiesByName($county_name) {
$SQL = "select view_counties.*
from view_counties
where view_counties.county_name = '{$county_name}'";
return $this->getTable("counties", $SQL);
}
// =============================
// Return a Counties Page Object
// =============================
public function getCountiesPage() {
// Find Criteria
$find_county = filter_input(INPUT_POST, "find_county") ?: "";
$find_county = $this->sanitizeString($find_county);
$find_words = implode("|", explode(" ", $find_county));
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_counties
where county_name regexp :county_name";
$statement = $connection->prepare($SQL);
$statement->bindValue(":county_name", $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_counties.*
from view_counties
where county_name regexp :county_name
order by county_name
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":county_name", $find_words);
$statement->execute();
$counties = $this->getTableXML("counties", $statement);
// Insert Pagination Attributes
$counties->addAttribute("count", $count);
$counties->addAttribute("start", $start);
$counties->addAttribute("end", $end);
$counties->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $counties;
}
// ==============
// Setup Counties
// ==============
public function setupCounties() {
$counties = $this->getCountiesPage();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($counties, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$content = $this->applyXSL($XML, $this->getXSL("setupCounties"));
$this->displayContent($content);
}
// ========================
// Return a Counties Object
// ========================
public function getSubscriptionCounties($subscription_serial) {
$SQL = "select view_subscriptioncounties.*
from view_subscriptioncounties
where view_subscriptioncounties.subscriptioncounty_subscription = '{$subscription_serial}'";
return $this->getTable("subscriptioncounties", $SQL);
}
}
?>
+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);
}
}
?>
+255
View File
@@ -0,0 +1,255 @@
<?php
// ============
// Export Class
// ============
class Export 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;
}
// =====================
// Create Export Request
// =====================
public function createExportRequest() {
$subscription_serial = filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription = (new Subscriptions())->getSubscription($subscription_serial);
if ($subscription->count() === 0) {
$this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
}
$export_type = filter_input(INPUT_POST, "export_type") ?: "";
$report_type = filter_input(INPUT_POST, "report_type") ?: "";
$exportjob_export_type = str_replace(' ', '', $subscription->record->subscription_full_title) . "$export_type";
$exportjob_file_name = str_replace(' ', '_', $subscription->record->subscription_full_title) . "_all_records.{$report_type}";
// $exportjob_file_name = str_replace('&', 'And', $subscription->record->subscription_full_title) . "_all_records.{$report_type}";
$SQL = "insert into exportjobs
( exportjob_subscription,
exportjob_export_type,
exportjob_file_name,
exportjob_file_type,
exportjob_creator,
exportjob_created )
VALUES ( :exportjob_subscription,
:exportjob_export_type,
:exportjob_file_name,
:exportjob_file_type,
:exportjob_creator,
:exportjob_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":exportjob_subscription", $subscription_serial);
$statement->bindValue(":exportjob_export_type", $exportjob_export_type);
$statement->bindValue(":exportjob_file_name", $exportjob_file_name);
$statement->bindValue(":exportjob_file_type", strtoupper($report_type));
$statement->bindValue(":exportjob_creator", $this->current_user_serial);
$statement->bindValue(":exportjob_created", $this->getTimestamp());
$statement->execute();
$this->displayNotice("Your export has been queued. You will receive an notification when it is ready.");
}
// ============
// User Exports
// ============
public function usersExports() {
$exports = $this->getUsersExports();
$popovers = (new Popovers())->getPopovers();
$this->markExportsAsSeen();
$XML = $this->mergeXML($exports, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$html = $this->applyXSL($XML, $this->getXSL("viewExports"));
$this->displayContent($html);
}
// =========================
// Mark User Exports as Seen
// =========================
public function markExportsAsSeen() {
$SQL = "update exportjobs
set exportjob_notified = true
where exportjobs.exportjob_creator = {$this->current_user_serial}";
$statement = $this->connect()->prepare($SQL);
$statement->execute();
}
// =======================
// Return a Exports Object
// =======================
public function getUsersExports() {
// Find Criteria
$find_exportjob = filter_input(INPUT_POST, "find_exportjob") ?: "";
$find_words = $this->sanitizeString($find_exportjob);
// Show Per Page
$this->pagination_size = filter_input(INPUT_POST, "exportjobs_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_exportjobs
where view_exportjobs.exportjob_creator = {$this->current_user_serial}
and view_exportjobs.subscription_full_title regexp :subscription_full_title";
$statement = $connection->prepare($SQL);
$statement->bindValue(":subscription_full_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_exportjobs.*
from view_exportjobs
where view_exportjobs.exportjob_creator = {$this->current_user_serial}
and view_exportjobs.subscription_full_title regexp :subscription_full_title
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":subscription_full_title", $find_words);
$statement->execute();
$exportjobs = $this->getTableXML("exportjobs", $statement);
// Insert Pagination Attributes
$exportjobs->addAttribute("count", $count);
$exportjobs->addAttribute("start", $start);
$exportjobs->addAttribute("end", $end);
$exportjobs->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $exportjobs;
}
// =====================================
// Return if users exports are completed
// =====================================
public function checkUsersCompletedExports_AJAX() {
$SQL = "select count(*) as notify
from view_exportjobs
where view_exportjobs.exportjob_creator = :current_user_serial
and view_exportjobs.exportjob_status = 'complete'
and view_exportjobs.exportjob_notified = 0";
$exportjobs = $this->getTable("exportjobs", $SQL, array('current_user_serial' => $this->current_user_serial));
// Create the User Object.
$users_exports = array();
$users_exports["notify"] = ($exportjobs->record->notify == 0) ? false : true;
if ($_SESSION[self::AJAX]) {
echo json_encode($users_exports);
} else {
return $users_exports;
}
}
// ===============
// Download Export
// ===============
public function downloadExport() {
$export_code = filter_input(INPUT_POST, "export_code") ?: "";
$SQL = "select view_exportjobs.*
from view_exportjobs
where view_exportjobs.exportjob_download_token = :export_code
and view_exportjobs.exportjob_status = 'complete' limit 1";
$exportjob = $this->getTable("exportjob", $SQL, array("export_code" => $export_code));
$file_path = str_replace('../exports/', './exports/', $exportjob->record->exportjob_file_path);
$file_name = $exportjob->record->exportjob_file_name;
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=\"$file_name\"");
readfile($file_path);
}
}
?>
+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();
}
}
?>
+324
View File
@@ -0,0 +1,324 @@
<?php
// ======================
// Migrate Business Facts
// ======================
class Migrate_BusinessFacts {
// Variables
private $log = "";
private $settings = "";
private $olddb_connection = "";
private $newdb_connection = "";
// ==================
// Class Constructor.
// ==================
public function __construct() {
// Open the Log
$this->log = fopen("../scripts/businessfacts.log", "w+");
if ($this->log === false) {
error_log("Business Facts : Unable to open log file");
exit();
}
$this->log(str_repeat("*", 50));
// 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("Business Facts : Unable to initialize settings");
exit();
}
// Open Database Connections
$this->olddb_connection = $this->connect_olddb();
$this->newdb_connection = $this->connect_newdb();
}
// ================================================
// Return a Old DEC-DR Database Database Connection
// ================================================
public function connect_olddb() {
try {
$host = (string) $this->settings->OldDatabaseServer;
$database = (string) $this->settings->OldDatabaseName;
$user = (string) $this->settings->OldDatabaseUser;
$password = (string) $this->settings->OldDatabasePassword;
$connection = new PDO("mysql:host={$host};dbname={$database};charset=utf8", $user, $password);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException | Exception $e) {
trigger_error($e->getMessage());
}
return $connection;
}
// ================================================
// Return a New DEC-DR Database Database Connection
// ================================================
public function connect_newdb() {
try {
$host = (string) $this->settings->DatabaseServer;
$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_EMULATE_PREPARES, false);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException | Exception $e) {
trigger_error($e->getMessage());
}
return $connection;
}
// =============================
// Log a message to the Log File
// =============================
private function log($message = "") {
fwrite($this->log, date("Y-m-d H:i A") . " : " . "{$message} \n");
}
// ===================
// Process Parcel Data
// ===================
public function process() {
$this->log("Starting Migration of Business Facts");
$this->migrateBusinessFacts();
$this->log("Business Facts Migration Process Complete");
}
// ====================
// Migrate Business Facts
// ====================
private function migrateBusinessFacts() {
$this->log("Processing Business Facts");
$businessfacts = $this->getBusinessFacts();
$SQL = "INSERT INTO businessfacts (
businessfact_legacy_id,
businessfact_company,
businessfact_address_one,
businessfact_address_two,
businessfact_city,
businessfact_state,
businessfact_zip,
businessfact_county,
businessfact_phone,
businessfact_fax,
businessfact_email_address,
businessfact_business_class,
businessfact_action,
businessfact_employee_count,
businessfact_inception,
businessfact_sic_code,
businessfact_contact_name,
businessfact_contact_title,
businessfact_license_date,
businessfact_home_based_business,
businessfact_year_established,
businessfact_entry_date,
businessfact_creator,
businessfact_created )
VALUES ( :businessfact_legacy_id,
:businessfact_company,
:businessfact_address_one,
:businessfact_address_two,
:businessfact_city,
:businessfact_state,
:businessfact_zip,
:businessfact_county,
:businessfact_phone,
:businessfact_fax,
:businessfact_email_address,
:businessfact_business_class,
:businessfact_action,
:businessfact_employee_count,
:businessfact_inception,
:businessfact_sic_code,
:businessfact_contact_name,
:businessfact_contact_title,
:businessfact_license_date,
:businessfact_home_based_business,
:businessfact_year_established,
:businessfact_entry_date,
:businessfact_creator,
:businessfact_created )";
$statement = $this->newdb_connection->prepare($SQL);
$counter = 0;
foreach ($businessfacts as $businessfact) {
$businessfact_legacy_id = $businessfact['BizFactsRecordID'] ?? null;
$businessfact_company = $businessfact['Company'] ?? null;
$businessfact_address_one = $businessfact['Address1'] ?? null;
$businessfact_address_two = $businessfact['Address2'] ?? null;
$businessfact_city = $this->getCityByCityName($businessfact['City']) ?? null;
$businessfact_state = $businessfact['State'] ?? null;
$businessfact_zip = $businessfact['Zip'] ?? null;
$businessfact_county = $this->getCountyByCountyName($businessfact['County']) ?? null;
$businessfact_phone = $this->normailizePhoneNumber($businessfact['Phone']) ?? null;
$businessfact_fax = $this->normailizePhoneNumber($businessfact['Fax']) ?? null;
$businessfact_email_address = $this->normailizeEmailAddress($businessfact['EmailAddress']) ?? null;
$businessfact_business_class = $this->getDropdownSerialByValue($businessfact['BC']) ?? null;
$businessfact_action = $this->getDropdownSerialByValue($businessfact['Description']) ?? null;
$businessfact_employee_count = $businessfact['ES'] ?? null;
$businessfact_inception = $businessfact['BizInception'] ?? null;
$businessfact_sic_code = $businessfact['SIC'] ?? null;
$businessfact_contact_name = $businessfact['ContactName'] ?? null;
$businessfact_contact_title = $businessfact['Title'] ?? null;
$businessfact_license_date = $businessfact['LicenseDate'] ?? null;
$businessfact_home_based_business = $businessfact['Home'] ?? null;
$businessfact_year_established = $businessfact['YearEst'] ?? null;
$businessfact_entry_date = $businessfact['EntryDate'] ?? null;
$statement->bindValue(':businessfact_legacy_id', $businessfact_legacy_id, PDO::PARAM_INT);
$statement->bindValue(':businessfact_company', $businessfact_company, PDO::PARAM_STR);
$statement->bindValue(':businessfact_address_one', $businessfact_address_one, PDO::PARAM_STR);
$statement->bindValue(':businessfact_address_two', $businessfact_address_two, PDO::PARAM_STR);
$statement->bindValue(':businessfact_city', $businessfact_city, PDO::PARAM_INT);
$statement->bindValue(':businessfact_state', $businessfact_state, PDO::PARAM_STR);
$statement->bindValue(':businessfact_zip', $businessfact_zip, PDO::PARAM_STR);
$statement->bindValue(':businessfact_county', $businessfact_county, PDO::PARAM_INT);
$statement->bindValue(':businessfact_phone', $businessfact_phone, PDO::PARAM_STR);
$statement->bindValue(':businessfact_fax', $businessfact_fax, PDO::PARAM_STR);
$statement->bindValue(':businessfact_email_address', $businessfact_email_address, PDO::PARAM_STR);
$statement->bindValue(':businessfact_business_class', $businessfact_business_class, PDO::PARAM_INT);
$statement->bindValue(':businessfact_action', $businessfact_action, PDO::PARAM_INT);
$statement->bindValue(':businessfact_employee_count', $businessfact_employee_count, PDO::PARAM_STR);
$statement->bindValue(':businessfact_inception', $businessfact_inception, PDO::PARAM_STR);
$statement->bindValue(':businessfact_sic_code', $businessfact_sic_code, PDO::PARAM_STR);
$statement->bindValue(':businessfact_contact_name', $businessfact_contact_name, PDO::PARAM_STR);
$statement->bindValue(':businessfact_contact_title', $businessfact_contact_title, PDO::PARAM_STR);
$statement->bindValue(':businessfact_license_date', $businessfact_license_date, PDO::PARAM_STR);
$statement->bindValue(':businessfact_home_based_business', $businessfact_home_based_business, PDO::PARAM_INT);
$statement->bindValue(':businessfact_year_established', $businessfact_year_established, PDO::PARAM_STR);
$statement->bindValue(':businessfact_entry_date', $businessfact_entry_date, PDO::PARAM_STR);
$statement->bindValue(':businessfact_creator', 'Migration', PDO::PARAM_STR);
$statement->bindValue(':businessfact_created', date("Y-m-d"), PDO::PARAM_STR);
$statement->execute();
$counter++;
// Issue an update message every 1000 records
if (($counter % 1000) == 0) {
$this->log("Processed $counter records... " . PHP_EOL);
echo "Processed $counter records... " . PHP_EOL;
}
}
}
// ======================
// Normalize Phone Number
// ======================
private function normailizePhoneNumber($phonenumber) {
return preg_replace('/\D+/', '', $phonenumber); // \D = non-digit
}
// ======================
// Normalize Phone Number
// ======================
function normailizeEmailAddress(string $email): string {
// Split at the first #
$clean = explode('#', $email, 2)[0];
// Normalize case
return strtolower(trim($clean));
}
// ============================
// Return a Business Facts Object
// ============================
private function getBusinessFacts() {
$SQL = "select * from BizFacts_tbl";
$businessfacts = $this->connect_olddb()->query($SQL)->fetchAll(PDO::FETCH_ASSOC);
return $businessfacts;
}
// =================================
// Return a Business Facts Dues Object
// =================================
private function getDropdownSerialByValue($description) {
$SQL = "select dropdown_serial from dropdowns where dropdown_value = '{$description}'";
$dropdown_serial = $this->connect_newdb()->query($SQL)->fetch(PDO::FETCH_ASSOC)['dropdown_serial'] ?? null;
return $dropdown_serial;
}
// ============================
// Return a Business Facts County
// ============================
private function getCountyByCountyName($county_name) {
$SQL = "select county_serial from counties where county_name = '{$county_name}'";
$county_serial = $this->connect_newdb()->query($SQL)->fetch(PDO::FETCH_ASSOC)['county_serial'] ?? null;
return $county_serial;
}
// ============================
// Return a Business Facts City
// ============================
private function getCityByCityName($city_name) {
$SQL = "select city_serial from cities where city_name = '{$city_name}'";
$city_serial = $this->connect_newdb()->query($SQL)->fetch(PDO::FETCH_ASSOC)['city_serial'] ?? null;
return $city_serial;
}
}
?>
+373
View File
@@ -0,0 +1,373 @@
<?php
// ================
// Migrate PZ Facts
// ================
class Migrate_PZFacts {
// Variables
private $log = "";
private $settings = "";
private $olddb_connection = "";
private $newdb_connection = "";
// ==================
// Class Constructor.
// ==================
public function __construct() {
// Open the Log
$this->log = fopen("../scripts/pzfacts.log", "w+");
if ($this->log === false) {
error_log("PZ Facts : Unable to open log file");
exit();
}
$this->log(str_repeat("*", 50));
// 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("PZ Facts : Unable to initialize settings");
exit();
}
// Open Database Connections
$this->olddb_connection = $this->connect_olddb();
$this->newdb_connection = $this->connect_newdb();
}
// ================================================
// Return a Old DEC-DR Database Database Connection
// ================================================
public function connect_olddb() {
try {
$host = (string) $this->settings->OldDatabaseServer;
$database = (string) $this->settings->OldDatabaseName;
$user = (string) $this->settings->OldDatabaseUser;
$password = (string) $this->settings->OldDatabasePassword;
$connection = new PDO("mysql:host={$host};dbname={$database};charset=utf8", $user, $password);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException | Exception $e) {
trigger_error($e->getMessage());
}
return $connection;
}
// ================================================
// Return a New DEC-DR Database Database Connection
// ================================================
public function connect_newdb() {
try {
$host = (string) $this->settings->DatabaseServer;
$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_EMULATE_PREPARES, false);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException | Exception $e) {
trigger_error($e->getMessage());
}
return $connection;
}
// =============================
// Log a message to the Log File
// =============================
private function log($message = "") {
fwrite($this->log, date("Y-m-d H:i A") . " : " . "{$message} \n");
}
// ===================
// Process Parcel Data
// ===================
public function process() {
$this->log("Starting Migration of Planning/Zoning Facts");
$this->migratePZFacts();
$this->log("Planning/Zoning Facts Migration Process Complete");
}
// ====================
// Migrate PZ Facts
// ====================
private function migratePZFacts() {
$this->log("Processing PZ Facts");
$pzfacts = $this->getPZFacts();
$SQL = "INSERT INTO pzfacts (
pzfact_legacy_id,
pzfact_entry_date,
pzfact_county,
pzfact_professional_name,
pzfact_professional_address,
pzfact_professional_state,
pzfact_professional_phone,
pzfact_professional_fax,
pzfact_owner_name,
pzfact_owner_address,
pzfact_owner_state,
pzfact_owner_phone,
pzfact_owner_fax,
pzfact_project_name,
pzfact_project_type,
pzfact_project_description,
pzfact_project_address,
pzfact_project_city,
pzfact_action_code,
pzfact_district,
pzfact_land_lot,
pzfact_lot,
pzfact_block,
pzfact_parcel_number,
pzfact_action_date,
pzfact_acres,
pzfact_status,
pzfact_dollar_value,
pzfact_estimated_ground_break,
pzfact_in_city_limit,
pzfact_creator,
pzfact_created )
VALUES ( :pzfact_legacy_id,
:pzfact_entry_date,
:pzfact_county,
:pzfact_professional_name,
:pzfact_professional_address,
:pzfact_professional_state,
:pzfact_professional_phone,
:pzfact_professional_fax,
:pzfact_owner_name,
:pzfact_owner_address,
:pzfact_owner_state,
:pzfact_owner_phone,
:pzfact_owner_fax,
:pzfact_project_name,
:pzfact_project_type,
:pzfact_project_description,
:pzfact_project_address,
:pzfact_project_city,
:pzfact_action_code,
:pzfact_district,
:pzfact_land_lot,
:pzfact_lot,
:pzfact_block,
:pzfact_parcel_number,
:pzfact_action_date,
:pzfact_acres,
:pzfact_status,
:pzfact_dollar_value,
:pzfact_estimated_ground_break,
:pzfact_in_city_limit,
:pzfact_creator,
:pzfact_created )";
$statement = $this->newdb_connection->prepare($SQL);
$counter = 0;
foreach ($pzfacts as $pzfact) {
$pzfact_legacy_id = $pzfact['PZ_ID'] ?? null;
$pzfact_entry_date = $pzfact['EntryDate'] ?? null;
$pzfact_county = $this->getCountyByCountyName($pzfact['County']) ?? null;
/* Professional */
$pzfact_professional_name = $pzfact['ProfessionalName'] ?? null;
$pzfact_professional_address = $pzfact['ProfessionalAddress'] ?? null;
$pzfact_professional_state = $pzfact['ProfessionalState'] ?? null;
$pzfact_professional_phone = $this->normailizePhoneNumber($pzfact['ProfessionalPhone']) ?? null;
$pzfact_professional_fax = $this->normailizePhoneNumber($pzfact['ProfessionalFax']) ?? null;
/* Owner */
$pzfact_owner_name = $pzfact['OwnerName'] ?? null;
$pzfact_owner_address = $pzfact['OwnerAddress'] ?? null;
$pzfact_owner_state = $pzfact['OwnerState'] ?? null;
$pzfact_owner_phone = $this->normailizePhoneNumber($pzfact['OwnerPhone']) ?? null;
$pzfact_owner_fax = $this->normailizePhoneNumber($pzfact['OwnerFax']) ?? null;
/* Project */
$pzfact_project_name = $pzfact['ProjectName'] ?? null;
$pzfact_project_type = $this->getDropdownSerialByValue($pzfact['ProjectType']) ?? null;
$pzfact_project_description = $pzfact['ProjectDescription'] ?? null;
$pzfact_project_address = $pzfact['ProjectAddress'] ?? null;
$pzfact_project_city = $this->getCityByCityName($pzfact['ProjectCity']) ?? null;
/* Zoning / action */
$pzfact_action_code = $this->getDropdownSerialByValue($pzfact['ActionCode']) ?? null;
$pzfact_district = $pzfact['District'] ?? null;
/* Parcel */
$pzfact_land_lot = $pzfact['LL'] ?? null;
$pzfact_lot = $pzfact['Lot'] ?? null;
$pzfact_block = $pzfact['Block'] ?? null;
$pzfact_parcel_number = $pzfact['Parcel'] ?? null;
/* Dates / values */
$pzfact_action_date = $pzfact['ActionDate'] ?? null;
$pzfact_acres = $pzfact['Acres'] ?? null;
$pzfact_status = $pzfact['Status'] ?? null;
$pzfact_dollar_value = $pzfact['DollarValueID'] ?? null;
$pzfact_estimated_ground_break = $pzfact['Est_Ground_Breaking'] ?? null;
/* Flags */
$pzfact_in_city_limit = isset($pzfact['City']) ? (int) $pzfact['City'] : 0;
/* Audit */
$pzfact_creator = 'Migration';
$pzfact_created = date('Y-m-d H:i:s');
$statement->bindValue(':pzfact_legacy_id', $pzfact_legacy_id, PDO::PARAM_INT);
$statement->bindValue(':pzfact_entry_date', $pzfact_entry_date, PDO::PARAM_STR);
$statement->bindValue(':pzfact_county', $pzfact_county, PDO::PARAM_INT);
$statement->bindValue(':pzfact_professional_name', $pzfact_professional_name, PDO::PARAM_STR);
$statement->bindValue(':pzfact_professional_address', $pzfact_professional_address, PDO::PARAM_STR);
$statement->bindValue(':pzfact_professional_state', $pzfact_professional_state, PDO::PARAM_STR);
$statement->bindValue(':pzfact_professional_phone', $pzfact_professional_phone, PDO::PARAM_STR);
$statement->bindValue(':pzfact_professional_fax', $pzfact_professional_fax, PDO::PARAM_STR);
$statement->bindValue(':pzfact_owner_name', $pzfact_owner_name, PDO::PARAM_STR);
$statement->bindValue(':pzfact_owner_address', $pzfact_owner_address, PDO::PARAM_STR);
$statement->bindValue(':pzfact_owner_state', $pzfact_owner_state, PDO::PARAM_STR);
$statement->bindValue(':pzfact_owner_phone', $pzfact_owner_phone, PDO::PARAM_STR);
$statement->bindValue(':pzfact_owner_fax', $pzfact_owner_fax, PDO::PARAM_STR);
$statement->bindValue(':pzfact_project_name', $pzfact_project_name, PDO::PARAM_STR);
$statement->bindValue(':pzfact_project_type', $pzfact_project_type, PDO::PARAM_INT);
$statement->bindValue(':pzfact_project_description', $pzfact_project_description, PDO::PARAM_STR);
$statement->bindValue(':pzfact_project_address', $pzfact_project_address, PDO::PARAM_STR);
$statement->bindValue(':pzfact_project_city', $pzfact_project_city, PDO::PARAM_INT);
$statement->bindValue(':pzfact_action_code', $pzfact_action_code, PDO::PARAM_INT);
$statement->bindValue(':pzfact_district', $pzfact_district, PDO::PARAM_INT);
$statement->bindValue(':pzfact_land_lot', $pzfact_land_lot, PDO::PARAM_STR);
$statement->bindValue(':pzfact_lot', $pzfact_lot, PDO::PARAM_STR);
$statement->bindValue(':pzfact_block', $pzfact_block, PDO::PARAM_STR);
$statement->bindValue(':pzfact_parcel_number', $pzfact_parcel_number, PDO::PARAM_STR);
$statement->bindValue(':pzfact_action_date', $pzfact_action_date, PDO::PARAM_STR);
$statement->bindValue(':pzfact_acres', $pzfact_acres, PDO::PARAM_STR);
$statement->bindValue(':pzfact_status', $pzfact_status, PDO::PARAM_STR);
$statement->bindValue(':pzfact_dollar_value', $pzfact_dollar_value, PDO::PARAM_STR);
$statement->bindValue(':pzfact_estimated_ground_break', $pzfact_estimated_ground_break, PDO::PARAM_STR);
$statement->bindValue(':pzfact_in_city_limit', $pzfact_in_city_limit, PDO::PARAM_INT);
$statement->bindValue(':pzfact_creator', $pzfact_creator, PDO::PARAM_STR);
$statement->bindValue(':pzfact_created', $pzfact_created, PDO::PARAM_STR);
$statement->execute();
$counter++;
// Issue an update message every 100 records
if (($counter % 100) == 0) {
$this->log("Processed $counter records... " . PHP_EOL);
echo "Processed $counter records... " . PHP_EOL;
}
}
}
// ======================
// Normalize Phone Number
// ======================
private function normailizePhoneNumber($phonenumber) {
return preg_replace('/\D+/', '', $phonenumber); // \D = non-digit
}
// ========================
// Return a PZ Facts Object
// ========================
private function getPZFacts() {
$SQL = "select * from PZ_tbl";
$pzfacts = $this->connect_olddb()->query($SQL)->fetchAll(PDO::FETCH_ASSOC);
return $pzfacts;
}
// =================
// Return a PZ Facts
// =================
private function getDropdownSerialByValue($description) {
$SQL = "select dropdown_serial from dropdowns where dropdown_value = '{$description}'";
$dropdown_serial = $this->connect_newdb()->query($SQL)->fetch(PDO::FETCH_ASSOC)['dropdown_serial'] ?? null;
return $dropdown_serial;
}
// ============================
// Return a PZ Facts County
// ============================
private function getCountyByCountyName($county_name) {
$SQL = "select county_serial from counties where county_name = '{$county_name}'";
$county_serial = $this->connect_newdb()->query($SQL)->fetch(PDO::FETCH_ASSOC)['county_serial'] ?? null;
return $county_serial;
}
// ============================
// Return a PZ Facts City
// ============================
private function getCityByCityName($city_name) {
$SQL = "select city_serial from cities where city_name = '{$city_name}'";
$city_serial = $this->connect_newdb()->query($SQL)->fetch(PDO::FETCH_ASSOC)['city_serial'] ?? null;
return $city_serial;
}
}
?>
+341
View File
@@ -0,0 +1,341 @@
<?php
// ====================
// Migrate Permit Facts
// ====================
class Migrate_PermitFacts {
// Variables
private $log = "";
private $settings = "";
private $olddb_connection = "";
private $newdb_connection = "";
// ==================
// Class Constructor.
// ==================
public function __construct() {
// Open the Log
$this->log = fopen("../scripts/permitfacts.log", "w+");
if ($this->log === false) {
error_log("Permit Facts : Unable to open log file");
exit();
}
$this->log(str_repeat("*", 50));
// 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("Permit Facts : Unable to initialize settings");
exit();
}
// Open Database Connections
$this->olddb_connection = $this->connect_olddb();
$this->newdb_connection = $this->connect_newdb();
}
// ================================================
// Return a Old DEC-DR Database Database Connection
// ================================================
public function connect_olddb() {
try {
$host = (string) $this->settings->OldDatabaseServer;
$database = (string) $this->settings->OldDatabaseName;
$user = (string) $this->settings->OldDatabaseUser;
$password = (string) $this->settings->OldDatabasePassword;
$connection = new PDO("mysql:host={$host};dbname={$database};charset=utf8", $user, $password);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException | Exception $e) {
trigger_error($e->getMessage());
}
return $connection;
}
// ================================================
// Return a New DEC-DR Database Database Connection
// ================================================
public function connect_newdb() {
try {
$host = (string) $this->settings->DatabaseServer;
$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_EMULATE_PREPARES, false);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException | Exception $e) {
trigger_error($e->getMessage());
}
return $connection;
}
// =============================
// Log a message to the Log File
// =============================
private function log($message = "") {
fwrite($this->log, date("Y-m-d H:i A") . " : " . "{$message} \n");
}
// ===================
// Process Parcel Data
// ===================
public function process() {
$this->log("Starting Migration of Permit Facts");
$this->migratePermitFacts();
$this->log("Permit Facts Migration Process Complete");
}
// ====================
// Migrate Permit Facts
// ====================
private function migratePermitFacts() {
$this->log("Processing Permit Facts");
$permitfacts = $this->getPermitFacts();
$SQL = "INSERT INTO permitfacts (
permitfact_legacy_id,
permitfact_entry_date,
permitfact_permit_number,
permitfact_permit_date,
permitfact_county,
permitfact_project_address,
permitfact_project_name,
permitfact_project_type,
permitfact_project_city,
permitfact_project_state,
permitfact_project_zip,
permitfact_company,
permitfact_address,
permitfact_city,
permitfact_state,
permitfact_zip,
permitfact_phone,
permitfact_size,
permitfact_value,
permitfact_work_type,
permitfact_building_type,
permitfact_lot_block,
permitfact_dist_ll,
permitfact_owner_name,
permitfact_owner_address,
permitfact_owner_city,
permitfact_owner_state,
permitfact_owner_zip,
permitfact_owner_phone,
permitfact_creator,
permitfact_created )
VALUES (
:permitfact_legacy_id,
:permitfact_entry_date,
:permitfact_permit_number,
:permitfact_permit_date,
:permitfact_county,
:permitfact_project_address,
:permitfact_project_name,
:permitfact_project_type,
:permitfact_project_city,
:permitfact_project_state,
:permitfact_project_zip,
:permitfact_company,
:permitfact_address,
:permitfact_city,
:permitfact_state,
:permitfact_zip,
:permitfact_phone,
:permitfact_size,
:permitfact_value,
:permitfact_work_type,
:permitfact_building_type,
:permitfact_lot_block,
:permitfact_dist_ll,
:permitfact_owner_name,
:permitfact_owner_address,
:permitfact_owner_city,
:permitfact_owner_state,
:permitfact_owner_zip,
:permitfact_owner_phone,
:permitfact_creator,
:permitfact_created ) ";
$statement = $this->newdb_connection->prepare($SQL);
$counter = 0;
foreach ($permitfacts as $permitfact) {
$permitfact_legacy_id = $permitfact['PermitFactsID'] ?? null;
$permitfact_entry_date = $permitfact['EntryDate'] ?? null;
$permitfact_permit_number = $permitfact['PermitNum'] ?? null;
$permitfact_permit_date = $permitfact['PermitDate'] ?? null;
$permitfact_county = $this->getCountyByCountyName($permitfact['County']) ?? null;
$permitfact_project_address = $permitfact['ProjectAddr'] ?? null;
$permitfact_project_name = $permitfact['ProjectName'] ?? null;
$permitfact_project_type = $this->getDropdownSerialByValue($permitfact['ProjectType']) ?? null;
$permitfact_project_city = $this->getCityByCityName($permitfact['ProjectCity']) ?? null;
$permitfact_project_state = $permitfact['ProjectState'] ?? null;
$permitfact_project_zip = $permitfact['ProjectZip'] ?? null;
$permitfact_company = $permitfact['Company'] ?? null;
$permitfact_address = $permitfact['Address'] ?? null;
$permitfact_city = $this->getCityByCityName($permitfact['City']) ?? null;
$permitfact_state = $permitfact['State'] ?? null;
$permitfact_zip = $permitfact['Zip'] ?? null;
$permitfact_phone = $this->normailizePhoneNumber($permitfact['Phone']) ?? null;
$permitfact_size = $permitfact['Size'] ?? null;
$permitfact_value = $permitfact['Value'] ?? null;
$permitfact_work_type = $this->getDropdownSerialByValue($permitfact['WorkType']) ?? null;
$permitfact_building_type = $this->getDropdownSerialByValue($permitfact['BldgType']) ?? null;
$permitfact_lot_block = $permitfact['Lot_BLK'] ?? null;
$permitfact_dist_ll = $permitfact['Dist_LL'] ?? null;
$permitfact_owner_name = $permitfact['OwnerName'] ?? null;
$permitfact_owner_address = $permitfact['OwnerAddress'] ?? null;
$permitfact_owner_city = $this->getCityByCityName($permitfact['OwnerCity']) ?? null;
$permitfact_owner_state = $permitfact['OwnerState'] ?? null;
$permitfact_owner_zip = $permitfact['OwnerZip'] ?? null;
$permitfact_owner_phone = $this->normailizePhoneNumber($permitfact['OwnerPhone']) ?? null;
$statement->bindValue(':PermitFactsID', $permitfact_legacy_id, PDO::PARAM_STR);
$statement->bindValue(':permitfact_entry_date', $permitfact_entry_date, PDO::PARAM_STR);
$statement->bindValue(':permitfact_permit_number', $permitfact_permit_number, PDO::PARAM_STR);
$statement->bindValue(':permitfact_permit_date', $permitfact_permit_date, PDO::PARAM_STR);
$statement->bindValue(':permitfact_county', $permitfact_county, PDO::PARAM_INT);
$statement->bindValue(':permitfact_project_address', $permitfact_project_address, PDO::PARAM_STR);
$statement->bindValue(':permitfact_project_name', $permitfact_project_name, PDO::PARAM_STR);
$statement->bindValue(':permitfact_project_type', $permitfact_project_type, PDO::PARAM_INT);
$statement->bindValue(':permitfact_project_city', $permitfact_project_city, PDO::PARAM_INT);
$statement->bindValue(':permitfact_project_state', $permitfact_project_state, PDO::PARAM_STR);
$statement->bindValue(':permitfact_project_zip', $permitfact_project_zip, PDO::PARAM_STR);
$statement->bindValue(':permitfact_company', $permitfact_company, PDO::PARAM_STR);
$statement->bindValue(':permitfact_address', $permitfact_address, PDO::PARAM_STR);
$statement->bindValue(':permitfact_city', $permitfact_city, PDO::PARAM_INT);
$statement->bindValue(':permitfact_state', $permitfact_state, PDO::PARAM_STR);
$statement->bindValue(':permitfact_zip', $permitfact_zip, PDO::PARAM_STR);
$statement->bindValue(':permitfact_phone', $permitfact_phone, PDO::PARAM_STR);
$statement->bindValue(':permitfact_size', $permitfact_size, PDO::PARAM_INT);
$statement->bindValue(':permitfact_value', $permitfact_value, PDO::PARAM_STR);
$statement->bindValue(':permitfact_work_type', $permitfact_work_type, PDO::PARAM_INT);
$statement->bindValue(':permitfact_building_type', $permitfact_building_type, PDO::PARAM_INT);
$statement->bindValue(':permitfact_lot_block', $permitfact_lot_block, PDO::PARAM_STR);
$statement->bindValue(':permitfact_dist_ll', $permitfact_dist_ll, PDO::PARAM_STR);
$statement->bindValue(':permitfact_owner_name', $permitfact_owner_name, PDO::PARAM_STR);
$statement->bindValue(':permitfact_owner_address', $permitfact_owner_address, PDO::PARAM_STR);
$statement->bindValue(':permitfact_owner_city', $permitfact_owner_city, PDO::PARAM_INT);
$statement->bindValue(':permitfact_owner_state', $permitfact_owner_state, PDO::PARAM_STR);
$statement->bindValue(':permitfact_owner_zip', $permitfact_owner_zip, PDO::PARAM_STR);
$statement->bindValue(':permitfact_owner_phone', $permitfact_owner_phone, PDO::PARAM_STR);
$statement->bindValue(':permitfact_creator', 'Migration', PDO::PARAM_STR);
$statement->bindValue(':permitfact_created', date("Y-m-d"), PDO::PARAM_STR);
$statement->execute();
$counter++;
// Issue an update message every 1000 records
if (($counter % 1000) == 0) {
$this->log("Processed $counter records... " . PHP_EOL);
echo "Processed $counter records... " . PHP_EOL;
}
}
}
// ======================
// Normalize Phone Number
// ======================
private function normailizePhoneNumber($phonenumber) {
return preg_replace('/\D+/', '', $phonenumber); // \D = non-digit
}
// ============================
// Return a Permit Facts Object
// ============================
private function getPermitFacts() {
$SQL = "select * from PermitFacts_tbl";
$permitfacts = $this->connect_olddb()->query($SQL)->fetchAll(PDO::FETCH_ASSOC);
return $permitfacts;
}
// =================================
// Return a Permit Facts Dues Object
// =================================
private function getDropdownSerialByValue($description) {
$SQL = "select dropdown_serial from dropdowns where dropdown_value = '{$description}'";
$dropdown_serial = $this->connect_newdb()->query($SQL)->fetch(PDO::FETCH_ASSOC)['dropdown_serial'] ?? null;
return $dropdown_serial;
}
// ============================
// Return a Permit Facts County
// ============================
private function getCountyByCountyName($county_name) {
$SQL = "select county_serial from counties where county_name = '{$county_name}'";
$county_serial = $this->connect_newdb()->query($SQL)->fetch(PDO::FETCH_ASSOC)['county_serial'] ?? null;
return $county_serial;
}
// ============================
// Return a Permit Facts City
// ============================
private function getCityByCityName($city_name) {
$SQL = "select city_serial from cities where city_name = '{$city_name}'";
$city_serial = $this->connect_newdb()->query($SQL)->fetch(PDO::FETCH_ASSOC)['city_serial'] ?? null;
return $city_serial;
}
}
?>
+207
View File
@@ -0,0 +1,207 @@
<?php
// ====================
// Migrate RDI Users
// ====================
class Migrate_Users {
// Variables
private $log = "";
private $settings = "";
private $olddb_connection = "";
private $newdb_connection = "";
// ==================
// Class Constructor.
// ==================
public function __construct() {
// Open the Log
$this->log = fopen("../scripts/rdiusers.log", "w+");
if ($this->log === false) {
error_log("RDI Users : Unable to open log file");
exit();
}
$this->log(str_repeat("*", 50));
// 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("RDI Users : Unable to initialize settings");
exit();
}
// Open Database Connections
$this->olddb_connection = $this->connect_olddb();
$this->newdb_connection = $this->connect_newdb();
}
// ================================================
// Return a Old DEC-DR Database Database Connection
// ================================================
public function connect_olddb() {
try {
$host = (string) $this->settings->OldDatabaseServer;
$database = (string) $this->settings->OldDatabaseName;
$user = (string) $this->settings->OldDatabaseUser;
$password = (string) $this->settings->OldDatabasePassword;
$connection = new PDO("mysql:host={$host};dbname={$database};charset=utf8", $user, $password);
$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException | Exception $e) {
trigger_error($e->getMessage());
}
return $connection;
}
// ================================================
// Return a New DEC-DR Database Database Connection
// ================================================
public function connect_newdb() {
try {
$host = (string) $this->settings->DatabaseServer;
$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_EMULATE_PREPARES, false);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException | Exception $e) {
trigger_error($e->getMessage());
}
return $connection;
}
// =============================
// Log a message to the Log File
// =============================
private function log($message = "") {
fwrite($this->log, date("Y-m-d H:i A") . " : " . "{$message} \n");
}
// ===================
// Process Parcel Data
// ===================
public function process() {
$this->log("Starting Migration of RDI Users");
$this->migrateUsers();
$this->log("RDI Users Migration Process Complete");
}
// ====================
// Migrate RDI Users
// ====================
private function migrateUsers() {
$this->log("Processing decweb Users");
$users = $this->getUsers();
$SQL = "INSERT INTO users (
user_id,
user_name,
user_email,
user_password,
user_role,
user_change_password,
user_active,
user_creator,
user_created )
VALUES (
:user_id,
:user_name,
:user_email,
:user_password,
:user_role,
:user_change_password,
:user_active,
:user_creator,
:user_created ) ";
$statement = $this->newdb_connection->prepare($SQL);
$counter = 0;
foreach ($users as $user) {
$user_id = $user['UserName'];
$user_name = $user['UserName'];
$user_email = $user['Email'];
$user_password = $user['Password'];
$user_role = "User";
$user_change_password = 0;
$user_active = 1;
$user_creator = "Migrated";
$user_created = date("Y-m-d H:i:s");
$user_password = password_hash($user_password, PASSWORD_DEFAULT);
$statement->bindValue(':user_id', $user_id);
$statement->bindValue(':user_name', $user_name);
$statement->bindValue(':user_email', $user_email);
$statement->bindValue(':user_password', $user_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', $user_creator);
$statement->bindValue(':user_created', $user_created);
$statement->execute();
$counter++;
// Issue an update message every 10 records
if (($counter % 10) == 0) {
$this->log("Processed $counter records... ");
}
}
}
// =====================
// Return a Users Object
// =====================
private function getUsers() {
$SQL = "select * from Users_tbl";
$users = $this->connect_olddb()->query($SQL)->fetchAll(PDO::FETCH_ASSOC);
return $users;
}
}
?>
+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();
}
}
?>
+631
View File
@@ -0,0 +1,631 @@
<?php
class PermitFacts 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;
}
// ==============
// Search Permits
// ==============
public function searchPermitFacts() {
$subscription_serial = $_SESSION['subscription_serial'];
$usersubscription_serial = $_SESSION['usersubscription_serial'];
$subscription = (new Subscriptions())->getSubscription($subscription_serial);
if ($subscription->count() === 0) {
$this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
}
$userssubscription = (new Users())->getUserSubscription($usersubscription_serial);
$user_subscription_start_date = $userssubscription->record->usersubscription_start_date;
$user_subscription_end_date = $userssubscription->record->usersubscription_end_date;
$searchhistory = (new SearchHistory())->getUsersPreviousSearchParameters($this->current_user_serial, $subscription_serial);
// Update Search History Record
if (empty($searchhistory)) {
(new SearchHistory())->saveUserSearchParameters($_POST);
} else {
(new SearchHistory())->updateUserSearchParameters($_POST);
}
$permits = $this->getPermitFactsPage($user_subscription_start_date, $user_subscription_end_date);
$searchhistory = (new SearchHistory())->getUsersPreviousSearchParameters($this->current_user_serial, $subscription_serial);
// Populate Entry Dates with what was searched for if provided or users entry dates if no entry dates were provided
$searchhistory->record->searchhistory_parameters->permitfact_entry_date_from = $permits->record->permitfact_entry_date_from;
$searchhistory->record->searchhistory_parameters->permitfact_entry_date_to = $permits->record->permitfact_entry_date_to;
$popovers = (new Popovers())->getPopovers();
$dropdowns = (new Dropdowns())->getDropdowns();
$cities = (new Cities())->getSubscriptionCities($subscription_serial);
$counties = (new Counties())->getSubscriptionCounties($subscription_serial);
$availablerecordcount = $this->userTotalAvailableRecordCount($user_subscription_start_date, $user_subscription_end_date);
$XML = $this->mergeXML($permits, "<XML/>");
$XML = $this->mergeXML($subscription, $XML);
$XML = $this->mergeXML($popovers, $XML);
$XML = $this->mergeXML($dropdowns, $XML);
$XML = $this->mergeXML($cities, $XML);
$XML = $this->mergeXML($counties, $XML);
$XML = $this->mergeXML($searchhistory, $XML);
$XML = $this->mergeXML($availablerecordcount, $XML);
$content = $this->applyXSL($XML, $this->getXSL("searchPermitFacts"));
$this->displayContent($content);
}
// =================================
// Return a Permit Facts Page Object
// =================================
public function getPermitFactsPage($user_subscription_start_date, $user_subscription_end_date) {
set_time_limit(0);
// Sanitize inputs
$permitfact_company = filter_input(INPUT_POST, "permitfact_company") ?: "";
$permitfact_project_name = filter_input(INPUT_POST, "permitfact_project_name") ?: "";
$permitfact_project_zip = filter_input(INPUT_POST, "permitfact_project_zip") ?: "";
$permitfact_project_city = filter_input(INPUT_POST, "permitfact_project_city") ?: "";
$permitfact_county = filter_input(INPUT_POST, "permitfact_county") ?: "";
$permitfact_project_type = filter_input(INPUT_POST, "permitfact_project_type") ?: "";
$permitfact_work_type = filter_input(INPUT_POST, "permitfact_work_type") ?: "";
$permitfact_building_type = filter_input(INPUT_POST, "permitfact_building_type") ?: "";
$permitfact_size_from = filter_input(INPUT_POST, "permitfact_size_from") ?: "";
$permitfact_size_to = filter_input(INPUT_POST, "permitfact_size_to") ?: "";
$permitfact_value_from = filter_input(INPUT_POST, "permitfact_value_from") ?: "";
$permitfact_value_to = filter_input(INPUT_POST, "permitfact_value_to") ?: "";
$permitfact_permit_date_from = filter_input(INPUT_POST, "permitfact_permit_date_from") ?: "";
$permitfact_permit_date_to = filter_input(INPUT_POST, "permitfact_permit_date_to") ?: "";
$permitfact_entry_date_from = filter_input(INPUT_POST, "permitfact_entry_date_from") ?: "";
$permitfact_entry_date_to = filter_input(INPUT_POST, "permitfact_entry_date_to") ?: "";
// Determine real date range based upon users subscription start date
if ($user_subscription_start_date <= date('Y-m-d', strtotime('-1 year'))) {
$user_subscription_start_date = date('Y-m-d', strtotime('-1 year'));
}
$permitfact_permit_date_from = ($permitfact_permit_date_from == "") ? null : date("Y-m-d", strtotime($permitfact_permit_date_from));
$permitfact_permit_date_to = ($permitfact_permit_date_to == "") ? null : date("Y-m-d", strtotime($permitfact_permit_date_to));
$permitfact_entry_date_from = ($permitfact_entry_date_from == "") ? null : date("Y-m-d", strtotime($permitfact_entry_date_from));
$permitfact_entry_date_to = ($permitfact_entry_date_to == "") ? null : date("Y-m-d", strtotime($permitfact_entry_date_to));
// Pagination settings
$pagination = filter_input(INPUT_POST, "pagination") ?: "";
$this->pagination_size = filter_input(INPUT_POST, "permitfacts_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
// Connect to DB
$connection = $this->connect();
// Record Count
$SQL = "select count(*) as count
from view_permitfacts
where view_permitfacts.permitfact_entry_date between :user_subscription_start_date and :user_subscription_end_date ";
if ($permitfact_company !== '') {
$SQL .= " and permitfact_company regexp :permitfact_company ";
}
if ($permitfact_project_name !== '') {
$SQL .= " and view_permitfacts.permitfact_project_name regexp :permitfact_project_name ";
}
if ($permitfact_project_zip !== '') {
$SQL .= " and view_permitfacts.permitfact_project_zip = :permitfact_project_zip ";
}
if ($permitfact_project_city !== '') {
$SQL .= " and view_permitfacts.permitfact_project_city in ($permitfact_project_city) ";
}
// if ($permitfact_project_city !== '') {
// $SQL .= " and view_permitfacts.permitfact_city in ($permitfact_project_city) ";
// } else {
// $cities = (new Cities())->getSubscriptionCities($_SESSION['subscription_serial']);
//
// $cityNames = [];
//
// foreach ($cities as $city) {
// $cityNames[] = " " . (string) $city->subscriptioncity_city . " ";
// }
//
// $permitfact_project_city = ' ' . implode(', ', $cityNames) . ' ';
//
// $SQL .= " and view_permitfacts.permitfact_city in ($permitfact_project_city) ";
// }
if ($permitfact_county !== '') {
$SQL .= " and view_permitfacts.permitfact_county in ($permitfact_county) ";
} else {
$counties = (new Counties())->getSubscriptionCounties($_SESSION['subscription_serial']);
$countyNames = [];
foreach ($counties as $county) {
$countyNames[] = " " . (string) $county->subscriptioncounty_county . " ";
}
$permitfact_county = ' ' . implode(', ', $countyNames) . ' ';
$SQL .= " and view_permitfacts.permitfact_county in ($permitfact_county) ";
}
if ($permitfact_project_type !== '') {
$SQL .= " and view_permitfacts.permitfact_project_type in ($permitfact_project_type) ";
}
if ($permitfact_work_type !== '') {
$SQL .= " and view_permitfacts.permitfact_work_type in ($permitfact_work_type) ";
}
if ($permitfact_building_type !== '') {
$SQL .= " and view_permitfacts.permitfact_building_type in ($permitfact_building_type) ";
}
if ($permitfact_size_from !== '' && $permitfact_size_to !== '') {
$SQL .= " and view_permitfacts.permitfact_size between '{$permitfact_size_from}' and '{$permitfact_size_to}' ";
} elseif ($permitfact_size_from != '') {
$SQL .= " and view_permitfacts.permitfact_size = '{$permitfact_size_from}' ";
} elseif ($permitfact_size_to != '') {
$SQL .= " and view_permitfacts.permitfact_size = '{$permitfact_size_to}' ";
}
if ($permitfact_value_from !== '' && $permitfact_value_to !== '') {
$SQL .= " and view_permitfacts.permitfact_value between '{$permitfact_value_from}' and '{$permitfact_value_to}' ";
} elseif ($permitfact_value_from != '') {
$SQL .= " and view_permitfacts.permitfact_value = '{$permitfact_value_from}' ";
} elseif ($permitfact_value_to != '') {
$SQL .= " and view_permitfacts.permitfact_value = '{$permitfact_value_to}' ";
}
// =======================
// Permit Date Logic Start
// =======================
$permitFrom = $permitfact_permit_date_from; // null or Y-m-d
$permitTo = $permitfact_permit_date_to; // null or Y-m-d
$subStart = $user_subscription_start_date; // Y-m-d
$subEnd = $user_subscription_end_date; // Y-m-d
// ---- Enforce subscription window for permit dates (only if user provided them) ----
if ($permitFrom !== null) {
if ($permitFrom < $subStart || $permitFrom > $subEnd) {
$this->displayNotice("The Permit Issue 'from' date or date range {$this->current_user_name} selected is outside your authorized access period.");
return;
}
}
if ($permitTo !== null) {
if ($permitTo < $subStart || $permitTo > $subEnd) {
$this->displayNotice("The Permit Issue 'to' date or date range {$this->current_user_name} selected is outside your authorized access period.");
return;
}
}
// ---- Build the permit date filter logic ----
if ($permitFrom !== null && $permitTo !== null) {
// If user reversed the dates, swap them
if ($permitFrom > $permitTo) {
$tmp = $permitFrom;
$permitFrom = $permitTo;
$permitTo = $tmp;
}
$SQL .= " AND view_permitfacts.permitfact_permit_date BETWEEN '{$permitFrom}' AND '{$permitTo}'";
} elseif ($permitFrom !== null) {
// User entered only "From" => treat as a specific date
$SQL .= " AND view_permitfacts.permitfact_permit_date = '{$permitFrom}'";
} elseif ($permitTo !== null) {
// User entered only "To" => treat as a specific date
$SQL .= " AND view_permitfacts.permitfact_permit_date = '{$permitTo}'";
}
// =====================
// Permit Date Logic End
// =====================
// ======================
// Entry Date Logic Start
// ======================
$entryFrom = $permitfact_entry_date_from; // null or Y-m-d
$entryTo = $permitfact_entry_date_to; // null or Y-m-d
$subStart = $user_subscription_start_date; // Y-m-d
$subEnd = $user_subscription_end_date; // Y-m-d
// ---- Enforce subscription window for entry dates (only if user provided them) ----
if ($entryFrom !== null) {
if ($entryFrom < $subStart || $entryFrom > $subEnd) {
$this->displayNotice("The Entry 'from' date or date range {$this->current_user_name} selected is outside your authorized access period.");
return;
}
}
if ($entryTo !== null) {
if ($entryTo < $subStart || $entryTo > $subEnd) {
$this->displayNotice("The Entry 'to' date or date range {$this->current_user_name} selected is outside your authorized access period.");
return;
}
}
// ---- Build the entry date filter logic ----
if ($entryFrom !== null && $entryTo !== null) {
// If user reversed the dates, swap them
if ($entryFrom > $entryTo) {
$tmp = $entryFrom;
$entryFrom = $entryTo;
$entryTo = $tmp;
}
$SQL .= " AND view_permitfacts.permitfact_entry_date BETWEEN '{$entryFrom}' AND '{$entryTo}'";
} elseif ($entryFrom !== null) {
// User entered only "From" => treat as a specific date
$SQL .= " AND view_permitfacts.permitfact_entry_date = '{$entryFrom}'";
} elseif ($entryTo !== null) {
// User entered only "To" => treat as a specific date
$SQL .= " AND view_permitfacts.permitfact_entry_date = '{$entryTo}'";
}
// ====================
// Entry Date Logic End
// ====================
$statement = $connection->prepare($SQL);
if ($permitfact_company !== '') {
$statement->bindValue(":permitfact_company", $permitfact_company, PDO::PARAM_STR);
}
if ($permitfact_project_name !== '') {
$statement->bindValue(":permitfact_project_name", $permitfact_project_name, PDO::PARAM_STR);
}
if ($permitfact_project_zip !== '') {
$statement->bindValue(":permitfact_project_zip", $permitfact_project_zip, PDO::PARAM_STR);
}
$statement->bindValue(":user_subscription_start_date", $user_subscription_start_date, PDO::PARAM_STR);
$statement->bindValue(":user_subscription_end_date", $user_subscription_end_date, PDO::PARAM_STR);
$statement->execute();
$recordset = $statement->fetch(PDO::FETCH_ASSOC);
$count = $recordset ? (int) $recordset["count"] : 0;
// === PAGINATION LOGIC ===
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 = min($this->pagination_page + 1, ceil($count / $this->pagination_size));
break;
case "last": $this->pagination_page = (int) ceil($count / $this->pagination_size);
break;
}
$offset = max(0, ($this->pagination_page - 1) * $this->pagination_size);
$start = $offset + 1;
$end = min($count, $start + $this->pagination_size - 1);
// === DATA QUERY ===
$SQL = "select view_permitfacts.*
from view_permitfacts
where view_permitfacts.permitfact_entry_date between :user_subscription_start_date and :user_subscription_end_date ";
if ($permitfact_company !== '') {
$SQL .= " and view_permitfacts.permitfact_company regexp :permitfact_company ";
}
if ($permitfact_project_name !== '') {
$SQL .= " and view_permitfacts.permitfact_project_name regexp :permitfact_project_name ";
}
if ($permitfact_project_zip !== '') {
$SQL .= " and view_permitfacts.permitfact_project_zip = :permitfact_project_zip ";
}
if ($permitfact_project_city !== '') {
$SQL .= " and view_permitfacts.permitfact_project_city in ($permitfact_project_city) ";
}
// if ($permitfact_project_city !== '') {
// $SQL .= " and view_permitfacts.permitfact_city in ($permitfact_project_city) ";
// } else {
// $cities = (new Cities())->getSubscriptionCities($_SESSION['subscription_serial']);
//
// $cityNames = [];
//
// foreach ($cities as $city) {
// $cityNames[] = " " . (string) $city->subscriptioncity_city . " ";
// }
//
// $permitfact_project_city = ' ' . implode(', ', $cityNames) . ' ';
//
// $SQL .= " and view_permitfacts.permitfact_city in ($permitfact_project_city) ";
// }
if ($permitfact_county !== '') {
$SQL .= " and view_permitfacts.permitfact_county in ($permitfact_county) ";
} else {
$counties = (new Counties())->getSubscriptionCounties($_SESSION['subscription_serial']);
$countyNames = [];
foreach ($counties as $county) {
$countyNames[] = " " . (string) $county->subscriptioncounty_county . " ";
}
$permitfact_county = ' ' . implode(', ', $countyNames) . ' ';
$SQL .= " and view_permitfacts.permitfact_county in ($permitfact_county) ";
}
if ($permitfact_project_type !== '') {
$SQL .= " and view_permitfacts.permitfact_project_type in ($permitfact_project_type) ";
}
if ($permitfact_work_type !== '') {
$SQL .= " and view_permitfacts.permitfact_work_type in ($permitfact_work_type) ";
}
if ($permitfact_building_type !== '') {
$SQL .= " and view_permitfacts.permitfact_building_type in ($permitfact_building_type) ";
}
if ($permitfact_size_from !== '' && $permitfact_size_to !== '') {
$SQL .= " and view_permitfacts.permitfact_size between '{$permitfact_size_from}' and '{$permitfact_size_from}' ";
} elseif ($permitfact_size_from != '') {
$SQL .= " and view_permitfacts.permitfact_size = '{$permitfact_size_from}' ";
} elseif ($permitfact_size_to != '') {
$SQL .= " and view_permitfacts.permitfact_size = '{$permitfact_size_from}' ";
}
if ($permitfact_value_from !== '' && $permitfact_value_to !== '') {
$SQL .= " and view_permitfacts.permitfact_value between '{$permitfact_value_from}' and '{$permitfact_value_to}' ";
} elseif ($permitfact_value_from !== '') {
$SQL .= " and view_permitfacts.permitfact_value = '{$permitfact_value_to}' ";
} elseif ($permitfact_value_to !== '') {
$SQL .= " and view_permitfacts.permitfact_value = '{$permitfact_value_to}' ";
}
// =======================
// Permit Date Logic Start
// =======================
$permitFrom = $permitfact_permit_date_from; // null or Y-m-d
$permitTo = $permitfact_permit_date_to; // null or Y-m-d
$subStart = $user_subscription_start_date; // Y-m-d
$subEnd = $user_subscription_end_date; // Y-m-d
// ---- Enforce subscription window for permit dates (only if user provided them) ----
if ($permitFrom !== null) {
if ($permitFrom < $subStart || $permitFrom > $subEnd) {
return;
}
}
if ($permitTo !== null) {
if ($permitTo < $subStart || $permitTo > $subEnd) {
return;
}
}
// ---- Build the permit date filter logic ----
if ($permitFrom !== null && $permitTo !== null) {
// If user reversed the dates, swap them
if ($permitFrom > $permitTo) {
$tmp = $permitFrom;
$permitFrom = $permitTo;
$permitTo = $tmp;
}
$SQL .= " AND view_permitfacts.permitfact_permit_date BETWEEN '{$permitFrom}' AND '{$permitTo}'";
} elseif ($permitFrom !== null) {
// User entered only "From" => treat as a specific date
$SQL .= " AND view_permitfacts.permitfact_permit_date = '{$permitFrom}'";
} elseif ($permitTo !== null) {
// User entered only "To" => treat as a specific date
$SQL .= " AND view_permitfacts.permitfact_permit_date = '{$permitTo}'";
}
// ======================
// Permit Date Logic End
// ======================
// ======================
// Entry Date Logic Start
// ======================
$entryFrom = $permitfact_entry_date_from; // null or Y-m-d
$entryTo = $permitfact_entry_date_to; // null or Y-m-d
$subStart = $user_subscription_start_date; // Y-m-d
$subEnd = $user_subscription_end_date; // Y-m-d
// ---- Enforce subscription window for entry dates (only if user provided them) ----
if ($entryFrom !== null) {
if ($entryFrom < $subStart || $entryFrom > $subEnd) {
return;
}
}
if ($entryTo !== null) {
if ($entryTo < $subStart || $entryTo > $subEnd) {
return;
}
}
// ---- Build the entry date filter logic ----
if ($entryFrom !== null && $entryTo !== null) {
// If user reversed the dates, swap them
if ($entryFrom > $entryTo) {
$tmp = $entryFrom;
$entryFrom = $entryTo;
$entryTo = $tmp;
}
$SQL .= " AND view_permitfacts.permitfact_entry_date BETWEEN '{$entryFrom}' AND '{$entryTo}'";
} elseif ($entryFrom !== null) {
// User entered only "From" => treat as a specific date
$SQL .= " AND view_permitfacts.permitfact_entry_date = '{$entryFrom}'";
} elseif ($entryTo !== null) {
// User entered only "To" => treat as a specific date
$SQL .= " AND view_permitfacts.permitfact_entry_date = '{$entryTo}'";
}
// ====================
// Entry Date Logic End
// ====================
if ($pagination !== 'off') {
$SQL .= " limit :limit
offset :offset";
}
$statement = $connection->prepare($SQL);
if ($permitfact_company !== '') {
$statement->bindValue(":permitfact_company", $permitfact_company, PDO::PARAM_STR);
}
if ($permitfact_project_name !== '') {
$statement->bindValue(":permitfact_project_name", $permitfact_project_name, PDO::PARAM_STR);
}
if ($permitfact_project_zip !== '') {
$statement->bindValue(":permitfact_project_zip", $permitfact_project_zip, PDO::PARAM_STR);
}
$statement->bindValue(":user_subscription_start_date", $user_subscription_start_date, PDO::PARAM_STR);
$statement->bindValue(":user_subscription_end_date", $user_subscription_end_date, PDO::PARAM_STR);
if ($pagination !== 'off') {
$statement->bindValue(":limit", $this->pagination_size, PDO::PARAM_INT);
$statement->bindValue(":offset", $offset, PDO::PARAM_INT);
}
$statement->execute();
$permitfacts = $this->getTableXML("permitfacts", $statement);
// Add searched entry_dates for search history
$permitfacts->record->permitfact_entry_date_from = !empty($entryFrom) ? date('m/d/Y', strtotime($entryFrom)) : date('m/d/Y', strtotime($user_subscription_start_date));
$permitfacts->record->permitfact_entry_date_to = !empty($entryTo) ? date('m/d/Y', strtotime($entryTo)) : date('m/d/Y', strtotime($user_subscription_end_date));
// Insert Pagination Attributes
$permitfacts->addAttribute("count", $count);
$permitfacts->addAttribute("start", $start);
$permitfacts->addAttribute("end", $end);
$permitfacts->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $permitfacts;
}
// ==================================
// Users Total Available Record Count
// ==================================
public function userTotalAvailableRecordCount($user_subscription_start_date, $user_subscription_end_date) {
// determine real date range based upon users subscription start date
if ($user_subscription_start_date <= date('Y-m-d', strtotime('-1 year'))) {
$user_subscription_start_date = date('Y-m-d', strtotime('-1 year'));
}
$SQL = "select count(*) as count
from view_permitfacts
where view_permitfacts.permitfact_entry_date between '{$user_subscription_start_date}' and '{$user_subscription_end_date}' ";
$counties = (new Counties())->getSubscriptionCounties($_SESSION['subscription_serial']);
$countyNames = [];
foreach ($counties as $county) {
$countyNames[] = " " . (string) $county->subscriptioncounty_county . " ";
}
$permitfact_county = ' ' . implode(', ', $countyNames) . ' ';
$SQL .= " and view_permitfacts.permitfact_county in ($permitfact_county) ";
return $this->getTable("userstotalavailablerecords", $SQL);
}
// ======================
// Get Users Full Dataset
// ======================
public function getPermitFactsFullDataset($user_subscription_start_date, $user_subscription_end_date) {
set_time_limit(0);
$connection = $this->connect();
$SQL = "select view_permitfacts.*
from view_permitfacts
where view_permitfacts.permitfact_entry_date between :user_subscription_start_date and :user_subscription_end_date";
$statement = $connection->prepare($SQL);
$statement->bindValue(":user_subscription_start_date", $user_subscription_start_date, PDO::PARAM_STR);
$statement->bindValue(":user_subscription_end_date", $user_subscription_end_date, PDO::PARAM_STR);
$statement->execute();
$permitfacts = $this->getTableXML("permitfacts", $statement);
return $permitfacts;
}
}
?>
+510
View File
@@ -0,0 +1,510 @@
<?php
class PlanningAndZoningFacts 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;
}
// ================================
// Search Planning And Zoning Facts
// ================================
public function searchPlanningAndZoningFacts() {
$subscription_serial = $_SESSION['subscription_serial'];
$usersubscription_serial = $_SESSION['usersubscription_serial'];
$subscription = (new Subscriptions())->getSubscription($subscription_serial);
if ($subscription->count() === 0) {
$this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
}
$userssubscription = (new Users())->getUserSubscription($usersubscription_serial);
$user_subscription_start_date = $userssubscription->record->usersubscription_start_date;
$user_subscription_end_date = $userssubscription->record->usersubscription_end_date;
$searchhistory = (new SearchHistory())->getUsersPreviousSearchParameters($this->current_user_serial, $subscription_serial);
// Update Search History Record
if (empty($searchhistory)) {
(new SearchHistory())->saveUserSearchParameters($_POST);
} else {
(new SearchHistory())->updateUserSearchParameters($_POST);
}
$planningzoningfacts = $this->getPZFactsPage($user_subscription_start_date, $user_subscription_end_date);
$searchhistory = (new SearchHistory())->getUsersPreviousSearchParameters($this->current_user_serial, $subscription_serial);
$searchhistory->record->searchhistory_parameters->pzfact_entry_date_from = $planningzoningfacts->record->pzfact_entry_date_from;
$searchhistory->record->searchhistory_parameters->pzfact_entry_date_to = $planningzoningfacts->record->pzfact_entry_date_to;
$popovers = (new Popovers())->getPopovers();
$dropdowns = (new Dropdowns())->getDropdowns();
// $cities = (new Cities())->getSubscriptionCities($subscription_serial);
$cities = $this->getPzCities();
// $counties = (new Counties())->getSubscriptionCounties($subscription_serial);
$counties = $this->getPzCounties();
$availablerecordcount = $this->userTotalAvailableRecordCount($user_subscription_start_date, $user_subscription_end_date);
$XML = $this->mergeXML($planningzoningfacts, "<XML/>");
$XML = $this->mergeXML($subscription, $XML);
$XML = $this->mergeXML($popovers, $XML);
$XML = $this->mergeXML($dropdowns, $XML);
$XML = $this->mergeXML($cities, $XML);
$XML = $this->mergeXML($counties, $XML);
$XML = $this->mergeXML($searchhistory, $XML);
$XML = $this->mergeXML($availablerecordcount, $XML);
$content = $this->applyXSL($XML, $this->getXSL("searchPZFacts"));
$this->displayContent($content);
}
// =======================
// Return PZ Cities Object
// =======================
public function getPzCities() {
$SQL = "select view_pzfacts.pzfact_project_city, view_pzfacts.project_city_verbose from view_pzfacts where pzfact_in_city_limit = 1 and project_city_verbose is not null group by project_city_verbose";
return $this->getTable("subscriptioncities", $SQL);
}
// =========================
// Return PZ Counties Object
// =========================
public function getPzCounties() {
$SQL = "select view_pzfacts.pzfact_county, view_pzfacts.pzfact_county_name_verbose from view_pzfacts where pzfact_county_name_verbose is not null group by pzfact_county_name_verbose";
return $this->getTable("subscriptioncounties", $SQL);
}
// =============================
// Return a PZ Facts Page Object
// =============================
public function getPZFactsPage($user_subscription_start_date, $user_subscription_end_date) {
// ---------------------------
// Read + normalize inputs
// ---------------------------
$pzfact_project_name = trim((string) filter_input(INPUT_POST, "pzfact_project_name")) ?: "";
$pzfact_project_city = trim((string) filter_input(INPUT_POST, "pzfact_project_city")) ?: "";
$pzfact_county = trim((string) filter_input(INPUT_POST, "pzfact_county")) ?: "";
$pzfact_project_type = trim((string) filter_input(INPUT_POST, "pzfact_project_type")) ?: "";
$pzfact_action_code = trim((string) filter_input(INPUT_POST, "pzfact_action_code")) ?: "";
$pzfact_acres_from = trim((string) filter_input(INPUT_POST, "pzfact_acres_from")) ?: "";
$pzfact_acres_to = trim((string) filter_input(INPUT_POST, "pzfact_acres_to")) ?: "";
$pzfact_entry_date_from = trim((string) filter_input(INPUT_POST, "pzfact_entry_date_from")) ?: "";
$pzfact_entry_date_to = trim((string) filter_input(INPUT_POST, "pzfact_entry_date_to")) ?: "";
// Pagination
$pagination = trim((string) filter_input(INPUT_POST, "pagination")) ?: "";
$this->pagination_size = filter_input(INPUT_POST, "pzfacts_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
// --------------------------------------------------------------
// Clamp subscription start to last year (your existing behavior)
// --------------------------------------------------------------
$oneYearAgo = date('Y-m-d', strtotime('-1 year'));
if ($user_subscription_start_date <= $oneYearAgo) {
$user_subscription_start_date = $oneYearAgo;
}
// Safety: make sure subscription end isn't before start
if ($user_subscription_end_date < $user_subscription_start_date) {
$this->displayNotice("Your authorized access period is invalid (end date is before start date).");
return;
}
// --------------------------------------
// Normalize entry dates to Y-m-d or null
// --------------------------------------
$entryFrom = ($pzfact_entry_date_from === "") ? null : date("Y-m-d", strtotime($pzfact_entry_date_from));
$entryTo = ($pzfact_entry_date_to === "") ? null : date("Y-m-d", strtotime($pzfact_entry_date_to));
// -------
// Connect
// -------
$connection = $this->connect();
// -------------------------------------
// Build WHERE clause once + params once
// -------------------------------------
$clauses = [];
$params = [];
// Always enforce subscription window
$clauses[] = "view_pzfacts.pzfact_entry_date BETWEEN :sub_start AND :sub_end";
$params[':sub_start'] = $user_subscription_start_date;
$params[':sub_end'] = $user_subscription_end_date;
// Project Name (REGEXP)
if ($pzfact_project_name !== '') {
$clauses[] = "view_pzfacts.pzfact_project_name REGEXP :project_name";
$params[':project_name'] = $pzfact_project_name;
}
// Helper: build safe IN (...) lists from a CSV string of numeric ids
$bindIn = function (string $field, string $csv, string $paramPrefix) use (&$clauses, &$params) {
// Accept "30,31, 32" etc.
$raw = array_values(array_filter(array_map('trim', explode(',', $csv)), 'strlen'));
// Keep digits only (prevents injection)
$items = [];
foreach ($raw as $v) {
if (ctype_digit($v)) {
$items[] = (int) $v;
}
}
if (!$items) {
return;
}
$placeholders = [];
foreach ($items as $i => $val) {
$ph = ":{$paramPrefix}{$i}";
$placeholders[] = $ph;
$params[$ph] = $val;
}
$clauses[] = "{$field} IN (" . implode(',', $placeholders) . ")";
};
// Safe IN filters
if ($pzfact_project_city !== '') {
$bindIn("view_pzfacts.pzfact_project_city", $pzfact_project_city, "city_");
}
if ($pzfact_county !== '') {
$bindIn("view_pzfacts.pzfact_county", $pzfact_county, "county_");
}
if ($pzfact_project_type !== '') {
$bindIn("view_pzfacts.pzfact_project_type", $pzfact_project_type, "ptype_");
}
if ($pzfact_action_code !== '') {
$bindIn("view_pzfacts.pzfact_action_code", $pzfact_action_code, "acode_");
}
// Acres filter (numeric; bind params)
if ($pzfact_acres_from !== '' && $pzfact_acres_to !== '') {
$clauses[] = "view_pzfacts.pzfact_acres BETWEEN :acres_from AND :acres_to";
$params[':acres_from'] = (float) $pzfact_acres_from;
$params[':acres_to'] = (float) $pzfact_acres_to;
} elseif ($pzfact_acres_from !== '') {
$clauses[] = "view_pzfacts.pzfact_acres = :acres_eq";
$params[':acres_eq'] = (float) $pzfact_acres_from;
} elseif ($pzfact_acres_to !== '') {
$clauses[] = "view_pzfacts.pzfact_acres = :acres_eq";
$params[':acres_eq'] = (float) $pzfact_acres_to;
}
// -----------------------------------------------------
// Entry Date Logic (User selection within subscription)
// -----------------------------------------------------
$subStart = $user_subscription_start_date;
$subEnd = $user_subscription_end_date;
if ($entryFrom !== null || $entryTo !== null) {
// Treat single date as a one-day range
if ($entryFrom !== null && $entryTo === null) {
$entryTo = $entryFrom;
}
if ($entryTo !== null && $entryFrom === null) {
$entryFrom = $entryTo;
}
// Swap if reversed
if ($entryFrom > $entryTo) {
$tmp = $entryFrom;
$entryFrom = $entryTo;
$entryTo = $tmp;
}
// Enforce subscription window with your existing policy (reject + notice)
if ($entryFrom < $subStart || $entryTo > $subEnd) {
$this->displayNotice("The Entry date or date range {$this->current_user_name} selected is outside your authorized access period.");
return;
}
// Add user range filter (intersection with subscription range)
$clauses[] = "view_pzfacts.pzfact_entry_date BETWEEN :entry_from AND :entry_to";
$params[':entry_from'] = $entryFrom;
$params[':entry_to'] = $entryTo;
}
// Build final WHERE SQL
$whereSql = "WHERE " . implode(" AND ", $clauses);
if ($pzfact_project_city !== '') {
$whereSql .= ' and pzfact_in_city_limit = 1';
}
// -----------
// COUNT query
// -----------
$sqlCount = "SELECT COUNT(*) AS count
FROM view_pzfacts
{$whereSql}";
$stmtCount = $connection->prepare($sqlCount);
foreach ($params as $k => $v) {
$type = is_int($v) ? PDO::PARAM_INT : PDO::PARAM_STR;
$stmtCount->bindValue($k, $v, $type);
}
$stmtCount->execute();
$recordset = $stmtCount->fetch(PDO::FETCH_ASSOC);
$count = $recordset ? (int) $recordset["count"] : 0;
// ---------------------------
// Pagination logic
// ---------------------------
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 = min($this->pagination_page + 1, (int) ceil($count / $this->pagination_size));
break;
case "last":
$this->pagination_page = (int) ceil($count / $this->pagination_size);
break;
}
$offset = max(0, ($this->pagination_page - 1) * $this->pagination_size);
$start = $offset + 1;
$end = min($count, $start + $this->pagination_size - 1);
// ----------
// DATA query
// ----------
$sqlData = "SELECT view_pzfacts.*
FROM view_pzfacts
{$whereSql}
LIMIT :limit
OFFSET :offset";
$stmtData = $connection->prepare($sqlData);
// Bind the same params again
foreach ($params as $k => $v) {
$type = is_int($v) ? PDO::PARAM_INT : PDO::PARAM_STR;
$stmtData->bindValue($k, $v, $type);
}
$stmtData->bindValue(":limit", (int) $this->pagination_size, PDO::PARAM_INT);
$stmtData->bindValue(":offset", (int) $offset, PDO::PARAM_INT);
$stmtData->execute();
$pzfacts = $this->getTableXML("pzfacts", $stmtData);
// ------------------------------------------------------------------------------------
// Add searched entry_dates for search history
// (keep your original behavior: default to subscription window if user didn't specify)
// ------------------------------------------------------------------------------------
$pzfacts->record->pzfact_entry_date_from = !empty($entryFrom) ? date('m/d/Y', strtotime($entryFrom)) : date('m/d/Y', strtotime($user_subscription_start_date));
$pzfacts->record->pzfact_entry_date_to = !empty($entryTo) ? date('m/d/Y', strtotime($entryTo)) : date('m/d/Y', strtotime($user_subscription_end_date));
// ---------------------
// Pagination attributes
// ---------------------
$pzfacts->addAttribute("count", $count);
$pzfacts->addAttribute("start", $start);
$pzfacts->addAttribute("end", $end);
$pzfacts->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $pzfacts;
}
// ==================================
// Users Total Available Record Count
// ==================================
public function userTotalAvailableRecordCount($user_subscription_start_date, $user_subscription_end_date) {
// determine real date range based upon users subscription start date
if ($user_subscription_start_date <= date('Y-m-d', strtotime('-1 year'))) {
$user_subscription_start_date = date('Y-m-d', strtotime('-1 year'));
}
$SQL = "select count(*) as count
from view_pzfacts
where view_pzfacts.pzfact_entry_date between '{$user_subscription_start_date}' and '{$user_subscription_end_date}' ";
// $counties = (new Counties())->getSubscriptionCounties($_SESSION['subscription_serial']);
//
// $countyNames = [];
//
// foreach ($counties as $county) {
// $countyNames[] = " " . (string) $county->subscriptioncounty_county . " ";
// }
//
// $pzfact_county = ' ' . implode(', ', $countyNames) . ' ';
//
// $SQL .= " and view_pzfacts.pzfact_county in ($pzfact_county) ";
return $this->getTable("userstotalavailablerecords", $SQL);
}
// =====================
// Search Business Facts
// =====================
public function planningAndZoningFactsBasic() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$dateranges = $this->getDateRangeXML();
$content = $this->applyXSL($dateranges, $this->getXSL("pzFactsBasic"));
$this->displayContent($content);
break;
case "results":
$week_start_raw = trim((string) filter_input(INPUT_POST, 'week_start'));
$week_end_raw = trim((string) filter_input(INPUT_POST, 'week_end'));
$week_start_db = $week_start_raw !== '' ? date('Y-m-d', strtotime($week_start_raw)) : null;
$week_end_db = $week_end_raw !== '' ? date('Y-m-d', strtotime($week_end_raw)) : null;
$pzfacts = $this->getPZFactsBasic($week_start_db, $week_end_db);
$dateranges = $this->getDateRangeXML();
$searched = $dateranges->addChild('searchedranges');
$searched->addChild('week_start', $week_start_db ? date('m/d/Y', strtotime($week_start_db)) : '');
$searched->addChild('week_end', $week_end_db ? date('m/d/Y', strtotime($week_end_db)) : '');
$xml = $this->mergeXML($pzfacts, '<XML/>');
$xml = $this->mergeXML($dateranges, $xml);
$content = $this->applyXSL($xml, $this->getXSL("pzFactsBasic"));
$this->displayContent($content);
break;
default:
$this->displayHome();
}
}
public function getDateRangeXML() {
$ranges = $this->getFridayThursdayRanges(2, new DateTimeImmutable('today'));
$xml = new SimpleXMLElement('<ranges/>');
$labels = [
0 => 'week_prior',
1 => 'two_weeks_prior',
];
foreach ($ranges as $i => $range) {
$name = $labels[$i] ?? 'prior_' . ($i + 1);
$node = $xml->addChild($name);
$start = date('m/d/Y', strtotime($range['start']));
$end = date('m/d/Y', strtotime($range['end']));
$node->addChild('start', $start);
$node->addChild('end', $end);
}
$xml->subscription_serial = $_SESSION['subscription_serial'];
return $xml;
}
public function getFridayThursdayRanges(int $weeks = 2, ?DateTimeInterface $today = null): array {
$today = $today ? DateTimeImmutable::createFromInterface($today) : new DateTimeImmutable('today');
// "last thursday" gives the most recent Thursday strictly before today.
// If today IS Thursday, we want today as the end date.
$end = ($today->format('N') === '4') ? $today : $today->modify('last thursday');
$ranges = [];
for ($i = 0; $i < $weeks; $i++) {
$start = $end->modify('-6 days');
$ranges[] = [
'start' => $start->format('Y-m-d'),
'end' => $end->format('Y-m-d'),
];
$end = $start->modify('-1 day'); // move to previous block
}
return $ranges;
}
// ======================================
// Return an Planning/Zoning Facts Object
// ======================================
public function getPZFactsBasic($week_start, $week_end) {
$SQL = "select view_pzfacts.*
from view_pzfacts
where view_pzfacts.pzfact_entry_date between '{$week_start}' and '{$week_end}'
order by view_pzfacts.pzfact_county, view_pzfacts.pzfact_project_name";
return $this->getTable("pzfacts", $SQL);
}
}
?>
+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);
}
}
?>
File diff suppressed because it is too large Load Diff
+380
View File
@@ -0,0 +1,380 @@
<?php
class ProjectTypes 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 ProjectType
// ========
public function addProjectType() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$constants = $this->getConstants();
$content = $this->applyXSL($constants, $this->getXSL("addProjectType"));
$this->displayContent($content);
break;
case "add":
$projecttype_name = filter_input(INPUT_POST, "projecttype_name") ?: "";
$SQL = "insert into projecttypes
( projecttype_name,
projecttype_creator,
projecttype_created )
VALUES ( :projecttype_name,
:projecttype_creator,
:projecttype_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":projecttype_name", $projecttype_name);
$statement->bindValue(":projecttype_creator", $this->current_user_name);
$statement->bindValue(":projecttype_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// =============
// Delete Project Type
// =============
public function deleteProjectType() {
$projecttype_serial = filter_input(INPUT_POST, "projecttype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$projecttype = $this->getProjectType($projecttype_serial);
if ($projecttype->count() == 0) {
$this->logError("Invalid ProjectType ({$projecttype_serial}). " . __METHOD__);
}
$SQL = "delete from projecttypes
where projecttype_serial = {$projecttype_serial}";
$this->executeSQL($SQL);
}
// ============================
// Determine if a ProjectType exists
// ============================
public function projecttypeExists() {
$projecttype_serial = filter_input(INPUT_POST, "projecttype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$projecttype_name = filter_input(INPUT_POST, "projecttype_name") ?: "";
$SQL = "select projecttype_serial
from view_projecttypes
where projecttype_serial != :projecttype_serial
and lower(projecttype_name) = :projecttype_name";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":projecttype_serial", $projecttype_serial);
$statement->bindValue(":projecttype_name", strtolower($projecttype_name));
$statement->execute();
$recordset = $statement->fetchAll(PDO::FETCH_ASSOC);
$exists = (count($recordset) > 0) ? true : false;
echo json_encode($exists);
}
// ======================================
// Determine if a ProjectType is Active (AJAX)
// ======================================
public function projecttypeActive() {
$rdi_projecttype = filter_input(INPUT_POST, "rdi_projecttype") ?: "";
$active = false;
$SQL = "select rdi_projecttype
from rdis
where rdi_projecttype = {$rdi_projecttype}
limit 1";
$workorders = $this->getTable("projecttype", $SQL);
$active = ($workorders->count() > 0) ? true : false;
echo json_encode($active);
}
// =============
// Edit a ProjectType
// =============
public function editProjectType() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$projecttype_serial = filter_input(INPUT_POST, "projecttype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$projecttype = $this->getProjectType($projecttype_serial);
if ($projecttype->count() == 0) {
$this->logError("Invalid ProjectType ({$projecttype_serial}). " . __METHOD__);
}
$constants = $this->getConstants();
$XML = $this->mergeXML($projecttype, "<XML/>");
$XML = $this->mergeXML($constants, $XML);
$content = $this->applyXSL($XML, $this->getXSL("editProjectType"));
$this->displayContent($content);
break;
case "update":
$projecttype_serial = filter_input(INPUT_POST, "projecttype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$projecttype_name = filter_input(INPUT_POST, "projecttype_name") ?: "";
// Verify the ProjectType
$projecttype = $this->getProjectType($projecttype_serial);
if ($projecttype->count() == 0) {
$this->logError("Invalid ProjectType ({$projecttype_serial}). " . __METHOD__);
}
$SQL = "update projecttypes
set projecttype_name = :projecttype_name,
projecttype_creator = :projecttype_creator,
projecttype_created = :projecttype_created
where projecttype_serial = :projecttype_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":projecttype_serial", $projecttype_serial);
$statement->bindValue(":projecttype_name", $projecttype_name);
$statement->bindValue(":projecttype_creator", $this->current_user_name);
$statement->bindValue(":projecttype_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ================================
// Return an Active ProjectTypes Object
// ================================
public function getActiveProjectTypes() {
$SQL = "select view_projecttypes.*
from view_projecttypes
where projecttype_active is true";
return $this->getTable("projecttypes", $SQL);
}
// =======================
// Return an ProjectType Object
// =======================
public function getProjectType($projecttype_serial = 0) {
$SQL = "select view_projecttypes.*
from view_projecttypes
where projecttype_serial = {$projecttype_serial}";
return $this->getTable("projecttypes", $SQL);
}
// ========================
// Return a ProjectTypes Object
// ========================
public function getProjectTypes() {
$SQL = "select view_projecttypes.*
from view_projecttypes";
return $this->getTable("projecttypes", $SQL);
}
// ========================
// Return a ProjectTypes Object
// ========================
public function getProjectTypesByArea($area) {
$SQL = "select view_projecttypes.*
from view_projecttypes
where view_projecttypes.projecttype_area = '{$area}'";
return $this->getTable("projecttypes", $SQL);
}
// ========================
// Return a ProjectTypes Object
// ========================
public function getProjectTypesByName($projecttype_name) {
$SQL = "select view_projecttypes.*
from view_projecttypes
where view_projecttypes.projecttype_name = '{$projecttype_name}'";
return $this->getTable("projecttypes", $SQL);
}
// =============================
// Return a ProjectTypes Page Object
// =============================
public function getProjectTypesPage() {
// Find Criteria
$find_projecttype = filter_input(INPUT_POST, "find_projecttype") ?: "";
$find_projecttype = $this->sanitizeString($find_projecttype);
$find_words = implode("|", explode(" ", $find_projecttype));
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_projecttypes
where projecttype_name regexp :projecttype_name";
$statement = $connection->prepare($SQL);
$statement->bindValue(":projecttype_name", $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_projecttypes.*
from view_projecttypes
where projecttype_name regexp :projecttype_name
order by projecttype_name
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":projecttype_name", $find_words);
$statement->execute();
$projecttypes = $this->getTableXML("projecttypes", $statement);
// Insert Pagination Attributes
$projecttypes->addAttribute("count", $count);
$projecttypes->addAttribute("start", $start);
$projecttypes->addAttribute("end", $end);
$projecttypes->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $projecttypes;
}
// ==============
// Setup ProjectTypes
// ==============
public function setupProjectTypes() {
$projecttypes = $this->getProjectTypesPage();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($projecttypes, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$content = $this->applyXSL($XML, $this->getXSL("setupProjectTypes"));
$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);
}
}
?>
+353
View File
@@ -0,0 +1,353 @@
<?php
class SICCodes 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 SIC Code
// ============
public function addSICCode() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$content = $this->applyXSL("", $this->getXSL("addSICCode"));
$this->displayContent($content);
break;
case "add":
$siccode_code = filter_input(INPUT_POST, "siccode_code") ?: "";
$siccode_description = filter_input(INPUT_POST, "siccode_description") ?: "";
$SQL = "insert into siccodes
( siccode_code,
siccode_description )
VALUES ( :siccode_code,
:siccode_description )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":siccode_code", $siccode_code);
$statement->bindValue(":siccode_description", $siccode_description);
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ===============
// Delete SIC Code
// ===============
public function deleteSICCode() {
$siccode_serial = filter_input(INPUT_POST, "siccode_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$siccode = $this->getSICCode($siccode_serial);
if ($siccode->count() == 0) {
$this->logError("Invalid SIC Code ({$siccode_serial}). " . __METHOD__);
}
$SQL = "delete from siccodes
where siccode_serial = {$siccode_serial}";
$this->executeSQL($SQL);
}
// ============================
// Determine if a SICCode exists
// ============================
public function siccodeExists() {
$siccode_serial = filter_input(INPUT_POST, "siccode_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$siccode_code = filter_input(INPUT_POST, "siccode_code") ?: "";
$SQL = "select siccode_serial
from view_siccodes
where siccode_serial != :siccode_serial
and siccode_code = :siccode_code";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":siccode_serial", $siccode_serial);
$statement->bindValue(":siccode_code", strtolower($siccode_code));
$statement->execute();
$recordset = $statement->fetchAll(PDO::FETCH_ASSOC);
$exists = (count($recordset) > 0) ? true : false;
echo json_encode($exists);
}
// ======================================
// Determine if a SICCode is Active (AJAX)
// ======================================
public function siccodeActive() {
$siccode_serial = filter_input(INPUT_POST, "siccode_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$active = false;
$SQL = "select workorder_siccode
from workorders
where workorder_siccode = {$siccode_serial}
limit 1";
$workorders = $this->getTable("workorders", $SQL);
$active = ($workorders->count() > 0) ? true : false;
echo json_encode($active);
}
// ===============
// Edit a SIC Code
// ===============
public function editSICCode() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$siccode_serial = filter_input(INPUT_POST, "siccode_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$siccode = $this->getSICCode($siccode_serial);
if ($siccode->count() == 0) {
$this->logError("Invalid SIC Code ({$siccode_serial}). " . __METHOD__);
}
$content = $this->applyXSL($siccode, $this->getXSL("editSICCode"));
$this->displayContent($content);
break;
case "update":
$siccode_serial = filter_input(INPUT_POST, "siccode_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$siccode_code = filter_input(INPUT_POST, "siccode_code") ?: "";
$siccode_description = filter_input(INPUT_POST, "siccode_description") ?: "";
// Verify the SIC Code
$siccode = $this->getSICCode($siccode_serial);
if ($siccode->count() == 0) {
$this->logError("Invalid SIC Code ({$siccode_serial}). " . __METHOD__);
}
$SQL = "update siccodes
set siccode_code = :siccode_code,
siccode_description = :siccode_description
where siccode_serial = :siccode_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":siccode_serial", $siccode_serial);
$statement->bindValue(":siccode_code", $siccode_code);
$statement->bindValue(":siccode_description", $siccode_description);
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ================================
// Return an Active SICCodes Object
// ================================
public function getActiveSICCodes() {
$SQL = "select view_siccodes.*
from view_siccodes
where siccode_description is true";
return $this->getTable("siccodes", $SQL);
}
// =========================
// Return an SIC Code Object
// =========================
public function getSICCode($siccode_serial = 0) {
$SQL = "select view_siccodes.*
from view_siccodes
where siccode_serial = {$siccode_serial}";
return $this->getTable("siccodes", $SQL);
}
// =========================
// Return a SIC Codes Object
// =========================
public function getSICCodes() {
$SQL = "select view_siccodes.*
from view_siccodes order by view_siccodes.siccode_description";
return $this->getTable("siccodes", $SQL);
}
// =============================
// Return a SICCodes Page Object
// =============================
public function getSICCodesPage() {
// Find Criteria
$find_siccode = filter_input(INPUT_POST, "find_siccode") ?: "";
$find_siccode = $this->sanitizeString($find_siccode);
$find_words = implode("|", explode(" ", $find_siccode));
$this->pagination_size = filter_input(INPUT_POST, "siccodes_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;
// Record Count
$connection = $this->connect();
$SQL = "select count(*) as count
from view_siccodes
where siccode_code regexp :siccode_code
or siccode_description regexp :siccode_description";
$statement = $connection->prepare($SQL);
$statement->bindValue(":siccode_code", $find_words);
$statement->bindValue(":siccode_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_siccodes.*
from view_siccodes
where siccode_code regexp :siccode_code
or siccode_description regexp :siccode_description
order by siccode_code
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":siccode_code", $find_words);
$statement->bindValue(":siccode_description", $find_words);
$statement->execute();
$siccodes = $this->getTableXML("siccodes", $statement);
// Insert Pagination Attributes
$siccodes->addAttribute("count", $count);
$siccodes->addAttribute("start", $start);
$siccodes->addAttribute("end", $end);
$siccodes->addAttribute("page", $this->pagination_page);
$_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;
return $siccodes;
}
// ===============
// Setup SIC Codes
// ===============
public function setupSICCodes() {
$siccodes = $this->getSICCodesPage();
$popovers = (new Popovers())->getPopovers();
$XML = $this->mergeXML($siccodes, "<XML/>");
$XML = $this->mergeXML($popovers, $XML);
$content = $this->applyXSL($XML, $this->getXSL("setupSICCodes"));
$this->displayContent($content);
}
}
?>
+260
View File
@@ -0,0 +1,260 @@
<?php
class SearchHistory extends Base {
// Variables
private $current_user_serial = 0;
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_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] ?? "";
}
// ============================
// Save Users Search Parameters
// ============================
public function saveUserSearchParameters($searchpayload) {
$user = $this->current_user_serial;
$subscription_serial = $searchpayload['subscription_serial'];
echo $subscription_serial;
die();
switch ($subscription_serial) {
case 1:
case 2:
case 3:
case 4:
$searchcriteria = json_encode(array_filter($searchpayload, fn($key) => str_starts_with($key, 'permitfact_'), ARRAY_FILTER_USE_KEY));
break;
case 5:
$searchcriteria = json_encode(array_filter($searchpayload, fn($key) => str_starts_with($key, 'pzfact_'), ARRAY_FILTER_USE_KEY));
break;
case 7:
case 10:
$searchcriteria = json_encode(array_filter($searchpayload, fn($key) => str_starts_with($key, 'businessfact_'), ARRAY_FILTER_USE_KEY));
break;
default :
return;
}
$SQL = "insert into searchhistories
( searchhistory_user,
searchhistory_subscription,
searchhistory_parameters,
searchhistory_creator,
searchhistory_created )
values ( :searchhistory_user,
:searchhistory_subscription,
:searchhistory_parameters,
:searchhistory_creator,
:searchhistory_created )";
$connection = $this->connect();
$statement = $connection->prepare($SQL);
$statement->bindValue(":searchhistory_user", $user);
$statement->bindValue(":searchhistory_subscription", $subscription_serial);
$statement->bindValue(":searchhistory_parameters", $searchcriteria);
$statement->bindValue(":searchhistory_creator", $this->current_user_name);
$statement->bindValue(":searchhistory_created", $this->getTimestamp());
$statement->execute();
}
// ============================
// Save Users Search Parameters
// ============================
public function updateUserSearchParameters($searchpayload) {
$user = $this->current_user_serial;
$subscription_serial = $searchpayload['subscription_serial'];
switch ($subscription_serial) {
case 1:
case 2:
case 3:
case 4:
$searchcriteria = json_encode(array_filter($searchpayload, fn($key) => str_starts_with($key, 'permitfact_'), ARRAY_FILTER_USE_KEY));
break;
case 5:
$searchcriteria = json_encode(array_filter($searchpayload, fn($key) => str_starts_with($key, 'pzfact_'), ARRAY_FILTER_USE_KEY));
break;
case 7:
case 10:
$searchcriteria = json_encode(array_filter($searchpayload, fn($key) => str_starts_with($key, 'businessfact_'), ARRAY_FILTER_USE_KEY));
break;
default :
return;
}
$SQL = "update searchhistories
set searchhistory_parameters = :searchhistory_parameters,
searchhistory_changer = :searchhistory_changer,
searchhistory_changed = :searchhistory_changed
where searchhistory_user = :searchhistory_user
and searchhistory_subscription = :searchhistory_subscription";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":searchhistory_parameters", $searchcriteria);
$statement->bindValue(":searchhistory_changer", $this->current_user_name);
$statement->bindValue(":searchhistory_changed", $this->getTimestamp());
$statement->bindValue(":searchhistory_user", $user);
$statement->bindValue(":searchhistory_subscription", $subscription_serial);
$statement->execute();
}
// ============================
// Gets Users Search Parameters
// ============================
public function getUsersPreviousSearchParameters($user, $subscription) {
$SQL = "select view_searchhistories.*
from view_searchhistories
where view_searchhistories.searchhistory_user = {$user}
and view_searchhistories.searchhistory_subscription = {$subscription}";
$recordset = $this->getTable("searchhistory", $SQL);
return $this->materializeSearchHistoryParameters($recordset);
}
// ============================
// Gets Users Search Parameters
// ============================
public function materializeSearchHistoryParameters(SimpleXMLElement $SXE): SimpleXMLElement {
if (!isset($SXE->record)) {
return $SXE;
}
// Keys that should ALWAYS materialize as <key><id>..</id></key>
// even if there is only one value.
$multiSelectKeys = [
'permitfact_project_city', 'permitfact_county', 'permitfact_project_type', 'permitfact_work_type', 'permitfact_building_type',
'businessfact_city', 'businessfact_city', 'businessfact_county', 'businessfact_action', 'businessfact_business_class',
'pzfact_project_city', 'pzfact_project_city', 'pzfact_project_city', 'pzfact_project_city'
];
foreach ($SXE->record as $record) {
if (!isset($record->searchhistory_parameters)) {
continue;
}
$json = trim((string) $record->searchhistory_parameters);
if ($json === '') {
continue;
}
$data = json_decode($json, true);
if (!is_array($data)) {
continue;
}
// Clear existing text content
$record->searchhistory_parameters[0] = null;
foreach ($data as $key => $value) {
$nodeName = preg_replace('/[^A-Za-z0-9_\-:.]/', '_', (string) $key);
$isMulti = in_array($key, $multiSelectKeys, true);
// If this is a multi-select key:
// - Accept arrays (preferred)
// - Accept CSV strings (legacy)
// - Accept single scalar and wrap it in <id>
if ($isMulti) {
$parent = $record->searchhistory_parameters->addChild($nodeName);
if (is_array($value)) {
$parts = $value;
} else {
$valueStr = trim((string) $value);
// empty -> create empty parent node and move on
if ($valueStr === '') {
continue;
}
// CSV or single
$parts = (strpos($valueStr, ',') !== false) ? explode(',', $valueStr) : [$valueStr];
}
$parts = array_values(array_filter(array_map('trim', $parts), fn($v) => $v !== ''));
foreach ($parts as $p) {
$parent->addChild('id', htmlspecialchars($p, ENT_XML1 | ENT_QUOTES, 'UTF-8'));
}
continue;
}
// Non-multi-select keys (same as your current behavior)
if (is_string($value) && strpos($value, ',') !== false) {
$parent = $record->searchhistory_parameters->addChild($nodeName);
$parts = array_values(array_filter(array_map('trim', explode(',', $value)), fn($v) => $v !== ''));
foreach ($parts as $p) {
$parent->addChild('id', htmlspecialchars($p, ENT_XML1 | ENT_QUOTES, 'UTF-8'));
}
} else {
$record->searchhistory_parameters->addChild(
$nodeName,
htmlspecialchars((string) $value, ENT_XML1 | ENT_QUOTES, 'UTF-8')
);
}
}
}
return $SXE;
}
}
?>
+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);
}
}
?>
+981
View File
@@ -0,0 +1,981 @@
<?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;
}
// =========================
// Go To Subscription Driver
// =========================
public function goToSubscription() {
$subscription_serial = (integer) filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$usersubscription_serial = (integer) filter_input(INPUT_POST, "usersubscription_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 1:
case 2:
case 3:
case 4:
$_SESSION['subscription_serial'] = $subscription_serial;
$_SESSION['usersubscription_serial'] = $usersubscription_serial;
(new PermitFacts())->searchPermitFacts();
break;
case 5:
$_SESSION['subscription_serial'] = $subscription_serial;
$_SESSION['usersubscription_serial'] = $usersubscription_serial;
(new PlanningAndZoningFacts())->searchPlanningAndZoningFacts();
break;
case 12:
$_SESSION['subscription_serial'] = $subscription_serial;
$_SESSION['usersubscription_serial'] = $usersubscription_serial;
(new PlanningAndZoningFacts())->planningAndZoningFactsBasic();
break;
case 7:
case 10:
$_SESSION['subscription_serial'] = $subscription_serial;
$_SESSION['usersubscription_serial'] = $usersubscription_serial;
(new BusinessFacts())->searchBusinessFacts();
break;
case 11:
$_SESSION['subscription_serial'] = $subscription_serial;
$_SESSION['usersubscription_serial'] = $usersubscription_serial;
(new BusinessFacts())->businessFactsBasic();
break;
}
}
// ===================
// 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);
}
// ====================
// Subscription Summary
// ====================
public function subscriptionSummary() {
$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__);
}
$counties = $this->getSubscriptionCountiesByMarket($subscription->record->subscription_serial);
$cities = $this->getSubscriptionCitiesByMarket($subscription->record->subscription_serial);
$XML = $this->mergeXML($subscription, "<XML/>");
$XML = $this->mergeXML($counties, $XML);
$XML = $this->mergeXML($cities, $XML);
$content = $this->applyXSL($XML, $this->getXSL("subscriptionSummary"));
$this->displayContent($content);
}
// ===================
// Users Subscriptions
// ===================
public function usersSubscriptions() {
$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);
}
// ================
// Add Subscription
// ================
public function addSubscription() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$dropdowns = (new Dropdowns())->getDropdowns();
$content = $this->applyXSL($dropdowns, $this->getXSL("addSubscription"));
$this->displayContent($content);
break;
case "add":
$subscription_title = filter_input(INPUT_POST, "subscription_title") ?: "";
$subscription_service_level = filter_input(INPUT_POST, "subscription_service_level", FILTER_SANITIZE_NUMBER_INT) ?: "";
$subscription_market = filter_input(INPUT_POST, "subscription_market", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$SQL = "insert into subscriptions
( subscription_title,
subscription_service_level,
subscription_market,
subscription_creator,
subscription_created )
VALUES ( :subscription_title,
:subscription_service_level,
:subscription_market,
:subscription_creator,
:subscription_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":subscription_title", $subscription_title);
$statement->bindValue(":subscription_service_level", $subscription_service_level);
$statement->bindValue(":subscription_market", $subscription_market);
$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__);
}
$dropdowns = (new Dropdowns())->getDropdowns();
$XML = $this->mergeXML($dropdowns, "<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_service_level = filter_input(INPUT_POST, "subscription_service_level", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription_market = filter_input(INPUT_POST, "subscription_market", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$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_service_level = :subscription_service_level,
subscription_market = :subscription_market
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_service_level", $subscription_service_level);
$statement->bindValue(":subscription_market", $subscription_market);
$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_start_dates = filter_input(INPUT_POST, "subscription_start_date", FILTER_DEFAULT, 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_start_date" => date("Y-m-d", strtotime($subscription_start_dates[$index] ?? "")),
"usersubscription_end_date" => date("Y-m-d", strtotime($subscription_end_dates[$index] ?? ""))
);
}
$SQL = "insert into usersubscriptions
( usersubscription_user,
usersubscription_subscription,
usersubscription_start_date,
usersubscription_end_date,
usersubscription_creator,
usersubscription_created )
VALUES ( :usersubscription_user,
:usersubscription_subscription,
:usersubscription_start_date,
:usersubscription_end_date,
:usersubscription_creator,
:usersubscription_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":usersubscription_user", $user_serial);
$statement->bindValue(":usersubscription_creator", $this->current_user_name);
$statement->bindValue(":usersubscription_created", $this->getTimestamp());
foreach ($subscriptions as $subscription) {
$subscription_serial = $subscription['usersubscription_subscription'];
$start_date = $subscription['usersubscription_start_date'];
$end_date = $subscription['usersubscription_end_date'];
$statement->bindValue(":usersubscription_subscription", $subscription_serial);
$statement->bindValue(":usersubscription_start_date", $start_date);
$statement->bindValue(":usersubscription_end_date", $end_date);
$statement->execute();
}
break;
default:
$this->displayHome();
}
}
// ==========================
// Add County To Subscription
// ==========================
public function addCountyToSubscription() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$subscription_serial = filter_input(INPUT_POST, "subscription_reference", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription = $this->getSubscription($subscription_serial);
if ($subscription->count() === 0) {
$this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
}
$counties = (new Counties())->getCounties();
$XML = $this->mergeXML($subscription, "<xml/>");
$XML = $this->mergeXML($counties, $XML);
$content = $this->applyXSL($XML, $this->getXSL("addCountyToSubscription"));
$this->displayContent($content);
break;
case "add":
$subscription_serial = filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$county_serial = filter_input(INPUT_POST, "county_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$SQL = "insert into subscriptioncounties
( subscriptioncounty_subscription,
subscriptioncounty_county,
subscriptioncounty_creator,
subscriptioncounty_created )
VALUES ( :subscriptioncounty_subscription,
:subscriptioncounty_county,
:subscriptioncounty_creator,
:subscriptioncounty_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":subscriptioncounty_subscription", $subscription_serial);
$statement->bindValue(":subscriptioncounty_county", $county_serial);
$statement->bindValue(":subscriptioncounty_creator", $this->current_user_name);
$statement->bindValue(":subscriptioncounty_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ===========================
// Edit a Subscriptions County
// ===========================
public function editSubscriptionCounty() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$subscriptioncounty_serial = filter_input(INPUT_POST, "subscriptioncounty_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscriptioncounty = $this->getSubscriptionCounty($subscriptioncounty_serial);
if ($subscriptioncounty->count() === 0) {
$this->logError("Invalid Subscription County ({$subscriptioncounty_serial}): " . __METHOD__);
}
$counties = (new Counties())->getCounties();
$XML = $this->mergeXML($subscriptioncounty, "<xml/>");
$XML = $this->mergeXML($counties, $XML);
$content = $this->applyXSL($XML, $this->getXSL("editSubscriptionCounty"));
$this->displayContent($content);
break;
case "update":
$subscriptioncounty_serial = filter_input(INPUT_POST, "subscriptioncounty_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$county_serial = filter_input(INPUT_POST, "county_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$SQL = "update subscriptioncounties
set subscriptioncounty_county = :subscriptioncounty_county,
subscriptioncounty_changer = :subscriptioncounty_changer,
subscriptioncounty_changed = :subscriptioncounty_changed
where subscriptioncounty_serial = :subscriptioncounty_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":subscriptioncounty_serial", $subscriptioncounty_serial);
$statement->bindValue(":subscriptioncounty_county", $county_serial);
$statement->bindValue(":subscriptioncounty_changer", $this->current_user_name);
$statement->bindValue(":subscriptioncounty_changed", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ==========================
// Delete Subscription County
// ==========================
public function deleteSubscriptionCounty() {
$subscriptioncounty_serial = filter_input(INPUT_POST, "subscriptioncounty_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscriptioncounty = $this->getSubscriptionCounty($subscriptioncounty_serial);
if ($subscriptioncounty->count() == 0) {
$this->logError("Invalid Subscription County ({$subscriptioncounty_serial}). " . __METHOD__);
}
$SQL = "delete from subscriptioncounties where subscriptioncounty_serial = {$subscriptioncounty_serial}";
$this->executeSQL($SQL);
}
// ===================================
// Return a Subscription County Object
// ===================================
public function getSubscriptionCounty($subscriptioncounty_serial = 0) {
$SQL = "select view_subscriptioncounties.*
from view_subscriptioncounties
where subscriptioncounty_serial = {$subscriptioncounty_serial}";
return $this->getTable("subscriptioncounty", $SQL);
}
// ========================
// Add City To Subscription
// ========================
public function addCityToSubscription() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$subscription_serial = filter_input(INPUT_POST, "subscription_reference", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription = $this->getSubscription($subscription_serial);
if ($subscription->count() === 0) {
$this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
}
$cities = (new Cities())->getCities();
$XML = $this->mergeXML($subscription, "<xml/>");
$XML = $this->mergeXML($cities, $XML);
$content = $this->applyXSL($XML, $this->getXSL("addCityToSubscription"));
$this->displayContent($content);
break;
case "add":
$subscription_serial = filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$city_serial = filter_input(INPUT_POST, "city_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$SQL = "insert into subscriptioncities
( subscriptioncity_subscription,
subscriptioncity_city,
subscriptioncity_creator,
subscriptioncity_created )
VALUES ( :subscriptioncity_subscription,
:subscriptioncity_city,
:subscriptioncity_creator,
:subscriptioncity_created )";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":subscriptioncity_subscription", $subscription_serial);
$statement->bindValue(":subscriptioncity_city", $city_serial);
$statement->bindValue(":subscriptioncity_creator", $this->current_user_name);
$statement->bindValue(":subscriptioncity_created", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ===========================
// Edit a Subscriptions City
// ===========================
public function editSubscriptionCity() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$subscriptioncity_serial = filter_input(INPUT_POST, "subscriptioncity_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscriptioncity = $this->getSubscriptionCity($subscriptioncity_serial);
if ($subscriptioncity->count() === 0) {
$this->logError("Invalid Subscription City ({$subscriptioncity_serial}): " . __METHOD__);
}
$cities = (new Cities())->getCities();
$XML = $this->mergeXML($subscriptioncity, "<xml/>");
$XML = $this->mergeXML($cities, $XML);
$content = $this->applyXSL($XML, $this->getXSL("editSubscriptionCity"));
$this->displayContent($content);
break;
case "update":
$subscriptioncity_serial = filter_input(INPUT_POST, "subscriptioncity_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$city_serial = filter_input(INPUT_POST, "city_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$SQL = "update subscriptioncities
set subscriptioncity_city = :subscriptioncity_city,
subscriptioncity_changer = :subscriptioncity_changer,
subscriptioncity_changed = :subscriptioncity_changed
where subscriptioncity_serial = :subscriptioncity_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":subscriptioncity_serial", $subscriptioncity_serial);
$statement->bindValue(":subscriptioncity_city", $city_serial);
$statement->bindValue(":subscriptioncity_changer", $this->current_user_name);
$statement->bindValue(":subscriptioncity_changed", $this->getTimestamp());
$statement->execute();
break;
default:
$this->displayHome();
}
}
// ==========================
// Delete Subscription City
// ==========================
public function deleteSubscriptionCity() {
$subscriptioncity_serial = filter_input(INPUT_POST, "subscriptioncity_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscriptioncity = $this->getSubscriptionCity($subscriptioncity_serial);
if ($subscriptioncity->count() == 0) {
$this->logError("Invalid Subscription City ({$subscriptioncity_serial}). " . __METHOD__);
}
$SQL = "delete from subscriptioncities where subscriptioncity_serial = {$subscriptioncity_serial}";
$this->executeSQL($SQL);
}
// ===================================
// Return a Subscription City Object
// ===================================
public function getSubscriptionCity($subscriptioncity_serial = 0) {
$SQL = "select view_subscriptioncities.*
from view_subscriptioncities
where subscriptioncity_serial = {$subscriptioncity_serial}";
return $this->getTable("subscriptioncity", $SQL);
}
// =========================
// 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->getSubscriptionsPage();
$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":
$usersubscription_serial = filter_input(INPUT_POST, "usersubscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription_start_date = filter_input(INPUT_POST, "subscription_start_date") ?: "";
$subscription_end_date = filter_input(INPUT_POST, "subscription_end_date") ?: "";
$subscription_start_date = date("Y-m-d", strtotime($subscription_start_date));
$subscription_end_date = date("Y-m-d", strtotime($subscription_end_date));
$SQL = "update usersubscriptions
set usersubscription_start_date = :usersubscription_start_date,
usersubscription_end_date = :usersubscription_end_date,
usersubscription_changer = :usersubscription_changer,
usersubscription_changed = :usersubscription_changed
where usersubscription_serial = :usersubscription_serial";
$statement = $this->connect()->prepare($SQL);
$statement->bindValue(":usersubscription_start_date", $subscription_start_date);
$statement->bindValue(":usersubscription_end_date", $subscription_end_date);
$statement->bindValue(":usersubscription_serial", $usersubscription_serial);
$statement->bindValue(":usersubscription_changer", $this->current_user_name);
$statement->bindValue(":usersubscription_changed", $this->getTimestamp());
$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_service_level regexp :subscription_service_level
or subscription_market regexp :subscription_market";
$statement = $connection->prepare($SQL);
$statement->bindValue(":subscription_title", $find_words);
$statement->bindValue(":subscription_service_level", $find_words);
$statement->bindValue(":subscription_market", $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_service_level regexp :subscription_service_level
or subscription_market regexp :subscription_market
order by subscription_title
limit {$this->pagination_size}
offset {$offset}";
$statement = $connection->prepare($SQL);
$statement->bindValue(":subscription_title", $find_words);
$statement->bindValue(":subscription_service_level", $find_words);
$statement->bindValue(":subscription_market", $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;
}
// ============================
// Return a Users Subscriptions
// ============================
public function getUsersActiveSubscriptions($user_serial) {
$SQL = "select view_usersubscriptions.*
from view_usersubscriptions
where usersubscription_user = {$user_serial}
order by view_usersubscriptions.subscription_full_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);
}
// ========================================
// Return a Subscriptions Assigned Counties
// ========================================
public function getSubscriptionCountiesByMarket($subscription_serial) {
$SQL = "select view_subscriptioncounties.*
from view_subscriptioncounties
where subscriptioncounty_subscription = {$subscription_serial}";
return $this->getTable("subscriptioncounties", $SQL);
}
// ======================================
// Return a Subscriptions Assigned Cities
// ======================================
public function getSubscriptionCitiesByMarket($subscription_serial) {
$SQL = "select view_subscriptioncities.*
from view_subscriptioncities
where subscriptioncity_subscription = {$subscription_serial}";
return $this->getTable("subscriptioncities", $SQL);
}
}
?>
+855
View File
@@ -0,0 +1,855 @@
<?php
// ===========
// Users Class
// ===========
class Users extends Base {
// Variables
private $current_user_id = "";
private $current_user_serial = "";
private $current_user_name = "";
private $current_user_client_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->current_user_client_name = $_SESSION[self::USER_CLIENT_NAME] ?? "";
$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())->getUsersActiveSubscriptions($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}'
// or user_client_name = '{$user_name}'";
//
// return $this->getTable("user", $SQL);
$SQL = "select view_users.*
from view_users
where user_id = ?
or user_name = ?";
$users = $this->getTable("users", $SQL, array($user_name, $user_name));
return $users;
}
// ======================
// 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("allusers", $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);
}
// ========================
// Login to the application
// ========================
public function login() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$XSLParms["BTN_SUBMIT"] = "main.php?action=Users.login&step=authenticate";
$XSLParms["INVALID_SIGNIN"] = "FALSE";
echo $this->applyXSL("", $this->getXSL("signIn"), $XSLParms);
exit();
break;
case "authenticate":
$user_name = filter_input(INPUT_POST, "user_name") ?: "";
$user_password = filter_input(INPUT_POST, "user_password") ?: "";
// The User must exist in the Users Table
$user = $this->getUserByUserName($user_name);
if ($user->count() > 0) {
// Automatically deny authentication if user is inactive
if ($user->record->user_active == 0) {
$XSLParms["BTN_SUBMIT"] = "main.php?action=Users.signIn&step=authenticate";
$XSLParms["INVALID_SIGNIN"] = "TRUE";
echo $this->applyXSL("", $this->getXSL("signIn"), $XSLParms);
die();
}
$stored_hashed_password = $user->record->user_password;
// Verify Password
if (password_verify($user_password, $stored_hashed_password)) {
$_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_CLIENT_NAME] = (string) $user->record->user_client_name;
$_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] ?? "";
// Determine if this is a System Administrator
if (count($this->getSettings()->xpath("//SystemAdministrator[. = '{$user_name}']")) > 0) {
$_SESSION[self::USER_ROLE] = "System Administrator";
}
// Create Journal Entry and finish
(new Journal())->journalEntry("{$_SESSION[self::USER_NAME]} logged in ({$_SESSION[self::USER_ROLE]}).");
$this->updateLogin();
header("Location: ./");
exit();
} else {
$XSLParms["BTN_SUBMIT"] = "main.php?action=Users.signIn&step=authenticate";
$XSLParms["INVALID_SIGNIN"] = "TRUE";
echo $this->applyXSL("", $this->getXSL("signIn"), $XSLParms);
die();
}
} else {
$XSLParms["BTN_SUBMIT"] = "main.php?action=Users.signIn&step=authenticate";
$XSLParms["INVALID_SIGNIN"] = "TRUE";
echo $this->applyXSL("", $this->getXSL("signIn"), $XSLParms);
die();
}
break;
default:
// User NOT Validated.
header("Location: ./");
exit();
}
}
// ===============
// 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 Object
// =====================
public function getUserSubscription($usersubscription_serial) {
$SQL = "select view_usersubscriptions.*
from view_usersubscriptions
where view_usersubscriptions.usersubscription_serial = {$usersubscription_serial}";
return $this->getTable("usersubscription", $SQL);
}
// =========
// Copy User
// =========
public function copyUser() {
$step = filter_input(INPUT_POST, "step") ?: "prompt";
switch ($step) {
case "prompt":
$user_serial = filter_input(INPUT_POST, "copyUser_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$copy_from_user = $this->getUser($user_serial);
$subscriptions = (new Subscriptions())->getUsersActiveSubscriptions($user_serial);
$users = $this->getUsers();
$XML = $this->mergeXML($copy_from_user, "<XML/>");
$XML = $this->mergeXML($subscriptions, $XML);
$XML = $this->mergeXML($users, $XML);
$content = $this->applyXSL($XML, $this->getXSL("copyUser"));
$this->displayContent($content);
break;
case "copy":
$receiving_user_serial = filter_input(INPUT_POST, "receiving_user_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
$subscription_serials = filter_input(INPUT_POST, "subscriptions", FILTER_SANITIZE_NUMBER_INT, FILTER_REQUIRE_ARRAY) ?: array();
$subscription_start_dates = filter_input(INPUT_POST, "subscription_start_date", FILTER_DEFAULT, 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_start_date" => date("Y-m-d", strtotime($subscription_start_dates[$index] ?? "")),
"usersubscription_end_date" => date("Y-m-d", strtotime($subscription_end_dates[$index] ?? ""))
);
}
// Add the Subscriptions to Receiving User
$connection = $this->connect();
$SQL = "insert into usersubscriptions
( usersubscription_user,
usersubscription_subscription,
usersubscription_start_date,
usersubscription_end_date,
usersubscription_creator,
usersubscription_created )
values ( :usersubscription_user,
:usersubscription_subscription,
:usersubscription_start_date,
:usersubscription_end_date,
:usersubscription_creator,
:usersubscription_created )";
$statement = $connection->prepare($SQL);
$statement->bindValue(":usersubscription_user", $receiving_user_serial);
$statement->bindValue(":usersubscription_creator", $this->current_user_name);
$statement->bindValue(":usersubscription_created", $this->getTimestamp());
foreach ($subscriptions as $subscription) {
$subscription_serial = $subscription['usersubscription_subscription'];
$start_date = $subscription['usersubscription_start_date'];
$end_date = $subscription['usersubscription_end_date'];
$statement->bindValue(":usersubscription_subscription", $subscription_serial);
$statement->bindValue(":usersubscription_start_date", $start_date);
$statement->bindValue(":usersubscription_end_date", $end_date);
$statement->execute();
}
break;
default:
$this->displayHome();
}
}
// ====================================
// 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);
}
}
?>