Browse Source

Merge branch 'develop'

Alan Lam 7 years ago
parent
commit
410cd84116
87 changed files with 4238 additions and 1902 deletions
  1. 1 0
      .gitignore
  2. 12 16
      Gulpfile.js
  3. 12 6
      composer.json
  4. 3 2
      controllers/account.php
  5. 3 1
      controllers/customer_ajax.php
  6. 47 41
      controllers/location_edit.php
  7. 1 23
      controllers/location_view.php
  8. 2 1
      controllers/practice.php
  9. 24 7
      controllers/project_export.php
  10. 12 83
      controllers/project_invoice.php
  11. 27 9
      controllers/projects.php
  12. 11 5
      controllers/test.php
  13. 16 4
      controllers/test_file.php
  14. 1 4
      controllers/test_invoice.php
  15. 16 0
      controllers/test_results_customer_list.php
  16. 26 0
      controllers/test_results_project_list.php
  17. 53 0
      controllers/test_results_test_list.php
  18. 1 1
      engine/account_icon.php
  19. 17 7
      engine/chart.php
  20. 6 3
      engine/constraint.php
  21. 23 4
      engine/core.php
  22. 50 3
      engine/customer.php
  23. 122 42
      engine/db.php
  24. 57 12
      engine/email.php
  25. 4 2
      engine/email_builder.php
  26. 43 12
      engine/form.php
  27. 1 1
      engine/form_exception.php
  28. 6 1
      engine/geolocation.php
  29. 0 2
      engine/geolocation_bounds.php
  30. 1 3
      engine/html.php
  31. 47 36
      engine/http.php
  32. 8 9
      engine/image.php
  33. 62 0
      engine/invoice.php
  34. 74 0
      engine/invoice_line_item.php
  35. 0 2
      engine/json.php
  36. 135 5
      engine/location.php
  37. 16 4
      engine/location_file.php
  38. 42 0
      engine/location_update_log_entry.php
  39. 7 0
      engine/location_venue_type.php
  40. 133 30
      engine/model.php
  41. 22 6
      engine/practice_test.php
  42. 376 34
      engine/project.php
  43. 18 4
      engine/project_location.php
  44. 18 5
      engine/session.php
  45. 22 3
      engine/site_session_handler.php
  46. 100 22
      engine/template.php
  47. 274 40
      engine/test.php
  48. 5 1
      engine/test_pdf.php
  49. 0 7
      engine/test_value.php
  50. 160 28
      engine/user.php
  51. 33 8
      engine/user_address.php
  52. 18 4
      engine/user_customer.php
  53. 9 4
      engine/user_file.php
  54. 123 161
      engine/util.php
  55. 13 1
      engine/venue_type.php
  56. 14 3
      engine/view.php
  57. 73 0
      export_processing/project_quickbooks_customer_csv.php
  58. 60 0
      export_processing/project_quickbooks_tester_csv.php
  59. BIN
      locales/en_GB/LC_MESSAGES/en_GB.mo
  60. 290 295
      locales/en_GB/LC_MESSAGES/en_GB.po
  61. BIN
      locales/es_ES/LC_MESSAGES/es_ES.mo
  62. 246 270
      locales/es_ES/LC_MESSAGES/es_ES.po
  63. BIN
      locales/nl_NL/LC_MESSAGES/nl_NL.mo
  64. 218 251
      locales/nl_NL/LC_MESSAGES/nl_NL.po
  65. 365 201
      package-lock.json
  66. 14 8
      package.json
  67. 3 3
      public/css/bootstrap.min.css
  68. 4 7
      public/js/Chart.bundle.min.js
  69. 1 1
      public/js/all.min.js
  70. 10 0
      public/js/app-projects.js
  71. 2 2
      public/js/bootstrap.min.js
  72. 0 0
      public/js/bootstrap.min.js.map
  73. 1 1
      public/js/popper.min.js
  74. 0 0
      public/js/popper.min.js.map
  75. 8 2
      routes.php
  76. 12 1
      views/customer_select.php
  77. 16 92
      views/location.php
  78. 57 48
      views/location_form.php
  79. 57 0
      views/location_log_tab.php
  80. 38 0
      views/location_photos_tab.php
  81. 162 0
      views/location_tests_tab.php
  82. 27 3
      views/projects.php
  83. 35 0
      views/test_results_customer_list.php
  84. 60 0
      views/test_results_project_list.php
  85. 142 0
      views/test_results_test_list.php
  86. 8 3
      views/test_verify_form.php
  87. 2 2
      views/user_edit_form.php

+ 1 - 0
.gitignore

@@ -12,3 +12,4 @@ tasks/data/
 backups/
 backups/
 files/countries.json
 files/countries.json
 scrap/
 scrap/
+tmp/

+ 12 - 16
Gulpfile.js

@@ -1,29 +1,25 @@
-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");
+let gulp = require("gulp");
+let sass = require("gulp-sass");
+let autoprefixer = require("gulp-autoprefixer");
+let cleancss = require("gulp-clean-css");
+let rename = require("gulp-rename");
 
 
-var input = "scss/*.scss";
-var output = "public/css";
+let input = "scss/*.scss";
+let output = "public/css";
 
 
-var sassOptions = {
+let sassOptions = {
 	"errLogToConsole": true,
 	"errLogToConsole": true,
 	"outputStyle": "expanded"
 	"outputStyle": "expanded"
 };
 };
 
 
-var autoprefixerOptions = {
-	"browsers": ["last 2 versions", "ie >= 9", "and_chr >= 2.3"]
-};
-
-var vendorCssFiles = [
+let vendorCssFiles = [
 	"./node_modules/datatables.net-bs4/css/dataTables.bootstrap4.min.css",
 	"./node_modules/datatables.net-bs4/css/dataTables.bootstrap4.min.css",
 	"./node_modules/datatables.net-buttons-bs4/css/buttons.bootstrap4.min.css",
 	"./node_modules/datatables.net-buttons-bs4/css/buttons.bootstrap4.min.css",
 	"./node_modules/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css",
 	"./node_modules/datatables.net-responsive-bs4/css/responsive.bootstrap4.min.css",
 	"./node_modules/daterangepicker/daterangepicker.css",
 	"./node_modules/daterangepicker/daterangepicker.css",
 ];
 ];
 
 
