ソースを参照

Initial commit.

Alan Lam 8 年 前
コミット
99e3f34fcc
100 ファイル変更、4895 行追加、0 行削除
  1. 6 0
      .gitignore
  2. 39 0
      Gulpfile.js
  3. 5 0
      composer.json
  4. 84 0
      composer.lock
  5. 32 0
      config.template.php
  6. 11 0
      controllers/.template.php
  7. 11 0
      controllers/404.php
  8. 11 0
      controllers/503.php
  9. 40 0
      controllers/account.php
  10. 68 0
      controllers/address_add.php
  11. 60 0
      controllers/address_edit.php
  12. 15 0
      controllers/addresses.php
  13. 11 0
      controllers/become_a_tester.php
  14. 11 0
      controllers/contact.php
  15. 19 0
      controllers/customer_view.php
  16. 14 0
      controllers/customers.php
  17. 11 0
      controllers/home.php
  18. 11 0
      controllers/jobs.php
  19. 73 0
      controllers/location_add.php
  20. 59 0
      controllers/location_edit.php
  21. 36 0
      controllers/location_view.php
  22. 17 0
      controllers/locations.php
  23. 43 0
      controllers/log_in.php
  24. 9 0
      controllers/log_out.php
  25. 5 0
      controllers/ping.php
  26. 11 0
      controllers/privacy_policy.php
  27. 53 0
      controllers/project.php
  28. 108 0
      controllers/project_add.php
  29. 241 0
      controllers/project_ajax.php
  30. 16 0
      controllers/projects.php
  31. 98 0
      controllers/register.php
  32. 11 0
      controllers/services.php
  33. 69 0
      controllers/settings.php
  34. 85 0
      controllers/submit_id.php
  35. 25 0
      controllers/template.php
  36. 52 0
      controllers/template_add.php
  37. 16 0
      controllers/templates.php
  38. 319 0
      controllers/test.php
  39. 18 0
      controllers/test_file.php
  40. 35 0
      controllers/test_result.php
  41. 45 0
      controllers/tests.php
  42. 16 0
      controllers/user.php
  43. 61 0
      controllers/user_edit.php
  44. 60 0
      controllers/user_verify.php
  45. 27 0
      controllers/user_verify_image.php
  46. 31 0
      controllers/users.php
  47. 72 0
      emails/registration.html
  48. 16 0
      engine/.model.template.php
  49. 77 0
      engine/constraint.php
  50. 79 0
      engine/core.php
  51. 56 0
      engine/customer.php
  52. 198 0
      engine/db.php
  53. 82 0
      engine/email.php
  54. 102 0
      engine/form.php
  55. 25 0
      engine/form_exception.php
  56. 87 0
      engine/geolocation.php
  57. 14 0
      engine/html.php
  58. 180 0
      engine/http.php
  59. 62 0
      engine/image.php
  60. 45 0
      engine/json.php
  61. 33 0
      engine/location.php
  62. 453 0
      engine/model.php
  63. 67 0
      engine/project.php
  64. 20 0
      engine/project_location.php
  65. 30 0
      engine/session.php
  66. 49 0
      engine/site_session_handler.php
  67. 99 0
      engine/template.php
  68. 121 0
      engine/test.php
  69. 16 0
      engine/test_value.php
  70. 167 0
      engine/user.php
  71. 38 0
      engine/user_address.php
  72. 20 0
      engine/user_customer.php
  73. 16 0
      engine/user_file.php
  74. 357 0
      engine/util.php
  75. 23 0
      engine/view.php
  76. 61 0
      initialise.php
  77. 97 0
      json/default_template.json
  78. 24 0
      package.json
  79. BIN
      psd/marker.psd
  80. BIN
      psd/required.psd
  81. 6 0
      public/.htaccess
  82. 5 0
      public/css/bootstrap.min.css
  83. BIN
      public/img/bg_required.png
  84. BIN
      public/img/blank.png
  85. BIN
      public/img/blank_carousel.png
  86. BIN
      public/img/gaming_machine.jpg
  87. BIN
      public/img/icon.png
  88. BIN
      public/img/join_us.jpg
  89. BIN
      public/img/logo.png
  90. BIN
      public/img/markers/building-blue.png
  91. BIN
      public/img/markers/building-green.png
  92. BIN
      public/img/markers/building-grey.png
  93. BIN
      public/img/markers/building-orange.png
  94. BIN
      public/img/markers/building-pink.png
  95. BIN
      public/img/markers/building-red.png
  96. BIN
      public/img/markers/user-green.png
  97. BIN
      public/img/markers/user-grey.png
  98. BIN
      public/img/markers/user-orange.png
  99. BIN
      public/img/markers/user-red.png
  100. BIN
      public/img/services_age_related.png

+ 6 - 0
.gitignore

@@ -0,0 +1,6 @@
+config.php
+files/
+node_modules/
+vendor/
+reference/
+logs/

+ 39 - 0
Gulpfile.js

@@ -0,0 +1,39 @@
+var gulp = require("gulp");
+var sass = require("gulp-sass");
+var autoprefixer = require("gulp-autoprefixer");
+var cleancss = require("gulp-clean-css");
+var rename = require("gulp-rename");
+
+var input = "scss/*.scss";
+var output = "public/css";
+
+var sassOptions = {
+	"errLogToConsole": true,
+	"outputStyle": "expanded"
+};
+
+var autoprefixerOptions = {
+	"browsers": ["last 2 versions", "ie >= 9", "and_chr >= 2.3"]
+};
+
+gulp.task("sass", function() {
+	return gulp
+		.src(input)
+		.pipe(sass(sassOptions).on("error", sass.logError))
+		.pipe(autoprefixer(autoprefixerOptions))
+		.pipe(cleancss())
+		.pipe(rename({
+			"suffix": ".min"
+		}))
+		.pipe(gulp.dest(output));
+});
+
+gulp.task("watch", function() {
+	return gulp
+		.watch(input, ["sass"])
+		.on("change", function(event) {
+			console.log("File " + event.path + " was " + event.type + ", running tasks...");
+		});
+});
+
+gulp.task("default", ["sass", "watch"]);

+ 5 - 0
composer.json

@@ -0,0 +1,5 @@
+{
+    "require": {
+        "phpmailer/phpmailer": "^6.0"
+    }
+}

+ 84 - 0
composer.lock

@@ -0,0 +1,84 @@
+{
+    "_readme": [
+        "This file locks the dependencies of your project to a known state",
+        "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
+        "This file is @generated automatically"
+    ],
+    "content-hash": "6d67203b6e9fc952ae681c538683a497",
+    "packages": [
+        {
+            "name": "phpmailer/phpmailer",
+            "version": "v6.0.3",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/PHPMailer/PHPMailer.git",
+                "reference": "44d49bab5ab1fef721d3ee07e75dc0865ddf4cc6"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/44d49bab5ab1fef721d3ee07e75dc0865ddf4cc6",
+                "reference": "44d49bab5ab1fef721d3ee07e75dc0865ddf4cc6",
+                "shasum": ""
+            },
+            "require": {
+                "ext-ctype": "*",
+                "ext-filter": "*",
+                "php": ">=5.5.0"
+            },
+            "require-dev": {
+                "doctrine/annotations": "1.2.*",
+                "friendsofphp/php-cs-fixer": "^2.2",
+                "phpdocumentor/phpdocumentor": "2.*",
+                "phpunit/phpunit": "^4.8 || ^5.7",
+                "zendframework/zend-eventmanager": "3.0.*",
+                "zendframework/zend-i18n": "2.7.3",
+                "zendframework/zend-serializer": "2.7.*"
+            },
+            "suggest": {
+                "ext-mbstring": "Needed to send email in multibyte encoding charset",
+                "hayageek/oauth2-yahoo": "Needed for Yahoo XOAUTH2 authentication",
+                "league/oauth2-google": "Needed for Google XOAUTH2 authentication",
+                "psr/log": "For optional PSR-3 debug logging",
+                "stevenmaguire/oauth2-microsoft": "Needed for Microsoft XOAUTH2 authentication",
+                "symfony/polyfill-mbstring": "To support UTF-8 if the Mbstring PHP extension is not enabled (^1.2)"
+            },
+            "type": "library",
+            "autoload": {
+                "psr-4": {
+                    "PHPMailer\\PHPMailer\\": "src/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "LGPL-2.1"
+            ],
+            "authors": [
+                {
+                    "name": "Jim Jagielski",
+                    "email": "jimjag@gmail.com"
+                },
+                {
+                    "name": "Marcus Bointon",
+                    "email": "phpmailer@synchromedia.co.uk"
+                },
+                {
+                    "name": "Andy Prevost",
+                    "email": "codeworxtech@users.sourceforge.net"
+                },
+                {
+                    "name": "Brent R. Matzelle"
+                }
+            ],
+            "description": "PHPMailer is a full-featured email creation and transfer class for PHP",
+            "time": "2018-01-05T13:19:58+00:00"
+        }
+    ],
+    "packages-dev": [],
+    "aliases": [],
+    "minimum-stability": "stable",
+    "stability-flags": [],
+    "prefer-stable": false,
+    "prefer-lowest": false,
+    "platform": [],
+    "platform-dev": []
+}

+ 32 - 0
config.template.php

@@ -0,0 +1,32 @@
+<?php
+
+define("SESSION_NAME", "name");
+
+define("DB_HOST", "");
+define("DB_USERNAME", "");
+define("DB_PASSWORD", "");
+define("DB_NAME", "");
+
+define("ROOT_DIR", __DIR__);
+define("DOMAIN", "");
+
+define("PRODUCTION", false);
+define("REGISTRATION_ENABLED", true);
+define("DEBUG_MODE", false);
+
+define("SMTP_HOST", "");
+define("SMTP_PORT", 587);
+define("SMTP_USERNAME", "");
+define("SMTP_PASSWORD", "");
+define("SMTP_AUTHENTICATION_TYPE", "tls");
+
+define("GOOGLE_RECAPTCHA_SITE_KEY", "");
+define("GOOGLE_RECAPTCHA_SECRET", "");
+
+define("GOOGLE_ANALYTICS_ID", "");
+define("GOOGLE_API_KEY", "");
+define("GOOGLE_MAPS_API_KEY", "");
+
+define("SALT", "");
+
+?>

+ 11 - 0
controllers/.template.php

@@ -0,0 +1,11 @@
+<?php
+
+$page_title = "Home";
+
+Core::addBreadcrumb("/", $page_title);
+
+View::includeOnce("header", compact("page_title"));
+View::include("home");
+View::includeOnce("footer");
+
+?>

+ 11 - 0
controllers/404.php

@@ -0,0 +1,11 @@
+<?php
+
+header("HTTP/1.0 404 Not Found");
+
+$page_title = "Page Not Found";
+
+View::includeOnce("header", compact("page_title"));
+View::include("404");
+View::includeOnce("footer");
+
+?>

+ 11 - 0
controllers/503.php

@@ -0,0 +1,11 @@
+<?php
+
+header("HTTP/1.0 503 Not Found");
+
+$page_title = "Internal Server Error";
+
+View::includeOnce("header", compact("page_title"));
+View::include("503");
+View::includeOnce("footer");
+
+?>

+ 40 - 0
controllers/account.php

@@ -0,0 +1,40 @@
+<?php
+
+$page_title = "Account";
+
+Core::addBreadcrumb("/account", $page_title);
+
+$buttons = [];
+if(Core::$user->level >= User::LEVEL_ADMIN) {
+	$buttons["/account/customers"] = "Customers";
+	$buttons["/account/users"] = "Users";
+}
+
+if(Core::$user->level >= User::LEVEL_CUSTOMER) {
+	$buttons["/account/projects"] = "Projects";
+	$buttons["/account/locations"] = "Locations";
+	$buttons["/account/templates"] = "Templates";
+}
+
+if(Core::$user->level >= User::LEVEL_TESTER) {
+	$buttons["/account/tests"] = "Tests";
+}
+
+if(Core::$user->level == User::LEVEL_TESTER) {
+	$buttons["/account/addresses"] = "Addresses";
+	$buttons["/account/tests-completed"] = "Tests (Completed)";
+}
+
+if(Core::$user->level == User::LEVEL_REGISTERED) {
+	$buttons["/account/submit-id"] = "Submit ID";
+}
+
+$buttons["/account/settings"] = "Settings";
+
+asort($buttons);
+
+View::includeOnce("header", compact("page_title"));
+View::include("account", compact("buttons"));
+View::includeOnce("footer");
+
+?>

+ 68 - 0
controllers/address_add.php

