Passed
Push — develop ( eb55f7...e088af )
by Felipe
04:32
created

src/lib.inc.php (1 issue)

Labels
Severity
1
<?php
2
3
/**
4
 * Function library read in upon startup
5
 *
6
 * $Id: lib.inc.php,v 1.123 2008/04/06 01:10:35 xzilla Exp $
7
 */
8
9
defined('BASE_PATH') or DEFINE('BASE_PATH', dirname(__DIR__));
10
11
DEFINE('THEME_PATH', BASE_PATH . '/src/themes');
12
// Enforce PHP environment
13
ini_set('arg_separator.output', '&amp;');
14
15
ini_set('error_log', BASE_PATH . '/temp/logs/phppga.php_error.log');
16
17
// Check to see if the configuration file exists, if not, explain
18
if (file_exists(BASE_PATH . '/config.inc.php')) {
19
    $conf = [];
20
    include BASE_PATH . '/config.inc.php';
21
} else {
22
    die('Configuration error: Copy config.inc.php-dist to config.inc.php and edit appropriately.');
23
}
24
$debugmode = (!isset($conf['debugmode'])) ? false : boolval($conf['debugmode']);
25
DEFINE('DEBUGMODE', $debugmode);
26
27
require_once BASE_PATH . '/vendor/autoload.php';
28
29
if (!defined('ADODB_ERROR_HANDLER_TYPE')) {
30
    define('ADODB_ERROR_HANDLER_TYPE', E_USER_ERROR);
31
}
32
33
if (!defined('ADODB_ERROR_HANDLER')) {
34
    define('ADODB_ERROR_HANDLER', '\PHPPgAdmin\Misc::adodb_throw');
35
}
36
37
// Start session (if not auto-started)
38
if (!ini_get('session.auto_start')) {
39
    session_name('PPA_ID');
40
    session_start();
41
}
42
43
$handler             = PhpConsole\Handler::getInstance();
44
\Kint::$enabled_mode = DEBUGMODE;
45
ini_set('display_errors', intval(DEBUGMODE));
46
ini_set('display_startup_errors', intval(DEBUGMODE));
47
if (DEBUGMODE) {
48
    error_reporting(E_ALL);
49
} else {
50
    $handler->setHandleErrors(false); // disable errors handling
51
    $handler->setHandleExceptions(false); // disable exceptions handling
52
    $handler->setCallOldHandlers(true); // disable passing errors & exceptions to prviously defined handlers
53
}
54
55
$handler->start(); // initialize handlers*/
56
\PhpConsole\Helper::register(); // it will register global PC class
57
58
$composerinfo = json_decode(file_get_contents(BASE_PATH . '/composer.json'));
59
$appVersion   = $composerinfo->version;
60
61
$config = [
62
    'msg'       => '',
63
    'appThemes' => [
64
        'default'    => 'Default',
65
        'cappuccino' => 'Cappuccino',
66
        'gotar'      => 'Blue/Green',
67
        'bootstrap'  => 'Bootstrap3',
68
    ],
69
    'settings'  => [
70
        'determineRouteBeforeAppMiddleware' => true,
71
        'base_path'                         => BASE_PATH,
72
        'debug'                             => DEBUGMODE,
73
74
        // Configuration file version.  If this is greater than that in config.inc.php, then
75
        // the app will refuse to run.  This and $conf['version'] should be incremented whenever
76
        // backwards incompatible changes are made to config.inc.php-dist.
77
        'base_version'                      => 60,
78
        // Application version
79
        'appVersion'                        => 'v' . $appVersion,
80
        // Application name
81
        'appName'                           => 'phpPgAdmin6',
82
83
        // PostgreSQL and PHP minimum version
84
        'postgresqlMinVer'                  => '9.3',
85
        'phpMinVer'                         => '5.6',
86
        'displayErrorDetails'               => DEBUGMODE,
87
        'addContentLengthHeader'            => false,
88
    ],
89
];
90
91
$app = new \Slim\App($config);
92
93
// Fetch DI Container
94
$container = $app->getContainer();
95
96
//\Kint::dump($container->environment);die();
97
98
$normalized_php_self = str_replace('/src/views', '', $container->environment->get('PHP_SELF'));
99
$subfolder           = str_replace('/' . basename($normalized_php_self), '', $normalized_php_self);
100
define('SUBFOLDER', $subfolder);
101
102
$container['version']     = 'v' . $appVersion;
103
$container['errors']      = [];
104
$container['requestobj']  = $container['request'];
105
$container['responseobj'] = $container['response'];
106
107
$container['utils'] = function ($c) {
108
    $utils = new \PHPPgAdmin\ContainerUtils($c);
109
    return $utils;
110
};
111
112
$container['conf'] = function ($c) use ($conf) {
113
114
    //\Kint::dump($conf);
115
    // Plugins are removed
116
    $conf['plugins'] = [];
117
118
    return $conf;
119
};
120
121
$container['lang'] = function ($c) {
122
    include_once BASE_PATH . '/src/translations.php';
123
124
    $c['appLangFiles'] = $appLangFiles;
125
    $c['language']     = $_language;
126
    $c['isolang']      = $_isolang;
127
128
    return $lang;
129
};
130
131
$container['plugin_manager'] = function ($c) {
132
    $plugin_manager = new \PHPPgAdmin\PluginManager($c);
133
    return $plugin_manager;
134
};
135
136
$container['serializer'] = function ($c) {
137
    $serializerbuilder = \JMS\Serializer\SerializerBuilder::create();
138
    $serializer        = $serializerbuilder
139
        ->setCacheDir(BASE_PATH . '/temp/jms')
140
        ->setDebug($c->get('settings')['debug'])
141
        ->build();
142
    return $serializer;
143
};
144
145
// Create Misc class references
146
$container['misc'] = function ($c) {
147
    $misc = new \PHPPgAdmin\Misc($c);
148
149
    $conf = $c->get('conf');
150
151
    // 4. Check for theme by server/db/user
152
    $_server_info = $misc->getServerInfo();
153
154
    //\PC::debug($_server_info, 'server info');
155
156
    /* starting with PostgreSQL 9.0, we can set the application name */
157
    if (isset($_server_info['pgVersion']) && $_server_info['pgVersion'] >= 9) {
158
        putenv('PGAPPNAME=' . $c->get('settings')['appName'] . '_' . $c->get('settings')['appVersion']);
159
    }
160
161
    $themefolders = [];
162
    if ($gestor = opendir(THEME_PATH)) {
163
164
        /* This is the right way to iterate on a folder */
165
        while (false !== ($foldername = readdir($gestor))) {
166
            if ($foldername == '.' || $foldername == '..') {
167
                continue;
168
            }
169
170
            $folderpath = THEME_PATH . DIRECTORY_SEPARATOR . $foldername;
171
172
            // if $folderpath if indeed a folder and contains a global.css file, then it's a theme
173
            if (is_dir($folderpath) && is_file($folderpath . DIRECTORY_SEPARATOR . 'global.css')) {
174
                $themefolders[$foldername] = $folderpath;
175
            }
176
        }
177
178
        closedir($gestor);
179
    }
180
181
    //\PC::debug($themefolders, 'themefolders');
182
    /* select the theme */
183
    unset($_theme);
184
185
    // List of themes
186
    if (!isset($conf['theme'])) {
187
        $conf['theme'] = 'default';
188
    }
189
    // 1. Check for the theme from a request var.
190
    // This happens when you use the selector in the intro screen
191
    if (isset($_REQUEST['theme']) && array_key_exists($_REQUEST['theme'], $themefolders)) {
192
        $_theme = $_REQUEST['theme'];
193
    }
194
    // 2. Check for theme session var
195
    elseif (!isset($_theme) && isset($_SESSION['ppaTheme']) && array_key_exists($_SESSION['ppaTheme'], $themefolders)) {
196
        $_theme = $_SESSION['ppaTheme'];
197
    }
198
    // 3. Check for theme in cookie var
199
    elseif (!isset($_theme) && isset($_COOKIE['ppaTheme']) && array_key_exists($_COOKIE['ppaTheme'], $themefolders)) {
200
        $_theme = $_COOKIE['ppaTheme'];
201
    }
202
203
    if (!isset($_theme) && !is_null($_server_info) && array_key_exists('theme', $_server_info)) {
204
        $server_theme = $_server_info['theme'];
205
206
        if (isset($server_theme['default']) && array_key_exists($server_theme['default'], $themefolders)) {
207
            $_theme = $server_theme['default'];
208
        }
209
210
        if (isset($_REQUEST['database'])
211
            && isset($server_theme['db'][$_REQUEST['database']])
212
            && array_key_exists($server_theme['db'][$_REQUEST['database']], $themefolders)
213
214
        ) {
215
            $_theme = $server_theme['db'][$_REQUEST['database']];
216
        }
217
218
        if (isset($_server_info['username'])
219
            && isset($server_theme['user'][$_server_info['username']])
220
            && array_key_exists($server_theme['user'][$_server_info['username']], $themefolders)
221
        ) {
222
            $_theme = $server_theme['user'][$_server_info['username']];
223
        }
224
    }
225
    // if any of the above conditions had set the $_theme variable
226
    // then we store it in the session and a cookie
227
    // and we overwrite $conf['theme'] with its value
228
    if (isset($_theme)) {
229
        /* save the selected theme in cookie for a year */
230
        setcookie('ppaTheme', $_theme, time() + 31536000, '/');
231
        $_SESSION['ppaTheme'] = $_theme;
232
        $conf['theme']        = $_theme;
233
    }
234
235
    $misc->setConf('theme', $conf['theme']);
236
237
    $misc->setHREF();
238
    $misc->setForm();
239
240
    return $misc;
241
};
242
243
// Register Twig View helper
244
$container['view'] = function ($c) {
245
    $conf = $c->get('conf');
246
    $misc = $c->misc;
247
248
    $view = new \Slim\Views\Twig(BASE_PATH . '/templates', [
249
        'cache'       => BASE_PATH . '/temp/twigcache',
250
        'auto_reload' => $c->get('settings')['debug'],
251
        'debug'       => $c->get('settings')['debug'],
252
    ]);
253
    $environment               = $c->get('environment');
254
    $base_script_trailing_shit = substr($environment['SCRIPT_NAME'], 1);
255
    $request_basepath          = $c['request']->getUri()->getBasePath();
256
    // Instantiate and add Slim specific extension
257
    $basePath = rtrim(str_ireplace($base_script_trailing_shit, '', $request_basepath), '/');
258
259
    $view->addExtension(new Slim\Views\TwigExtension($c['router'], $basePath));
260
261
    $view->offsetSet('subfolder', SUBFOLDER);
262
    $view->offsetSet('theme', $c->misc->getConf('theme'));
263
    $view->offsetSet('Favicon', $c->misc->icon('Favicon'));
264
    $view->offsetSet('Introduction', $c->misc->icon('Introduction'));
265
    $view->offsetSet('lang', $c->lang);
266
267
    $view->offsetSet('applangdir', $c->lang['applangdir']);
268
269
    $view->offsetSet('appName', $c->get('settings')['appName']);
270
271
    $misc->setView($view);
272
273
    //\PC::debug($c->conf, 'conf');
274
    //\PC::debug($c->view->offsetGet('subfolder'), 'subfolder');
275
    //\PC::debug($c->view->offsetGet('theme'), 'theme');
276
277
    return $view;
278
};
279
280
$container['haltHandler'] = function ($c) {
281
    return function ($request, $response, $exits, $status = 500) use ($c) {
282
        $title = 'PHPPgAdmin Error';
283
284
        $html = '<p>The application could not run because of the following error:</p>';
285
286
        $output = sprintf(
287
            "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>" .
288
            '<title>%s</title><style>' .
289
            'body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}' .
290
            'h3{margin:0;font-size:28px;font-weight:normal;line-height:30px;}' .
291
            'span{display:inline-block;font-size:16px;}' .
292
            '</style></head><body><h3>%s</h3><p>%s</p><span>%s</span></body></html>',
293
            $title,
294
            $title,
295
            $html,
296
            implode('<br>', $exits)
297
        );
298
299
        $body = new \Slim\Http\Body(fopen('php://temp', 'r+'));
0 ignored issues
show
It seems like fopen('php://temp', 'r+') can also be of type false; however, parameter $stream of Slim\Http\Body::__construct() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

299
        $body = new \Slim\Http\Body(/** @scrutinizer ignore-type */ fopen('php://temp', 'r+'));
Loading history...
300
        $body->write($output);
301
302
        return $response
303
            ->withStatus($status)
304
            ->withHeader('Content-type', 'text/html')
305
            ->withBody($body);
306
    };
307
};
308
309
// Set the requestobj and responseobj properties of the container
310
// as the value of $request and $response, which already contain the route
311
$app->add(function ($request, $response, $next) {
312
    $this['requestobj']  = $request;
313
    $this['responseobj'] = $response;
314
315
    $misc = $this->get('misc');
316
317
    $this->view->offsetSet('METHOD', $request->getMethod());
318
    $this->view->offsetSet('subject', $request->getAttribute('route')->getArgument('subject'));
319
320
    $query_string = $request->getUri()->getQuery();
321
    $this->view->offsetSet('query_string', $query_string);
322
    $path = SUBFOLDER . '/' . $request->getUri()->getPath() . ($query_string ? '?' . $query_string : '');
323
    $this->view->offsetSet('path', $path);
324
325
    $params = $request->getParams();
326
327
    // remove tabs and linebreaks from query
328
    if (isset($params['query'])) {
329
        $params['query'] = str_replace(["\r", "\n", "\t"], ' ', $params['query']);
330
    }
331
    $this->view->offsetSet('params', $params);
332
333
    //return $this->utils->die('hola');
334
335
    if (count($this['errors']) > 0) {
336
        return ($this->haltHandler)($this->requestobj, $this->responseobj, $this['errors'], 412);
337
    }
338
    // First execute anything else
339
    $response = $next($request, $response);
340
341
    // Any other request, pass on current response
342
    return $response;
343
});
344
345
$container['action'] = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
346
347
if (!isset($msg)) {
348
    $msg = '';
349
}
350
351
$container['msg'] = $msg;
352