aboutsummaryrefslogtreecommitdiff
path: root/r7r_repo/main.php
blob: a6e019990721d4b278fe4b73c46a30edd1820b40 (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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
<?php

/* Load and check config */
require_once(dirname(__FILE__) . "/config.php");
if(!defined("CONFIG_FILLED_OUT"))
	die("Config file not filled out.");

/* Include database functions... */
require_once(dirname(__FILE__) . "/db.php");
db_connect();

/* create tables */
if(!SKIP_TABLE_CREATION)
{
	$db_structure = "CREATE TABLE IF NOT EXISTS `PREFIX_packages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text COLLATE utf8_unicode_ci NOT NULL,
  `lastversion` int(11) NOT NULL,
  `user` int(11) NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `lastupdate` bigint(20) NOT NULL,
  `txtversion` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE IF NOT EXISTS `PREFIX_settings_kvstorage` (
  `key` text COLLATE utf8_unicode_ci NOT NULL,
  `value` text COLLATE utf8_unicode_ci NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE IF NOT EXISTS `PREFIX_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text COLLATE utf8_unicode_ci NOT NULL,
  `pwhash` text COLLATE utf8_unicode_ci NOT NULL,
  `isadmin` tinyint(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
	$queries = explode(";", $db_structure);
	foreach($queries as $q)
	{
		if(!empty($q))
			qdb($q);
	}
}

/* Include more files... */
require_once(dirname(__FILE__) . "/stupid_template_engine.php");
require_once(dirname(__FILE__) . "/models.php");
require_once(dirname(__FILE__) . "/urlprocess.php");
require_once(dirname(__FILE__) . "/pwhash.php");
require_once(dirname(__FILE__) . "/pluginpackage.php");
require_once(dirname(__FILE__) . "/utils.php");

/* init STE */
$tpl_basedir = dirname(__FILE__). "/templates";
$ste = new \ste\STECore(new \ste\FilesystemStorageAccess("$tpl_basedir/src", "$tpl_basedir/transc"));

$ste->register_tag(
	"loremipsum",
	function($ste, $params, $sub)
	{
		$repeats = empty($params["repeat"]) ? 1 : $params["repeat"] + 0;
		return implode("\n\n", array_repeat("<p>Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\n\n<p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>\n\n<p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>\n\n<p>Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>\n\n<p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis.</p>\n\n<p>At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, At accusam aliquyam diam diam dolore dolores duo eirmod eos erat, et nonumy sed tempor et et invidunt justo labore Stet clita ea et gubergren, kasd magna no rebum. sanctus sea sed takimata ut vero voluptua. est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.</p>\n\n<p>Consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>", $repeats));
	}
);

/* start session and check auth. */
session_start();
$user = NULL;
if(isset($_SESSION["r7r_repo_login_name"]))
{
	try
	{
		$user = User::by_name($_SESSION["r7r_repo_login_name"]);
	}
	catch(DoesNotExistError $e)
	{
		unset($_SESSION["r7r_repo_login_name"]);
	}
}

/* url handlers */
$url_handlers = array(
	"_prelude" => function(&$data, $url_now, &$url_next)
	{
		global $ste, $settings, $user;
		
		if(@$settings["setup_finished"])
			$ste->vars["repo"] = array(
				"name"        => $settings["repo_name"],
				"description" => $settings["repo_description"],
				"baseurl"     => $settings["repo_baseurl"],
				"public"      => ($settings["repo_mode"] == "public")
			);
		
		if($user === NULL)
			$ste->vars["user"] = array(
				"logged_in" => False,
				"admin"     => False
			);
		else
			$ste->vars["user"] = array(
				"logged_in" => True,
				"name"      => $user->get_name(),
				"admin"     => $user->isadmin
			);
	},
	"_notfound" => url_action_simple(function($data)
	{
		header("HTTP/1.1 404 Not Found");
		header("Content-Type: text/plain");
		echo "404 Not Found\nThe resource  \"{$_SERVER["REQUEST_URI"]}\" could not be found.\n";
	}),
	"_index" => url_action_alias(array("index")),
	"index" => function(&$data, $url_now, &$url_next)
	{
		global $ste;
		$url_next = array();
		
		$ste->vars["menu"] = "home";
		
		$latest = Package::latest();
		$ste->vars["latest_pkgs"] = array_map(function($pkg) { return array(
			"name"        => $pkg->get_name(),
			"version"     => $pkg->txtversion,
			"description" => $pkg->description,
			"last_update" => $pkg->lastversion
		); }, $latest);
		
		echo $ste->exectemplate("home.html");
	},
	"login" => function(&$data, $url_now, &$url_next)
	{
		global $ste, $user;
		
		if(($user === NULL) and isset($_POST["login"]))
		{
			try
			{
				$user = User::by_name($_POST["username"]);
				if(PasswordHash::validate($_POST["password"], $user->pwhash))
				{
					$ste->vars["success"] = "Logged in successfully.";
					$_SESSION["r7r_repo_login_name"] = $user->get_name();
					$url_next = array("_prelude", "index");
				}
				else
				{
					$user = NULL;
					$ste->vars["error"] = "Username / Password wrong.";
					$url_next = array("index");
				}
			}
			catch(DoesNotExistError $e)
			{
				$user = NULL;
				$ste->vars["error"] = "Username / Password wrong.";
				$url_next = array("index");
			}
		}
		else
			$url_next = array("index");
	},
	"logout" => function(&$data, $url_now, &$url_next)
	{
		global $ste, $user;
		
		if($user === NULL)
		{
			$url_next = array("index");
			return;
		}
		
		$user = NULL;
		unset($_SESSION["r7r_repo_login_name"]);
		$ste->vars["success"] = "Logged out successfully.";
		$url_next = array("_prelude", "index");
	},
	"setup" => function(&$data, $url_now, &$url_next)
	{
		global $settings, $ste;
		
		/* If initial setup was already finished, nobody should be allowed to access this. */
		if(@$settings["setup_finished"])
			throw new NotFoundError();
		
		$url_next = array();
		
		/* Test file permissions */
		$permissions_missing = array_filter(array("/packages", "/packagelist", "/repometa"), function($f) { return !@is_writable(dirname(__FILE__) . "/..$f"); });
		if(!empty($permissions_missing))
			$ste->vars["error"] = "No writing permissions on these files/directories: \"" . implode("\", \"", $permissions_missing) . "\"";
		else
		{
			/* Check input */
			if(!empty($_POST["send_data"]))
			{
				if(empty($_POST["admin_name"]) or empty($_POST["admin_password"]) or empty($_POST["repo_name"]) or empty($_POST["repo_description"]) or empty($_POST["repo_baseurl"]) or (($_POST["repo_mode"] != "public") and ($_POST["repo_mode"] != "private")))
					$ste->vars["error"] = "Form not filled out completely";
				else
				{
					/* Insert data */
					$admin = User::create($_POST["admin_name"]);
					$admin->pwhash = PasswordHash::create($_POST["admin_password"]);
					$admin->isadmin = True;
					$admin->save();
					$settings["repo_name"]        = $_POST["repo_name"];
					$settings["repo_description"] = $_POST["repo_description"];
					$settings["repo_baseurl"]     = $_POST["repo_baseurl"];
					$settings["repo_mode"]        = $_POST["repo_mode"];
					
					update_repometa();
					
					$settings["setup_finished"] = True;
					
					$url_next = array("index");
					return;
				}
			}
		}
		
		$ste->vars["baseurl_predicted"] = self_url();
		echo $ste->exectemplate("setup.html");
	}
);

/* bootstrapping... */
$urlpath = explode("/", $_GET["action"]);
$rel_path_to_root = implode("/", array_merge(array("."), array_repeat("..", count($urlpath) - 1)));
$GLOBALS["rel_path_to_root"] = $rel_path_to_root;
$data = array("rel_path_to_root" => $rel_path_to_root);
$ste->vars["rel_path_to_root"] = $rel_path_to_root;
/* Enforce setup */
if(!@$settings["setup_finished"])
	$urlpath = array("setup");
/*try
{*/
	url_process($urlpath, $url_handlers, $data);
/*}
catch(Exception $e)
{
	header("HTTP/1.1 500 Internal Server Error");
	header("Content-Type: text/plain");
	echo "Internal Server Error\nReason: " . get_class($e) . "(" . $e->getMessage() . ") thrown.\n";
}*/

/* save settings */
$settings->save();

?>