summaryrefslogtreecommitdiff
path: root/src/web/core/core.php
blob: feaecdf5826698597281570a01744ddb8f730a6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php /* Copyright (c) 2024 Freya Murphy */

/**
 * Core functions needed everywhere
 */
abstract class Core {

	private static ?DatabaseHelper $db = NULL;

	/**
	 * Loads the database
	 */
	public static function db(): DatabaseHelper
	{
		if (!Component::$db)
			Component::$db = new DatabaseHelper();
		return Component::$db;
	}

	/**
	 * Gets the stamp for a asset path
	 * @param string $path
	 */
	public static function asset_stamp(string $path): int
	{
		if (ENVIRONMENT == 'devlopment')
			return time();
		if (isset(FILE_TIMES[$path]))
			return FILE_TIMES[$path];
		return 0;
	}

	/**
	 * Gets a full path url from a relative path
	 * @param string $path
	 * @param bool $timestamp
 	 */
	public static function get_url(string $path, bool $timestamp = FALSE): string
	{
		$scheme = 'http';
		if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']))
			$scheme = $_SERVER['HTTP_X_FORWARDED_PROTO'];

		$host = $_SERVER['HTTP_HOST'];

		if (ENVIRONMENT == 'production')
			$host = lang('domain');

		$base = lang('base_path');
		$url = "{$scheme}://{$host}{$base}{$path}";
		if ($timestamp) {
			$time = Core::asset_stamp($path);
			$url .= "?timestamp={$time}";
		}
		return $url;
	}

	/**
	 * Loads a js html link
	 * @param string $path - the path to the js file
	 */
	public static function link_js(string $path): string
	{
		$stamp = Core::asset_stamp("public/$path");
		$href = Core::get_url("public/{$path}?timestamp={$stamp}");
		return '<script src="'. $href .'"></script>';
	}

	/**
	 * Loads a css html link
	 * @param string $path - the path to the css file
	 */
	public static function link_css(string $path): string
	{
		$stamp = Core::asset_stamp("public/$path");
		$href = Core::get_url("public/{$path}?timestamp={$stamp}");
		return '<link rel="stylesheet" href="'. $href .'">';
	}

	/**
	 * Loads a css html link
	 * @param string $path - the path to the css file
	 */
	public static function embed_css(string $path): string
	{
		$file = PUBLIC_ROOT . '/' . $path;
		if (file_exists($file)) {
			$text = file_get_contents($file);
			return "<style>{$text}</style>";
		} else {
			return "";
		}
	}

	/**
	 * Formats a ISO date
	 * @param $iso_date the ISO date
	 */
	public static function format_date(string $iso_date): string
	{
		return date("Y-m-d D H:i", strtotime($iso_date)) . ' EST';
	}
}