/
system_controller.class.php
400 lines (366 loc) · 13.5 KB
/
system_controller.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
<?php
require_once dirname(__FILE__).'/view.class.php';
class System_Controller
{
private $_view = NULL;
private $_friendly_errors = false;
private $_base_dir = '';
private $_object_cache = Array();
private $_transaction_depth = 0;
static private $instance = NULL;
/**
* Get the instance of the System Controller.
*
* Singleton pattern.
*
* @param type $base_dir The base directory.
* @return \System_Controller
*/
public static function get($base_dir=NULL)
{
static $instance = null;
if ($instance == NULL) {
$instance = new System_Controller($base_dir);
}
return $instance;
}
private function __construct($base_dir=NULL)
{
if (is_null($base_dir)) $base_dir = dirname(dirname(__FILE__));
$this->_base_dir = $base_dir;
$path_sep = defined('PATH_SEPARATOR') ? PATH_SEPARATOR : ((FALSE === strpos($_ENV['OS'], 'Win')) ? ';' : ':');
ini_set('include_path', ini_get('include_path').$path_sep.$this->_base_dir);
if (!isset($_SESSION['views'][$base_dir]) || isset($_REQUEST['regen'])) {
$_SESSION['views'][$base_dir] = Array();
$raw_filenames = glob($this->_base_dir.'/views/*.class.php');
natsort($raw_filenames);
foreach ($raw_filenames as $filename) {
$filename = basename($filename);
$classname = null;
if (preg_match('/^view_([0-9]*)_(.*)__([0-9]*)_(.*)\.class\.php/', $filename, $matches)) {
$classname = 'View_'.$matches[2].'__'.$matches[4];
} else if (preg_match('/^view_([0-9]*)_(.*)\.class\.php/', $filename, $matches)) {
if ($matches[1] == 0) $matches[2] = '_'.$matches[2];
$classname = 'View_'.$matches[2];
}
if ($classname) {
include_once($this->_base_dir.'/views/'.$filename);
$showView = TRUE;
if ($view_perm = call_user_func(Array($classname, 'getMenuPermissionLevel'))) {
$showView = !empty($GLOBALS['user_system']) && $GLOBALS['user_system']->havePerm($view_perm);
} else if ($view_feature = call_user_func(Array($classname, 'getMenuRequiredFeature'))) {
$showView = $this->featureEnabled($view_feature);
}
if ($showView) {
if (preg_match('/^view_([0-9]*)_(.*)__([0-9]*)_(.*)\.class\.php/', $filename, $matches)) {
$_SESSION['views'][$base_dir][$matches[2]]['children'][$matches[4]]['filename'] = $filename;
} else if (preg_match('/^view_([0-9]*)_(.*)\.class\.php/', $filename, $matches)) {
if ($matches[1] == 0) $matches[2] = '_'.$matches[2];
$_SESSION['views'][$base_dir][$matches[2]]['filename'] = $filename;
}
}
}
}
}
}
public function initErrorHandler()
{
$error_level = defined('E_DEPRECATED') ? (E_ALL & ~constant('E_DEPRECATED') /*& ~constant('E_STRICT')*/) : E_ALL;
error_reporting($error_level);
set_error_handler(Array($this, '_handleError'));
set_exception_handler(Array($this, '_handleException'));
}
public function run()
{
$this->setGlobalHeaders();
if (!empty($_REQUEST['call'])) {
$this->initErrorHandler();
$call_name = str_replace('/', '', $_REQUEST['call']);
// Try both the Jethro and system_root calls folders
$filename = ''; //dirname(dirname(__FILE__)).'/calls/call_'.$call_name.'.class.php';
if (!file_exists($filename)) {
$filename = $this->_base_dir.'/calls/call_'.$call_name.'.class.php';
}
if (file_exists($filename)) {
include_once dirname(__FILE__).'/call.class.php';
include_once $filename;
$classname = 'Call_'.$call_name;
$call_obj = new $classname;
$call_obj->run();
} else {
trigger_error('Unknown call '.ents($_REQUEST['call']), E_USER_WARNING);
}
} else {
$this->initErrorHandler();
$raw_view_name = array_get($_REQUEST, 'view', 'home');
$bits = explode('__', $raw_view_name);
$view_filename = null;
if (count($bits) > 1) {
if (!empty($_SESSION['views'][$this->_base_dir][$bits[0]]['children'][$bits[1]])) {
$view_filename = $_SESSION['views'][$this->_base_dir][$bits[0]]['children'][$bits[1]]['filename'];
$view_classname = 'View_'.$bits[0].'__'.$bits[1];
}
} else if (isset($_SESSION['views'][$this->_base_dir][$bits[0]])
&& isset($_SESSION['views'][$this->_base_dir][$bits[0]]['filename'])) {
// NB if they have permission to a sub-view (eg services > view) but not to the top level
// view (eg services) then the view will be in the array but without a filename
$view_filename = $_SESSION['views'][$this->_base_dir][$bits[0]]['filename'];
$view_classname = 'View_'.$bits[0];
}
if (!is_null($view_filename)) {
require_once $this->_base_dir.'/views/'.$view_filename;
$view_perm = call_user_func(Array($view_classname, 'getMenuPermissionLevel'));
if (!empty($view_perm) && !$GLOBALS['user_system']->havePerm($view_perm)) {
trigger_error("You don't have permission to access this view", E_USER_ERROR); // exits
}
$this->_view = new $view_classname();
$this->_view->processView();
}
require $this->_base_dir.'/templates/main.template.php';
restore_error_handler();
}
}
public function getTitle()
{
if (is_null($this->_view)) {
return '';
} else {
return $this->_view->getTitle();
}
}
public function shouldShowNavigation()
{
if ($this->_view) return $this->_view->shouldShowNavigation();
}
public function printNavigation()
{
if ($this->_view && !$this->_view->shouldShowNavigation()) return;
$current_view = array_get($_REQUEST, 'view', 'home');
foreach ($_SESSION['views'][$this->_base_dir] as $name => $data) {
if ($name[0] == '_') continue;
$class = '';
if (($current_view == $name) || (strpos($current_view, $name.'__') === 0)) $class = 'active';
if (empty($data['children'])) {
// deliberately - only leaf nodes can be navigated to directly
?>
<li class="<?php echo $class; ?>">
<a href="?view=<?php echo $name; ?>" ><?php echo ucwords(str_replace('_', ' ', $name)); ?></a>
</li>
<?php
} else {
// pardon the formatting - IE is having a white-space tantrum
?>
<li class="<?php echo $class; ?> dropdown">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"><?php echo gettext(ucwords(str_replace('_', ' ', $name))); ?><i class="caret"></i></a>
<ul class="dropdown-menu"><?php
foreach ($data['children'] as $subname => $sub_details) {
$class = ($current_view == $name.'__'.$subname) ? 'active' : '';
?><li class="<?php echo $class; ?>"><a href="?view=<?php echo $name.'__'.$subname; ?>"><?php echo gettext(ucwords(str_replace('_', ' ', $subname))); ?></a></li><?php
}
?></ul>
</li>
<?php
}
}
}
public function printBody()
{
if (is_null($this->_view)) {
echo 'Error: Undefined view';
} else {
$this->_view->printView();
}
}
public function includeDBClass($classname)
{
$classname = strtolower($classname);
require_once dirname(__FILE__).'/db_object.class.php';
require_once 'db_objects/'.$classname.'.class.php';
}
public function getDBObject($classname, $id)
{
if (!isset($this->_object_cache[$classname]) || !isset($this->_object_cache[$classname][$id])) {
$this->includeDBClass($classname);
$this->_object_cache[$classname][$id] = new $classname($id);
if (!$this->_object_cache[$classname][$id]->id) $this->_object_cache[$classname][$id] = null;
}
return $this->_object_cache[$classname][$id];
}
public function getDBObjectData($classname, $params=Array(), $logic='OR', $order='', $refreshCache=FALSE)
{
static $cache = Array();
$cacheKey = "$classname-$logic-$order-".serialize($params);
if ($refreshCache || !isset($cache[$cacheKey])) {
$this->includeDBClass($classname);
$sample = new $classname();
$cache[$cacheKey] = $sample->getInstancesData($params, $logic, $order);
}
return $cache[$cacheKey];
}
public function doTransaction($operation)
{
switch (strtoupper($operation)) {
case 'BEGIN':
$this->_transaction_depth++;
if ($this->_transaction_depth == 1) $GLOBALS['db']->beginTransaction();
break;
case 'COMMIT':
$this->_transaction_depth--;
if ($this->_transaction_depth == 0) $GLOBALS['db']->commit();
break;
case 'ROLLBACK':
// Rollback always rolls back everything
@$GLOBALS['db']->rollback();
$this->_transaction_depth--;
}
}
public function setFriendlyErrors($enabled)
{
$this->_friendly_errors = $enabled;
}
public function _handleError($errno, $errstr, $errfile, $errline)
{
if (error_reporting() == 0) return; // the "@" shutup-operator was used
$send_email = true;
$showTechDetails = ifdef('SHOW_ERROR_DETAILS', (JETHRO_VERSION == 'DEV'));
$exit = false;
switch ($errno) {
case E_ERROR:
case E_USER_ERROR:
if (FALSE !== strpos($errstr, 'variables should be assigned by reference')) return;
$bg = 'error';
$title = 'SYSTEM ERROR (ERROR)';
$exit = true;
break;
case E_WARNING:
case E_USER_WARNING:
$bg = 'warning';
$title = 'SYSTEM ERROR (WARNING)';
break;
case E_NOTICE:
$bg = $showTechDetails ? 'info' : NULL; // on prod, send emails but show nothing in browser
$title = 'SYSTEM ERROR (NOTICE)';
break;
case E_USER_NOTICE:
$send_email = false; // never send emails for E_USER_NOTICE
if ($this->_friendly_errors || (!headers_sent() && !$showTechDetails)) {
add_message('Error: '.$errstr, 'failure');
return;
} else if (!$showTechDetails) {
// if headers are sent, print it now - we don't want it on the next page load
print_message('Error: '.$errstr, 'failure');
return;
}
$bg = 'warning';
$title = 'NOTICE';
break;
default:
$bg = 'info';
$title = 'SYSTEM ERROR';
break;
}
$bt = debug_backtrace();
array_shift($bt); // remove reference to this handleError function
$this->_reportError($title, $bg, $errstr, $errfile, $errline, $bt, $send_email);
if ($exit) exit();
}
private function _reportError($title, $bg, $errstr, $errfile, $errline, $bt, $send_email)
{
foreach ($bt as &$b) {
if (!empty($b['args'])) {
foreach ($b['args'] as &$v) {
if (!is_scalar($v)) $v = '[Object/Array]';
}
}
unset($b['object']);
}
$showTechDetails = ifdef('SHOW_ERROR_DETAILS', (JETHRO_VERSION == 'DEV'));
if ($bg) {
?>
<div class="alert<?php if(isset($bg)){ echo" alert-".$bg;} ?>">
<?php
if ($showTechDetails || !$send_email) {
?>
<h4><?php echo $title; ?></h4>
<p><?php echo $errstr; ?></p>
<?php
} else {
echo _('An error occurred. Please contact your system administrator for help.');
}
if ($showTechDetails) {
?>
<u class="clickable" onclick="var parentDiv=this.parentNode; while (parentDiv.tagName != 'DIV') { parentDiv = parentDiv.parentNode; }; with (parentDiv.getElementsByTagName('PRE')[0].style) { display = (display == 'block') ? 'none' : 'block' }">Show Details</u>
<pre style="display: none; background: white; font-weight: normal; color: black"><b>Line <?php echo $errline; ?> of File <?php echo $errfile; ?></b>
<?php
print_r($bt);
?>
</pre>
<?php
}
?>
</div>
<?php
}
if ($send_email && defined('ERRORS_EMAIL_ADDRESS') && constant('ERRORS_EMAIL_ADDRESS')) {
$content = "$errstr \nLine $errline of $errfile\n\n";
if (!empty($GLOBALS['user_system'])) {
$content .= "USER: ".$GLOBALS['user_system']->getCurrentPerson('id')." ".$GLOBALS['user_system']->getCurrentUser('user')."\n";
}
$content .= 'REFERER: '.array_get($_SERVER, 'HTTP_REFERER', '')."\n";
$content .= 'USER_AGENT: '.array_get($_SERVER, 'HTTP_USER_AGENT', '')."\n\n";
$safe_request = $_REQUEST;
unset($safe_request['password']);
$content .= "REQUEST: \n".print_r($safe_request,1)."\n\n";
$content .= "BACKTRACE:\n";
$content .= print_r($bt, 1);
@mail(constant('ERRORS_EMAIL_ADDRESS'), 'Jethro Error from '.BASE_URL, $content);
}
if ($send_email) error_log("$errstr - Line $errline of $errfile");
}
public function _handleException($exception)
{
$this->_reportError('Fatal Error (Exception)', 'error', $exception->getMessage(), $exception->getFile(), $exception->getLine(), $exception->getTrace(), TRUE);
exit();
}
public function runHooks($hook_name, $params)
{
require_once 'include/hook.class.php';
$dir = @opendir(JETHRO_ROOT.'/hooks/'.$hook_name);
while ($dir && ($hook_file = readdir($dir))) {
if (is_dir(JETHRO_ROOT.'/hooks/'.$hook_file)) continue;
if ($hook_file[0] == '.') continue;
if (0 === strpos($hook_file, 'sample.')) continue;
require_once 'hooks/'.$hook_name.'/'.$hook_file;
$class_name = str_replace('.class.php', '', $hook_file);
call_user_func(Array($class_name, 'run'), $params);
}
}
public function featureEnabled($feature)
{
$enabled_features = explode(',', strtoupper(ifdef('ENABLED_FEATURES', '')));
return in_array(strtoupper($feature), $enabled_features);
}
public static function checkConfigHealth()
{
if (REQUIRE_HTTPS && (FALSE === strpos(BASE_URL, 'https://'))) {
trigger_error("Configuration file error: If you set REQUIRE_HTTPS to true, your BASE_URL must start with https", E_USER_ERROR);
}
if (substr(BASE_URL, -1) != '/') {
trigger_error("Configuration file error: Your BASE_URL must end with a slash", E_USER_ERROR);
}
}
public function setGlobalHeaders()
{
if (session_id()) {
// log just a subset for security
header('X-Jethro-Session: '.substr(session_id(), 0, 5));
}
if (!empty($_SESSION['user'])) {
header('X-Jethro-User: '.array_get($_SESSION['user'], 'username'));
header('X-Jethro-UID: '.array_get($_SESSION['user'], 'id'));
} elseif (!empty($_SESSION['member'])) {
header('X-Jethro-User: '.array_get($_SESSION['member'], 'email'));
header('X-Jethro-UID: '.array_get($_SESSION['member'], 'id'));
}
}
}