Passed
Push — develop ( 752940...292b66 )
by Felipe
04:30
created

Misc::getConnection()   B

Complexity

Conditions 9
Paths 13

Size

Total Lines 54
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 7.255
c 0
b 0
f 0
cc 9
eloc 30
nc 13
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * PHPPgAdmin v6.0.0-beta.43
5
 */
6
7
namespace PHPPgAdmin;
8
9
use PHPPgAdmin\Decorators\Decorator;
10
11
/**
12
 * @file
13
 * Class to hold various commonly used functions
14
 *
15
 * Id: Misc.php,v 1.171 2008/03/17 21:35:48 ioguix Exp $
16
 *
17
 * @package PHPPgAdmin
18
 */
19
20
/**
21
 * Class to hold various commonly used functions.
22
 *
23
 * @version $Id: Misc.php,v 1.171 2008/03/17 21:35:48 ioguix Exp $
0 ignored issues
show
Coding Style introduced by
Invalid version "$Id: Misc.php,v 1.171 2008/03/17 21:35:48 ioguix Exp $" in doc comment; consider "Release: <package_version>" instead
Loading history...
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
24
 *
25
 * @package PHPPgAdmin
26
 */
27
class Misc
28
{
29
    use \PHPPgAdmin\Traits\HelperTrait;
30
31
    private $_connection;
32
    private $_no_db_connection = false;
33
    private $_reload_browser   = false;
34
    private $_data;
35
    private $_database;
36
    private $_server_id;
37
    private $_server_info;
38
    private $_error_msg = '';
39
40
    public $appLangFiles    = [];
41
    public $appName         = '';
42
    public $appVersion      = '';
43
    public $form            = '';
44
    public $href            = '';
45
    public $controller_name = 'Misc';
46
    public $lang            = [];
47
48
    protected $container;
49
50
    /**
51
     * @param \Slim\Container $container The container
52
     */
53
    public function __construct(\Slim\Container $container)
54
    {
55
        $this->container = $container;
56
57
        $this->lang = $container->get('lang');
58
        $this->conf = $container->get('conf');
59
60
        //$this->view           = $container->get('view');
61
        $this->plugin_manager = $container->get('plugin_manager');
62
        $this->appLangFiles   = $container->get('appLangFiles');
63
64
        $this->appName          = $container->get('settings')['appName'];
65
        $this->appVersion       = $container->get('settings')['appVersion'];
66
        $this->postgresqlMinVer = $container->get('settings')['postgresqlMinVer'];
67
        $this->phpMinVer        = $container->get('settings')['phpMinVer'];
68
69
        $base_version = $container->get('settings')['base_version'];
70
71
        //$this->prtrace($base_version);
72
73
        // Check for config file version mismatch
74
        if (!isset($this->conf['version']) || $base_version > $this->conf['version']) {
75
            $container->get('utils')->addError($this->lang['strbadconfig']);
76
        }
77
78
        // Check database support is properly compiled in
79
        if (!function_exists('pg_connect')) {
80
            $container->get('utils')->addError($this->lang['strnotloaded']);
81
        }
82
83
        // Check the version of PHP
84
        if (version_compare(PHP_VERSION, $this->phpMinVer, '<')) {
85
            $container->get('utils')->addError(sprintf('Version of PHP not supported. Please upgrade to version %s or later.', $this->phpMinVer));
86
        }
87
        //$this->dumpAndDie($this);
88
89
        $this->getServerId();
90
    }
91
92
    public function serverToSha()
93
    {
94
        $request_server = $this->container->requestobj->getParam('server');
95
        if ($request_server === null) {
96
            return null;
97
        }
98
        $srv_array = explode(':', $request_server);
99
        if (count($srv_array) === 3) {
100
            return sha1($request_server);
101
        }
102
103
        return $request_server;
104
    }
105
106
    public function getServerId()
107
    {
108
        if ($this->_server_id) {
109
            return $this->_server_id;
110
        }
111
112
        $request_server = $this->serverToSha();
113
114
        if (count($this->conf['servers']) === 1) {
115
            $info             = $this->conf['servers'][0];
116
            $this->_server_id = sha1($info['host'] . ':' . $info['port'] . ':' . $info['sslmode']);
117
        } elseif ($request_server !== null) {
118
            $this->_server_id = $request_server;
119
        } elseif (isset($_SESSION['webdbLogin']) && count($_SESSION['webdbLogin']) > 0) {
120
            //$this->prtrace('webdbLogin', $_SESSION['webdbLogin']);
121
            $this->_server_id = array_keys($_SESSION['webdbLogin'])[0];
122
        }
123
124
        return $this->_server_id;
125
    }
126
127
    /**
128
     * Sets the view instance property of this class.
129
     *
130
     * @param \Slim\Views\Twig $view view instance
131
     *
132
     * @return \PHPPgAdmin\Misc this class instance
133
     */
134
    public function setView(\Slim\Views\Twig $view)
135
    {
136
        $this->view = $view;
137
138
        return $this;
139
    }
140
141
    /**
142
     * Adds or modifies a key in the $conf instance property of this class.
143
     *
144
     * @param string $key   name of the key to set
145
     * @param mixed  $value value of the key to set
146
     *
147
     * @return \PHPPgAdmin\Misc this class instance
148
     */
149
    public function setConf($key, $value)
150
    {
151
        $this->conf[$key] = $value;
152
153
        return $this;
154
    }
155
156
    /**
157
     * gets the value of a config property, or the array of all config properties.
1 ignored issue
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
158
     *
159
     * @param null|string $key value of the key to be retrieved. If null, the full array is returnes
160
     *
161
     * @return null|array|string the whole $conf array, the value of $conf[key] or null if said key does not exist
162
     */
163
    public function getConf($key = null)
164
    {
165
        if ($key === null) {
166
            return $this->conf;
167
        }
168
        if (array_key_exists($key, $this->conf)) {
169
            return $this->conf[$key];
170
        }
171
172
        return null;
173
    }
174
175
    /**
176
     * Displays link to the context help.
177
     *
178
     * @param string $str      the string that the context help is related to (already escaped)
179
     * @param string $help     help section identifier
180
     * @param bool   $do_print true to echo, false to return
181
     */
182
    public function printHelp($str, $help = null, $do_print = true)
183
    {
184
        //\PC::debug(['str' => $str, 'help' => $help], 'printHelp');
185
        if ($help !== null) {
186
            $helplink = $this->getHelpLink($help);
187
            $str .= '<a class="help" href="' . $helplink . '" title="' . $this->lang['strhelp'] . '" target="phppgadminhelp">';
188
            $str .= $this->lang['strhelpicon'] . '</a>';
189
        }
190
        if ($do_print) {
191
            echo $str;
192
        } else {
193
            return $str;
194
        }
195
    }
196
197
    /**
198
     * Gets the help link.
199
     *
200
     * @param string $help The help subject
201
     *
202
     * @return string the help link
203
     */
204
    public function getHelpLink($help)
205
    {
206
        return htmlspecialchars(SUBFOLDER . '/help?help=' . urlencode($help) . '&server=' . urlencode($this->getServerId()));
207
    }
208
209
    /**
210
     * Internally sets the reload browser property.
211
     *
212
     * @param bool $flag sets internal $_reload_browser var which will be passed to the footer methods
213
     *
214
     * @return \PHPPgAdmin\Misc this class instance
215
     */
216
    public function setReloadBrowser($flag)
217
    {
218
        $this->_reload_browser = (bool) $flag;
219
220
        return $this;
221
    }
222
223
    public function getReloadBrowser()
224
    {
225
        return $this->_reload_browser;
226
    }
227
228
    public function getContainer()
229
    {
230
        return $this->container;
231
    }
232
233
    /**
234
     * sets $_no_db_connection boolean value, allows to render scripts that do not need an active session.
1 ignored issue
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
235
     *
236
     * @param bool $flag true or false to allow unconnected clients to access the view
237
     *
238
     * @return \PHPPgAdmin\Misc this class instance
239
     */
240
    public function setNoDBConnection($flag)
241
    {
242
        $this->_no_db_connection = (bool) $flag;
243
244
        return $this;
245
    }
246
247
    /**
248
     * Gets member variable $_no_db_connection.
249
     *
250
     * @return bool value of member variable $_no_db_connection
251
     */
252
    public function getNoDBConnection()
253
    {
254
        return $this->_no_db_connection;
255
    }
256
257
    /**
258
     * Sets the last error message to display afterwards instead of just dying with the error msg.
259
     *
260
     * @param string $msg error message string
261
     *
262
     * @return \PHPPgAdmin\Misc this class instance
263
     */
264
    public function setErrorMsg($msg)
265
    {
266
        $this->_error_msg = $msg;
267
268
        return $this;
269
    }
270
271
    /**
272
     * Returns the error messages stored in member variable $_error_msg.
273
     *
274
     * @return string the error message
275
     */
276
    public function getErrorMsg()
277
    {
278
        return $this->_error_msg;
279
    }
280
281
    /**
282
     * Creates a database accessor.
283
     *
284
     * @param string $database  the name of the database
285
     * @param mixed  $server_id the id of the server
286
     *
287
     * @internal mixed $plaform placeholder that will receive the value of the platform
288
     */
289
    public function getDatabaseAccessor($database = '', $server_id = null)
290
    {
291
        $lang = $this->lang;
292
293
        if ($server_id !== null) {
294
            $this->_server_id = $server_id;
295
        }
296
        //$this->prtrace($this->_server_id);
297
298
        $server_info = $this->getServerInfo($this->_server_id);
299
300
        if ($this->_no_db_connection || !isset($server_info['username'])) {
301
            return null;
302
        }
303
304
        if ($this->_data === null) {
305
            try {
306
                $_connection = $this->getConnection($database, $this->_server_id);
307
            } catch (\Exception $e) {
308
                $this->setServerInfo(null, null, $this->_server_id);
309
                $this->setNoDBConnection(true);
310
                $this->setErrorMsg($e->getMessage());
311
312
                return null;
313
            }
314
315
            //$this->prtrace('_connection', $_connection);
316
            if (!$_connection) {
317
                $this->container->utils->addError($lang['strloginfailed']);
318
                $this->setErrorMsg($lang['strloginfailed']);
319
320
                return null;
321
            }
322
            // Get the name of the database driver we need to use.
323
            // The description of the server is returned in $platform.
324
            $_type = $_connection->getDriver($platform);
1 ignored issue
show
Comprehensibility Best Practice introduced by
The variable $platform seems to be never defined.
Loading history...
325
326
            //$this->prtrace(['type' => $_type, 'platform' => $platform, 'pgVersion' => $_connection->conn->pgVersion]);
327
328
            if ($_type === null) {
329
                $errormsg = sprintf($lang['strpostgresqlversionnotsupported'], $this->postgresqlMinVer);
330
                $this->container->utils->addError($errormsg);
331
                $this->setErrorMsg($errormsg);
332
333
                return null;
334
            }
335
            $_type = '\PHPPgAdmin\Database\\' . $_type;
336
337
            $this->setServerInfo('platform', $platform, $this->_server_id);
338
            $this->setServerInfo('pgVersion', $_connection->conn->pgVersion, $this->_server_id);
339
340
            // Create a database wrapper class for easy manipulation of the
341
            // connection.
342
343
            $this->_data           = new $_type($_connection->conn, $this->container, $server_info);
344
            $this->_data->platform = $_connection->platform;
345
346
            //$this->_data->getHelpPages();
347
348
            //$this->prtrace('help_page has ' . count($this->_data->help_page) . ' items');
349
350
            /* we work on UTF-8 only encoding */
351
            $this->_data->execute("SET client_encoding TO 'UTF-8'");
352
353
            if ($this->_data->hasByteaHexDefault()) {
354
                $this->_data->execute('SET bytea_output TO escape');
355
            }
356
        }
357
358
        if (
0 ignored issues
show
Coding Style introduced by
First condition of a multi-line IF statement must directly follow the opening parenthesis
Loading history...
359
            $this->_no_db_connection === false &&
360
            $this->getDatabase() !== null &&
361
            isset($_REQUEST['schema'])
362
        ) {
363
            $status = $this->_data->setSchema($_REQUEST['schema']);
364
365
            if ($status != 0) {
366
                $this->container->utils->addError($this->lang['strbadschema']);
367
                $this->setErrorMsg($this->lang['strbadschema']);
368
369
                return null;
370
            }
371
        }
372
373
        return $this->_data;
374
    }
375
376
    public function getConnection($database = '', $server_id = null)
377
    {
378
        $lang = $this->lang;
379
380
        if ($this->_connection === null) {
381
            if ($server_id !== null) {
382
                $this->_server_id = $server_id;
383
            }
384
            $server_info     = $this->getServerInfo($this->_server_id);
385
            $database_to_use = $this->getDatabase($database);
386
387
            // Perform extra security checks if this config option is set
388
            if ($this->conf['extra_login_security']) {
389
                // Disallowed logins if extra_login_security is enabled.
390
                // These must be lowercase.
391
                $bad_usernames = [
392
                    'pgsql'         => 'pgsql',
393
                    'postgres'      => 'postgres',
394
                    'root'          => 'root',
395
                    'administrator' => 'administrator',
396
                ];
397
398
                if (
0 ignored issues
show
Coding Style introduced by
First condition of a multi-line IF statement must directly follow the opening parenthesis
Loading history...
399
                    isset($server_info['username']) &&
400
                    array_key_exists(strtolower($server_info['username']), $bad_usernames)
401
                ) {
402
                    $msg = $lang['strlogindisallowed'];
403
404
                    throw new \Exception($msg);
405
                }
406
407
                if (
0 ignored issues
show
Coding Style introduced by
First condition of a multi-line IF statement must directly follow the opening parenthesis
Loading history...
408
                    !isset($server_info['password']) ||
409
                    $server_info['password'] == ''
410
                ) {
411
                    $msg = $lang['strlogindisallowed'];
412
413
                    throw new \Exception($msg);
414
                }
415
            }
416
417
            try {
418
                // Create the connection object and make the connection
419
                $this->_connection = new \PHPPgAdmin\Database\Connection(
420
                    $server_info,
421
                    $database_to_use,
422
                    $this->container
423
                );
424
            } catch (\PHPPgAdmin\ADOdbException $e) {
425
                throw new \Exception($lang['strloginfailed']);
426
            }
427
        }
428
429
        return $this->_connection;
430
    }
431
432
    /**
433
     * Validate and retrieve information on a server.
434
     * If the parameter isn't supplied then the currently
435
     * connected server is returned.
436
     *
437
     * @param string $server_id A server identifier (host:port)
438
     *
439
     * @return array An associative array of server properties
440
     */
441
    public function getServerInfo($server_id = null)
442
    {
443
        //\PC::debug(['$server_id' => $server_id]);
444
445
        if ($server_id !== null) {
446
            $this->_server_id = $server_id;
447
        } elseif ($this->_server_info !== null) {
448
            return $this->_server_info;
449
        }
450
451
        // Check for the server in the logged-in list
452
        if (isset($_SESSION['webdbLogin'][$this->_server_id])) {
453
            $this->_server_info = $_SESSION['webdbLogin'][$this->_server_id];
454
455
            return $this->_server_info;
456
        }
457
458
        // Otherwise, look for it in the conf file
459
        foreach ($this->conf['servers'] as $idx => $info) {
460
            $server_string = $info['host'] . ':' . $info['port'] . ':' . $info['sslmode'];
461
            $server_sha    = sha1($server_string);
462
463
            if (
0 ignored issues
show
Coding Style introduced by
First condition of a multi-line IF statement must directly follow the opening parenthesis
Loading history...
464
                $this->_server_id === $server_string ||
465
                $this->_server_id === $server_sha
466
            ) {
467
                if (isset($info['username'])) {
468
                    $this->setServerInfo(null, $info, $this->_server_id);
469
                } elseif (isset($_SESSION['sharedUsername'])) {
470
                    $info['username'] = $_SESSION['sharedUsername'];
471
                    $info['password'] = $_SESSION['sharedPassword'];
472
                    $this->setReloadBrowser(true);
473
                    $this->setServerInfo(null, $info, $this->_server_id);
474
                }
475
                $this->_server_info = $info;
476
477
                return $this->_server_info;
478
            }
479
        }
480
481
        if ($server_id === null) {
482
            $this->_server_info = null;
483
484
            return $this->_server_info;
485
        }
486
487
        $this->prtrace('Invalid server param');
488
        $this->_server_info = null;
489
        // Unable to find a matching server, are we being hacked?
490
        return $this->halt($this->lang['strinvalidserverparam']);
491
    }
492
493
    /**
494
     * Set server information.
495
     *
496
     * @param string      $key       parameter name to set, or null to replace all
497
     *                               params with the assoc-array in $value
498
     * @param mixed       $value     the new value, or null to unset the parameter
499
     * @param null|string $server_id the server identifier, or null for current server
500
     */
501
    public function setServerInfo($key, $value, $server_id = null)
502
    {
503
        //\PC::debug('setsetverinfo');
504
        if ($server_id === null) {
505
            $server_id = $this->container->requestobj->getParam('server');
506
        }
507
508
        if ($key === null) {
0 ignored issues
show
introduced by
The condition $key === null is always false.
Loading history...
509
            if ($value === null) {
510
                unset($_SESSION['webdbLogin'][$server_id]);
511
            } else {
512
                //\PC::debug(['server_id' => $server_id, 'value' => $value], 'webdbLogin null key');
513
                $_SESSION['webdbLogin'][$server_id] = $value;
514
            }
515
        } else {
516
            if ($value === null) {
517
                unset($_SESSION['webdbLogin'][$server_id][$key]);
518
            } else {
519
                //\PC::debug(['server_id' => $server_id, 'key' => $key, 'value' => $value], __FILE__ . ' ' . __LINE__ . ' webdbLogin key ' . $key);
520
                $_SESSION['webdbLogin'][$server_id][$key] = $value;
521
            }
522
        }
523
    }
524
525
    public function getDatabase($database = '')
526
    {
527
        if ($this->_server_id === null && !isset($_REQUEST['database'])) {
528
            return null;
529
        }
530
531
        $server_info = $this->getServerInfo($this->_server_id);
532
533
        if (
0 ignored issues
show
Coding Style introduced by
First condition of a multi-line IF statement must directly follow the opening parenthesis
Loading history...
534
            $this->_server_id !== null &&
535
            isset($server_info['useonlydefaultdb']) &&
536
            $server_info['useonlydefaultdb'] === true
537
        ) {
538
            $this->_database = $server_info['defaultdb'];
539
        } elseif ($database !== '') {
540
            $this->_database = $database;
541
        } elseif (isset($_REQUEST['database'])) {
542
            // Connect to the current database
543
            $this->_database = $_REQUEST['database'];
544
        } else {
545
            // or if one is not specified then connect to the default database.
546
            $this->_database = $server_info['defaultdb'];
547
        }
548
549
        return $this->_database;
550
    }
551
552
    /**
553
     * Set the current schema.
554
     *
555
     * @param string $schema The schema name
556
     *
557
     * @return int 0 on success
558
     */
559
    public function setCurrentSchema($schema)
560
    {
561
        $data = $this->getDatabaseAccessor();
562
563
        $status = $data->setSchema($schema);
564
        if ($status != 0) {
565
            return $status;
566
        }
567
568
        $_REQUEST['schema'] = $schema;
569
        $this->container->offsetSet('schema', $schema);
570
        $this->setHREF();
571
572
        return 0;
573
    }
574
575
    /**
576
     * Checks if dumps are properly set up.
577
     *
578
     * @param bool $all (optional) True to check pg_dumpall, false to just check pg_dump
579
     *
580
     * @return bool True, dumps are set up, false otherwise
581
     */
582
    public function isDumpEnabled($all = false)
583
    {
584
        $info = $this->getServerInfo();
585
586
        return !empty($info[$all ? 'pg_dumpall_path' : 'pg_dump_path']);
587
    }
588
589
    /**
590
     * Sets the href tracking variable.
591
     *
592
     * @return \PHPPgAdmin\Misc this class instance
593
     */
594
    public function setHREF()
595
    {
596
        $this->href = $this->getHREF();
597
        //\PC::debug($this->href, 'Misc::href');
598
        return $this;
599
    }
600
601
    /**
602
     * Get a href query string, excluding objects below the given object type (inclusive).
603
     *
604
     * @param null|string $exclude_from
605
     *
606
     * @return string
607
     */
608
    public function getHREF($exclude_from = null)
609
    {
610
        $href = [];
611
612
        $server   = $this->container->server || isset($_REQUEST['server']) ? $_REQUEST['server'] : null;
613
        $database = $this->container->database || isset($_REQUEST['database']) ? $_REQUEST['database'] : null;
614
        $schema   = $this->container->schema || isset($_REQUEST['schema']) ? $_REQUEST['schema'] : null;
615
616
        if ($server && $exclude_from !== 'server') {
617
            $href[] = 'server=' . urlencode($server);
618
        }
619
        if ($database && $exclude_from !== 'database') {
620
            $href[] = 'database=' . urlencode($database);
621
        }
622
        if ($schema && $exclude_from !== 'schema') {
623
            $href[] = 'schema=' . urlencode($schema);
624
        }
625
626
        $this->href = htmlentities(implode('&', $href));
627
628
        return $this->href;
629
    }
630
631
    public function getSubjectParams($subject)
632
    {
633
        $plugin_manager = $this->plugin_manager;
634
635
        $vars = [];
636
637
        switch ($subject) {
638
            case 'root':
639
                $vars = [
640
                    'params' => [
641
                        'subject' => 'root',
642
                    ],
643
                ];
644
645
                break;
646
            case 'server':
647
                $vars = ['params' => [
648
                    'server'  => $_REQUEST['server'],
649
                    'subject' => 'server',
650
                ]];
651
652
                break;
653
            case 'role':
654
                $vars = ['params' => [
655
                    'server'   => $_REQUEST['server'],
656
                    'subject'  => 'role',
657
                    'action'   => 'properties',
658
                    'rolename' => $_REQUEST['rolename'],
659
                ]];
660
661
                break;
662
            case 'database':
663
                $vars = ['params' => [
664
                    'server'   => $_REQUEST['server'],
665
                    'subject'  => 'database',
666
                    'database' => $_REQUEST['database'],
667
                ]];
668
669
                break;
670
            case 'schema':
671
                $vars = ['params' => [
672
                    'server'   => $_REQUEST['server'],
673
                    'subject'  => 'schema',
674
                    'database' => $_REQUEST['database'],
675
                    'schema'   => $_REQUEST['schema'],
676
                ]];
677
678
                break;
679
            case 'table':
680
                $vars = ['params' => [
681
                    'server'   => $_REQUEST['server'],
682
                    'subject'  => 'table',
683
                    'database' => $_REQUEST['database'],
684
                    'schema'   => $_REQUEST['schema'],
685
                    'table'    => $_REQUEST['table'],
686
                ]];
687
688
                break;
689
            case 'selectrows':
690
                $vars = [
691
                    'url'    => 'tables',
692
                    'params' => [
693
                        'server'   => $_REQUEST['server'],
694
                        'subject'  => 'table',
695
                        'database' => $_REQUEST['database'],
696
                        'schema'   => $_REQUEST['schema'],
697
                        'table'    => $_REQUEST['table'],
698
                        'action'   => 'confselectrows',
699
                    ]];
700
701
                break;
702
            case 'view':
703
                $vars = ['params' => [
704
                    'server'   => $_REQUEST['server'],
705
                    'subject'  => 'view',
706
                    'database' => $_REQUEST['database'],
707
                    'schema'   => $_REQUEST['schema'],
708
                    'view'     => $_REQUEST['view'],
709
                ]];
710
711
                break;
712
            case 'matview':
713
                $vars = ['params' => [
714
                    'server'   => $_REQUEST['server'],
715
                    'subject'  => 'matview',
716
                    'database' => $_REQUEST['database'],
717
                    'schema'   => $_REQUEST['schema'],
718
                    'matview'  => $_REQUEST['matview'],
719
                ]];
720
721
                break;
722
            case 'fulltext':
723
            case 'ftscfg':
724
                $vars = ['params' => [
725
                    'server'   => $_REQUEST['server'],
726
                    'subject'  => 'fulltext',
727
                    'database' => $_REQUEST['database'],
728
                    'schema'   => $_REQUEST['schema'],
729
                    'action'   => 'viewconfig',
730
                    'ftscfg'   => $_REQUEST['ftscfg'],
731
                ]];
732
733
                break;
734
            case 'function':
735
                $vars = ['params' => [
736
                    'server'       => $_REQUEST['server'],
737
                    'subject'      => 'function',
738
                    'database'     => $_REQUEST['database'],
739
                    'schema'       => $_REQUEST['schema'],
740
                    'function'     => $_REQUEST['function'],
741
                    'function_oid' => $_REQUEST['function_oid'],
742
                ]];
743
744
                break;
745
            case 'aggregate':
746
                $vars = ['params' => [
747
                    'server'   => $_REQUEST['server'],
748
                    'subject'  => 'aggregate',
749
                    'action'   => 'properties',
750
                    'database' => $_REQUEST['database'],
751
                    'schema'   => $_REQUEST['schema'],
752
                    'aggrname' => $_REQUEST['aggrname'],
753
                    'aggrtype' => $_REQUEST['aggrtype'],
754
                ]];
755
756
                break;
757
            case 'column':
758
                if (isset($_REQUEST['table'])) {
759
                    $vars = ['params' => [
760
                        'server'   => $_REQUEST['server'],
761
                        'subject'  => 'column',
762
                        'database' => $_REQUEST['database'],
763
                        'schema'   => $_REQUEST['schema'],
764
                        'table'    => $_REQUEST['table'],
765
                        'column'   => $_REQUEST['column'],
766
                    ]];
767
                } else {
768
                    $vars = ['params' => [
769
                        'server'   => $_REQUEST['server'],
770
                        'subject'  => 'column',
771
                        'database' => $_REQUEST['database'],
772
                        'schema'   => $_REQUEST['schema'],
773
                        'view'     => $_REQUEST['view'],
774
                        'column'   => $_REQUEST['column'],
775
                    ]];
776
                }
777
778
                break;
779
            case 'plugin':
780
                $vars = [
781
                    'url'    => 'plugin',
782
                    'params' => [
783
                        'server'  => $_REQUEST['server'],
784
                        'subject' => 'plugin',
785
                        'plugin'  => $_REQUEST['plugin'],
786
                    ]];
787
788
                if (!is_null($plugin_manager->getPlugin($_REQUEST['plugin']))) {
789
                    $vars['params'] = array_merge($vars['params'], $plugin_manager->getPlugin($_REQUEST['plugin'])->get_subject_params());
790
                }
791
792
                break;
793
            default:
794
                return false;
795
        }
796
797
        if (!isset($vars['url'])) {
798
            $vars['url'] = SUBFOLDER . '/redirect';
799
        }
800
        if ($vars['url'] == SUBFOLDER . '/redirect' && isset($vars['params']['subject'])) {
801
            $vars['url'] = SUBFOLDER . '/redirect/' . $vars['params']['subject'];
802
            unset($vars['params']['subject']);
803
        }
804
805
        return $vars;
806
    }
807
808
    /**
809
     * Sets the form tracking variable.
810
     */
811
    public function setForm()
812
    {
813
        $form = [];
814
        if ($this->container->server) {
815
            $form[] = '<input type="hidden" name="server" value="' . htmlspecialchars($this->container->server) . '" />';
816
        }
817
        if ($this->container->database) {
818
            $form[] = '<input type="hidden" name="database" value="' . htmlspecialchars($this->container->database) . '" />';
819
        }
820
821
        if ($this->container->schema) {
822
            $form[] = '<input type="hidden" name="schema" value="' . htmlspecialchars($this->container->schema) . '" />';
823
        }
824
        $this->form = implode("\n", $form);
825
826
        return $this->form;
827
        //\PC::debug($this->form, 'Misc::form');
828
    }
829
830
    /**
831
     * Render a value into HTML using formatting rules specified
832
     * by a type name and parameters.
833
     *
834
     * @param string $str    The string to change
835
     * @param string $type   Field type (optional), this may be an internal PostgreSQL type, or:
836
     *                       yesno    - same as bool, but renders as 'Yes' or 'No'.
837
     *                       pre      - render in a <pre> block.
838
     *                       nbsp     - replace all spaces with &nbsp;'s
839
     *                       verbatim - render exactly as supplied, no escaping what-so-ever.
840
     *                       callback - render using a callback function supplied in the 'function' param.
841
     * @param array  $params Type parameters (optional), known parameters:
842
     *                       null     - string to display if $str is null, or set to TRUE to use a default 'NULL' string,
843
     *                       otherwise nothing is rendered.
844
     *                       clip     - if true, clip the value to a fixed length, and append an ellipsis...
845
     *                       cliplen  - the maximum length when clip is enabled (defaults to $conf['max_chars'])
846
     *                       ellipsis - the string to append to a clipped value (defaults to $lang['strellipsis'])
847
     *                       tag      - an HTML element name to surround the value.
848
     *                       class    - a class attribute to apply to any surrounding HTML element.
849
     *                       align    - an align attribute ('left','right','center' etc.)
850
     *                       true     - (type='bool') the representation of true.
851
     *                       false    - (type='bool') the representation of false.
852
     *                       function - (type='callback') a function name, accepts args ($str, $params) and returns a rendering.
853
     *                       lineno   - prefix each line with a line number.
854
     *                       map      - an associative array.
855
     *
856
     * @return string The HTML rendered value
857
     */
858
    public function printVal($str, $type = null, $params = [])
859
    {
860
        $lang = $this->lang;
861
        $data = $this->getDatabaseAccessor();
862
863
        // Shortcircuit for a NULL value
864
        if (!$str) {
865
            return isset($params['null'])
866
            ? ($params['null'] === true ? '<i>NULL</i>' : $params['null'])
867
            : '';
868
        }
869
870
        if (isset($params['map'], $params['map'][$str])) {
871
            $str = $params['map'][$str];
872
        }
873
874
        // Clip the value if the 'clip' parameter is true.
875
        if (isset($params['clip']) && $params['clip'] === true) {
876
            $maxlen   = isset($params['cliplen']) && is_integer($params['cliplen']) ? $params['cliplen'] : $this->conf['max_chars'];
877
            $ellipsis = isset($params['ellipsis']) ? $params['ellipsis'] : $lang['strellipsis'];
878
            if (strlen($str) > $maxlen) {
879
                $str = substr($str, 0, $maxlen - 1) . $ellipsis;
880
            }
881
        }
882
883
        $out   = '';
884
        $class = '';
885
886
        switch ($type) {
887
            case 'int2':
888
            case 'int4':
889
            case 'int8':
890
            case 'float4':
891
            case 'float8':
892
            case 'money':
893
            case 'numeric':
894
            case 'oid':
895
            case 'xid':
896
            case 'cid':
897
            case 'tid':
898
                $align = 'right';
899
                $out   = nl2br(htmlspecialchars(\PHPPgAdmin\Traits\HelperTrait::br2ln($str)));
900
901
                break;
902
            case 'yesno':
903
                if (!isset($params['true'])) {
904
                    $params['true'] = $lang['stryes'];
905
                }
906
907
                if (!isset($params['false'])) {
908
                    $params['false'] = $lang['strno'];
909
                }
910
911
            // no break - fall through to boolean case.
912
            case 'bool':
913
            case 'boolean':
914
                if (is_bool($str)) {
915
                    $str = $str ? 't' : 'f';
916
                }
917
918
                switch ($str) {
919
                    case 't':
920
                        $out   = (isset($params['true']) ? $params['true'] : $lang['strtrue']);
921
                        $align = 'center';
922
923
                        break;
924
                    case 'f':
925
                        $out   = (isset($params['false']) ? $params['false'] : $lang['strfalse']);
926
                        $align = 'center';
927
928
                        break;
929
                    default:
930
                        $out = htmlspecialchars($str);
931
                }
932
933
                break;
934
            case 'bytea':
935
                $tag   = 'div';
936
                $class = 'pre';
937
                $out   = $data->escapeBytea($str);
938
939
                break;
940
            case 'errormsg':
941
                $tag   = 'pre';
942
                $class = 'error';
943
                $out   = htmlspecialchars($str);
944
945
                break;
946
            case 'pre':
947
                $tag = 'pre';
948
                $out = htmlspecialchars($str);
949
950
                break;
951
            case 'prenoescape':
952
                $tag = 'pre';
953
                $out = $str;
954
955
                break;
956
            case 'nbsp':
957
                $out = nl2br(str_replace(' ', '&nbsp;', \PHPPgAdmin\Traits\HelperTrait::br2ln($str)));
958
959
                break;
960
            case 'verbatim':
961
                $out = $str;
962
963
                break;
964
            case 'callback':
965
                $out = $params['function']($str, $params);
966
967
                break;
968
            case 'prettysize':
969
                if ($str == -1) {
970
                    $out = $lang['strnoaccess'];
971
                } else {
972
                    $limit = 10 * 1024;
973
                    $mult  = 1;
974
                    if ($str < $limit * $mult) {
975
                        $out = $str . ' ' . $lang['strbytes'];
976
                    } else {
977
                        $mult *= 1024;
978
                        if ($str < $limit * $mult) {
979
                            $out = floor(($str + $mult / 2) / $mult) . ' ' . $lang['strkb'];
980
                        } else {
981
                            $mult *= 1024;
982
                            if ($str < $limit * $mult) {
983
                                $out = floor(($str + $mult / 2) / $mult) . ' ' . $lang['strmb'];
984
                            } else {
985
                                $mult *= 1024;
986
                                if ($str < $limit * $mult) {
987
                                    $out = floor(($str + $mult / 2) / $mult) . ' ' . $lang['strgb'];
988
                                } else {
989
                                    $mult *= 1024;
990
                                    if ($str < $limit * $mult) {
991
                                        $out = floor(($str + $mult / 2) / $mult) . ' ' . $lang['strtb'];
992
                                    }
993
                                }
994
                            }
995
                        }
996
                    }
997
                }
998
999
                break;
1000
            default:
1001
                // If the string contains at least one instance of >1 space in a row, a tab
1002
                // character, a space at the start of a line, or a space at the start of
1003
                // the whole string then render within a pre-formatted element (<pre>).
1004
                if (preg_match('/(^ |  |\t|\n )/m', $str)) {
1005
                    $tag   = 'pre';
1006
                    $class = 'data';
1007
                    $out   = htmlspecialchars($str);
1008
                } else {
1009
                    $out = nl2br(htmlspecialchars(\PHPPgAdmin\Traits\HelperTrait::br2ln($str)));
1010
                }
1011
        }
1012
1013
        if (isset($params['class'])) {
1014
            $class = $params['class'];
1015
        }
1016
1017
        if (isset($params['align'])) {
1018
            $align = $params['align'];
1019
        }
1020
1021
        if (!isset($tag) && (isset($class) || isset($align))) {
1022
            $tag = 'div';
1023
        }
1024
1025
        if (isset($tag)) {
1026
            $alignattr = isset($align) ? " style=\"text-align: {$align}\"" : '';
1027
            $classattr = isset($class) ? " class=\"{$class}\"" : '';
1028
            $out       = "<{$tag}{$alignattr}{$classattr}>{$out}</{$tag}>";
1029
        }
1030
1031
        // Add line numbers if 'lineno' param is true
1032
        if (isset($params['lineno']) && $params['lineno'] === true) {
1033
            $lines = explode("\n", $str);
1034
            $num   = count($lines);
1035
            if ($num > 0) {
1036
                $temp = "<table>\n<tr><td class=\"{$class}\" style=\"vertical-align: top; padding-right: 10px;\"><pre class=\"{$class}\">";
1037
                for ($i = 1; $i <= $num; ++$i) {
1038
                    $temp .= $i . "\n";
1039
                }
1040
                $temp .= "</pre></td><td class=\"{$class}\" style=\"vertical-align: top;\">{$out}</td></tr></table>\n";
1041
                $out = $temp;
1042
            }
1043
            unset($lines);
1044
        }
1045
1046
        return $out;
1047
    }
1048
1049
    /**
1050
     * A function to recursively strip slashes.  Used to
1051
     * enforce magic_quotes_gpc being off.
1052
     *
1053
     * @param mixed $var The variable to strip (passed by reference)
1054
     */
1055
    public function stripVar(&$var)
1056
    {
1057
        if (is_array($var)) {
1058
            foreach ($var as $k => $v) {
1059
                $this->stripVar($var[$k]);
1060
1061
                /* magic_quotes_gpc escape keys as well ...*/
1062
                if (is_string($k)) {
1063
                    $ek = stripslashes($k);
1064
                    if ($ek !== $k) {
1065
                        $var[$ek] = $var[$k];
1066
                        unset($var[$k]);
1067
                    }
1068
                }
1069
            }
1070
        } else {
1071
            $var = stripslashes($var);
1072
        }
1073
    }
1074
1075
    /**
1076
     * Retrieve the tab info for a specific tab bar.
1077
     *
1078
     * @param string $section the name of the tab bar
1079
     *
1080
     * @return array array of tabs
1081
     */
1082
    public function getNavTabs($section)
1083
    {
1084
        $data           = $this->getDatabaseAccessor();
1085
        $lang           = $this->lang;
1086
        $plugin_manager = $this->plugin_manager;
1087
1088
        $hide_advanced = ($this->conf['show_advanced'] === false);
1089
        $tabs          = [];
1090
1091
        switch ($section) {
1092
            case 'root':
1093
                $tabs = [
1094
                    'intro'   => [
1095
                        'title' => $lang['strintroduction'],
1096
                        'url'   => 'intro',
1097
                        'icon'  => 'Introduction',
1098
                    ],
1099
                    'servers' => [
1100
                        'title' => $lang['strservers'],
1101
                        'url'   => 'servers',
1102
                        'icon'  => 'Servers',
1103
                    ],
1104
                ];
1105
1106
                break;
1107
            case 'server':
1108
                $hide_users = true;
1109
                if ($data) {
1110
                    $hide_users = !$data->isSuperUser();
1111
                }
1112
1113
                $tabs = [
1114
                    'databases' => [
1115
                        'title'   => $lang['strdatabases'],
1116
                        'url'     => 'alldb',
1117
                        'urlvars' => ['subject' => 'server'],
1118
                        'help'    => 'pg.database',
1119
                        'icon'    => 'Databases',
1120
                    ],
1121
                ];
1122
                if ($data && $data->hasRoles()) {
1123
                    $tabs = array_merge($tabs, [
1 ignored issue
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
1124
                        'roles' => [
1125
                            'title'   => $lang['strroles'],
1126
                            'url'     => 'roles',
1127
                            'urlvars' => ['subject' => 'server'],
1128
                            'hide'    => $hide_users,
1129
                            'help'    => 'pg.role',
1130
                            'icon'    => 'Roles',
1131
                        ],
1132
                    ]);
1 ignored issue
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
1133
                } else {
1134
                    $tabs = array_merge($tabs, [
1 ignored issue
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
1135
                        'users'  => [
1136
                            'title'   => $lang['strusers'],
1137
                            'url'     => 'users',
1138
                            'urlvars' => ['subject' => 'server'],
1139
                            'hide'    => $hide_users,
1140
                            'help'    => 'pg.user',
1141
                            'icon'    => 'Users',
1142
                        ],
1143
                        'groups' => [
1144
                            'title'   => $lang['strgroups'],
1145
                            'url'     => 'groups',
1146
                            'urlvars' => ['subject' => 'server'],
1147
                            'hide'    => $hide_users,
1148
                            'help'    => 'pg.group',
1149
                            'icon'    => 'UserGroups',
1150
                        ],
1151
                    ]);
1 ignored issue
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
1152
                }
1153
1154
                $tabs = array_merge($tabs, [
1 ignored issue
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
1155
                    'account'     => [
1156
                        'title'   => $lang['straccount'],
1157
                        'url'     => ($data && $data->hasRoles()) ? 'roles' : 'users',
1158
                        'urlvars' => ['subject' => 'server', 'action' => 'account'],
1159
                        'hide'    => !$hide_users,
1160
                        'help'    => 'pg.role',
1161
                        'icon'    => 'User',
1162
                    ],
1163
                    'tablespaces' => [
1164
                        'title'   => $lang['strtablespaces'],
1165
                        'url'     => 'tablespaces',
1166
                        'urlvars' => ['subject' => 'server'],
1167
                        'hide'    => !$data || !$data->hasTablespaces(),
1168
                        'help'    => 'pg.tablespace',
1169
                        'icon'    => 'Tablespaces',
1170
                    ],
1171
                    'export'      => [
1172
                        'title'   => $lang['strexport'],
1173
                        'url'     => 'alldb',
1174
                        'urlvars' => ['subject' => 'server', 'action' => 'export'],
1175
                        'hide'    => !$this->isDumpEnabled(),
1176
                        'icon'    => 'Export',
1177
                    ],
1178
                ]);
1 ignored issue
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
1179
1180
                break;
1181
            case 'database':
1182
                $tabs = [
1183
                    'schemas'    => [
1184
                        'title'   => $lang['strschemas'],
1185
                        'url'     => 'schemas',
1186
                        'urlvars' => ['subject' => 'database'],
1187
                        'help'    => 'pg.schema',
1188
                        'icon'    => 'Schemas',
1189
                    ],
1190
                    'sql'        => [
1191
                        'title'   => $lang['strsql'],
1192
                        'url'     => 'database',
1193
                        'urlvars' => ['subject' => 'database', 'action' => 'sql', 'new' => 1],
1194
                        'help'    => 'pg.sql',
1195
                        'tree'    => false,
1196
                        'icon'    => 'SqlEditor',
1197
                    ],
1198
                    'find'       => [
1199
                        'title'   => $lang['strfind'],
1200
                        'url'     => 'database',
1201
                        'urlvars' => ['subject' => 'database', 'action' => 'find'],
1202
                        'tree'    => false,
1203
                        'icon'    => 'Search',
1204
                    ],
1205
                    'variables'  => [
1206
                        'title'   => $lang['strvariables'],
1207
                        'url'     => 'database',
1208
                        'urlvars' => ['subject' => 'database', 'action' => 'variables'],
1209
                        'help'    => 'pg.variable',
1210
                        'tree'    => false,
1211
                        'icon'    => 'Variables',
1212
                    ],
1213
                    'processes'  => [
1214
                        'title'   => $lang['strprocesses'],
1215
                        'url'     => 'database',
1216
                        'urlvars' => ['subject' => 'database', 'action' => 'processes'],
1217
                        'help'    => 'pg.process',
1218
                        'tree'    => false,
1219
                        'icon'    => 'Processes',
1220
                    ],
1221
                    'locks'      => [
1222
                        'title'   => $lang['strlocks'],
1223
                        'url'     => 'database',
1224
                        'urlvars' => ['subject' => 'database', 'action' => 'locks'],
1225
                        'help'    => 'pg.locks',
1226
                        'tree'    => false,
1227
                        'icon'    => 'Key',
1228
                    ],
1229
                    'admin'      => [
1230
                        'title'   => $lang['stradmin'],
1231
                        'url'     => 'database',
1232
                        'urlvars' => ['subject' => 'database', 'action' => 'admin'],
1233
                        'tree'    => false,
1234
                        'icon'    => 'Admin',
1235
                    ],
1236
                    'privileges' => [
1237
                        'title'   => $lang['strprivileges'],
1238
                        'url'     => 'privileges',
1239
                        'urlvars' => ['subject' => 'database'],
1240
                        'hide'    => !isset($data->privlist['database']),
1241
                        'help'    => 'pg.privilege',
1242
                        'tree'    => false,
1243
                        'icon'    => 'Privileges',
1244
                    ],
1245
                    'languages'  => [
1246
                        'title'   => $lang['strlanguages'],
1247
                        'url'     => 'languages',
1248
                        'urlvars' => ['subject' => 'database'],
1249
                        'hide'    => $hide_advanced,
1250
                        'help'    => 'pg.language',
1251
                        'icon'    => 'Languages',
1252
                    ],
1253
                    'casts'      => [
1254
                        'title'   => $lang['strcasts'],
1255
                        'url'     => 'casts',
1256
                        'urlvars' => ['subject' => 'database'],
1257
                        'hide'    => $hide_advanced,
1258
                        'help'    => 'pg.cast',
1259
                        'icon'    => 'Casts',
1260
                    ],
1261
                    'export'     => [
1262
                        'title'   => $lang['strexport'],
1263
                        'url'     => 'database',
1264
                        'urlvars' => ['subject' => 'database', 'action' => 'export'],
1265
                        'hide'    => !$this->isDumpEnabled(),
1266
                        'tree'    => false,
1267
                        'icon'    => 'Export',
1268
                    ],
1269
                ];
1270
1271
                break;
1272
            case 'schema':
1273
                $tabs = [
1274
                    'tables'      => [
1275
                        'title'   => $lang['strtables'],
1276
                        'url'     => 'tables',
1277
                        'urlvars' => ['subject' => 'schema'],
1278
                        'help'    => 'pg.table',
1279
                        'icon'    => 'Tables',
1280
                    ],
1281
                    'views'       => [
1282
                        'title'   => $lang['strviews'],
1283
                        'url'     => 'views',
1284
                        'urlvars' => ['subject' => 'schema'],
1285
                        'help'    => 'pg.view',
1286
                        'icon'    => 'Views',
1287
                    ],
1288
                    'matviews'    => [
1289
                        'title'   => 'M ' . $lang['strviews'],
1290
                        'url'     => 'materializedviews',
1291
                        'urlvars' => ['subject' => 'schema'],
1292
                        'help'    => 'pg.matview',
1293
                        'icon'    => 'MViews',
1294
                    ],
1295
                    'sequences'   => [
1296
                        'title'   => $lang['strsequences'],
1297
                        'url'     => 'sequences',
1298
                        'urlvars' => ['subject' => 'schema'],
1299
                        'help'    => 'pg.sequence',
1300
                        'icon'    => 'Sequences',
1301
                    ],
1302
                    'functions'   => [
1303
                        'title'   => $lang['strfunctions'],
1304
                        'url'     => 'functions',
1305
                        'urlvars' => ['subject' => 'schema'],
1306
                        'help'    => 'pg.function',
1307
                        'icon'    => 'Functions',
1308
                    ],
1309
                    'fulltext'    => [
1310
                        'title'   => $lang['strfulltext'],
1311
                        'url'     => 'fulltext',
1312
                        'urlvars' => ['subject' => 'schema'],
1313
                        'help'    => 'pg.fts',
1314
                        'tree'    => true,
1315
                        'icon'    => 'Fts',
1316
                    ],
1317
                    'domains'     => [
1318
                        'title'   => $lang['strdomains'],
1319
                        'url'     => 'domains',
1320
                        'urlvars' => ['subject' => 'schema'],
1321
                        'help'    => 'pg.domain',
1322
                        'icon'    => 'Domains',
1323
                    ],
1324
                    'aggregates'  => [
1325
                        'title'   => $lang['straggregates'],
1326
                        'url'     => 'aggregates',
1327
                        'urlvars' => ['subject' => 'schema'],
1328
                        'hide'    => $hide_advanced,
1329
                        'help'    => 'pg.aggregate',
1330
                        'icon'    => 'Aggregates',
1331
                    ],
1332
                    'types'       => [
1333
                        'title'   => $lang['strtypes'],
1334
                        'url'     => 'types',
1335
                        'urlvars' => ['subject' => 'schema'],
1336
                        'hide'    => $hide_advanced,
1337
                        'help'    => 'pg.type',
1338
                        'icon'    => 'Types',
1339
                    ],
1340
                    'operators'   => [
1341
                        'title'   => $lang['stroperators'],
1342
                        'url'     => 'operators',
1343
                        'urlvars' => ['subject' => 'schema'],
1344
                        'hide'    => $hide_advanced,
1345
                        'help'    => 'pg.operator',
1346
                        'icon'    => 'Operators',
1347
                    ],
1348
                    'opclasses'   => [
1349
                        'title'   => $lang['stropclasses'],
1350
                        'url'     => 'opclasses',
1351
                        'urlvars' => ['subject' => 'schema'],
1352
                        'hide'    => $hide_advanced,
1353
                        'help'    => 'pg.opclass',
1354
                        'icon'    => 'OperatorClasses',
1355
                    ],
1356
                    'conversions' => [
1357
                        'title'   => $lang['strconversions'],
1358
                        'url'     => 'conversions',
1359
                        'urlvars' => ['subject' => 'schema'],
1360
                        'hide'    => $hide_advanced,
1361
                        'help'    => 'pg.conversion',
1362
                        'icon'    => 'Conversions',
1363
                    ],
1364
                    'privileges'  => [
1365
                        'title'   => $lang['strprivileges'],
1366
                        'url'     => 'privileges',
1367
                        'urlvars' => ['subject' => 'schema'],
1368
                        'help'    => 'pg.privilege',
1369
                        'tree'    => false,
1370
                        'icon'    => 'Privileges',
1371
                    ],
1372
                    'export'      => [
1373
                        'title'   => $lang['strexport'],
1374
                        'url'     => 'schemas',
1375
                        'urlvars' => ['subject' => 'schema', 'action' => 'export'],
1376
                        'hide'    => !$this->isDumpEnabled(),
1377
                        'tree'    => false,
1378
                        'icon'    => 'Export',
1379
                    ],
1380
                ];
1381
                if (!$data->hasFTS()) {
1382
                    unset($tabs['fulltext']);
1383
                }
1384
1385
                break;
1386
            case 'table':
1387
                $tabs = [
1388
                    'columns'     => [
1389
                        'title'   => $lang['strcolumns'],
1390
                        'url'     => 'tblproperties',
1391
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1392
                        'icon'    => 'Columns',
1393
                        'branch'  => true,
1394
                    ],
1395
                    'browse'      => [
1396
                        'title'   => $lang['strbrowse'],
1397
                        'icon'    => 'Columns',
1398
                        'url'     => 'display',
1399
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1400
                        'return'  => 'table',
1401
                        'branch'  => true,
1402
                    ],
1403
                    'select'      => [
1404
                        'title'   => $lang['strselect'],
1405
                        'icon'    => 'Search',
1406
                        'url'     => 'tables',
1407
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table'), 'action' => 'confselectrows'],
1408
                        'help'    => 'pg.sql.select',
1409
                    ],
1410
                    'insert'      => [
1411
                        'title'   => $lang['strinsert'],
1412
                        'url'     => 'tables',
1413
                        'urlvars' => [
1414
                            'action' => 'confinsertrow',
1415
                            'table'  => Decorator::field('table'),
1416
                        ],
1417
                        'help'    => 'pg.sql.insert',
1418
                        'icon'    => 'Operator',
1419
                    ],
1420
                    'indexes'     => [
1421
                        'title'   => $lang['strindexes'],
1422
                        'url'     => 'indexes',
1423
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1424
                        'help'    => 'pg.index',
1425
                        'icon'    => 'Indexes',
1426
                        'branch'  => true,
1427
                    ],
1428
                    'constraints' => [
1429
                        'title'   => $lang['strconstraints'],
1430
                        'url'     => 'constraints',
1431
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1432
                        'help'    => 'pg.constraint',
1433
                        'icon'    => 'Constraints',
1434
                        'branch'  => true,
1435
                    ],
1436
                    'triggers'    => [
1437
                        'title'   => $lang['strtriggers'],
1438
                        'url'     => 'triggers',
1439
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1440
                        'help'    => 'pg.trigger',
1441
                        'icon'    => 'Triggers',
1442
                        'branch'  => true,
1443
                    ],
1444
                    'rules'       => [
1445
                        'title'   => $lang['strrules'],
1446
                        'url'     => 'rules',
1447
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1448
                        'help'    => 'pg.rule',
1449
                        'icon'    => 'Rules',
1450
                        'branch'  => true,
1451
                    ],
1452
                    'admin'       => [
1453
                        'title'   => $lang['stradmin'],
1454
                        'url'     => 'tables',
1455
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table'), 'action' => 'admin'],
1456
                        'icon'    => 'Admin',
1457
                    ],
1458
                    'info'        => [
1459
                        'title'   => $lang['strinfo'],
1460
                        'url'     => 'info',
1461
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1462
                        'icon'    => 'Statistics',
1463
                    ],
1464
                    'privileges'  => [
1465
                        'title'   => $lang['strprivileges'],
1466
                        'url'     => 'privileges',
1467
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1468
                        'help'    => 'pg.privilege',
1469
                        'icon'    => 'Privileges',
1470
                    ],
1471
                    'import'      => [
1472
                        'title'   => $lang['strimport'],
1473
                        'url'     => 'tblproperties',
1474
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table'), 'action' => 'import'],
1475
                        'icon'    => 'Import',
1476
                        'hide'    => false,
1477
                    ],
1478
                    'export'      => [
1479
                        'title'   => $lang['strexport'],
1480
                        'url'     => 'tblproperties',
1481
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table'), 'action' => 'export'],
1482
                        'icon'    => 'Export',
1483
                        'hide'    => false,
1484
                    ],
1485
                ];
1486
1487
                break;
1488
            case 'view':
1489
                $tabs = [
1490
                    'columns'    => [
1491
                        'title'   => $lang['strcolumns'],
1492
                        'url'     => 'viewproperties',
1493
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view')],
1494
                        'icon'    => 'Columns',
1495
                        'branch'  => true,
1496
                    ],
1497
                    'browse'     => [
1498
                        'title'   => $lang['strbrowse'],
1499
                        'icon'    => 'Columns',
1500
                        'url'     => 'display',
1501
                        'urlvars' => [
1502
                            'action'  => 'confselectrows',
1503
                            'return'  => 'schema',
1504
                            'subject' => 'view',
1505
                            'view'    => Decorator::field('view'),
1506
                        ],
1507
                        'branch'  => true,
1508
                    ],
1509
                    'select'     => [
1510
                        'title'   => $lang['strselect'],
1511
                        'icon'    => 'Search',
1512
                        'url'     => 'views',
1513
                        'urlvars' => ['action' => 'confselectrows', 'view' => Decorator::field('view')],
1514
                        'help'    => 'pg.sql.select',
1515
                    ],
1516
                    'definition' => [
1517
                        'title'   => $lang['strdefinition'],
1518
                        'url'     => 'viewproperties',
1519
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view'), 'action' => 'definition'],
1520
                        'icon'    => 'Definition',
1521
                    ],
1522
                    'rules'      => [
1523
                        'title'   => $lang['strrules'],
1524
                        'url'     => 'rules',
1525
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view')],
1526
                        'help'    => 'pg.rule',
1527
                        'icon'    => 'Rules',
1528
                        'branch'  => true,
1529
                    ],
1530
                    'privileges' => [
1531
                        'title'   => $lang['strprivileges'],
1532
                        'url'     => 'privileges',
1533
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view')],
1534
                        'help'    => 'pg.privilege',
1535
                        'icon'    => 'Privileges',
1536
                    ],
1537
                    'export'     => [
1538
                        'title'   => $lang['strexport'],
1539
                        'url'     => 'viewproperties',
1540
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view'), 'action' => 'export'],
1541
                        'icon'    => 'Export',
1542
                        'hide'    => false,
1543
                    ],
1544
                ];
1545
1546
                break;
1547
            case 'matview':
1548
                $tabs = [
1549
                    'columns'    => [
1550
                        'title'   => $lang['strcolumns'],
1551
                        'url'     => 'materializedviewproperties',
1552
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1553
                        'icon'    => 'Columns',
1554
                        'branch'  => true,
1555
                    ],
1556
                    'browse'     => [
1557
                        'title'   => $lang['strbrowse'],
1558
                        'icon'    => 'Columns',
1559
                        'url'     => 'display',
1560
                        'urlvars' => [
1561
                            'action'  => 'confselectrows',
1562
                            'return'  => 'schema',
1563
                            'subject' => 'matview',
1564
                            'matview' => Decorator::field('matview'),
1565
                        ],
1566
                        'branch'  => true,
1567
                    ],
1568
                    'select'     => [
1569
                        'title'   => $lang['strselect'],
1570
                        'icon'    => 'Search',
1571
                        'url'     => 'materializedviews',
1572
                        'urlvars' => ['action' => 'confselectrows', 'matview' => Decorator::field('matview')],
1573
                        'help'    => 'pg.sql.select',
1574
                    ],
1575
                    'definition' => [
1576
                        'title'   => $lang['strdefinition'],
1577
                        'url'     => 'materializedviewproperties',
1578
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview'), 'action' => 'definition'],
1579
                        'icon'    => 'Definition',
1580
                    ],
1581
                    'indexes'    => [
1582
                        'title'   => $lang['strindexes'],
1583
                        'url'     => 'indexes',
1584
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1585
                        'help'    => 'pg.index',
1586
                        'icon'    => 'Indexes',
1587
                        'branch'  => true,
1588
                    ],
1589
                    /*'constraints' => [
1590
                    'title' => $lang['strconstraints'],
1591
                    'url' => 'constraints',
1592
                    'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1593
                    'help' => 'pg.constraint',
1594
                    'icon' => 'Constraints',
1595
                    'branch' => true,
1596
                     */
1597
1598
                    'rules'      => [
1599
                        'title'   => $lang['strrules'],
1600
                        'url'     => 'rules',
1601
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1602
                        'help'    => 'pg.rule',
1603
                        'icon'    => 'Rules',
1604
                        'branch'  => true,
1605
                    ],
1606
                    'privileges' => [
1607
                        'title'   => $lang['strprivileges'],
1608
                        'url'     => 'privileges',
1609
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1610
                        'help'    => 'pg.privilege',
1611
                        'icon'    => 'Privileges',
1612
                    ],
1613
                    'export'     => [
1614
                        'title'   => $lang['strexport'],
1615
                        'url'     => 'materializedviewproperties',
1616
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview'), 'action' => 'export'],
1617
                        'icon'    => 'Export',
1618
                        'hide'    => false,
1619
                    ],
1620
                ];
1621
1622
                break;
1623
            case 'function':
1624
                $tabs = [
1625
                    'definition' => [
1626
                        'title'   => $lang['strdefinition'],
1627
                        'url'     => 'functions',
1628
                        'urlvars' => [
1629
                            'subject'      => 'function',
1630
                            'function'     => Decorator::field('function'),
1631
                            'function_oid' => Decorator::field('function_oid'),
1632
                            'action'       => 'properties',
1633
                        ],
1634
                        'icon'    => 'Definition',
1635
                    ],
1636
                    'privileges' => [
1637
                        'title'   => $lang['strprivileges'],
1638
                        'url'     => 'privileges',
1639
                        'urlvars' => [
1640
                            'subject'      => 'function',
1641
                            'function'     => Decorator::field('function'),
1642
                            'function_oid' => Decorator::field('function_oid'),
1643
                        ],
1644
                        'icon'    => 'Privileges',
1645
                    ],
1646
                ];
1647
1648
                break;
1649
            case 'aggregate':
1650
                $tabs = [
1651
                    'definition' => [
1652
                        'title'   => $lang['strdefinition'],
1653
                        'url'     => 'aggregates',
1654
                        'urlvars' => [
1655
                            'subject'  => 'aggregate',
1656
                            'aggrname' => Decorator::field('aggrname'),
1657
                            'aggrtype' => Decorator::field('aggrtype'),
1658
                            'action'   => 'properties',
1659
                        ],
1660
                        'icon'    => 'Definition',
1661
                    ],
1662
                ];
1663
1664
                break;
1665
            case 'role':
1666
                $tabs = [
1667
                    'definition' => [
1668
                        'title'   => $lang['strdefinition'],
1669
                        'url'     => 'roles',
1670
                        'urlvars' => [
1671
                            'subject'  => 'role',
1672
                            'rolename' => Decorator::field('rolename'),
1673
                            'action'   => 'properties',
1674
                        ],
1675
                        'icon'    => 'Definition',
1676
                    ],
1677
                ];
1678
1679
                break;
1680
            case 'popup':
1681
                $tabs = [
1682
                    'sql'  => [
1683
                        'title'   => $lang['strsql'],
1684
                        'url'     => '/src/views/sqledit',
1685
                        'urlvars' => ['action' => 'sql', 'subject' => 'schema'],
1686
                        'help'    => 'pg.sql',
1687
                        'icon'    => 'SqlEditor',
1688
                    ],
1689
                    'find' => [
1690
                        'title'   => $lang['strfind'],
1691
                        'url'     => '/src/views/sqledit',
1692
                        'urlvars' => ['action' => 'find', 'subject' => 'schema'],
1693
                        'icon'    => 'Search',
1694
                    ],
1695
                ];
1696
1697
                break;
1698
            case 'column':
1699
                $tabs = [
1700
                    'properties' => [
1701
                        'title'   => $lang['strcolprop'],
1702
                        'url'     => 'colproperties',
1703
                        'urlvars' => [
1704
                            'subject' => 'column',
1705
                            'table'   => Decorator::field('table'),
1706
                            'column'  => Decorator::field('column'),
1707
                        ],
1708
                        'icon'    => 'Column',
1709
                    ],
1710
                    'privileges' => [
1711
                        'title'   => $lang['strprivileges'],
1712
                        'url'     => 'privileges',
1713
                        'urlvars' => [
1714
                            'subject' => 'column',
1715
                            'table'   => Decorator::field('table'),
1716
                            'column'  => Decorator::field('column'),
1717
                        ],
1718
                        'help'    => 'pg.privilege',
1719
                        'icon'    => 'Privileges',
1720
                    ],
1721
                ];
1722
1723
                break;
1724
            case 'fulltext':
1725
                $tabs = [
1726
                    'ftsconfigs' => [
1727
                        'title'   => $lang['strftstabconfigs'],
1728
                        'url'     => 'fulltext',
1729
                        'urlvars' => ['subject' => 'schema'],
1730
                        'hide'    => !$data->hasFTS(),
1731
                        'help'    => 'pg.ftscfg',
1732
                        'tree'    => true,
1733
                        'icon'    => 'FtsCfg',
1734
                    ],
1735
                    'ftsdicts'   => [
1736
                        'title'   => $lang['strftstabdicts'],
1737
                        'url'     => 'fulltext',
1738
                        'urlvars' => ['subject' => 'schema', 'action' => 'viewdicts'],
1739
                        'hide'    => !$data->hasFTS(),
1740
                        'help'    => 'pg.ftsdict',
1741
                        'tree'    => true,
1742
                        'icon'    => 'FtsDict',
1743
                    ],
1744
                    'ftsparsers' => [
1745
                        'title'   => $lang['strftstabparsers'],
1746
                        'url'     => 'fulltext',
1747
                        'urlvars' => ['subject' => 'schema', 'action' => 'viewparsers'],
1748
                        'hide'    => !$data->hasFTS(),
1749
                        'help'    => 'pg.ftsparser',
1750
                        'tree'    => true,
1751
                        'icon'    => 'FtsParser',
1752
                    ],
1753
                ];
1754
1755
                break;
1756
        }
1757
1758
        // Tabs hook's place
1759
        $plugin_functions_parameters = [
1760
            'tabs'    => &$tabs,
1761
            'section' => $section,
1762
        ];
1763
        $plugin_manager->do_hook('tabs', $plugin_functions_parameters);
1764
1765
        return $tabs;
1766
    }
1767
1768
    /**
1769
     * Get the URL for the last active tab of a particular tab bar.
1770
     *
1771
     * @param string $section
1772
     *
1773
     * @return null|mixed
1774
     */
1775
    public function getLastTabURL($section)
1776
    {
1777
        //$data = $this->getDatabaseAccessor();
1778
1779
        $tabs = $this->getNavTabs($section);
1780
1781
        if (isset($_SESSION['webdbLastTab'][$section])) {
1782
            $tab = $tabs[$_SESSION['webdbLastTab'][$section]];
1783
        } else {
1784
            $tab = reset($tabs);
1785
        }
1786
        //$this->prtrace(['section' => $section, 'tabs' => $tabs, 'tab' => $tab]);
1787
        return isset($tab['url']) ? $tab : null;
1788
    }
1789
1790
    /**
1791
     * Do multi-page navigation.  Displays the prev, next and page options.
1792
     *
1793
     * @param int    $page      - the page currently viewed
1794
     * @param int    $pages     - the maximum number of pages
1795
     * @param string $gets      -  the parameters to include in the link to the wanted page
1796
     * @param int    $max_width - the number of pages to make available at any one time (default = 20)
1797
     */
1798
    public function printPages($page, $pages, $gets, $max_width = 20)
1799
    {
1800
        $lang = $this->lang;
1801
1802
        $window = 10;
1803
1804
        if ($page < 0 || $page > $pages) {
1805
            return;
1806
        }
1807
1808
        if ($pages < 0) {
1809
            return;
1810
        }
1811
1812
        if ($max_width <= 0) {
1813
            return;
1814
        }
1815
1816
        unset($gets['page']);
1817
        $url = http_build_query($gets);
1818
1819
        if ($pages > 1) {
1820
            echo "<p style=\"text-align: center\">\n";
1821
            if ($page != 1) {
1822
                echo "<a class=\"pagenav\" href=\"?{$url}&amp;page=1\">{$lang['strfirst']}</a>\n";
1823
                $temp = $page - 1;
1824
                echo "<a class=\"pagenav\" href=\"?{$url}&amp;page={$temp}\">{$lang['strprev']}</a>\n";
1825
            }
1826
1827
            if ($page <= $window) {
1828
                $min_page = 1;
1829
                $max_page = min(2 * $window, $pages);
1830
            } elseif ($page > $window && $pages >= $page + $window) {
1831
                $min_page = ($page - $window) + 1;
1832
                $max_page = $page + $window;
1833
            } else {
1834
                $min_page = ($page - (2 * $window - ($pages - $page))) + 1;
1835
                $max_page = $pages;
1836
            }
1837
1838
            // Make sure min_page is always at least 1
1839
            // and max_page is never greater than $pages
1840
            $min_page = max($min_page, 1);
1841
            $max_page = min($max_page, $pages);
1842
1843
            for ($i = $min_page; $i <= $max_page; ++$i) {
1844
                #if ($i != $page) echo "<a class=\"pagenav\" href=\"?{$url}&amp;page={$i}\">$i</a>\n";
0 ignored issues
show
Coding Style introduced by
Perl-style comments are not allowed. Use "// Comment." or "/* comment */" instead.
Loading history...
1845
                if ($i != $page) {
1846
                    echo "<a class=\"pagenav\" href=\"display?{$url}&amp;page={$i}\">${i}</a>\n";
1847
                } else {
1848
                    echo "${i}\n";
1849
                }
1850
            }
1851
            if ($page != $pages) {
1852
                $temp = $page + 1;
1853
                echo "<a class=\"pagenav\" href=\"display?{$url}&amp;page={$temp}\">{$lang['strnext']}</a>\n";
1854
                echo "<a class=\"pagenav\" href=\"display?{$url}&amp;page={$pages}\">{$lang['strlast']}</a>\n";
1855
            }
1856
            echo "</p>\n";
1857
        }
1858
    }
1859
1860
    /**
1861
     * Converts a PHP.INI size variable to bytes.  Taken from publically available
1862
     * function by Chris DeRose, here: http://www.php.net/manual/en/configuration.directives.php#ini.file-uploads.
1863
     *
1864
     * @param mixed $strIniSize The PHP.INI variable
1865
     *
1866
     * @return float|double|int size in bytes, false on failure
1867
     */
1868
    public function inisizeToBytes($strIniSize)
1869
    {
1870
        // This function will take the string value of an ini 'size' parameter,
1871
        // and return a double (64-bit float) representing the number of bytes
1872
        // that the parameter represents. Or false if $strIniSize is unparseable.
1873
        $a_IniParts = [];
1874
1875
        if (!is_string($strIniSize)) {
1876
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer|double.
Loading history...
1877
        }
1878
1879
        if (!preg_match('/^(\d+)([bkm]*)$/i', $strIniSize, $a_IniParts)) {
1880
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer|double.
Loading history...
1881
        }
1882
1883
        $nSize   = (float) $a_IniParts[1];
1884
        $strUnit = strtolower($a_IniParts[2]);
1885
1886
        switch ($strUnit) {
1887
            case 'm':
1888
                return $nSize * (float) 1048576;
1889
            case 'k':
1890
                return $nSize * (float) 1024;
1891
            case 'b':
1892
            default:
1893
                return $nSize;
1894
        }
1895
    }
1896
1897
    public function getRequestVars($subject = '')
1898
    {
1899
        $v = [];
1900
        if (!empty($subject)) {
1901
            $v['subject'] = $subject;
1902
        }
1903
1904
        if ($this->_server_id !== null && $subject != 'root') {
1905
            $v['server'] = $this->_server_id;
1906
            if ($this->_database !== null && $subject != 'server') {
1907
                $v['database'] = $this->_database;
1908
                if (isset($_REQUEST['schema']) && $subject != 'database') {
1909
                    $v['schema'] = $_REQUEST['schema'];
1910
                }
1911
            }
1912
        }
1913
        //$this->prtrace($v);
1914
        return $v;
1915
    }
1916
1917
    public function icon($icon)
1918
    {
1919
        if (is_string($icon)) {
1920
            $path = "/images/themes/{$this->conf['theme']}/{$icon}";
1921
            if (file_exists(\BASE_PATH . $path . '.png')) {
1922
                return SUBFOLDER . $path . '.png';
1923
            }
1924
1925
            if (file_exists(\BASE_PATH . $path . '.gif')) {
1926
                return SUBFOLDER . $path . '.gif';
1927
            }
1928
1929
            if (file_exists(\BASE_PATH . $path . '.ico')) {
1930
                return SUBFOLDER . $path . '.ico';
1931
            }
1932
1933
            $path = "/images/themes/default/{$icon}";
1934
            if (file_exists(\BASE_PATH . $path . '.png')) {
1935
                return SUBFOLDER . $path . '.png';
1936
            }
1937
1938
            if (file_exists(\BASE_PATH . $path . '.gif')) {
1939
                return SUBFOLDER . $path . '.gif';
1940
            }
1941
1942
            if (file_exists(\BASE_PATH . $path . '.ico')) {
1943
                return SUBFOLDER . $path . '.ico';
1944
            }
1945
        } else {
1946
            // Icon from plugins
1947
            $path = "/plugins/{$icon[0]}/images/{$icon[1]}";
1948
            if (file_exists(\BASE_PATH . $path . '.png')) {
1949
                return SUBFOLDER . $path . '.png';
1950
            }
1951
1952
            if (file_exists(\BASE_PATH . $path . '.gif')) {
1953
                return SUBFOLDER . $path . '.gif';
1954
            }
1955
1956
            if (file_exists(\BASE_PATH . $path . '.ico')) {
1957
                return SUBFOLDER . $path . '.ico';
1958
            }
1959
        }
1960
1961
        return '';
1962
    }
1963
1964
    /**
1965
     * Function to escape command line parameters.
1966
     *
1967
     * @param string $str The string to escape
1968
     *
1969
     * @return string The escaped string
1970
     */
1971
    public function escapeShellArg($str)
1972
    {
1973
        //$data = $this->getDatabaseAccessor();
1974
        $lang = $this->lang;
1975
1976
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1977
            // Due to annoying PHP bugs, shell arguments cannot be escaped
1978
            // (command simply fails), so we cannot allow complex objects
1979
            // to be dumped.
1980
            if (preg_match('/^[_.[:alnum:]]+$/', $str)) {
1981
                return $str;
1982
            }
1983
1984
            return $this->halt($lang['strcannotdumponwindows']);
1985
        }
1986
1987
        return escapeshellarg($str);
1988
    }
