Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ContainerUtils.php « classes « src - github.com/HuasoFoundries/phpPgAdmin6.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b1f03e1ec32f52ecbf14515f5e2d254e81baf831 (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
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
<?php

/**
 * PHPPgAdmin 6.1.3
 */

namespace PHPPgAdmin;

use ArrayAccess;
use PHPPgAdmin\Decorators\Decorator;
use PHPPgAdmin\Traits\HelperTrait;
use Psr\Container\ContainerInterface;
use Slim\App;
use Slim\Collection;
use Slim\Container;
use Slim\DefaultServicesProvider;
use Slim\Flash\Messages;
use Slim\Http\Request;
use Slim\Http\Response;

/**
 * @property array $deploy_info
 * @property Messages $flash
 * @property \GuzzleHttp\Client $fcIntranetClient
 * @property Misc $misc
 * @property ViewManager $view
 * @property Request $request
 * @property Response $response
 * @property string $BASE_PATH
 * @property string $THEME_PATH
 * @property string $subFolder
 * @property bool $DEBUGMODE
 * @property bool $IN_TEST
 * @property string  $server
 * @property string $database
 * @property string  $schema
 *
 * @method mixed get(string)
 */
class ContainerUtils extends Container implements ContainerInterface
{
    use HelperTrait;

    /**
     * @var null|self
     */
    private static $instance;

    /**
     * $appInstance.
     *
     * @var null|App
     */
    private static $appInstance;

    /**
     * Default settings.
     *
     * @var array
     */
    private $defaultSettings = [
        'httpVersion' => '1.1',
        'responseChunkSize' => 4096,
        'outputBuffering' => 'append',
        'determineRouteBeforeAppMiddleware' => false,
        'displayErrorDetails' => false,
        'addContentLengthHeader' => true,
        'routerCacheFile' => false,
    ];

    /**
     * Undocumented variable.
     *
     * @var array
     */
    private static $envConfig = [
        'BASE_PATH' => '',
        'subFolder' => '',
        'DEBUGMODE' => false,
        'THEME_PATH' => '',
    ];

    /**
     * @param array $values the parameters or objects
     */
    final public function __construct(array $values = [])
    {
        parent::__construct($values);

        $userSettings = $values['settings'] ?? [];
        $this->registerDefaultServices($userSettings);
        self::$instance = $this;
    }

    /**
     * Gets the subfolder.
     *
     * @param string $path The path
     *
     * @return string the subfolder
     */
    public function getSubfolder(string $path = ''): string
    {
        return \implode(\DIRECTORY_SEPARATOR, [$this->subFolder, $path]);
    }

    public static function getAppInstance(array $config = []): App
    {
        $config = \array_merge(self::getDefaultConfig($config['debugmode'] ?? false), $config);

        $container = self::getContainerInstance($config);

        if (!self::$appInstance) {
            self::$appInstance = new App($container);
        }

        return self::$appInstance;
    }

    public static function getContainerInstance(array $config = []): self
    {
        self::$envConfig = [
            'msg' => '',
            'appThemes' => [
                'default' => 'Default',
                'cappuccino' => 'Cappuccino',
                'gotar' => 'Blue/Green',
                'bootstrap' => 'Bootstrap3',
            ],
            'display_sizes' => ['schemas' => false, 'tables' => false],
            'BASE_PATH' => $config['BASE_PATH'] ?? \dirname(__DIR__, 2),
            'subFolder' => $config['subfolder'] ?? '',
            'debug' => $config['debugmode'] ?? false,
            'THEME_PATH' => $config['theme_path'] ?? \dirname(__DIR__, 2) . '/assets/themes',
            'IN_TEST' => $config['IN_TEST'] ?? false,
            'webdbLastTab' => [],
        ];

        self::$envConfig = \array_merge(self::$envConfig, $config);
        if (!self::$instance) {
            self::$instance = new static(self::$envConfig);

            self::$instance
                ->withConf(self::$envConfig);
             

            $handlers = new ContainerHandlers(self::$instance);
            $handlers->setExtra()
                ->setMisc()
                ->setViews()
                ->storeMainRequestParams()
                ->setHaltHandler();
        }

        //ddd($container->subfolder);
        return self::$instance;
    }

    /**
     * Determines the redirection url according to query string.
     *
     * @return string the redirect url
     */
    public function getRedirectUrl()
    {
        $container = self::getContainerInstance();
        $query_string = $container->request->getUri()->getQuery();

        // if server_id isn't set, then you will be redirected to intro
        if (null === $container->request->getQueryParam('server')) {
            $destinationurl = $this->subFolder. '/intro';
        } else {
            // otherwise, you'll be redirected to the login page for that server;
            $destinationurl = $this->subFolder. '/login' . ($query_string ? '?' . $query_string : '');
        }

        return $destinationurl;
    }

    /**
     * Adds a flash message to the session that will be displayed on the next request.
     *
     * @param mixed  $content msg content (can be object, array, etc)
     * @param string $key     The key to associate with the message. Defaults to the stack
     *                        trace of the closure or method that called addFlassh
     */
    public function addFlash($content, $key = ''): void
    {
        if ('' === $key) {
            $key = self::getBackTrace();
        }
        $container = self::getContainerInstance();
        // $this->dump(__METHOD__ . ': addMessage ' . $key . '  ' . json_encode($content));
        if ($container->flash) {
            $container->flash->addMessage($key, $content);
        }
    }

    /**
     * Gets the destination with the last active tab selected for that controller
     * Usually used after going through a redirect route.
     *
     * @param string $subject The subject, usually a view name like 'server' or 'table'
     *
     * @return string The destination url with last tab set in the query string
     */
    public function getDestinationWithLastTab($subject)
    {
        $container = self::getContainerInstance();
        $_server_info = $container->misc->getServerInfo();
        $this->addFlash($subject, 'getDestinationWithLastTab');
        //$this->prtrace('$_server_info', $_server_info);
        // If username isn't set in server_info, you should login
        $url = $container->misc->getLastTabURL($subject) ?? ['url' => 'alldb', 'urlvars' => ['subject' => 'server']];
        $destinationurl = $this->getRedirectUrl();

        if (!isset($_server_info['username'])||!\is_array($url)) {
            return $destinationurl;
        }

        $this->addFlash($url, 'getLastTabURL for ' . $subject);
        // Load query vars into superglobal arrays
        if (isset($url['urlvars'])) {
            $urlvars = [];

            foreach ($url['urlvars'] as $key => $urlvar) {
                //$this->prtrace($key, $urlvar);
                $urlvars[$key] = Decorator::get_sanitized_value($urlvar, $_REQUEST);
            }
            $_REQUEST = \array_merge($_REQUEST, $urlvars);
            $_GET = \array_merge($_GET, $urlvars);
        }
        $actionurl = Decorator::actionurl($url['url'], $_GET);
        $destinationurl =str_replace($this->subFolder,'', $actionurl->value($_GET));
if(strpos($destinationurl,$subject)===0) {
    $destinationurl=$this->subFolder.'/'.$destinationurl;
}
        return $destinationurl;
    }

    /**
     * Adds an error to the errors array property of the container.
     *
     * @param string $errormsg The error msg
     *
     * @return Container The app container
     */
    public function addError(string $errormsg): Container
    {
        $container = self::getContainerInstance();
        $errors = $container->get('errors');
        $errors[] = $errormsg;
        $container->offsetSet('errors', $errors);

        return $container;
    }

    /**
     * Returns a string with html <br> variant replaced with a new line.
     *
     * @param string $msg message to parse (<br> separated)
     *
     * @return string parsed message (linebreak separated)
     */
    public static function br2ln($msg)
    {
        return \str_replace(['<br>', '<br/>', '<br />'], \PHP_EOL, $msg);
    }

    public static function getDefaultConfig(bool $debug = false): array
    {
        return  [
            'settings' => [
                'displayErrorDetails' => $debug,
                'determineRouteBeforeAppMiddleware' => true,
                'base_path' => \dirname(__DIR__, 2),
                'debug' => $debug,
                'phpMinVer' => '7.2', // PHP minimum version
                'addContentLengthHeader' => false,
                'appName' => 'PHPPgAdmin6',
            ],
        ];
    }

    /**
     * @param array $conf
     */
    private function withConf($conf): self
    {
        $container = self::getContainerInstance();
        $conf['plugins'] = [];

        $container->BASE_PATH = $conf['BASE_PATH'];
        $container->subFolder = $conf['subfolder']??$conf['subFolder'];
        $container->debug = $conf['debugmode'];
        $container->THEME_PATH = $conf['theme_path'];
        $container->IN_TEST = $conf['IN_TEST'];
        $container['errors'] = [];
        $container['conf'] = static function (Container $c) use ($conf): array {
            $display_sizes = $conf['display_sizes'];

            if (\is_array($display_sizes)) {
                $conf['display_sizes'] = [
                    'schemas' => (bool) isset($display_sizes['schemas']) && true === $display_sizes['schemas'],
                    'tables' => (bool) isset($display_sizes['tables']) && true === $display_sizes['tables'],
                ];
            } else {
                $conf['display_sizes'] = [
                    'schemas' => (bool) $display_sizes,
                    'tables' => (bool) $display_sizes,
                ];
            }

            if (!isset($conf['theme'])) {
                $conf['theme'] = 'default';
            }

            foreach ($conf['servers'] as &$server) {
                if (!isset($server['port'])) {
                    $server['port'] = 5432;
                }

                if (!isset($server['sslmode'])) {
                    $server['sslmode'] = 'unspecified';
                }
            }
            //self::$envConfig=[
            //'BASE_PATH'=>$conf['BASE_PATH'],
            //'subFolder'=>$conf['subfolder'],
            //'DEBUGMODE'=>$conf['debugmode'],
            //'THEME_PATH'=>$conf['theme_path'],
            //'IN_TEST'=>$conf['IN_TEST']
            //];

            return $conf;
        };

        $container->subFolder = $conf['subfolder'];

        return $this;
    }

    /**
     * This function registers the default services that Slim needs to work.
     *
     * All services are shared, they are registered such that the
     * same instance is returned on subsequent calls.
     *
     * @param array $userSettings Associative array of application settings
     */
    private function registerDefaultServices($userSettings): void
    {
        $defaultSettings = $this->defaultSettings;

        /**
         * This service MUST return an array or an instance of ArrayAccess.
         *
         * @return array|ArrayAccess
         */
        $this['settings'] = static function () use ($userSettings, $defaultSettings): Collection {
            return new Collection(\array_merge($defaultSettings, $userSettings));
        };

        $defaultProvider = new DefaultServicesProvider();
        $defaultProvider->register($this);
    }
}