test.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. <?php /** @noinspection PhpUnhandledExceptionInspection */
  2. /**
  3. * @var Test $test
  4. */
  5. Core::addScript("public/js/app-test.js");
  6. $test = Test::get($id);
  7. if(!$test) throw new Exception(__("Test cannot be found."));
  8. $is_confirmed = $test->status == Test::STATUS_CONFIRMED;
  9. $is_started = $test->status == Test::STATUS_STARTED;
  10. $is_unverified = $test->status == Test::STATUS_PENDING_VERIFICATION;
  11. $location = $test->getLocation();
  12. $project = $test->getProject();
  13. $customer = $project->getCustomer();
  14. $tester = $test->getTester();
  15. $template = $project->getTemplate();
  16. $template_overrides = $project->getTemplateOverrides();
  17. if($template_overrides) $template->setOverrides($template_overrides);
  18. $template->setKeys($project->getTemplateKeys());
  19. $page_title = $location->name;
  20. Core::addBreadcrumb("/account", "Account");
  21. Core::addBreadcrumb("/account/tests", "Tests");
  22. Core::addBreadcrumb("/account/tests/$id", $page_title);
  23. // Do test
  24. if(Core::$user->level == User::LEVEL_TESTER) {
  25. Core::$show_footer_content = false;
  26. if(Core::$user->id != $test->tester_id) throw new Exception(__("You do not have permission to view this page."));
  27. if($test->status == Test::STATUS_ASSIGNED) throw new Exception(__("You do not have permission to view this page as you have not accepted the test yet."));
  28. // Show completed message
  29. if($test->status > Test::STATUS_PENDING_VERIFICATION) {
  30. View::includeOnce("header", compact("page_title"));
  31. View::include("test_form", compact("test", "location", "project", "template"));
  32. View::includeOnce("footer");
  33. return;
  34. }
  35. $json = json_decode($template->getJSON());
  36. $submit = http::value("submit");
  37. if($submit) {
  38. $previous_timezone = date_default_timezone_get();
  39. try {
  40. Core::validateCSRFToken($submit);
  41. $form_exception = new FormException;
  42. if($is_confirmed) {
  43. // Parse before the test form
  44. $fields = $json->beforeTest;
  45. }
  46. if($is_started || $is_unverified) {
  47. // Parse after the test form
  48. $fields = $json->duringTest;
  49. // Start/End times
  50. if($is_started) {
  51. $start_override = http::getDateTimeFromFields("start_override");
  52. $end_override = http::getDateTimeFromFields("end_override");
  53. $start_unix = null;
  54. $end_unix = null;
  55. if($start_override && $end_override) {
  56. $start_unix = strtotime($start_override);
  57. $end_unix = strtotime($end_override);
  58. if($start_unix > $end_unix) $form_exception->addError(__("Entry Time must not be after Exit Time."));
  59. if(!$start_unix && $end_unix && $test->dts_start) {
  60. $recorded_start_unix = Util::getUnixTimeFromUTC($test->dts_start);
  61. if($end_unix < $recorded_start_unix) $form_exception->addError(__("Exit Time cannot be later than the recorded Entry Time."));
  62. }
  63. }
  64. else {
  65. $form_exception->addError(__("Entry Time and Exit Time must be filled in."));
  66. }
  67. }
  68. }
  69. foreach($fields as $field) {
  70. $name = $field->name ?? false;
  71. if(empty($name)) continue; // Not a field
  72. $label = $field->label ?? "";
  73. $type = $field->type;
  74. $required = $field->required ?? false;
  75. $values = $field->values ?? [];
  76. if($type == "file") {
  77. $file = (object) $_FILES[$name];
  78. try {
  79. if(!$required && $file->error == UPLOAD_ERR_NO_FILE) continue;
  80. if($required && $file->error == UPLOAD_ERR_NO_FILE) {
  81. throw new Exception("$label is required.");
  82. }
  83. // Detect upload error
  84. if($file->error != UPLOAD_ERR_OK) throw new Exception(HTTP::getUploadErrorString($file->error));
  85. // Get image details
  86. $size = @getimagesize($file->tmp_name);
  87. if(!$size) throw new Exception(sprintf(__("The uploaded file for %s is not an image."), $label));
  88. list($width, $height, $type) = $size;
  89. if($type != IMAGETYPE_JPEG) throw new Exception(sprintf(__("The uploaded file for %s is not a JPEG."), $label));
  90. // Resize image
  91. $output_image = Image::normalise($file->tmp_name);
  92. // Write image to disk
  93. $output_path = $test->getDirectory() . "/" . $name . ".jpg";
  94. imagejpeg($output_image, $output_path, 60);
  95. imagedestroy($output_image);
  96. }
  97. catch(Exception $e) {
  98. $form_exception->addError($e->getMessage());
  99. }
  100. }
  101. else {
  102. $value = http::value($name, "trim");
  103. if($required && empty($value)) $form_exception->addError(sprintf(__("%s is required."), $label));
  104. if($values && !in_array($value, $values)) $form_exception->addError(sprintf(__("Value for %s is invalid."), $label));
  105. if(in_array($name, Test::TEST_FIELDS)) {
  106. $test->$name = $value;
  107. }
  108. else {
  109. $test_value = TestValue::get($test->id, $name);
  110. if(!$test_value) {
  111. $test_value = new TestValue;
  112. $test_value->test_id = $test->id;
  113. $test_value->name = $name;
  114. }
  115. $test_value->value = $value;
  116. $success = $test_value->commit();
  117. if(!$success) $form_exception->addError(sprintf(__("Failed to save value for %s."), $label));
  118. }
  119. }
  120. }
  121. if($form_exception->hasErrors()) throw $form_exception;
  122. date_default_timezone_set("UTC");
  123. // Before the Test
  124. if($is_confirmed) {
  125. $test->status = Test::STATUS_STARTED;
  126. $test->dts_start = Util::getDateTime();
  127. $test->dts_updated = Util::getDateTime();
  128. $success = $test->commit();
  129. if(!$success) throw new Exception(__("Failed to save test. Please try again later."));
  130. Core::addAlert("success", __("Photos uploaded successfully."));
  131. HTTP::redirect("/account/tests/$id");
  132. }
  133. // During the test
  134. if($is_started || $is_unverified) {
  135. $test->status = Test::STATUS_PENDING_VERIFICATION;
  136. if($is_started) {
  137. if($start_unix && $end_unix) {
  138. $test->dts_start = date("Y-m-d H:i:s", $start_unix);
  139. $test->dts_end = date("Y-m-d H:i:s", $end_unix);
  140. }
  141. else if($end_unix) {
  142. $test->dts_end = date("Y-m-d H:i:s", $end_unix);
  143. }
  144. }
  145. $test->pass = 1;
  146. if($template->hasPassFail()) {
  147. $test->pass = ($test->challenge_stage <= $template->getPassStage()) ? 1 : 0; // Pass = Challenged during browsing or before
  148. }
  149. $test->dts_updated = Util::getDateTime();
  150. $success = $test->commit();
  151. if(!$success) throw new Exception(__("Failed to save test. Please try again later."));
  152. JSON::success();
  153. }
  154. }
  155. catch(FormException $e) {
  156. if(HTTP::isAJAX()) {
  157. $e->generateJSONError();
  158. }
  159. else {
  160. $e->generateAlerts();
  161. }
  162. }
  163. catch(Exception $e) {
  164. if(HTTP::isAJAX()) {
  165. JSON::fail($e->getMessage());
  166. }
  167. else {
  168. Core::addAlert("danger", $e->getMessage());
  169. }
  170. }
  171. date_default_timezone_set($previous_timezone);
  172. }
  173. View::includeOnce("header", compact("page_title"));
  174. View::include("test_form", compact("test", "location", "project", "template"));
  175. View::includeOnce("footer");
  176. }
  177. // Verify test
  178. else if(Core::$user->level >= User::LEVEL_ADMIN) {
  179. $json = json_decode($template->getJSON());
  180. $fields = array_merge($json->beforeTest, [(object) ["type" => "hr"]], $json->duringTest);
  181. $values = $test->getValues();
  182. $names = array_map(function($value) { return $value->name; }, $values);
  183. $values = array_combine(
  184. array_map(function($value) { return $value->name; }, $values),
  185. array_map(function($value) { return $value->value; }, $values)
  186. );
  187. $directory = $test->getDirectory();
  188. $submit = http::value("submit");
  189. $tester_message = http::value("tester_message", "trim");
  190. if($submit) {
  191. try {
  192. Core::validateCSRFToken($submit);
  193. $form_exception = new FormException;
  194. $accept = http::value("accept");
  195. $reject = http::value("reject");
  196. $accept_tester_invoice = http::value("accept_tester_invoice");
  197. $reject_tester_invoice = http::value("reject_tester_invoice");
  198. if(($accept || $reject) && $test->status != Test::STATUS_PENDING_VERIFICATION) {
  199. throw new Exception("This test is no longer pending verification.");
  200. }
  201. if(empty($test->verifier_id)) {
  202. $test->verifier_id = Core::$user->id;
  203. $test->dts_verified = Util::getDateTime();
  204. }
  205. $test->verifier_notes = http::value("verifier_notes", "trim");
  206. // Check selected retest project
  207. $new_test_project = false;
  208. $new_test_project_id = http::value("new_test_project_id", "int");
  209. $new_test_is_retest = http::value("new_test_is_retest", "int");
  210. if($new_test_project_id) {
  211. $new_test_project = Project::get($new_test_project_id);
  212. if(!$new_test_project || $new_test_project->customer_id != $customer->id) throw new Exception("The new test project selected is invalid.");
  213. }
  214. // Modify test values
  215. // Overrides
  216. $unix_start = strtotime($test->dts_start . " UTC");
  217. $unix_end = strtotime($test->dts_end . " UTC");
  218. $pass_override = http::value("pass_override");
  219. if(strlen($pass_override) > 0) {
  220. $test->pass = $pass_override;
  221. }
  222. $start_override = http::getDateTimeFromFields("start_override");
  223. if($start_override) {
  224. $unix_start = strtotime($start_override);
  225. }
  226. $end_override = http::getDateTimeFromFields("end_override");
  227. if($end_override) {
  228. $unix_end = strtotime($end_override);
  229. }
  230. if($unix_start > $unix_end) {
  231. $form_exception->addError("Start time cannot be after end time.");
  232. }
  233. else {
  234. $test->dts_start = Util::getDateTime($unix_start);
  235. $test->dts_end = Util::getDateTime($unix_end);
  236. }
  237. $test->customer_fee = null;
  238. $customer_fee = http::value("customer_fee", "float");
  239. if($customer_fee !== false && $customer_fee != $project->default_customer_fee) {
  240. $test->customer_fee = $customer_fee;
  241. }
  242. $test->test_fee = null;
  243. $tester_fee = http::value("tester_fee", "float");
  244. if($tester_fee !== false && $tester_fee != $project->default_tester_fee) {
  245. $test->test_fee = $tester_fee;
  246. }
  247. // Test forms
  248. foreach($fields as $field) {
  249. if($field->type == "header") continue;
  250. if($field->type == "file") continue;
  251. if(empty($field->name)) continue;
  252. $value = http::value($field->name, "trim");
  253. if(in_array($field->name, Test::TEST_FIELDS)) $test->{$field->name} = $value;
  254. else {
  255. $test_value = TestValue::get($id, $field->name);
  256. if(!$test_value) {
  257. $test_value = new TestValue;
  258. $test_value->test_id = $id;
  259. $test_value->name = $field->name;
  260. }
  261. $test_value->value = $value;
  262. $test_value->commit();
  263. }
  264. }
  265. // Accept test as completed
  266. if($accept) {
  267. $test->status = Test::STATUS_COMPLETED;
  268. }
  269. // Reject test
  270. if($reject) {
  271. $test->status = Test::STATUS_CANCELLED;
  272. }
  273. if($form_exception->hasErrors()) throw $form_exception;
  274. $test->retest = http::value("retest", "int");
  275. $test->dts_updated = Util::getDateTime();
  276. $success = $test->commit();
  277. if(!$success) throw new Exception("Failed to update the test. Please try again later.");
  278. if($new_test_project) {
  279. $new_test = new Test;
  280. $new_test->project_id = $new_test_project->id;
  281. $new_test->location_id = $location->id;
  282. $new_test->status = Test::STATUS_UNASSIGNED;
  283. $new_test->dts_created = Util::getDateTime();
  284. if($new_test_is_retest) {
  285. $new_test->retest = 1;
  286. }
  287. $success = $new_test->commit();
  288. }
  289. // If rejected, recreate empty test for the location
  290. if($reject) {
  291. $new_test = new Test;
  292. $new_test->project_id = $test->project_id;
  293. $new_test->location_id = $test->location_id;
  294. $new_test->status = Test::STATUS_UNASSIGNED;
  295. $new_test->dts_created = Util::getDateTime();
  296. $success = $new_test->commit();
  297. if(!$success) throw new Exception("Failed to create a new test. Please try again later.");
  298. }
  299. if($accept) {
  300. $tester->score++;
  301. $tester->commit();
  302. // Save PDF
  303. $mpdf = $test->getMPDF();
  304. $pdf_string = $mpdf->Output("", "S");
  305. $pdf_path = $directory . "/pdf.pdf";
  306. $success = file_put_contents($pdf_path, $pdf_string);
  307. $email_customer = http::value("email_customer");
  308. $email_location = http::value("email_location");
  309. $email_location_area_manager = http::value("email_location_area_manager");
  310. if($email_customer && $customer->email_after_test && $customer->email) {
  311. $test->sendResultEmail($customer->email);
  312. }
  313. if($email_location && $customer->email_locations_after_test && $location->email) {
  314. $test->sendResultEmail($location->email);
  315. }
  316. if($email_location_area_manager && $customer->email_locations_after_test && $location->area_manager_email) {
  317. $test->sendResultEmail($location->area_manager_email);
  318. }
  319. if(EMAIL_TEST_RESULT) {
  320. $test->sendResultEmail(EMAIL_TEST_RESULT);
  321. }
  322. if(EMAIL_TEST_RESULT_COPY) {
  323. $test->sendResultEmail(EMAIL_TEST_RESULT_COPY);
  324. }
  325. }
  326. if($test->status_tester_invoice == Test::STATUS_TESTER_INVOICE_PENDING) {
  327. if($accept_tester_invoice) {
  328. $success = $test->markTesterInvoicePaid();
  329. if(!$success) throw new Exception("Failed to mark tester invoice as paid.");
  330. }
  331. if($reject_tester_invoice) {
  332. $success = $test->rejectTesterInvoice();
  333. if(!$success) throw new Exception("Failed to reject tester invoice.");
  334. }
  335. }
  336. Core::addAlert("success", "Test updated successfully.");
  337. HTTP::redirect("/account/tests/$id");
  338. }
  339. catch(FormException $e) {
  340. $e->generateAlerts();
  341. }
  342. catch(Exception $e) {
  343. Core::addAlert("danger", $e->getMessage());
  344. }
  345. }
  346. $projects = $customer->getProjects();
  347. /** @var Project[] $future_projects */
  348. $future_projects = array_filter($projects, function($p) use ($project) {
  349. if($p->id == $project->id) return false;
  350. if($p->template_id != $project->template_id) return false;
  351. $unix_deadline = Util::getUnixTimeFromUTC($p->dts_deadline);
  352. return ($unix_deadline > time());
  353. });
  354. View::includeOnce("header", compact("page_title"));
  355. View::include("test_verify_form", compact("test", "tester", "location", "project", "future_projects", "customer", "template", "fields", "values", "tester_message"));
  356. View::includeOnce("footer");
  357. return;
  358. }
  359. // View test results
  360. else if(Core::$user->level >= User::LEVEL_VENUE) {
  361. HTTP::redirect("/account/tests/$id/result");
  362. }
  363. else {
  364. throw new Exception(__("Invalid request."));
  365. }