1989
1990
    /**
1991
     * Function to escape command line programs.
1992
     *
1993
     * @param string $str The string to escape
1994
     *
1995
     * @return string The escaped string
1996
     */
1997
    public function escapeShellCmd($str)
1998
    {
1999
        $data = $this->getDatabaseAccessor();
2000
2001
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2002
            $data->fieldClean($str);
2003
2004
            return '"' . $str . '"';
2005
        }
2006
2007
        return escapeshellcmd($str);
2008
    }
2009
2010
    /**
2011
     * Save the given SQL script in the history
2012
     * of the database and server.
2013
     *
2014
     * @param string $script the SQL script to save
2015
     */
2016
    public function saveScriptHistory($script)
2017
    {
2018
        list($usec, $sec)                                                           = explode(' ', microtime());
2019
        $time                                                                       = ((float) $usec + (float) $sec);
2020
        $_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']]["${time}"] = [
2021
            'query'    => $script,
2022
            'paginate' => !isset($_REQUEST['paginate']) ? 'f' : 't',
2023
            'queryid'  => $time,
2024
        ];
2025
    }
2026
2027
    /**
2028
     * returns an array representing FKs definition for a table, sorted by fields
1 ignored issue
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
2029
     * or by constraint.
2030
     *
2031
     * @param string $table The table to retrieve FK contraints from
2032
     *
2033
     * @return array|bool the array of FK definition:
2034
     *                    array(
2035
     *                    'byconstr' => array(
2036
     *                    constrain id => array(
2037
     *                    confrelid => foreign relation oid
2038
     *                    f_schema => foreign schema name
2039
     *                    f_table => foreign table name
2040
     *                    pattnums => array of parent's fields nums
2041
     *                    pattnames => array of parent's fields names
2042
     *                    fattnames => array of foreign attributes names
2043
     *                    )
2044
     *                    ),
2045
     *                    'byfield' => array(
2046
     *                    attribute num => array (constraint id, ...)
2047
     *                    ),
2048
     *                    'code' => HTML/js code to include in the page for auto-completion
2049
     *                    )
2050
     */
