test.php 14 KB

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