router.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. try {
  3. require "initialise.php";
  4. // Load routes
  5. require "routes.php";
  6. $path = http::value("path");
  7. if(empty($path)) $path = "home";
  8. // Loop through routes
  9. foreach($routes as $regex => $options) {
  10. // Check if path matches the route
  11. if(preg_match($regex, $path, $matches)) {
  12. // Get controller
  13. $controller = $options["controller"];
  14. // Get route type
  15. $route_type = $options["type"] ?? "page";
  16. $require_log_in = $options["require_log_in"] ?? false;
  17. $require_admin = $options["require_admin"] ?? false;
  18. $require_user_level = $options["require_user_level"] ?? false;
  19. $allow_ajax = $options["allow_ajax"] ?? true;
  20. // Get params
  21. $params = $options["params"] ?? [];
  22. // Set param variables
  23. if($params) {
  24. foreach($params as $index => $name) {
  25. ${$name} = $matches[$index + 1];
  26. }
  27. }
  28. $controller_directory = "controllers";
  29. $controller_path = $controller_directory . "/" . $controller . ".php";
  30. if(!file_exists($controller_path)) throw new Exception("Controller \"$controller\" not found.");
  31. if($require_log_in) {
  32. Core::requireLogIn();
  33. }
  34. if($require_admin) {
  35. Core::requireAdmin();
  36. }
  37. if($require_user_level) {
  38. Core::requireUserLevel($require_user_level);
  39. }
  40. if(!$allow_ajax) {
  41. Core::refuseAJAX();
  42. }
  43. // Load the controller
  44. require $controller_path;
  45. // Session cleanup
  46. if(empty($_SESSION) && session_status() == PHP_SESSION_ACTIVE) {
  47. session_destroy();
  48. }
  49. // Quit
  50. exit;
  51. }
  52. }
  53. // 404 if no page was found
  54. require "controllers/404.php";
  55. }
  56. catch (Exception $e) {
  57. $route_type = $route_type ?? "page";
  58. // Force JSON exceptions for AJAX calls
  59. if(HTTP::isAJAX()) {
  60. $route_type = "json";
  61. }
  62. if($route_type == "page") {
  63. // Show error page
  64. $page_title = "Error";
  65. View::includeOnce("header", compact("page_title"));
  66. View::include("error", ["error_message" => $e->getMessage()]);
  67. View::includeOnce("footer");
  68. }
  69. else if($route_type == "json") {
  70. // JSON error
  71. JSON::header();
  72. JSON::fail(["reason" => $e->getMessage()]);
  73. }
  74. else {
  75. echo $e->getMessage();
  76. }
  77. }
  78. ?>