2051
    public function getAutocompleteFKProperties($table)
2052
    {
2053
        $data = $this->getDatabaseAccessor();
2054
2055
        $fksprops = [
2056
            'byconstr' => [],
2057
            'byfield'  => [],
2058
            'code'     => '',
2059
        ];
2060
2061
        $constrs = $data->getConstraintsWithFields($table);
2062
2063
        if (!$constrs->EOF) {
2064
            //$conrelid = $constrs->fields['conrelid'];
2065
            while (!$constrs->EOF) {
2066
                if ($constrs->fields['contype'] == 'f') {
2067
                    if (!isset($fksprops['byconstr'][$constrs->fields['conid']])) {
2068
                        $fksprops['byconstr'][$constrs->fields['conid']] = [
2069
                            'confrelid' => $constrs->fields['confrelid'],
2070
                            'f_table'   => $constrs->fields['f_table'],
2071
                            'f_schema'  => $constrs->fields['f_schema'],
2072
                            'pattnums'  => [],
2073
                            'pattnames' => [],
2074
                            'fattnames' => [],
2075
                        ];
2076
                    }
2077
2078
                    $fksprops['byconstr'][$constrs->fields['conid']]['pattnums'][]  = $constrs->fields['p_attnum'];
2079
                    $fksprops['byconstr'][$constrs->fields['conid']]['pattnames'][] = $constrs->fields['p_field'];
2080
                    $fksprops['byconstr'][$constrs->fields['conid']]['fattnames'][] = $constrs->fields['f_field'];
2081
2082
                    if (!isset($fksprops['byfield'][$constrs->fields['p_attnum']])) {
2083
                        $fksprops['byfield'][$constrs->fields['p_attnum']] = [];
2084
                    }
2085
2086
                    $fksprops['byfield'][$constrs->fields['p_attnum']][] = $constrs->fields['conid'];
2087
                }
2088
                $constrs->moveNext();
2089
            }
2090
2091
            $fksprops['code'] = "<script type=\"text/javascript\">\n";
2092
            $fksprops['code'] .= "var constrs = {};\n";
2093
            foreach ($fksprops['byconstr'] as $conid => $props) {
2094
                $fksprops['code'] .= "constrs.constr_{$conid} = {\n";
2095
                $fksprops['code'] .= 'pattnums: [' . implode(',', $props['pattnums']) . "],\n";
2096
                $fksprops['code'] .= "f_table:'" . addslashes(htmlentities($props['f_table'], ENT_QUOTES, 'UTF-8')) . "',\n";
2097
                $fksprops['code'] .= "f_schema:'" . addslashes(htmlentities($props['f_schema'], ENT_QUOTES, 'UTF-8')) . "',\n";
2098
                $_ = '';
2099
                foreach ($props['pattnames'] as $n) {
2100
                    $_ .= ",'" . htmlentities($n, ENT_QUOTES, 'UTF-8') . "'";
2101
                }
2102
                $fksprops['code'] .= 'pattnames: [' . substr($_, 1) . "],\n";
2103
2104
                $_ = '';
2105
                foreach ($props['fattnames'] as $n) {
2106
                    $_ .= ",'" . htmlentities($n, ENT_QUOTES, 'UTF-8') . "'";
2107
                }
2108
2109
                $fksprops['code'] .= 'fattnames: [' . substr($_, 1) . "]\n";
2110
                $fksprops['code'] .= "};\n";
2111
            }
2112
2113
            $fksprops['code'] .= "var attrs = {};\n";
2114
            foreach ($fksprops['byfield'] as $attnum => $cstrs) {
2115
                $fksprops['code'] .= "attrs.attr_{$attnum} = [" . implode(',', $fksprops['byfield'][$attnum]) . "];\n";
2116
            }
2117
2118
            $fksprops['code'] .= "var table='" . addslashes(htmlentities($table, ENT_QUOTES, 'UTF-8')) . "';";
2119
            $fksprops['code'] .= "var server='" . htmlentities($_REQUEST['server'], ENT_QUOTES, 'UTF-8') . "';";
2120
            $fksprops['code'] .= "var database='" . addslashes(htmlentities($_REQUEST['database'], ENT_QUOTES, 'UTF-8')) . "';";
2121
            $fksprops['code'] .= "var subfolder='" . SUBFOLDER . "';";
2122
            $fksprops['code'] .= "</script>\n";
2123
2124
            $fksprops['code'] .= '<div id="fkbg"></div>';
2125
            $fksprops['code'] .= '<div id="fklist"></div>';
2126
            $fksprops['code'] .= '<script src="' . SUBFOLDER . '/js/ac_insert_row.js" type="text/javascript"></script>';
2127
        } else {
2128
            /* we have no foreign keys on this table */
2129
            return false;
2130
        }
2131
2132
        return $fksprops;
2133
    }
2134
}
2135