Core.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. <?php
  2. namespace App;
  3. use Exception;
  4. use Gettext\Loader\MoLoader;
  5. use Gettext\Translator;
  6. use Gettext\TranslatorFunctions;
  7. use Monolog\Logger;
  8. use RuntimeException;
  9. class Core {
  10. public const SCRIPT_GLOBAL = 0;
  11. public const SCRIPT_PAGE = 1;
  12. private static $instance;
  13. /** @var User */
  14. protected $user;
  15. /** @var Breadcrumb[] */
  16. protected $breadcrumbs = [];
  17. /** @var string */
  18. protected $locale;
  19. /** @var Translator */
  20. protected $translator;
  21. /** @var string */
  22. protected $controllerName = "home";
  23. /** @var string[] Global scripts */
  24. protected $scripts = [];
  25. /** @var string[] Page scripts */
  26. protected $pageScripts = [];
  27. /** @var string[] CSS stylesheets */
  28. protected $stylesheets = [];
  29. /** @var Logger */
  30. protected $logger;
  31. // Static methods
  32. public static function getInstance(): Core {
  33. if(self::$instance === null) {
  34. self::$instance = new Core();
  35. }
  36. return self::$instance;
  37. }
  38. public static function hasReCaptcha(): bool {
  39. return !empty($_ENV["RECAPTCHA_SECRET_KEY"]);
  40. }
  41. public static function reCaptchaCheck(string $recaptcha_token): bool {
  42. if(!self::hasReCaptcha()) {
  43. return true;
  44. }
  45. $url = sprintf("https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s&remoteip=%s",
  46. $_ENV["RECAPTCHA_SECRET_KEY"], $recaptcha_token, $_SERVER["REMOTE_ADDR"]
  47. );
  48. $response = file_get_contents($url);
  49. $object = json_decode($response);
  50. if(!$object) {
  51. return false;
  52. }
  53. return $object->success && $object->score >= 0.6;
  54. }
  55. /**
  56. * Core constructor.
  57. * @throws Exception
  58. */
  59. public function __construct() {
  60. if(PHP_SAPI !== "cli") {
  61. $this->initSession();
  62. }
  63. $this->initBreadcrumbs();
  64. $this->initLocalisation();
  65. }
  66. // Object methods
  67. /**
  68. * @return void
  69. * @throws Exception
  70. */
  71. private function initSession(): void {
  72. session_name($_ENV["SESSION_NAME"]);
  73. session_start();
  74. $user_id = $_SESSION["user_id"] ?? null;
  75. if($user_id && $this->hasConnection()) {
  76. $this->user = User::get($user_id);
  77. }
  78. if($this->isLoggedIn()) {
  79. setcookie($_ENV["SESSION_NAME"], session_id(), time() + 28 * 86400, "/");
  80. $this->user->touch();
  81. }
  82. register_shutdown_function(static function() {
  83. if(empty($_SESSION) && session_status() === PHP_SESSION_ACTIVE) {
  84. session_destroy();
  85. }
  86. });
  87. }
  88. private function initBreadcrumbs(): void {
  89. $this->breadcrumbs[] = new Breadcrumb("/", $this->getSiteName());
  90. }
  91. private function initLocalisation(): void {
  92. $this->locale = $_ENV["LOCALE"];
  93. $this->translator = new Translator;
  94. TranslatorFunctions::register($this->translator);
  95. $mo_path = $_ENV["DIR_ROOT"] . "/i18n/$this->locale/LC_MESSAGES/$this->locale.mo";
  96. if(!file_exists($mo_path)) {
  97. return;
  98. }
  99. $loader = new MoLoader();
  100. $translations = $loader->loadFile($mo_path);
  101. $this->translator->addTranslations($translations->toArray());
  102. }
  103. /**
  104. * @param string $path
  105. * @param string $mode
  106. * @throws Exception
  107. */
  108. public function addStylesheet(string $path, string $mode = "append"): void {
  109. if(!file_exists($_ENV["DIR_ROOT"] . "/public/$path")) {
  110. throw new RuntimeException("'$path' does not exist.");
  111. }
  112. if($mode === "prepend") {
  113. array_unshift($this->stylesheets, $path);
  114. }
  115. else {
  116. $this->stylesheets[] = $path;
  117. }
  118. }
  119. /**
  120. * @param string $path File path relative to /public
  121. * @param int $type
  122. * @throws Exception
  123. */
  124. public function addScript(string $path, int $type = self::SCRIPT_GLOBAL): void {
  125. if(!file_exists($_ENV["DIR_ROOT"] . "/public/$path")) {
  126. throw new RuntimeException("'$path' does not exist.");
  127. }
  128. if($type === self::SCRIPT_PAGE) {
  129. $this->pageScripts[] = $path;
  130. }
  131. else {
  132. $this->scripts[] = $path;
  133. }
  134. }
  135. public function getStylesheets(): array {
  136. return $this->stylesheets;
  137. }
  138. public function getGlobalScripts(): array {
  139. return $this->scripts;
  140. }
  141. public function getPageScripts(): array {
  142. return $this->pageScripts;
  143. }
  144. /**
  145. * @return Breadcrumb[]
  146. */
  147. public function getBreadcrumbs(): array {
  148. return $this->breadcrumbs;
  149. }
  150. public function getLocale(): string {
  151. return $this->locale;
  152. }
  153. /**
  154. * @param string $name
  155. * @param array $params
  156. * @throws Exception
  157. */
  158. public function requireController(string $name, array $params = []): void {
  159. extract($params, EXTR_OVERWRITE);
  160. $path = $_ENV["DIR_ROOT"] . "/controllers/$name.php";
  161. if(!file_exists($path)) {
  162. throw new RuntimeException("Controller '$name' could not be found.");
  163. }
  164. $this->controllerName = $name;
  165. require $path;
  166. }
  167. public function getUser(): ?User {
  168. return $this->user;
  169. }
  170. /**
  171. * @return bool
  172. * @throws Exception
  173. */
  174. public function isLoggedIn(): bool {
  175. return ($this->user !== null);
  176. }
  177. /**
  178. * @return string
  179. */
  180. public function getControllerName(): string {
  181. return $this->controllerName;
  182. }
  183. public function addBreadcrumb(string $url, string $name): void {
  184. $this->breadcrumbs[] = new Breadcrumb($url, $name);
  185. }
  186. public function hasConnection(): bool {
  187. return Database::$connection !== null;
  188. }
  189. public function getSiteName(): string {
  190. return $_ENV["SITE_NAME"];
  191. }
  192. public function getTabTitle(): string {
  193. $breadcrumbs = array_reverse($this->getBreadcrumbs());
  194. $parts = [];
  195. foreach($breadcrumbs as $breadcrumb) {
  196. $parts[] = $breadcrumb->getName();
  197. }
  198. return implode(" | ", $parts);
  199. }
  200. public function getSettings(): object {
  201. $filename = "settings.json";
  202. if(file_exists($filename)) {
  203. $settings_json = file_get_contents($filename);
  204. $settings = json_decode($settings_json);
  205. }
  206. else {
  207. $settings = (object) [
  208. "defaultCompanyId" => null
  209. ];
  210. }
  211. return $settings;
  212. }
  213. public function saveSettings(object $settings): bool {
  214. return file_put_contents("settings.json", json_encode($settings));
  215. }
  216. /**
  217. * @param Logger $logger
  218. */
  219. public function setLogger(Logger $logger): void {
  220. $this->logger = $logger;
  221. }
  222. /**
  223. * @return Logger
  224. */
  225. public function getLogger(): Logger {
  226. return $this->logger;
  227. }
  228. }