-var jsFiles = [
+let jsFiles = [
 	"./node_modules/jquery/dist/jquery.min.*",
 	"./node_modules/jquery/dist/jquery.min.*",
 	"./node_modules/bootstrap/dist/js/bootstrap.min.*",
 	"./node_modules/bootstrap/dist/js/bootstrap.min.*",
 	"./node_modules/popper.js/dist/umd/popper.min.*",
 	"./node_modules/popper.js/dist/umd/popper.min.*",
@@ -57,7 +53,7 @@ gulp.task("sass", function() {
 	return gulp
 	return gulp
 		.src(input)
 		.src(input)
 		.pipe(sass(sassOptions).on("error", sass.logError))
 		.pipe(sass(sassOptions).on("error", sass.logError))
-		.pipe(autoprefixer(autoprefixerOptions))
+		.pipe(autoprefixer())
 		.pipe(cleancss())
 		.pipe(cleancss())
 		.pipe(rename({
 		.pipe(rename({
 			"suffix": ".min"
 			"suffix": ".min"
@@ -81,4 +77,4 @@ gulp.task("watch", function() {
 });
 });
 
 
 
 
-gulp.task("default", gulp.series("sass", "copy-vendor-css", "copy-js", "watch"));
+gulp.task("default", gulp.series("sass", "copy-vendor-css", "copy-js", "watch"));

+ 12 - 6
composer.json

@@ -1,8 +1,14 @@
 {
 {
-    "require": {
-        "phpmailer/phpmailer": "^6.0",
-		"phpoffice/phppresentation": "dev-master",
-        "mpdf/mpdf": "^7.1",
-        "gettext/gettext": "^4.6"
-    }
+  "require": {
+    "phpmailer/phpmailer": "^6.0",
+    "phpoffice/phppresentation": "dev-master",
+    "mpdf/mpdf": "^7.1",
+    "gettext/gettext": "^4.6",
+    "ext-mysqli": "*",
+    "ext-json": "*",
+    "ext-curl": "*",
+    "ext-gd": "*",
+    "ext-exif": "*",
+    "ext-mbstring": "*"
+  }
 }
 }

+ 3 - 2
controllers/account.php

@@ -25,7 +25,6 @@ if($user->level >= User::LEVEL_ADMIN) {
 	$tests_pending_verification = count($tests);
 	$tests_pending_verification = count($tests);
 
 
 	$icons[] = new AccountIcon(__("Projects"), "/account/projects", "list");
 	$icons[] = new AccountIcon(__("Projects"), "/account/projects", "list");
-	$icons[] = new AccountIcon(__("Locations"), "/account/locations", "map-marker");
 	$icons[] = new AccountIcon(__("Templates"), "/account/templates", "file-alt");
 	$icons[] = new AccountIcon(__("Templates"), "/account/templates", "file-alt");
 	$icons[] = new AccountIcon(__("Venue Types"), "/account/venue-types", "list-alt");
 	$icons[] = new AccountIcon(__("Venue Types"), "/account/venue-types", "list-alt");
 
 
@@ -39,7 +38,9 @@ if($user->level >= User::LEVEL_ADMIN) {
 }
 }
 
 
 if($user->level >= User::LEVEL_CUSTOMER) {
 if($user->level >= User::LEVEL_CUSTOMER) {
+	$icons[] = new AccountIcon(__("Locations"), "/account/locations", "map-marker");
 	$icons[] = new AccountIcon(__("Reports"), "/account/reports", "chart-pie");
 	$icons[] = new AccountIcon(__("Reports"), "/account/reports", "chart-pie");
+	$icons[] = new AccountIcon(__("Test Results"), "/account/test-results", "clipboard-list-check");
 }
 }
 
 
 if($user->isTester() || $user->isAdmin()) {
 if($user->isTester() || $user->isAdmin()) {
@@ -104,4 +105,4 @@ View::includeOnce("header", compact("page_title"));
 View::include("account", compact("icons", "actions", "to_do", "referrals"));
 View::include("account", compact("icons", "actions", "to_do", "referrals"));
 View::includeOnce("footer");
 View::includeOnce("footer");
 
 
-?>
+?>

+ 3 - 1
controllers/customer_ajax.php

@@ -5,6 +5,8 @@ JSON::header();
 $customer = Customer::get($id);
 $customer = Customer::get($id);
 if(!$customer) JSON::fail("Customer not found.");
 if(!$customer) JSON::fail("Customer not found.");
 
 
+if(!Core::$user->hasPermission($customer)) throw new Exception(__("No permission."));
+
 switch($action) {
 switch($action) {
 	case "get-locations":
 	case "get-locations":
 
 
@@ -43,4 +45,4 @@ switch($action) {
 		]);
 		]);
 
 
 		break;
 		break;
-}
+}

+ 47 - 41
controllers/location_edit.php

@@ -6,6 +6,8 @@ $location = Location::get($id);
 if(!$location) throw new Exception("Location not found.");
 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.");
 if(!Core::$user->hasPermission($location)) throw new Exception("You do not have have permission to access this page.");
 
 
+$original_data = $location->getModelData();
+
 $customer = $location->getCustomer();
 $customer = $location->getCustomer();
 
 
 $submit = http::value("submit");
 $submit = http::value("submit");
@@ -39,7 +41,7 @@ if($submit) {
 		$location->area_manager = http::value("area_manager", "trim");
 		$location->area_manager = http::value("area_manager", "trim");
 		$location->area_manager_email = http::value("area_manager_email", "email");
 		$location->area_manager_email = http::value("area_manager_email", "email");
 
 
-		$location->closed = http::value("closed", "int");
+		$location->closed = http::value("closed", "int") ? 1 : 0;
 
 
 		if(empty($location->name)) $form_exception->addError("Name is required.");
 		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->address_1)) $form_exception->addError("Location line 1 is required.");
@@ -51,56 +53,62 @@ if($submit) {
 		else if(empty($location->longitude)) $form_exception->addError("Map location is required.");
 		else if(empty($location->longitude)) $form_exception->addError("Map location is required.");
 
 
 		// Photo
 		// Photo
-		$photo = (object) $_FILES["photo"];
-		if($photo->error != UPLOAD_ERR_NO_FILE) {
-			try {
-				if($photo->error != UPLOAD_ERR_OK) throw new Exception(HTTP::getUploadErrorString($photo->error));
-				if(!Image::isJPEG($photo->tmp_name)) throw new Exception("Photo is not a JPEG image.");
-
-				// Photo OK
-				$file = new LocationFile;
-				$file->location_id = $id;
-				$file->type = LocationFile::TYPE_PHOTO;
-				$file->dts_uploaded = Util::getDateTime();
-				$file->commit();
-
-				$id = $file->id;
 
 
-				$directory = $location->getDirectory();
-				$file_path = $directory . "/$id.jpg";
-
-				$output_image = Image::normalise($photo->tmp_name);
-				$success = imagejpeg($output_image, $file_path);
-				imagedestroy($output_image);
-				if(!$success) throw new Exception("Failed to save photo.");
-			}
-			catch(Exception $e) {
-				$form_exception->addError($e->getMessage());
+		if(Core::$user->isAdmin()) {
+			$photo = (object) $_FILES["photo"];
+			if($photo->error != UPLOAD_ERR_NO_FILE) {
+				try {
+					if($photo->error != UPLOAD_ERR_OK) throw new Exception(HTTP::getUploadErrorString($photo->error));
+					if(!Image::isJPEG($photo->tmp_name)) throw new Exception("Photo is not a JPEG image.");
+
+					// Photo OK
+					$file = new LocationFile;
+					$file->location_id = $id;
+					$file->type = LocationFile::TYPE_PHOTO;
+					$file->dts_uploaded = Util::getDateTime();
+					$file->commit();
+
+					$id = $file->id;
+
+					$directory = $location->getDirectory();
+					$file_path = $directory . "/$id.jpg";
+
+					$output_image = Image::normalise($photo->tmp_name);
+					$success = imagejpeg($output_image, $file_path);
+					imagedestroy($output_image);
+					if(!$success) throw new Exception("Failed to save photo.");
+				}
+				catch(Exception $e) {
+					$form_exception->addError($e->getMessage());
+				}
 			}
 			}
-		}
 
 
-		// Delete Photos
-		$delete_file_ids = http::value("delete_file_ids", "int");
-		$files = LocationFile::query([
-			"id" => $delete_file_ids,
-			"location_id" => $id,
-		]);
-		if($files) {
-			$directory = $location->getDirectory();
-			foreach($files as $file) {
-				$pattern = $directory . "/$file->id.*";
-				foreach(glob($pattern) as $path) {
-					unlink($path);
+			// Delete Photos
+			$delete_file_ids = http::value("delete_file_ids", "int");
+			$files = LocationFile::query([
+				"id" => $delete_file_ids,
+				"location_id" => $id,
+			]);
+			if($files) {
+				$directory = $location->getDirectory();
+				foreach($files as $file) {
+					$pattern = $directory . "/$file->id.*";
+					foreach(glob($pattern) as $path) {
+						unlink($path);
+					}
+					$file->delete();
 				}
 				}
-				$file->delete();
 			}
 			}
 		}
 		}
 
 
+		$modified_fields = $location->getModifiedFields();
 
 
 		if($form_exception->hasErrors()) throw $form_exception;
 		if($form_exception->hasErrors()) throw $form_exception;
 		$success = $location->commit();
 		$success = $location->commit();
 		if(!$success) throw new Exception("Failed to edit location at this time. Please try again later.");
 		if(!$success) throw new Exception("Failed to edit location at this time. Please try again later.");
 
 
+		$location->logUpdate($original_data, $modified_fields);
+
 		// Venue types
 		// Venue types
 		$venue_type_ids = http::value("venue_type_ids", "int");
 		$venue_type_ids = http::value("venue_type_ids", "int");
 		$venue_types = VenueType::query(["id" => $venue_type_ids]);
 		$venue_types = VenueType::query(["id" => $venue_type_ids]);
@@ -132,5 +140,3 @@ Core::addBreadcrumb("/account/locations/$id/edit", $page_title);
 View::includeOnce("header", compact("page_title"));
 View::includeOnce("header", compact("page_title"));
 View::include("location_form", compact("location", "photos"));
 View::include("location_form", compact("location", "photos"));
 View::includeOnce("footer");
 View::includeOnce("footer");
-
-?>

+ 1 - 23
controllers/location_view.php

@@ -13,28 +13,6 @@ Core::addBreadcrumb("/account/locations", "Locations");
 Core::addBreadcrumb("/account/locations?customer_id=$customer->id", "$customer->name Locations");
 Core::addBreadcrumb("/account/locations?customer_id=$customer->id", "$customer->name Locations");
 Core::addBreadcrumb("/account/locations/$location->id", $page_title);
 Core::addBreadcrumb("/account/locations/$location->id", $page_title);
 
 
-$status_constraint = new Constraint("BETWEEN");
-
-if(Core::$user->level >= User::LEVEL_ADMIN) {
-	$status_constraint->setValues(Test::STATUS_UNASSIGNED, Test::STATUS_COMPLETED);
-}
-else {
-	$status_constraint->setValues(Test::STATUS_COMPLETED, Test::STATUS_COMPLETED);
-}
-
-$tests = Test::query([
-	"location_id" => $location->id,
-	"status" => $status_constraint,
-], [
-	"sort" => "status",
-	"order" => "asc",
-]);
-
-$projects = Project::load(array_column($tests, "project_id"));
-
-
 View::includeOnce("header", compact("page_title"));
 View::includeOnce("header", compact("page_title"));
-View::include("location", compact("location", "tests"));
+View::include("location", compact("location"));
 View::includeOnce("footer");
 View::includeOnce("footer");
-
-?>

+ 2 - 1
controllers/practice.php

@@ -23,6 +23,7 @@ if(!$test || $reset) {
 	$test = new PracticeTest;
 	$test = new PracticeTest;
 	$test->tester_id = Core::$user->id;
 	$test->tester_id = Core::$user->id;
 	$test->status = Test::STATUS_CONFIRMED;
 	$test->status = Test::STATUS_CONFIRMED;
+	$test->setTemplateId($template->id);
 	$tests[$id] = $test;
 	$tests[$id] = $test;
 	$_SESSION["practice_tests"] = $tests;
 	$_SESSION["practice_tests"] = $tests;
 
 
@@ -198,4 +199,4 @@ View::includeOnce("header", compact("page_title"));
 View::include("practice_form", compact("test", "template", "fields"));
 View::include("practice_form", compact("test", "template", "fields"));
 View::includeOnce("footer");
 View::includeOnce("footer");
 
 
-?>
+?>

+ 24 - 7
controllers/project_export.php

@@ -11,12 +11,23 @@ else {
 $projects = Project::query(["id" => $ids]);
 $projects = Project::query(["id" => $ids]);
 if(!$projects) throw new Exception("No projects to export.");
 if(!$projects) throw new Exception("No projects to export.");
 
 
-$template_ids = array_column($projects, "template_id");
-$template_ids = array_unique($template_ids);
-if(count($template_ids) != 1) throw new Exception("Cannot create export with different templates.");
+$template_processing = false;
 
 
-$template = Template::get($template_ids[0]);
-if(!$template) throw new Exception("Template cannot be found.");
+switch($type) {
+	case "admin":
+	case "customer":
+		$template_processing = true;
+		break;
+}
+
+if($template_processing) {
+	$template_ids = array_column($projects, "template_id");
+	$template_ids = array_unique($template_ids);
+	if(count($template_ids) != 1) throw new Exception("Cannot create export with different templates.");
+
+	$template = Template::get($template_ids[0]);
+	if(!$template) throw new Exception("Template cannot be found.");
+}
 
 
 $tests = Test::query([
 $tests = Test::query([
 	"project_id" => $ids,
 	"project_id" => $ids,
@@ -33,10 +44,16 @@ switch($type) {
 		$template->exportTestsCSV("project_customer_csv.php", $tests);
 		$template->exportTestsCSV("project_customer_csv.php", $tests);
 		break;
 		break;
 
 
+	case "quickbooks-customer":
+		Project::exportCSV("project_quickbooks_customer_csv.php", $projects);
+		break;
+
+	case "quickbooks-tester":
+		Test::exportCSV("project_quickbooks_tester_csv.php", $tests);
+		break;
+
 	case "kml":
 	case "kml":
 		// TODO
 		// TODO
 		break;
 		break;
 
 
 }
 }
-
-

+ 12 - 83
controllers/project_invoice.php

@@ -7,55 +7,19 @@ if(!$project) throw new Exception(__("Project not found."));
 if(!$project->dts_finished) throw new Exception(__("An invoice cannot be generated for this project as it has not been marked as finished."));
 if(!$project->dts_finished) throw new Exception(__("An invoice cannot be generated for this project as it has not been marked as finished."));
 if(!Core::$user->canAdmin()) throw new Exception(__("You do not have permission to access this resource."));
 if(!Core::$user->canAdmin()) throw new Exception(__("You do not have permission to access this resource."));
 
 
-$customer = $project->getCustomer();
-$template = $project->getTemplate();
-$invoice_fields = $template->getCustomerInvoiceFields();
-
-// Calculation
-$default_customer_fee = $project->default_customer_fee;
-$tests = $project->getTests();
-
-$invoice_field_totals = [];
-$test_fee_invoice_counts = [];
-
-$test_costs = 0;
-foreach($tests as $test) {
-
-	$values = $test->getValues(true);
-
-	$fee = $test->customer_fee ?? $default_customer_fee;
-	$test_costs += $fee;
-
-	$count = $test_fee_invoice_counts[$fee] ?? 0;
-	++$count;
-	$test_fee_invoice_counts[$fee] = $count;
+$invoice = $project->getCustomerInvoice();
 
 
-	foreach($invoice_fields as $field) {
-		if(!isset($invoice_field_totals[$field->name])) {
-			$invoice_field_totals[$field->name] = 0;
-		}
+$line_items = $invoice->getLineItems();
 
 
-		$invoice_field_totals[$field->name] += (float) ($values[$field->name] ?? 0);
-	}
-}
-
-$total_ex_vat = $test_costs + array_sum($invoice_field_totals);
-$vat = round($total_ex_vat * 0.20, 2);
-
-$total_inc_vat = $total_ex_vat + $vat;
+$customer = $project->getCustomer();
 
 
-// Processing
-usort($tests, function($a, $b) {
-	return $a->dts_start <=> $b->dts_start;
-});
+$total_ex_vat = $invoice->getTotal();
+$vat = $invoice->getTax();
 
 
-Location::load(array_column($tests, "location_id"));
-Template::load(array_column($tests, "template_id"));
+$total_inc_vat = $invoice->getTotalIncTax();
 
 
 // Filename
 // Filename
-$reference =
-	"P" . str_pad($project->id, 3, "0", STR_PAD_LEFT) .
-	"/C" . str_pad($customer->id, 3, "0", STR_PAD_LEFT);
+$reference = $invoice->getReference();
 
 
 $download_filename = str_replace("/", "_", $reference) . " - " . $project->name . " - Invoice.pdf";
 $download_filename = str_replace("/", "_", $reference) . " - " . $project->name . " - Invoice.pdf";
 
 
@@ -190,53 +154,18 @@ ob_start();
 				</tr>
 				</tr>
 
 
 				<?php
 				<?php
-				/*
-				foreach($tests as $test) {
-					$location = $test->getLocation();
-					$location_address = $location->getDisplayAddress(["address_1", "address_2", "city", "county", "postal_code"]);
-					?>
-
-					<tr>
-						<td>
-							<strong><?=htmlspecialchars($location->name)?></strong><br />
-							<?=nl2br(htmlspecialchars("{$location_address}\n" . date("d/m/Y H:i", strtotime($test->dts_start . " UTC"))))?>
-						</td>
-						<td align="right" valign="top">1</td>
-						<td align="right" valign="top">£<?=number_format($default_customer_fee, 2)?></td>
-						<td align="right" valign="top">£<?=number_format($default_customer_fee, 2)?></td>
-					</tr>
-					<?php
-				}
-				*/
-
-				foreach($test_fee_invoice_counts as $fee => $count) {
-					?>
-					<tr>
-						<td>
-							<strong><?=htmlspecialchars($template->name)?> Testing</strong>
-						</td>
-						<td align="right" valign="top"><?=number_format($count)?></td>
-						<td align="right" valign="top">£<?=number_format($fee, 2)?></td>
-						<td align="right" valign="top">£<?=number_format($fee * $count, 2)?></td>
-					</tr>
-					<?php
-				}
-
-				foreach($invoice_fields as $field) {
-					$total = $invoice_field_totals[$field->name] ?? 0;
-					if(!$total) continue;
+				foreach($line_items as $item) {
 					?>
 					?>
 					<tr>
 					<tr>
 						<td>
 						<td>
-							<strong><?=htmlspecialchars($field->label)?></strong>
+							<strong><?=htmlspecialchars($item->getName())?></strong>
 						</td>
 						</td>
-						<td align="center" valign="top">-</td>
-						<td align="center" valign="top">-</td>
-						<td align="right" valign="top">£<?=number_format($total, 2)?></td>
+						<td align="right" valign="top"><?=htmlspecialchars($item->getDisplayQuantity())?></td>
+						<td align="right" valign="top"><?=htmlspecialchars($item->getDisplayPrice())?></td>
+						<td align="right" valign="top"><?=htmlspecialchars($item->getDisplayTotal())?></td>
 					</tr>
 					</tr>
 					<?php
 					<?php
 				}
 				}
-
 				?>
 				?>
 
 
 				<tr>
 				<tr>

+ 27 - 9
controllers/projects.php

@@ -1,26 +1,43 @@
-<?php
+<?php /** @noinspection PhpUnhandledExceptionInspection */
 
 
 Core::addBreadcrumb("/account", "Account");
 Core::addBreadcrumb("/account", "Account");
 Core::addBreadcrumb("/account/projects", "Projects");
 Core::addBreadcrumb("/account/projects", "Projects");
 
 
 Core::addScript("public/js/app-projects.js");
 Core::addScript("public/js/app-projects.js");
 
 
-$customer = Customer::getForAdmin();
+Core::$allow_all_customers = true;
 
 
-$page_title = "$customer->name Projects";
+$customer_id = http::value("customer_id");
+if(Core::$user->isAdmin() && $customer_id == "ALL") {
 
 
-Core::addBreadcrumb("/account/projects?customer_id=$customer->id", $page_title);
+	$page_title = "All Projects";
+	Core::addBreadcrumb("/account/projects?customer_id=ALL", $page_title);
 
 
-$nvp = ["customer_id" => $customer->id];
+	$nvp = [];
+
+	$customer = new Customer;
+	$customer->id = "ALL";
+	$customer->name = "All";
+
+}
+else {
+	$customer = Customer::getForAdmin();
+	$page_title = "$customer->name Projects";
+	Core::addBreadcrumb("/account/projects?customer_id=$customer->id", $page_title);
+
+	$nvp = ["customer_id" => $customer->id];
+}
 
 
 $id = http::value("id", "int");
 $id = http::value("id", "int");
 $name = http::value("name", "trim");
 $name = http::value("name", "trim");
 $year = http::value("year", "int");
 $year = http::value("year", "int");
+$report_month = http::value("report_month", "db");
 
 
 if($year === false) {
 if($year === false) {
 	$year = date("Y");
 	$year = date("Y");
 }
 }
 
 
+
 if($id) $nvp["id"] = $id;
 if($id) $nvp["id"] = $id;
 if($name) $nvp["name"] = (new Constraint("CONTAINS"))->setValues($name);
 if($name) $nvp["name"] = (new Constraint("CONTAINS"))->setValues($name);
 if($year) {
 if($year) {
@@ -28,14 +45,15 @@ if($year) {
 	$max_dts = "{$year}-12-31 23:59:59";
 	$max_dts = "{$year}-12-31 23:59:59";
 	$nvp["dts_start"] = (new Constraint("BETWEEN"))->setValues($min_dts, $max_dts);
 	$nvp["dts_start"] = (new Constraint("BETWEEN"))->setValues($min_dts, $max_dts);
 }
 }
+if($report_month) {
+	$nvp["dts_report"] = (new Constraint("BEGINS_WITH"))->setValues($report_month);
+}
 
 
 $projects = Project::query($nvp, ["sort" => "dts_start", "order" => "desc"]);
 $projects = Project::query($nvp, ["sort" => "dts_start", "order" => "desc"]);
 $templates = Template::load(array_column($projects, "template_id"));
 $templates = Template::load(array_column($projects, "template_id"));
 
 
-$filter_count = count($nvp) - 1;
+$filter_count = count($nvp);
 
 
 View::includeOnce("header", compact("page_title"));
 View::includeOnce("header", compact("page_title"));
-View::include("projects", compact("customer", "filter_count", "projects", "year"));
+View::include("projects", compact("customer", "filter_count", "projects", "year", "report_month"));
 View::includeOnce("footer");
 View::includeOnce("footer");
-
-?>

+ 11 - 5
controllers/test.php

@@ -1,5 +1,9 @@
 <?php
 <?php
 
 
+/**
+ * @var Test $test
+ */
+
 Core::addScript("public/js/app-test.js");
 Core::addScript("public/js/app-test.js");
 
 
 $test = Test::get($id);
 $test = Test::get($id);
@@ -187,7 +191,11 @@ if(Core::$user->level == User::LEVEL_TESTER) {
 					}
 					}
 				}
 				}
 
 
-				$test->pass = ($test->challenge_stage <= $template->pass_stage) ? 1 : 0; // Pass = Challenged during browsing or before
+				$test->pass = 1;
+				if($template->hasPassFail()) {
+					$test->pass = ($test->challenge_stage <= $template->getPassStage()) ? 1 : 0; // Pass = Challenged during browsing or before
+				}
+
 				$test->dts_updated = Util::getDateTime();
 				$test->dts_updated = Util::getDateTime();
 
 
 				$success = $test->commit();
 				$success = $test->commit();
@@ -241,8 +249,6 @@ else if(Core::$user->level >= User::LEVEL_ADMIN) {
 
 
 	$directory = $test->getDirectory();
 	$directory = $test->getDirectory();
 
 
-	$has_pdf = file_exists($directory . "/pdf.pdf");
-
 	$submit = http::value("submit");
 	$submit = http::value("submit");
 	$tester_message = http::value("tester_message", "trim");
 	$tester_message = http::value("tester_message", "trim");
 	if($submit) {
 	if($submit) {
@@ -447,7 +453,7 @@ else if(Core::$user->level >= User::LEVEL_ADMIN) {
 	});
 	});
 
 
 	View::includeOnce("header", compact("page_title"));
 	View::includeOnce("header", compact("page_title"));
-	View::include("test_verify_form", compact("test", "has_pdf", "tester", "location", "project", "future_projects", "customer", "template", "fields", "values", "tester_message"));
+	View::include("test_verify_form", compact("test", "tester", "location", "project", "future_projects", "customer", "template", "fields", "values", "tester_message"));
 	View::includeOnce("footer");
 	View::includeOnce("footer");
 	return;
 	return;
 }
 }
@@ -460,4 +466,4 @@ else {
 	throw new Exception(__("Invalid request."));
 	throw new Exception(__("Invalid request."));
 }
 }
 
 
-?>
+?>

+ 16 - 4
controllers/test_file.php

@@ -3,10 +3,24 @@
 $test = Test::get($id);
 $test = Test::get($id);
 if(!$test) throw new Exception(__("Test not found."));
 if(!$test) throw new Exception(__("Test not found."));
 
 
-if(Core::$user->level < User::LEVEL_ADMIN) {
-	if(Core::$user->id != $test->tester_id) throw new Exception(__("You do not have permission to access this resource."));
+$is_pdf = $name == "pdf";
+
+if($is_pdf) {
+	$project = $test->getProject();
+
+	$customers = Core::$user->getCustomers();
+	$customer_ids = array_column($customers, "id");
+
+	if(!in_array($project->customer_id, $customer_ids)) throw new Exception(__("You do not have permission to access this resource."));
 }
 }
 
 
+if(!$is_pdf) {
+	if(Core::$user->level < User::LEVEL_ADMIN) {
+		if(Core::$user->id != $test->tester_id) throw new Exception(__("You do not have permission to access this resource."));
+	}
+}
+
+
 $directory = $test->getDirectory();
 $directory = $test->getDirectory();
 $path_jpg = $directory . "/" . $name . ".jpg";
 $path_jpg = $directory . "/" . $name . ".jpg";
 $path_pdf = $directory . "/" . $name . ".pdf";
 $path_pdf = $directory . "/" . $name . ".pdf";
@@ -23,5 +37,3 @@ else {
 	header("Content-Type: image/png");
 	header("Content-Type: image/png");
 	readfile("public/img/blank.png");
 	readfile("public/img/blank.png");
 }
 }
-
-?>

+ 1 - 4
controllers/test_invoice.php

@@ -36,10 +36,7 @@ if(!$address) throw new Exception(__("Invoice address not found. Please set an a
 if(!$tester->hasValidPaymentMethod()) throw new Exception(__("No valid payment method found. Please go to the Settings page and make sure all respective fields are filled in and then try again."));
 if(!$tester->hasValidPaymentMethod()) throw new Exception(__("No valid payment method found. Please go to the Settings page and make sure all respective fields are filled in and then try again."));
 
 
 // Filename
 // Filename
-$reference =
-	"T" . str_pad($test->id, 3, "0", STR_PAD_LEFT) .
-	"/L" . str_pad($location->id, 3, "0", STR_PAD_LEFT) .
-	"/U" . str_pad($tester->id, 3, "0", STR_PAD_LEFT);
+$reference = $test->getTesterInvoiceReference();
 
 
 $download_filename = str_replace("/", "_", $reference) . " - " . $tester->getDisplayName() . " - Invoice.pdf";
 $download_filename = str_replace("/", "_", $reference) . " - " . $tester->getDisplayName() . " - Invoice.pdf";
 
 

+ 16 - 0
controllers/test_results_customer_list.php

@@ -0,0 +1,16 @@
+<?php
+
+$customers = Core::$user->getCustomers();
+if(count($customers) == 1) {
+	$customer = $customers[0];
+	http::redirect($customer->getTestResultsUrl());
+}
+
+$page_title = __("Test Results");
+
+Core::addBreadcrumb("/account", __("Account"));
+Core::addBreadcrumb("/account/test-results", $page_title);
+
+View::includeOnce("header", compact("page_title"));
+View::include("test_results_customer_list", compact("customers"));
+View::includeOnce("footer");

+ 26 - 0
controllers/test_results_project_list.php

@@ -0,0 +1,26 @@
+<?php
+
+$customers = Core::$user->getCustomers();
+if(!$customers) throw new Exception(__("An unexpected error has occurred. Please try again later."));
+
+$customer_ids = array_column($customers, "id");
+if(!in_array($customer_id, $customer_ids)) throw new Exception(__("You do not have permission to access this page."));
+
+$customer = Customer::get($customer_id);
+$projects = $customer->getProjects();
+
+$projects = array_filter($projects, function($project) {
+    return $project->isFinished();
+});
+
+$test_results_url = $customer->getTestResultsUrl();
+
+$page_title = $customer->name;
+
+Core::addBreadcrumb("/account", __("Account"));
+Core::addBreadcrumb("/account/test-results", __("Test Results"));
+Core::addBreadcrumb($test_results_url, $customer->name);
+
+View::includeOnce("header", compact("page_title"));
+View::include("test_results_project_list", compact("projects"));
+View::includeOnce("footer");

+ 53 - 0
controllers/test_results_test_list.php

@@ -0,0 +1,53 @@
+<?php
+
+$customers = Core::$user->getCustomers();
+if(!$customers) throw new Exception(__("An unexpected error has occurred. Please try again later."));
+
+$project = Project::get($project_id);
+if(!$project) throw new Exception(__("Project not found."));
+
+$template = $project->getTemplate();
+$has_pass_fail = $template->hasPassFail();
+
+$customer_ids = array_column($customers, "id");
+if(!in_array($project->customer_id, $customer_ids)) throw new Exception(__("You do not have permission to access this page."));
+
+$customer = $project->getCustomer();
+$tests = $project->getTests();
+
+$location_ids = array_column($tests, "location_id");
+Location::load($location_ids);
+
+usort($tests, function($a, $b) {
+    $a_location = $a->getLocation();
+    $b_location = $b->getLocation();
+
+    return strnatcasecmp($a_location->name, $b_location->name);
+});
+
+$test_count = $project->getTestCount();
+$pass_count = $project->getPassCount();
+$fail_count = $project->getFailCount();
+
+$pass_percentage = 0;
+$fail_percentage = 0;
+
+$pass_fail_count = $pass_count + $fail_count;
+if($pass_fail_count > 0) {
+    $pass_percentage = number_format($pass_count / $pass_fail_count, 4) * 100;
+    $fail_percentage = 100 - $pass_percentage;
+}
+
+$project_list_url = $customer->getTestResultsUrl();
+$test_list_url = $project->getTestResultsUrl();
+
+$page_title = __("Test Results %s Test List", $project->name);
+
+Core::addBreadcrumb("/account", __("Account"));
+Core::addBreadcrumb("/account/test-results", __("Test Results"));
+Core::addBreadcrumb($project_list_url, $customer->name);
+Core::addBreadcrumb($test_list_url, $project->name);
+
+View::includeOnce("header", compact("page_title"));
+View::include("test_results_test_list", compact("project", "has_pass_fail", "tests", "test_count", "pass_count", "fail_count", "pass_percentage", "fail_percentage"));
+View::includeOnce("footer");

+ 1 - 1
engine/account_icon.php

@@ -18,4 +18,4 @@ class AccountIcon {
 		$this->counter = $counter;
 		$this->counter = $counter;
 	}
 	}
 
 
-}
+}

+ 17 - 7
engine/chart.php

@@ -1,8 +1,10 @@
-<?php
+<?php /** @noinspection DuplicatedCode */
+/** @noinspection PhpUnused */
+/** @noinspection PhpUndefinedMethodInspection */
+/** @noinspection PhpUnusedLocalVariableInspection */
 
 
-use PhpOffice\PhpPresentation\Style\Color;
+use PhpOffice\PhpPresentation\Slide;
 use PhpOffice\PhpPresentation\Style\Alignment;
 use PhpOffice\PhpPresentation\Style\Alignment;
-use PhpOffice\PhpPresentation\Shape\Drawing\Base64;
 
 
 class Chart {
 class Chart {
 
 
@@ -59,6 +61,10 @@ class Chart {
 	public $printPercentages = false;
 	public $printPercentages = false;
 	public $printTotalColumn = false;
 	public $printTotalColumn = false;
 
 
+	/**
+	 * Chart constructor.
+	 * @throws Exception
+	 */
 	public function __construct() {
 	public function __construct() {
 		$this->id = bin2hex(random_bytes(8));
 		$this->id = bin2hex(random_bytes(8));
 	}
 	}
@@ -383,7 +389,7 @@ class Chart {
 	}
 	}
 
 
 	// Presentation methods
 	// Presentation methods
-	public function addChart($slide, $path) {
+	public function addChart(Slide $slide, string $path) {
 
 
 		$chart_offset_y = 100;
 		$chart_offset_y = 100;
 		if($this->print) {
 		if($this->print) {
@@ -401,7 +407,13 @@ class Chart {
 		return true;
 		return true;
 	}
 	}
 
 
-	public function addDataTable($slide, $offset_x = 30, $offset_y = 540) {
+	/**
+	 * @param Slide $slide
+	 * @param int $offset_x
+	 * @param int $offset_y
+	 * @throws Exception
+	 */
+	public function addDataTable(Slide $slide, int $offset_x = 30, int $offset_y = 540) {
 
 
 		$labels = $this->getLabels();
 		$labels = $this->getLabels();
 		$datasets = array_merge($this->getDatasets(), $this->getPrintDatasets());
 		$datasets = array_merge($this->getDatasets(), $this->getPrintDatasets());
@@ -506,5 +518,3 @@ class Chart {
 	}
 	}
 
 
 }
 }
-
-?>

+ 6 - 3
engine/constraint.php

@@ -22,7 +22,12 @@ class Constraint {
 	private $type;
 	private $type;
 	private $values = [];
 	private $values = [];
 
 
-	public function __construct($type) {
+	/**
+	 * Constraint constructor.
+	 * @param string $type
+	 * @throws Exception
+	 */
+	public function __construct(string $type) {
 		$type = "TYPE_" . strtoupper($type);
 		$type = "TYPE_" . strtoupper($type);
 		if(!defined("Constraint::$type")) throw new Exception("Constraint::$type is not defined.");
 		if(!defined("Constraint::$type")) throw new Exception("Constraint::$type is not defined.");
 		$this->type = constant("Constraint::$type");
 		$this->type = constant("Constraint::$type");
@@ -73,5 +78,3 @@ class Constraint {
 	}
 	}
 
 
 }
 }
-
-?>

+ 23 - 4
engine/core.php

@@ -1,7 +1,11 @@
-<?php
+<?php /** @noinspection PhpUnused */
+
 
 
 class Core {
 class Core {
 
 
+	/**
+	 * @var User $user
+	 */
 	public static $user = null;
 	public static $user = null;
 	public static $admin = false;
 	public static $admin = false;
 
 
@@ -13,6 +17,8 @@ class Core {
 	public static $show_alerts = true;
 	public static $show_alerts = true;
 	public static $show_footer_content = true;
 	public static $show_footer_content = true;
 
 
+	public static $allow_all_customers = false;
+
 	public static $page = 1;
 	public static $page = 1;
 	public static $page_count = 1;
 	public static $page_count = 1;
 
 
@@ -79,6 +85,9 @@ class Core {
 		}
 		}
 	}
 	}
 
 
+	/**
+	 * @throws Exception
+	 */
 	public static function requireAdmin() {
 	public static function requireAdmin() {
 		Core::requireLogIn();
 		Core::requireLogIn();
 		if(Core::$user->canAdmin() === false) {
 		if(Core::$user->canAdmin() === false) {
@@ -86,6 +95,10 @@ class Core {
 		}
 		}
 	}
 	}
 
 
+	/**
+	 * @param $level
+	 * @throws Exception
+	 */
 	public static function requireUserLevel($level) {
 	public static function requireUserLevel($level) {
 		Core::requireLogIn();
 		Core::requireLogIn();
 		if(Core::$user->level < $level) {
 		if(Core::$user->level < $level) {
@@ -97,11 +110,19 @@ class Core {
 		return !empty($_SESSION["user_id"]);
 		return !empty($_SESSION["user_id"]);
 	}
 	}
 
 
-	public static function validateCSRFToken($token) {
+	/**
+	 * @param string $token
+	 * @return bool
+	 * @throws Exception
+	 */
+	public static function validateCSRFToken(string $token) {
 		if($_SESSION["csrf_token"] !== $token) throw new Exception("CSRF attempt blocked.");
 		if($_SESSION["csrf_token"] !== $token) throw new Exception("CSRF attempt blocked.");
 		return true;
 		return true;
 	}
 	}
 
 
+	/**
+	 * @throws Exception
+	 */
 	public static function refuseAJAX() {
 	public static function refuseAJAX() {
 		if(HTTP::isAJAX()) {
 		if(HTTP::isAJAX()) {
 			header("HTTP/1.1 403 Forbidden");
 			header("HTTP/1.1 403 Forbidden");
@@ -110,5 +131,3 @@ class Core {
 	}
 	}
 
 
 }
 }
-
-?>

+ 50 - 3
engine/customer.php

@@ -1,5 +1,24 @@
 <?php
 <?php
 
 
+/**
+ * @property int $id
+ * @property string $name
+ * @property string $address_1
+ * @property string $address_2
+ * @property string $city
+ * @property string $county
+ * @property string $postal_code
+ * @property string $country
+ * @property string $email
+ * @property string $phone
+ * @property string $invoice_contact_name
+ * @property bool $email_after_test
+ * @property bool $email_locations_after_test
+ * @property string $internal_id_field_name
+ * @property string $region_field_name
+ * @property string $area_manager_field_name
+ */
+
 class Customer extends Model {
 class Customer extends Model {
 
 
 	protected static $table = "customer";
 	protected static $table = "customer";
@@ -12,7 +31,12 @@ class Customer extends Model {
 	];
 	];
 
 
 	// Static methods
 	// Static methods
-	public static function getForAdmin() {
+
+	/**
+	 * @return Customer
+	 * @throws Exception
+	 */
+	public static function getForAdmin(): ?Customer {
 		$customers = Core::$user->getCustomers();
 		$customers = Core::$user->getCustomers();
 		if(count($customers) == 0) throw new Exception("At least one customer must exist before this page can be accessed.");
 		if(count($customers) == 0) throw new Exception("At least one customer must exist before this page can be accessed.");
 		else if(count($customers) == 1) {
 		else if(count($customers) == 1) {
@@ -33,7 +57,7 @@ class Customer extends Model {
 			// Enforce restriction if CUSTOMER or lower
 			// Enforce restriction if CUSTOMER or lower
 			if(Core::$user->level < User::LEVEL_ADMIN) {
 			if(Core::$user->level < User::LEVEL_ADMIN) {
 				$link = UserCustomer::get(Core::$user->id, $customer_id);
 				$link = UserCustomer::get(Core::$user->id, $customer_id);
-				if(!$link) $customer = false;
+				if(!$link) $customer = null;
 			}
 			}
 		}
 		}
 
 
@@ -43,17 +67,40 @@ class Customer extends Model {
 	}
 	}
 
 
 	// Object methods
 	// Object methods
-	public function getLocations($query = []) {
+
+	/**
+	 * @param array $query
+	 * @return Location[]
+	 * @throws Exception
+	 */
+	public function getLocations(array $query = []): array {
 		$nvp = array_merge(["customer_id" => $this->id], $query);
 		$nvp = array_merge(["customer_id" => $this->id], $query);
 		return Location::query($nvp, ["sort" => "name"]);
 		return Location::query($nvp, ["sort" => "name"]);
 	}
 	}
 
 
+	/**
+	 * @return Project[]
+	 * @throws Exception
+	 */
 	public function getProjects() {
 	public function getProjects() {
 		return Project::query(["customer_id" => $this->id], ["sort" => "dts_deadline", "order" => "desc"]);
 		return Project::query(["customer_id" => $this->id], ["sort" => "dts_deadline", "order" => "desc"]);
 	}
 	}
 
 
+	/**
+	 * @return Template[]
+	 * @throws Exception
+	 */
 	public function getTemplates() {
 	public function getTemplates() {
 		return Template::query(["customer_id" => $this->id], ["sort" => "name"]);
 		return Template::query(["customer_id" => $this->id], ["sort" => "name"]);
 	}
 	}
 
 
+	/**
+	 * @return string
+	 */
+	public function getTestResultsUrl(): string {
+		$slug = Util::slugWithId($this->name, $this->id);
+		$url = "/account/test-results/{$slug}";
+		return $url;
+	}
+
 }
 }

+ 122 - 42
engine/db.php

@@ -1,4 +1,4 @@
-<?php
+<?php /** @noinspection PhpUnused */
 
 
 class db {
 class db {
 
 
@@ -9,67 +9,103 @@ class db {
 
 
 	public static $DB = null;
 	public static $DB = null;
 
 
-	public static function affected_rows($link = null) {
+	public static function affected_rows(mysqli $link = null): int {
 		if(empty($link)) $link = db::$DB;
 		if(empty($link)) $link = db::$DB;
 		return mysqli_affected_rows($link);
 		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);
+	/**
+	 * @param string $host
+	 * @param string $username
+	 * @param string $password
+	 * @param string $database
+	 * @param int $port
+	 * @return mysqli
+	 * @throws Exception
+	 */
+	public static function connect(string $host, string $username, string $password, string $database = "", int $port = 3306): mysqli {
+		$link = @new mysqli($host, $username, $password, $database, $port);
+		db::$DB = $link;
+
+		if(!is_null($link->connect_error)) {
+			throw new Exception("Connect Error: " . $link->connect_error);
 		}
 		}
 		db::query("SET NAMES utf8mb4");
 		db::query("SET NAMES utf8mb4");
-		return db::$DB;
+		return $link;
 	}
 	}
 
 
-	public static function data_seek($result, $row_number) {
-		mysqli_data_seek($result, $row_number);
+	/**
+	 * @param mysqli_result $result
+	 * @param int $row_number
+	 * @return bool
+	 */
+	public static function data_seek(mysqli_result $result, int $row_number): bool {
+		return mysqli_data_seek($result, $row_number);
 	}
 	}
 
 
-	public static function escape($string) {
+	/**
+	 * @param string $string
+	 * @return string
+	 */
+	public static function escape(string $string): string {
 		return mysqli_real_escape_string(db::$DB, $string);
 		return mysqli_real_escape_string(db::$DB, $string);
 	}
 	}
 
 
-	public static function error() {
+	/**
+	 * @return string
+	 */
+	public static function error(): string {
 		return mysqli_error(db::$DB);
 		return mysqli_error(db::$DB);
 	}
 	}
 
 
-	public static function fetch_array($result) {
+	/**
+	 * @param mysqli_result $result
+	 * @return array|null
+	 */
+	public static function fetch_array(mysqli_result $result): ?array {
 		return mysqli_fetch_array($result);
 		return mysqli_fetch_array($result);
 	}
 	}
 
 
-	public static function fetch_assoc($result) {
+	/**
+	 * @param mysqli_result $result
+	 * @return array|null
+	 */
+	public static function fetch_assoc(mysqli_result $result): ?array {
 		return mysqli_fetch_assoc($result);
 		return mysqli_fetch_assoc($result);
 	}
 	}
 
 
-	public static function fetch_object($result) {
+	/**
+	 * @param mysqli_result $result
+	 * @return object|null
+	 */
+	public static function fetch_object(mysqli_result $result): ?object {
 		return mysqli_fetch_object($result);
 		return mysqli_fetch_object($result);
 	}
 	}
 
 
-	public static function fetch_row($result) {
+	/**
+	 * @param mysqli_result $result
+	 * @return array|null
+	 */
+	public static function fetch_row(mysqli_result $result): ?array {
 		return mysqli_fetch_row($result);
 		return mysqli_fetch_row($result);
 	}
 	}
 
 
-	public static function free_result($result) {
+	public static function free_result(mysqli_result $result): void {
 		mysqli_free_result($result);
 		mysqli_free_result($result);
 	}
 	}
 
 
-	public static function get_value_string($pairs, $escape=false) {
+	/**
+	 * @param array $pairs
+	 * @param bool $escape
+	 * @return string
+	 */
+	public static function get_value_string(array $pairs, bool $escape = false): string {
 
 
 		if($escape) {
 		if($escape) {
 			$pairs = array_map(array("db", "escape"), $pairs);
 			$pairs = array_map(array("db", "escape"), $pairs);
 		}
 		}
 
 
-		$string_array = array();
+		$string_array = [];
 
 
 		foreach($pairs as $field => $value) {
 		foreach($pairs as $field => $value) {
 			if(is_null($value)) {
 			if(is_null($value)) {
@@ -85,7 +121,12 @@ class db {
 		return implode(", ", $string_array);
 		return implode(", ", $string_array);
 	}
 	}
 
 
-	public static function get_where_string($pairs, $options = []) {
+	/**
+	 * @param array $pairs
+	 * @param array|bool $options
+	 * @return string
+	 */
+	public static function get_where_string(array $pairs, $options = []): string {
 
 
 		$escape = false;
 		$escape = false;
 		$fuzzy = false;
 		$fuzzy = false;
@@ -104,7 +145,7 @@ class db {
 			$pairs = array_map(array("db", "escape"), $pairs);
 			$pairs = array_map(array("db", "escape"), $pairs);
 		}
 		}
 
 
-		$string_array = array();
+		$string_array = [];
 
 
 		foreach($pairs as $field => $value) {
 		foreach($pairs as $field => $value) {
 			if(is_null($value)) {
 			if(is_null($value)) {
@@ -128,17 +169,30 @@ class db {
 		return implode(" AND ", $string_array);
 		return implode(" AND ", $string_array);
 	}
 	}
 
 
-	public static function has_index($table, $index_name) {
+	/**
+	 * @param string $table
+	 * @param string $index_name
+	 * @return bool
+	 * @throws Exception
+	 */
+	public static function has_index(string $table, string $index_name): bool {
 		$sql = "SHOW INDEX FROM `$table` WHERE `Key_name`='$index_name'";
 		$sql = "SHOW INDEX FROM `$table` WHERE `Key_name`='$index_name'";
 		$result = db::query($sql);
 		$result = db::query($sql);
 		return db::num_rows($result)==1;
 		return db::num_rows($result)==1;
 	}
 	}
 
 
-	public static function insert_id() {
+	/**
+	 * @return int
+	 */
+	public static function insert_id(): int {
 		return mysqli_insert_id(db::$DB);
 		return mysqli_insert_id(db::$DB);
 	}
 	}
 
 
-	public static function num_rows($result) {
+	/**
+	 * @param mysqli_result $result
+	 * @return int
+	 */
+	public static function num_rows(mysqli_result $result): int {
 
 
 		if(is_bool($result)) {
 		if(is_bool($result)) {
 			return 0;
 			return 0;
@@ -147,21 +201,40 @@ class db {
 		return mysqli_num_rows($result);
 		return mysqli_num_rows($result);
 	}
 	}
 
 
-	public static function object_or_false($result) {
-		return mysqli_num_rows($result)>0 ? db::fetch_object($result) : false;
+	/**
+	 * @param mysqli_result $result
+	 * @return object|null
+	 */
+	public static function object_or_null(mysqli_result $result): ?object {
+		return mysqli_num_rows($result)>0 ? db::fetch_object($result) : null;
 	}
 	}
 
 
-	public static function object_with_id($table, $field, $id) {
+	/**
+	 * @param string $table
+	 * @param string $field
+	 * @param int $id
+	 * @return object|null
+	 * @throws Exception
+	 */
+	public static function object_with_id(string $table, string $field, int $id): ?object {
 		$sql = "SELECT * FROM `$table` WHERE `$field`='$id'";
 		$sql = "SELECT * FROM `$table` WHERE `$field`='$id'";
 		$result = db::query($sql);
 		$result = db::query($sql);
-		return db::object_or_false($result);
+		return db::object_or_null($result);
 	}
 	}
 
 
-	public static function ping() {
+	/**
+	 * @return bool
+	 */
+	public static function ping(): bool {
 		return mysqli_ping(db::$DB);
 		return mysqli_ping(db::$DB);
 	}
 	}
 
 
-	public static function query($sql) {
+	/**
+	 * @param string $sql
+	 * @return bool|mysqli_result
+	 * @throws Exception
+	 */
+	public static function query(string $sql) {
 		if(!is_string($sql)) return false;
 		if(!is_string($sql)) return false;
 
 
 		self::$last_query = $sql;
 		self::$last_query = $sql;
@@ -182,18 +255,25 @@ class db {
 		return $result;
 		return $result;
 	}
 	}
 
 
-	public static function select_db($name, $link_identifier=NULL) {
+	/**
+	 * @param string $name
+	 * @param mysqli|null $link_identifier
+	 * @return bool
+	 */
+	public static function select_db(string $name, mysqli $link_identifier = null): bool {
 		if(is_null($link_identifier)) {
 		if(is_null($link_identifier)) {
-			mysqli_select_db(db::$DB, $name);
+			return mysqli_select_db(db::$DB, $name);
 		}
 		}
 		else {
 		else {
-			mysqli_select_db($link_identifier, $name);
+			return mysqli_select_db($link_identifier, $name);
 		}
 		}
 	}
 	}
 
 
-	public static function thread_id() {
+	/**
+	 * @return int
+	 */
+	public static function thread_id(): int {
 		return mysqli_thread_id(db::$DB);
 		return mysqli_thread_id(db::$DB);
 	}
 	}
 }
 }
 
 
-?>

+ 57 - 12
engine/email.php

@@ -1,9 +1,10 @@
-<?php
+<?php /** @noinspection PhpUnused */
 
 
 use PHPMailer\PHPMailer\PHPMailer;
 use PHPMailer\PHPMailer\PHPMailer;
 
 
 class Email {
 class Email {
 
 
+    /** @var PHPMailer $instance */
 	private $instance;
 	private $instance;
 
 
 	private $htmlContent = "";
 	private $htmlContent = "";
@@ -41,7 +42,11 @@ class Email {
 		$this->instance = Email::getPHPMailerInstance();
 		$this->instance = Email::getPHPMailerInstance();
 	}
 	}
 
 
-	public function loadHtmlTemplate($template_name) {
+	/**
+	 * @param string $template_name
+	 * @throws Exception
+	 */
+	public function loadHtmlTemplate(string $template_name) {
 
 
 		$this->instance->IsHTML(true);
 		$this->instance->IsHTML(true);
 
 
@@ -53,41 +58,81 @@ class Email {
 		$this->htmlContent = $content;
 		$this->htmlContent = $content;
 	}
 	}
 
 
-	public function setValues($values = []) {
+	/**
+	 * @param array $values
+	 * @return bool
+	 */
+	public function setValues(array $values = []) {
 		foreach($values as $key => $value) {
 		foreach($values as $key => $value) {
 			$this->htmlContent = str_replace("{" . $key . "}", $value, $this->htmlContent);
 			$this->htmlContent = str_replace("{" . $key . "}", $value, $this->htmlContent);
 		}
 		}
 		return true;
 		return true;
 	}
 	}
 
 
-	public function addAttachment($path, $name = "", $encoding = "base64", $type = "", $disposition = "attachment") {
+	/**
+	 * @param string $path
+	 * @param string $name
+	 * @param string $encoding
+	 * @param string $type
+	 * @param string $disposition
+	 * @return bool
+	 * @throws \PHPMailer\PHPMailer\Exception
+	 */
+	public function addAttachment(string $path, string $name = "", string $encoding = "base64", string $type = "", string $disposition = "attachment") {
 		return $this->instance->addAttachment($path, $name, $encoding, $type, $disposition);
 		return $this->instance->addAttachment($path, $name, $encoding, $type, $disposition);
 	}
 	}
 
 
-	public function setFrom($email, $name="") {
+	/**
+	 * @param string $email
+	 * @param string $name
+	 * @return bool
+	 * @throws \PHPMailer\PHPMailer\Exception
+	 */
+	public function setFrom(string $email, string $name = "") {
 		return $this->instance->setFrom($email, $name);
 		return $this->instance->setFrom($email, $name);
 	}
 	}
 
 
-	public function addAddress($email, $name="") {
+	/**
+	 * @param string $email
+	 * @param string $name
+	 * @return bool
+	 */
+	public function addAddress(string $email, string $name = "") {
 		return $this->instance->addAddress($email, $name);
 		return $this->instance->addAddress($email, $name);
 	}
 	}
 
 
-	public function addReplyTo($email, $name="") {
+	/**
+	 * @param string $email
+	 * @param string $name
+	 * @return bool
+	 */
+	public function addReplyTo(string $email, string $name = "") {
 		return $this->instance->addReplyTo($email, $name);
 		return $this->instance->addReplyTo($email, $name);
 	}
 	}
 
 
-	public function setSubject($subject) {
+	/**
+	 * @param string $subject
+	 * @return bool
+	 */
+	public function setSubject(string $subject) {
 		$this->instance->Subject = $subject;
 		$this->instance->Subject = $subject;
 		return true;
 		return true;
 	}
 	}
 
 
-	public function setHtmlContent($string) {
+	/**
+	 * @param string $string
+	 */
+	public function setHtmlContent(string $string) {
 		$this->instance->IsHTML(true);
 		$this->instance->IsHTML(true);
 
 
 		$this->htmlContent = $string;
 		$this->htmlContent = $string;
 	}
 	}
 
 
-	public function send() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function send(): bool {
 		// Does our sanity checks and then send email
 		// Does our sanity checks and then send email
 		$instance = $this->instance;
 		$instance = $this->instance;
 
 
@@ -97,7 +142,7 @@ class Email {
 		if(empty($this->htmlContent)) throw new Exception("No content is set.");
 		if(empty($this->htmlContent)) throw new Exception("No content is set.");
 
 
 		// Embed images
 		// Embed images
-		$match_count = preg_match_all("/src\=\"(\.\.\/public\/img\/[^\"]*)\"/i", $this->htmlContent, $all_matches);
+		$match_count = preg_match_all("/src=\"(\.\.\/public\/img\/[^\"]*)\"/i", $this->htmlContent, $all_matches);
 		if($match_count > 0) {
 		if($match_count > 0) {
 
 
 			$paths = $all_matches[1];
 			$paths = $all_matches[1];
@@ -114,7 +159,7 @@ class Email {
 			}
 			}
 		}
 		}
 
 
-		$count = preg_match_all("/\{([a-z\-]+)\}/", $this->htmlContent, $matches);
+		$count = preg_match_all("/{([a-z\-]+)}/", $this->htmlContent, $matches);
 		if($count > 0) {
 		if($count > 0) {
 			$missing_keys = [];
 			$missing_keys = [];
 			foreach($matches[1] as $key) {
 			foreach($matches[1] as $key) {

+ 4 - 2
engine/email_builder.php

@@ -1,4 +1,6 @@
-<?php
+<?php /** @noinspection HtmlRequiredLangAttribute */
+/** @noinspection HtmlDeprecatedTag */
+/** @noinspection HtmlDeprecatedAttribute */
 
 
 class EmailBuilder {
 class EmailBuilder {
 
 
@@ -135,4 +137,4 @@ EOD;
 
 
 	}
 	}
 
 
-}
+}

+ 43 - 12
engine/form.php

@@ -1,4 +1,4 @@
-<?php
+<?php /** @noinspection DuplicatedCode */
 
 
 class Form {
 class Form {
 
 
@@ -7,11 +7,20 @@ class Form {
 		1 => YES,
 		1 => YES,
 	];
 	];
 
 
-	public static function checked($value) {
+	/**
+	 * @param $value
+	 * @return string
+	 */
+	public static function checked($value): string {
 		return !empty($value) ? "checked" : "";
 		return !empty($value) ? "checked" : "";
 	}
 	}
 
 
-	public static function checkRecaptcha($required_score = 0.5) {
+	/**
+	 * @param float $required_score
+	 * @return bool
+	 * @throws Exception
+	 */
+	public static function checkRecaptcha(float $required_score = 0.5) {
 
 
 		if(!defined("GOOGLE_RECAPTCHA_SECRET")) return true;
 		if(!defined("GOOGLE_RECAPTCHA_SECRET")) return true;
 
 
@@ -124,7 +133,7 @@ class Form {
 			}
 			}
 		}
 		}
 
 
-		if(!$countries) return false;
+		if(!$countries) return;
 
 
 		$country_pairs = get_object_vars($countries);
 		$country_pairs = get_object_vars($countries);
 		sort($country_pairs);
 		sort($country_pairs);
@@ -142,7 +151,11 @@ class Form {
 		}
 		}
 	}
 	}
 
 
-	public static function renderField($options) {
+	/**
+	 * @param object $options
+	 * @throws Exception
+	 */
+	public static function renderField(object $options) {
 
 
 		switch($options->type) {
 		switch($options->type) {
 
 
@@ -180,7 +193,11 @@ class Form {
 		<?php
 		<?php
 	}
 	}
 
 
-	private static function renderTextField($options) {
+	/**
+	 * @param object $options
+	 * @throws Exception
+	 */
+	private static function renderTextField(object $options) {
 		$id = str_replace("_", "-", $options->name);
 		$id = str_replace("_", "-", $options->name);
 		$placeholder = "Enter " . strtolower($options->label);
 		$placeholder = "Enter " . strtolower($options->label);
 		$value = $options->value ?? http::value($options->name);
 		$value = $options->value ?? http::value($options->name);
@@ -204,7 +221,11 @@ class Form {
 		<?php
 		<?php
 	}
 	}
 
 
-	private static function renderNumberField($options) {
+	/**
+	 * @param object $options
+	 * @throws Exception
+	 */
+	private static function renderNumberField(object $options) {
 		$id = str_replace("_", "-", $options->name);
 		$id = str_replace("_", "-", $options->name);
 		$placeholder = "Enter " . strtolower($options->label);
 		$placeholder = "Enter " . strtolower($options->label);
 		$value = $options->value ?? http::value($options->name);
 		$value = $options->value ?? http::value($options->name);
@@ -244,7 +265,11 @@ class Form {
 		<?php
 		<?php
 	}
 	}
 
 
-	private static function renderSelectField($options) {
+	/**
+	 * @param object $options
+	 * @throws Exception
+	 */
+	private static function renderSelectField(object $options) {
 		$id = str_replace("_", "-", $options->name);
 		$id = str_replace("_", "-", $options->name);
 		$selected_value = $options->value ?? http::value($options->name);
 		$selected_value = $options->value ?? http::value($options->name);
 		$required = ($options->required ?? false) ? "required" : "";
 		$required = ($options->required ?? false) ? "required" : "";
@@ -277,9 +302,11 @@ class Form {
 		<?php
 		<?php
 	}
 	}
 
 
-	private static function renderFileField($options) {
+	/**
+	 * @param object $options
+	 */
+	private static function renderFileField(object $options) {
 		$id = str_replace("_", "-", $options->name);
 		$id = str_replace("_", "-", $options->name);
-		$placeholder = "Enter " . strtolower($options->label);
 		$required = ($options->required ?? false) ? "required" : "";
 		$required = ($options->required ?? false) ? "required" : "";
 		$help_text = $options->helpText ?? false;
 		$help_text = $options->helpText ?? false;
 		?>
 		?>
@@ -299,7 +326,11 @@ class Form {
 		<?php
 		<?php
 	}
 	}
 
 
-	private static function renderTextareaField($options) {
+	/**
+	 * @param object $options
+	 * @throws Exception
+	 */
+	private static function renderTextareaField(object $options) {
 		$id = str_replace("_", "-", $options->name);
 		$id = str_replace("_", "-", $options->name);
 		$placeholder = "Enter " . strtolower($options->label);
 		$placeholder = "Enter " . strtolower($options->label);
 		$value = $options->value ?? http::value($options->name);
 		$value = $options->value ?? http::value($options->name);
@@ -325,4 +356,4 @@ class Form {
 
 
 }
 }
 
 
-?>
+?>

+ 1 - 1
engine/form_exception.php

@@ -30,4 +30,4 @@ class FormException extends Exception {
 		]);
 		]);
 	}
 	}
 
 
-}
+}

+ 6 - 1
engine/geolocation.php

@@ -8,7 +8,6 @@ class Geolocation {
 	const MILES_IN_KM = 0.621371;
 	const MILES_IN_KM = 0.621371;
 	const KMS_IN_MILE = 1.60934;
 	const KMS_IN_MILE = 1.60934;
 
 
-
 	public static function getBounds($lat_lng, $distance, $units = Geolocation::UNIT_MILES) {
 	public static function getBounds($lat_lng, $distance, $units = Geolocation::UNIT_MILES) {
 
 
 		list($latitude, $longitude) = $lat_lng;
 		list($latitude, $longitude) = $lat_lng;
@@ -65,6 +64,12 @@ class Geolocation {
 		}
 		}
 	}
 	}
 
 
+	/**
+	 * @param $address
+	 * @param string $region
+	 * @return array
+	 * @throws Exception
+	 */
 	public static function geocode($address, $region = "uk") {
 	public static function geocode($address, $region = "uk") {
 		$query = [
 		$query = [
 			"address" =>  $address,
 			"address" =>  $address,

+ 0 - 2
engine/geolocation_bounds.php

@@ -40,5 +40,3 @@ class GeolocationBounds {
 	}
 	}
 
 
 }
 }
-
-?>

+ 1 - 3
engine/html.php

@@ -15,9 +15,7 @@ class HTML {
 		$modified_time = filemtime($path);
 		$modified_time = filemtime($path);
 		$src = preg_replace("/^public\//", "/", $path);
 		$src = preg_replace("/^public\//", "/", $path);
 		?>
 		?>
-		<link rel="stylesheet" type="text/css" href="<?=htmlspecialchars($src)?>?<?=$modified_time?>"></link>
+        <link rel="stylesheet" type="text/css" href="<?=htmlspecialchars($src)?>?<?=$modified_time?>" />
 		<?php
 		<?php
 	}
 	}
 }
 }
-
-?>

+ 47 - 36
engine/http.php

@@ -8,7 +8,14 @@ class HTTP {
 		return (!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest");
 		return (!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest");
 	}
 	}
 
 
-	public static function post($url, $fields_or_data, $curl_options = []) {
+	/**
+	 * @param string $url
+	 * @param $fields_or_data
+	 * @param array $curl_options
+	 * @return bool|string
+	 * @throws Exception
+	 */
+	public static function post(string $url, $fields_or_data, $curl_options = []) {
 
 
 		$curl_handle = curl_init($url);
 		$curl_handle = curl_init($url);
 
 
@@ -38,7 +45,12 @@ class HTTP {
 		header("Pragma: public");
 		header("Pragma: public");
 	}
 	}
 
 
-	public static function getDateFromFields($prefix = "") {
+	/**
+	 * @param string $prefix
+	 * @return string
+	 * @throws Exception
+	 */
+	public static function getDateFromFields(string $prefix = ""): string {
 		$date = false;
 		$date = false;
 
 
 		if(empty($prefix)) {
 		if(empty($prefix)) {
@@ -66,7 +78,12 @@ class HTTP {
 		return $date;
 		return $date;
 	}
 	}
 
 
-	public static function getDateTimeFromFields($prefix = "") {
+	/**
+	 * @param string $prefix
+	 * @return bool|string
+	 * @throws Exception
+	 */
+	public static function getDateTimeFromFields(string $prefix = "") {
 		$date = http::getDateFromFields($prefix);
 		$date = http::getDateFromFields($prefix);
 		if($date === false) return false;
 		if($date === false) return false;
 
 
@@ -96,9 +113,17 @@ class HTTP {
 		return "$date $hour:$minute:$second";
 		return "$date $hour:$minute:$second";
 	}
 	}
 
 
-	public static function value($key, $validation = "none", $request_type = "request") {
+	/**
+	 * @param string $key
+	 * @param string $validation
+	 * @param string $request_type
+	 * @return mixed
+	 * @throws Exception
+	 */
+	public static function value(string $key, string $validation = "none", string $request_type = "request") {
 
 
 		$request_type = strtolower($request_type);
 		$request_type = strtolower($request_type);
+		$array = [];
 
 
 		switch($request_type) {
 		switch($request_type) {
 
 
@@ -182,16 +207,16 @@ class HTTP {
 
 
 	public static function getUploadErrorString($error, $name = "file") {
 	public static function getUploadErrorString($error, $name = "file") {
 		switch($error) {
 		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.";
+			case UPLOAD_ERR_OK: return sprintf(__("The %s uploaded successfully."), $name);
+			case UPLOAD_ERR_FORM_SIZE:
+			case UPLOAD_ERR_INI_SIZE: return sprintf(__("The %s uploaded was too large."), $name);
+			case UPLOAD_ERR_PARTIAL: return sprintf(__("The %s uploaded was only partially uploaded."), $name);
+			case UPLOAD_ERR_NO_FILE: return sprintf(__("No %s was uploaded."), $name);
+			case UPLOAD_ERR_NO_TMP_DIR: return sprintf(__("The %s cannot be uploaded as the temporary folder is missing."), $name);
+			case UPLOAD_ERR_CANT_WRITE: return sprintf(__("The %s cannot be written to disk."), $name);
+			case UPLOAD_ERR_EXTENSION: return sprintf(__("The %s uploaded was blocked by an extension."), $name);
 		}
 		}
-		return "Unknown error.";
+		return __("Unknown error.");
 	}
 	}
 
 
 	public static function setStatusCode($code) {
 	public static function setStatusCode($code) {
@@ -209,36 +234,22 @@ class HTTP {
 		header("HTTP/1.1 $string");
 		header("HTTP/1.1 $string");
 	}
 	}
 
 
-	public static function validateUploadedFile($file) {
+	/**
+	 * @param array $file
+	 * @return bool
+	 * @throws Exception
+	 */
+	public static function validateUploadedFile(array $file) {
 		$file = (object) $file;
 		$file = (object) $file;
 		if($file->error > 0) {
 		if($file->error > 0) {
 			switch($file->error) {
 			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;
+				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.");
+			throw new Exception(__("The uploaded file could not be stored. Please try again later."));
 		}
 		}
 		return true;
 		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);
-	}
-
-
 }
 }
 
 
-?>

+ 8 - 9
engine/image.php

@@ -7,19 +7,18 @@ class Image {
 	public static function isJPEG($path) {
 	public static function isJPEG($path) {
 		$size = @getimagesize($path);
 		$size = @getimagesize($path);
 		if(!$size) return false;
 		if(!$size) return false;
-		list($width, $height, $type) = $size;
+		list(, , $type) = $size;
 		if($type != IMAGETYPE_JPEG) return false;
 		if($type != IMAGETYPE_JPEG) return false;
 		return true;
 		return true;
 	}
 	}
 
 
-	public static function normalise($path, $size = 1920) {
+	public static function normalise($path, $max_width = 1920) {
 
 
 		$size = getimagesize($path);
 		$size = getimagesize($path);
 
 
-		list($width, $height, $type) = $size;
+		list($width, $height) = $size;
 
 
 		$exif = exif_read_data($path);
 		$exif = exif_read_data($path);
-		$orientation = 0;
 		$rotate_angle = 0;
 		$rotate_angle = 0;
 		$is_flipped = false;
 		$is_flipped = false;
 		if($exif !== false) {
 		if($exif !== false) {
@@ -33,13 +32,13 @@ class Image {
 		$original_image = imagecreatefromjpeg($path);
 		$original_image = imagecreatefromjpeg($path);
 
 
 		if($width > $height) {
 		if($width > $height) {
-			if($width > 1920) {
-				$width = 1920;
+			if($width > $max_width) {
+				$width = $max_width;
 			}
 			}
 		}
 		}
 		else {
 		else {
-			if($height > 1920) {
-				$ratio = $height / 1920;
+			if($height > $max_width) {
+				$ratio = $height / $max_width;
 				$width = floor($width / $ratio);
 				$width = floor($width / $ratio);
 			}
 			}
 		}
 		}
@@ -67,4 +66,4 @@ class Image {
 
 
 	}
 	}
 
 
-}
+}

+ 62 - 0
engine/invoice.php

@@ -0,0 +1,62 @@
+<?php
+
+/**
+ * @property InvoiceLineItem[] $lineItems
+ */
+
+class Invoice {
+
+    private $lineItems = [];
+    private $taxRate = 0.2;
+    private $reference = "";
+
+    public function addLineItem(InvoiceLineItem $item) {
+        $this->lineItems[] = $item;
+    }
+
+    public function addLineItems(array $items) {
+        foreach($items as $item) {
+            $this->addLineItem($item);
+        }
+    }
+
+    /**
+     * @return InvoiceLineItem[]
+     */
+    public function getLineItems(): array {
+        return $this->lineItems;
+    }
+
+    public function getTotal() {
+        $total = 0;
+        foreach($this->lineItems as $item) {
+            $total += $item->getTotal();
+        }
+        return $total;
+    }
+
+    public function getTaxRate(): float {
+        return $this->taxRate;
+    }
+
+    public function setTaxRate(float $tax_rate): void {
+        $this->taxRate = $tax_rate;
+    }
+
+    public function getTax() {
+        return round($this->getTotal() * $this->taxRate);
+    }
+
+    public function getTotalIncTax() {
+        return $this->getTotal() + $this->getTax();
+    }
+
+    public function setReference(string $reference): void {
+        $this->reference = $reference;
+    }
+
+    public function getReference(): string {
+        return $this->reference;
+    }
+
+}

+ 74 - 0
engine/invoice_line_item.php

@@ -0,0 +1,74 @@
+<?php
+
+/**
+ * @property string $name
+ * @property int $quantity
+ * @property float $price
+ */
+
+class InvoiceLineItem {
+
+    private $name = "Untitled Item";
+    private $quantity = 0;
+    private $price = 0;
+
+    // Static methods
+
+    // Object methods
+    public function __construct(string $name) {
+        $this->name = $name;
+    }
+
+    public function getName(): string {
+        return $this->name;
+    }
+
+    public function setName(string $name): void {
+        $this->name = $name;
+    }
+
+    public function incrementQuantity(): void {
+        ++$this->quantity;
+    }
+
+    public function getQuantity(): int {
+        return $this->quantity;
+    }
+
+    public function setQuantity(int $quantity): void {
+        $this->quantity = $quantity;
+    }
+
+    public function getDisplayQuantity(): string {
+        if($this->quantity == 0) return "-";
+        return $this->quantity;
+    }
+
+    public function addPrice(float $price): void {
+        $this->price += $price;
+    }
+
+    public function getPrice(): float {
+        return $this->price;
+    }
+
+    public function setPrice(float $price): void {
+        $this->price = $price;
+    }
+
+    public function getDisplayPrice(): string {
+        if($this->quantity == 0) return "-";
+        return "£" . number_format($this->getPrice(), 2);
+    }
+
+    public function getTotal(): float {
+        if($this->quantity == 0) return $this->price;
+        return $this->quantity * $this->price;
+    }
+
+    public function getDisplayTotal(): string {
+        return "£" . number_format($this->getTotal(), 2);
+    }
+
+
+}

+ 0 - 2
engine/json.php

@@ -41,5 +41,3 @@ class JSON {
 	}
 	}
 
 
 }
 }
-
-?>

+ 135 - 5
engine/location.php

@@ -1,5 +1,36 @@
 <?php
 <?php
 
 
+/**
+ * @property int $id
+ * @property int $customer_id
+ * @property string $name
+ * @property string $legal_entity_name
+ * @property string $address_1
+ * @property string $address_2
+ * @property string $city
+ * @property string $county
+ * @property string $postal_code
+ * @property string $state
+ * @property string $country
+ * @property string $email
+ * @property string $phone
+ * @property string $opening_hours
+ * @property string $shop_left
+ * @property string $shop_right
+ * @property string $brand
+ * @property string $region
+ * @property string $region_name
+ * @property string $internal_id
+ * @property string $area_manager
+ * @property string $area_manager_name
+ * @property string $area_manager_email
+ * @property string $operations_manager_name
+ * @property bool $closed
+ * @property double $latitude
+ * @property double $longitude
+ * @property string $dts_verified
+ */
+
 class Location extends Model {
 class Location extends Model {
 
 
 	protected static $table = "location";
 	protected static $table = "location";
@@ -7,7 +38,13 @@ class Location extends Model {
 	protected static $fillable_fields = ["customer_id", "name", "legal_entity_name", "address_1", "address_2", "city", "county", "postal_code", "state", "country", "email", "phone", "opening_hours", "shop_left", "shop_right", "brand", "region", "region_name", "internal_id", "area_manager", "area_manager_name", "area_manager_email", "operations_manager_name", "closed", "latitude", "longitude", "dts_verified"];
 	protected static $fillable_fields = ["customer_id", "name", "legal_entity_name", "address_1", "address_2", "city", "county", "postal_code", "state", "country", "email", "phone", "opening_hours", "shop_left", "shop_right", "brand", "region", "region_name", "internal_id", "area_manager", "area_manager_name", "area_manager_email", "operations_manager_name", "closed", "latitude", "longitude", "dts_verified"];
 
 
 	// Object methods
 	// Object methods
-	public function assignVenueTypes($types) {
+
+	/**
+	 * @param array $types
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function assignVenueTypes(array $types): bool {
 		$links = LocationVenueType::query(["location_id" => $this->id]);
 		$links = LocationVenueType::query(["location_id" => $this->id]);
 		foreach($links as $link) {
 		foreach($links as $link) {
 			$link->delete();
 			$link->delete();
@@ -23,14 +60,22 @@ class Location extends Model {
 		return true;
 		return true;
 	}
 	}
 
 
-	public function getVenueTypes() {
+	/**
+	 * @return VenueType[]
+	 * @throws Exception
+	 */
+	public function getVenueTypes(): array {
 		$links = LocationVenueType::query(["location_id" => $this->id]);
 		$links = LocationVenueType::query(["location_id" => $this->id]);
 		$ids = array_column($links, "venue_type_id");
 		$ids = array_column($links, "venue_type_id");
 
 
 		return VenueType::query(["id" => $ids]);
 		return VenueType::query(["id" => $ids]);
 	}
 	}
 
 
-	public function getCustomer() {
+	/**
+	 * @return Customer|null
+	 * @throws Exception
+	 */
+	public function getCustomer(): ?Customer {
 		return Customer::get($this->customer_id);
 		return Customer::get($this->customer_id);
 	}
 	}
 
 
@@ -57,6 +102,10 @@ class Location extends Model {
 		];
 		];
 	}
 	}
 
 
+	/**
+	 * @return LocationFile[]
+	 * @throws Exception
+	 */
 	public function getPhotos() {
 	public function getPhotos() {
 		return LocationFile::query([
 		return LocationFile::query([
 			"location_id" => $this->id,
 			"location_id" => $this->id,
@@ -64,6 +113,87 @@ class Location extends Model {
 		]);
 		]);
 	}
 	}
 
 
-}
+	/**
+	 * @return Test[]
+	 * @throws Exception
+	 */
+	public function getTests() {
+		return Test::query([
+			"location_id" => $this->id,
+			"status" => (new Constraint("MORE_THAN_OR_EQUAL"))->setValues(Test::STATUS_UNASSIGNED),
+		], [
+			"sort" => "dts_start",
+			"order" => "desc",
+		]);
+	}
+
+	/**
+	 * @return Test[]
+	 * @throws Exception
+	 */
+	public function getCompletedTests() {
+		return Test::query([
+			"location_id" => $this->id,
+			"status" => Test::STATUS_COMPLETED,
+		], [
+			"sort" => "dts_start",
+			"order" => "desc",
+		]);
+	}
+
+	/**
+	 * @param object $old_data
+	 * @param array $modified_fields
+	 * @return bool
+	 * @throws Exception
+	 */
+    public function logUpdate(object $old_data, array $modified_fields): bool {
+
+		if(empty($modified_fields)) return true;
+
+        $entry = new LocationUpdateLogEntry;
+        $entry->location_id = $this->id;
+        $entry->user_id = Core::$user->id;
+        $entry->modifications_json = json_encode($this->getModifiedArray($old_data, $modified_fields));
+        $entry->dts = Util::getDateTime();
+        return $entry->commit();
+	}
 
 
-?>
+	/**
+	 * @return LocationUpdateLogEntry[]
+	 * @throws Exception
+	 */
+	public function getUpdateLogEntries() {
+
+		return LocationUpdateLogEntry::query([
+			"location_id" => $this->id,
+		], [
+			"sort" => "dts",
+			"order" => "desc",
+		]);
+
+	}
+
+	/**
+	 * @param object $old_data
+	 * @param array $modified_fields
+	 * @return array
+	 */
+    private function getModifiedArray(object $old_data, array $modified_fields): array {
+
+		$new_data = $this->getModelData();
+
+        $modified = [];
+
+        foreach($modified_fields as $field) {
+            $modified[] = [
+				"field" => $field,
+                "before" => $old_data->$field,
+                "after" => $new_data->$field,
+            ];
+        }
+
+        return $modified;
+    }
+
+}

+ 16 - 4
engine/location_file.php

@@ -1,5 +1,14 @@
 <?php
 <?php
 
 
+/**
+ * Class LocationFile
+ *
+ * @property int $id
+ * @property int $location_id
+ * @property int $type
+ * @property string $dts_uploaded
+ */
+
 class LocationFile extends Model {
 class LocationFile extends Model {
 
 
 	protected static $table = "location_file";
 	protected static $table = "location_file";
@@ -9,9 +18,12 @@ class LocationFile extends Model {
 	const TYPE_PHOTO = 1;
 	const TYPE_PHOTO = 1;
 
 
 	// Object methods
 	// Object methods
-	public function getLocation() {
-		return Location::get($location_id);
+
+	/**
+	 * @return Location|null
+	 * @throws Exception
+	 */
+	public function getLocation(): ?Location {
+		return Location::get($this->location_id);
 	}
 	}
 }
 }
-
-?>

+ 42 - 0
engine/location_update_log_entry.php

@@ -0,0 +1,42 @@
+<?php
+
+/**
+ * @property int $id
+ * @property int $location_id
+ * @property int $user_id
+ * @property string $modifications_json
+ * @property string $dts
+ */
+
+class LocationUpdateLogEntry extends Model {
+
+	protected static $table = "location_update_log_entry";
+	protected static $id_field = "id";
+	protected static $fillable_fields = ["location_id", "user_id", "modifications_json", "dts"];
+
+	// Object methods
+
+	/**
+	 * @return Location
+	 * @throws Exception
+	 */
+	public function getLocation(): ?Location {
+		return Location::get($this->location_id);
+	}
+
+	/**
+	 * @return User
+	 * @throws Exception
+	 */
+	public function getUser(): ?User {
+		return User::get($this->user_id);
+	}
+
+	/**
+	 * @return array
+	 */
+	public function getModifications(): array {
+		return json_decode($this->modifications_json) ?: [];
+	}
+
+}

+ 7 - 0
engine/location_venue_type.php

@@ -1,5 +1,12 @@
 <?php
 <?php
 
 
+/**
+ * Class LocationVenueType
+ *
+ * @property int $location_id
+ * @property int $venue_type_id
+ */
+
 class LocationVenueType extends Model {
 class LocationVenueType extends Model {
 
 
 	protected static $table = "location_venue_type";
 	protected static $table = "location_venue_type";

+ 133 - 30
engine/model.php

@@ -1,4 +1,4 @@
-<?php
+<?php /** @noinspection PhpUnused */
 
 
 abstract class Model {
 abstract class Model {
 
 
@@ -17,7 +17,12 @@ abstract class Model {
 	protected $in_db;
 	protected $in_db;
 
 
 	// Magic methods
 	// Magic methods
-	public function __get($name) {
+
+	/**
+	 * @param string $name
+	 * @return mixed
+	 */
+	public function __get(string $name) {
 
 
 		if(in_array($name, static::$object_fields)) {
 		if(in_array($name, static::$object_fields)) {
 			return $this->$name ?? null;
 			return $this->$name ?? null;
@@ -30,7 +35,12 @@ abstract class Model {
 		return isset($this->model_data->$name) ? $this->model_data->$name : null;
 		return isset($this->model_data->$name) ? $this->model_data->$name : null;
 	}
 	}
 
 
-	public function __set($name, $value) {
+	/**
+	 * @param string $name
+	 * @param string $value
+	 * @throws Exception
+	 */
+	public function __set(string $name, string $value): void {
 
 
 		if(in_array($name, static::$object_fields)) {
 		if(in_array($name, static::$object_fields)) {
 			$this->$name = $value;
 			$this->$name = $value;
@@ -68,14 +78,23 @@ abstract class Model {
 		}
 		}
 	}
 	}
 
 
-	public function __isset($name) {
+	/**
+	 * @param string $name
+	 * @return bool
+	 */
+	public function __isset(string $name) {
 		$value = $this->$name;
 		$value = $this->$name;
 		return !is_null($value);
 		return !is_null($value);
 	}
 	}
 
 
 	// Static method
 	// Static method
 
 
-	public static function get($id) {
+	/**
+	 * @param $id
+	 * @return static|null
+	 * @throws Exception
+	 */
+	public static function get($id): ?object {
 
 
 		$table = static::$table;
 		$table = static::$table;
 		$is_compound_key = is_array(static::$id_field);
 		$is_compound_key = is_array(static::$id_field);
@@ -86,13 +105,13 @@ abstract class Model {
 		}
 		}
 
 
 		$id_field = static::$id_field;
 		$id_field = static::$id_field;
-		$class = get_called_class();
+		$nvp = [];
 
 
-		if($is_compound_key) { // Compound key
+		if($is_compound_key && is_array($id_field)) { // Compound key
 			$args = func_get_args();
 			$args = func_get_args();
 			$fields = $id_field;
 			$fields = $id_field;
 
 
-			if(count($args) != count($fields)) return false;
+			if(count($args) != count($fields)) return null;
 
 
 			foreach($fields as $index => $field) {
 			foreach($fields as $index => $field) {
 				$nvp[$field] = $args[$index];
 				$nvp[$field] = $args[$index];
@@ -106,10 +125,10 @@ abstract class Model {
 
 
 		$sql = "SELECT * FROM `$table` WHERE $where";
 		$sql = "SELECT * FROM `$table` WHERE $where";
 		$result = db::query($sql);
 		$result = db::query($sql);
-		$object = db::object_or_false($result);
+		$object = db::object_or_null($result);
 
 
 		if($object) {
 		if($object) {
-			$object = new $class($object);
+			$object = new static($object);
 			if(!$is_compound_key) {
 			if(!$is_compound_key) {
 				static::$repositories[$table][$id] = $object;
 				static::$repositories[$table][$id] = $object;
 			}
 			}
@@ -118,7 +137,13 @@ abstract class Model {
 		return $object;
 		return $object;
 	}
 	}
 
 
-	public static function getOrException($id, $exception_message = false) {
+	/**
+	 * @param int $id
+	 * @param bool $exception_message
+	 * @return static|null
+	 * @throws Exception
+	 */
+	public static function getOrException(int $id, bool $exception_message = false): ?object {
 
 
 		if(!$exception_message) $exception_message = get_called_class() . " not found.";
 		if(!$exception_message) $exception_message = get_called_class() . " not found.";
 
 
@@ -127,7 +152,11 @@ abstract class Model {
 		return $object;
 		return $object;
 	}
 	}
 
 
-	public static function getAll() {
+	/**
+	 * @return static[]
+	 * @throws Exception
+	 */
+	public static function getAll(): array {
 		$objects = [];
 		$objects = [];
 
 
 		$table = static::$table;
 		$table = static::$table;
@@ -141,7 +170,12 @@ abstract class Model {
 		return $objects;
 		return $objects;
 	}
 	}
 
 
-	public static function load(...$id_sets) {
+	/**
+	 * @param array ...$id_sets
+	 * @return static[]
+	 * @throws Exception
+	 */
+	public static function load(...$id_sets): array {
 
 
 		$table = static::$table;
 		$table = static::$table;
 
 
@@ -162,7 +196,11 @@ abstract class Model {
 		return $items;
 		return $items;
 	}
 	}
 
 
-	public static function loadAll() {
+	/**
+	 * @return static[]
+	 * @throws Exception
+	 */
+	public static function loadAll(): array {
 		$table = static::$table;
 		$table = static::$table;
 
 
 		$items = static::query([], ["id_as_key" => true]);
 		$items = static::query([], ["id_as_key" => true]);
@@ -173,7 +211,12 @@ abstract class Model {
 		return $items;
 		return $items;
 	}
 	}
 
 
-	public static function deleteMultiple($nvp = []) {
+	/**
+	 * @param array $nvp
+	 * @return int
+	 * @throws Exception
+	 */
+	public static function deleteMultiple($nvp = []): int {
 		$table = static::$table;
 		$table = static::$table;
 
 
 		$vs = "1";
 		$vs = "1";
@@ -182,8 +225,6 @@ abstract class Model {
 			$vs = db::get_where_string($nvp);
 			$vs = db::get_where_string($nvp);
 		}
 		}
 
 
-		$objects = [];
-
 		$sql = "DELETE FROM `$table` WHERE $vs";
 		$sql = "DELETE FROM `$table` WHERE $vs";
 		$result = db::query($sql);
 		$result = db::query($sql);
 		if(!$result) return false;
 		if(!$result) return false;
@@ -191,7 +232,13 @@ abstract class Model {
 		return db::affected_rows();
 		return db::affected_rows();
 	}
 	}
 
 
-	public static function query($nvp = [], $options = []) {
+	/**
+	 * @param string|array $nvp
+	 * @param array $options
+	 * @return static[]
+	 * @throws Exception
+	 */
+	public static function query($nvp = [], $options = []): array {
 		if(is_array($nvp)) {
 		if(is_array($nvp)) {
 			return static::findByNVP($nvp, $options);
 			return static::findByNVP($nvp, $options);
 		}
 		}
@@ -200,17 +247,33 @@ abstract class Model {
 		}
 		}
 	}
 	}
 
 
-	public static function queryFuzzy($nvp = [], $options = []) {
+	/**
+	 * @param array $nvp
+	 * @param array $options
+	 * @return static[]
+	 * @throws Exception
+	 */
+	public static function queryFuzzy($nvp = [], $options = []): array {
 		$options["fuzzy"] = true;
 		$options["fuzzy"] = true;
 		return static::findByNVP($nvp, $options);
 		return static::findByNVP($nvp, $options);
 	}
 	}
 
 
-	public static function queryOne($nvp = [], $options = []) {
+	/**
+	 * @param array $nvp
+	 * @param array $options
+	 * @return static|null
+	 * @throws Exception
+	 */
+	public static function queryOne($nvp = [], $options = []): ?object {
 		$rows = static::findByNVP($nvp, $options);
 		$rows = static::findByNVP($nvp, $options);
-		return $rows ? $rows[0] : false;
+		return $rows ? $rows[0] : null;
 	}
 	}
 
 
-	private static function getRemappedNVP($nvp = []) {
+	/**
+	 * @param array $nvp
+	 * @return array
+	 */
+	private static function getRemappedNVP($nvp = []): array {
 		$mapped_nvp = [];
 		$mapped_nvp = [];
 		foreach($nvp as $field => $value) {
 		foreach($nvp as $field => $value) {
 			$field = static::$field_map[$field] ?? $field;
 			$field = static::$field_map[$field] ?? $field;
@@ -219,7 +282,12 @@ abstract class Model {
 		return $mapped_nvp;
 		return $mapped_nvp;
 	}
 	}
 
 
-	public static function count($nvp = []) {
+	/**
+	 * @param array $nvp
+	 * @return int
+	 * @throws Exception
+	 */
+	public static function count($nvp = []): int {
 		$table = static::$table;
 		$table = static::$table;
 
 
 		$vs = "1";
 		$vs = "1";
@@ -228,8 +296,6 @@ abstract class Model {
 			$vs = db::get_where_string($nvp);
 			$vs = db::get_where_string($nvp);
 		}
 		}
 
 
-		$objects = [];
-
 		$sql = "SELECT COUNT(*) AS `count` FROM `$table` WHERE $vs";
 		$sql = "SELECT COUNT(*) AS `count` FROM `$table` WHERE $vs";
 		$result = db::query($sql);
 		$result = db::query($sql);
 		$row = db::fetch_object($result);
 		$row = db::fetch_object($result);
@@ -237,7 +303,13 @@ abstract class Model {
 		return $row->count;
 		return $row->count;
 	}
 	}
 
 
-	public static function findByNVP($nvp, $options = []) {
+	/**
+	 * @param array $nvp
+	 * @param array $options
+	 * @return static[]
+	 * @throws Exception
+	 */
+	public static function findByNVP(array $nvp, array $options = []): array {
 
 
 		if(empty($nvp)) {
 		if(empty($nvp)) {
 			$vs = "1";
 			$vs = "1";
@@ -250,7 +322,13 @@ abstract class Model {
 		return static::findByValueString($vs, $options);
 		return static::findByValueString($vs, $options);
 	}
 	}
 
 
-	private static function findByValueString($vs, $options = []) {
+	/**
+	 * @param string $vs
+	 * @param array $options
+	 * @return static[]
+	 * @throws Exception
+	 */
+	private static function findByValueString(string $vs, array $options = []): array {
 		$table = static::$table;
 		$table = static::$table;
 
 
 		$options = (object) $options;
 		$options = (object) $options;
@@ -322,7 +400,7 @@ abstract class Model {
 		$id = $this->getID();
 		$id = $this->getID();
 
 
 		$nvp = [];
 		$nvp = [];
-		if(is_array($id)) {
+		if(is_array($id) && is_array($id_field)) {
 			$nvp = array_combine($id_field, $id);
 			$nvp = array_combine($id_field, $id);
 		}
 		}
 		else {
 		else {
@@ -334,6 +412,11 @@ abstract class Model {
 		return $where;
 		return $where;
 	}
 	}
 
 
+	/**
+	 * @param bool $testing
+	 * @return bool
+	 * @throws Exception
+	 */
 	public final function commit($testing = false) {
 	public final function commit($testing = false) {
 
 
 		$this->preCommit();
 		$this->preCommit();
@@ -394,19 +477,36 @@ abstract class Model {
 			$this->in_db = true;
 			$this->in_db = true;
 		}
 		}
 
 
+		if($result) {
+			$this->modified_fields = [];
+		}
+
 		return !empty($result);
 		return !empty($result);
 	}
 	}
 
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function testCommit() {
 	public function testCommit() {
 		return $this->commit(true);
 		return $this->commit(true);
 	}
 	}
 
 
+	/**
+	 * @param bool $testing
+	 * @return bool
+	 * @throws Exception
+	 */
 	public final function commitOrException($testing = false) {
 	public final function commitOrException($testing = false) {
 		$success = $this->commit($testing);
 		$success = $this->commit($testing);
 		if(!$success) throw new Exception("Database error.");
 		if(!$success) throw new Exception("Database error.");
 		return $success;
 		return $success;
 	}
 	}
 
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function delete() {
 	public function delete() {
 		$table = static::$table;
 		$table = static::$table;
 
 
@@ -419,9 +519,13 @@ abstract class Model {
 		$sql = "DELETE FROM `$table` WHERE $where";
 		$sql = "DELETE FROM `$table` WHERE $where";
 		$result = db::query($sql);
 		$result = db::query($sql);
 
 
-		return empty($result) ? false : db::affected_rows() ? true : false;
+		return empty($result) ? false : (db::affected_rows() ? true : false);
 	}
 	}
 
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public final function deleteOrException() {
 	public final function deleteOrException() {
 		$success = $this->delete();
 		$success = $this->delete();
 		if(!$success) throw new Exception("Database error.");
 		if(!$success) throw new Exception("Database error.");
@@ -451,4 +555,3 @@ abstract class Model {
 
 
 }
 }
 
 
-?>

+ 22 - 6
engine/practice_test.php

@@ -2,23 +2,39 @@
 
 
 class PracticeTest extends Test {
 class PracticeTest extends Test {
 
 
-	protected $values = [];
+	private $values = [];
+	private $template_id = null;
 
 
 	// Constants
 	// Constants
-	public function getValues($as_assoc_array = false) {
+
+	/**
+	 * @param bool $as_assoc_array
+	 * @return array
+	 */
+	public function getValues(bool $as_assoc_array = false): array {
 		return $this->values;
 		return $this->values;
 	}
 	}
 
 
-	public function setValue($key, $value) {
+	/**
+	 * @param string $key
+	 * @param string $value
+	 * @return bool
+	 */
+	public function setValue(string $key, string $value): bool {
 		$this->values[$key] = $value;
 		$this->values[$key] = $value;
 		return true;
 		return true;
 	}
 	}
 
 
-	public function getDirectory() {
+	/**
+	 * @return string
+	 */
+	public function getDirectory(): string {
 		$directory = ROOT_DIR . "/files/users/$this->tester_id/practice_tests/$this->template_id";
 		$directory = ROOT_DIR . "/files/users/$this->tester_id/practice_tests/$this->template_id";
 		if(!file_exists($directory)) mkdir($directory, 0777, true);
 		if(!file_exists($directory)) mkdir($directory, 0777, true);
 		return $directory;
 		return $directory;
 	}
 	}
-}
 
 
-?>
+	public function setTemplateId(int $id) {
+		$this->template_id = $id;
+	}
+}

+ 376 - 34
engine/project.php

@@ -1,34 +1,190 @@
-<?php
+<?php /** @noinspection PhpIncludeInspection */
+
+/**
+ * @property int $id
+ * @property int $customer_id
+ * @property int $template_id
+ * @property string $name
+ * @property int $test_count
+ * @property int $min_age
+ * @property int $max_age
+ * @property float $default_customer_fee
+ * @property float $default_tester_fee
+ * @property int $time_of_day
+ * @property bool $tester_can_claim
+ * @property string $template_overrides_json
+ * @property string $dts_start
+ * @property string $dts_deadline
+ * @property string $dts_created
+ * @property string $dts_updated
+ * @property string $dts_report
+ * @property string $dts_finished
+ * @property int $user_id_finished
+ */
 
 
 class Project extends Model {
 class Project extends Model {
 
 
+	const TOD_ANYTIME = "A";
+	const TOD_DAYTIME = "D";
+	const TOD_NIGHTTIME = "N";
+
 	protected static $table = "project";
 	protected static $table = "project";
 	protected static $id_field = "id";
 	protected static $id_field = "id";
 	protected static $fillable_fields = ["customer_id", "template_id", "name", "test_count", "min_age", "max_age", "default_customer_fee", "default_tester_fee", "time_of_day", "tester_can_claim", "template_overrides_json", "dts_start", "dts_deadline", "dts_created", "dts_updated", "dts_report", "dts_finished", "user_id_finished"];
 	protected static $fillable_fields = ["customer_id", "template_id", "name", "test_count", "min_age", "max_age", "default_customer_fee", "default_tester_fee", "time_of_day", "tester_can_claim", "template_overrides_json", "dts_start", "dts_deadline", "dts_created", "dts_updated", "dts_report", "dts_finished", "user_id_finished"];
 
 
-	protected static $field_map = [
-	];
+	/**
+	 * @var Test[] $tests
+	 */
+	protected $tests = null;
+
+	// Static methods
+
+	/**
+	 * @param string $processing_file
+	 * @param array $projects
+	 * @throws Exception
+	 */
+	public static function exportCSV(string $processing_file, /** @noinspection PhpUnusedParameterInspection */ $projects = []) {
+
+		// Get processing file
+		$processing_file_path = ROOT_DIR . "/export_processing/{$processing_file}";
+		if(!file_exists($processing_file_path)) throw new Exception("Processing file not found.");
+
+		// Output
+		HTTP::setDownloadHeaders("export.csv");
+
+		$handle = fopen("php://output", "w");
+		require $processing_file_path;
+		fclose($handle);
+	}
+
+	/**
+	 * @return string[]
+	 * @throws Exception
+	 */
+	public static function getReportMonths(): array {
+
+		$current_report_month = new DateTime("2018-01-01", new DateTimeZone("UTC"));
+
+		$month_interval = new DateInterval("P1M");
+
+		$report_months = [];
+
+		do {
+			$key = $current_report_month->format("Y-m");
+			$report_months[$key] = $current_report_month->format("M Y");
+			$current_report_month->add($month_interval);
+			$time = $current_report_month->format("U");
+			if($time > time()) break;
+		} while(true);
+
+		return $report_months;
+	}
 
 
 	// Object methods
 	// Object methods
-	public function getCustomer() {
+
+	/**
+	 * @return Customer
+	 * @throws Exception
+	 */
+	public function getCustomer(): ?Customer {
 		return Customer::get($this->customer_id);
 		return Customer::get($this->customer_id);
 	}
 	}
 
 
-	public function getTests() {
+	/**
+	 * @return Test[]
+	 * @throws Exception
+	 */
+	public function getTests(): array {
+
+		if(!is_null($this->tests)) return $this->tests;
 
 
 		$nvp = [];
 		$nvp = [];
 		$nvp["project_id"] = $this->id;
 		$nvp["project_id"] = $this->id;
 		$nvp["status"] = (new Constraint("MORE_THAN"))->setValues(Test::STATUS_CANCELLED);
 		$nvp["status"] = (new Constraint("MORE_THAN"))->setValues(Test::STATUS_CANCELLED);
 
 
-		return Test::query($nvp);
+		$this->tests = Test::query($nvp);
+
+		return $this->tests;
+	}
+
+	/**
+	 * @return int
+	 * @throws Exception
+	 */
+	public function getTestCount(): int {
+		if(is_null($this->tests)) $this->getTests();
+		return count($this->tests);
 	}
 	}
 
 
-	public function getLocations() {
+	/**
+	 * @return int
+	 * @throws Exception
+	 */
+	public function getPassCount(): int {
+		$count = 0;
+		$tests = $this->getTests();
+		foreach($tests as $test) {
+			if(!$test->isPass()) continue;
+			++$count;
+		}
+		return $count;
+	}
+
+	/**
+	 * @return int
+	 * @throws Exception
+	 */
+	public function getFailCount(): int {
+		$count = 0;
+		$tests = $this->getTests();
+		foreach($tests as $test) {
+			if(!$test->isFail()) continue;
+			++$count;
+		}
+		return $count;
+	}
+
+	/**
+	 * @return int
+	 * @throws Exception
+	 */
+	public function getPendingCount(): int {
+		$count = 0;
+		$tests = $this->getTests();
+		foreach($tests as $test) {
+			if(!$test->isPending()) continue;
+			++$count;
+		}
+		return $count;
+	}
+
+	/**
+	 * @return string
+	 * @throws Exception
+	 */
+	public function getPassRate(): string {
+		$pass_count = $this->getPassCount();
+		$fail_count = $this->getFailCount();
+		$pass_fail_count = $pass_count + $fail_count;
+		if($pass_fail_count == 0) return "0%";
+
+		return (number_format($pass_count / $pass_fail_count, 4) * 100) . "%";
+	}
+
+	/**
+	 * @return Location[]
+	 * @throws Exception
+	 */
+	public function getLocations(): array {
 		$tests = $this->getTests();
 		$tests = $this->getTests();
 		return Location::query(["id" => array_column($tests, "location_id")]);
 		return Location::query(["id" => array_column($tests, "location_id")]);
 	}
 	}
 
 
-	public function getDisplayAgeRange() {
+	/**
+	 * @return string
+	 */
+	public function getDisplayAgeRange(): string {
 
 
 		if($this->min_age && $this->max_age) {
 		if($this->min_age && $this->max_age) {
 			return $this->min_age . " to " . $this->max_age;
 			return $this->min_age . " to " . $this->max_age;
@@ -44,7 +200,26 @@ class Project extends Model {
 
 
 	}
 	}
 
 
-	public function getCompletedPercentage() {
+	/**
+	 * @return string
+	 */
+	public function getNameHtml(): string {
+
+		if($this->isAnytime()) {
+			return htmlspecialchars($this->name);
+		}
+
+		$icon = $this->getTimeOfDayIcon();
+		$time_of_day = $this->getTimeOfDayText();
+
+		return htmlspecialchars($this->name) . " <i class=\"fa fa-fw fa-{$icon}\" data-toggle=\"tooltip\" title=\"{$time_of_day}\"></i>";
+	}
+
+	/**
+	 * @return float
+	 * @throws Exception
+	 */
+	public function getCompletedPercentage(): float {
 
 
 		$test_count = $this->test_count;
 		$test_count = $this->test_count;
 
 
@@ -58,64 +233,111 @@ class Project extends Model {
 
 
 	}
 	}
 
 
-	public function getTemplate() {
+	/**
+	 * @return Template
+	 * @throws Exception
+	 */
+	public function getTemplate(): ?Template {
 		return Template::get($this->template_id);
 		return Template::get($this->template_id);
 	}
 	}
 
 
-	public function getTemplateOverrides() {
+	/**
+	 * @return array
+	 */
+	public function getTemplateOverrides(): array {
 		$overrides = json_decode($this->template_overrides_json) ?: [];
 		$overrides = json_decode($this->template_overrides_json) ?: [];
 		return $overrides;
 		return $overrides;
 	}
 	}
 
 
-	public function getTimeOfDayText() {
+	/**
+	 * @return string
+	 */
+	public function getTimeOfDayText(): string {
 		switch($this->time_of_day) {
 		switch($this->time_of_day) {
-			case "A": return "Any";
-			case "D": return "Day";
-			case "N": return "Night";
+			default:
+			case self::TOD_ANYTIME: return "Any";
+			case self::TOD_DAYTIME: return "Day";
+			case self::TOD_NIGHTTIME: return "Night";
 		}
 		}
 	}
 	}
 
 
-	public function getTimeOfDayIcon() {
+	/**
+	 * @return string
+	 */
+	public function getTimeOfDayIcon(): string {
 		switch($this->time_of_day) {
 		switch($this->time_of_day) {
-			case "A": return "adjust";
-			case "D": return "sun";
-			case "N": return "moon";
+			default:
+			case self::TOD_ANYTIME: return "adjust";
+			case self::TOD_DAYTIME: return "sun";
+			case self::TOD_NIGHTTIME: return "moon";
 		}
 		}
 	}
 	}
 
 
-	public function getURL() {
+	/**
+	 * @return string
+	 */
+	public function getURL(): string {
 		return "/account/projects/{$this->id}";
 		return "/account/projects/{$this->id}";
 	}
 	}
 
 
-	public function getDirectory() {
+	/**
+	 * @return string
+	 */
+	public function getDirectory(): string {
 		$directory = ROOT_DIR . "/files/projects/" . $this->id;
 		$directory = ROOT_DIR . "/files/projects/" . $this->id;
 		if(!file_exists($directory)) mkdir($directory, 0777, true);
 		if(!file_exists($directory)) mkdir($directory, 0777, true);
 		return $directory;
 		return $directory;
 	}
 	}
 
 
-	public function hasInvoicePDF() {
+	/**
+	 * @return bool
+	 */
+	public function hasInvoicePDF(): bool {
 		$directory = $this->getDirectory();
 		$directory = $this->getDirectory();
 		return file_exists($directory . "/invoice.pdf");
 		return file_exists($directory . "/invoice.pdf");
 	}
 	}
 
 
-	public function isAnytime() {
-		return $this->time_of_day == "A";
+	/**
+	 * @return bool
+	 */
+	public function isAnytime(): bool {
+		return $this->time_of_day == self::TOD_ANYTIME;
 	}
 	}
 
 
-	public function isDaytime() {
-		return $this->time_of_day == "D";
+	/**
+	 * @return bool
+	 */
+	public function isDaytime(): bool {
+		return $this->time_of_day == self::TOD_DAYTIME;
 	}
 	}
 
 
-	public function isNighttime() {
-		return $this->time_of_day == "N";
+	/**
+	 * @return bool
+	 */
+	public function isNighttime(): bool {
+		return $this->time_of_day == self::TOD_NIGHTTIME;
 	}
 	}
 
 
-	public function isPastDeadline() {
+	/**
+	 * @return bool
+	 */
+	public function isPastDeadline(): bool {
 		$deadline_unix = Util::getUnixTimeFromUTC($this->dts_deadline);
 		$deadline_unix = Util::getUnixTimeFromUTC($this->dts_deadline);
 		return time() > $deadline_unix;
 		return time() > $deadline_unix;
 	}
 	}
 
 
-	public function markFinished() {
+	/**
+	 * @return bool
+	 */
+	public function isFinished(): bool {
+		return $this->dts_finished === null;
+	}
+
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function markFinished(): bool {
 
 
 		if(!Core::$user) throw new Exception("Trying to mark project as finished while not logged in.");
 		if(!Core::$user) throw new Exception("Trying to mark project as finished while not logged in.");
 		if(!Core::$user->isAdmin()) throw new Exception("Trying to mark project as finished with non-admin account.");
 		if(!Core::$user->isAdmin()) throw new Exception("Trying to mark project as finished with non-admin account.");
@@ -125,13 +347,21 @@ class Project extends Model {
 		return $this->commit();
 		return $this->commit();
 	}
 	}
 
 
-	public function markUnfinished() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function markUnfinished(): bool {
 		$this->dts_finished = null;
 		$this->dts_finished = null;
 		$this->user_id_finished = null;
 		$this->user_id_finished = null;
 		return $this->commit();
 		return $this->commit();
 	}
 	}
 
 
-	public function getDisplayReportMonth() {
+	/**
+	 * @return string
+	 * @throws Exception
+	 */
+	public function getDisplayReportMonth(): string {
 		$report_month = "-";
 		$report_month = "-";
 		if($this->dts_report) {
 		if($this->dts_report) {
 			$dt_report = new DateTime($this->dts_report . " UTC");
 			$dt_report = new DateTime($this->dts_report . " UTC");
@@ -140,7 +370,11 @@ class Project extends Model {
 		return $report_month;
 		return $report_month;
 	}
 	}
 
 
-	public function getDataTableRow() {
+	/**
+	 * @return array
+	 * @throws Exception
+	 */
+	public function getDataTableRow(): array {
 
 
 		$tests = $this->getTests();
 		$tests = $this->getTests();
 
 
@@ -151,11 +385,119 @@ class Project extends Model {
 			"testCount" => count($tests),
 			"testCount" => count($tests),
 			"timeOfDay" => $this->getTimeOfDayText(),
 			"timeOfDay" => $this->getTimeOfDayText(),
 			"unixStart" => Util::getUnixTimeFromUTC($this->dts_start),
 			"unixStart" => Util::getUnixTimeFromUTC($this->dts_start),
-			"unixEnd" => Util::getUnixTimeFromUTC($this->dts_end),
+			"unixEnd" => Util::getUnixTimeFromUTC($this->dts_deadline),
 
 
 			"reportMonth" => $this->getDisplayReportMonth(),
 			"reportMonth" => $this->getDisplayReportMonth(),
 			"unixReport" => $this->dts_report ? Util::getUnixTimeFromUTC($this->dts_report) : 0,
 			"unixReport" => $this->dts_report ? Util::getUnixTimeFromUTC($this->dts_report) : 0,
 		];
 		];
 	}
 	}
 
 
+	/**
+	 * @return string
+	 * @throws Exception
+	 */
+	public function getTestResultsUrl(): string {
+		$customer = $this->getCustomer();
+		$customer_slug = Util::slugWithId($customer->name, $customer->id);
+		$project_slug = Util::slugWithId($this->name, $this->id);
+		return "/account/test-results/{$customer_slug}/{$project_slug}";
+	}
+
+	/**
+	 * @return Invoice
+	 * @throws Exception
+	 */
+	public function getCustomerInvoice(): Invoice {
+
+		$invoice = new Invoice;
+		$invoice->setReference($this->getInvoiceReference());
+
+		$test_line_items = $this->getTestInvoiceLineItems();
+		$field_line_items = $this->getFieldInvoiceLineItems();
+
+		$invoice->addLineItems($test_line_items);
+		$invoice->addLineItems($field_line_items);
+
+		return $invoice;
+
+	}
+
+	/**
+	 * @return string
+	 * @throws Exception
+	 */
+	private function getInvoiceReference(): string {
+
+		$customer = $this->getCustomer();
+
+		return
+			"P" . str_pad($this->id, 3, "0", STR_PAD_LEFT) .
+			"/C" . str_pad($customer->id, 3, "0", STR_PAD_LEFT);
+	}
+
+	/**
+	 * @return InvoiceLineItem[]
+	 * @throws Exception
+	 */
+	private function getTestInvoiceLineItems(): array {
+
+		/**
+		 * @var InvoiceLineItem[] $items
+		 */
+
+		$template = $this->getTemplate();
+
+		$default_customer_fee = $this->default_customer_fee;
+		$tests = $this->getTests();
+
+		$items = [];
+
+		foreach($tests as $test) {
+
+			$fee = $test->customer_fee ?? $default_customer_fee;
+
+			$key = "fee_{$fee}";
+
+			$item = $items[$key] ?? null;
+
+			if(!$item) {
+				$item = new InvoiceLineItem(__("%s Testing", $template->name));
+				$item->setPrice($fee);
+			}
+
+			$item->incrementQuantity();
+
+			$items[$key] = $item;
+
+		}
+
+		return array_values($items);
+	}
+
+	/**
+	 * @return InvoiceLineItem[]
+	 * @throws Exception
+	 */
+	private function getFieldInvoiceLineItems(): array {
+
+		$template = $this->getTemplate();
+		$invoice_fields = $template->getCustomerInvoiceFields();
+
+		$tests = $this->getTests();
+
+		$items = [];
+
+		foreach($tests as $test) {
+			$values = $test->getValues(true);
+
+			foreach($invoice_fields as $field) {
+				$item = $items[$field->name] ?? (new InvoiceLineItem($field->label));
+				$item->addPrice((float) $values[$field->name] ?? 0);
+				$items[$field->name] = $item;
+			}
+		}
+
+		return $items;
+	}
+
 }
 }

+ 18 - 4
engine/project_location.php

@@ -1,5 +1,12 @@
 <?php
 <?php
 
 
+/**
+ * Class ProjectLocation
+ *
+ * @property int $project_id
+ * @property int $location_id
+ */
+
 class ProjectLocation extends Model {
 class ProjectLocation extends Model {
 
 
 	protected static $table = "project_location";
 	protected static $table = "project_location";
@@ -7,14 +14,21 @@ class ProjectLocation extends Model {
 	protected static $fillable_fields = ["project_id", "location_id"];
 	protected static $fillable_fields = ["project_id", "location_id"];
 
 
 	// Object methods
 	// Object methods
-	public function getProject() {
+
+	/**
+	 * @return Project|null
+	 * @throws Exception
+	 */
+	public function getProject(): ?Project {
 		return Project::get($this->project_id);
 		return Project::get($this->project_id);
 	}
 	}
 
 
-	public function getLocation() {
+	/**
+	 * @return Location|null
+	 * @throws Exception
+	 */
+	public function getLocation(): ?Location {
 		return Location::get($this->location_id);
 		return Location::get($this->location_id);
 	}
 	}
 
 
 }
 }
-
-?>

+ 18 - 5
engine/session.php

@@ -1,12 +1,24 @@
 <?php
 <?php
 
 
+/**
+ * Class Session
+ *
+ * @property int $id
+ * @property string $data
+ * @property string $dts_last_access
+ */
+
 class Session extends Model {
 class Session extends Model {
 
 
 	protected static $table = "session";
 	protected static $table = "session";
 	protected static $id_field = "id";
 	protected static $id_field = "id";
 	protected static $fillable_fields = ["id", "data", "dts_last_access"];
 	protected static $fillable_fields = ["id", "data", "dts_last_access"];
 
 
-	public static function start($name="", $timeout=3600) {
+	/**
+	 * @param string $name
+	 * @param int $timeout
+	 */
+	public static function start(string $name = "", int $timeout = 3600) {
 
 
 		$handler = new SiteSessionHandler();
 		$handler = new SiteSessionHandler();
 		session_set_save_handler($handler, true);
 		session_set_save_handler($handler, true);
@@ -19,12 +31,13 @@ class Session extends Model {
 		session_start();
 		session_start();
 	}
 	}
 
 
-	public static function extend($timeout) {
+	/**
+	 * @param int $timeout
+	 */
+	public static function extend(int $timeout) {
 		$id = session_id();
 		$id = session_id();
 		$name = session_name();
 		$name = session_name();
-		setcookie($name, $id, time()+$timeout, "/", "");
+		setcookie($name, $id, time() + $timeout, "/", "");
 	}
 	}
 
 
 }
 }
-
-?>

+ 22 - 3
engine/site_session_handler.php

@@ -6,11 +6,22 @@ class SiteSessionHandler implements SessionHandlerInterface {
 		return true;
 		return true;
 	}
 	}
 
 
+	/**
+	 * @param string $id
+	 * @return string
+	 * @throws Exception
+	 */
 	public function read($id) {
 	public function read($id) {
 		$session = Session::get($id);
 		$session = Session::get($id);
 		return $session ? $session->data : "";
 		return $session ? $session->data : "";
 	}
 	}
 
 
+	/**
+	 * @param string $id
+	 * @param string $data
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function write($id, $data) {
 	public function write($id, $data) {
 
 
 		$session = Session::get($id);
 		$session = Session::get($id);
@@ -28,6 +39,11 @@ class SiteSessionHandler implements SessionHandlerInterface {
 		return true;
 		return true;
 	}
 	}
 
 
+	/**
+	 * @param string $id
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function destroy($id) {
 	public function destroy($id) {
 
 
 		$session = Session::get($id);
 		$session = Session::get($id);
@@ -35,15 +51,18 @@ class SiteSessionHandler implements SessionHandlerInterface {
 		return true;
 		return true;
 	}
 	}
 
 
+	/**
+	 * @param int $lifetime
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function gc($lifetime) {
 	public function gc($lifetime) {
 		$threshold = time() - $lifetime;
 		$threshold = time() - $lifetime;
 		$date_time = date("Y-m-d H:i:s", $threshold);
 		$date_time = date("Y-m-d H:i:s", $threshold);
 
 
 		$sql = "DELETE FROM `session` WHERE `dts_last_access` < '$date_time'";
 		$sql = "DELETE FROM `session` WHERE `dts_last_access` < '$date_time'";
 		$result = db::query($sql);
 		$result = db::query($sql);
-		return $result;
+		return !empty($result);
 	}
 	}
 
 
 }
 }
-
-?>

+ 100 - 22
engine/template.php

@@ -1,17 +1,32 @@
-<?php
+<?php /** @noinspection PhpIncludeInspection */
+
+/**
+ * @property int $id
+ * @property int $customer_id
+ * @property string $name
+ * @property string $json
+ * @property string $json_file
+ * @property bool $practice
+ * @property string $folder
+ * @property int $pass_stage
+ */
 
 
 class Template extends Model {
 class Template extends Model {
 
 
 	protected static $table = "template";
 	protected static $table = "template";
 	protected static $id_field = "id";
 	protected static $id_field = "id";
-	protected static $fillable_fields = ["customer_id", "name", "json", "json_file", "practice", "pass_stage"];
+	protected static $fillable_fields = ["customer_id", "name", "json", "json_file", "practice", "folder", "pass_stage"];
 
 
 	private $overrides = [];
 	private $overrides = [];
 
 
 	// Object methods
 	// Object methods
-	public function exportTestsCSV($processing_file, $tests = []) {
 
 
-		$template = $this;
+	/**
+	 * @param string $processing_file
+	 * @param Test[] $tests
+	 * @throws Exception
+	 */
+	public function exportTestsCSV(string $processing_file, array $tests = []) {
 
 
 		// Preload
 		// Preload
 		Project::load(array_column($tests, "project_id"));
 		Project::load(array_column($tests, "project_id"));
@@ -32,19 +47,17 @@ class Template extends Model {
 		});
 		});
 
 
 		// Output
 		// Output
-		header("Content-Type: text/plain");
-		header("Content-Disposition: attachment; filename=\"export.csv\"");
-		header("Cache-Control: private, max-age=0, must-revalidate");
-		header("Pragma: public");
+		HTTP::setDownloadHeaders("export.csv");
 
 
 		$handle = fopen("php://output", "w");
 		$handle = fopen("php://output", "w");
-
 		require $processing_file_path;
 		require $processing_file_path;
-
 		fclose($handle);
 		fclose($handle);
 	}
 	}
 
 
-	public function getJSON() {
+	/**
+	 * @return string
+	 */
+	public function getJSON(): string {
 		$json_path = ROOT_DIR . "/json/" . $this->json_file;
 		$json_path = ROOT_DIR . "/json/" . $this->json_file;
 
 
 		if(!empty($this->json_file) && file_exists($json_path)) {
 		if(!empty($this->json_file) && file_exists($json_path)) {
@@ -54,27 +67,45 @@ class Template extends Model {
 		return $this->json;
 		return $this->json;
 	}
 	}
 
 
-	public function getCustomer() {
+	/**
+	 * @return Customer|null
+	 * @throws Exception
+	 */
+	public function getCustomer(): ?Customer {
 		return Customer::get($this->customer_id);
 		return Customer::get($this->customer_id);
 	}
 	}
 
 
-	public function getProcessingFilePath($file) {
+	/**
+	 * @param $file
+	 * @return string
+	 * @throws Exception
+	 */
+	public function getProcessingFilePath($file): string {
 		if(!$this->folder) throw new Exception("Template processing folder not set.");
 		if(!$this->folder) throw new Exception("Template processing folder not set.");
 
 
 		$folder_path = ROOT_DIR . "/template_processing/" . $this->folder;
 		$folder_path = ROOT_DIR . "/template_processing/" . $this->folder;
 		if(!file_exists($folder_path)) throw new Exception("Template processing folder does not exist.");
 		if(!file_exists($folder_path)) throw new Exception("Template processing folder does not exist.");
 
 
 		$file_path = $folder_path . "/" . $file;
 		$file_path = $folder_path . "/" . $file;
-		if(!file_exists($file_path)) throw new Exception("Template processing file \"$file\" does not exist.");
+		if(!file_exists($file_path)) {
+			$file_path = ROOT_DIR . "/template_processing/_common/{$file}";
+			if(!file_exists($file_path)) throw new Exception("Template processing file \"$file\" does not exist.");
+		}
 
 
 		return $file_path;
 		return $file_path;
 	}
 	}
 
 
-	public function getURL() {
+	/**
+	 * @return string
+	 */
+	public function getURL(): string {
 		return "/account/templates/" . $this->id;
 		return "/account/templates/" . $this->id;
 	}
 	}
 
 
-	public function getFields() {
+	/**
+	 * @return array
+	 */
+	public function getFields(): array {
 		$fields = [];
 		$fields = [];
 
 
 		$json = json_decode($this->getJSON());
 		$json = json_decode($this->getJSON());
@@ -90,25 +121,56 @@ class Template extends Model {
 		return $fields;
 		return $fields;
 	}
 	}
 
 
-	public function getTesterInvoiceFields() {
+	/**
+	 * @return array
+	 * @throws Exception
+	 */
+	public function getTesterInvoiceFields(): array {
 		$json = json_decode($this->getJSON());
 		$json = json_decode($this->getJSON());
 		if(!$json) throw new Exception("Failed to decode template JSON.");
 		if(!$json) throw new Exception("Failed to decode template JSON.");
 
 
 		return $json->testerInvoiceFields ?? [];
 		return $json->testerInvoiceFields ?? [];
 	}
 	}
 
 
-	public function getCustomerInvoiceFields() {
+	/**
+	 * @return array
+	 * @throws Exception
+	 */
+	public function getCustomerInvoiceFields(): array {
 		$json = json_decode($this->getJSON());
 		$json = json_decode($this->getJSON());
 		if(!$json) throw new Exception("Failed to decode template JSON.");
 		if(!$json) throw new Exception("Failed to decode template JSON.");
 
 
 		return $json->customerInvoiceFields ?? [];
 		return $json->customerInvoiceFields ?? [];
 	}
 	}
 
 
-	public function setOverrides($overrides) {
+	/**
+	 * @param array $values
+	 * @return float
+	 * @throws Exception
+	 */
+	public function getTesterInvoiceCosts(array $values = []): float {
+		$costs = 0;
+
+		$invoice_fields = $this->getTesterInvoiceFields();
+		foreach($invoice_fields as $field) {
+			$costs += (float) $values[$field->name] ?? 0;
+		}
+
+		return $costs;
+	}
+
+	/**
+	 * @param array $overrides
+	 */
+	public function setOverrides(array $overrides) {
 		$this->overrides = $overrides;
 		$this->overrides = $overrides;
 	}
 	}
 
 
-	public function applyOverridesToField($field) {
+	/**
+	 * @param object $field
+	 * @return object
+	 */
+	public function applyOverridesToField(object $field): object {
 		foreach($this->overrides as $override) {
 		foreach($this->overrides as $override) {
 			if(empty($field->name)) continue;
 			if(empty($field->name)) continue;
 			if($override->field == $field->name) {
 			if($override->field == $field->name) {
@@ -122,6 +184,9 @@ class Template extends Model {
 		return $field;
 		return $field;
 	}
 	}
 
 
+	/**
+	 * @throws Exception
+	 */
 	public function renderBeforeTestForm() {
 	public function renderBeforeTestForm() {
 
 
 		$json = json_decode($this->getJSON());
 		$json = json_decode($this->getJSON());
@@ -154,6 +219,9 @@ class Template extends Model {
 		<?php
 		<?php
 	}
 	}
 
 
+	/**
+	 * @throws Exception
+	 */
 	public function renderDuringTestForm() {
 	public function renderDuringTestForm() {
 
 
 		$json = json_decode($this->getJSON());
 		$json = json_decode($this->getJSON());
@@ -293,8 +361,18 @@ class Template extends Model {
 		<?php
 		<?php
 	}
 	}
 
 
+	/**
+	 * @return int
+	 */
+	public function getPassStage(): int {
+		return (int) $this->pass_stage;
+	}
 
 
+	/**
+	 * @return bool
+	 */
+	public function hasPassFail(): bool {
+		return !is_null($this->pass_stage);
+	}
 
 
 }
 }
-
-?>

+ 274 - 40
engine/test.php

@@ -1,4 +1,45 @@
-<?php
+<?php /** @noinspection HtmlDeprecatedTag */
+/** @noinspection HtmlDeprecatedAttribute */
+
+use Mpdf\Mpdf;
+
+/**
+ * @property int $id
+ * @property int $project_id
+ * @property int $location_id
+ * @property int $tester_id
+ * @property int $status
+ * @property int $status_tester_invoice
+ * @property float $customer_fee
+ * @property float $test_fee
+ * @property string $test_time
+ * @property float $test_travel_cost
+ * @property string $shop_left
+ * @property string $shop_right
+ * @property string $attire
+ * @property int $challenge_stage
+ * @property string $challenge_description
+ * @property string $challenger_name
+ * @property string $challenger_description
+ * @property string $challenger_gender
+ * @property string $challenger_eye_contact
+ * @property string $additional_notes
+ * @property string $dts_due
+ * @property string $dts_start
+ * @property string $dts_end
+ * @property string $dts_tester_invoice_generated
+ * @property string $dts_tester_invoice_paid
+ * @property int $verifier_id
+ * @property string $verifier_notes
+ * @property bool $pass
+ * @property bool $retest
+ * @property string $dts_created
+ * @property string $dts_updated
+ * @property string $dts_assigned
+ * @property string $dts_verified
+ *
+ * @method Test get(int $id)
+ */
 
 
 class Test extends Model {
 class Test extends Model {
 
 
@@ -52,7 +93,12 @@ class Test extends Model {
 	const TEST_TIME_NIGHT = 3;
 	const TEST_TIME_NIGHT = 3;
 
 
 	// Static methods
 	// Static methods
-	public static function getStatusTesterInvoiceText($status) {
+
+	/**
+	 * @param int $status
+	 * @return string
+	 */
+	public static function getStatusTesterInvoiceText(int $status): string {
 		switch($status) {
 		switch($status) {
 			case Test::STATUS_TESTER_INVOICE_NONE:
 			case Test::STATUS_TESTER_INVOICE_NONE:
 				return __("No Invoice Generated");
 				return __("No Invoice Generated");
@@ -64,7 +110,11 @@ class Test extends Model {
 		return __("Unknown");
 		return __("Unknown");
 	}
 	}
 
 
-	public static function getStatusTesterInvoiceClass($status) {
+	/**
+	 * @param int $status
+	 * @return string
+	 */
+	public static function getStatusTesterInvoiceClass(int $status): string {
 		switch($status) {
 		switch($status) {
 			case Test::STATUS_TESTER_INVOICE_NONE:
 			case Test::STATUS_TESTER_INVOICE_NONE:
 				return "secondary";
 				return "secondary";
@@ -76,8 +126,38 @@ class Test extends Model {
 		return "";
 		return "";
 	}
 	}
 
 
+	/**
+	 * @param string $processing_file
+	 * @param array $tests
+	 * @throws Exception
+	 */
+	public static function exportCSV(string $processing_file, array $tests = []): void {
+
+		// Preload
+		Project::load(array_column($tests, "project_id"));
+		Location::load(array_column($tests, "location_id"));
+		User::load(array_column($tests, "tester_id"));
+
+		// Get processing file
+		$processing_file_path = ROOT_DIR . "/export_processing/{$processing_file}";
+		if(!file_exists($processing_file_path)) throw new Exception("Processing file not found.");
+
+		// Output
+		HTTP::setDownloadHeaders("export.csv");
+
+		$handle = fopen("php://output", "w");
+		require $processing_file_path;
+		fclose($handle);
+	}
+
 	// Object methods
 	// Object methods
-	public function sendAssignEmail($message) {
+
+	/**
+	 * @param string $message
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function sendAssignEmail(string $message): bool {
 
 
 		$tester = $this->getTester();
 		$tester = $this->getTester();
 		$location = $this->getLocation();
 		$location = $this->getLocation();
@@ -138,9 +218,15 @@ class Test extends Model {
 		$mail->addAddress($tester->email, $tester->getDisplayName());
 		$mail->addAddress($tester->email, $tester->getDisplayName());
 		$mail->setSubject(__("You have been allocated a test"));
 		$mail->setSubject(__("You have been allocated a test"));
 		$mail->send();
 		$mail->send();
+
+		return true;
 	}
 	}
 
 
-	public function sendClaimedEmail() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function sendClaimedEmail(): bool {
 
 
 		$tester = $this->getTester();
 		$tester = $this->getTester();
 		$location = $this->getLocation();
 		$location = $this->getLocation();
@@ -170,10 +256,8 @@ class Test extends Model {
 			'<b>', '</b>',
 			'<b>', '</b>',
 			'<b>', '</b>'
 			'<b>', '</b>'
 		));
 		));
-		$builder->addParagraph(sprintf(__("If you have any questions please send them to %s or call %s on %s."),
-			"<a href=\"mailto:tests@check-policy.com\">tests@check-policy.com</a>",
-			"<b>$admin_first_name</b>",
-			"<b>$admin_phone</b>"
+		$builder->addParagraph(sprintf(__("If you have any questions please send them to %s."),
+			"<a href=\"mailto:tests@check-policy.com\">tests@check-policy.com</a>"
 		));
 		));
 		$builder->addParagraph(__("If you are unable to submit the results via the web-based app please contact us and we can send you an offline form to complete."));
 		$builder->addParagraph(__("If you are unable to submit the results via the web-based app please contact us and we can send you an offline form to complete."));
 		$content = $builder->build();
 		$content = $builder->build();
@@ -185,9 +269,15 @@ class Test extends Model {
 		$mail->addAddress($tester->email, $tester->getDisplayName());
 		$mail->addAddress($tester->email, $tester->getDisplayName());
 		$mail->setSubject(__("You have claimed a test"));
 		$mail->setSubject(__("You have claimed a test"));
 		$mail->send();
 		$mail->send();
+
+		return true;
 	}
 	}
 
 
-	public function sendDeclineEmail() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function sendDeclineEmail(): bool {
 
 
 		$tester = $this->getTester();
 		$tester = $this->getTester();
 		$location = $this->getLocation();
 		$location = $this->getLocation();
@@ -219,9 +309,16 @@ class Test extends Model {
 		$mail->addAddress(EMAIL_CONTACT, APP_NAME . " Contact");
 		$mail->addAddress(EMAIL_CONTACT, APP_NAME . " Contact");
 		$mail->setSubject("Test declined: $project->name / $location->name");
 		$mail->setSubject("Test declined: $project->name / $location->name");
 		$mail->send();
 		$mail->send();
+
+		return true;
 	}
 	}
 
 
-	public function sendResultEmail($to_address) {
+	/**
+	 * @param string $to_address
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function sendResultEmail(string $to_address): bool {
 
 
 		$location = $this->getLocation();
 		$location = $this->getLocation();
 		$project = $this->getProject();
 		$project = $this->getProject();
@@ -281,9 +378,15 @@ class Test extends Model {
 		$mail->setSubject($subject);
 		$mail->setSubject($subject);
 
 
 		$mail->send();
 		$mail->send();
+
+		return true;
 	}
 	}
 
 
-	public function decline() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function decline(): bool {
 		$this->sendDeclineEmail();
 		$this->sendDeclineEmail();
 
 
 		$this->status = Test::STATUS_UNASSIGNED;
 		$this->status = Test::STATUS_UNASSIGNED;
@@ -294,16 +397,25 @@ class Test extends Model {
 		return $this->commit();
 		return $this->commit();
 	}
 	}
 
 
-	public function getChallengeStageText() {
+	/**
+	 * @return string
+	 */
+	public function getChallengeStageText(): string {
 		if(is_null($this->challenge_stage)) return "";
 		if(is_null($this->challenge_stage)) return "";
 		return Test::STAGES[$this->challenge_stage];
 		return Test::STAGES[$this->challenge_stage];
 	}
 	}
 
 
-	public function getStatusText() {
+	/**
+	 * @return string
+	 */
+	public function getStatusText(): string {
 		return Test::STATUSES[$this->status];
 		return Test::STATUSES[$this->status];
 	}
 	}
 
 
-	public function getStatusClass() {
+	/**
+	 * @return string
+	 */
+	public function getStatusClass(): string {
 		switch($this->status) {
 		switch($this->status) {
 			case Test::STATUS_CANCELLED:
 			case Test::STATUS_CANCELLED:
 				return "secondary";
 				return "secondary";
@@ -318,25 +430,47 @@ class Test extends Model {
 			case Test::STATUS_COMPLETED:
 			case Test::STATUS_COMPLETED:
 				return "success";
 				return "success";
 		}
 		}
+		return "";
 	}
 	}
 
 
-	public function getProject() {
+	/**
+	 * @return Project|null
+	 * @throws Exception
+	 */
+	public function getProject(): ?Project {
 		return Project::get($this->project_id);
 		return Project::get($this->project_id);
 	}
 	}
 
 
-	public function getLocation() {
+	/**
+	 * @return Location
+	 * @throws Exception
+	 */
+	public function getLocation(): ?Location {
 		return Location::get($this->location_id);
 		return Location::get($this->location_id);
 	}
 	}
 
 
-	public function getTester() {
+	/**
+	 * @return User
+	 * @throws Exception
+	 */
+	public function getTester(): ?User {
 		return User::get($this->tester_id);
 		return User::get($this->tester_id);
 	}
 	}
 
 
-	public function getVerifier() {
+	/**
+	 * @return User
+	 * @throws Exception
+	 */
+	public function getVerifier(): ?User {
 		return User::get($this->verifier_id);
 		return User::get($this->verifier_id);
 	}
 	}
 
 
-	public function getValues($as_assoc_array = false) {
+	/**
+	 * @param bool $as_assoc_array
+	 * @return array
+	 * @throws Exception
+	 */
+	public function getValues(bool $as_assoc_array = false): array {
 		$rows = TestValue::query(["test_id" => $this->id]);
 		$rows = TestValue::query(["test_id" => $this->id]);
 
 
 		if($as_assoc_array) {
 		if($as_assoc_array) {
@@ -351,22 +485,28 @@ class Test extends Model {
 		return $values;
 		return $values;
 	}
 	}
 
 
-	public function getDirectory() {
+	/**
+	 * @return string
+	 */
+	public function getDirectory(): string {
 		$directory = ROOT_DIR . "/files/tests/" . $this->id;
 		$directory = ROOT_DIR . "/files/tests/" . $this->id;
-		if($this->project_id == "PRACTICE") {
-			$directory = ROOT_DIR . "/files/users/$this->tester_id/practice_tests/$this->template_id";
-		}
 		if(!file_exists($directory)) mkdir($directory, 0777, true);
 		if(!file_exists($directory)) mkdir($directory, 0777, true);
 		return $directory;
 		return $directory;
 	}
 	}
 
 
+	/**
+	 * @return bool|float|int
+	 */
 	public function getDuration() {
 	public function getDuration() {
 		if(is_null($this->dts_end)) return false;
 		if(is_null($this->dts_end)) return false;
 		$seconds = Util::getDurationFromDTS($this->dts_start, $this->dts_end);
 		$seconds = Util::getDurationFromDTS($this->dts_start, $this->dts_end);
 		return $seconds;
 		return $seconds;
 	}
 	}
 
 
-	public function getDisplayDuration() {
+	/**
+	 * @return string
+	 */
+	public function getDisplayDuration(): string {
 		$secs = $this->getDuration();
 		$secs = $this->getDuration();
 		$mins = floor($secs / 60);
 		$mins = floor($secs / 60);
 		$secs = $secs % 60;
 		$secs = $secs % 60;
@@ -374,29 +514,44 @@ class Test extends Model {
 		return "$mins min. $secs sec.";
 		return "$mins min. $secs sec.";
 	}
 	}
 
 
-	public function getPassClass() {
+	/**
+	 * @return string Bootstrap class name
+	 */
+	public function getPassClass(): string {
 		if(is_null($this->pass)) return "secondary";
 		if(is_null($this->pass)) return "secondary";
 		return $this->pass ? "success" : "danger";
 		return $this->pass ? "success" : "danger";
 	}
 	}
 
 
-	public function getPassIcon() {
+	/**
+	 * @return string FA icon name without prefix
+	 */
+	public function getPassIcon(): string {
 		if(is_null($this->pass)) return "clock";
 		if(is_null($this->pass)) return "clock";
 		return $this->pass ? "check-circle" : "times-circle";
 		return $this->pass ? "check-circle" : "times-circle";
 	}
 	}
 
 
-	public function getPassText() {
-		if(is_null($this->pass)) return "Pending";
+	/**
+	 * @return string Pending, Pass or Fail
+	 */
+	public function getPassText(): string {
+		if(is_null($this->pass)) return __("Pending");
 		return $this->pass ? __("Pass") : __("Fail");
 		return $this->pass ? __("Pass") : __("Fail");
 	}
 	}
 
 
-	public function getMPDF() {
+	public function getMPDF(): Mpdf {
+		/** @var Mpdf $mpdf */
 		$id = $this->id;
 		$id = $this->id;
 		$output = false;
 		$output = false;
 		require ROOT_DIR . "/controllers/test_pdf.php";
 		require ROOT_DIR . "/controllers/test_pdf.php";
 		return $mpdf;
 		return $mpdf;
 	}
 	}
 
 
-	public function assignTester($tester) {
+	/**
+	 * @param User $tester
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function assignTester(User $tester): bool {
 		$this->tester_id = $tester->id;
 		$this->tester_id = $tester->id;
 		$this->dts_assigned = Util::getDateTime();
 		$this->dts_assigned = Util::getDateTime();
 		$success = $this->commit();
 		$success = $this->commit();
@@ -407,7 +562,11 @@ class Test extends Model {
 
 
 	}
 	}
 
 
-	public function getPreviousTest() {
+	/**
+	 * @return Test|null
+	 * @throws Exception
+	 */
+	public function getPreviousTest(): ?Test {
 
 
 		$nvp = [
 		$nvp = [
 			"dts_start" => (new Constraint("LESS_THAN"))->setValues($this->dts_start),
 			"dts_start" => (new Constraint("LESS_THAN"))->setValues($this->dts_start),
@@ -420,30 +579,87 @@ class Test extends Model {
 			"order" => "desc",
 			"order" => "desc",
 		]);
 		]);
 
 
-		return $tests ? $tests[0] : false;
+		return $tests ? $tests[0] : null;
 
 
 	}
 	}
 
 
-	public function unassignTester() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function unassignTester(): bool {
 		$this->status = Test::STATUS_UNASSIGNED;
 		$this->status = Test::STATUS_UNASSIGNED;
 		$this->tester_id = null;
 		$this->tester_id = null;
 		$this->dts_due = null;
 		$this->dts_due = null;
 		$this->dts_assigned = null;
 		$this->dts_assigned = null;
-		$success = $this->commit();
+		return $this->commit();
+	}
 
 
-		return $success;
+	/**
+	 * @return bool
+	 */
+	public function isPass(): bool {
+		if(is_null($this->pass)) return false;
+		return !empty($this->pass);
+	}
+
+	/**
+	 * @return bool
+	 */
+	public function isPending(): bool {
+		return is_null($this->pass);
+	}
+
+	/**
+	 * @return bool
+	 */
+	public function isFail(): bool {
+		if(is_null($this->pass)) return false;
+		return empty($this->pass);
+	}
+
+	/**
+	 * @return bool
+	 */
+	public function isCompleted() {
+		return $this->status == Test::STATUS_COMPLETED;
 	}
 	}
 
 
+	/**
+	 * @return bool
+	 */
 	public function isPendingVerification() {
 	public function isPendingVerification() {
 		return $this->status == Test::STATUS_PENDING_VERIFICATION;
 		return $this->status == Test::STATUS_PENDING_VERIFICATION;
 	}
 	}
 
 
-	public function hasTesterInvoicePDF() {
+	/**
+	 * @return bool
+	 */
+	public function hasPDF(): bool {
+		$directory = $this->getDirectory();
+		return file_exists($directory . "/pdf.pdf");
+	}
+
+	/**
+	 * @return string
+	 */
+	public function getPDFUrl(): string {
+		return "/account/tests/{$this->id}/files/pdf";
+	}
+
+	/**
+	 * @return bool
+	 */
+	public function hasTesterInvoicePDF(): bool {
 		$directory = $this->getDirectory();
 		$directory = $this->getDirectory();
 		return file_exists($directory . "/tester_invoice.pdf");
 		return file_exists($directory . "/tester_invoice.pdf");
 	}
 	}
 
 
-	public function markTesterInvoicePaid() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function markTesterInvoicePaid(): bool {
 
 
 		if($this->status_tester_invoice == Test::STATUS_TESTER_INVOICE_PENDING) {
 		if($this->status_tester_invoice == Test::STATUS_TESTER_INVOICE_PENDING) {
 			$this->status_tester_invoice = Test::STATUS_TESTER_INVOICE_PAID;
 			$this->status_tester_invoice = Test::STATUS_TESTER_INVOICE_PAID;
@@ -454,7 +670,11 @@ class Test extends Model {
 		return false;
 		return false;
 	}
 	}
 
 
-	public function rejectTesterInvoice() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function rejectTesterInvoice(): bool {
 		if($this->status_tester_invoice == Test::STATUS_TESTER_INVOICE_PENDING) {
 		if($this->status_tester_invoice == Test::STATUS_TESTER_INVOICE_PENDING) {
 			$this->status_tester_invoice = Test::STATUS_TESTER_INVOICE_NONE;
 			$this->status_tester_invoice = Test::STATUS_TESTER_INVOICE_NONE;
 			$this->dts_tester_invoice_generated = null;
 			$this->dts_tester_invoice_generated = null;
@@ -468,5 +688,19 @@ class Test extends Model {
 		return false;
 		return false;
 	}
 	}
 
 
+	/**
+	 * @return string
+	 * @throws Exception
+	 */
+	public function getTesterInvoiceReference(): string {
+
+		$location = $this->getLocation();
+		$tester = $this->getTester();
+
+		return
+		"T" . str_pad($this->id, 3, "0", STR_PAD_LEFT) .
+		"/L" . str_pad($location->id, 3, "0", STR_PAD_LEFT) .
+		"/U" . str_pad($tester->id, 3, "0", STR_PAD_LEFT);
+	}
+
 }
 }
-?>

+ 5 - 1
engine/test_pdf.php

@@ -2,7 +2,11 @@
 
 
 class TestPDF {
 class TestPDF {
 
 
-	public static function getValueHtml($value) {
+	/**
+	 * @param string $value
+	 * @return string
+	 */
+	public static function getValueHtml(string $value): string {
 		if(empty($value)) {
 		if(empty($value)) {
 			return "<span class=\"text-muted\">N/A</span>";
 			return "<span class=\"text-muted\">N/A</span>";
 		}
 		}

+ 0 - 7
engine/test_value.php

@@ -6,11 +6,4 @@ class TestValue extends Model {
 	protected static $id_field = ["test_id", "name"];
 	protected static $id_field = ["test_id", "name"];
 	protected static $fillable_fields = ["test_id", "name", "value"];
 	protected static $fillable_fields = ["test_id", "name", "value"];
 
 
-	protected static $field_map = [
-	];
-
-	// Object methods
-
 }
 }
-
-?>

+ 160 - 28
engine/user.php

@@ -1,5 +1,43 @@
 <?php
 <?php
 
 
+/**
+ * Class User
+ *
+ * @property int $id
+ * @property string $email
+ * @property int $old_id
+ * @property int $referrer_id
+ * @property string $password
+ * @property bool $activated
+ * @property int $level
+ * @property int $score
+ * @property string $title
+ * @property string $first_name
+ * @property string $last_name
+ * @property string $gender
+ * @property string $date_of_birth
+ * @property string $locale
+ * @property bool $reported
+ * @property string $reported_comment
+ * @property bool $can_claim
+ * @property string $phone
+ * @property string $verify_token
+ * @property string $reset_token
+ * @property bool $terms_accepted
+ * @property bool $newsletter_consent
+ * @property int $preferred_payment_method
+ * @property string $bank_name
+ * @property string $bank_sort_code
+ * @property string $bank_account_number
+ * @property string $paypal_email
+ * @property string $dts_registered
+ * @property string $dts_last_seen
+ * @property string $dts_verified
+ * @property string $dts_deleted
+ * @property int $verifier_id
+ * @property string $verifier_notes
+ */
+
 class User extends Model {
 class User extends Model {
 
 
 	protected static $table = "user";
 	protected static $table = "user";
@@ -40,7 +78,11 @@ class User extends Model {
 	];
 	];
 
 
 	// Static methods
 	// Static methods
-	public static function titles() {
+
+	/**
+	 * @return array
+	 */
+	public static function titles(): array {
 		return [
 		return [
 			"Miss" => MISS,
 			"Miss" => MISS,
 			"Mr" => MR,
 			"Mr" => MR,
@@ -49,7 +91,10 @@ class User extends Model {
 		];
 		];
 	}
 	}
 
 
-	public static function genders() {
+	/**
+	 * @return array
+	 */
+	public static function genders(): array {
 		return [
 		return [
 			"Female" => FEMALE,
 			"Female" => FEMALE,
 			"Male" => MALE,
 			"Male" => MALE,
@@ -57,7 +102,11 @@ class User extends Model {
 		];
 		];
 	}
 	}
 
 
-	public static function validatePassword($password) {
+	/**
+	 * @param string $password
+	 * @return bool
+	 */
+	public static function validatePassword(string $password): bool {
 		$lowercase = preg_match("/[a-z]/", $password);
 		$lowercase = preg_match("/[a-z]/", $password);
 		$uppercase = preg_match("/[A-Z]/", $password);
 		$uppercase = preg_match("/[A-Z]/", $password);
 		$number = preg_match("/[0-9]/", $password);
 		$number = preg_match("/[0-9]/", $password);
@@ -68,7 +117,11 @@ class User extends Model {
 	}
 	}
 
 
 	// Object methods
 	// Object methods
-	public function hasValidPaymentMethod() {
+
+	/**
+	 * @return bool
+	 */
+	public function hasValidPaymentMethod(): bool {
 		switch($this->preferred_payment_method) {
 		switch($this->preferred_payment_method) {
 			case User::PAYMENT_METHOD_BANK_TRANSFER: {
 			case User::PAYMENT_METHOD_BANK_TRANSFER: {
 				if(empty($this->bank_name)) return false;
 				if(empty($this->bank_name)) return false;
@@ -84,6 +137,10 @@ class User extends Model {
 		return true;
 		return true;
 	}
 	}
 
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function sendActivationEmail() {
 	public function sendActivationEmail() {
 
 
 		$this->verify_token = bin2hex(random_bytes(16));
 		$this->verify_token = bin2hex(random_bytes(16));
@@ -114,6 +171,10 @@ class User extends Model {
 		return true;
 		return true;
 	}
 	}
 
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function sendWelcomeEmail() {
 	public function sendWelcomeEmail() {
 
 
 		// Content
 		// Content
@@ -140,6 +201,10 @@ class User extends Model {
 
 
 	}
 	}
 
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function sendIDPassEmail() {
 	public function sendIDPassEmail() {
 
 
 		// Content
 		// Content
@@ -175,6 +240,11 @@ class User extends Model {
 
 
 	}
 	}
 
 
+	/**
+	 * @param string $reason
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function sendIDFailEmail($reason = "No reason given.") {
 	public function sendIDFailEmail($reason = "No reason given.") {
 
 
 		// Content
 		// Content
@@ -202,6 +272,10 @@ class User extends Model {
 		return true;
 		return true;
 	}
 	}
 
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function sendPasswordResetEmail() {
 	public function sendPasswordResetEmail() {
 
 
 		$this->reset_token = bin2hex(random_bytes(16));
 		$this->reset_token = bin2hex(random_bytes(16));
@@ -235,12 +309,19 @@ class User extends Model {
 
 
 	}
 	}
 
 
+	/**
+	 * @return bool
+	 */
 	public function canAdmin() {
 	public function canAdmin() {
 		return $this->level >= User::LEVEL_ADMIN;
 		return $this->level >= User::LEVEL_ADMIN;
 	}
 	}
 
 
-	public function getReferrer() {
-		return is_null($this->referrer_id) ? false : User::get($this->referrer_id);
+	/**
+	 * @return User|null
+	 * @throws Exception
+	 */
+	public function getReferrer(): ?User {
+		return is_null($this->referrer_id) ? null : User::get($this->referrer_id);
 	}
 	}
 
 
 	public function getDirectory() {
 	public function getDirectory() {
@@ -295,6 +376,10 @@ class User extends Model {
 		return "Unspecified";
 		return "Unspecified";
 	}
 	}
 
 
+	/**
+	 * @return int|string
+	 * @throws Exception
+	 */
 	public function getAge() {
 	public function getAge() {
 
 
 		if(is_null($this->date_of_birth)) return __("N/A");
 		if(is_null($this->date_of_birth)) return __("N/A");
@@ -312,33 +397,41 @@ class User extends Model {
 		return implode(" ", $parts);
 		return implode(" ", $parts);
 	}
 	}
 
 
-	public function hasPermission($object) {
+	/**
+	 * @param $object
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function hasPermission($object): bool {
 
 
-		if($this->level == User::LEVEL_SUPERADMIN) return true;
-		if($this->level == User::LEVEL_ADMIN) return true;
+		if($this->isAdmin()) return true;
 
 
 		$customers = $this->getCustomers();
 		$customers = $this->getCustomers();
 		$customer_ids = array_column($customers, "id");
 		$customer_ids = array_column($customers, "id");
 
 
-		if(is_a($object, "Customer")) {
+		if($object instanceof Customer) {
 			return in_array($object->id, $customer_ids);
 			return in_array($object->id, $customer_ids);
 		}
 		}
 
 
-		if(is_a($object, "Location")) {
+		if($object instanceof Location) {
 			return in_array($object->customer_id, $customer_ids);
 			return in_array($object->customer_id, $customer_ids);
 		}
 		}
 
 
-		if(is_a($object, "Project")) {
+		if($object instanceof Project) {
 			return in_array($object->customer_id, $customer_ids);
 			return in_array($object->customer_id, $customer_ids);
 		}
 		}
 
 
-		if(is_a($object, "Template")) {
+		if($object instanceof Template) {
 			return in_array($object->customer_id, $customer_ids);
 			return in_array($object->customer_id, $customer_ids);
 		}
 		}
 
 
 		return false;
 		return false;
 	}
 	}
 
 
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
 	public function deactivate() {
 	public function deactivate() {
 		// Decline all pending tests
 		// Decline all pending tests
 		$pending_tests = $this->getPendingTests();
 		$pending_tests = $this->getPendingTests();
@@ -351,7 +444,11 @@ class User extends Model {
 		return $this->commit();
 		return $this->commit();
 	}
 	}
 
 
-	public function softDelete() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function softDelete(): bool {
 
 
 		// Delete identification documents
 		// Delete identification documents
 		$this->deleteIDFiles();
 		$this->deleteIDFiles();
@@ -379,12 +476,14 @@ class User extends Model {
 		// Set deleted time
 		// Set deleted time
 		$this->dts_deleted = Util::getDateTime();
 		$this->dts_deleted = Util::getDateTime();
 
 
-		$success = $this->commit();
-
-		return true;
+		return $this->commit();
 	}
 	}
 
 
-	public function deleteIDFiles() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function deleteIDFiles(): bool {
 
 
 		$files = UserFile::query([
 		$files = UserFile::query([
 			"user_id" => $this->id,
 			"user_id" => $this->id,
@@ -401,8 +500,11 @@ class User extends Model {
 		return true;
 		return true;
 	}
 	}
 
 
-
-	public function deleteAddresses() {
+	/**
+	 * @return bool
+	 * @throws Exception
+	 */
+	public function deleteAddresses(): bool {
 		$addresses = $this->getAddresses();
 		$addresses = $this->getAddresses();
 		foreach($addresses as $address) {
 		foreach($addresses as $address) {
 			$address->delete();
 			$address->delete();
@@ -411,7 +513,11 @@ class User extends Model {
 		return true;
 		return true;
 	}
 	}
 
 
-	public function getAddresses() {
+	/**
+	 * @return UserAddress[]
+	 * @throws Exception
+	 */
+	public function getAddresses(): array {
 
 
 		$addresses = UserAddress::query([
 		$addresses = UserAddress::query([
 			"user_id" => $this->id,
 			"user_id" => $this->id,
@@ -422,7 +528,11 @@ class User extends Model {
 		return $addresses;
 		return $addresses;
 	}
 	}
 
 
-	public function getInvoiceAddress() {
+	/**
+	 * @return UserAddress|null
+	 * @throws Exception
+	 */
+	public function getInvoiceAddress(): ?UserAddress {
 		$addresses = UserAddress::query([
 		$addresses = UserAddress::query([
 			"user_id" => $this->id,
 			"user_id" => $this->id,
 		]);
 		]);
@@ -434,9 +544,13 @@ class User extends Model {
 		// If only one address in account, just return it
 		// If only one address in account, just return it
 		if(count($addresses) == 1) return array_shift($addresses);
 		if(count($addresses) == 1) return array_shift($addresses);
 
 
-		return false;
+		return null;
 	}
 	}
 
 
+	/**
+	 * @return Customer[]
+	 * @throws Exception
+	 */
 	public function getCustomers() {
 	public function getCustomers() {
 
 
 		if($this->level >= User::LEVEL_ADMIN) {
 		if($this->level >= User::LEVEL_ADMIN) {
@@ -453,7 +567,11 @@ class User extends Model {
 		return [];
 		return [];
 	}
 	}
 
 
-	public function getPendingTests() {
+	/**
+	 * @return Test[]
+	 * @throws Exception
+	 */
+	public function getPendingTests(): array {
 		return Test::query([
 		return Test::query([
 			"tester_id" => $this->id,
 			"tester_id" => $this->id,
 			"status" => [Test::STATUS_ASSIGNED, Test::STATUS_CONFIRMED, Test::STATUS_STARTED, Test::STATUS_PENDING_VERIFICATION],
 			"status" => [Test::STATUS_ASSIGNED, Test::STATUS_CONFIRMED, Test::STATUS_STARTED, Test::STATUS_PENDING_VERIFICATION],
@@ -463,7 +581,11 @@ class User extends Model {
 		]);
 		]);
 	}
 	}
 
 
-	public function getCompletedTests() {
+	/**
+	 * @return Test[]
+	 * @throws Exception
+	 */
+	public function getCompletedTests(): array {
 		return Test::query([
 		return Test::query([
 			"tester_id" => $this->id,
 			"tester_id" => $this->id,
 			"status" => [Test::STATUS_CANCELLED, Test::STATUS_COMPLETED],
 			"status" => [Test::STATUS_CANCELLED, Test::STATUS_COMPLETED],
@@ -473,17 +595,27 @@ class User extends Model {
 		]);
 		]);
 	}
 	}
 
 
-	public function getReferrals() {
+	/**
+	 * @return User[]
+	 * @throws Exception
+	 */
+	public function getReferrals(): array {
 		return User::query([
 		return User::query([
 			"referrer_id" => $this->id
 			"referrer_id" => $this->id
 		]);
 		]);
 	}
 	}
 
 
-	public function getPreferredPaymentMethodText() {
+	/**
+	 * @return string
+	 */
+	public function getPreferredPaymentMethodText(): string {
 		return User::PAYMENT_METHODS[$this->preferred_payment_method];
 		return User::PAYMENT_METHODS[$this->preferred_payment_method];
 	}
 	}
 
 
-	public function getURL() {
+	/**
+	 * @return string
+	 */
+	public function getURL(): string {
 		return "/account/users/{$this->id}";
 		return "/account/users/{$this->id}";
 	}
 	}
 
 

+ 33 - 8
engine/user_address.php

@@ -1,24 +1,48 @@
 <?php
 <?php
 
 
+/**
+ * Class UserAddress
+ *
+ * @property int $id
+ * @property int $user_id
+ * @property string $name
+ * @property string $address_1
+ * @property string $address_2
+ * @property string $city
+ * @property string $county
+ * @property string $postal_code
+ * @property string $state
+ * @property string $country
+ * @property double $latitude
+ * @property double $longitude
+ * @property float $max_radius_miles
+ * @property bool $invoice
+ */
+
 class UserAddress extends Model {
 class UserAddress extends Model {
 
 
 	protected static $table = "user_address";
 	protected static $table = "user_address";
 	protected static $id_field = "id";
 	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", "invoice"];
 	protected static $fillable_fields = ["user_id", "name", "address_1", "address_2", "city", "county", "postal_code", "state", "country", "latitude", "longitude", "max_radius_miles", "invoice"];
 
 
-	protected static $field_map = [
-	];
-
 	const RADIUSES = [
 	const RADIUSES = [
 		"0.25", "0.50", "1.00", "1.50", "2.00", "2.50", "3.00", "4.00", "5.00", "7.50", "10.00", "12.50", "15.00", "20.00", "25.00",
 		"0.25", "0.50", "1.00", "1.50", "2.00", "2.50", "3.00", "4.00", "5.00", "7.50", "10.00", "12.50", "15.00", "20.00", "25.00",
 	];
 	];
 
 
 	// Object methods
 	// Object methods
-	public function getUser() {
+
+	/**
+	 * @return User|null
+	 * @throws Exception
+	 */
+	public function getUser(): ?User {
 		return User::get($this->user_id);
 		return User::get($this->user_id);
 	}
 	}
 
 
-	public function getDisplayAddress() {
+	/**
+	 * @return string
+	 */
+	public function getDisplayAddress(): string {
 		$parts = [];
 		$parts = [];
 		$fields = ["address_1", "address_2", "city", "county", "postal_code", "state", "country"];
 		$fields = ["address_1", "address_2", "city", "county", "postal_code", "state", "country"];
 
 
@@ -29,10 +53,11 @@ class UserAddress extends Model {
 		return implode(", ", array_filter($parts));
 		return implode(", ", array_filter($parts));
 	}
 	}
 
 
-	public function getGeolocation() {
+	/**
+	 * @return array
+	 */
+	public function getGeolocation(): array {
 		return [$this->latitude, $this->longitude];
 		return [$this->latitude, $this->longitude];
 	}
 	}
 
 
 }
 }
-
-?>

+ 18 - 4
engine/user_customer.php

@@ -1,5 +1,12 @@
 <?php
 <?php
 
 
+/**
+ * Class UserCustomer
+ *
+ * @property int $user_id
+ * @property int $customer_id
+ */
+
 class UserCustomer extends Model {
 class UserCustomer extends Model {
 
 
 	protected static $table = "user_customer";
 	protected static $table = "user_customer";
@@ -7,14 +14,21 @@ class UserCustomer extends Model {
 	protected static $fillable_fields = ["user_id", "customer_id"];
 	protected static $fillable_fields = ["user_id", "customer_id"];
 
 
 	// Object methods
 	// Object methods
-	public function getUser() {
+
+	/**
+	 * @return User|null
+	 * @throws Exception
+	 */
+	public function getUser(): ?User {
 		return User::get($this->user_id);
 		return User::get($this->user_id);
 	}
 	}
 
 
-	public function getCustomer() {
+	/**
+	 * @return Customer|null
+	 * @throws Exception
+	 */
+	public function getCustomer(): ?Customer {
 		return Customer::get($this->customer_id);
 		return Customer::get($this->customer_id);
 	}
 	}
 
 
 }
 }
-
-?>

+ 9 - 4
engine/user_file.php

@@ -1,5 +1,14 @@
 <?php
 <?php
 
 
+/**
+ * Class UserFile
+ *
+ * @property int $id
+ * @property int $user_id
+ * @property int $type
+ * @property string $dts_uploaded
+ */
+
 class UserFile extends Model {
 class UserFile extends Model {
 
 
 	protected static $table = "user_file";
 	protected static $table = "user_file";
@@ -9,8 +18,4 @@ class UserFile extends Model {
 	const TYPE_ID = 1;
 	const TYPE_ID = 1;
 	const TYPE_PHOTO = 2;
 	const TYPE_PHOTO = 2;
 
 
-	// Object methods
-
 }
 }
-
-?>

+ 123 - 161
engine/util.php

@@ -1,7 +1,12 @@
 <?php
 <?php
+
 class Util {
 class Util {
 
 
-	public static function getGenderText($gender) {
+	/**
+	 * @param string $gender
+	 * @return string
+	 */
+	public static function getGenderText(string $gender): string {
 		switch($gender) {
 		switch($gender) {
 			case "M": return MALE;
 			case "M": return MALE;
 			case "F": return FEMALE;
 			case "F": return FEMALE;
@@ -9,7 +14,11 @@ class Util {
 		}
 		}
 	}
 	}
 
 
-	public static function getBooleanText($boolean) {
+	/**
+	 * @param string $boolean
+	 * @return string
+	 */
+	public static function getBooleanText(string $boolean): string {
 		switch($boolean) {
 		switch($boolean) {
 			case "Y": return YES;
 			case "Y": return YES;
 			case "N": return NO;
 			case "N": return NO;
@@ -17,12 +26,23 @@ class Util {
 		}
 		}
 	}
 	}
 
 
-	public static function convertUTF8($string, $target_encoding = "CP1252") {
+	/**
+	 * @param string $string
+	 * @param string $target_encoding
+	 * @return string
+	 */
+	public static function convertUTF8(string $string, string $target_encoding = "CP1252"): string {
 		return mb_convert_encoding($string, $target_encoding, "UTF-8");
 		return mb_convert_encoding($string, $target_encoding, "UTF-8");
 	}
 	}
 
 
-	public static function getPaginationObject($array, $page_size = 25) {
-		$item_count = count($array);
+	/**
+	 * @param array $items
+	 * @param int $page_size
+	 * @return object
+	 * @throws Exception
+	 */
+	public static function getPaginationObject(array $items, int $page_size = 25) {
+		$item_count = count($items);
 
 
 		$page = http::value("page");
 		$page = http::value("page");
 		if($page < 1) $page = 1;
 		if($page < 1) $page = 1;
@@ -56,12 +76,22 @@ class Util {
 		];
 		];
 	}
 	}
 
 
-	public static function getItemDirectory($folder, $id) {
+	/**
+	 * @param string $folder
+	 * @param int $id
+	 * @return string
+	 */
+	public static function getItemDirectory(string $folder, int $id): string {
 		$shard = str_pad($id % 1000, 3, "0", STR_PAD_LEFT);
 		$shard = str_pad($id % 1000, 3, "0", STR_PAD_LEFT);
 		return ROOT_DIR . "/files/" . $folder . "/" . $shard . "/" . $id;
 		return ROOT_DIR . "/files/" . $folder . "/" . $shard . "/" . $id;
 	}
 	}
 
 
-	public static function createItemDirectory($folder, $id) {
+	/**
+	 * @param string $folder
+	 * @param int $id
+	 * @return string
+	 */
+	public static function createItemDirectory(string $folder, int $id): string {
 
 
 		$directory = Util::getItemDirectory($folder, $id);
 		$directory = Util::getItemDirectory($folder, $id);
 
 
@@ -72,15 +102,32 @@ class Util {
 		return $directory;
 		return $directory;
 	}
 	}
 
 
-	public static function slug($string) {
+	/**
+	 * @param string $string
+	 * @return string
+	 */
+	public static function slug(string $string): string {
 		$slug = strtolower($string);
 		$slug = strtolower($string);
 		$slug = preg_replace("/[^0-9a-z]/i", "-", $slug); // Replace anything not 0-9 a-z with dash
 		$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 = preg_replace("/-+/", "-", $slug); // Replace consequential dashes with dash
 		$slug = trim($slug, "-");
 		$slug = trim($slug, "-");
 		return $slug;
 		return $slug;
 	}
 	}
 
 
-	public static function getDisplayFileSize($size) {
+	/**
+	 * @param string $string
+	 * @param int $id
+	 * @return string
+	 */
+	public static function slugWithId(string $string, int $id): string {
+		return Util::slug($string) . "-" . $id;
+	}
+
+	/**
+	 * @param int $size
+	 * @return string
+	 */
+	public static function getDisplayFileSize(int $size): string {
 		if($size < pow(2, 10)) return number_format($size) . " bytes";
 		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, 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, 30)) return number_format($size / pow(2, 20), 2) . " MB";
@@ -88,7 +135,12 @@ class Util {
 		return number_format($size / pow(2, 40), 2) . " TB";
 		return number_format($size / pow(2, 40), 2) . " TB";
 	}
 	}
 
 
-	public static function timeDifference($unix_time, $options = []) {
+	/**
+	 * @param int $unix_time
+	 * @param array $options
+	 * @return string
+	 */
+	public static function timeDifference(int $unix_time, $options = []): string {
 
 
 		$plain = $options["plain"] ?? false;
 		$plain = $options["plain"] ?? false;
 
 
@@ -141,7 +193,11 @@ class Util {
 
 
 	}
 	}
 
 
-	public static function getTimeZones() {
+	/**
+	 * @return array
+	 * @throws Exception
+	 */
+	public static function getTimeZones(): array {
 
 
 		// Taken and modified from: https://stackoverflow.com/a/17355238
 		// Taken and modified from: https://stackoverflow.com/a/17355238
 
 
@@ -202,25 +258,46 @@ class Util {
 		return $time_zone_list;
 		return $time_zone_list;
 	}
 	}
 
 
-	public static function getDate($time = false) {
+	/**
+	 * @param bool $time
+	 * @return string
+	 */
+	public static function getDate($time = false): string {
 		if(!$time) $time = time();
 		if(!$time) $time = time();
 		return gmdate("Y-m-d", $time);
 		return gmdate("Y-m-d", $time);
 	}
 	}
 
 
-	public static function getUTCDateTime($time = false) {
+	/**
+	 * @param bool $time
+	 * @return string
+	 */
+	public static function getUTCDateTime($time = false): string {
 		return Util::getDateTime($time);
 		return Util::getDateTime($time);
 	}
 	}
 
 
-	public static function getDateTime($time = false) {
+	/**
+	 * @param bool $time
+	 * @return string
+	 */
+	public static function getDateTime($time = false): string {
 		if(!$time) $time = time();
 		if(!$time) $time = time();
 		return gmdate("Y-m-d H:i:s", $time);
 		return gmdate("Y-m-d H:i:s", $time);
 	}
 	}
 
 
-	public static function getUnixTimeFromUTC($dts) {
+	/**
+	 * @param string $dts
+	 * @return false|int
+	 */
+	public static function getUnixTimeFromUTC(string $dts) {
 		return strtotime($dts . " UTC");
 		return strtotime($dts . " UTC");
 	}
 	}
 
 
-	public static function getDurationFromDTS($dts1, $dts2) {
+	/**
+	 * @param string $dts1
+	 * @param string $dts2
+	 * @return float|int
+	 */
+	public static function getDurationFromDTS(string $dts1, string $dts2) {
 		$tz = date_default_timezone_get();
 		$tz = date_default_timezone_get();
 		date_default_timezone_set("UTC");
 		date_default_timezone_set("UTC");
 
 
@@ -232,7 +309,11 @@ class Util {
 		return abs($t2 - $t1);
 		return abs($t2 - $t1);
 	}
 	}
 
 
-	public static function getDisplayDateTime($time = false) {
+	/**
+	 * @param int|bool $time
+	 * @return string
+	 */
+	public static function getDisplayDateTime($time = false): string {
 		if($time === false) $time = time();
 		if($time === false) $time = time();
 
 
 		$current_year = date("Y");
 		$current_year = date("Y");
@@ -243,7 +324,11 @@ class Util {
 		return date($format, $time);
 		return date($format, $time);
 	}
 	}
 
 
-	public static function getDisplayDate($time = false) {
+	/**
+	 * @param int|bool $time
+	 * @return string
+	 */
+	public static function getDisplayDate($time = false): string {
 		if($time === false) $time = time();
 		if($time === false) $time = time();
 
 
 		$current_year = date("Y");
 		$current_year = date("Y");
@@ -254,17 +339,27 @@ class Util {
 		return date($format, $time);
 		return date($format, $time);
 	}
 	}
 
 
-	public static function getDisplayDateTimeFromUTC($dts) {
+	/**
+	 * @param string $dts
+	 * @return string
+	 */
+	public static function getDisplayDateTimeFromUTC(string $dts): string {
 		$unix = Util::getUnixTimeFromUTC($dts);
 		$unix = Util::getUnixTimeFromUTC($dts);
 		return Util::getDisplayDateTime($unix);
 		return Util::getDisplayDateTime($unix);
 	}
 	}
 
 
-	public static function sortObjectArray($array, $field, $compare_function = "") {
+	/**
+	 * @param array $array
+	 * @param string $field
+	 * @param string $compare_function
+	 * @return array
+	 */
+	public static function sortObjectArray(array $array, string $field, string $compare_function = ""): array {
 
 
 		usort($array, function($a, $b) use ($compare_function, $field) {
 		usort($array, function($a, $b) use ($compare_function, $field) {
 
 
 			switch($compare_function) {
 			switch($compare_function) {
-				case "":
+				default:
 					if($a->$field == $b->$field) return 0;
 					if($a->$field == $b->$field) return 0;
 					return ($a->$field < $b->$field) ? -1 : 1;
 					return ($a->$field < $b->$field) ? -1 : 1;
 				case "strnatcasecmp":
 				case "strnatcasecmp":
@@ -275,7 +370,11 @@ class Util {
 		return $array;
 		return $array;
 	}
 	}
 
 
-	public static function arrayFlipByID($input = []) {
+	/**
+	 * @param array $input
+	 * @return array
+	 */
+	public static function arrayFlipByID(array $input = []): array {
 		$output = [];
 		$output = [];
 
 
 		foreach($input as $object) {
 		foreach($input as $object) {
@@ -285,141 +384,4 @@ class Util {
 		return $output;
 		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;
-	}
-}
+}

+ 13 - 1
engine/venue_type.php

@@ -1,5 +1,12 @@
 <?php
 <?php
 
 
+/**
+ * Class VenueType
+ *
+ * @property int $id
+ * @property string $name
+ */
+
 class VenueType extends Model {
 class VenueType extends Model {
 
 
 	protected static $table = "venue_type";
 	protected static $table = "venue_type";
@@ -7,7 +14,12 @@ class VenueType extends Model {
 	protected static $fillable_fields = ["name"];
 	protected static $fillable_fields = ["name"];
 
 
 	// Static methods
 	// Static methods
-	public static function getAll() {
+
+	/**
+	 * @return VenueType[]
+	 * @throws Exception
+	 */
+	public static function getAll(): array {
 		return self::query([], ["sort" => "name"]);
 		return self::query([], ["sort" => "name"]);
 	}
 	}
 
 

+ 14 - 3
engine/view.php

@@ -4,11 +4,17 @@ class View {
 
 
 	protected static $included = [];
 	protected static $included = [];
 
 
-	public static function include($view, $params = []) {
+	/**
+	 * @param string $view
+	 * @param array $params
+	 * @throws Exception
+	 */
+	public static function include(string $view, array $params = []) {
 		$view_path = ROOT_DIR . "/views/" . $view . ".php";
 		$view_path = ROOT_DIR . "/views/" . $view . ".php";
 		if(file_exists($view_path)) {
 		if(file_exists($view_path)) {
 			self::$included[] = $view;
 			self::$included[] = $view;
 			extract($params);
 			extract($params);
+			/** @noinspection PhpIncludeInspection */
 			require $view_path;
 			require $view_path;
 		}
 		}
 		else {
 		else {
@@ -16,8 +22,13 @@ class View {
 		}
 		}
 	}
 	}
 
 
-	public static function includeOnce($view, $params = []) {
+	/**
+	 * @param string $view
+	 * @param array $params
+	 * @throws Exception
+	 */
+	public static function includeOnce(string $view, array $params = []) {
 		if(in_array($view, self::$included)) return;
 		if(in_array($view, self::$included)) return;
 		self::include($view, $params);
 		self::include($view, $params);
 	}
 	}
-}
+}

+ 73 - 0
export_processing/project_quickbooks_customer_csv.php

@@ -0,0 +1,73 @@
+<?php
+
+/**
+ * @var Project[] $projects
+ */
+
+$utc_timezone = new DateTimeZone("UTC");
+$invoice_interval = new DateInterval("P30D");
+
+$current_dt = new DateTime();
+$date = $current_dt->format("d/m/Y");
+
+$field_names = [
+	"Invoice No",
+	"Customer",
+	"Invoice Date",
+	"Due Date",
+	"Terms",
+	"Location",
+	"Memo",
+	"Item (Product/Service)",
+	"Item Description",
+	"Item Quantity",
+	"Item Rate",
+	"Item Amount",
+	"Item Tax Code",
+	"Item Tax Amount",
+	"Service Date",
+];
+
+fputcsv($handle, $field_names);
+
+foreach($projects as $project) {
+
+    if($project->dts_finished === null) continue;
+
+    $customer = $project->getCustomer();
+
+    $invoice = $project->getCustomerInvoice();
+    $line_items = $invoice->getLineItems();
+
+    $invoice_generated_dt = new DateTime($project->dts_finished, $utc_timezone);
+    $invoice_date = $invoice_generated_dt->format("d/m/Y");
+
+    $invoice_generated_dt->add($invoice_interval);
+	$invoice_due_date = $invoice_generated_dt->format("d/m/Y");
+
+	$time_text = $project->getTimeOfDayText();
+
+    foreach($line_items as $item) {
+
+		$output = [];
+
+		$output[] = $invoice->getReference(); // "Invoice No",
+		$output[] = $customer->name; // "Customer",
+		$output[] = $invoice_date; // "Invoice Date",
+		$output[] = $invoice_due_date; // "Due Date",
+		$output[] = "Net 30"; // "Terms",
+		$output[] = ""; // "Location",
+		$output[] = "{$project->id} {$project->name} ({$time_text})"; // "Memo",
+		$output[] = $item->getName(); // "Item (Product/Service)",
+		$output[] = ""; // "Item Description",
+		$output[] = $item->getQuantity() ?: "1"; // "Item Quantity",
+		$output[] = $item->getPrice(); // "Item Rate",
+		$output[] = $item->getTotal(); // "Item Amount",
+		$output[] = ($invoice->getTaxRate() * 100) . "%"; // "Item Tax Code",
+		$output[] = $invoice->getTaxRate() * $item->getTotal(); // "Item Tax Amount",
+		$output[] = $date; // "Service Date",
+
+		fputcsv($handle, $output);
+
+    }
+}

+ 60 - 0
export_processing/project_quickbooks_tester_csv.php

@@ -0,0 +1,60 @@
+<?php
+
+$utc_timezone = new DateTimeZone("UTC");
+$invoice_interval = new DateInterval("P30D");
+
+$field_names = [
+	"BillNo",
+	"Supplier",
+	"BillDate",
+	"DueDate",
+	"Terms",
+	"Location",
+	"Memo",
+	"Account",
+	"LineDescription",
+	"LineAmount",
+	"LineTaxCode",
+	"LineTaxAmount",
+];
+
+fputcsv($handle, $field_names);
+
+foreach($tests as $test) {
+
+    if($test->dts_tester_invoice_paid === null) continue;
+
+    $project = $test->getProject();
+    $template = $project->getTemplate();
+	$location = $test->getLocation();
+	$tester = $test->getTester();
+	$values = $test->getValues(true);
+
+    $test_cost = $test->test_fee > 0 ? $test->test_fee : $project->default_tester_fee;
+    $travel_costs = $test->test_travel_cost > 0 ? $test->test_travel_cost : 0;
+    $other_costs = $template->getTesterInvoiceCosts($values);
+
+    $total_cost = $test_cost + $travel_costs + $other_costs;
+
+    $invoice_generated_dt = new DateTime($test->dts_tester_invoice_generated, $utc_timezone);
+    $invoice_date = $invoice_generated_dt->format("d/m/Y");
+
+    $invoice_generated_dt->add($invoice_interval);
+    $invoice_due_date = $invoice_generated_dt->format("d/m/Y");
+
+	$output = [];
+	$output[] = $test->getTesterInvoiceReference();
+	$output[] = sprintf("%d %s %s", $tester->id, $tester->first_name, $tester->last_name);
+	$output[] = $invoice_date;
+	$output[] = $invoice_due_date;
+	$output[] = "Net 30";
+	$output[] = "";
+	$output[] = "$location->id $location->name";
+	$output[] = "Tester Fees";
+	$output[] = "";
+	$output[] = $total_cost;
+	$output[] = "No VAT";
+	$output[] = "0";
+
+	fputcsv($handle, $output);
+}

BIN
locales/en_GB/LC_MESSAGES/en_GB.mo


File diff suppressed because it is too large
+ 290 - 295
locales/en_GB/LC_MESSAGES/en_GB.po


BIN
locales/es_ES/LC_MESSAGES/es_ES.mo


File diff suppressed because it is too large
+ 246 - 270
locales/es_ES/LC_MESSAGES/es_ES.po


BIN
locales/nl_NL/LC_MESSAGES/nl_NL.mo


File diff suppressed because it is too large
+ 218 - 251
locales/nl_NL/LC_MESSAGES/nl_NL.po


File diff suppressed because it is too large
+ 365 - 201
package-lock.json


+ 14 - 8
package.json

@@ -14,26 +14,32 @@
   "license": "ISC",
   "license": "ISC",
   "dependencies": {
   "dependencies": {
     "@google/markerclusterer": "^1.0.3",
     "@google/markerclusterer": "^1.0.3",
-    "bootstrap": "^4.2.1",
-    "chart.js": "^2.7.3",
+    "bootstrap": "^4.3.1",
+    "chart.js": "^2.8.0",
     "chartjs-plugin-datalabels": "^0.6.0",
     "chartjs-plugin-datalabels": "^0.6.0",
     "clipboard": "^2.0.4",
     "clipboard": "^2.0.4",
     "datatables.net-bs4": "^1.10.19",
     "datatables.net-bs4": "^1.10.19",
     "datatables.net-buttons-bs4": "^1.5.6",
     "datatables.net-buttons-bs4": "^1.5.6",
     "datatables.net-responsive-bs4": "^2.2.3",
     "datatables.net-responsive-bs4": "^2.2.3",
     "daterangepicker": "^3.0.5",
     "daterangepicker": "^3.0.5",
-    "gulp": "^4.0.1",
-    "gulp-autoprefixer": "^6.1.0",
+    "gulp": "^4.0.2",
+    "gulp-autoprefixer": "^7.0.0",
     "gulp-clean-css": "^4.2.0",
     "gulp-clean-css": "^4.2.0",
     "gulp-rename": "^1.4.0",
     "gulp-rename": "^1.4.0",
     "gulp-sass": "^4.0.2",
     "gulp-sass": "^4.0.2",
     "holderjs": "^2.9.6",
     "holderjs": "^2.9.6",
     "jquery": "^3.4.1",
     "jquery": "^3.4.1",
-    "popper.js": "^1.14.6"
+    "popper.js": "^1.15.0"
   },
   },
   "devDependencies": {
   "devDependencies": {
-    "@fortawesome/fontawesome-pro": "^5.8.1",
+    "@fortawesome/fontawesome-pro": "^5.10.2",
     "cross-env": "^5.2.0",
     "cross-env": "^5.2.0",
-    "laravel-mix": "^4.0.15"
-  }
+    "laravel-mix": "^4.1.2"
+  },
+  "browserslist": [
+    "last 1 version",
+    "> 1%",
+    "maintained node versions",
+    "not dead"
+  ]
 }
 }

File diff suppressed because it is too large
+ 3 - 3
public/css/bootstrap.min.css


File diff suppressed because it is too large
+ 4 - 7
public/js/Chart.bundle.min.js


File diff suppressed because it is too large
+ 1 - 1
public/js/all.min.js


+ 10 - 0
public/js/app-projects.js

@@ -22,6 +22,16 @@ $(function() {
 				$("#projects-form").attr("action", "/account/projects/export-csv");
 				$("#projects-form").attr("action", "/account/projects/export-csv");
 				$("#type").val("customer");
 				$("#type").val("customer");
 				break;
 				break;
+
+			case "export-quickbooks-customer-csv":
+				$("#projects-form").attr("action", "/account/projects/export-csv");
+				$("#type").val("quickbooks-customer");
+				break;
+
+			case "export-quickbooks-tester-csv":
+				$("#projects-form").attr("action", "/account/projects/export-csv");
+				$("#type").val("quickbooks-tester");
+				break;
 		}
 		}
 	});
 	});
 
 

File diff suppressed because it is too large
+ 2 - 2
public/js/bootstrap.min.js


File diff suppressed because it is too large
+ 0 - 0
public/js/bootstrap.min.js.map


File diff suppressed because it is too large
+ 1 - 1
public/js/popper.min.js


File diff suppressed because it is too large
+ 0 - 0
public/js/popper.min.js.map


+ 8 - 2
routes.php

@@ -65,12 +65,17 @@ $routes = [
 	"/^account\/projects\/$id_pattern\/edit$/" => ["controller" => "project_edit", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/edit$/" => ["controller" => "project_edit", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/edit\/template-overrides$/" => ["controller" => "project_edit_template_overrides", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/edit\/template-overrides$/" => ["controller" => "project_edit_template_overrides", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/export-csv$/" => ["controller" => "project_export", "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/export-csv$/" => ["controller" => "project_export", "require_user_level" => User::LEVEL_ADMIN],
-	"/^account\/projects\/$id_pattern\/export-(admin|customer)-csv$/" => ["controller" => "project_export", "params" => ["id", "type"], "require_user_level" => User::LEVEL_ADMIN],
+	"/^account\/projects\/$id_pattern\/export-(admin|customer|quickbooks)-csv$/" => ["controller" => "project_export", "params" => ["id", "type"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/export-kml$/" => ["controller" => "project_kml", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/export-kml$/" => ["controller" => "project_kml", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/invoice$/" => ["controller" => "project_invoice", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/invoice$/" => ["controller" => "project_invoice", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/(mark-finished|mark-unfinished)$/" => ["controller" => "project_mark_finished", "params" => ["id", "action"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/(mark-finished|mark-unfinished)$/" => ["controller" => "project_mark_finished", "params" => ["id", "action"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/(get-locations|get-testers|create-test|assign-tester)$/" => ["controller" => "project_ajax", "params" => ["id", "action"], "type" => "json", "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/projects\/$id_pattern\/(get-locations|get-testers|create-test|assign-tester)$/" => ["controller" => "project_ajax", "params" => ["id", "action"], "type" => "json", "require_user_level" => User::LEVEL_ADMIN],
 
 
+	// Test Results
+	"/^account\/test-results$/" => ["controller" => "test_results_customer_list"],
+	"/^account\/test-results\/{$slug_id_pattern}$/" => ["controller" => "test_results_project_list", "params" => ["customer_id"]],
+	"/^account\/test-results\/{$slug_id_pattern}\/{$slug_id_pattern}$/" => ["controller" => "test_results_test_list", "params" => ["customer_id", "project_id"]],
+
 	// Tests
 	// Tests
 	"/^account\/tests$/" => ["controller" => "tests", "require_user_level" => User::LEVEL_TESTER],
 	"/^account\/tests$/" => ["controller" => "tests", "require_user_level" => User::LEVEL_TESTER],
 	"/^account\/tests\/postal\-codes$/" => ["controller" => "tests_tester_postal_codes", "require_user_level" => User::LEVEL_TESTER],
 	"/^account\/tests\/postal\-codes$/" => ["controller" => "tests_tester_postal_codes", "require_user_level" => User::LEVEL_TESTER],
@@ -79,6 +84,7 @@ $routes = [
 	"/^account\/tests\/completed$/" => ["controller" => "tests_completed", "require_user_level" => User::LEVEL_TESTER],
 	"/^account\/tests\/completed$/" => ["controller" => "tests_completed", "require_user_level" => User::LEVEL_TESTER],
 	"/^account\/tests\/$id_pattern$/" => ["controller" => "test", "params" => ["id"], "require_user_level" => User::LEVEL_TESTER],
 	"/^account\/tests\/$id_pattern$/" => ["controller" => "test", "params" => ["id"], "require_user_level" => User::LEVEL_TESTER],
 	"/^account\/tests\/$id_pattern\/(selfie)$/" => ["controller" => "test_file", "params" => ["id", "name"], "require_user_level" => User::LEVEL_TESTER],
 	"/^account\/tests\/$id_pattern\/(selfie)$/" => ["controller" => "test_file", "params" => ["id", "name"], "require_user_level" => User::LEVEL_TESTER],
+	"/^account\/tests\/$id_pattern\/files\/(pdf)$/" => ["controller" => "test_file", "params" => ["id", "name"], "require_user_level" => User::LEVEL_CUSTOMER],
 	"/^account\/tests\/$id_pattern\/files\/([a-z_]+)$/" => ["controller" => "test_file", "params" => ["id", "name"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/tests\/$id_pattern\/files\/([a-z_]+)$/" => ["controller" => "test_file", "params" => ["id", "name"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/tests\/$id_pattern\/result$/" => ["controller" => "test_result", "params" => ["id"], "require_user_level" => User::LEVEL_VENUE],
 	"/^account\/tests\/$id_pattern\/result$/" => ["controller" => "test_result", "params" => ["id"], "require_user_level" => User::LEVEL_VENUE],
 	"/^account\/tests\/$id_pattern\/pdf$/" => ["controller" => "test_pdf", "params" => ["id"], "require_user_level" => User::LEVEL_VENUE],
 	"/^account\/tests\/$id_pattern\/pdf$/" => ["controller" => "test_pdf", "params" => ["id"], "require_user_level" => User::LEVEL_VENUE],
@@ -121,7 +127,7 @@ $routes = [
 	"/^account\/customers\/$id_pattern$/" => ["controller" => "customer_view", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/customers\/$id_pattern$/" => ["controller" => "customer_view", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/customers\/$id_pattern\/edit$/" => ["controller" => "customer_edit", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 	"/^account\/customers\/$id_pattern\/edit$/" => ["controller" => "customer_edit", "params" => ["id"], "require_user_level" => User::LEVEL_ADMIN],
 
 
-	"/^api\/customers\/$id_pattern\/(get-locations)$/" => ["controller" => "customer_ajax", "params" => ["id", "action"], "require_user_level" => User::LEVEL_ADMIN],
+	"/^api\/customers\/$id_pattern\/(get-locations)$/" => ["controller" => "customer_ajax", "params" => ["id", "action"], "require_user_level" => User::LEVEL_CUSTOMER],
 
 
 	// Practice
 	// Practice
 	"/^account\/practice$/" => ["controller" => "practice_template_select", "require_user_level" => User::LEVEL_TESTER],
 	"/^account\/practice$/" => ["controller" => "practice_template_select", "require_user_level" => User::LEVEL_TESTER],

+ 12 - 1
views/customer_select.php

@@ -8,6 +8,17 @@
 	$uri_parts = explode("?", $uri);
 	$uri_parts = explode("?", $uri);
 	$path = array_shift($uri_parts);
 	$path = array_shift($uri_parts);
 
 
+	if(Core::$user->isAdmin() && Core::$allow_all_customers) {
+		$query = $_GET;
+		unset($query["path"]);
+		$query["customer_id"] = "ALL";
+		?>
+		<a class="list-group-item list-group-item-action" href="<?=htmlspecialchars($path)?>?<?=http_build_query($query)?>">
+			<?=__("All")?>
+		</a>
+		<?php
+	}
+
 	foreach($customers as $customer) {
 	foreach($customers as $customer) {
 		$query = $_GET;
 		$query = $_GET;
 		unset($query["path"]);
 		unset($query["path"]);
@@ -23,4 +34,4 @@
 	?>
 	?>
 	</div>
 	</div>
 
 
-</div>
+</div>

+ 16 - 92
views/location.php

@@ -1,9 +1,10 @@
 <?php
 <?php
-$tabs = [
-	["details", "Details"],
-	["photos", "Photos"],
-	["tests", "Tests"],
-];
+
+$tabs = [];
+$tabs[] = ["details", __("Details")];
+if(Core::$user->isAdmin()) $tabs[] = ["photos", __("Photos")];
+$tabs[] = ["tests", __("Tests")];
+if(Core::$user->isAdmin()) $tabs[] = ["log", __("Log")];
 
 
 $details = [
 $details = [
 	"ID" => $location->id,
 	"ID" => $location->id,
@@ -18,12 +19,10 @@ if($location->region) $details["Region"] = $location->region;
 if($location->internal_id) $details["Internal ID"] = $location->internal_id;
 if($location->internal_id) $details["Internal ID"] = $location->internal_id;
 if($location->area_manager) $details["Area Manager"] = $location->area_manager;
 if($location->area_manager) $details["Area Manager"] = $location->area_manager;
 
 
-$photos = $location->getPhotos();
 $venue_types = $location->getVenueTypes();
 $venue_types = $location->getVenueTypes();
 $type_names = array_column($venue_types, "name");
 $type_names = array_column($venue_types, "name");
 $type_names_csv = implode(", ", $type_names);
 $type_names_csv = implode(", ", $type_names);
 
 
-
 if($venue_types) $details["Types"] = $type_names_csv;
 if($venue_types) $details["Types"] = $type_names_csv;
 
 
 ?>
 ?>
@@ -86,94 +85,19 @@ if($venue_types) $details["Types"] = $type_names_csv;
 				</div>
 				</div>
 			</div>
 			</div>
 		</div>
 		</div>
-		<div class="tab-pane fade" id="photos" role="tabpanel" aria-labelledby="photos-tab">
+
 		<?php
 		<?php
-		if(empty($photos)) {
-			?>
-			<div class="alert alert-info">
-				<i class="fal fa-fw fa-info-circle"></i> No photos are available for this location.
-			</div>
-			<?php
+		if(Core::$user->isAdmin()) {
+			View::include("location_photos_tab", compact("location"));
 		}
 		}
-		else {
-			?>
-			<div class="row">
-			<?php
-			foreach($photos as $photo) {
-				$uri = "/account/locations/$location->id/photos/$photo->id";
-				?>
-				<div class="col-md-4">
-					<a href="<?=$uri?>">
-						<img class="border img-fluid img-contain" src="/img/blank_4_3.png" style="background-image: url(<?=$uri?>)" />
-					</a>
-				</div>
-				<?php
-			}
-			?>
-			</div>
-			<?php
+
+		View::include("location_tests_tab", compact("location"));
+
+		if(Core::$user->isAdmin()) {
+			View::include("location_log_tab", compact("location"));
 		}
 		}
 		?>
 		?>
-		</div>
-		<div class="tab-pane fade" id="tests" role="tabpanel" aria-labelledby="tests-tab">
-			<?php
-			if(empty($tests)) {
-				?>
-				<div class="alert alert-info">
-					This location has no tests.
-				</div>
-				<?php
-			}
-			else {
-				?>
-				<table class="table table-hover">
-					<thead>
-						<tr>
-							<th>ID</th>
-							<th>Project</th>
-							<th>Status</th>
-							<th></th>
-						</tr>
-					</thead>
-					<tbody>
-					<?php
-					foreach($tests as $test) {
-						$project = $test->getProject();
-						?>
-						<tr>
-							<td class="text-right align-middle">
-								<?=$test->id?>
-							</td>
-							<td class="align-middle">
-								<a href="/account/projects/<?=$project->id?>"><?=htmlspecialchars($project->name)?></a>
-							</td>
-							<td class="align-middle">
-								<span class="badge badge-lg badge-<?=$test->getStatusClass()?>"><?=htmlspecialchars($test->getStatusText())?></span>
-							</td>
-							<td class="text-right">
-							<?php
-							if($test->status >= Test::STATUS_PENDING_VERIFICATION) {
-								?>
-								<a class="btn btn-outline-primary" href="/account/tests/<?=$test->id?>">View Results</a>
-								<?php
-							}
-							else {
-								?>
-								<a class="btn btn-outline-primary" href="/account/projects/<?=$test->project_id?>">View Project</a>
-								<?php
-							}
-							?>
-							</td>
-						</tr>
-						<?php
-					}
-					?>
-					</tbody>
-				</table>
-				<?php
-			}
-			?>
-		</div>
+
 	</div>
 	</div>
 
 
-</div>
+</div>

+ 57 - 48
views/location_form.php

@@ -1,9 +1,12 @@
 <?php
 <?php
 $tabs = [
 $tabs = [
 	["details", "Details"],
 	["details", "Details"],
-	["photos", "Photos"],
 ];
 ];
 
 
+if(Core::$user->isAdmin()) {
+	$tabs[] = ["photos", "Photos"];
+}
+
 $venue_types = VenueType::getAll();
 $venue_types = VenueType::getAll();
 $venue_type_count = count($venue_types);
 $venue_type_count = count($venue_types);
 $venue_type_columns = array_chunk($venue_types, ceil($venue_type_count / 2));
 $venue_type_columns = array_chunk($venue_types, ceil($venue_type_count / 2));
@@ -122,7 +125,7 @@ if($location->id) {
 									<input class="form-check-input" type="checkbox" name="closed" id="closed" value="1" <?=Form::checked($location->closed)?> />
 									<input class="form-check-input" type="checkbox" name="closed" id="closed" value="1" <?=Form::checked($location->closed)?> />
 									<label for="closed">Closed</label>
 									<label for="closed">Closed</label>
 								</div>
 								</div>
-								<small class="text-muted form-text">By marking a location as closed, they will no longer appear for selection in new Projects.</small>
+								<small class="text-muted form-text">By marking a location as closed, the location will be unable to be selected for any new tests.</small>
 							</div>
 							</div>
 						</div>
 						</div>
 					</div>
 					</div>
@@ -139,7 +142,7 @@ if($location->id) {
 						}
 						}
 						else {
 						else {
 							?>
 							?>
-							<div class="mb-3" id="map" style="height: 330px;" data-maps data-lat="<?=$location->latitude?>" data-lng="<?=$location->longitude?>" data-zoom="14" data-marker="true" data-marker-draggable="true" data-marker-dragend-target="#map-data"></div>
+							<div class="mb-3" id="map" style="height: 330px;" data-maps data-lat="<?=$location->latitude?>" data-lng="<?=$location->longitude?>" data-zoom="15" data-marker="true" data-marker-draggable="true" data-marker-dragend-target="#map-data"></div>
 
 
 							<div id="map-data">
 							<div id="map-data">
 								<input type="hidden" name="latitude" data-latitude value="<?=$location->latitude?>" />
 								<input type="hidden" name="latitude" data-latitude value="<?=$location->latitude?>" />
@@ -212,72 +215,78 @@ if($location->id) {
 				</div>
 				</div>
 			</div>
 			</div>
 
 
-			<div class="tab-pane fade" id="photos" role="tabpanel" aria-labelledby="photos-tab">
-				<div class="row">
-					<div class="col-lg">
-						<div class="row mb-1">
-							<label class="col-sm-4 col-form-label" for="shop-left">Shop Name (Left)</label>
-							<div class="col-sm">
-								<input class="form-control" type="text" name="shop_left" id="shop-left" placeholder="Enter shop name (left)" value="<?=htmlspecialchars($location->shop_left)?>" />
+			<?php
+			if(Core::$user->isAdmin()) {
+				?>
+
+				<div class="tab-pane fade" id="photos" role="tabpanel" aria-labelledby="photos-tab">
+					<div class="row">
+						<div class="col-lg">
+							<div class="row mb-1">
+								<label class="col-sm-4 col-form-label" for="shop-left">Shop Name (Left)</label>
+								<div class="col-sm">
+									<input class="form-control" type="text" name="shop_left" id="shop-left" placeholder="Enter shop name (left)" value="<?=htmlspecialchars($location->shop_left)?>" />
+								</div>
 							</div>
 							</div>
-						</div>
-						<div class="row mb-1">
-							<label class="col-sm-4 col-form-label" for="shop-right">Shop Name (Right)</label>
-							<div class="col-sm">
-								<input class="form-control" type="text" name="shop_right" id="shop-right" placeholder="Enter shop name (right)" value="<?=htmlspecialchars($location->shop_right)?>" />
+							<div class="row mb-1">
+								<label class="col-sm-4 col-form-label" for="shop-right">Shop Name (Right)</label>
+								<div class="col-sm">
+									<input class="form-control" type="text" name="shop_right" id="shop-right" placeholder="Enter shop name (right)" value="<?=htmlspecialchars($location->shop_right)?>" />
+								</div>
 							</div>
 							</div>
-						</div>
 
 
-					</div>
-					<div class="col-lg">
-					<?php
-					if($location->id) {
-						?>
-						<div class="row mb-3">
-							<label class="col-sm-4 col-form-label" for="photo">JPEG File</label>
-							<div class="col-sm">
-								<input class="form-control-file" type="file" name="photo" id="photo" />
-							</div>
 						</div>
 						</div>
+						<div class="col-lg">
 						<?php
 						<?php
-						if(!empty($photos)) {
+						if($location->id) {
 							?>
 							?>
-							<h3>Manage Photos</h3>
-
-							<div class="row">
+							<div class="row mb-3">
+								<label class="col-sm-4 col-form-label" for="photo">JPEG File</label>
+								<div class="col-sm">
+									<input class="form-control-file" type="file" name="photo" id="photo" />
+								</div>
+							</div>
 							<?php
 							<?php
-							foreach($photos as $photo) {
+							if(!empty($photos)) {
 								?>
 								?>
-								<div class="col-md-6">
-									<div class="card">
-										<img class="card-img-top img-cover" src="/img/blank_4_3.png" alt="Photo" style="background-image: url(/account/locations/6/photos/<?=$photo->id?>)" />
-										<div class="card-body">
-											<div class="form-check">
-												<input class="form-check-input" type="checkbox" name="delete_file_ids[]" id="photo-<?=$photo->id?>" value="<?=$photo->id?>" />
-												<label class="form-check-label" for="photo-<?=$photo->id?>">Delete</label>
+								<h3>Manage Photos</h3>
+
+								<div class="row">
+								<?php
+								foreach($photos as $photo) {
+									?>
+									<div class="col-md-6">
+										<div class="card">
+											<img class="card-img-top img-cover" src="/img/blank_4_3.png" alt="Photo" style="background-image: url(/account/locations/6/photos/<?=$photo->id?>)" />
+											<div class="card-body">
+												<div class="form-check">
+													<input class="form-check-input" type="checkbox" name="delete_file_ids[]" id="photo-<?=$photo->id?>" value="<?=$photo->id?>" />
+													<label class="form-check-label" for="photo-<?=$photo->id?>">Delete</label>
+												</div>
 											</div>
 											</div>
 										</div>
 										</div>
 									</div>
 									</div>
+									<?php
+								}
+								?>
 								</div>
 								</div>
 								<?php
 								<?php
 							}
 							}
+						}
+						else {
 							?>
 							?>
+							<div class="alert alert-info">
+								<i class="fal fa-fw fa-info-circle"></i> Adding photos will become available when location is added.
 							</div>
 							</div>
 							<?php
 							<?php
 						}
 						}
-					}
-					else {
 						?>
 						?>
-						<div class="alert alert-info">
-							<i class="fal fa-fw fa-info-circle"></i> Adding photos will become available when location is added.
 						</div>
 						</div>
-						<?php
-					}
-					?>
 					</div>
 					</div>
 				</div>
 				</div>
-			</div>
-
+				<?php
+			}
+			?>
 		</div>
 		</div>
 
 
 		<div class="row">
 		<div class="row">
@@ -293,4 +302,4 @@ if($location->id) {
 		</div>
 		</div>
 
 
 	</form>
 	</form>
-</div>
+</div>

+ 57 - 0
views/location_log_tab.php

@@ -0,0 +1,57 @@
+
+<?php
+/**
+ * @var Location $location
+ */
+
+$entries = $location->getUpdateLogEntries();
+
+?>
+<div class="tab-pane fade" id="log" role="tabpanel" aria-labelledby="log-tab">
+<?php
+if(empty($entries)) {
+    ?>
+    <div class="alert alert-info">
+        <i class="fal fa-fw fa-info-circle"></i> No log entries to display for this location.
+    </div>
+    <?php
+}
+else {
+    ?>
+    <table class="table table-sm table-bordered">
+        <thead>
+            <tr>
+                <th>Date/Time</th>
+                <th>User</th>
+                <th>Field</th>
+                <th>Before</th>
+                <th>After</th>
+            </tr>
+        </thead>
+        <tbody>
+            <?php
+            foreach($entries as $entry) {
+                $user = $entry->getUser();
+                $dts = Util::getDisplayDateTimeFromUTC($entry->dts);
+                $modifications = $entry->getModifications();
+                foreach($modifications as $modification) {
+                    ?>
+                    <tr>
+                        <td><?=htmlspecialchars($dts)?></td>
+                        <td><a href="<?=htmlspecialchars($user->getURL())?>"><?=htmlspecialchars($user->email)?></a></td>
+                        <td class="text-monospace"><?=htmlspecialchars($modification->field)?></td>
+                        <td class="text-monospace"><?=htmlspecialchars($modification->before)?></td>
+                        <td class="text-monospace"><?=htmlspecialchars($modification->after)?></td>
+                    </tr>
+                    <?php
+                }
+                ?>
+                <?php
+            }
+            ?>
+        </tbody>
+    </table>
+    <?php
+}
+?>
+</div>

+ 38 - 0
views/location_photos_tab.php

@@ -0,0 +1,38 @@
+
+<?php
+/**
+ * @var Location $location
+ */
+
+$photos = $location->getPhotos();
+
+?>
+<div class="tab-pane fade" id="photos" role="tabpanel" aria-labelledby="photos-tab">
+<?php
+if(empty($photos)) {
+    ?>
+    <div class="alert alert-info">
+        <i class="fal fa-fw fa-info-circle"></i> No photos are available for this location.
+    </div>
+    <?php
+}
+else {
+    ?>
+    <div class="row">
+    <?php
+    foreach($photos as $photo) {
+        $uri = "/account/locations/$location->id/photos/$photo->id";
+        ?>
+        <div class="col-md-4">
+            <a href="<?=$uri?>">
+                <img class="border img-fluid img-contain" src="/img/blank_4_3.png" style="background-image: url(<?=$uri?>)" />
+            </a>
+        </div>
+        <?php
+    }
+    ?>
+    </div>
+    <?php
+}
+?>
+</div>

+ 162 - 0
views/location_tests_tab.php

@@ -0,0 +1,162 @@
+<?php
+/**
+ * @var Location $location
+ */
+
+if(Core::$user->isAdmin()) {
+    $tests = $location->getTests();
+}
+else {
+    $tests = $location->getCompletedTests();
+}
+
+?>
+
+<div class="tab-pane fade" id="tests" role="tabpanel" aria-labelledby="tests-tab">
+    <?php
+    if(empty($tests)) {
+        ?>
+        <div class="alert alert-info">
+            This location has no tests.
+        </div>
+        <?php
+    }
+    else {
+        ?>
+        <table class="table table-bordered table-hover">
+            <thead>
+                <tr>
+                    <th>ID</th>
+                    <?php
+                    if(Core::$user->isAdmin()) {
+                        ?>
+                        <th>Project</th>
+                        <?php
+                    }
+                    else {
+                        ?>
+                        <th>Date/Time</th>
+                        <?php
+                    }
+                    ?>
+                    <th>Status</th>
+                    <th>Result</th>
+                    <th>Challenge Stage</th>
+                    <th>PDF</th>
+                    <?php
+                    if(Core::$user->isAdmin()) {
+                        ?>
+                        <th>Actions</th>
+                        <?php
+                    }
+                    ?>
+                </tr>
+            </thead>
+            <tbody>
+            <?php
+            foreach($tests as $test) {
+                $project = $test->getProject();
+                $template = $project->getTemplate();
+                $has_pass_fail = $template->hasPassFail();
+
+                $pass_text = $test->getPassText();
+                $pass_class = $test->getPassClass();
+                $pass_icon = $test->getPassIcon();
+
+                $challenge_stage = $test->challenge_stage;
+                $challenge_stage_text = $test->getChallengeStageText();
+                ?>
+                <tr>
+                    <td class="text-right align-middle">
+                        <?=$test->id?>
+                    </td>
+                    <td>
+                        <?php
+                        if(Core::$user->isAdmin()) {
+                            ?>
+                            <a href="/account/projects/<?=$project->id?>"><?=htmlspecialchars($project->name)?></a>
+                            <?php
+                        }
+                        else {
+                            echo Util::getDisplayDateTimeFromUTC($test->dts_start);
+                        }
+                        ?>
+                    </td>
+                    <td class="text-center">
+                        <span class="badge badge-lg badge-<?=$test->getStatusClass()?>"><?=htmlspecialchars($test->getStatusText())?></span>
+                    </td>
+                    <td class="text-center">
+                    <?php
+                    if($has_pass_fail) {
+                        ?>
+                        <strong class="text-<?=$pass_class?>"><?=htmlspecialchars($pass_text)?></strong>
+                        <?php
+                    }
+                    else {
+                        echo htmlspecialchars(__("N/A"));
+                    }
+                    ?>
+                    </td>
+                    <td>
+                    <?php
+                    if($has_pass_fail) {
+                        if($test->isPending()) {
+                            ?>
+                            <?=htmlspecialchars(__("Pending"))?>
+                            <?php
+                        }
+                        else {
+                            ?>
+                            <strong class="text-<?=$pass_class?>"><?=htmlspecialchars(__("Stage %d", $challenge_stage))?></strong> -
+                            <?=htmlspecialchars($challenge_stage_text)?>
+                            <?php
+                        }
+                    }
+                    else {
+                        echo htmlspecialchars(__("N/A"));
+                    }
+                    ?>
+                    </td>
+                    <td>
+                    <?php
+                    if($test->hasPDF()) {
+                        $pdf_url = $test->getPDFUrl();
+                        ?>
+                        <a href="<?=htmlspecialchars($pdf_url)?>" target="_blank">View PDF</a>
+                        <?php
+                    }
+                    else {
+                        echo htmlspecialchars(__("No PDF available"));
+                    }
+                    ?>
+                    </td>
+                    <?php
+                    if(Core::$user->isAdmin()) {
+                        ?>
+                        <td>
+                        <?php
+                        if($test->status >= Test::STATUS_PENDING_VERIFICATION) {
+                            ?>
+                            <a href="/account/tests/<?=$test->id?>">View Results</a>
+                            <?php
+                        }
+                        else {
+                            ?>
+                            <a href="/account/projects/<?=$test->project_id?>">View Project</a>
+                            <?php
+                        }
+                        ?>
+                        </td>
+                        <?php
+                    }
+                    ?>
+                </tr>
+                <?php
+            }
+            ?>
+            </tbody>
+        </table>
+        <?php
+    }
+    ?>
+</div>

+ 27 - 3
views/projects.php

@@ -1,3 +1,8 @@
+<?php
+
+$report_months = array_reverse(Project::getReportMonths());
+
+?>
 <div class="container mt-3 py-4">
 <div class="container mt-3 py-4">
 
 
 	<div class="row">
 	<div class="row">
@@ -33,7 +38,7 @@
 			<form method="get">
 			<form method="get">
 				<div class="row">
 				<div class="row">
 					<div class="col-lg">
 					<div class="col-lg">
-						<input type="hidden" name="customer_id" value="<?=http::value("customer_id", "int")?>" />
+						<input type="hidden" name="customer_id" value="<?=htmlspecialchars($customer->id)?>" />
 						<div class="row mb-1">
 						<div class="row mb-1">
 							<label class="col-sm-4 col-form-label" for="id">ID</label>
 							<label class="col-sm-4 col-form-label" for="id">ID</label>
 							<div class="col-sm">
 							<div class="col-sm">
@@ -62,10 +67,27 @@
 								</select>
 								</select>
 							</div>
 							</div>
 						</div>
 						</div>
+                        <div class="row mb-1">
+                            <label for="report-month" class="col-sm-4 col-form-label"><?=htmlspecialchars(__("Report Month"))?></label>
+                            <div class="col-sm">
+                                <select class="form-control" name="report_month" id="report-month">
+                                    <option value=""><?=htmlspecialchars(__("Select Report Month"))?></option>
+                                    <?php
+                                    foreach($report_months as $value => $display) {
+                                        $selected = ($value == $report_month) ? "selected" : "";
+                                        ?>
+                                        <option value="<?=$value?>" <?=$selected?>><?=$display?></option>
+                                        <?php
+                                    }
+                                    ?>
+                                </select>
+                            </div>
+
+                        </div>
 						<div class="row">
 						<div class="row">
 							<div class="col-sm offset-sm-4">
 							<div class="col-sm offset-sm-4">
 								<button class="btn btn-primary" type="submit">Submit</button>
 								<button class="btn btn-primary" type="submit">Submit</button>
-								<a class="btn btn-secondary" href="/account/projects?customer_id=<?=$customer->id?>">Clear Filters</a>
+								<a class="btn btn-secondary" href="/account/projects?customer_id=<?=htmlspecialchars($customer->id)?>">Clear Filters</a>
 							</div>
 							</div>
 						</div>
 						</div>
 					</div>
 					</div>
@@ -91,6 +113,8 @@
 						<option value="">Select Action</option>
 						<option value="">Select Action</option>
 						<option value="export-admin-csv">Export CSV</option>
 						<option value="export-admin-csv">Export CSV</option>
 						<option value="export-customer-csv">Export Customer CSV</option>
 						<option value="export-customer-csv">Export Customer CSV</option>
+						<option value="export-quickbooks-customer-csv">Export Quickbooks Customer CSV</option>
+						<option value="export-quickbooks-tester-csv">Export Quickbooks Tester CSV</option>
 					</select>
 					</select>
 					<div class="input-group-append">
 					<div class="input-group-append">
 						<button type="submit" class="btn btn-primary" name="submit" value="<?=htmlspecialchars($_SESSION["csrf_token"])?>">
 						<button type="submit" class="btn btn-primary" name="submit" value="<?=htmlspecialchars($_SESSION["csrf_token"])?>">
@@ -101,4 +125,4 @@
 			</div>
 			</div>
 		</div>
 		</div>
 	</form>
 	</form>
-</div>
+</div>

+ 35 - 0
views/test_results_customer_list.php

@@ -0,0 +1,35 @@
+<div class="container mt-3 py-4">
+
+    <h2><?=htmlspecialchars(__("Test Results"))?></h2>
+
+    <h3><?=htmlspecialchars(__("Select Customer"))?></h3>
+
+    <?php
+
+    if(empty($customers)) {
+        ?>
+        <div class="alert alert-info">
+        <?php
+            echo __("No customers to display.");
+        ?>
+        </div>
+        <?php
+    }
+    else {
+        ?>
+        <div class="list-group">
+        <?php
+        foreach($customers as $customer) {
+            $url = $customer->getTestResultsUrl();
+            ?>
+            <a class="list-group-item list-group-item-action" href="<?=htmlspecialchars($url)?>">
+                <?=htmlspecialchars($customer->name)?>
+            </a>
+            <?php
+        }
+        ?>
+        </div>
+        <?php
+    }
+    ?>
+</div>

+ 60 - 0
views/test_results_project_list.php

@@ -0,0 +1,60 @@
+<?php
+/**
+ * @var Project[] $projects
+ */
+?>
+<div class="container mt-3 py-4">
+
+    <h2><?=htmlspecialchars(__("Test Results"))?></h2>
+
+    <h3><?=htmlspecialchars(__("Select Project"))?></h3>
+
+    <?php
+
+    if(empty($projects)) {
+        ?>
+        <div class="alert alert-info">
+        <?php
+            echo __("No projects to display.");
+        ?>
+        </div>
+        <?php
+    }
+    else {
+        ?>
+
+        <table class="table table-bordered">
+            <col style="width: 40%;">
+            <col style="width: 15%;">
+            <col style="width: 15%;">
+            <col style="width: 15%;">
+            <col style="width: 15%;">
+            <thead>
+                <th><?=htmlspecialchars(__("Name"))?></th>
+                <th><?=htmlspecialchars(__("Report Month"))?></th>
+                <th><?=htmlspecialchars(__("Test Count"))?></th>
+                <th><?=htmlspecialchars(__("Pass / Fail"))?></th>
+                <th><?=htmlspecialchars(__("Pass Rate"))?></th>
+            </thead>
+            <tbody>
+            <?php
+            foreach($projects as $project) {
+                $url = $project->getTestResultsUrl();
+                ?>
+                <tr>
+                    <td><a href="<?=htmlspecialchars($url)?>"><?=$project->getNameHtml()?></a></td>
+                    <td><?=$project->getDisplayReportMonth()?></td>
+                    <td><?=$project->getTestCount()?></td>
+                    <td><?=$project->getPassCount()?> / <?=$project->getFailCount()?></td>
+                    <td><?=$project->getPassRate()?></td>
+                </tr>
+                <?php
+            }
+            ?>
+            </tbody>
+        </table>
+
+        <?php
+    }
+    ?>
+</div>

+ 142 - 0
views/test_results_test_list.php

@@ -0,0 +1,142 @@
+<?php
+/**
+ * @var Test[] $tests
+ */
+?>
+<div class="container mt-3 py-4">
+
+    <h2><?=htmlspecialchars(__("%s Test Results", $project->name))?></h2>
+
+    <?php
+
+    if(empty($tests)) {
+        ?>
+        <div class="alert alert-info">
+        <?php
+            echo __("No tests to display.");
+        ?>
+        </div>
+        <?php
+    }
+    else {
+
+        ?>
+        <div class="row">
+            <div class="col-3">
+                <div class="card mb-3">
+                    <div class="card-body">
+                        Test Count
+                        <div class="stat">
+                            <?=$test_count?>
+                        </div>
+                    </div>
+                </div>
+            </div>
+            <div class="col">
+            <?php
+
+            if($has_pass_fail) {
+                ?>
+                <div class="card mb-3">
+                    <div class="card-body">
+                        Pass Rate
+                        <div class="stat mb-3">
+                            <?=number_format($pass_count)?> Pass / <?=number_format($fail_count)?> Fail (<?=intval($pass_percentage)?>% Pass)
+                        </div>
+                        <div class="progress">
+                            <div class="progress-bar bg-success" role="progressbar" style="width: <?=$pass_percentage?>%"></div>
+                            <div class="progress-bar bg-danger" role="progressbar" style="width: <?=$fail_percentage?>%"></div>
+                        </div>
+                    </div>
+                </div>
+                <?php
+            }
+
+            ?>
+            </div>
+        </div>
+
+        <h3><?=__("Tests")?></h3>
+
+        <table class="table table-bordered table-hover">
+            <thead>
+                <tr>
+                    <th><?=htmlspecialchars(__("Location"))?></th>
+                    <?php
+                    if($has_pass_fail) {
+                        ?>
+                        <th><?=htmlspecialchars(__("Result"))?></th>
+                        <th><?=htmlspecialchars(__("Challenge Stage"))?></th>
+                        <?php
+                    }
+                    ?>
+                    <th><?=htmlspecialchars(__("PDF"))?></th>
+                </tr>
+            </thead>
+            <tbody>
+            <?php
+            foreach($tests as $test) {
+
+                $has_pdf = $test->hasPDF();
+
+                $location = $test->getLocation();
+
+                $pass_text = $test->getPassText();
+                $pass_class = $test->getPassClass();
+                $pass_icon = $test->getPassIcon();
+
+                $challenge_stage = $test->challenge_stage;
+                $challenge_stage_text = $test->getChallengeStageText();
+
+                ?>
+                <tr>
+                    <td>
+                        <?=htmlspecialchars($location->name)?>
+                    </td>
+                    <?php
+                    if($has_pass_fail) {
+                        ?>
+                        <td class="text-center">
+                            <strong class="text-<?=$pass_class?>"><?=htmlspecialchars($pass_text)?></strong>
+                        </td>
+                        <td>
+                        <?php
+                        if($test->isPending()) {
+                            ?>
+                            <?=htmlspecialchars(__("Pending"))?>
+                            <?php
+                        }
+                        else {
+                            ?>
+                            <strong class="text-<?=$pass_class?>"><?=htmlspecialchars(__("Stage %d", $challenge_stage))?></strong> -
+                            <?=htmlspecialchars($challenge_stage_text)?>
+                            <?php
+                        }
+                        ?>
+                        </td>
+                        <?php
+                    }
+                    ?>
+                    <td>
+                    <?php
+                    if($has_pdf) {
+                        $pdf_url = $test->getPDFUrl();
+                        ?>
+                        <a href="<?=htmlspecialchars($pdf_url)?>" target="_blank">View PDF</a>
+                        <?php
+                    }
+                    else {
+                        echo htmlspecialchars(__("No PDF available"));
+                    }
+                    ?>
+                    </td>
+                </tr>
+                <?php
+            }
+            ?>
+            </tbody>
+        </table>
+        <?php
+    }
+    ?>
+</div>

+ 8 - 3
views/test_verify_form.php

@@ -1,5 +1,9 @@
 <?php
 <?php
 
 
+/**
+ * @var Test $test
+ */
+
 $test_details = [
 $test_details = [
 	"Status" => "<span class=\"badge badge-lg badge-" . $test->getStatusClass() . "\">" . $test->getStatusText() . "</span>",
 	"Status" => "<span class=\"badge badge-lg badge-" . $test->getStatusClass() . "\">" . $test->getStatusText() . "</span>",
 	"Result" => "<span class=\"badge badge-lg badge-" . $test->getPassClass() . "\">" . $test->getPassText() . "</span>",
 	"Result" => "<span class=\"badge badge-lg badge-" . $test->getPassClass() . "\">" . $test->getPassText() . "</span>",
@@ -93,9 +97,10 @@ function render_card_list_group($details) {
 					<div class="dropdown-divider"></div>
 					<div class="dropdown-divider"></div>
 					<a class="dropdown-item" href="/account/tests/<?=$test->id?>/pdf" target="_blank">Generate New PDF</a>
 					<a class="dropdown-item" href="/account/tests/<?=$test->id?>/pdf" target="_blank">Generate New PDF</a>
 					<?php
 					<?php
-					if($has_pdf) {
+					if($test->hasPDF()) {
+						$pdf_url = $test->getPDFUrl();
 						?>
 						?>
-						<a class="dropdown-item" href="/account/tests/<?=$test->id?>/files/pdf" target="_blank">View Sent PDF</a>
+						<a class="dropdown-item" href="<?=$pdf_url?>" target="_blank">View Sent PDF</a>
 						<?php
 						<?php
 					}
 					}
 					if($test->hasTesterInvoicePDF()) {
 					if($test->hasTesterInvoicePDF()) {
@@ -464,4 +469,4 @@ function render_card_list_group($details) {
 			</div>
 			</div>
 		</div>
 		</div>
 	</form>
 	</form>
-</div>
+</div>

+ 2 - 2
views/user_edit_form.php

@@ -129,7 +129,7 @@ var userId = <?=$user->id?>;
 				<div class="row mb-1">
 				<div class="row mb-1">
 					<label class="col-sm-4 col-form-label"  for="password">Password (if changing)</label>
 					<label class="col-sm-4 col-form-label"  for="password">Password (if changing)</label>
 					<div class="col-sm">
 					<div class="col-sm">
-						<input class="form-control" type="password" name="password" id="password" placeholder="Enter password" />
+						<input class="form-control" type="password" name="password" id="password" placeholder="Enter password" autocomplete="new-password" />
 						<small class="text-muted form-text">At least <span data-length-requirement>6 characters</span>. Must contain at least one <span data-lowercase-requirement>lowercase</span>, <span data-uppercase-requirement>uppercase</span>, <span data-number-requirement>number</span> and <span data-special-requirement>special</span> character.</small>
 						<small class="text-muted form-text">At least <span data-length-requirement>6 characters</span>. Must contain at least one <span data-lowercase-requirement>lowercase</span>, <span data-uppercase-requirement>uppercase</span>, <span data-number-requirement>number</span> and <span data-special-requirement>special</span> character.</small>
 					</div>
 					</div>
 				</div>
 				</div>
@@ -238,4 +238,4 @@ var userId = <?=$user->id?>;
 		<button class="btn btn-primary" type="submit" name="submit" value="<?=htmlspecialchars($_SESSION["csrf_token"])?>">Submit</button>
 		<button class="btn btn-primary" type="submit" name="submit" value="<?=htmlspecialchars($_SESSION["csrf_token"])?>">Submit</button>
 		<a class="btn btn-secondary" href="<?=htmlspecialchars($_SERVER["HTTP_REFERER"] ?? "/account/users/$user->id")?>">Cancel</a>
 		<a class="btn btn-secondary" href="<?=htmlspecialchars($_SERVER["HTTP_REFERER"] ?? "/account/users/$user->id")?>">Cancel</a>
 	</form>
 	</form>
-</div>
+</div>

Some files were not shown because too many files changed in this diff