router.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. Core::$controller = $controller;
  15. // Get route type
  16. $route_type = $options["type"] ?? "page";
  17. $require_log_in = $options["require_log_in"] ?? false;
  18. $require_admin = $options["require_admin"] ?? false;
  19. $require_user_level = $options["require_user_level"] ?? false;
  20. $allow_ajax = $options["allow_ajax"] ?? true;
  21. // Get params
  22. $params = $options["params"] ?? [];
  23. // Set param variables
  24. if($params) {
  25. foreach($params as $index => $name) {
  26. ${$name} = $matches[$index + 1];
  27. }
  28. }
  29. $controller_directory = "controllers";
  30. $controller_path = $controller_directory . "/" . $controller . ".php";
  31. if(!file_exists($controller_path)) throw new Exception("Controller \"$controller\" not found.");
  32. if($require_log_in) {
  33. Core::requireLogIn();
  34. }
  35. if(preg_match("/^account/", $path) && $path != "account" && !preg_match("/(settings|deactivate|reactivate|delete|accept-terms|decline-terms)$/", $path)) {
  36. Core::requireTerms();
  37. }
  38. if($require_admin) {
  39. Core::requireAdmin();
  40. }
  41. if($require_user_level) {
  42. Core::requireUserLevel($require_user_level);
  43. }
  44. if(!$allow_ajax) {
  45. Core::refuseAJAX();
  46. }
  47. if($path != "log-in") {
  48. unset($_SESSION["log_in_redirect_uri"]);
  49. }
  50. // Load the controller
  51. require $controller_path;
  52. // Session cleanup
  53. if(empty($_SESSION) && session_status() == PHP_SESSION_ACTIVE) {
  54. session_destroy();
  55. }
  56. // Quit
  57. exit;
  58. }
  59. }
  60. // 404 if no page was found
  61. require "controllers/404.php";
  62. }
  63. catch (Exception $e) {
  64. $route_type = $route_type ?? "page";
  65. // Force JSON exceptions for AJAX calls
  66. if(HTTP::isAJAX()) {
  67. $route_type = "json";
  68. }
  69. if($route_type == "page") {
  70. // Show error page
  71. $page_title = "Error";
  72. View::includeOnce("header", compact("page_title"));
  73. View::include("error", ["error_message" => $e->getMessage()]);
  74. View::includeOnce("footer");
  75. }
  76. else if($route_type == "json") {
  77. // JSON error
  78. JSON::header();
  79. JSON::fail(["reason" => $e->getMessage()]);
  80. }
  81. else {
  82. echo $e->getMessage();
  83. }
  84. }
  85. ?>