/
frontcontroller.class.php
602 lines (493 loc) · 19.1 KB
/
frontcontroller.class.php
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
<?php
/** @file frontcontroller.class.php Centralized point of entry
*
* Also oversees and routes HTTP request interpretation to plugins.
*
* @authors Copyright © 2009-2013 Daniel Swanson <danij@dengine.net>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
// Define the "platform", our expected default configuration.
require_once('includes/platform.inc.php');
includeGuard('FrontController');
require(DIR_INCLUDES.'/utilities.inc.php');
require_once(DIR_CLASSES.'/contentcache.class.php');
require_once(DIR_CLASSES.'/actions.class.php');
require_once(DIR_CLASSES.'/request.class.php');
require_once(DIR_CLASSES.'/plugins.class.php');
require_once(DIR_CLASSES.'/actioner.interface.php');
require_once(DIR_CLASSES.'/requestinterpreter.interface.php');
class FrontController
{
private static $singleton = NULL;
private $_request;
private $_plugins;
private $_actions;
private $_contentCache = NULL;
private $_visibleErrors = false;
private $_homeURL = '';
private $_siteTitle = 'Website';
private $_siteAuthor = 'Author';
private $_siteAuthorEmail = 'N/A';
private $_siteDesigner = 'N/A';
private $_siteDesignerEmail = 'N/A';
private $_siteCopyright = 'N/A';
private $_siteDescription = '';
private $_siteRobotRevisitDays = 0;
private $_defaultPageKeywords = NULL;
private function parseConfig($config)
{
if(!is_array($config))
return;
if(array_key_exists('VisibleErrors', $config))
$this->_visibleErrors = (bool) $config['VisibleErrors'];
if(array_key_exists('HomeAddress', $config))
$this->_homeURL = $config['HomeAddress'];
if(array_key_exists('Title', $config))
$this->_siteTitle = $config['Title'];
if(array_key_exists('Author', $config))
$this->_siteAuthor = $config['Author'];
if(array_key_exists('AuthorEmail', $config))
$this->_siteAuthorEmail = $config['AuthorEmail'];
if(array_key_exists('Designer', $config))
$this->_siteDesigner = $config['Designer'];
if(array_key_exists('DesignerEmail', $config))
$this->_siteDesignerEmail = $config['DesignerEmail'];
if(array_key_exists('HomeURL', $config))
$this->_siteHomeURL = $config['HomeURL'];
if(array_key_exists('Copyright', $config))
$this->_siteCopyright = $config['Copyright'];
if(array_key_exists('Description', $config))
$this->_siteDescription = $config['Description'];
if(array_key_exists('RobotRevisitDays', $config))
$this->_siteRobotRevisitDays = $config['RobotRevisitDays'];
if(array_key_exists('Keywords', $config))
$this->_defaultPageKeywords = $config['Keywords'];
}
private function __construct($config)
{
if(!is_array($config))
throw new Exception('Invalid config, array expected');
if((double)phpversion() < 5.1)
throw new Exception('PHP version 5.1 required.');
$this->parseConfig($config);
// Set error handling behavior.
error_reporting(E_ALL);
ini_set('display_errors', (bool) $this->_visibleErrors);
ini_set('display_startup_errors', (bool) $this->_visibleErrors);
set_error_handler(array(&$this,"ErrorHandler"));
// Locate plugins.
$this->_plugins = new Plugins(DIR_PLUGINS);
// Construct the Request
$url = ($_SERVER['SERVER_PORT'] == '443' ? 'https' : 'http') .'://';
if(isset($_SERVER['HTTP_HOST']))
$url .= $_SERVER['HTTP_HOST'];
if(isset($_SERVER['REQUEST_URI']))
$url .= $_SERVER['REQUEST_URI'];
$this->_request = new Request($url, $_POST);
$this->_actions = new Actions();
}
private function __clone() {}
/**
* Returns the Singleton front controller instance.
*/
public static function &fc()
{
if(is_null(self::$singleton))
{
$siteconfig = array();
include('./config.inc.php');
self::$singleton = new FrontController($siteconfig);
}
return self::$singleton;
}
public function &request()
{
return $this->_request;
}
public function &plugins()
{
return $this->_plugins;
}
public function findPlugin($pluginName)
{
return $this->plugins()->find($pluginName);
}
public function siteTitle()
{
return $this->_siteTitle;
}
public function siteAuthor()
{
return $this->_siteAuthor;
}
public function siteAuthorEmail()
{
return $this->_siteAuthorEmail;
}
public function siteDesigner()
{
return $this->_siteDesigner;
}
public function siteDesignerEmail()
{
return $this->_siteDesignerEmail;
}
public function siteCopyright()
{
return $this->_siteCopyright;
}
public function siteDescription()
{
return $this->_siteDescription;
}
public function robotRevisitDays()
{
return $this->_siteRobotRevisitDays;
}
public function &defaultPageKeywords()
{
return $this->_defaultPageKeywords;
}
public function homeURL()
{
return $this->_homeURL;
}
public function enqueueAction($actioner, $args=NULL)
{
try
{
$this->_actions->enqueue($actioner, $args);
}
catch(Exception $e)
{
throw new Exception('Failed to enqueue Action');
}
}
public function interpretRequest()
{
// Determine action:
try
{
// Maybe a plugin?
$this->plugins()->interpretRequest($this->_request);
foreach($this->_actions as $ActionRecord)
{
try
{
$ActionRecord['actioner']->execute($ActionRecord['args']);
}
catch(Exception $e)
{
throw $e; // Lets simply re-throw and abort for now.
}
}
}
catch(Exception $e)
{
// We'll show the homepage.
$this->enqueueAction($this->findPlugin('home'), NULL);
}
}
private function &getContentCache()
{
if(!is_object($this->_contentCache))
{
$this->_contentCache = new ContentCache(DIR_CACHE);
}
return $this->_contentCache;
}
public static function &contentCache()
{
return self::fc()->getContentCache();
}
public static function ErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
$errortype = array (
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parsing Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
E_STRICT => 'Runtime Notice'
);
// Log it?
if(ini_get('log_errors'))
{
error_log(sprintf("PHP %s: %s in %s on line %d",
isset($errortype[$errno])? $errortype[$errno] : "$errno", $errmsg, $filename, $linenum));
}
// Display it?
if(ini_get('display_errors'))
{
printf("<br />\n<b>%s</b>: %s in <b>%s</b> on line <b>%d</b><br /><br />\n",
$errortype[$errno], $errmsg, $filename, $linenum);
return true;
}
switch($errno)
{
case E_NOTICE:
case E_USER_NOTICE:
case E_USER_WARNING:
case E_STRICT:
return true;
default:
exit(); // Get out of here!
}
}
public function outputHeader($mainHeading='')
{
$siteTitle = $this->siteTitle();
if(strlen($mainHeading) > 0)
$siteTitle = "$mainHeading • $siteTitle";
header('X-Frame-Options: SAMEORIGIN');
?><!DOCTYPE html>
<html dir="ltr" lang="en-GB">
<head>
<title><?=$siteTitle?></title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<meta name="author" content="<?=$this->siteAuthor()?>" />
<meta name="keywords" content="<?php { $keywords = $this->defaultPageKeywords(); foreach($keywords as $keyword) echo $keyword.','; } ?>" />
<meta name="description" content="<?=$this->siteDescription()?>" />
<meta name="robots" content="index, follow" />
<meta name="revisit-after" content="<?=$this->robotRevisitDays()?> DAYS" />
<meta name="rating" content="GENERAL" />
<meta name="generator" content="<?=$this->homeURL()?>" />
<link rel="icon" href="http://dl.dropboxusercontent.com/u/11948701/dengine.net/images/favicon.png" type="image/png" />
<link rel="shortcut icon" href="http://dl.dropboxusercontent.com/u/11948701/dengine.net/images/favicon.png" type="image/png" />
<link rel="alternate" type="application/rss+xml" title="Doomsday Engine RSS News Feed" href="http://dengine.net/forums/rss.php?mode=news" />
<!-- jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" media="all" href="/style.css" />
</head>
<?php
}
public function beginPage($mainHeading='', $page=null)
{
?>
<body>
<div id="mainouter">
<div id="main">
<?php
$this->outputMainMenu($page);
?>
<div id="maininner">
<div id="framepanel_bottom" role="main">
<div id="pageheading">
<h1><?php
if(strlen($mainHeading) > 0)
echo htmlspecialchars($mainHeading);
else
echo $this->siteTitle();
?></h1>
</div>
<?php
}
public function endPage()
{
?>
</div>
<div class="framepanel" id="framepanel_top">
<?php
$this->outputTopPanel();
?> <div id="servers"><?php
$this->outputMasterStatus();
?> </div><?php
?>
</div>
</div>
</div>
</div>
<div id="libicons">
<?php
// Output the lib icons (OpenGL, SDL etc).
includeHTML('libraryicons');
?>
</div>
<footer id="footer" role="contentinfo">
<?php
$this->outputFooter();
?>
</footer>
</body>
</html>
<?php
}
/**
* Generate HTML markup for a summary of this server.
*/
private function generateServerSummary(&$info)
{
if(!is_array($info))
throw new Exception('Invalid info argument, array expected.');
$serverMetadataLabel = 'Address: '. htmlspecialchars($info['at']).':'. htmlspecialchars($info['port'])
.' Open: '. ($info['open']? 'yes':'no');
// Should we include the extra info?
/*.' Info: '. htmlspecialchars($info['info']);*/
// Any required addons?.
$addonArr = array_filter(explode(';', $info['pwads']));
if(count($addonArr))
{
$serverMetadataLabel .= 'Add-ons: '. implode(' ', $addonArr);
}
// Format the game setup label.
$setupArr = array_filter(explode(' ', $info['setup']));
$gameMetadataLabel = 'Map: '. htmlspecialchars($info['map']) .' Setup: '. htmlspecialchars(implode(' ', $setupArr));
$playerCountLabel = 'Number of players currently in-game';
$playerMaxLabel = 'Maximum number of players';
// Begin html generation.
$html = '<span class="player-summary"><label title="'. htmlspecialchars($playerCountLabel) .'">'. htmlspecialchars($info['nump']) .'</label> / <label title="'. htmlspecialchars($playerMaxLabel) .'">'. htmlspecialchars($info['maxp']) .'</label></span> '
.'<label title="'. htmlspecialchars($serverMetadataLabel) .'"><span class="name">'. htmlspecialchars($info['name']) .'</span></label> '
.'<label title="'. htmlspecialchars($gameMetadataLabel) .'"><span class="game-mode">'. htmlspecialchars($info['mode']) .'</span></label>';
// Wrap it in the container used for styling and visual element ordering.
return '<span class="server">'. $html .'</span>';
}
public static function serverSorter($b, $a)
{
// Open servers are grouped together.
$diff = (integer)($b['open'] - $a['open']);
if($diff) return $diff;
// Servers with active players get priority
$diff = (integer)($b['nump'] - $a['nump']);
if($diff) return -($diff);
// Order by lexicographical difference in the server name.
$diff = strcmp($b['mode'], $a['mode']);
if($diff) return $diff;
// Order by lexicographical difference in the server name.
return strcmp($b['name'], $a['name']);
}
private function outputMasterStatus()
{
// Maximum number of servers listed in the summary.
$limit = 3;
$content = '';
/**
* @todo We do NOT need to interface with the master server. We are able
* to implement all expected functionality by simply parsing the
* XML feed output.
*/
require_once(DIR_CLASSES.'/masterserver.class.php');
$db = new MasterServer();
// Build the servers collection.
$servers = array();
while(list($ident, $info) = each($db->servers))
{
if(!is_array($info)) continue;
$servers[] = $info;
}
// Sort the collection.
uasort($servers, array('self', 'serverSorter'));
$serverCount = count($servers);
// Generate the content.
$content .= '<span id="servers-label">'. ($serverCount > 0? 'Most Active Servers':'No Active Servers') .'</span><br />';
if($serverCount)
{
$playerCount = (integer)0;
foreach($servers as &$server)
{
$playerCount += $server['nump'];
}
$content .= '<ul>';
$n = (integer)0;
foreach($servers as &$server)
{
if($limit !== 0 && $n++ == $limit) break;
$content .= '<li>'. $this->generateServerSummary($server) .'</li>';
}
$content .= '</ul>';
$content .= '<span id="summary"><a href="/masterserver" title="Click here to see the complete server listing">'. ("$serverCount ". ($serverCount === 1? 'server':'servers') ." in total, {$playerCount} active ". ($playerCount === 1? 'player':'players')) .'</a></span>';
}
$content .= '<br /><span id="servers-timestamp">'. date("d-M-y H:i:s T" /*DATE_RFC850*/, time()). '</span>';
echo $content;
}
private function buildTabs($tabs, $page=NULL, $normalClassName=NULL, $selectClassName=NULL)
{
$result = "";
if(is_array($tabs))
{
for($i = 0; $i < count($tabs); ++$i)
{
$tab = $tabs[$i];
$result .= '<li>';
if(!is_null($page) && !strcasecmp($page, substr($tab['page'], 1)))
{
$result .= '<span ';
if(isset($selectClassName))
$result .= "class=\"$selectClassName\" ";
$result .= '>'.$tab['label'].'</span>';
}
else
{
$result .= '<a ';
if(isset($normalClassName))
$result .= "class=\"$normalClassName\" ";
$result .= 'href="'.$tab['page'].'" title="'.$tab['tooltip'].'">'.$tab['label'].'</a>';
}
$result .= '</li>';
}
}
return $result;
}
private function outputMainMenu($page=NULL)
{
$leftTabs = array();
$leftTabs[] = array('page'=>'/engine', 'label'=>'Engine', 'tooltip'=>'About Doomsday Engine');
$leftTabs[] = array('page'=>'/games', 'label'=>'Games', 'tooltip'=>'Games playable with Doomsday Engine');
$leftTabs[] = array('page'=>'/dew', 'label'=>'Wiki', 'tooltip'=>'Doomsday Engine Wiki');
$rightTabs = array();
$rightTabs[] = array('page'=>'/addons', 'label'=>'Add-ons', 'tooltip'=>'Add-ons for games playable with Doomsday Engine');
$rightTabs[] = array('page'=>'/forums', 'label'=>'Forums', 'tooltip'=>'Doomsday Engine User Forums');
$rightTabs[] = array('page'=>'/masterserver', 'label'=>'Servers', 'tooltip'=>'Doomsday Engine Master Server');
?>
<div id="menuouter"><nav id="menu" class="hnav">
<div id="divider"></div>
<ul><section class="left">
<?php
echo $this->buildTabs($leftTabs, $page, "paddle_left", "paddle_left_select");
?></section>
<li class="logo"><a href="/" title="<?=$this->homeURL()?>"><span class="hidden">.</span></a></li><section class="right">
<?php
echo $this->buildTabs($rightTabs, $page, "paddle_right", "paddle_right_select");
?></section>
</ul>
<div id="divider2"></div>
</nav></div>
<?php
}
private function outputTopPanel()
{
?>
<div id="panorama">
</div>
<?php
}
private function outputFooter()
{
?>
<p class="disclaimer"><a href="mailto:webmaster@dengine.net" title="Contact Webmaster">Webmaster</a> - Site design © <?php echo date('Y'); ?> <a href="mailto:<?php echo $this->siteDesignerEmail(); ?>" title="Contact <?php echo $this->siteDesigner(); ?>"><?php echo $this->siteDesigner(); ?></a> - Built by <a href="mailto:<?php echo $this->siteDesignerEmail(); ?>" title="Contact <?php echo $this->siteDesigner(); ?>"><?php echo $this->siteDesigner(); ?></a> / <a href="mailto:<?php echo $this->siteAuthorEmail(); ?>" title="Contact <?php echo $this->siteAuthor(); ?>"><?php echo $this->siteAuthor(); ?></a></p>
<p class="disclaimer">The Doomsday Engine is licensed under the terms of the <a href="http://www.gnu.org/licenses/gpl.html" rel="nofollow">GNU/GPL License ver 2</a>. The Doomsday Engine logo is Copyright © 2005-<?php echo date('Y'); ?>, the deng team.</p>
<hr />
<?php
includeHTML('legal');
}
}