Repository navigation
Expand file tree
/
Copy pathcontroller.inc.php
More file actions
496 lines (447 loc) · 14.9 KB
/
Copy pathcontroller.inc.php
File metadata and controls
496 lines (447 loc) · 14.9 KB
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
<?php
/*
* controller.inc.php
* Generic dispatcher code mixed with some hotglue-specific controllers
*
* Copyright Gottfried Haider, Danja Vasiliev 2010.
* This source code is licensed under the GNU General Public License.
* See the file COPYING for more details.
*/
@require_once('config.inc.php');
require_once('common.inc.php');
require_once('html.inc.php');
require_once('log.inc.php');
require_once('modules.inc.php');
// module glue gets loaded on demand
require_once('util.inc.php');
if (!isset($controllers)) {
$controllers = [];
}
/**
* show a site where authenticated users can create new pages
*/
/**
* refuse the request when it is for the site options page: it is not a page
* a visitor or an author can see, edit or create (see site_options_page())
*
* @return bool true if the request was refused (a 404 was sent)
*/
function controller_refuse_site_options($args)
{
if (!empty($args[0][0]) && get_first_item(expl('.', $args[0][0])) == '_options') {
hotglue_error(404);
return true;
}
return false;
}
function controller_create_page($args)
{
if (controller_refuse_site_options($args)) {
return;
}
page_canonical($args[0][0]);
$page = $args[0][0];
if (page_exists($page)) {
log_msg('debug', 'controller_create_page: page '.quot($page).'already exists, invoking controller_edit');
controller_edit($args);
return;
}
load_modules('glue');
default_html(true);
html_add_css(base_url().'css/hotglue_error.css');
if (USE_MIN_FILES) {
html_add_js(base_url().'js/create_page.min.js');
} else {
html_add_js(base_url().'js/create_page.js');
}
html_add_js_var('$.glue.page', $page);
html_add_js_var('$.glue.q', (SHORT_URLS ? '' : '?'));
$bdy = &body();
elem_attr($bdy, 'id', 'create_page');
body_append(tab(1).'<div id="paper">'.nl());
body_append(tab(2).'<div id="wrapper">'.nl());
body_append(tab(3).'<div id="content">'.nl());
body_append(tab(4).'<div id="left-nav">'.nl());
body_append(tab(5).'<img src="'.htmlspecialchars(base_path(), ENT_COMPAT, 'UTF-8').'img/hotglue-logo.png" alt="logo">'.nl());
body_append(tab(4).'</div>'.nl());
body_append(tab(4).'<div id="main">'.nl());
body_append(tab(5).'<h1 id="error-title">Page does not exist yet!</h1>'.nl());
body_append(tab(5).'<p>'.nl());
body_append(tab(6).'This page does not exist yet!<br>'.nl());
body_append(tab(6).'Would you like to create the page?'.nl());
body_append(tab(5).'</p>'.nl());
body_append(tab(5).'<form><input id="create_page_btn" type="button" value="Create it!"></form>'.nl());
body_append(tab(4).'</div>'.nl());
body_append(tab(3).'</div>'.nl());
body_append(tab(2).'</div>'.nl());
body_append(tab(2).'<div style="position: absolute; left: 200px; top: -10px; z-index: 2;">'.nl());
body_append(tab(3).'<img src="'.htmlspecialchars(base_path(), ENT_COMPAT, 'UTF-8').'img/hotglue-404.png" alt="404">'.nl());
body_append(tab(2).'</div>'.nl());
body_append(tab(1).'</div>'.nl());
echo html_finalize();
}
register_controller('*', 'create_page', 'controller_create_page', ['auth'=>true]);
/**
* show a site to edit pages
*/
function controller_edit($args)
{
if (controller_refuse_site_options($args)) {
return;
}
handle_updates();
// this is a good spot to log the server's php version as well
log_msg('debug', 'controller_edit: running on php version '.phpversion());
// most of these checks are only necessary if the client calls
// page/edit directly
page_canonical($args[0][0]);
$page = $args[0][0];
if (!page_exists($page)) {
log_msg('debug', 'controller_edit: page '.quot($page).' does not exist, invoking controller_create_page');
controller_create_page($args);
return;
}
// create page on the fly
load_modules('glue');
default_html(true);
html_add_js_var('$.glue.page', $page);
html_add_css(base_url().'css/edit.css', 5);
if (USE_MIN_FILES) {
html_add_js(base_url().'js/moveable.min.js', 3);
} else {
html_add_js(base_url().'js/moveable.js', 3);
}
// deferred per Alpine's own recommendation: without it, the script runs
// as soon as it's parsed (still inside <head>, before <body> exists),
// forcing Alpine to fall back to retrying initialization later - a
// race that can intermittently affect the context-menu toggle buttons
// (loop/controls/autoplay/mute etc.) built on its x-data/x-bind/x-on
// plumbing (see $.glue.toggle_button in js/glue.js)
if (USE_MIN_FILES) {
html_add_js(base_url().'js/alpine.min.js', 3, true);
} else {
html_add_js(base_url().'js/alpine.js', 3, true);
}
if (USE_MIN_FILES) {
html_add_js(base_url().'js/vanilla-picker.min.js', 3);
} else {
html_add_js(base_url().'js/vanilla-picker.js', 3);
}
if (USE_MIN_FILES) {
html_add_js(base_url().'js/edit.min.js', 4);
} else {
html_add_js(base_url().'js/edit.js', 4);
}
render_page(['page'=>$page, 'edit'=>true]);
echo html_finalize();
}
register_controller('*', 'edit', 'controller_edit', ['auth'=>true]);
/**
* this is the default (fallback) controller
*
* it mainly invokes other controllers or sends error messages
*/
function controller_default($args)
{
if (empty($args[0][0]) && empty($args[0][1])) {
// take the default page
$args[0][0] = startpage();
log_msg('debug', 'controller_default: using the default page');
} elseif ($args[0][0] == 'edit' && empty($args[0][1])) {
// quirk: edit the default page
$args[0][0] = startpage();
$args[0][1] = 'edit';
log_msg('debug', 'controller_default: using the default page');
invoke_controller($args);
return;
}
page_canonical($args[0][0]);
$obj = expl('.', $args[0][0]);
if (controller_refuse_site_options($args)) {
return;
}
if (count($obj) == 2) {
// page requested
if (page_exists($args[0][0])) {
if (DEFAULT_TO_EDIT && is_auth()) {
log_msg('debug', 'controller_default: invoking controller_edit');
controller_edit($args);
} else {
log_msg('debug', 'controller_default: invoking controller_show');
controller_show($args);
}
} elseif (ALWAYS_PROMPT_CREATE_PAGE || is_auth() || $args[0][0] == startpage()) {
log_msg('debug', 'controller_default: invoking controller_create_page');
controller_create_page($args);
} else {
log_msg('info', 'controller_default: page '.quot($args[0][0]).' not found, serving 404');
hotglue_error(404);
}
} else {
// possibly object requested
if (object_exists($args[0][0])) {
// try to serve upload
if (isset($args['download']) && $args['download']) {
// prompt file save dialog on client
$dl = true;
} else {
$dl = false;
}
log_msg('debug', 'controller_default: invoking serve_resource');
if (!serve_resource($args[0][0], $dl)) {
log_msg('info', 'controller_default: object '.quot($args[0][0]).' has no associated resource, serving 404');
hotglue_error(404);
}
} else {
log_msg('info', 'controller_default: object '.quot($args[0][0]).' not found, serving 404');
hotglue_error(404);
}
}
}
register_controller('*', '*', 'controller_default');
/**
* promt the user to authenticate
*
* this might be helpful as other controller's authentication seem to be only
* valid for the respective directory. (e.g. having privileges in '/foo/edit'
* does not seem to have an effect on the parent directory or any other sibling
* directory.
*/
function controller_login($args)
{
if (!is_auth()) {
prompt_auth();
} else {
// redirect - kept relative (not prefixed with base_url()) so it
// stays on whatever domain the request actually came in on, see
// module_object.inc.php's object_alter_render_late() for the full
// rationale
if (SHORT_URLS) {
header('Location: '.base_path().'pages');
} else {
header('Location: '.base_path().'?pages');
}
die();
}
}
register_controller('login', '', 'controller_login');
/**
* show a page
*/
function controller_show($args)
{
if (controller_refuse_site_options($args)) {
return;
}
// most of these checks are only necessary if the client calls
// page/show directly
page_canonical($args[0][0]);
$page = $args[0][0];
if (!page_exists($page)) {
log_msg('info', 'controller_show: page '.quot($page).' not found, serving 404');
hotglue_error(404);
}
// if viewing is restricted ask to authenticate
if (VIEW_NEEDS_AUTH && !is_auth()) {
prompt_auth();
}
// per-page password (SOW-page-password.md): the gate runs before the
// cache and before the render, so nothing of a protected page - not
// even a stale cached copy - is served without the session flag
page_password_gate($page);
$gated = page_password_required($page);
// serve from page if possible
if (!$gated && 0 < CACHE_TIME && is_cached('page', $page, CACHE_TIME)) {
serve_cached('page', $page);
die();
}
// otherwise create page on the fly
load_modules('glue');
default_html(false);
// protected pages are never cached: the cached html would outlive the
// password and serve the content to whoever came next
$cache_page = !$gated;
render_page(['page'=>$page, 'edit'=>false]);
// the $cache_page parameter is set by the html_finalize()
$html = html_finalize($cache_page);
if ($gated) {
// the protected page's static assets go through the session-checked
// proxy (controller_asset) - everything the render referenced
// directly under the page's own shared dir is rewritten, so no
// direct-url fetch bypasses the password
$pn = get_first_item(expl('.', $page));
$html = str_replace(CONTENT_DIR.'/'.$pn.'/shared/', '?asset&p='.urlencode($page).'&f=', $html);
}
echo $html;
// and cache it
if (0 < CACHE_TIME && $cache_page) {
cache_output('page', $page, $html);
}
}
register_controller('*', 'show_page', 'controller_show');
/**
* invoke a controller based on the query arguments given
*
* this function does not return in case of an error.
* @param array $args query-arguments array
* @return mixed return value of controller that was called
*/
function invoke_controller($args)
{
global $controllers;
// change query-arguments so that we always have a arg0 and arg1
if (!isset($args[0])) {
$args[0] = ['', ''];
} elseif (is_string($args[0])) {
$args[0] = [$args[0], ''];
}
// load all modules
// TODO (later): fastpath for serving cached pages or files (the latter one
// is only doable when we store in the object file which module to load)
load_modules();
$match = false;
if (isset($controllers[$args[0][0].'-'.$args[0][1]])) {
// foo/bar would match controller for "foo/bar"
$match = $controllers[$args[0][0].'-'.$args[0][1]];
$reason = $args[0][0].'/'.$args[0][1];
} elseif (isset($controllers[$args[0][0].'-*'])) {
// foo/bar would match "foo/*"
$match = $controllers[$args[0][0].'-*'];
$reason = $args[0][0].'/*';
} elseif (isset($controllers['*-'.$args[0][1]])) {
// foo/bar would match "*/bar"
$match = $controllers['*-'.$args[0][1]];
$reason = '*/'.$args[0][1];
} elseif (isset($controllers['*-*'])) {
// foo/bar would match "*/*"
$match = $controllers['*-*'];
$reason = '*/*';
}
if ($match !== false) {
// check authentication for those controllers that require it
if (isset($match['auth']) && $match['auth']) {
if (!is_auth()) {
prompt_auth();
}
// also check the referer to prevent against cross site request
// forgery (xsrf)
// this is not really optimal, since proxies can filter the referer
// header, but as a first step..
// use request_base_url() (always derived from this request),
// not base_url() (can be a fixed, different domain when
// BASE_URL is configured, e.g. a custom domain pointed at this
// install - comparing against it would reject every legitimate
// request that didn't arrive on that one specific domain)
if (!empty($_SERVER['HTTP_REFERER'])) {
$bu = request_base_url();
if (substr($_SERVER['HTTP_REFERER'], 0, strlen($bu)) != $bu) {
log_msg('warn', 'controller: possible xsrf detected, referer is '.quot($_SERVER['HTTP_REFERER']).', arguments '.var_dump_inl($args));
hotglue_error(400);
}
}
}
log_msg('info', 'controller: invoking controller '.quot($reason).' => '.$match['func']);
return $match['func']($args);
} else {
// normally we won't reach this as some default (*/*) controller will
// be present
log_msg('warn', 'controller: no match for '.quot($args[0][0].'/'.$args[0][1]));
hotglue_error(400);
}
}
/**
* parse the QUERY_STRING server variable
*
* @return array query-arguments array (key/value and numeric keys)
*/
function parse_query_string()
{
// QUERY_STRING per se seems not to be affected by magic quotes, only
// the derived $_GET, $_POST etc
$q = $_SERVER['QUERY_STRING'] ?? '';
$args = [];
$num_args = [];
// strip a tailing slash
if (substr($q, -1) == '/') {
$q = substr($q, 0, -1);
}
// explode query string
// this could also be done with parse_str() instead
$temp = expl('&', $q);
foreach ($temp as $a) {
if (($p = strpos($a, '=')) !== false) {
$args[urldecode(substr($a, 0, $p))] = urldecode(substr($a, $p+1));
} else {
$num_args[] = urldecode($a);
}
}
// merge $num_args into $args
for ($i=0; $i < count($num_args); $i++) {
// explode slashes in arguments without a key
if (($p = strpos($num_args[$i], '/')) !== false) {
$args[$i] = expl('/', $num_args[$i]);
} else {
$args[$i] = $num_args[$i];
}
}
return $args;
}
/**
* register a controller
*
* @param string $arg0 first argument of query to match (* for wildcard)
* @param string $arg1 second argument of query to match (* for widcard)
* @param string $func function name
* @param array $args optional arguments
*/
function register_controller($arg0, $arg1, $func, $args = [])
{
global $controllers;
$controllers[$arg0.'-'.$arg1] = array_merge($args, ['func'=>$func]);
log_msg('debug', 'controller: registered controller '.quot($arg0.'/'.$arg1).' => '.$func);
}
/**
* serve a resource associated with an object
*
* the function might not return (e.g. when a module calls serve_file()).
* @param string $s object (e.g. page.rev.obj)
* @param bool $dl download file
* @return bool
*/
function serve_resource($s, $dl)
{
load_modules('glue');
// resolve symlinks
$ret = object_get_symlink(['name'=>$s]);
if ($ret['#error'] == false && $ret['#data'] !== false) {
log_msg('debug', 'controller: resolved resource '.quot($s).' into '.quot($ret['#data']));
$s = $ret['#data'];
}
$obj = load_object(['name'=>$s]);
if ($obj['#error']) {
return false;
} else {
$obj = $obj['#data'];
}
// per-page password (SOW-page-password.md): the php-served object
// resources of a protected page need the same session the page's html
// does - otherwise the direct ?object url bypasses the gate entirely.
// Authenticated users pass (the editor needs its own objects).
if (!is_auth()) {
$a = expl('.', $s);
array_pop($a);
if (!page_password_allowed(implode('.', $a))) {
hotglue_error(403);
}
}
$ret = invoke_hook_while('serve_resource', false, ['obj'=>$obj, 'dl'=>$dl]);
// this is probably not needed as the module will most likely call
// serve_file() on success, which does not return
foreach ($ret as $key=>$val) {
if ($val !== false) {
return true;
}
}
return false;
}
register_hook('serve_resource', 'serve resources associated with objects');