@@ -0,0 +1,68 @@
+<?php
+
+$page_title = "Add Address";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/addresses", "Addresses");
+Core::addBreadcrumb("/account/addresses/add", $page_title);
+
+$user_address = new UserAddress;
+
+$submit = http::value("submit");
+if($submit) {
+	try {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		$user_address->name = http::value("name", "trim");
+		$user_address->postal_code = http::value("postal_code", "trim");
+
+		if(empty($user_address->name)) $form_exception->addError("Name is required.");
+		if(empty($user_address->postal_code)) {
+			$form_exception->addError("Postal code is required.");
+		}
+		else {
+			// Geocode the postal code
+			try {
+				$results = Geolocation::geocode($user_address->postal_code);
+
+				$result = $results[0];
+
+				foreach($result->address_components as $component) {
+					$types = $component->types;
+					if(in_array("postal_code", $types)) $user_address->postal_code = $component->long_name;
+					if(in_array("route", $types)) $user_address->address_1 = $component->long_name;
+					if(in_array("postal_town", $types)) $user_address->city = $component->long_name;
+					if(in_array("administrative_area_level_1", $types)) $user_address->state = $component->long_name;
+					if(in_array("country", $types)) $user_address->country = $component->long_name;
+				}
+
+				$user_address->latitude = $result->geometry->location->lat;
+				$user_address->longitude = $result->geometry->location->lng;
+			}
+			catch(Exception $e) {
+				$form_exception->addError("Failed to get location from postal code.");
+			}
+		}
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		$success = $user_address->commit();
+
+		Core::addAlert("success", "Address added successfully.");
+		HTTP::redirect("/account/addresses");
+	}
+	catch(FormException $e) {
+		$e->generateAlerts();
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+View::includeOnce("header", compact("page_title"));
+View::include("address_add_form", compact("user_address"));
+View::includeOnce("footer");
+
+?>

+ 60 - 0
controllers/address_edit.php

@@ -0,0 +1,60 @@
+<?php
+
+$page_title = "Edit Address";
+
+$user_address = UserAddress::get($id);
+if(!$user_address) throw new Exception("Address not found.");
+
+$submit = http::value("submit");
+if($submit) {
+	try {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		$user_address->name = http::value("name", "trim");
+		$user_address->address_1 = http::value("address_1", "trim");
+		$user_address->address_2 = http::value("address_2", "trim");
+		$user_address->city = http::value("city", "trim");
+		$user_address->county = http::value("county", "trim");
+		$user_address->postal_code = http::value("postal_code", "trim");
+		$user_address->max_radius_miles = http::value("max_radius_miles", "float");
+
+		$user_address->latitude = http::value("latitude", "float");
+		$user_address->longitude = http::value("longitude", "float");
+
+		if(empty($user_address->name)) $form_exception->addError("Name is required.");
+		if(empty($user_address->address_1)) $form_exception->addError("Address line 1 is required.");
+		if(empty($user_address->city)) $form_exception->addError("City is required.");
+		if(empty($user_address->postal_code)) $form_exception->addError("Postal code is required.");
+		if(empty($user_address->max_radius_miles)) $form_exception->addError("Max distance is required.");
+		if(!in_array($user_address->max_radius_miles, UserAddress::RADIUSES)) $form_exception->addError("Max distance is invalid.");
+
+		if(empty($user_address->latitude)) $form_exception->addError("Map location is required.");
+		else if(empty($user_address->longitude)) $form_exception->addError("Map location is required.");
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		$success = $user_address->commit();
+
+		Core::addAlert("success", "Address updated successfully.");
+		HTTP::redirect("/account/addresses");
+	}
+	catch(FormException $e) {
+		$e->generateAlerts();
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/addresses", "Addresses");
+Core::addBreadcrumb("/account/addresses/edit/$id", $page_title);
+
+View::includeOnce("header", compact("page_title"));
+View::include("address_edit_form", compact("user_address"));
+View::includeOnce("footer");
+
+?>

+ 15 - 0
controllers/addresses.php

@@ -0,0 +1,15 @@
+<?php
+
+$page_title = "Addresses";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/addresses", $page_title);
+
+$user = Core::$user;
+$addresses = $user->getAddresses();
+
+View::includeOnce("header", compact("page_title"));
+View::include("addresses", compact("addresses"));
+View::includeOnce("footer");
+
+?>

+ 11 - 0
controllers/become_a_tester.php

@@ -0,0 +1,11 @@
+<?php
+
+$page_title = "Become a Tester";
+
+Core::addBreadcrumb("/become-a-tester", $page_title);
+
+View::includeOnce("header", compact("page_title"));
+View::include("become_a_tester");
+View::includeOnce("footer");
+
+?>

+ 11 - 0
controllers/contact.php

@@ -0,0 +1,11 @@
+<?php
+
+$page_title = "Contact";
+
+Core::addBreadcrumb("/contact", $page_title);
+
+View::includeOnce("header", compact("page_title"));
+View::include("contact");
+View::includeOnce("footer");
+
+?>

+ 19 - 0
controllers/customer_view.php

@@ -0,0 +1,19 @@
+<?php
+
+$customer = Customer::get($id);
+if(!$customer) throw new Exception("Customer not found.");
+
+$page_title = $customer->name;
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/customers", "Customers");
+Core::addBreadcrumb("/account/customers/$id", $page_title);
+
+$projects = Project::query(["customer_id" => $id]);
+$locations = $customer->getLocations();
+
+View::includeOnce("header", compact("page_title"));
+View::include("customer", compact("customer", "projects", "locations"));
+View::includeOnce("footer");
+
+?>

+ 14 - 0
controllers/customers.php

@@ -0,0 +1,14 @@
+<?php
+
+$page_title = "Customers";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/customers", $page_title);
+
+$customers = Customer::query([], ["sort" => "name"]);
+
+View::includeOnce("header", compact("page_title"));
+View::include("customers", compact("customers"));
+View::includeOnce("footer");
+
+?>

+ 11 - 0
controllers/home.php

@@ -0,0 +1,11 @@
+<?php
+
+$page_title = "Home";
+
+Core::$show_alerts = false;
+
+View::includeOnce("header", compact("page_title"));
+View::include("home");
+View::includeOnce("footer");
+
+?>

+ 11 - 0
controllers/jobs.php

@@ -0,0 +1,11 @@
+<?php
+
+$page_title = "Jobs";
+
+Core::addBreadcrumb("/jobs", $page_title);
+
+View::includeOnce("header", compact("page_title"));
+View::include("jobs");
+View::includeOnce("footer");
+
+?>

+ 73 - 0
controllers/location_add.php

@@ -0,0 +1,73 @@
+<?php
+
+$page_title = "Add Location";
+
+$customer = Customer::getForAdmin();
+if(!$customer) throw new Exception("You do not have permission to access this page.");
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/locations", "Locations");
+Core::addBreadcrumb("/account/locations/add", $page_title);
+
+$location = new Location;
+$location->customer_id = $customer->id;
+
+$submit = http::value("submit");
+if($submit) {
+	try {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		$location->name = http::value("name", "trim");
+		$location->address_1 = http::value("address", "trim");
+
+		if(empty($location->name)) $form_exception->addError("Name is required.");
+		if(empty($location->address_1)) {
+			$form_exception->addError("Full address is required.");
+		}
+		else {
+			// Geocode the full address
+			try {
+				$results = Geolocation::geocode($location->address_1);
+
+				$result = $results[0];
+
+				foreach($result->address_components as $component) {
+					$types = $component->types;
+					if(in_array("postal_code", $types)) $location->postal_code = $component->long_name;
+					if(in_array("route", $types)) $location->address_1 = $component->long_name;
+					if(in_array("postal_town", $types)) $location->city = $component->long_name;
+					if(in_array("administrative_area_level_1", $types)) $location->state = $component->long_name;
+					if(in_array("country", $types)) $location->country = $component->long_name;
+				}
+
+				$location->latitude = $result->geometry->location->lat;
+				$location->longitude = $result->geometry->location->lng;
+			}
+			catch(Exception $e) {
+				$form_exception->addError("Failed to get location from full address: " . $e->getMessage());
+			}
+		}
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		$success = $location->commit();
+		if(!$success) throw new Exception("Faileds to add location at this time. Please try again later.");
+
+		Core::addAlert("success", "Location added successfully.");
+		HTTP::redirect("/account/locations/$location->id");
+	}
+	catch(FormException $e) {
+		$e->generateAlerts();
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+View::includeOnce("header", compact("page_title"));
+View::include("location_add_form", compact("location"));
+View::includeOnce("footer");
+
+?>

+ 59 - 0
controllers/location_edit.php

@@ -0,0 +1,59 @@
+<?php
+
+$page_title = "Edit Location";
+
+$location = Location::get($id);
+if(!$location) throw new Exception("Location not found.");
+if(!Core::$user->hasPermission($location)) throw new Exception("You do not have have permission to access this page.");
+
+$submit = http::value("submit");
+if($submit) {
+	try {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		$location->name = http::value("name", "trim");
+		$location->address_1 = http::value("address_1", "trim");
+		$location->address_2 = http::value("address_2", "trim");
+		$location->city = http::value("city", "trim");
+		$location->county = http::value("county", "trim");
+		$location->postal_code = http::value("postal_code", "trim");
+
+		$location->latitude = http::value("latitude", "float");
+		$location->longitude = http::value("longitude", "float");
+
+		if(empty($location->name)) $form_exception->addError("Name is required.");
+		if(empty($location->address_1)) $form_exception->addError("Location line 1 is required.");
+		if(empty($location->city)) $form_exception->addError("City is required.");
+		if(empty($location->postal_code)) $form_exception->addError("Postal code is required.");
+
+		if(empty($location->latitude)) $form_exception->addError("Map location is required.");
+		else if(empty($location->longitude)) $form_exception->addError("Map location is required.");
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		$success = $location->commit();
+
+		Core::addAlert("success", "Location updated successfully.");
+		HTTP::redirect("/account/locations");
+	}
+	catch(FormException $e) {
+		$e->generateAlerts();
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/locations", "Locations");
+Core::addBreadcrumb("/account/locations/$id", $location->name);
+Core::addBreadcrumb("/account/locations/$id/edit", $page_title);
+
+View::includeOnce("header", compact("page_title"));
+View::include("location_edit_form", compact("location"));
+View::includeOnce("footer");
+
+?>

+ 36 - 0
controllers/location_view.php

@@ -0,0 +1,36 @@
+<?php
+
+$location = Location::get($id);
+if(!$location) throw new Exception("Location not found.");
+if(!Core::$user->hasPermission($location)) throw new Exception("You do not have permission to access this page.");
+
+$page_title = $location->name;
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/locations", "Locations");
+Core::addBreadcrumb("/account/locations/$location->id", $page_title);
+
+$status_constraint = new Constraint("BETWEEN");
+$status_constraint->setValues(Test::STATUS_ASSIGNED, Test::STATUS_PENDING_VERIFICATION);
+
+$pending_tests = Test::query([
+	"location_id" => $location->id,
+	"status" => $status_constraint,
+], [
+	"sort" => "id",
+	"order" => "desc",
+]);
+
+$completed_tests = Test::query([
+	"location_id" => $location->id,
+	"status" => Test::STATUS_COMPLETED,
+], [
+	"sort" => "dts_end",
+	"order" => "desc",
+]);
+
+View::includeOnce("header", compact("page_title"));
+View::include("location", compact("location"));
+View::includeOnce("footer");
+
+?>

+ 17 - 0
controllers/locations.php

@@ -0,0 +1,17 @@
+<?php
+
+$page_title = "Locations";
+
+$customer = Customer::getForAdmin();
+if(!$customer) throw new Exception("You do not have permission to access this page.");
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/locations", $page_title);
+
+$locations = $customer->getLocations();
+
+View::includeOnce("header", compact("page_title"));
+View::include("locations", compact("customer", "locations"));
+View::includeOnce("footer");
+
+?>

+ 43 - 0
controllers/log_in.php

@@ -0,0 +1,43 @@
+<?php
+
+$page_title = "Log In";
+
+Core::addBreadcrumb("/log-in", "Log In");
+
+$submit = http::value("submit");
+$csrf_token = $_SESSION["csrf_token"];
+
+if($submit) {
+	try {
+		Core::validateCSRFToken($submit);
+
+		$email = http::value("email", "email");
+		$password = http::value("password");
+
+		if(empty($email)) throw new Exception("Email address is invalid.");
+		if(empty($password)) throw new Exception("Password must be given.");
+
+		$user = User::queryOne([
+			"email" => db::escape($email)
+		]);
+
+		if(!$user) throw new Exception("Account not found.");
+		if(!password_verify($password, $user->password)) throw new Exception("Password is incorrect.");
+
+		$_SESSION["user_id"] = $user->id;
+
+		Core::addAlert("success", "Log in successful.");
+		HTTP::redirect("/account");
+
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+
+View::includeOnce("header", compact("page_title"));
+View::include("log_in");
+View::includeOnce("footer");
+
+?>

+ 9 - 0
controllers/log_out.php

@@ -0,0 +1,9 @@
+<?php
+
+unset($_SESSION["user_id"]);
+
+Core::addAlert("success", "Log out successful.");
+
+HTTP::redirect("/log-in");
+
+?>

+ 5 - 0
controllers/ping.php

@@ -0,0 +1,5 @@
+<?php
+
+JSON::success();
+
+?>

+ 11 - 0
controllers/privacy_policy.php

@@ -0,0 +1,11 @@
+<?php
+
+$page_title = "Privacy Policy";
+
+Core::addBreadcrumb("/privacy-policy", $page_title);
+
+View::includeOnce("header", compact("page_title"));
+View::include("privacy_policy");
+View::includeOnce("footer");
+
+?>

+ 53 - 0
controllers/project.php

@@ -0,0 +1,53 @@
+<?php
+
+$project = Project::get($id);
+if(!$project) throw new Exception("Project not found.");
+if(!Core::$user->hasPermission($project)) throw new Exception("You do not have permission to access this page.");
+
+$page_title = $project->name;
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/projects", "Projects");
+Core::addBreadcrumb("/account/projects/$project->id", $page_title);
+
+Core::addScript("public/js/app-project.js");
+
+$completed_percentage = $project->getCompletedPercentage();
+
+$customer = $project->getCustomer();
+
+$locations = $customer->getLocations();
+
+$tests = $project->getTests();
+usort($tests, function($a, $b) {
+	return $a->status <=> $b->status;
+});
+
+$created_test_count = count($tests);
+
+$pending_verification_tests = array_filter($tests, function($test) { return $test->status == Test::STATUS_PENDING_VERIFICATION; });
+$pending_verification_test_count = count($pending_verification_tests);
+
+$completed_tests = array_filter($tests, function($test) { return $test->status == Test::STATUS_COMPLETED; });
+$completed_test_count = count($completed_tests);
+
+$min_lat = $min_lng = 180;
+$max_lat = $max_lng = -180;
+
+foreach($locations as $location) {
+	if($location->latitude < $min_lat) $min_lat = $location->latitude;
+	if($location->latitude > $max_lat) $max_lat = $location->latitude;
+	if($location->longitude < $min_lng) $min_lng = $location->longitude;
+	if($location->longitude > $max_lng) $max_lng = $location->longitude;
+}
+
+$latitude = ($min_lat + $max_lat) / 2;
+$longitude = ($min_lng + $max_lng) / 2;
+
+$deadline_date = explode(" ", $project->dts_deadline)[0];
+
+View::includeOnce("header", compact("page_title"));
+View::include("project", compact("project", "tests", "latitude", "longitude", "completed_percentage", "customer", "locations", "deadline_date", "created_test_count", "completed_test_count"));
+View::includeOnce("footer");
+
+?>

+ 108 - 0
controllers/project_add.php

@@ -0,0 +1,108 @@
+<?php
+
+Core::addScript("public/js/app-project-form.js");
+
+$page_title = "Add Project";
+
+$customer = Customer::getForAdmin();
+
+if(empty($customer)) throw new Exception("Customer not found.");
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/projects", "Projects");
+Core::addBreadcrumb("/account/projects/add", $page_title);
+
+// Check templates
+$templates = $customer->getTemplates();
+if(empty($templates)) throw new Exception("A template must exist before a project can be created.");
+
+$project = new Project;
+$project->customer_id = $customer->id;
+$project->default_tester_fee = 10;
+
+$submit = http::value("submit");
+if($submit) {
+	try {
+
+		$location_ids = http::value("location_ids");
+		$location_ids = explode(", ", $location_ids);
+		$location_ids = array_filter($location_ids);
+
+		Core::validateCSRFToken($submit);
+
+		$project->template_id = http::value("template_id", "int");
+		$project->name = http::value("name", "trim");
+		$project->test_count = http::value("test_count", "int");
+		$project->min_age = http::value("min_age", "int");
+		$project->max_age = http::value("max_age", "int");
+		$project->default_tester_fee = http::value("default_tester_fee", "int");
+		$project->dts_start = http::value("date_start");
+		$project->dts_deadline = http::value("date_deadline");
+
+		$form_exception = new FormException;
+
+		if(empty($project->template_id)) $form_exception->addError("Template is required.");
+		else {
+			$template = Template::get($project->template_id);
+			if($template->customer_id != $customer->id) $form_exception->addError("Invalid template selected.");
+		}
+		if(empty($project->name)) $form_exception->addError("Name is required.");
+		if(empty($project->test_count)) $form_exception->addError("Test count is required.");
+		if(empty($project->min_age)) $form_exception->addError("Minimum age is required.");
+		if(empty($project->max_age)) $form_exception->addError("Maximum age is required.");
+		if(empty($project->default_tester_fee)) $form_exception->addError("Default tester fee is required.");
+		if(empty($project->dts_start)) $form_exception->addError("Start Date is required.");
+		if(empty($project->dts_deadline)) $form_exception->addError("Deadline is required.");
+		if($project->min_age > $project->max_age) $form_exception->addError("Minimum age cannot be greater than maximum age.");
+
+		$project->dts_start .= " 00:00:00";
+		$project->dts_deadline .= " 23:59:59";
+		$project->dts_created = Util::getDateTime();
+
+		$unix_start = strtotime($project->dts_start);
+		$unix_end = strtotime($project->dts_deadline);
+
+		if($unix_start > $unix_end) $form_exception->addError("Start Date cannot be after the Deadline.");
+
+		// Verify location IDs
+		Location::load($location_ids);
+		foreach($location_ids as $location_id) {
+			$location = Location::get($location_id);
+			if(!$location) $form_exception->addError("An invalid location was picked.");
+			if($location->customer_id != $customer->id) $form_exception->addError("An invalid location was picked.");
+		}
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		$success = $project->commit();
+		if(!$success) throw new Exception("Project could not be added at this time. Please try again later.");
+
+		// Create test for location IDs
+		foreach($location_ids as $location_id) {
+			$test = new Test;
+			$test->project_id = $project->id;
+			$test->location_id = $location_id;
+			$test->status = Test::STATUS_UNASSIGNED;
+			$test->dts_created = Util::getDateTime();
+			$success = $test->commit();
+			if(!$success) throw new Exception("Test cannot be created, please try again later.");
+		}
+
+		Core::addAlert("success", "Project added successfully.");
+		HTTP::redirect("/account/projects/$project->id");
+	}
+	catch(FormException $e) {
+		$e->generateAlerts();
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+$locations = $customer->getLocations();
+
+View::includeOnce("header", compact("page_title"));
+View::include("project_add_form", compact("project", "templates", "locations"));
+View::includeOnce("footer");
+
+?>

+ 241 - 0
controllers/project_ajax.php

@@ -0,0 +1,241 @@
+<?php
+
+JSON::header();
+
+$project = Project::get($id);
+if(!$project) throw new Exception("Project cannot be found.");
+if(!Core::$user->hasPermission($project)) throw new Exception("You do not have permission to access this resource.");
+
+$submit = http::value("submit");
+
+if($submit) {
+	try {
+
+		Core::validateCSRFToken($submit);
+
+		switch($action) {
+
+			// Gets all locations for a project
+			case "get-locations": {
+
+				$customer = $project->getCustomer();
+				$tests = $project->getTests();
+
+				$locations = Location::load(array_column($tests, "location_id"));
+
+
+				$location_tests = [];
+
+				foreach($tests as $test) {
+					if($test->status == Test::STATUS_CANCELLED) continue;
+					$location_tests[$test->location_id] = $test;
+				}
+
+				$output = [];
+
+				foreach($locations as $location) {
+
+					$test = $location_tests[$location->id] ?? false;
+
+					$test_id = null;
+					$status = 0;
+					$status_text = "";
+					$class = "secondary";
+					if($test) {
+						$test_id = $test->id;
+						$class = $test->getStatusClass();
+						$status = $test->status;
+						$status_text = $test->getStatusText();
+					}
+
+					$output[] = (object) [
+						"id" => (int) $location->id,
+						"testId" => (int) $test_id,
+						"name" => $location->name,
+						"address" => $location->getDisplayAddress(["address_1", "address_2", "city", "postal_code"]),
+						"status" => $status,
+						"statusText" => $status_text,
+						"class" => $class,
+						"latitude" => (float) $location->latitude,
+						"longitude" => (float) $location->longitude
+					];
+				}
+
+				usort($output, function($a, $b) {
+					return $a->status <=> $b->status;
+				});
+
+				JSON::success([
+					"locations" => $output
+				]);
+
+				break;
+			}
+
+
+			// Gets testers near a project
+			case "get-testers": {
+
+				$location_id = http::value("location_id", "int");
+				$location = Location::get($location_id);
+				if(!$location) throw new Exception("Location not found.");
+
+				$status_constraint = new Constraint("MORE_THAN_OR_EQUAL");
+				$status_constraint->setValues(Test::STATUS_UNASSIGNED);
+
+				$nvp = [
+					"location_id" => $location_id,
+					"project_id" => $project->id,
+					"status" => $status_constraint,
+				];
+
+				$test = Test::queryOne($nvp);
+				if(!$test) throw new Exception("A test does not exist for this project.");
+
+				/*
+				$max_distance = http::value("max_distance", "int");
+				if($max_distance < 2.5) $max_distance = 2.5;
+				if($max_distance > 25) $max_distance = 25;
+				*/
+
+				$max_distance = 25;
+
+				$bounds = Geolocation::getBounds($location->getGeolocation(), $max_distance);
+
+				$lat_constraint = new Constraint("BETWEEN");
+				$lat_constraint->setValues($bounds->southWest[0], $bounds->northEast[0]);
+
+				$lng_constraint = new Constraint("BETWEEN");
+				$lng_constraint->setValues($bounds->southWest[1], $bounds->northEast[1]);
+
+				$nvp = [
+					"latitude" => $lat_constraint,
+					"longitude" => $lng_constraint
+				];
+
+				$addresses = UserAddress::query($nvp);
+
+				$users = User::load(array_column($addresses, "user_id"));
+
+				$pending_tests = Test::query([
+					"tester_id" => array_column($users, "id"),
+					"status" => Test::STATUS_ASSIGNED,
+				]);
+
+				$age_constraint = false;
+
+				usort($addresses, function($a, $b) use ($location) {
+					$lat_lng = $location->getGeolocation();
+					return Geolocation::getDistance($lat_lng, $a->getGeolocation()) <=> Geolocation::getDistance($lat_lng, $b->getGeolocation());
+				});
+
+				$output = [];
+
+				foreach($addresses as $address) {
+					$user = $address->getUser();
+
+					$is_current_tester = $user->id == $test->tester_id;
+
+					$distance_miles = Geolocation::getDistance($location->getGeolocation(), $address->getGeolocation());
+					$distance_kilometers = $distance_miles * Geolocation::KMS_IN_MILE;
+
+					$user_pending_tests = array_filter($pending_tests, function($test) use ($user) {
+						return ($user->id == $test->tester_id);
+					});
+					$pending_test_count = count($user_pending_tests);
+
+					$age = $user->getAge();
+
+					// Age check
+					if($project->min_age && $project->max_age && ($age < $project->min_age || $age > $project->max_age)) {
+						continue;
+					}
+					else if($project->min_age && $age < $project->min_age) {
+						continue;
+					}
+					else if($project->max_age && $age > $project->max_age) {
+						continue;
+					}
+
+					$max_radius_exceeded = ($distance_miles > $address->max_radius_miles);
+
+					$output[] = [
+						"id" => (int) $user->id,
+						"addressId" => (int) $address->id,
+						"name" => $user->getDisplayName(),
+						"age" => $age,
+						"phone" => $user->phone,
+						"score" => (int) $user->score,
+						"distanceMiles" => $distance_miles,
+						"distanceKilometers" => $distance_kilometers,
+						"maxRadiusMiles" => (float) $address->max_radius_miles,
+						"maxRadiusKilometers" => $address->max_radius_miles * Geolocation::KMS_IN_MILE,
+						"maxRadiusExceeded" => $max_radius_exceeded,
+						"latitude" => (float) $address->latitude,
+						"longitude" => (float) $address->longitude,
+						"pendingTestCount" => $pending_test_count,
+						"isCurrentTester" => $is_current_tester
+					];
+
+				}
+
+				JSON::success([
+					"testers" => $output
+				]);
+			}
+
+			// Assigns a tester to a test
+			case "assign-tester": {
+
+				$location_id = http::value("location_id", "int");
+				$location = Location::get($location_id);
+				if(!$location) throw new Exception("Location not found.");
+
+				$status_constraint = new Constraint("MORE_THAN_OR_EQUAL");
+				$status_constraint->setValues(Test::STATUS_UNASSIGNED);
+
+				$nvp = [
+					"location_id" => $location_id,
+					"project_id" => $project->id,
+					"status" => $status_constraint,
+				];
+
+				$test = Test::queryOne($nvp);
+				if(!$test) throw new Exception("A test does not exist for this location.");
+
+				$address_id = http::value("address_id", "int");
+				$address = UserAddress::get($address_id);
+				if(!$address) throw new Exception("User address cannot be found.");
+
+				$user = $address->getUser();
+				if($user->level == User::LEVEL_UNVERIFIED) throw new Exception("A test cannot be assigned to an unverified user.");
+				if($user->level == User::LEVEL_DEACTIVATED) throw new Exception("A test cannot be assigned to a deactivated user.");
+				if($user->level >= User::LEVEL_VENUE) throw new Exception("A test cannot be assigned to a user that's not a tester.");
+
+				$test->status = Test::STATUS_ASSIGNED;
+				$test->tester_id = $user->id;
+				$test->dts_assigned = Util::getDateTime();
+
+				$success = $test->commit();
+				if(!$success) throw new Exception("Test cannot be assigned, please try again later.");
+
+				// TODO: send user email
+
+				JSON::success();
+
+				break;
+			}
+
+			default:
+				throw new Exception("Invalid request.");
+		}
+
+	}
+	catch(Exception $e) {
+		JSON::fail($e->getMessage());
+	}
+}
+
+JSON::fail("Invalid request.");
+
+?>

+ 16 - 0
controllers/projects.php

@@ -0,0 +1,16 @@
+<?php
+
+$page_title = "Projects";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/projects", $page_title);
+
+$customer = Customer::getForAdmin();
+
+$projects = $customer->getProjects();
+
+View::includeOnce("header", compact("page_title"));
+View::include("projects", compact("customer", "projects"));
+View::includeOnce("footer");
+
+?>

+ 98 - 0
controllers/register.php

@@ -0,0 +1,98 @@
+<?php
+
+if(Core::$user) HTTP::redirect("/account");
+
+$page_title = "Register";
+
+Core::addBreadcrumb("/register", $page_title);
+
+$user = new User;
+$user_address = new UserAddress();
+
+try {
+	$submit = http::value("submit");
+
+	if($submit) {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		$password = http::value("password");
+		$password_confirm = http::value("password_confirm");
+
+		if($password != $password_confirm) $form_exception->addError("Passwords do not match.");
+
+		$user->email = http::value("email", "email");
+		$user->password = password_hash($password, PASSWORD_DEFAULT, ["cost" => 14]);
+		$user->title = http::value("title", "trim");
+		$user->first_name = http::value("first_name", "trim");
+		$user->last_name = http::value("last_name", "trim");
+		$user->date_of_birth = http::value("date_of_birth", "trim");
+		$user->phone = http::value("phone", "trim");
+		$user->dts_registered = gmdate("Y-m-d H:i:s");
+
+		$user_address->postal_code = http::value("postal_code");
+
+		if(empty($user->email)) $form_exception->addError("Email address is invalid.");
+		if(empty($user->title)) $form_exception->addError("Title is required.");
+		if(empty($user->first_name)) $form_exception->addError("First name is required.");
+		if(empty($user->last_name)) $form_exception->addError("Last name is required.");
+		if(empty($user->date_of_birth)) $form_exception->addError("Date of birth is required.");
+		if(empty($user->phone)) $form_exception->addError("Mobile number is required.");
+
+		if(empty($user_address->postal_code)) $form_exception->addError("Postal code is required.");
+
+		$email_exists = User::query(["email" => $user->email]);
+		if($email_exists) $form_exception->addError("Email address is already registered.");
+
+		// Geocode the postal code
+		try {
+			$results = Geolocation::geocode($user_address->postal_code);
+
+			$result = $results[0];
+
+			foreach($result->address_components as $component) {
+				$types = $component->types;
+				if(in_array("postal_code", $types)) $user_address->postal_code = $component->long_name;
+				if(in_array("route", $types)) $user_address->address_1 = $component->long_name;
+				if(in_array("postal_town", $types)) $user_address->city = $component->long_name;
+				if(in_array("administrative_area_level_1", $types)) $user_address->state = $component->long_name;
+				if(in_array("country", $types)) $user_address->country = $component->long_name;
+			}
+
+			$user_address->latitude = $result->geometry->location->lat;
+			$user_address->longitude = $result->geometry->location->lng;
+		}
+		catch(Exception $e) {
+			$form_exception->addError("Failed to get location from postal code.");
+		}
+
+		if($form_exception->hasErrors()) {
+			throw $form_exception;
+		}
+
+		// OK
+		$success = $user->commit();
+		if(!$success) throw new Exception("Registration failed. Please try again later.");
+
+		$user_address->user_id = $user->id;
+		$success = $user_address->commit();
+
+		// TODO: Send out registration email
+
+		Core::addAlert("success", "Registration successful. You can now log in.");
+		HTTP::redirect("/log-in");
+	}
+}
+catch(FormException $e) {
+	$e->generateAlerts();
+}
+catch(Exception $e) {
+	Core::addAlert("danger", $e->getMessage());
+}
+
+View::includeOnce("header", compact("page_title"));
+View::include("register", compact("user", "user_address"));
+View::includeOnce("footer");
+
+?>

+ 11 - 0
controllers/services.php

@@ -0,0 +1,11 @@
+<?php
+
+$page_title = "Services";
+
+Core::addBreadcrumb("/services", $page_title);
+
+View::includeOnce("header", compact("page_title"));
+View::include("services");
+View::includeOnce("footer");
+
+?>

+ 69 - 0
controllers/settings.php

@@ -0,0 +1,69 @@
+<?php
+
+$page_title = "Settings";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/settings", $page_title);
+
+$user = Core::$user;
+
+$submit = http::value("submit");
+if($submit) {
+	try {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		// Password
+		$password = http::value("password");
+		$password_confirm = http::value("password_confirm");
+
+		if($password != $password_confirm) $form_exception->addError("Passwords do not match.");
+		if($password) {
+			$user->password = password_hash($password, PASSWORD_DEFAULT, ["cost" => 14]);
+		}
+
+		$user->title = http::value("title", "trim");
+		$user->first_name = http::value("first_name", "trim");
+		$user->last_name = http::value("last_name", "trim");
+		$user->date_of_birth = http::value("date_of_birth", "trim");
+		$user->phone = http::value("phone", "trim");
+
+		if(empty($user->email)) $form_exception->addError("Email address is invalid.");
+		if(empty($user->title)) $form_exception->addError("Title is required.");
+		if(empty($user->first_name)) $form_exception->addError("First name is required.");
+		if(empty($user->last_name)) $form_exception->addError("Last name is required.");
+		if(empty($user->date_of_birth)) $form_exception->addError("Date of birth is required.");
+		if(empty($user->phone)) $form_exception->addError("Mobile number is required.");
+
+		// Activation
+		$deactivate = http::value("deactivate");
+		if($deactivate && $user->level == User::LEVEL_TESTER) {
+			$user->level = User::LEVEL_DEACTIVATED;
+		}
+
+		$reactivate = http::value("reactivate");
+		if($reactivate && $user->level == User::LEVEL_DEACTIVATED) {
+			$user->level = User::LEVEL_TESTER;
+		}
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		$success = $user->commit();
+
+		Core::addAlert("success", "Settings saved successfully.");
+		HTTP::redirect("/account/settings");
+	}
+	catch(FormException $e) {
+		$e->generateAlerts();
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+View::includeOnce("header", compact("page_title"));
+View::include("settings", compact("user"));
+View::includeOnce("footer");
+
+?>

+ 85 - 0
controllers/submit_id.php

@@ -0,0 +1,85 @@
+<?php
+
+$page_title = "Submit ID";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/submit-id", $page_title);
+
+$submit = http::value("submit");
+if($submit) {
+
+	$user = Core::$user;
+
+	try {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		$id_document = (object) $_FILES["id_document"];
+		$photo = (object) $_FILES["photo"];
+
+		if($id_document->error != UPLOAD_ERR_OK) $form_exception->addError(HTTP::getUploadErrorString($id_document->error));
+		if($photo->error != UPLOAD_ERR_OK) $form_exception->addError(HTTP::getUploadErrorString($photo->error));
+
+		$size = @getimagesize($id_document->tmp_name);
+		if(!$size) $form_exception->addError("The uploaded ID document is not an image.");
+		list($width, $height, $type) = $size;
+		if($type != IMAGETYPE_JPEG) $form_exception->addError("The uploaded ID document is not a JPEG.");
+
+		$size = @getimagesize($photo->tmp_name);
+		if(!$size) $form_exception->addError("The uploaded photo is not an image.");
+		list($width, $height, $type) = $size;
+		if($type != IMAGETYPE_JPEG) $form_exception->addError("The uploaded photo is not a JPEG.");
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		$files = [$id_document, $photo];
+		foreach($files as $index => $file) {
+
+			if($index == 0) {
+				$name = "ID document";
+				$type = UserFile::TYPE_ID;
+			}
+			if($index == 1) {
+				$name = "photo";
+				$type = UserFile::TYPE_PHOTO;
+			}
+
+			$output_image = Image::normalise($file->tmp_name);
+
+			$user_file = new UserFile;
+			$user_file->user_id = $user->id;
+			$user_file->type = $type;
+			$user_file->dts_uploaded = Util::getDateTime();
+
+			$success = $user_file->commit();
+			if(!$success) throw new Exception("Failed to save the $name. Please try again later.");
+
+			$output_path = $user->getDirectory() . "/" . $user_file->id . ".jpg";
+
+			imagejpeg($output_image, $output_path, 60);
+			imagedestroy($output_image);
+		}
+
+		$user->level = User::LEVEL_UNVERIFIED;
+
+		$success = $user->commit();
+
+		// TODO: Send out pending verification email
+
+		Core::addAlert("success", "ID submitted successfully.");
+		HTTP::redirect("/account");
+	}
+	catch(FormException $e) {
+		$e->generateAlerts();
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+View::includeOnce("header", compact("page_title"));
+View::include("submit_id");
+View::includeOnce("footer");
+
+?>

+ 25 - 0
controllers/template.php

@@ -0,0 +1,25 @@
+<?php
+
+Core::addScript("/public/js/app-test.js");
+
+$template = Template::get($id);
+
+if(!Core::$user->hasPermission($template)) throw new Exception("You do not have permission to access this page.");
+
+$page_title = $template->name;
+
+Core::addScript("public/js/app-test.js");
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/templates", "Templates");
+Core::addBreadcrumb("/account/templates/$template->id", $page_title);
+
+if(HTTP::isAJAX()) {
+	JSON::success();
+}
+
+View::includeOnce("header", compact("page_title"));
+View::include("template", compact("template"));
+View::includeOnce("footer");
+
+?>

+ 52 - 0
controllers/template_add.php

@@ -0,0 +1,52 @@
+<?php
+
+$page_title = "Add Template";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/templates", "Templates");
+Core::addBreadcrumb($_SERVER["REQUEST_URI"], $page_title);
+
+$customer = Customer::getForAdmin();
+
+$template = new Template;
+$template->customer_id = $customer->id;
+$template->json = file_get_contents("json/default_template.json");
+
+$submit = http::value("submit");
+if($submit) {
+	try {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		$template->name = http::value("name", "trim");
+		$template->json = http::value("json", "trim");
+
+		if(empty($template->name)) $form_exception->addError("Name is required.");
+		if(empty($template->json)) $form_exception->addError("JSON is required.");
+
+		$json = json_decode($template->json);
+		if(!$json) {
+			$form_exception->addError("JSON error: " . json_last_error_msg());
+		}
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		$success = $template->commit();
+
+		Core::addAlert("success", "Template added successfully.");
+		HTTP::redirect("/account/templates?customer_id=$customer->id");
+	}
+	catch(FormException $e) {
+		$e->generateAlerts();
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+View::includeOnce("header", compact("page_title"));
+View::include("template_add_form", compact("template"));
+View::includeOnce("footer");
+
+?>

+ 16 - 0
controllers/templates.php

@@ -0,0 +1,16 @@
+<?php
+
+$page_title = "Templates";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/templates", $page_title);
+
+$customer = Customer::getForAdmin();
+
+$templates = $customer->getTemplates();
+
+View::includeOnce("header", compact("page_title"));
+View::include("templates", compact("customer", "templates"));
+View::includeOnce("footer");
+
+?>

+ 319 - 0
controllers/test.php

@@ -0,0 +1,319 @@
+<?php
+
+Core::addScript("public/js/app-test.js");
+
+$test = Test::get($id);
+if(!$test) throw new Exception("Test cannot be found.");
+
+$location = $test->getLocation();
+$project = $test->getProject();
+$tester = $test->getTester();
+$template = $project->getTemplate();
+
+$page_title = $location->name;
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/tests", "Tests");
+Core::addBreadcrumb("/account/tests/$id", $page_title);
+
+$fillable_fields = ["shop_left", "shop_right", "attire", "challenge_stage", "challenge_description", "challenger_name", "challenger_description", "challenger_gender", "challenger_eye_contact", "additional_notes"];
+
+// Do test
+if(Core::$user->level == User::LEVEL_TESTER) {
+
+	Core::$show_footer_content = false;
+
+	if(Core::$user->id != $test->tester_id) throw new Exception("You do not have permission to view this page.");
+
+	// Show completed message
+	if($test->status >= Test::STATUS_PENDING_VERIFICATION) {
+		View::includeOnce("header", compact("page_title"));
+		View::include("test_form", compact("test", "location", "project", "template"));
+		View::includeOnce("footer");
+		return;
+	}
+
+	$json = json_decode($template->json);
+
+	$submit = http::value("submit");
+	if($submit) {
+
+		$previous_timezone = date_default_timezone_get();
+
+		date_default_timezone_set("UTC");
+
+		try {
+			Core::validateCSRFToken($submit);
+
+			$form_exception = new FormException;
+
+			if($test->status == Test::STATUS_ASSIGNED) {
+				// Parse before the test form
+				$fields = $json->beforeTest;
+
+			}
+
+			if($test->status == Test::STATUS_STARTED) {
+				// Parse after the test form
+				$fields = $json->duringTest;
+
+				$duration = http::value("duration", "int");
+				if(!$duration) $form_exception->addError("Duration was not submitted.");
+
+			}
+
+			foreach($fields as $field) {
+
+				$name = $field->name ?? false;
+				if(empty($name)) continue; // Not a field
+
+				$label = $field->label ?? "";
+				$type = $field->type;
+				$required = $field->required ?? false;
+				$values = $field->values ?? [];
+
+				if($type == "file") {
+					$file = (object) $_FILES[$name];
+
+					try {
+						if(!$required && $file->error == UPLOAD_ERR_NO_FILE) continue;
+						if($required && $file->error == UPLOAD_ERR_NO_FILE) {
+							throw new Exception("$label is required.");
+						}
+
+						// Detect upload error
+						if($file->error != UPLOAD_ERR_OK) throw new Exception(HTTP::getUploadErrorString($file->error));
+
+						// Get image details
+						$size = @getimagesize($file->tmp_name);
+						if(!$size) throw new Exception("The uploaded file for $label is not an image.");
+						list($width, $height, $type) = $size;
+						if($type != IMAGETYPE_JPEG) throw new Exception("The uploaded file for $label is not a JPEG.");
+
+						// Resize image
+						$output_image = Image::normalise($file->tmp_name);
+
+						// Write image to disk
+						$output_path = $test->getDirectory() . "/" . $name . ".jpg";
+
+						imagejpeg($output_image, $output_path, 60);
+						imagedestroy($output_image);
+					}
+					catch(Exception $e) {
+						$form_exception->addError($e->getMessage());
+					}
+				}
+				else {
+					$value = http::value($name, "trim");
+
+					if($required && empty($value)) $form_exception->addError("$label is required.");
+					if($values && !in_array($value, $values)) $form_exception->addError("Value for $label is invalid.");
+
+					if(in_array($name, $fillable_fields)) {
+						$test->$name = $value;
+					}
+					else {
+						$test_value = TestValue::get($test->id, $name);
+						if(!$test_value) {
+							$test_value->test_id = $test->id;
+							$test_value->name = $name;
+						}
+						$test_value->value = $value;
+						$success = $test_value->commit();
+						if(!$success) $form_exception->addError("Failed to save value for $label.");
+					}
+				}
+
+			}
+
+			if($form_exception->hasErrors()) throw $form_exception;
+
+			// Before the Test
+			if($test->status == Test::STATUS_ASSIGNED) {
+				$test->status = Test::STATUS_STARTED;
+				$test->dts_start = Util::getDateTime();
+				$success = $test->commit();
+				if(!$success) throw new Exception("Failed to save test. Please try again later.");
+
+				HTTP::redirect("/account/tests/$id");
+
+			}
+
+			// During the test
+			if($test->status == Test::STATUS_STARTED) {
+				$test->status = Test::STATUS_PENDING_VERIFICATION;
+
+				$unix_start = strtotime($test->dts_start);
+				$unix_end = $unix_start + floor($duration / 1000); // $duration is milliseconds
+
+				$test->dts_end = date("Y-m-d H:i:s", $unix_end);
+
+				$test->pass = ($test->challenge_stage <= 2) ? 1 : 0; // Pass = Challenged during browsing or before
+
+				$success = $test->commit();
+				if(!$success) throw new Exception("Failed to save test. Please try again later.");
+
+				JSON::success();
+			}
+
+		}
+		catch(FormException $e) {
+			$e->generateAlerts();
+		}
+		catch(Exception $e) {
+			Core::addAlert("danger", $e->getMessage());
+		}
+
+		date_default_timezone_set($previous_timezone);
+
+	}
+
+
+	View::includeOnce("header", compact("page_title"));
+	View::include("test_form", compact("test", "location", "project", "template"));
+	View::includeOnce("footer");
+
+}
+
+// Verify test
+else if(Core::$user->level >= User::LEVEL_ADMIN) {
+
+	$json = json_decode($template->json);
+	$fields = array_merge($json->beforeTest, $json->duringTest);
+	$values = $test->getValues();
+
+	$names = array_map(function($value) { return $value->name; }, $values);
+
+	$values = array_combine(
+		array_map(function($value) { return $value->name; }, $values),
+		array_map(function($value) { return $value->value; }, $values)
+	);
+
+	$submit = http::value("submit");
+	$tester_message = http::value("tester_message", "trim");
+	if($submit) {
+		try {
+			Core::validateCSRFToken($submit);
+
+			$form_exception = new FormException;
+
+			$accept = http::value("accept");
+			$reject = http::value("reject");
+
+			$test->verifier_id = Core::$user->id;
+			$test->verifier_notes = http::value("verifier_notes", "trim");
+			$test->dts_verified = Util::getDateTime();
+
+			// Modify values and accept test as completed
+			if($accept) {
+				$test->status = Test::STATUS_COMPLETED;
+
+				// Overrides
+				$unix_start = strtotime($test->dts_start . " UTC");
+				$unix_end = strtotime($test->dts_end . " UTC");
+
+				$pass_override = http::value("pass_override");
+				if(strlen($pass_override) > 0) {
+					$test->pass = $pass_override;
+				}
+
+				$start_override = http::value("start_override");
+				if($start_override) {
+					$unix_start = strtotime($start_override);
+				}
+
+				$end_override = http::value("end_override");
+				if($end_override) {
+					$unix_end = strtotime($end_override);
+				}
+
+				if($unix_start > $unix_end) {
+					$form_exception->addError("Start time cannot be after end time.");
+				}
+				else {
+					$test->dts_start = Util::getDateTime($unix_start);
+					$test->dts_end = Util::getDateTime($unix_end);
+				}
+
+				$test->test_fee = null;
+				$tester_fee = http::value("tester_fee", "int");
+				if($tester_fee != $project->default_tester_fee) {
+					$test->test_fee = $tester_fee;
+				}
+
+				// Test forms
+				foreach($fields as $field) {
+					if($field->type == "header") continue;
+					if($field->type == "file") continue;
+					if(empty($field->name)) continue;
+
+					$value = http::value($field->name, "trim");
+
+					if(in_array($field->name, $fillable_fields)) $test->{$field->name} = $value;
+					else {
+						$test_value = TestValue::get($id, $field->name);
+						if(!$test_value) {
+							$test_value = new TestValue;
+							$test_value->test_id = $id;
+							$test_value->name = $field->name;
+						}
+						$test_value->value = $value;
+						$test_value->commit();
+					}
+				}
+
+				// TODO: Send email to venue/HQ/tester
+			}
+
+			// Reject test
+			if($reject) {
+				$test->status = Test::STATUS_CANCELLED;
+			}
+
+			if($form_exception->hasErrors()) throw $form_exception;
+
+			$success = $test->commit();
+			if(!$success) throw new Exception("Failed to update the test. Please try again later.");
+
+			// If rejected, recreate empty test for the location
+			if($reject) {
+				$new_test = new Test;
+				$new_test->project_id = $test->project_id;
+				$new_test->location_id = $test->location_id;
+				$new_test->status = Test::STATUS_UNASSIGNED;
+				$new_test->dts_created = Util::getDateTime();
+				$success = $new_test->commit();
+				if(!$success) throw new Exception("Failed to create a new test. Please try again later.");
+			}
+
+			if($accept) {
+				$tester->score++;
+				$tester->commit();
+			}
+
+			Core::addAlert("success", "Test verified successfully.");
+			HTTP::redirect("/account/tests/$id");
+		}
+		catch(FormException $e) {
+			$e->generateAlerts();
+		}
+		catch(Exception $e) {
+			Core::addAlert("danger", $e->getMessage());
+		}
+	}
+
+	View::includeOnce("header", compact("page_title"));
+	View::include("test_verify_form", compact("test", "tester", "location", "project", "template", "fields", "values", "tester_message"));
+	View::includeOnce("footer");
+	return;
+}
+
+// View test results
+else if(Core::$user->level >= User::LEVEL_VENUE) {
+	HTTP::redirect("/account/tests/$id/result");
+}
+else {
+	throw new Exception("Invalid request.");
+}
+
+?>

+ 18 - 0
controllers/test_file.php

@@ -0,0 +1,18 @@
+<?php
+
+$test = Test::get($id);
+if(!$test) throw new Exception("Test not found.");
+
+$directory = $test->getDirectory();
+$path = $directory . "/" . $name . ".jpg";
+
+if(file_exists($path)) {
+	header("Content-Type: image/jpeg");
+	readfile($path);
+}
+else {
+	header("Content-Type: image/png");
+	readfile("public/img/blank.png");
+}
+
+?>

+ 35 - 0
controllers/test_result.php

@@ -0,0 +1,35 @@
+<?php
+
+$test = Test::get($id);
+if(!$test) throw new Exception("Test cannot be found.");
+
+$location = $test->getLocation();
+$project = $test->getProject();
+$tester = $test->getTester();
+$template = $project->getTemplate();
+
+$json = json_decode($template->json);
+$fields = array_merge($json->beforeTest, $json->duringTest);
+$values = $test->getValues();
+
+$names = array_map(function($value) { return $value->name; }, $values);
+
+$values = array_combine(
+	array_map(function($value) { return $value->name; }, $values),
+	array_map(function($value) { return $value->value; }, $values)
+);
+
+$tester = $test->getTester();
+$verifier = $test->getVerifier();
+
+$page_title = $location->name;
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/tests", "Tests");
+Core::addBreadcrumb("/account/tests/$id", $page_title);
+
+View::includeOnce("header", compact("page_title"));
+View::include("test", compact("test", "location", "tester", "verifier", "fields", "values"));
+View::includeOnce("footer");
+
+?>

+ 45 - 0
controllers/tests.php

@@ -0,0 +1,45 @@
+<?php
+
+$page_title = "Tests";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/tests", $page_title);
+
+$user = Core::$user;
+
+// Admin / Super Admin
+if($user->level >= User::LEVEL_ADMIN) {
+
+	$status = http::value("status", "int");
+
+	$nvp = [];
+	if($status) $nvp["status"] = $status;
+
+	$filter_count = count($nvp);
+	if(!$filter_count) $filter_count = "";
+
+	$tests = Test::query($nvp, ["sort" => "status"]);
+
+	View::includeOnce("header", compact("page_title"));
+	View::include("test_list", compact("tests", "filter_count", "status"));
+	View::includeOnce("footer");
+}
+
+// HQ / Venue (view completed tests)
+else if($user->level >= User::LEVEL_VENUE) {
+
+	View::includeOnce("header", compact("page_title"));
+	View::include("test_list_completed", compact("tests"));
+	View::includeOnce("footer");
+}
+
+// Tester
+else if($user->level == User::LEVEL_TESTER) {
+	$tests = $user->getPendingTests();
+
+	View::includeOnce("header", compact("page_title"));
+	View::include("test_list_assigned", compact("tests"));
+	View::includeOnce("footer");
+}
+
+?>

+ 16 - 0
controllers/user.php

@@ -0,0 +1,16 @@
+<?php
+
+$user = User::get($id);
+if(!$user) throw new Exception("User not found.");
+
+$page_title = $user->getDisplayName();
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/users", "Users");
+Core::addBreadcrumb("/account/users/$id", $page_title);
+
+View::includeOnce("header", compact("page_title"));
+View::include("user", compact("user"));
+View::includeOnce("footer");
+
+?>

+ 61 - 0
controllers/user_edit.php

@@ -0,0 +1,61 @@
+<?php
+
+$user = User::get($id);
+if(!$user) throw new Exception("User not found.");
+
+$page_title = "Edit User";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/users", "Users");
+Core::addBreadcrumb("/account/users/$id", $user->getDisplayName());
+Core::addBreadcrumb("/account/users/$id/edit", $page_title);
+
+$submit = http::value("submit");
+if($submit) {
+	try {
+		Core::validateCSRFToken($submit);
+
+		$form_exception = new FormException;
+
+		// Password
+		$password = http::value("password");
+		$password_confirm = http::value("password_confirm");
+
+		if($password != $password_confirm) $form_exception->addError("Passwords do not match.");
+		if($password) {
+			$user->password = password_hash($password, PASSWORD_DEFAULT, ["cost" => 14]);
+		}
+
+		$user->title = http::value("title", "trim");
+		$user->first_name = http::value("first_name", "trim");
+		$user->last_name = http::value("last_name", "trim");
+		$user->date_of_birth = http::value("date_of_birth", "trim");
+		$user->phone = http::value("phone", "trim");
+
+		if(empty($user->email)) $form_exception->addError("Email address is invalid.");
+		if(empty($user->title)) $form_exception->addError("Title is required.");
+		if(empty($user->first_name)) $form_exception->addError("First name is required.");
+		if(empty($user->last_name)) $form_exception->addError("Last name is required.");
+		if(empty($user->date_of_birth)) $form_exception->addError("Date of birth is required.");
+		if(empty($user->phone)) $form_exception->addError("Mobile number is required.");
+
+		if($form_exception->hasErrors()) throw $form_exception;
+
+		$success = $user->commit();
+
+		Core::addAlert("success", "User updated successfully.");
+		HTTP::redirect("/account/users/$id");
+	}
+	catch(FormException $e) {
+		$e->generateAlerts();
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+View::includeOnce("header", compact("page_title"));
+View::include("user_edit_form", compact("user"));
+View::includeOnce("footer");
+
+?>

+ 60 - 0
controllers/user_verify.php

@@ -0,0 +1,60 @@
+<?php
+
+$user = User::get($id);
+if(!$user) throw new Exception("User not found.");
+if($user->level != User::LEVEL_UNVERIFIED) throw new Exception("User level is not unverified.");
+
+$page_title = "Verify User";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/users", "Users");
+Core::addBreadcrumb("/account/users/$id/verify", $page_title);
+
+$submit = http::value("submit");
+if($submit) {
+
+	$accept = http::value("accept");
+	$reject = http::value("reject");
+
+	$verifier_notes = http::value("verifier_notes");
+	$reject_reason = http::value("reject_reason");
+
+	try {
+		Core::validateCSRFToken($submit);
+
+		if($accept) {
+			$user->level = User::LEVEL_TESTER;
+			$user->verifier_id = Core::$user->id;
+			$user->dts_verified = Util::getDateTime();
+			$user->verifier_notes = $verifier_notes;
+		}
+
+		if($reject) {
+			$user->deleteIDFiles();
+			$user->level = User::LEVEL_REGISTERED;
+		}
+
+		$success = $user->commit();
+		if(!$success) throw new Exception("Failed to update user level. Please try again later.");
+
+		if($accept) {
+			// TODO: Send accepted email
+		}
+
+		if($reject) {
+			// TODO: Send rejection email
+		}
+
+		Core::addAlert("success", "User updated successfully.");
+		HTTP::redirect("/account/users");
+	}
+	catch(Exception $e) {
+		Core::addAlert("danger", $e->getMessage());
+	}
+}
+
+View::includeOnce("header", compact("page_title"));
+View::include("user_verify", compact("user"));
+View::includeOnce("footer");
+
+?>

+ 27 - 0
controllers/user_verify_image.php

@@ -0,0 +1,27 @@
+<?php
+
+$user = User::get($id);
+if(!$user) throw new Exception("User not found.");
+
+switch($type) {
+	case "id-document":
+		$file_type = UserFile::TYPE_ID;
+		break;
+	case "photo":
+		$file_type = UserFile::TYPE_PHOTO;
+		break;
+}
+
+$nvp = [
+	"user_id" => $id,
+	"type" => $file_type
+];
+
+$file = UserFile::queryOne($nvp);
+if(!$file) HTTP::redirect("/img/blank.png");
+
+$path = $user->getDirectory() . "/" . $file->id . ".jpg";
+if(!file_exists($path)) HTTP::redirect("/img/blank.png");
+
+header("Content-Type: image/jpeg");
+readfile($path);

+ 31 - 0
controllers/users.php

@@ -0,0 +1,31 @@
+<?php
+
+$page_title = "Users";
+
+Core::addBreadcrumb("/account", "Account");
+Core::addBreadcrumb("/account/users", $page_title);
+
+$first_name = http::value("first_name", "trim");
+$last_name = http::value("last_name", "trim");
+$email = http::value("email", "trim");
+$level = http::value("level", "int");
+
+$customer_id = http::value("customer_id", "int");
+$location_id = http::value("location_id", "int");
+
+$nvp = [];
+if($first_name !== false) $nvp["first_name"] = ((new Constraint("CONTAINS"))->setValues($first_name));
+if($last_name !== false) $nvp["last_name"] = ((new Constraint("CONTAINS"))->setValues($last_name));
+if(strlen($email) > 0) $nvp["email"] = $email;
+if($level !== false) $nvp["level"] = $level;
+
+$filter_count = "";
+if($nvp) $filter_count = count(array_keys($nvp));
+
+$users = User::query($nvp);
+
+View::includeOnce("header", compact("page_title"));
+View::include("users", compact("users", "filter_count", "first_name", "last_name", "email", "level", "customer_id", "location_id"));
+View::includeOnce("footer");
+
+?>

+ 72 - 0
emails/registration.html

@@ -0,0 +1,72 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+	<head>
+		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+		<title>Check Policy</title>
+		<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
+	</head>
+	<body>
+		<table align="center" border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse;">
+			<tr>
+				<td>
+					<table border="0" cellpadding="0" cellspacing="0" width="600" style="border: 1px solid #cccccc;">
+						<tr>
+							<td align="center" style="padding: 40px 0 40px 0; border-bottom: 1px solid #cccccc;">
+								<a href="">
+									<img src="http://local.check-policy.co.uk/img/logo.png" width="200" height="41" style="display: block;" alt="Check Policy logo" />
+								</a>
+							</td>
+						</tr>
+						<tr>
+							<td style="padding: 40px 30px 40px 30px;">
+								<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
+									<tr>
+										<td style="padding: 0 0 20px 0; font-family: Arial, sans-serif;">
+											<b>Dear {name},</b>
+										</td>
+									</tr>
+									<tr>
+										<td style="padding: 0 0 20px 0; font-family: Arial, sans-serif; font-size: 24px;">
+											<b>Thanks for registering!</b>
+										</td>
+									</tr>
+									<tr>
+										<td style="padding: 0 0 20px 0; font-family: Arial, sans-serif;">
+											Before you can use your account we will need you to verify your email address. Simply click on this link to verify your email address:
+										</td>
+									</tr>
+									<tr>
+										<td style="padding: 0 0 20px 0; font-family: Arial, sans-serif;">
+											<a href="{link}">{link}</a>
+										</td>
+									</tr>
+									<tr>
+										<td style="font-family: Arial, sans-serif;">
+											Check Policy Team
+										</td>
+									</tr>
+								</table>
+							</td>
+						</tr>
+						<tr>
+							<td bgcolor="#4CAF50" style="padding: 40px 30px 40px 30px;">
+								<table align="center" border="0" cellpadding="0" cellspacing="0" width="100%">
+									<tr>
+										<td style="font-family: Arial, sans-serif;">
+											<b><font color="#ffffff">&copy; Check Policy 2018</font></b>
+										</td>
+										<td align="right" style="font-family: Arial, sans-serif;">
+											<a href="https://www.facebook.com/checkpolicy" style="color: #ffffff;">
+												<font color="#ffffff">Facebook</font>
+											</a>
+										</td>
+									</tr>
+								</table>
+							</td>
+						</tr>
+					</table>
+				</td>
+			</tr>
+		</table>
+	</body>
+</html>

+ 16 - 0
engine/.model.template.php

@@ -0,0 +1,16 @@
+<?php
+
+class ModelTemplate extends Model {
+
+	protected static $table = "table";
+	protected static $id_field = "id";
+	protected static $fillable_fields = ["field"];
+
+	protected static $field_map = [
+	];
+
+	// Object methods
+
+}
+
+?>

+ 77 - 0
engine/constraint.php

@@ -0,0 +1,77 @@
+<?php
+
+class Constraint {
+
+	const TYPE_LESS_THAN = 0;
+	const TYPE_LESS_THAN_OR_EQUAL = 1;
+	const TYPE_EQUALS = 2;
+	const TYPE_MORE_THAN_OR_EQUAL = 3;
+	const TYPE_MORE_THAN = 4;
+
+	const TYPE_BETWEEN = 5;
+
+	const TYPE_BEGINS_WITH = 6;
+	const TYPE_CONTAINS = 7;
+	const TYPE_ENDS_WITH = 8;
+
+	const TYPE_NOT_EQUALS = 9;
+
+	const TYPE_IS_NULL = 10;
+	const TYPE_NOT_NULL = 11;
+
+	private $type;
+	private $values = [];
+
+	public function __construct($type) {
+		$type = "TYPE_" . strtoupper($type);
+		if(!defined("Constraint::$type")) throw new Exception("Constraint::$type is not defined.");
+		$this->type = constant("Constraint::$type");
+	}
+
+	public function setValues(...$values) {
+		$this->values = array_map("db::escape", $values);
+		return $this;
+	}
+
+	public function getConstraintString() {
+
+		$value_1 = $this->values[0] ?? 0;
+		$value_2 = $this->values[1] ?? 0;
+
+		switch($this->type) {
+			case self::TYPE_LESS_THAN:
+				return " < '$value_1'";
+			case self::TYPE_LESS_THAN_OR_EQUAL:
+				return " <= '$value_1'";
+			case self::TYPE_EQUALS:
+				return " = '$value_1'";
+			case self::TYPE_MORE_THAN_OR_EQUAL:
+				return " >= '$value_1'";
+			case self::TYPE_MORE_THAN:
+				return " > '$value_1'";
+
+			case self::TYPE_BETWEEN:
+				return " BETWEEN '$value_1' AND '$value_2'";
+
+			case self::TYPE_BEGINS_WITH:
+				return " LIKE '$value_1%'";
+			case self::TYPE_CONTAINS:
+				return " LIKE '%$value_1%'";
+			case self::TYPE_ENDS_WITH:
+				return " LIKE '%$value_1'";
+
+			case self::TYPE_NOT_EQUALS:
+				return " != '$value_1'";
+
+			case self::TYPE_IS_NULL:
+				return " IS NULL";
+			case self::TYPE_IS_NOT_NULL:
+				return " IS NOT NULL";
+		}
+
+		return false;
+	}
+
+}
+
+?>

+ 79 - 0
engine/core.php

@@ -0,0 +1,79 @@
+<?php
+
+class Core {
+
+	public static $user = null;
+	public static $admin = false;
+
+	public static $breadcrumbs = [];
+
+	public static $use_default_container = true;
+	public static $show_alerts = true;
+	public static $show_footer_content = true;
+
+	public static $scripts = [];
+
+	public static function addAlert($class, $message) {
+		$alerts = $_SESSION["alerts"] ?? [];
+		$alerts[] = [$class, $message];
+		$_SESSION["alerts"] = $alerts;
+	}
+
+	public static function addBreadcrumb($url, $name) {
+		Core::$breadcrumbs[] = [$url, $name];
+	}
+
+	public static function addScript($path) {
+		Core::$scripts[] = $path;
+	}
+
+	public static function getScripts() {
+		return Core::$scripts;
+	}
+
+	public static function getAlerts() {
+		$alerts = $_SESSION["alerts"] ?? [];
+		unset($_SESSION["alerts"]);
+		return $alerts;
+	}
+
+	public static function requireLogIn() {
+		if(!Core::$user) {
+			$_SESSION["log_in_redirect_uri"] = $_SERVER["REQUEST_URI"];
+			http::redirect("/log-in");
+		}
+	}
+
+	public static function requireAdmin() {
+		Core::requireLogIn();
+		if(Core::$user->canAdmin() === false) {
+			throw new Exception("No permission to access this page.");
+		}
+	}
+
+	public static function requireUserLevel($level) {
+		Core::requireLogIn();
+		if(Core::$user->level < $level) {
+			throw new Exception("No permission to access this page.");
+		}
+	}
+
+	public static function isLoggedIn() {
+		return !empty($_SESSION["user_id"]);
+	}
+
+	public static function validateCSRFToken($token) {
+		if($_SESSION["csrf_token"] !== $token) throw new Exception("CSRF attempt blocked.");
+		return true;
+	}
+
+	public static function refuseAJAX() {
+		if(HTTP::isAJAX()) {
+			header("HTTP/1.1 403 Forbidden");
+			throw new Exception("AJAX calls not allowed.");
+		}
+	}
+
+}
+
+?>

+ 56 - 0
engine/customer.php

@@ -0,0 +1,56 @@
+<?php
+
+class Customer extends Model {
+
+	protected static $table = "customer";
+	protected static $id_field = "id";
+	protected static $fillable_fields = ["name"];
+
+	protected static $field_map = [
+	];
+
+	// Static methods
+	public static function getForAdmin() {
+		$customers = Core::$user->getCustomers();
+		if(count($customers) == 0) throw new Exception("At least one customer must exist before this page can be accessed.");
+		else if(count($customers) == 1) {
+			$customer = array_shift($customers);
+		}
+		else {
+			$customer_id = http::value("customer_id", "int");
+			if(!$customer_id) {
+				View::includeOnce("header", compact("page_title"));
+				View::include("customer_select", compact("customers"));
+				View::includeOnce("footer");
+			}
+
+			$customer = Customer::get($customer_id);
+
+			// Enforce restriction if CUSTOMER or lower
+			if(Core::$user->level < User::LEVEL_ADMIN) {
+				$link = UserCustomer::get(Core::$user->id, $customer_id);
+				if(!$link) $customer = false;
+			}
+		}
+
+		if(empty($customer)) throw new Exception("Customer not found.");
+
+		return $customer;
+	}
+
+	// Object methods
+	public function getLocations() {
+		return Location::query(["customer_id" => $this->id], ["sort" => "name"]);
+	}
+
+	public function getProjects() {
+		return Project::query(["customer_id" => $this->id], ["sort" => "dts_deadline", "order" => "desc"]);
+	}
+
+	public function getTemplates() {
+		return Template::query(["customer_id" => $this->id], ["sort" => "name"]);
+	}
+
+}
+
+?>

+ 198 - 0
engine/db.php

@@ -0,0 +1,198 @@
+<?php
+
+class db {
+
+	public static $last_query = "";
+
+	public static $queries = [];
+	public static $query_count = 0;
+
+	public static $DB = null;
+
+	public static function affected_rows($link = null) {
+		if(empty($link)) $link = db::$DB;
+		return mysqli_affected_rows($link);
+	}
+
+	public static function cast_all_rows($result, $class_name) {
+		$objects = [];
+		while($row = db::fetch_object($result)) {
+			$objects[] = new $class_name($row);
+		}
+		return $objects;
+	}
+
+	public static function connect($host, $username, $password, $database = "", $port = 3306) {
+		db::$DB = @new mysqli($host, $username, $password, $database, $port);
+		if(!is_null(db::$DB->connect_error)) {
+			throw new Exception("Connect Error: " . db::$DB->connect_error);
+		}
+		db::query("SET NAMES utf8mb4");
+		return db::$DB;
+	}
+
+	public static function data_seek($result, $row_number) {
+		mysqli_data_seek($result, $row_number);
+	}
+
+	public static function escape($string) {
+		return mysqli_real_escape_string(db::$DB, $string);
+	}
+
+	public static function error() {
+		return mysqli_error(db::$DB);
+	}
+
+	public static function fetch_array($result) {
+		return mysqli_fetch_array($result);
+	}
+
+	public static function fetch_assoc($result) {
+		return mysqli_fetch_assoc($result);
+	}
+
+	public static function fetch_object($result) {
+		return mysqli_fetch_object($result);
+	}
+
+	public static function fetch_row($result) {
+		return mysqli_fetch_row($result);
+	}
+
+	public static function free_result($result) {
+		mysqli_free_result($result);
+	}
+
+	public static function get_value_string($pairs, $escape=false) {
+
+		if($escape) {
+			$pairs = array_map(array("db", "escape"), $pairs);
+		}
+
+		$string_array = array();
+
+		foreach($pairs as $field => $value) {
+			if(is_null($value)) {
+				$string_array[] = "`$field`=NULL";
+			}
+			else if(stripos($field, "binary")!==false && stripos($value, "x'")===0) {
+				$string_array[] = "`$field`=$value";
+			}
+			else {
+				$string_array[] = "`$field`='$value'";
+			}
+		}
+		return implode(", ", $string_array);
+	}
+
+	public static function get_where_string($pairs, $options = []) {
+
+		$escape = false;
+		$fuzzy = false;
+
+		if(is_bool($options)) { // Legacy escape
+			$escape = $options;
+		}
+
+		if(is_array($options)) {
+			$escape = $options["escape"] ?? false;
+			$fuzzy = $options["fuzzy"] ?? false;
+		}
+
+
+		if($escape) {
+			$pairs = array_map(array("db", "escape"), $pairs);
+		}
+
+		$string_array = array();
+
+		foreach($pairs as $field => $value) {
+			if(is_null($value)) {
+				$string_array[] = "`$field` IS NULL";
+			}
+			else if(is_array($value)) {
+				$values = array_map(function($str) {
+					return "'$str'";
+				}, $value);
+
+				$string_array[] = "`$field` IN (" . implode(", ", $values) . ")";
+			}
+			else if(is_a($value, "Constraint")) {
+				$string_array[] = "`$field` " . $value->getConstraintString();
+			}
+			else {
+				$string_array[] = $fuzzy ? "`$field` LIKE '%$value%'" : "`$field`='$value'";
+			}
+		}
+		return implode(" AND ", $string_array);
+	}
+
+	public static function has_index($table, $index_name) {
+		$sql = "SHOW INDEX FROM `$table` WHERE `Key_name`='$index_name'";
+		$result = db::query($sql);
+		return db::num_rows($result)==1;
+	}
+
+	public static function insert_id() {
+		return mysqli_insert_id(db::$DB);
+	}
+
+	public static function num_rows($result) {
+
+		if(is_bool($result)) {
+			return 0;
+		}
+
+		return mysqli_num_rows($result);
+	}
+
+	public static function object_or_false($result) {
+		return mysqli_num_rows($result)>0 ? db::fetch_object($result) : false;
+	}
+
+	public static function object_with_id($table, $field, $id) {
+		$sql = "SELECT * FROM `$table` WHERE `$field`='$id'";
+		$result = db::query($sql);
+		return db::object_or_false($result);
+	}
+
+	public static function ping() {
+		return mysqli_ping(db::$DB);
+	}
+
+	public static function query($sql) {
+		if(!is_string($sql)) return false;
+
+		self::$last_query = $sql;
+
+		$result = mysqli_query(db::$DB, $sql);
+		if(!$result) {
+			if(!PRODUCTION) {
+				throw new Exception("Query failed: $sql");
+			}
+			else {
+				throw new Exception("A database error has occurred. Please try again later.");
+			}
+		}
+
+		self::$queries[] = $sql;
+		self::$query_count++;
+
+		return $result;
+	}
+
+	public static function select_db($name, $link_identifier=NULL) {
+		if(is_null($link_identifier)) {
+			mysqli_select_db(db::$DB, $name);
+		}
+		else {
+			mysqli_select_db($link_identifier, $name);
+		}
+	}
+
+	public static function thread_id() {
+		return mysqli_thread_id(db::$DB);
+	}
+}
+
+?>

+ 82 - 0
engine/email.php

@@ -0,0 +1,82 @@
+<?php
+
+use PHPMailer\PHPMailer\PHPMailer;
+
+class Email {
+
+	private $instance;
+
+	private $htmlContent = "";
+
+	// Static functions
+	public static function getPHPMailerInstance() {
+		$mail = new PHPMailer(true);
+		$mail->isSMTP();
+		$mail->Host = SMTP_HOST;
+		$mail->SMTPAuth = true;
+		$mail->Username = SMTP_USERNAME;
+		$mail->Password = SMTP_PASSWORD;
+		$mail->SMTPSecure = SMTP_AUTHENTICATION_TYPE;
+		$mail->Port = SMTP_PORT;
+		return $mail;
+	}
+
+	public function __construct() {
+		$this->instance = Email::getPHPMailerInstance();
+	}
+
+	public function loadHtmlTemplate($template_name) {
+
+		$this->instance->IsHTML(true);
+
+		$path = "emails/$template_name.html";
+		if(!file_exists($path)) throw new Exception("Email HTML template \"$template_name\" cannot be found.");
+
+		$this->htmlContent = file_get_contents($path);
+	}
+
+	public function setValues($values = []) {
+		foreach($values as $key => $value) {
+			$this->htmlContent = str_replace("{" . $key . "}", $value, $this->htmlContent);
+		}
+		return true;
+	}
+
+	public function setFrom($email, $name="") {
+		return $this->instance->setFrom($email, $name);
+	}
+
+	public function addAddress($email, $name="") {
+		return $this->instance->addAddress($email, $name);
+	}
+
+	public function setSubject($subject) {
+		$this->instance->Subject = $subject;
+		return true;
+	}
+
+	public function send() {
+		// Does our sanity checks and then send email
+		$instance = $this->instance;
+
+		$to_addresses = $instance->getToAddresses();
+		if(empty($to_addresses)) throw new Exception("No recipients are set.");
+		if(empty($instance->Subject)) throw new Exception("No subject is set.");
+		if(empty($this->htmlContent)) throw new Exception("No content is set.");
+
+		$count = preg_match_all("/\{([a-z\-]+)\}/", $this->htmlContent, $matches);
+		if($count > 0) {
+			$missing_keys = [];
+			foreach($matches[1] as $key) {
+				$missing_keys[] = $key;
+			}
+			throw new Exception("Missing values: " . implode(", ", $missing_keys));
+		}
+
+		$instance->Body = $this->htmlContent;
+
+		return $this->instance->send();
+
+	}
+
+}

+ 102 - 0
engine/form.php

@@ -0,0 +1,102 @@
+<?php
+
+class Form {
+
+	public static function renderField($options) {
+
+		switch($options->type) {
+
+			case "header":
+				self::renderHeader($options);
+				break;
+
+			case "dropdown":
+			case "select":
+				self::renderSelectField($options);
+				break;
+
+			case "text":
+				self::renderTextField($options);
+				break;
+
+			case "textarea":
+				self::renderTextareaField($options);
+				break;
+
+			case "file":
+				self::renderFileField($options);
+				break;
+		}
+
+	}
+
+	private static function renderHeader($options) {
+		?>
+		<h3><?=htmlspecialchars($options->content)?></h3>
+		<?php
+	}
+
+	private static function renderTextField($options) {
+		$id = str_replace("_", "-", $options->name);
+		$placeholder = "Enter " . strtolower($options->label);
+		$value = $options->value ?? http::value($options->name);
+		$required = ($options->required ?? false) ? "required" : "";
+		?>
+		<div class="form-group">
+			<label for="<?=$id?>"><?=htmlspecialchars($options->label)?></label>
+			<input class="form-control" type="text" name="<?=$options->name?>" id="<?=$id?>" placeholder="<?=htmlspecialchars($placeholder)?>" value="<?=htmlspecialchars($value)?>" <?=$required?> />
+		</div>
+		<?php
+	}
+
+	private static function renderSelectField($options) {
+		$id = str_replace("_", "-", $options->name);
+		$selected_value = $options->value ?? http::value($options->name);
+		$required = ($options->required ?? false) ? "required" : "";
+
+		?>
+		<div class="form-group">
+			<label for="<?=$id?>"><?=htmlspecialchars($options->label)?></label>
+			<select class="form-control" name="<?=$options->name?>" id="<?=$id?>" <?=$required?>>
+			<?php
+			foreach($options->values as $index => $value) {
+				$display = $options->displayStrings[$index];
+				$selected = ($selected_value === strval($value)) ? "selected" : "";
+				?>
+				<option value="<?=htmlspecialchars($value)?>" <?=$selected?>><?=htmlspecialchars($display)?></option>
+				<?php
+			}
+			?>
+			</select>
+		</div>
+		<?php
+	}
+
+	private static function renderFileField($options) {
+		$id = str_replace("_", "-", $options->name);
+		$placeholder = "Enter " . strtolower($options->label);
+		$required = ($options->required ?? false) ? "required" : "";
+		?>
+		<div class="form-group">
+			<label for="<?=$id?>"><?=htmlspecialchars($options->label)?></label>
+			<input class="form-control-file" type="file" name="<?=$options->name?>" id="<?=$id?>" accept="image/*" capture="camera" <?=$required?> />
+		</div>
+		<?php
+	}
+
+	private static function renderTextareaField($options) {
+		$id = str_replace("_", "-", $options->name);
+		$placeholder = "Enter " . strtolower($options->label);
+		$value = $options->value ?? http::value($options->name);
+		$required = ($options->required ?? false) ? "required" : "";
+		?>
+		<div class="form-group">
+			<label for="<?=$id?>"><?=htmlspecialchars($options->label)?></label>
+			<textarea class="form-control" name="<?=$options->name?>" id="<?=$id?>" placeholder="<?=htmlspecialchars($placeholder)?>" rows="4" <?=$required?>><?=htmlspecialchars($value)?></textarea>
+		</div>
+		<?php
+	}
+
+}
+
+?>

+ 25 - 0
engine/form_exception.php

@@ -0,0 +1,25 @@
+<?php
+
+class FormException extends Exception {
+
+	private $errors = [];
+
+	public function addError($error_message) {
+		$this->errors[] = $error_message;
+	}
+
+	public function getErrors() {
+		return $this->errors;
+	}
+
+	public function hasErrors() {
+		return !empty($this->errors);
+	}
+
+	public function generateAlerts() {
+		foreach($this->getErrors() as $message) {
+			Core::addAlert("danger", $message);
+		}
+	}
+
+}

+ 87 - 0
engine/geolocation.php

@@ -0,0 +1,87 @@
+<?php
+
+class Geolocation {
+
+	const UNIT_MILES = 0;
+	const UNIT_KILOMETERS = 1;
+
+	const MILES_IN_KM = 0.621371;
+	const KMS_IN_MILE = 1.60934;
+
+
+	public static function getBounds($lat_lng, $distance, $units = Geolocation::UNIT_MILES) {
+
+		list($latitude, $longitude) = $lat_lng;
+
+		// Find latitude radius
+		for($latitude_radius = $found_distance = 0; $found_distance < $distance; $latitude_radius += 0.001) {
+			$found_distance = Geolocation::getDistance($lat_lng, [$latitude + $latitude_radius, $longitude], $units);
+		}
+
+		// Find longitude radius
+		for($longitude_radius = $found_distance = 0; $found_distance < $distance; $longitude_radius += 0.001) {
+			$found_distance = Geolocation::getDistance($lat_lng, [$latitude, $longitude + $longitude_radius], $units);
+		}
+
+		$min_latitude = $latitude - $latitude_radius;
+		$max_latitude = $latitude + $latitude_radius;
+		$min_longitude = $longitude - $longitude_radius;
+		$max_longitude = $longitude + $longitude_radius;
+
+		return (object) [
+			"southWest" => [$min_latitude, $min_longitude],
+			"northEast" => [$max_latitude, $max_longitude],
+		];
+	}
+
+	public static function getDistance($from, $to, $units = Geolocation::UNIT_MILES) {
+
+		if(empty($from) || empty($to)) {
+			return false;
+		}
+
+		$src_lat = $from[0];
+		$src_lng = $from[1];
+
+		$lat = $to[0];
+		$lng = $to[1];
+
+		$delta_lng = deg2rad($lng-$src_lng);
+		$delta_lat = deg2rad($lat-$src_lat);
+
+		$radius = 6371;
+
+		$a = pow(sin($delta_lat/2), 2) + cos(deg2rad($lat))*cos(deg2rad($src_lat))*pow(sin($delta_lng/2), 2);
+		$c = 2*atan2(sqrt($a), sqrt(1-$a));
+		$distance = $radius*$c; // distance in km
+
+		switch($units) {
+			case Geolocation::UNIT_MILES:
+				return round($distance*10)/10;
+			case Geolocation::UNIT_KILOMETERS:
+				return round($distance / 0.1609344)/10;
+			default:
+				return false;
+		}
+	}
+
+	public static function geocode($address) {
+		$query = [
+			"address" =>  $address,
+			"key" => GOOGLE_API_KEY,
+			"region" => "uk",
+		];
+
+		$url = "https://maps.googleapis.com/maps/api/geocode/json?" . http_build_query($query);
+
+		$string = @file_get_contents($url);
+
+		$object = json_decode($string);
+		if(!$object) throw new Exception("Failed to validate address.");
+		if($object->status != "OK") throw new Exception("Failed to validate address.");
+
+		$results = $object->results;
+
+		return $results;
+	}
+}

+ 14 - 0
engine/html.php

@@ -0,0 +1,14 @@
+<?php
+
+class HTML {
+	public static function script($path) {
+		if(!file_exists($path)) return;
+		$modified_time = filemtime($path);
+		$src = preg_replace("/^public\//", "/", $path);
+		?>
+		<script type="text/javascript" src="<?=htmlspecialchars($src)?>?<?=$modified_time?>"></script>
+		<?php
+	}
+}
+
+?>

+ 180 - 0
engine/http.php

@@ -0,0 +1,180 @@
+<?php
+
+class HTTP {
+
+	public static $curl_last_error = "";
+
+	public static function isAJAX() {
+		return (!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest");
+	}
+
+	public static function post($url, $fields_or_data, $curl_options = []) {
+
+		$curl_handle = curl_init($url);
+
+		curl_setopt($curl_handle, CURLOPT_POST, 1);
+		curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $fields_or_data);
+		curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
+
+		if(!empty($curl_options)) {
+			foreach($curl_options as $option => $value) {
+				curl_setopt($curl_handle, $option, $value);
+			}
+		}
+
+		$result = curl_exec($curl_handle);
+
+		if($result === false) {
+			http::$curl_last_error = curl_error($curl_handle);
+			throw new Exception("cURL Error: " . curl_error($curl_handle));
+		}
+
+		return $result;
+	}
+
+	public static function value($key, $validation = "none", $request_type = "request") {
+
+		$request_type = strtolower($request_type);
+
+		switch($request_type) {
+
+			case "request":
+				$array = $_REQUEST;
+				break;
+			case "get":
+				$array = $_GET;
+				break;
+			case "post":
+				$array = $_POST;
+				break;
+			default:
+				trigger_error("http::value called with \"$request_type\" request_type", E_USER_ERROR);
+				break;
+		}
+
+		if(!isset($array[$key])) return false;
+
+		$value = $array[$key];
+
+		switch($validation) {
+
+			case "int": {
+				if(strlen($value)===0) return false;
+				return is_array($value) ? array_map("intval", $value) : intval($value);
+			}
+
+			case "double":
+			case "float": {
+				if(strlen($value)===0) return false;
+				return floatval($value);
+			}
+
+			// Return database escaped string
+			case "db": {
+				return is_array($value) ? array_map("db::escape", $value) : db::escape($value);
+			}
+
+			case "html": {
+				return is_array($value) ? array_map("htmlspecialchars", $value) : htmlspecialchars($value);
+			}
+
+			case "trim": {
+				return is_array($value) ? array_map("trim", $value) : trim($value);
+			}
+
+			case "":
+			case "none": {
+				return $value;
+			}
+
+			case "email": {
+				return filter_var($value, FILTER_VALIDATE_EMAIL);
+			}
+
+			default: {
+				throw new Exception("Unknown validation type: $validation");
+			}
+		}
+
+	}
+
+	public static function redirect($url) {
+		header("HTTP/1.1 303 See Other");
+		header("Location: " . $url);
+		exit;
+	}
+
+	public static function isSSL() {
+		if(isset($_SERVER["SERVER_PORT"])) {
+			return $_SERVER["SERVER_PORT"] == 443;
+		}
+
+		return false;
+	}
+
+	public static function getProtocol() {
+		return (HTTP::isSSL()) ? "https" : "http";
+	}
+
+	public static function getUploadErrorString($error, $name = "file") {
+		switch($error) {
+			case UPLOAD_ERR_OK: return "The $name uploaded successfully.";
+			case UPLOAD_ERR_INI_SIZE: return "The $name uploaded was too large.";
+			case UPLOAD_ERR_FORM_SIZE: return "The $name uploaded was too large.";
+			case UPLOAD_ERR_PARTIAL: return "The $name uploaded was only partially uploaded.";
+			case UPLOAD_ERR_NO_FILE: return "No $name was uploaded.";
+			case UPLOAD_ERR_NO_TMP_DIR: return "The $name cannot be uploaded as the temporary folder is missing.";
+			case UPLOAD_ERR_CANT_WRITE: return "The $name cannot be written to disk.";
+			case UPLOAD_ERR_EXTENSION: return "The $name uploaded was blocked by an extension.";
+		}
+		return "Unknown error.";
+	}
+
+	public static function setStatusCode($code) {
+		switch ($code) {
+			case 403:
+				$string = "403 Forbidden";
+				break;
+			case 404:
+				$string = "404 Not Found";
+				break;
+			default:
+				$string = "200 OK";
+				break;
+		}
+		header("HTTP/1.1 $string");
+	}
+
+	public static function validateUploadedFile($file) {
+		$file = (object) $file;
+		if($file->error > 0) {
+			switch($file->error) {
+				case UPLOAD_ERR_NO_FILE: throw new Exception("No file was submitted."); break;
+				case UPLOAD_ERR_INI_SIZE: throw new Exception("The uploaded file was too large."); break;
+			}
+			throw new Exception("The uploaded file could not be stored. Please try again later.");
+		}
+		return true;
+	}
+
+	public static function sendFile($path) {
+		$modified_time = filemtime($path);
+		$mime_type = Picture::getFileMIMEType($path);
+
+		$max_age = 7 * 86400;
+
+		header("Cache-Control: public, max-age=$max_age");
+
+		header("Expires: " . date("r", time() + $max_age));
+		header("Pragma: cache");
+
+		header("Last-Modified: " . date("r", $modified_time));
+
+		header("X-Sendfile: " . $path);
+		header("Content-Type: " . $mime_type);
+	}
+
+
+}
+
+?>

+ 62 - 0
engine/image.php

@@ -0,0 +1,62 @@
+<?php
+
+class Image {
+
+	// Takes an image and makes the largest dimension 1920 pixels large and rotates it according to EXIF data.
+
+	public static function normalise($path, $size = 1920) {
+
+		$size = getimagesize($path);
+
+		list($width, $height, $type) = $size;
+
+		$exif = exif_read_data($path);
+		$orientation = 0;
+		$rotate_angle = 0;
+		$is_flipped = false;
+		if($exif !== false) {
+			$orientation = $exif["Orientation"] ?? 0;
+			if(in_array($orientation, [6, 5])) $rotate_angle = 270;
+			if(in_array($orientation, [3, 4])) $rotate_angle = 180;
+			if(in_array($orientation, [8, 7])) $rotate_angle = 90;
+			if(in_array($orientation, [5, 4, 7])) $is_flipped = true;
+		}
+
+		$original_image = imagecreatefromjpeg($path);
+
+		if($width > $height) {
+			if($width > 1920) {
+				$width = 1920;
+			}
+		}
+		else {
+			if($height > 1920) {
+				$ratio = $height / 1920;
+				$width = floor($width / $ratio);
+			}
+		}
+
+		// Resize
+		if($width != $size[0]) {
+			$output_image = imagescale($original_image, $width, -1, IMG_BICUBIC);
+			imagedestroy($original_image);
+		}
+		else {
+			$output_image = $original_image;
+		}
+
+		// Rotate
+		if($rotate_angle) {
+			$output_image = imagerotate($output_image, $rotate_angle, 0);
+		}
+
+		// Flip
+		if($is_flipped) {
+			$output_image = imageflip($output_image, IMG_FLIP_HORIZONTAL);
+		}
+
+		return $output_image;
+
+	}
+
+}

+ 45 - 0
engine/json.php

@@ -0,0 +1,45 @@
+<?php
+
+class JSON {
+
+	public static function header() {
+		header("Content-Type: application/json");
+	}
+
+	public static function success($array=array()) {
+
+		$flags = PRODUCTION ? 0 : JSON_PRETTY_PRINT;
+
+		$output = array(
+			"success" => true,
+		);
+
+		$output = array_merge($output, $array);
+
+		die(json_encode($output, $flags));
+
+	}
+
+	public static function fail($array = []) {
+
+		$flags = PRODUCTION ? 0 : JSON_PRETTY_PRINT;
+
+		$output = array(
+			"success" => false
+		);
+
+		if(is_string($array)) {
+			$array = [
+				"message" => $array,
+			];
+		}
+
+		$output = array_merge($output, $array);
+
+		die(json_encode($output, $flags));
+
+	}
+
+}
+
+?>

+ 33 - 0
engine/location.php

@@ -0,0 +1,33 @@
+<?php
+
+class Location extends Model {
+
+	protected static $table = "location";
+	protected static $id_field = "id";
+	protected static $fillable_fields = ["customer_id", "name", "address_1", "address_2", "city", "county", "postal_code", "state", "country", "latitude", "longitude", "dts_verified"];
+
+	protected static $field_map = [
+	];
+
+	// Object methods
+	public function getCustomer() {
+		return Customer::get($this->customer_id);
+	}
+
+	public function getDisplayAddress($fields = ["address_1", "address_2", "city", "county", "postal_code", "state", "country"]) {
+		$parts = [];
+
+		foreach($fields as $field) {
+			$parts[] = $this->$field;
+		}
+
+		return implode(", ", array_filter($parts));
+	}
+
+	public function getGeolocation() {
+		return [$this->latitude, $this->longitude];
+	}
+
+}
+
+?>

+ 453 - 0
engine/model.php

@@ -0,0 +1,453 @@
+<?php
+
+abstract class Model {
+
+	protected static $table = "";
+	protected static $id_field = "";
+	protected static $fillable_fields = [];
+	protected static $enforce_field_check = true;
+	protected static $field_map = []; // Used for field name aliases
+	protected static $object_fields = [];
+	protected static $blob_fields = [];
+	protected static $repositories = [];
+
+	// Object variables
+	protected $model_data;
+	protected $modified_fields = [];
+	protected $in_db;
+
+	// Magic methods
+	public function __get($name) {
+
+		if(in_array($name, static::$object_fields)) {
+			return $this->$name ?? null;
+		}
+
+		if(isset(static::$field_map[$name])) {
+			$name = static::$field_map[$name];
+		}
+
+		return isset($this->model_data->$name) ? $this->model_data->$name : null;
+	}
+
+	public function __set($name, $value) {
+
+		if(in_array($name, static::$object_fields)) {
+			$this->$name = $value;
+			return;
+		}
+
+		if(isset(static::$field_map[$name])) {
+			$name = static::$field_map[$name];
+		}
+
+		$id_field = static::$id_field;
+
+		if($name == "model_data") {
+			$this->model_data = $value;
+		}
+		else if(in_array($name, static::$fillable_fields)) {
+
+			if(!is_null($value)) {
+				$value = strval($value);
+			}
+
+			if(!isset($this->model_data->$name) || ($this->model_data->$name !== $value)) {
+				$this->model_data->$name = $value;
+				$this->modified_fields[] = $name;
+			}
+		}
+		else if($name == $id_field && empty($this->model_data->$id_field)) {
+			$this->model_data->$id_field = $value;
+		}
+		else if(static::$enforce_field_check) {
+			throw new Exception("Attempt to set an unfillable field $name");
+		}
+		else {
+			$this->model_data->$name = $value;
+		}
+	}
+
+	public function __isset($name) {
+		$value = $this->$name;
+		return !is_null($value);
+	}
+
+	// Static method
+
+	public static function get($id) {
+
+		$table = static::$table;
+
+		// Check repo for item
+		if(!is_array($id) && isset(static::$repositories[$table][$id])) {
+			return static::$repositories[$table][$id];
+		}
+
+		$id_field = static::$id_field;
+		$class = get_called_class();
+
+		if(is_array($id_field)) { // Compound key
+			$args = func_get_args();
+			$fields = $id_field;
+
+			if(count($args) != count($fields)) return false;
+
+			foreach($fields as $index => $field) {
+				$nvp[$field] = $args[$index];
+			}
+		}
+		else {
+			$nvp[$id_field] = $id;
+		}
+
+		$where = db::get_where_string($nvp, true);
+
+		$sql = "SELECT * FROM `$table` WHERE $where";
+		$result = db::query($sql);
+		$object = db::object_or_false($result);
+
+		if($object) {
+			$object = new $class($object);
+			if(!is_array($id)) {
+				static::$repositories[$table][$id] = $object;
+			}
+		}
+
+		return $object;
+	}
+
+	public static function getOrException($id, $exception_message = false) {
+
+		if(!$exception_message) $exception_message = get_called_class() . " not found.";
+
+		$object = static::get($id);
+		if(!$object) throw new Exception($exception_message);
+		return $object;
+	}
+
+	public static function getAll() {
+		$objects = [];
+
+		$table = static::$table;
+
+		$sql = "SELECT * FROM `$table`";
+		$result = db::query($sql);
+		while($row = db::fetch_object($result)) {
+			$objects[] = new static($row);
+		}
+
+		return $objects;
+	}
+
+	public static function load(...$id_sets) {
+
+		$table = static::$table;
+
+		$ids = [];
+		foreach($id_sets as $set) {
+			$ids = array_merge($ids, $set);
+		}
+
+		if(empty($ids)) return [];
+
+		$ids = array_unique($ids);
+
+		$items = static::query([static::$id_field => $ids], ["id_as_key" => true]);
+		foreach($items as $id => $item) {
+			static::$repositories[$table][$id] = $item;
+		}
+
+		return $items;
+	}
+
+	public static function loadAll() {
+		$table = static::$table;
+
+		$items = static::query([], ["id_as_key" => true]);
+		foreach($items as $id => $item) {
+			static::$repositories[$table][$id] = $item;
+		}
+
+		return $items;
+	}
+
+	public static function deleteMultiple($nvp = []) {
+		$table = static::$table;
+
+		$vs = "1";
+		if(!empty($nvp)) {
+			$nvp = static::getRemappedNVP($nvp);
+			$vs = db::get_where_string($nvp);
+		}
+
+		$objects = [];
+
+		$sql = "DELETE FROM `$table` WHERE $vs";
+		$result = db::query($sql);
+		if(!$result) return false;
+
+		return db::affected_rows();
+	}
+
+	public static function query($nvp = [], $options = []) {
+		if(is_array($nvp)) {
+			return static::findByNVP($nvp, $options);
+		}
+		else {
+			return static::findByValueString($nvp, $options);
+		}
+	}
+
+	public static function queryFuzzy($nvp = [], $options = []) {
+		$options["fuzzy"] = true;
+		return static::findByNVP($nvp, $options);
+	}
+
+	public static function queryOne($nvp = [], $options = []) {
+		$rows = static::findByNVP($nvp, $options);
+		return $rows ? $rows[0] : false;
+	}
+
+	private static function getRemappedNVP($nvp = []) {
+		$mapped_nvp = [];
+		foreach($nvp as $field => $value) {
+			$field = static::$field_map[$field] ?? $field;
+			$mapped_nvp[$field] = $value;
+		}
+		return $mapped_nvp;
+	}
+
+	public static function count($nvp = []) {
+		$table = static::$table;
+
+		$vs = "1";
+		if(!empty($nvp)) {
+			$nvp = static::getRemappedNVP($nvp);
+			$vs = db::get_where_string($nvp);
+		}
+
+		$objects = [];
+
+		$sql = "SELECT COUNT(*) AS `count` FROM `$table` WHERE $vs";
+		$result = db::query($sql);
+		$row = db::fetch_object($result);
+
+		return $row->count;
+	}
+
+	public static function findByNVP($nvp, $options = []) {
+
+		if(empty($nvp)) {
+			$vs = "1";
+		}
+		else {
+			$nvp = static::getRemappedNVP($nvp);
+			$vs = db::get_where_string($nvp, $options);
+		}
+
+		return static::findByValueString($vs, $options);
+	}
+
+	private static function findByValueString($vs, $options = []) {
+		$table = static::$table;
+
+		$options = (object) $options;
+
+		$objects = [];
+
+		$sql = "SELECT * FROM `$table` WHERE $vs";
+
+		if(isset($options->sort)) {
+			$sort = static::$field_map[$options->sort] ?? $options->sort;
+
+			$sql .= " ORDER BY `$sort`";
+			if(isset($options->order)) {
+				$sql .= " " . strtoupper($options->order);
+			}
+		}
+
+		if(isset($options->limit)) {
+			$sql .= " LIMIT";
+			if(isset($options->offset)) {
+				$sql .= " $options->offset,";
+			}
+			$sql .= " $options->limit";
+		}
+
+		$result = db::query($sql);
+		while($row = db::fetch_object($result)) {
+			$objects[] = new static($row);
+		}
+
+		if(!empty($options->id_as_key)) {
+			$objects = Util::arrayFlipByID($objects);
+		}
+
+		return $objects;
+	}
+
+	// Constructor
+	public function __construct($model_data = null) {
+
+		if(is_null($model_data)) {
+			$model_data = (object) [];
+		}
+		if(is_array($model_data)) {
+			$model_data = (object) $model_data;
+		}
+
+		$this->model_data = $model_data;
+
+		$this->in_db = !is_null($this->getID());
+
+	}
+
+	// Object methods
+	public final function isModified() {
+		return !empty($this->modified_fields);
+	}
+
+	public final function getModifiedFields() {
+		return $this->modified_fields;
+	}
+
+	private function preCommit() {
+	}
+
+	private final function getIDWhere() {
+
+		$id_field = static::$id_field;
+		$id = $this->getID();
+
+		$nvp = [];
+		if(is_array($id)) {
+			$nvp = array_combine($id_field, $id);
+		}
+		else {
+			$nvp[$id_field] = $id;
+		}
+
+		$where = db::get_where_string($nvp, true);
+
+		return $where;
+	}
+
+	public final function commit($testing = false) {
+
+		$this->preCommit();
+
+		$id_field = static::$id_field;
+		$table = static::$table;
+		$blob_fields = static::$blob_fields;
+
+		$nvp = [];
+
+		foreach($this->modified_fields as $field) {
+			if(in_array($field, $blob_fields)) {
+				$nvp[$field] = "x'" . bin2hex($this->model_data->$field) . "'";
+			}
+			// NULL
+			else if(is_null($this->model_data->$field)) {
+				$nvp[$field] = null;
+			}
+			// Value
+			else {
+				$nvp[$field] = db::escape($this->model_data->$field);
+			}
+		}
+
+		if(empty($nvp)) return true;
+
+		$value_string = db::get_value_string($nvp);
+
+		if($this->in_db) {
+			// Update
+			$where = $this->getIDWhere();
+			$sql = "UPDATE `$table` SET $value_string WHERE $where";
+		}
+		else {
+			// Insert
+			$sql = "INSERT INTO `$table` SET $value_string";
+		}
+
+		if($testing == false) {
+			$result = db::query($sql);
+
+			if(empty($this->in_db) && $result) {
+				// Set ID
+				$insert_id = db::insert_id();
+				if(!empty($insert_id)) {
+					$this->$id_field = $insert_id;
+				}
+				$this->in_db = true;
+			}
+		}
+		else {
+			db::$last_query = $sql;
+
+			$result = true;
+			if(empty($this->in_db) && !is_array(static::$id_field)) {
+				$this->$id_field = mt_rand(1, 32768);
+			}
+			$this->in_db = true;
+		}
+
+		return !empty($result);
+	}
+
+	public function testCommit() {
+		return $this->commit(true);
+	}
+
+	public final function commitOrException($testing = false) {
+		$success = $this->commit($testing);
+		if(!$success) throw new Exception("Database error.");
+		return $success;
+	}
+
+	public function delete() {
+		$table = static::$table;
+
+		$id = $this->getID();
+
+		if(is_null($id)) return false;
+
+		$where = $this->getIDWhere();
+
+		$sql = "DELETE FROM `$table` WHERE $where";
+		$result = db::query($sql);
+
+		return empty($result) ? false : db::affected_rows() ? true : false;
+	}
+
+	public final function deleteOrException() {
+		$success = $this->delete();
+		if(!$success) throw new Exception("Database error.");
+		return $success;
+	}
+
+	public final function getID() {
+		$id_field = static::$id_field;
+		if(is_array($id_field)) {
+			$values = [];
+			$fields = $id_field;
+			foreach($fields as $field) {
+				$value = $this->model_data->$field ?? null;
+				if(is_null($value)) return null;
+				$values[] = $this->model_data->$field;
+			}
+			return $values;
+		}
+		else {
+			return $this->model_data->$id_field ?? null;
+		}
+	}
+
+	public final function getModelData() {
+		return clone $this->model_data;
+	}
+
+}
+
+?>

+ 67 - 0
engine/project.php

@@ -0,0 +1,67 @@
+<?php
+
+class Project extends Model {
+
+	protected static $table = "project";
+	protected static $id_field = "id";
+	protected static $fillable_fields = ["customer_id", "template_id", "name", "test_count", "min_age", "max_age", "default_tester_fee", "dts_start", "dts_deadline", "dts_created", "dts_updated"];
+
+	protected static $field_map = [
+	];
+
+	// Object methods
+	public function getCustomer() {
+		return Customer::get($this->customer_id);
+	}
+
+	public function getTests() {
+
+		$nvp = [];
+		$nvp["project_id"] = $this->id;
+		$nvp["status"] = (new Constraint("MORE_THAN"))->setValues(Test::STATUS_CANCELLED);
+
+		return Test::query($nvp);
+	}
+
+	public function getLocations() {
+		$links = ProjectLocation::query(["project_id" => $this->id]);
+		return Location::query(["id" => array_column($links, "location_id")]);
+	}
+
+	public function getDisplayAgeRange() {
+
+		if($this->min_age && $this->max_age) {
+			return $this->min_age . " to " . $this->max_age;
+		}
+		else if($this->min_age) {
+			return "At least " . $this->min_age;
+		}
+		else if($this->max_age) {
+			return "Up to " . $this->max_age;
+		}
+
+		return "No age restriction";
+
+	}
+
+	public function getCompletedPercentage() {
+
+		$test_count = $this->test_count;
+
+		$tests = $this->getTests();
+		$completed_tests = array_filter($tests, function($test) {
+			return $test->status == Test::STATUS_COMPLETED;
+		});
+		$completed_test_count = count($completed_tests);
+
+		return floor(($completed_test_count / $test_count) * 100);
+
+	}
+
+	public function getTemplate() {
+		return Template::get($this->template_id);
+	}
+
+}
+
+?>

+ 20 - 0
engine/project_location.php

@@ -0,0 +1,20 @@
+<?php
+
+class ProjectLocation extends Model {
+
+	protected static $table = "project_location";
+	protected static $id_field = ["project_id", "location_id"];
+	protected static $fillable_fields = ["project_id", "location_id"];
+
+	// Object methods
+	public function getProject() {
+		return Project::get($this->project_id);
+	}
+
+	public function getLocation() {
+		return Location::get($this->location_id);
+	}
+
+}
+
+?>

+ 30 - 0
engine/session.php

@@ -0,0 +1,30 @@
+<?php
+
+class Session extends Model {
+
+	protected static $table = "session";
+	protected static $id_field = "id";
+	protected static $fillable_fields = ["id", "data", "dts_last_access"];
+
+	public static function start($name="", $timeout=3600) {
+
+		$handler = new SiteSessionHandler();
+		session_set_save_handler($handler, true);
+
+		session_set_cookie_params($timeout, "/", "");
+
+		// Set session name if passed
+		if(!empty($name)) session_name($name);
+
+		session_start();
+	}
+
+	public static function extend($timeout) {
+		$id = session_id();
+		$name = session_name();
+		setcookie($name, $id, time()+$timeout, "/", "");
+	}
+
+}
+
+?>

+ 49 - 0
engine/site_session_handler.php

@@ -0,0 +1,49 @@
+<?php
+
+class SiteSessionHandler implements SessionHandlerInterface {
+
+	public function open($path, $name) {
+		return true;
+	}
+
+	public function read($id) {
+		$session = Session::get($id);
+		return $session ? $session->data : "";
+	}
+
+	public function write($id, $data) {
+
+		$session = Session::get($id);
+		if(!$session) {
+			$session = new Session;
+		}
+
+		$session->id = $id;
+		$session->data = $data;
+		$session->dts_last_access = date('Y-m-d H:i:s');
+		return $session->commit();
+	}
+
+	public function close() {
+		return true;
+	}
+
+	public function destroy($id) {
+
+		$session = Session::get($id);
+		if($session) $session->delete();
+		return true;
+	}
+
+	public function gc($lifetime) {
+		$threshold = time() - $lifetime;
+		$date_time = date("Y-m-d H:i:s", $threshold);
+
+		$sql = "DELETE FROM `session` WHERE `dts_last_access` < '$date_time'";
+		$result = db::query($sql);
+		return $result;
+	}
+
+}
+
+?>

+ 99 - 0
engine/template.php

@@ -0,0 +1,99 @@
+<?php
+
+class Template extends Model {
+
+	protected static $table = "template";
+	protected static $id_field = "id";
+	protected static $fillable_fields = ["customer_id", "name", "json"];
+
+	protected static $field_map = [
+	];
+
+	// Object methods
+	public function getCustomer() {
+		return Customer::get($this->customer_id);
+	}
+
+	public function renderBeforeTestForm() {
+
+		$json = json_decode($this->json);
+		$fields = $json->beforeTest;
+
+		?>
+		<form method="post" enctype="multipart/form-data">
+
+			<div class="alert alert-info">
+				<i class="fal fa-fw fa-info-circle"></i>
+				Answer as clearly and accurately as you can otherwise you may be contacted after the test for clarification and/or verification purposes.
+			</div>
+
+			<?php
+			foreach($fields as $field) {
+				Form::renderField($field);
+			}
+			?>
+
+			<div class="bg-light text-center p-3 mb-3" style="position: sticky; top: 0px;">
+
+				<button class="btn btn-block btn-success" type="submit" name="submit" value="<?=$_SESSION["csrf_token"]?>">Start Test</button>
+				<small data-test-no-internet-text class="form-text text-success">
+					Tap this button just before you enter the venue and wait for the form to submit.
+				</small>
+
+			</div>
+		</form>
+		<?php
+	}
+
+	public function renderDuringTestForm() {
+
+		$json = json_decode($this->json);
+		$fields = $json->duringTest;
+
+		?>
+		<form method="post" id="test-form">
+
+			<input type="hidden" name="duration" id="duration" value="" required />
+
+			<div class="bg-light text-center p-3 mb-3" style="position: sticky; top: 104px; z-index: 1000;">
+
+				<div class="" id="test-stop-button-container">
+					<button class="btn btn-block btn-danger" type="button" id="test-stop-button">Stop Test</button>
+					<small data-test-no-internet-text class="form-text text-danger">
+						Tap this button when you are outside of the venue.
+					</small>
+				</div>
+
+				<div class="d-none" id="test-submit-button-container">
+					<input type="hidden" name="submit" value="<?=htmlspecialchars($_SESSION["csrf_token"])?>" />
+					<button class="btn btn-block btn-primary" type="submit" id="test-submit-button">Submit Test Results</button>
+					<small class="form-text text-muted d-none" id="test-no-internet-text">
+						<span class="text-danger">No Internet Connectivity</span><br />
+						Please check your Internet connectivity and try again.
+					</small>
+					<small id="test-submit-status">
+
+					</small>
+				</div>
+
+			</div>
+
+			<div class="alert alert-info">
+				<i class="fal fa-fw fa-info-circle"></i>
+				Answer as clearly and accurately as you can otherwise you may be contacted after the test for clarification and/or verification purposes.
+			</div>
+
+			<?php
+			foreach($fields as $field) {
+				Form::renderField($field);
+			}
+			?>
+		</form>
+		<?php
+	}
+
+
+
+}
+
+?>

+ 121 - 0
engine/test.php

@@ -0,0 +1,121 @@
+<?php
+
+class Test extends Model {
+
+	protected static $table = "test";
+	protected static $id_field = "id";
+	protected static $fillable_fields = ["project_id", "location_id", "tester_id", "status", "test_fee", "test_time", "shop_left", "shop_right", "attire", "challenge_stage", "challenge_description", "challenger_name", "challenger_description", "challenger_gender", "challenger_eye_contact", "additional_notes", "dts_start", "dts_end", "verifier_id", "verifier_notes", "pass", "dts_created", "dts_assigned", "dts_verified"];
+
+	protected static $field_map = [
+	];
+
+	// Constants
+
+	const STATUS_CANCELLED = 0;
+	const STATUS_UNASSIGNED = 1; // Location needs a tester
+	const STATUS_ASSIGNED = 2; // Tester assigned
+	const STATUS_CONFIRMED = 3; // Tester has said they can do it
+	const STATUS_STARTED = 4;
+	const STATUS_PENDING_VERIFICATION = 8;
+	const STATUS_COMPLETED = 16;
+
+	const STATUSES = [
+		0 => "Cancelled",
+		1 => "Unassigned",
+		2 => "Assigned",
+		3 => "Confirmed",
+		4 => "Started",
+		8 => "Pending Verification",
+		16 => "Completed",
+	];
+
+	const TEST_TIME_ANYTIME = 1;
+	const TEST_TIME_DAY = 2;
+	const TEST_TIME_NIGHT = 3;
+
+	// Object methods
+	public function getStatusText() {
+		return Test::STATUSES[$this->status];
+	}
+
+	public function getStatusClass() {
+		switch($this->status) {
+			case Test::STATUS_CANCELLED:
+				return "secondary";
+			case Test::STATUS_UNASSIGNED:
+				return "danger";
+			case Test::STATUS_ASSIGNED:
+			case Test::STATUS_CONFIRMED:
+			case Test::STATUS_STARTED:
+				return "warning";
+			case Test::STATUS_PENDING_VERIFICATION:
+				return "primary";
+			case Test::STATUS_COMPLETED:
+				return "success";
+		}
+	}
+
+	public function getProject() {
+		return Project::get($this->project_id);
+	}
+
+	public function getLocation() {
+		return Location::get($this->location_id);
+	}
+
+	public function getTester() {
+		return User::get($this->tester_id);
+	}
+
+	public function getVerifier() {
+		return User::get($this->verifier_id);
+	}
+
+	public function getValues() {
+		return TestValue::query(["test_id" => $this->id]);
+	}
+
+	public function getDirectory() {
+		$directory = ROOT_DIR . "/files/tests/" . $this->id;
+		if(!file_exists($directory)) mkdir($directory, 0777, true);
+		return $directory;
+	}
+
+	public function getDuration() {
+		if(is_null($this->dts_end)) return false;
+		$seconds = Util::getDurationFromDTS($this->dts_start, $this->dts_end);
+		return $seconds;
+	}
+
+	public function getDisplayDuration() {
+		$secs = $this->getDuration();
+		$mins = floor($secs / 60);
+		$secs = $secs % 60;
+
+		return "$mins min. $secs sec.";
+	}
+
+	public function getPassClass() {
+		if(is_null($this->pass)) return "secondary";
+		return $this->pass ? "success" : "danger";
+	}
+
+	public function getPassText() {
+		if(is_null($this->pass)) return "Pending";
+		return $this->pass ? "Pass" : "Fail";
+	}
+
+	public function assignTester($tester) {
+		$this->tester_id = $tester->id;
+		$this->dts_assigned = Util::getDateTime();
+		$success = $this->commit();
+
+		// TODO: Notify tester
+
+		return $success;
+
+	}
+
+}
+
+?>

+ 16 - 0
engine/test_value.php

@@ -0,0 +1,16 @@
+<?php
+
+class TestValue extends Model {
+
+	protected static $table = "test_value";
+	protected static $id_field = ["test_id", "name"];
+	protected static $fillable_fields = ["test_id", "name", "value"];
+
+	protected static $field_map = [
+	];
+
+	// Object methods
+
+}
+
+?>

+ 167 - 0
engine/user.php

@@ -0,0 +1,167 @@
+<?php
+
+class User extends Model {
+
+	protected static $table = "user";
+	protected static $id_field = "id";
+	protected static $fillable_fields = ["email", "old_id", "password", "level", "score", "title", "first_name", "last_name", "gender", "date_of_birth", "phone", "bank_sort_code", "bank_account_number", "dts_registered", "dts_last_seen", "dts_verified", "verifier_id", "verifier_notes"];
+
+	protected static $field_map = [
+	];
+
+	// Constants
+
+	const TITLES = ["Miss", "Mr", "Ms", "Dr"];
+	const GENDERS = ["Female", "Male", "Unspecified"];
+
+	const LEVEL_BANNED = 0;
+	const LEVEL_REGISTERED = 1;
+	const LEVEL_UNVERIFIED = 2;
+	const LEVEL_DEACTIVATED = 4;
+	const LEVEL_TESTER = 8;
+	const LEVEL_VENUE = 16;
+	const LEVEL_CUSTOMER = 32;
+	const LEVEL_ADMIN = 64;
+	const LEVEL_SUPERADMIN = 128;
+
+	const LEVELS = [
+		0 => "Banned",
+		1 => "Registered",
+		2 => "Unverified",
+		4 => "Deactivated",
+		8 => "Tester",
+		16 => "Venue",
+		32 => "Customer",
+		64 => "Admin",
+		128 => "Super Admin",
+	];
+
+	// Object methods
+	public function canAdmin() {
+		return $this->level >= User::LEVEL_ADMIN;
+	}
+
+	public function getDirectory() {
+		$directory = ROOT_DIR . "/files/users/" . $this->id;
+		if(!file_exists($directory)) mkdir($directory, 0777, true);
+		return $directory;
+	}
+
+	public function getLevelText() {
+		return User::LEVELS[$this->level];
+	}
+
+	public function getGenderText() {
+
+		if($this->gender == "M") return "Male";
+		if($this->gender == "F") return "Female";
+
+		return "Unspecified";
+	}
+
+	public function getAge() {
+
+		if(is_null($this->date_of_birth)) return "N/A";
+
+		$now = new DateTime("now");
+		$dob = new DateTime($this->date_of_birth);
+		return $dob->diff($now)->y;
+	}
+
+	public function getDisplayName() {
+		$parts = array_filter([$this->title, $this->first_name, $this->last_name]);
+		return implode(" ", $parts);
+	}
+
+	public function hasPermission($object) {
+
+		if($this->level == User::LEVEL_SUPERADMIN) return true;
+		if($this->level == User::LEVEL_ADMIN) return true;
+
+		$customers = $this->getCustomers();
+		$customer_ids = array_column($customers, "id");
+
+		if(is_a($object, "Customer")) {
+			return in_array($object->id, $customer_ids);
+		}
+
+		if(is_a($object, "Location")) {
+			return in_array($object->customer_id, $customer_ids);
+		}
+
+		if(is_a($object, "Project")) {
+			return in_array($object->customer_id, $customer_ids);
+		}
+
+		if(is_a($object, "Template")) {
+			return in_array($object->customer_id, $customer_ids);
+		}
+
+		return false;
+	}
+
+	public function deleteIDFiles() {
+
+		$files = UserFile::query([
+			"user_id" => $this->id,
+			"type" => [UserFile::TYPE_ID, UserFile::TYPE_PHOTO]
+		]);
+
+		foreach($files as $file) {
+			$path = $this->getDirectory() . "/" . $file->id . ".jpg";
+			if(file_exists($path)) unlink($path);
+
+			$file->delete();
+		}
+
+		return true;
+	}
+
+	public function getAddresses() {
+
+		$addresses = UserAddress::query([
+			"user_id" => $this->id,
+		], [
+			"sort" => "name"
+		]);
+
+		return $addresses;
+	}
+
+	public function getCustomers() {
+
+		if($this->level >= User::LEVEL_ADMIN) {
+			return Customer::query([], ["sort" => "name"]);
+		}
+
+		if($this->level == User::LEVEL_CUSTOMER) {
+			$links = UserCustomer::query(["user_id" => $this->id]);
+			return Customer::query([
+				"id" => array_column($links, "customer_id")
+			], ["sort" => "name"]);
+		}
+
+		return [];
+	}
+
+	public function getPendingTests() {
+		return Test::query([
+			"tester_id" => $this->id,
+			"status" => Test::STATUS_ASSIGNED,
+		], [
+			"sort" => "id",
+		]);
+	}
+
+	public function getCompletedTests() {
+		return Test::query([
+			"tester_id" => $this->id,
+			"status" => Test::STATUS_COMPLETED,
+		], [
+			"sort" => "id",
+		]);
+	}
+
+}
+
+?>

+ 38 - 0
engine/user_address.php

@@ -0,0 +1,38 @@
+<?php
+
+class UserAddress extends Model {
+
+	protected static $table = "user_address";
+	protected static $id_field = "id";
+	protected static $fillable_fields = ["user_id", "name", "address_1", "address_2", "city", "county", "postal_code", "state", "country", "latitude", "longitude", "max_radius_miles"];
+
+	protected static $field_map = [
+	];
+
+	const RADIUSES = [
+		"0.25", "0.50", "1.00", "1.50", "2.00", "2.50", "3.00", "4.00", "5.00", "7.50", "10.00"
+	];
+
+	// Object methods
+	public function getUser() {
+		return User::get($this->user_id);
+	}
+
+	public function getDisplayAddress() {
+		$parts = [];
+		$fields = ["address_1", "address_2", "city", "county", "postal_code", "state", "country"];
+
+		foreach($fields as $field) {
+			$parts[] = $this->$field;
+		}
+
+		return implode(", ", array_filter($parts));
+	}
+
+	public function getGeolocation() {
+		return [$this->latitude, $this->longitude];
+	}
+
+}
+
+?>

+ 20 - 0
engine/user_customer.php

@@ -0,0 +1,20 @@
+<?php
+
+class UserCustomer extends Model {
+
+	protected static $table = "user_customer";
+	protected static $id_field = ["user_id", "customer_id"];
+	protected static $fillable_fields = ["user_id", "customer_id"];
+
+	// Object methods
+	public function getUser() {
+		return User::get($this->user_id);
+	}
+
+	public function getCustomer() {
+		return Customer::get($this->customer_id);
+	}
+
+}
+
+?>

+ 16 - 0
engine/user_file.php

@@ -0,0 +1,16 @@
+<?php
+
+class UserFile extends Model {
+
+	protected static $table = "user_file";
+	protected static $id_field = "id";
+	protected static $fillable_fields = ["user_id", "type", "dts_uploaded"];
+
+	const TYPE_ID = 1;
+	const TYPE_PHOTO = 2;
+
+	// Object methods
+
+}
+
+?>

+ 357 - 0
engine/util.php

@@ -0,0 +1,357 @@
+<?php
+class Util {
+
+	public static function getItemDirectory($folder, $id) {
+		$shard = str_pad($id % 1000, 3, "0", STR_PAD_LEFT);
+		return ROOT_DIR . "/files/" . $folder . "/" . $shard . "/" . $id;
+	}
+
+	public static function createItemDirectory($folder, $id) {
+
+		$directory = Util::getItemDirectory($folder, $id);
+
+		if(!file_exists($directory)) {
+			mkdir($directory, 0777, true);
+		}
+
+		return $directory;
+	}
+
+	public static function slug($string) {
+		$slug = strtolower($string);
+		$slug = preg_replace("/[^0-9a-z]/i", "-", $slug); // Replace anything not 0-9 a-z with dash
+		$slug = preg_replace("/\-+/", "-", $slug); // Replace consequential dashes with dash
+		$slug = trim($slug, "-");
+		return $slug;
+	}
+
+	public static function getDisplayFileSize($size) {
+		if($size < pow(2, 10)) return number_format($size) . " bytes";
+		if($size < pow(2, 20)) return number_format($size / pow(2, 10), 2) . " KB";
+		if($size < pow(2, 30)) return number_format($size / pow(2, 20), 2) . " MB";
+		if($size < pow(2, 40)) return number_format($size / pow(2, 30), 2) . " GB";
+		return number_format($size / pow(2, 40), 2) . " TB";
+	}
+
+	public static function timeDifference($unix_time, $options = []) {
+
+		$plain = $options["plain"] ?? false;
+
+		$now = time();
+		$difference = $now - $unix_time;
+
+		$tense = ($difference >= 0) ? "ago" : "to go";
+
+		$difference = abs($difference);
+
+		if($difference < 60) {
+			$value = $difference;
+			$class = "text-danger";
+			$unit = "second";
+		}
+		else if($difference < 3600) {
+			$value = floor($difference / 60);
+			$class = "text-danger";
+			$unit = "minute";
+		}
+		else if($difference < 86400) {
+			$value = floor($difference / 3600);
+			$class = "text-warning";
+			$unit = "hour";
+		}
+		else if($difference < 2592000) {
+			$value = floor($difference / 86400);
+			$class = "";
+			$unit = "day";
+		}
+		else if($difference < 31536000) {
+			$value = floor($difference / 2592000);
+			$class = "text-muted";
+			$unit = "month";
+		}
+		else {
+			$value = floor($difference / 31536000);
+			$class = "text-muted";
+			$unit = "year";
+		}
+
+		$text = "$value $unit" . ($value != 1 ? "s" : "") . " $tense";
+
+		if($plain) {
+			return "$text";
+		}
+		else {
+			return "<span class=\"$class\">$text</span>";
+		}
+
+	}
+
+	public static function getTimeZones() {
+
+		// Taken and modified from: https://stackoverflow.com/a/17355238
+
+		static $regions = [
+			DateTimeZone::AFRICA,
+			DateTimeZone::AMERICA,
+			DateTimeZone::ANTARCTICA,
+			DateTimeZone::ASIA,
+			DateTimeZone::ATLANTIC,
+			DateTimeZone::AUSTRALIA,
+			DateTimeZone::EUROPE,
+			DateTimeZone::INDIAN,
+			DateTimeZone::PACIFIC,
+		];
+
+		$identifiers = [];
+		foreach($regions as $region) {
+			$identifiers = array_merge($identifiers, DateTimeZone::listIdentifiers($region));
+		}
+
+		$time_zone_offsets = [];
+		foreach($identifiers as $identifier) {
+			$tz = new DateTimeZone($identifier);
+			$time_zone_offsets[] = (object) [
+				"identifier" => $identifier,
+				"offset" => $tz->getOffset(new DateTime),
+			];
+		}
+
+		uasort($time_zone_offsets, function($a, $b) {
+			if($a->offset > $b->offset) return 1;
+			else if($a->offset < $b->offset) return -1;
+			else return strcasecmp($a->identifier, $b->identifier);
+		});
+
+		$sr = [
+			"/" => ", ",
+			"St" => "St.",
+			"_" => " ",
+		];
+
+		$time_zone_list = [];
+		foreach($time_zone_offsets as $object) {
+
+			$identifier = $object->identifier;
+			$offset = $object->offset;
+
+			$display_identifier = str_replace(array_keys($sr), array_values($sr), $identifier);
+
+			$offset_prefix = $offset < 0 ? "-" : "+";
+			$offset_formatted = gmdate("H:i", abs($offset));
+
+			$pretty_offset = "UTC${offset_prefix}${offset_formatted}";
+
+			$time_zone_list[$identifier] = "${pretty_offset} - $display_identifier";
+		}
+
+		return $time_zone_list;
+	}
+
+	public static function getDate($time = false) {
+		if(!$time) $time = time();
+		return gmdate("Y-m-d", $time);
+	}
+
+	public static function getDateTime($time = false) {
+		if(!$time) $time = time();
+		return gmdate("Y-m-d H:i:s", $time);
+	}
+
+	public static function getDurationFromDTS($dts1, $dts2) {
+		$tz = date_default_timezone_get();
+		date_default_timezone_set("UTC");
+
+		$t1 = strtotime($dts1);
+		$t2 = strtotime($dts2);
+
+		date_default_timezone_set($tz);
+
+		return abs($t2 - $t1);
+	}
+
+	public static function getDisplayDateTime($time = false) {
+		if($time === false) $time = time();
+
+		$current_year = date("Y");
+		$year = date("Y", $time);
+
+		$format = ($year == $current_year) ? "M j, H:i" : "M j Y, H:i";
+
+		return date($format, $time);
+	}
+
+	public static function getDisplayDate($time = false) {
+		if($time === false) $time = time();
+
+		$current_year = date("Y");
+		$year = date("Y", $time);
+
+		$format = ($year == $current_year) ? "M j" : "M j Y";
+
+		return date($format, $time);
+	}
+
+	public static function sortObjectArray($array, $field, $compare_function = "") {
+
+		usort($array, function($a, $b) use ($compare_function, $field) {
+
+			switch($compare_function) {
+				case "":
+					if($a->$field == $b->$field) return 0;
+					return ($a->$field < $b->$field) ? -1 : 1;
+				case "strnatcasecmp":
+					return strnatcasecmp($a->$field, $b->$field);
+			}
+		});
+
+		return $array;
+	}
+
+	public static function arrayFlipByID($input = []) {
+		$output = [];
+
+		foreach($input as $object) {
+			$output[$object->getID()] = $object;
+		}
+
+		return $output;
+	}
+
+	public static function formatText($string, $options = []) {
+
+		$bb_code = $options["bb_code"] ?? true;
+		$emoticon = $options["emoticon"] ?? true;
+
+		$string = htmlspecialchars($string);
+		$string = nl2br($string);
+
+		/*
+		if($emoticon && $emoticonresult) {
+			db::data_seek($emoticonresult, 0);
+			while($myrow = db::fetch_array($emoticonresult)) {
+				$replacetext = $myrow["replacetext"];
+				$url = $myrow["url"];
+				$description = $myrow["description"];
+				$string = str_replace("$replacetext", "<img src=\"$dirPrefix$url\" alt=\"$description\" />", $string);
+			}
+		}
+		*/
+
+		if($emoticon) {
+			$string = Emoticon::apply($string);
+		}
+
+		if($bb_code) {
+			$string = Util::BBCode($string);
+		}
+
+		$pattern = "[0-9a-zA-Z\&\/\-\#\%\.\?\=\;\_\:\,\+\(\)\!]";
+
+		$string = preg_replace("/^http(s?):\/\/($pattern*)/", "<a href=\"http$1://$2\" target=\"_blank\">http$1://$2</a> ", $string); // Case for beginning
+		$string = preg_replace("/\shttp(s?):\/\/($pattern*)/", " <a href=\"http$1://$2\" target=\"_blank\">http$1://$2</a>", $string); // Case for middle
+		$string = preg_replace("/http(s?):\/\/($pattern*)$/", " <a href=\"http$1://$2\" target=\"_blank\">http$1://$2</a>", $string); // Case for end
+
+		return $string;
+	}
+
+	public static function BBCode($string) {
+
+		preg_match_all("/\[quote/i", $string, $matches);
+		$quote_begin_count = count($matches["0"]);
+
+		preg_match_all("/\[\/quote\]/i", $string, $matches);
+		$quote_end_count = count($matches["0"]);
+
+		$quotes = min($quote_begin_count, $quote_end_count);
+
+		$valid_quotes = ($quote_begin_count == $quote_end_count);
+
+		if(!$valid_quotes) {
+		}
+
+		$search = [
+			"/\[b\](.*?)\[\/b\]/is",
+			"/\[i\](.*?)\[\/i\]/is",
+			"/\[u\](.*?)\[\/u\]/is",
+			"/\[s\](.*?)\[\/s\]/is",
+			"/\[spoiler\](.*?)\[\/spoiler\]/is",
+			"/\[img\=(.*?)\]/is",
+			"/\[img\](.*?)\[\/img\]/is",
+			"/\[img width\=(.*?)\](.*?)\[\/img\]/is",
+			"/\[url\](.*?)\[\/url\]/is",
+			"/\[url\=(.*?)\](.*?)\[\/url\]/is",
+			"/\[color\=(.*?)\](.*?)\[\/color\]/is",
+			"/\[colour\=(.*?)\](.*?)\[\/colour\]/is",
+			"/\[size\=(.*?)\](.*?)\[\/size\]/is",
+			"/\[font\=(.*?)\](.*?)\[\/font\]/is",
+			"/\[center\](.*?)\[\/center\]<br \/>/is",
+			"/\[center\](.*?)\[\/center\]/is",
+			"/\[code\](.*?)\[\/code\]/is",
+			"/\[background\=(.*?)\](.*?)\[\/background\]/is",
+			"/\[youtube\][^\s]+v\=([A-Za-z0-9\-_]+)[^\s]*\[\/youtube\]/is", // YouTube URL
+			"/\[youtube\]([A-Za-z0-9\-_]+?)\[\/youtube\]/is", // YouTube ID
+			"/\[twitch\]([A-Za-z0-9\-_]+?)\[\/twitch\]/is", // Twitch ID
+			"/\[hrd?\]\<br \/\>/is",
+			"/\[nico\](.*?)\[\/nico\]/is",
+			"/\[leftfloat\](.*?)\[\/leftfloat\]/is",
+			"/\[rightfloat\](.*?)\[\/rightfloat\]/is",
+			"/\[leftfloat width\=(.*?)\](.*?)\[\/leftfloat\]/is",
+			"/\[clear\]/is",
+		];
+
+		$replace = [
+			'<strong>$1</strong>',
+			'<em>$1</em>',
+			'<u>$1</u>',
+			'<del>$1</del>',
+			'<span class="spoiler">$1</span>',
+			'<img class="img-fluid" src="$1" alt="$1" />',
+			'<img class="img-fluid" src="$1" alt="$1" />',
+			'<img class="img-fluid" width="$1" src="$2" alt="$2" />',
+			'<a href="$1" target="_blank">$1</a>',
+			'<a href="$1" target="_blank">$2</a>',
+			'<span style="color: $1;">$2</span>',
+			'<span style="color: $1;">$2</span>',
+			'<span style="font-size: $1'.'px;">$2</span>',
+			'<span style="font-family: $1;">$2</span>',
+			'<div class="text-center">$1</div>',
+			'<div class="text-center">$1</div>',
+			'<div class="code">$1</div>',
+			'<span style="background: $1;">$2</span>',
+			'<iframe width="448" height="280" src="https://www.youtube.com/embed/$1"></iframe>',
+			'<iframe width="448" height="280" src="https://www.youtube.com/embed/$1"></iframe>',
+			'<object type="application/x-shockwave-flash" height="378" width="620" id="live_embed_player_flash" data="https://www.twitch.tv/widgets/live_embed_player.swf?channel=$1" bgcolor="#000000">
+<param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="movie" value="http://www.twitch.tv/widgets/live_embed_player.swf" /><param name="flashvars" value="hostname=www.twitch.tv&channel=$1&auto_play=false&start_volume=25" /></object>',
+			'<hr />',
+			'<script type="text/javascript" src="https://ext.nicovideo.jp/thumb_watch/$1"></script>',
+			'<div class="float-left">$1</div>',
+			'<div class="float-right">$1</div>',
+			'<div class="float-left" style="width: $1%;">$2</div>',
+			'<div class="float-none"></div>',
+		];
+
+		$string = preg_replace($search, $replace, $string);
+
+		if($valid_quotes) {
+			$search = [
+				"/\[quote\]/is",
+				"/\[quote\=(.*?)\]([^\]])/is",
+				"/\[quote\=(.*?)\]/is",
+				"/\[\/quote\]<br \/>/is",
+				"/\[\/quote\]/is",
+			];
+
+			$replace = [
+				'<div class="card quote mb-3"><div class="card-header">Quote</div><div class="card-body">',
+				'<div class="card quote mb-3"><div class="card-header">Quote: $1</div><div class="card-body">$2',
+				'<div class="card quote mb-3"><div class="card-header">Quote: $1</div><div class="card-body">',
+				'</div></div>',
+				'</div></div>',
+			];
+
+			$string = preg_replace($search, $replace, $string, $quotes);
+		}
+
+		return $string;
+	}
+}

+ 23 - 0
engine/view.php

@@ -0,0 +1,23 @@
+<?php
+
+class View {
+
+	protected static $included = [];
+
+	public static function include($view, $params = []) {
+		$view_path = ROOT_DIR . "/views/" . $view . ".php";
+		if(file_exists($view_path)) {
+			self::$included[] = $view;
+			extract($params);
+			require $view_path;
+		}
+		else {
+			throw new Exception("View \"$view\" not found");
+		}
+	}
+
+	public static function includeOnce($view, $params = []) {
+		if(in_array($view, self::$included)) return;
+		self::include($view, $params);
+	}
+}

+ 61 - 0
initialise.php

@@ -0,0 +1,61 @@
+<?php
+
+// Runtime checks
+if (phpversion() < "7") die("Project requires PHP 7.0 or above");
+//if (!extension_loaded("imagick")) die("Project requires the Imagick PHP extension");
+if (!extension_loaded("mysqli")) die("Project requires the MySQLi PHP extension");
+if (!extension_loaded("curl")) die("Project requires the PHP cURL extension");
+if (!extension_loaded("json")) die("Project requires the json PHP extension");
+if (!extension_loaded("mbstring")) die("Project requires the mbstring PHP extension");
+
+function get_class_file_name($class_name) {
+	$file_name = preg_replace("/([a-z])([A-Z])/", "$1_$2", $class_name);
+	$file_name = preg_replace("/([A-Z])([A-Z][a-z])/", "$1_$2", $file_name);
+
+	$file_name = strtolower($file_name);
+	return $file_name;
+}
+
+spl_autoload_register(function ($class_name) {
+	$path = __DIR__ . "/engine/" . get_class_file_name($class_name) . ".php";
+	if(file_exists($path)) {
+		require $path;
+	}
+});
+
+chdir(__DIR__);
+
+require "config.php";
+require "vendor/autoload.php";
+
+DB::connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
+
+Core::addBreadcrumb("/", "Home");
+
+// Start session
+Session::start(SESSION_NAME);
+
+if(!isset($_SESSION["csrf_token"])) {
+	$_SESSION["csrf_token"] = bin2hex(random_bytes(16));
+}
+
+// Load the user if a session has a userid
+if(!empty($_SESSION["user_id"])) {
+	Core::$user = User::get($_SESSION["user_id"]);
+	Core::$admin = Core::$user->canAdmin();
+
+	Core::$user->dts_last_seen = gmdate("Y-m-d H:i:s");
+	Core::$user->commit();
+}
+
+// Extend session cookie if it exists
+if(!empty($_COOKIE[SESSION_NAME])) {
+	Session::extend(time() + 14 * 86400);
+}
+
+Core::addScript("public/js/jquery-3.3.1.min.js");
+Core::addScript("public/js/popper.min.js");
+Core::addScript("public/js/bootstrap.min.js");
+Core::addScript("public/js/app.js");
+
+?>

+ 97 - 0
json/default_template.json

@@ -0,0 +1,97 @@
+{
+	"beforeTest": [
+		{
+			"type": "header",
+			"content": "Before the Test"
+		},
+		{
+			"type": "text",
+			"name": "shop_left",
+			"label": "Shop Name (Left)",
+			"maxLength": 50,
+			"required": true
+		},
+		{
+			"type": "text",
+			"name": "shop_right",
+			"label": "Shop Name (Right)",
+			"maxLength": 50,
+			"required": true
+		},
+		{
+			"type": "text",
+			"name": "attire",
+			"label": "Attire",
+			"maxLength": 100,
+			"required": true
+		},
+		{
+			"type": "file",
+			"label": "Selfie",
+			"name": "selfie",
+			"required": true
+		}
+	],
+	"duringTest": [
+		{
+			"type": "header",
+			"content": "Challenge"
+		},
+		{
+			"type": "dropdown",
+			"name": "challenge_stage",
+			"label": "Stage",
+			"values": ["", 1, 2, 3, 4, 5],
+			"displayStrings": ["Select stage", "Challenge on entry", "Challenge during browsing", "Challenge during play", "Challenge on exit", "No challenge"],
+			"required": true
+		},
+		{
+			"type": "textarea",
+			"name": "challenge_description",
+			"label": "Description",
+			"maxLength": 200
+		},
+
+		{
+			"type": "header",
+			"content": "Challenger (if challenged)"
+		},
+		{
+			"type": "text",
+			"name": "challenger_name",
+			"label": "Name",
+			"maxLength": 50
+		},
+		{
+			"type": "textarea",
+			"name": "challenger_description",
+			"label": "Description",
+			"maxLength": 200
+		},
+		{
+			"type": "dropdown",
+			"name": "challenger_gender",
+			"label": "Gender",
+			"values": ["", "M", "F"],
+			"displayStrings": ["No challenge/Don't know", "M", "F"]
+		},
+		{
+			"type": "dropdown",
+			"name": "challenger_eye_contact",
+			"label": "Eye Contact",
+			"values": ["", "0", "1"],
+			"displayStrings": ["No challenge/Don't know", "No", "Yes"]
+		},
+
+		{
+			"type": "header",
+			"content": "Additional Notes"
+		},
+		{
+			"type": "textarea",
+			"name": "additional_notes",
+			"label": "Additional Notes",
+			"maxLength": 200
+		}
+	]
+}

+ 24 - 0
package.json

@@ -0,0 +1,24 @@
+{
+  "name": "check-policy.co.uk",
+  "version": "1.0.0",
+  "description": "Check Policy system.",
+  "main": "Gulpfile.js",
+  "scripts": {
+    "test": "echo \"Error: no test specified\" && exit 1"
+  },
+  "author": "Alan Lam",
+  "license": "ISC",
+  "dependencies": {
+    "bootstrap": "^4.0.0",
+    "holderjs": "^2.9.4",
+    "jquery": "^3.3.1",
+    "popper.js": "^1.12.9"
+  },
+  "devDependencies": {
+    "gulp": "^3.9.1",
+    "gulp-autoprefixer": "^4.0.0",
+    "gulp-clean-css": "^3.4.0",
+    "gulp-rename": "^1.2.2",
+    "gulp-sass": "^3.1.0"
+  }
+}

BIN
psd/marker.psd


BIN
psd/required.psd


+ 6 - 0
public/.htaccess

@@ -0,0 +1,6 @@
+Options -Indexes -MultiViews
+
+RewriteEngine on
+RewriteCond %{REQUEST_FILENAME} !-f 
+RewriteCond %{REQUEST_FILENAME} !-d 
+RewriteRule ^(.*)$ index.php?path=$1&%{QUERY_STRING} [B]

ファイルの差分が大きいため隠しています
+ 5 - 0
public/css/bootstrap.min.css


BIN
public/img/bg_required.png


BIN
public/img/blank.png


BIN
public/img/blank_carousel.png


BIN
public/img/gaming_machine.jpg


BIN
public/img/icon.png


BIN
public/img/join_us.jpg


BIN
public/img/logo.png


BIN
public/img/markers/building-blue.png


BIN
public/img/markers/building-green.png


BIN
public/img/markers/building-grey.png


BIN
public/img/markers/building-orange.png


BIN
public/img/markers/building-pink.png


BIN
public/img/markers/building-red.png


BIN
public/img/markers/user-green.png


BIN
public/img/markers/user-grey.png


BIN
public/img/markers/user-orange.png


BIN
public/img/markers/user-red.png


BIN
public/img/services_age_related.png


この差分においてかなりの量のファイルが変更されているため、一部のファイルを表示していません