Passed
Push — develop ( 5ae676...d12c25 )
by Felipe
04:37
created

Misc::getDatabase()   D

Complexity

Conditions 10
Paths 6

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 17
nc 6
nop 1

How to fix   Complexity   

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.44
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
 * Release: Misc.php,v 1.171 2008/03/17 21:35:48 ioguix Exp $
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 ($this->_no_db_connection === false &&
359
            $this->getDatabase() !== null &&
360
            isset($_REQUEST['schema'])
361
        ) {
362
            $status = $this->_data->setSchema($_REQUEST['schema']);
363
364
            if ($status != 0) {
365
                $this->container->utils->addError($this->lang['strbadschema']);
366
                $this->setErrorMsg($this->lang['strbadschema']);
367
368
                return null;
369
            }
370
        }
371
372
        return $this->_data;
373
    }
374
375
    public function getConnection($database = '', $server_id = null)
376
    {
377
        $lang = $this->lang;
378
379
        if ($this->_connection === null) {
380
            if ($server_id !== null) {
381
                $this->_server_id = $server_id;
382
            }
383
            $server_info     = $this->getServerInfo($this->_server_id);
384
            $database_to_use = $this->getDatabase($database);
385
386
            // Perform extra security checks if this config option is set
387
            if ($this->conf['extra_login_security']) {
388
                // Disallowed logins if extra_login_security is enabled.
389
                // These must be lowercase.
390
                $bad_usernames = [
391
                    'pgsql'         => 'pgsql',
392
                    'postgres'      => 'postgres',
393
                    'root'          => 'root',
394
                    'administrator' => 'administrator',
395
                ];
396
397
                if (isset($server_info['username']) &&
398
                    array_key_exists(strtolower($server_info['username']), $bad_usernames)
399
                ) {
400
                    $msg = $lang['strlogindisallowed'];
401
402
                    throw new \Exception($msg);
403
                }
404
405
                if (!isset($server_info['password']) ||
406
                    $server_info['password'] == ''
407
                ) {
408
                    $msg = $lang['strlogindisallowed'];
409
410
                    throw new \Exception($msg);
411
                }
412
            }
413
414
            try {
415
                // Create the connection object and make the connection
416
                $this->_connection = new \PHPPgAdmin\Database\Connection(
417
                    $server_info,
418
                    $database_to_use,
419
                    $this->container
420
                );
421
            } catch (\PHPPgAdmin\ADOdbException $e) {
422
                throw new \Exception($lang['strloginfailed']);
423
            }
424
        }
425
426
        return $this->_connection;
427
    }
428
429
    /**
430
     * Validate and retrieve information on a server.
431
     * If the parameter isn't supplied then the currently
432
     * connected server is returned.
433
     *
434
     * @param string $server_id A server identifier (host:port)
435
     *
436
     * @return array An associative array of server properties
437
     */
438
    public function getServerInfo($server_id = null)
439
    {
440
        //\PC::debug(['$server_id' => $server_id]);
441
442
        if ($server_id !== null) {
443
            $this->_server_id = $server_id;
444
        } elseif ($this->_server_info !== null) {
445
            return $this->_server_info;
446
        }
447
448
        // Check for the server in the logged-in list
449
        if (isset($_SESSION['webdbLogin'][$this->_server_id])) {
450
            $this->_server_info = $_SESSION['webdbLogin'][$this->_server_id];
451
452
            return $this->_server_info;
453
        }
454
455
        // Otherwise, look for it in the conf file
456
        foreach ($this->conf['servers'] as $idx => $info) {
457
            $server_string = $info['host'].':'.$info['port'].':'.$info['sslmode'];
458
            $server_sha    = sha1($server_string);
459
460
            if ($this->_server_id === $server_string ||
461
                $this->_server_id === $server_sha
462
            ) {
463
                if (isset($info['username'])) {
464
                    $this->setServerInfo(null, $info, $this->_server_id);
465
                } elseif (isset($_SESSION['sharedUsername'])) {
466
                    $info['username'] = $_SESSION['sharedUsername'];
467
                    $info['password'] = $_SESSION['sharedPassword'];
468
                    $this->setReloadBrowser(true);
469
                    $this->setServerInfo(null, $info, $this->_server_id);
470
                }
471
                $this->_server_info = $info;
472
473
                return $this->_server_info;
474
            }
475
        }
476
477
        if ($server_id === null) {
478
            $this->_server_info = null;
479
480
            return $this->_server_info;
481
        }
482
483
        $this->prtrace('Invalid server param');
484
        $this->_server_info = null;
485
        // Unable to find a matching server, are we being hacked?
486
        return $this->halt($this->lang['strinvalidserverparam']);
487
    }
488
489
    /**
490
     * Set server information.
491
     *
492
     * @param string      $key       parameter name to set, or null to replace all
493
     *                               params with the assoc-array in $value
494
     * @param mixed       $value     the new value, or null to unset the parameter
495
     * @param null|string $server_id the server identifier, or null for current server
496
     */
497
    public function setServerInfo($key, $value, $server_id = null)
498
    {
499
        //\PC::debug('setsetverinfo');
500
        if ($server_id === null) {
501
            $server_id = $this->container->requestobj->getParam('server');
502
        }
503
504
        if ($key === null) {
0 ignored issues
show
introduced by
The condition $key === null is always false.
Loading history...
505
            if ($value === null) {
506
                unset($_SESSION['webdbLogin'][$server_id]);
507
            } else {
508
                //\PC::debug(['server_id' => $server_id, 'value' => $value], 'webdbLogin null key');
509
                $_SESSION['webdbLogin'][$server_id] = $value;
510
            }
511
        } else {
512
            if ($value === null) {
513
                unset($_SESSION['webdbLogin'][$server_id][$key]);
514
            } else {
515
                //\PC::debug(['server_id' => $server_id, 'key' => $key, 'value' => $value], __FILE__ . ' ' . __LINE__ . ' webdbLogin key ' . $key);
516
                $_SESSION['webdbLogin'][$server_id][$key] = $value;
517
            }
518
        }
519
    }
520
521
    public function getDatabase($database = '')
522
    {
523
        if ($this->_server_id === null && !isset($_REQUEST['database'])) {
524
            return null;
525
        }
526
527
        $server_info = $this->getServerInfo($this->_server_id);
528
529
        if ($this->_server_id !== null &&
530
            isset($server_info['useonlydefaultdb']) &&
531
            $server_info['useonlydefaultdb'] === true &&
532
            isset($_server_info['defaultdb'])
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $_server_info does not exist. Did you maybe mean $server_info?
Loading history...
533
        ) {
534
            $this->_database = $server_info['defaultdb'];
535
        } elseif ($database !== '') {
536
            $this->_database = $database;
537
        } elseif (isset($_REQUEST['database'])) {
538
            // Connect to the current database
539
            $this->_database = $_REQUEST['database'];
540
        } elseif (isset($_server_info['defaultdb'])) {
541
            // or if one is not specified then connect to the default database.
542
            $this->_database = $server_info['defaultdb'];
543
        } else {
544
            return null;
545
        }
546
547
        return $this->_database;
548
    }
549
550
    /**
551
     * Set the current schema.
552
     *
553
     * @param string $schema The schema name
554
     *
555
     * @return int 0 on success
556
     */
557
    public function setCurrentSchema($schema)
558
    {
559
        $data = $this->getDatabaseAccessor();
560
561
        $status = $data->setSchema($schema);
562
        if ($status != 0) {
563
            return $status;
564
        }
565
566
        $_REQUEST['schema'] = $schema;
567
        $this->container->offsetSet('schema', $schema);
568
        $this->setHREF();
569
570
        return 0;
571
    }
572
573
    /**
574
     * Checks if dumps are properly set up.
575
     *
576
     * @param bool $all (optional) True to check pg_dumpall, false to just check pg_dump
577
     *
578
     * @return bool True, dumps are set up, false otherwise
579
     */
580
    public function isDumpEnabled($all = false)
581
    {
582
        $info = $this->getServerInfo();
583
584
        return !empty($info[$all ? 'pg_dumpall_path' : 'pg_dump_path']);
585
    }
586
587
    /**
588
     * Sets the href tracking variable.
589
     *
590
     * @return \PHPPgAdmin\Misc this class instance
591
     */
592
    public function setHREF()
593
    {
594
        $this->href = $this->getHREF();
595
        //\PC::debug($this->href, 'Misc::href');
596
        return $this;
597
    }
598
599
    /**
600
     * Get a href query string, excluding objects below the given object type (inclusive).
601
     *
602
     * @param null|string $exclude_from
603
     *
604
     * @return string
605
     */
606
    public function getHREF($exclude_from = null)
607
    {
608
        $href = [];
609
610
        $server   = $this->container->server || isset($_REQUEST['server']) ? $_REQUEST['server'] : null;
611
        $database = $this->container->database || isset($_REQUEST['database']) ? $_REQUEST['database'] : null;
612
        $schema   = $this->container->schema || isset($_REQUEST['schema']) ? $_REQUEST['schema'] : null;
613
614
        if ($server && $exclude_from !== 'server') {
615
            $href[] = 'server='.urlencode($server);
616
        }
617
        if ($database && $exclude_from !== 'database') {
618
            $href[] = 'database='.urlencode($database);
619
        }
620
        if ($schema && $exclude_from !== 'schema') {
621
            $href[] = 'schema='.urlencode($schema);
622
        }
623
624
        $this->href = htmlentities(implode('&', $href));
625
626
        return $this->href;
627
    }
628
629
    public function getSubjectParams($subject)
630
    {
631
        $plugin_manager = $this->plugin_manager;
632
633
        $vars = [];
634
635
        switch ($subject) {
636
            case 'root':
637
                $vars = [
638
                    'params' => [
639
                        'subject' => 'root',
640
                    ],
641
                ];
642
643
                break;
644
            case 'server':
645
                $vars = ['params' => [
646
                    'server'  => $_REQUEST['server'],
647
                    'subject' => 'server',
648
                ]];
649
650
                break;
651
            case 'role':
652
                $vars = ['params' => [
653
                    'server'   => $_REQUEST['server'],
654
                    'subject'  => 'role',
655
                    'action'   => 'properties',
656
                    'rolename' => $_REQUEST['rolename'],
657
                ]];
658
659
                break;
660
            case 'database':
661
                $vars = ['params' => [
662
                    'server'   => $_REQUEST['server'],
663
                    'subject'  => 'database',
664
                    'database' => $_REQUEST['database'],
665
                ]];
666
667
                break;
668
            case 'schema':
669
                $vars = ['params' => [
670
                    'server'   => $_REQUEST['server'],
671
                    'subject'  => 'schema',
672
                    'database' => $_REQUEST['database'],
673
                    'schema'   => $_REQUEST['schema'],
674
                ]];
675
676
                break;
677
            case 'table':
678
                $vars = ['params' => [
679
                    'server'   => $_REQUEST['server'],
680
                    'subject'  => 'table',
681
                    'database' => $_REQUEST['database'],
682
                    'schema'   => $_REQUEST['schema'],
683
                    'table'    => $_REQUEST['table'],
684
                ]];
685
686
                break;
687
            case 'selectrows':
688
                $vars = [
689
                    'url'    => 'tables',
690
                    'params' => [
691
                        'server'   => $_REQUEST['server'],
692
                        'subject'  => 'table',
693
                        'database' => $_REQUEST['database'],
694
                        'schema'   => $_REQUEST['schema'],
695
                        'table'    => $_REQUEST['table'],
696
                        'action'   => 'confselectrows',
697
                    ], ];
698
699
                break;
700
            case 'view':
701
                $vars = ['params' => [
702
                    'server'   => $_REQUEST['server'],
703
                    'subject'  => 'view',
704
                    'database' => $_REQUEST['database'],
705
                    'schema'   => $_REQUEST['schema'],
706
                    'view'     => $_REQUEST['view'],
707
                ]];
708
709
                break;
710
            case 'matview':
711
                $vars = ['params' => [
712
                    'server'   => $_REQUEST['server'],
713
                    'subject'  => 'matview',
714
                    'database' => $_REQUEST['database'],
715
                    'schema'   => $_REQUEST['schema'],
716
                    'matview'  => $_REQUEST['matview'],
717
                ]];
718
719
                break;
720
            case 'fulltext':
721
            case 'ftscfg':
722
                $vars = ['params' => [
723
                    'server'   => $_REQUEST['server'],
724
                    'subject'  => 'fulltext',
725
                    'database' => $_REQUEST['database'],
726
                    'schema'   => $_REQUEST['schema'],
727
                    'action'   => 'viewconfig',
728
                    'ftscfg'   => $_REQUEST['ftscfg'],
729
                ]];
730
731
                break;
732
            case 'function':
733
                $vars = ['params' => [
734
                    'server'       => $_REQUEST['server'],
735
                    'subject'      => 'function',
736
                    'database'     => $_REQUEST['database'],
737
                    'schema'       => $_REQUEST['schema'],
738
                    'function'     => $_REQUEST['function'],
739
                    'function_oid' => $_REQUEST['function_oid'],
740
                ]];
741
742
                break;
743
            case 'aggregate':
744
                $vars = ['params' => [
745
                    'server'   => $_REQUEST['server'],
746
                    'subject'  => 'aggregate',
747
                    'action'   => 'properties',
748
                    'database' => $_REQUEST['database'],
749
                    'schema'   => $_REQUEST['schema'],
750
                    'aggrname' => $_REQUEST['aggrname'],
751
                    'aggrtype' => $_REQUEST['aggrtype'],
752
                ]];
753
754
                break;
755
            case 'column':
756
                if (isset($_REQUEST['table'])) {
757
                    $vars = ['params' => [
758
                        'server'   => $_REQUEST['server'],
759
                        'subject'  => 'column',
760
                        'database' => $_REQUEST['database'],
761
                        'schema'   => $_REQUEST['schema'],
762
                        'table'    => $_REQUEST['table'],
763
                        'column'   => $_REQUEST['column'],
764
                    ]];
765
                } else {
766
                    $vars = ['params' => [
767
                        'server'   => $_REQUEST['server'],
768
                        'subject'  => 'column',
769
                        'database' => $_REQUEST['database'],
770
                        'schema'   => $_REQUEST['schema'],
771
                        'view'     => $_REQUEST['view'],
772
                        'column'   => $_REQUEST['column'],
773
                    ]];
774
                }
775
776
                break;
777
            case 'plugin':
778
                $vars = [
779
                    'url'    => 'plugin',
780
                    'params' => [
781
                        'server'  => $_REQUEST['server'],
782
                        'subject' => 'plugin',
783
                        'plugin'  => $_REQUEST['plugin'],
784
                    ], ];
785
786
                if (!is_null($plugin_manager->getPlugin($_REQUEST['plugin']))) {
787
                    $vars['params'] = array_merge($vars['params'], $plugin_manager->getPlugin($_REQUEST['plugin'])->get_subject_params());
788
                }
789
790
                break;
791
            default:
792
                return false;
793
        }
794
795
        if (!isset($vars['url'])) {
796
            $vars['url'] = SUBFOLDER.'/redirect';
797
        }
798
        if ($vars['url'] == SUBFOLDER.'/redirect' && isset($vars['params']['subject'])) {
799
            $vars['url'] = SUBFOLDER.'/redirect/'.$vars['params']['subject'];
800
            unset($vars['params']['subject']);
801
        }
802
803
        return $vars;
804
    }
805
806
    /**
807
     * Sets the form tracking variable.
808
     */
809
    public function setForm()
810
    {
811
        $form = [];
812
        if ($this->container->server) {
813
            $form[] = '<input type="hidden" name="server" value="'.htmlspecialchars($this->container->server).'" />';
814
        }
815
        if ($this->container->database) {
816
            $form[] = '<input type="hidden" name="database" value="'.htmlspecialchars($this->container->database).'" />';
817
        }
818
819
        if ($this->container->schema) {
820
            $form[] = '<input type="hidden" name="schema" value="'.htmlspecialchars($this->container->schema).'" />';
821
        }
822
        $this->form = implode("\n", $form);
823
824
        return $this->form;
825
        //\PC::debug($this->form, 'Misc::form');
826
    }
827
828
    /**
829
     * Render a value into HTML using formatting rules specified
830
     * by a type name and parameters.
831
     *
832
     * @param string $str    The string to change
833
     * @param string $type   Field type (optional), this may be an internal PostgreSQL type, or:
834
     *                       yesno    - same as bool, but renders as 'Yes' or 'No'.
835
     *                       pre      - render in a <pre> block.
836
     *                       nbsp     - replace all spaces with &nbsp;'s
837
     *                       verbatim - render exactly as supplied, no escaping what-so-ever.
838
     *                       callback - render using a callback function supplied in the 'function' param.
839
     * @param array  $params Type parameters (optional), known parameters:
840
     *                       null     - string to display if $str is null, or set to TRUE to use a default 'NULL' string,
841
     *                       otherwise nothing is rendered.
842
     *                       clip     - if true, clip the value to a fixed length, and append an ellipsis...
843
     *                       cliplen  - the maximum length when clip is enabled (defaults to $conf['max_chars'])
844
     *                       ellipsis - the string to append to a clipped value (defaults to $lang['strellipsis'])
845
     *                       tag      - an HTML element name to surround the value.
846
     *                       class    - a class attribute to apply to any surrounding HTML element.
847
     *                       align    - an align attribute ('left','right','center' etc.)
848
     *                       true     - (type='bool') the representation of true.
849
     *                       false    - (type='bool') the representation of false.
850
     *                       function - (type='callback') a function name, accepts args ($str, $params) and returns a rendering.
851
     *                       lineno   - prefix each line with a line number.
852
     *                       map      - an associative array.
853
     *
854
     * @return string The HTML rendered value
855
     */
856
    public function printVal($str, $type = null, $params = [])
857
    {
858
        $lang = $this->lang;
859
        $data = $this->getDatabaseAccessor();
860
861
        // Shortcircuit for a NULL value
862
        if (!$str) {
863
            return isset($params['null'])
864
            ? ($params['null'] === true ? '<i>NULL</i>' : $params['null'])
865
            : '';
866
        }
867
868
        if (isset($params['map'], $params['map'][$str])) {
869
            $str = $params['map'][$str];
870
        }
871
872
        // Clip the value if the 'clip' parameter is true.
873
        if (isset($params['clip']) && $params['clip'] === true) {
874
            $maxlen   = isset($params['cliplen']) && is_integer($params['cliplen']) ? $params['cliplen'] : $this->conf['max_chars'];
875
            $ellipsis = isset($params['ellipsis']) ? $params['ellipsis'] : $lang['strellipsis'];
876
            if (strlen($str) > $maxlen) {
877
                $str = substr($str, 0, $maxlen - 1).$ellipsis;
878
            }
879
        }
880
881
        $out   = '';
882
        $class = '';
883
884
        switch ($type) {
885
            case 'int2':
886
            case 'int4':
887
            case 'int8':
888
            case 'float4':
889
            case 'float8':
890
            case 'money':
891
            case 'numeric':
892
            case 'oid':
893
            case 'xid':
894
            case 'cid':
895
            case 'tid':
896
                $align = 'right';
897
                $out   = nl2br(htmlspecialchars(\PHPPgAdmin\Traits\HelperTrait::br2ln($str)));
898
899
                break;
900
            case 'yesno':
901
                if (!isset($params['true'])) {
902
                    $params['true'] = $lang['stryes'];
903
                }
904
905
                if (!isset($params['false'])) {
906
                    $params['false'] = $lang['strno'];
907
                }
908
909
            // no break - fall through to boolean case.
910
            case 'bool':
911
            case 'boolean':
912
                if (is_bool($str)) {
913
                    $str = $str ? 't' : 'f';
914
                }
915
916
                switch ($str) {
917
                    case 't':
918
                        $out   = (isset($params['true']) ? $params['true'] : $lang['strtrue']);
919
                        $align = 'center';
920
921
                        break;
922
                    case 'f':
923
                        $out   = (isset($params['false']) ? $params['false'] : $lang['strfalse']);
924
                        $align = 'center';
925
926
                        break;
927
                    default:
928
                        $out = htmlspecialchars($str);
929
                }
930
931
                break;
932
            case 'bytea':
933
                $tag   = 'div';
934
                $class = 'pre';
935
                $out   = $data->escapeBytea($str);
936
937
                break;
938
            case 'errormsg':
939
                $tag   = 'pre';
940
                $class = 'error';
941
                $out   = htmlspecialchars($str);
942
943
                break;
944
            case 'pre':
945
                $tag = 'pre';
946
                $out = htmlspecialchars($str);
947
948
                break;
949
            case 'prenoescape':
950
                $tag = 'pre';
951
                $out = $str;
952
953
                break;
954
            case 'nbsp':
955
                $out = nl2br(str_replace(' ', '&nbsp;', \PHPPgAdmin\Traits\HelperTrait::br2ln($str)));
956
957
                break;
958
            case 'verbatim':
959
                $out = $str;
960
961
                break;
962
            case 'callback':
963
                $out = $params['function']($str, $params);
964
965
                break;
966
            case 'prettysize':
967
                if ($str == -1) {
968
                    $out = $lang['strnoaccess'];
969
                } else {
970
                    $limit = 10 * 1024;
971
                    $mult  = 1;
972
                    if ($str < $limit * $mult) {
973
                        $out = $str.' '.$lang['strbytes'];
974
                    } else {
975
                        $mult *= 1024;
976
                        if ($str < $limit * $mult) {
977
                            $out = floor(($str + $mult / 2) / $mult).' '.$lang['strkb'];
978
                        } else {
979
                            $mult *= 1024;
980
                            if ($str < $limit * $mult) {
981
                                $out = floor(($str + $mult / 2) / $mult).' '.$lang['strmb'];
982
                            } else {
983
                                $mult *= 1024;
984
                                if ($str < $limit * $mult) {
985
                                    $out = floor(($str + $mult / 2) / $mult).' '.$lang['strgb'];
986
                                } else {
987
                                    $mult *= 1024;
988
                                    if ($str < $limit * $mult) {
989
                                        $out = floor(($str + $mult / 2) / $mult).' '.$lang['strtb'];
990
                                    }
991
                                }
992
                            }
993
                        }
994
                    }
995
                }
996
997
                break;
998
            default:
999
                // If the string contains at least one instance of >1 space in a row, a tab
1000
                // character, a space at the start of a line, or a space at the start of
1001
                // the whole string then render within a pre-formatted element (<pre>).
1002
                if (preg_match('/(^ |  |\t|\n )/m', $str)) {
1003
                    $tag   = 'pre';
1004
                    $class = 'data';
1005
                    $out   = htmlspecialchars($str);
1006
                } else {
1007
                    $out = nl2br(htmlspecialchars(\PHPPgAdmin\Traits\HelperTrait::br2ln($str)));
1008
                }
1009
        }
1010
1011
        if (isset($params['class'])) {
1012
            $class = $params['class'];
1013
        }
1014
1015
        if (isset($params['align'])) {
1016
            $align = $params['align'];
1017
        }
1018
1019
        if (!isset($tag) && (isset($class) || isset($align))) {
1020
            $tag = 'div';
1021
        }
1022
1023
        if (isset($tag)) {
1024
            $alignattr = isset($align) ? " style=\"text-align: {$align}\"" : '';
1025
            $classattr = isset($class) ? " class=\"{$class}\"" : '';
1026
            $out       = "<{$tag}{$alignattr}{$classattr}>{$out}</{$tag}>";
1027
        }
1028
1029
        // Add line numbers if 'lineno' param is true
1030
        if (isset($params['lineno']) && $params['lineno'] === true) {
1031
            $lines = explode("\n", $str);
1032
            $num   = count($lines);
1033
            if ($num > 0) {
1034
                $temp = "<table>\n<tr><td class=\"{$class}\" style=\"vertical-align: top; padding-right: 10px;\"><pre class=\"{$class}\">";
1035
                for ($i = 1; $i <= $num; ++$i) {
1036
                    $temp .= $i."\n";
1037
                }
1038
                $temp .= "</pre></td><td class=\"{$class}\" style=\"vertical-align: top;\">{$out}</td></tr></table>\n";
1039
                $out = $temp;
1040
            }
1041
            unset($lines);
1042
        }
1043
1044
        return $out;
1045
    }
1046
1047
    /**
1048
     * A function to recursively strip slashes.  Used to
1049
     * enforce magic_quotes_gpc being off.
1050
     *
1051
     * @param mixed $var The variable to strip (passed by reference)
1052
     */
1053
    public function stripVar(&$var)
1054
    {
1055
        if (is_array($var)) {
1056
            foreach ($var as $k => $v) {
1057
                $this->stripVar($var[$k]);
1058
1059
                /* magic_quotes_gpc escape keys as well ...*/
1060
                if (is_string($k)) {
1061
                    $ek = stripslashes($k);
1062
                    if ($ek !== $k) {
1063
                        $var[$ek] = $var[$k];
1064
                        unset($var[$k]);
1065
                    }
1066
                }
1067
            }
1068
        } else {
1069
            $var = stripslashes($var);
1070
        }
1071
    }
1072
1073
    /**
1074
     * Retrieve the tab info for a specific tab bar.
1075
     *
1076
     * @param string $section the name of the tab bar
1077
     *
1078
     * @return array array of tabs
1079
     */
1080
    public function getNavTabs($section)
1081
    {
1082
        $data           = $this->getDatabaseAccessor();
1083
        $lang           = $this->lang;
1084
        $plugin_manager = $this->plugin_manager;
1085
1086
        $hide_advanced = ($this->conf['show_advanced'] === false);
1087
        $tabs          = [];
1088
1089
        switch ($section) {
1090
            case 'root':
1091
                $tabs = [
1092
                    'intro'   => [
1093
                        'title' => $lang['strintroduction'],
1094
                        'url'   => 'intro',
1095
                        'icon'  => 'Introduction',
1096
                    ],
1097
                    'servers' => [
1098
                        'title' => $lang['strservers'],
1099
                        'url'   => 'servers',
1100
                        'icon'  => 'Servers',
1101
                    ],
1102
                ];
1103
1104
                break;
1105
            case 'server':
1106
                $hide_users = true;
1107
                if ($data) {
1108
                    $hide_users = !$data->isSuperUser();
1109
                }
1110
1111
                $tabs = [
1112
                    'databases' => [
1113
                        'title'   => $lang['strdatabases'],
1114
                        'url'     => 'alldb',
1115
                        'urlvars' => ['subject' => 'server'],
1116
                        'help'    => 'pg.database',
1117
                        'icon'    => 'Databases',
1118
                    ],
1119
                ];
1120
                if ($data && $data->hasRoles()) {
1121
                    $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...
1122
                        'roles' => [
1123
                            'title'   => $lang['strroles'],
1124
                            'url'     => 'roles',
1125
                            'urlvars' => ['subject' => 'server'],
1126
                            'hide'    => $hide_users,
1127
                            'help'    => 'pg.role',
1128
                            'icon'    => 'Roles',
1129
                        ],
1130
                    ]);
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...
1131
                } else {
1132
                    $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...
1133
                        'users'  => [
1134
                            'title'   => $lang['strusers'],
1135
                            'url'     => 'users',
1136
                            'urlvars' => ['subject' => 'server'],
1137
                            'hide'    => $hide_users,
1138
                            'help'    => 'pg.user',
1139
                            'icon'    => 'Users',
1140
                        ],
1141
                        'groups' => [
1142
                            'title'   => $lang['strgroups'],
1143
                            'url'     => 'groups',
1144
                            'urlvars' => ['subject' => 'server'],
1145
                            'hide'    => $hide_users,
1146
                            'help'    => 'pg.group',
1147
                            'icon'    => 'UserGroups',
1148
                        ],
1149
                    ]);
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...
1150
                }
1151
1152
                $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...
1153
                    'account'     => [
1154
                        'title'   => $lang['straccount'],
1155
                        'url'     => ($data && $data->hasRoles()) ? 'roles' : 'users',
1156
                        'urlvars' => ['subject' => 'server', 'action' => 'account'],
1157
                        'hide'    => !$hide_users,
1158
                        'help'    => 'pg.role',
1159
                        'icon'    => 'User',
1160
                    ],
1161
                    'tablespaces' => [
1162
                        'title'   => $lang['strtablespaces'],
1163
                        'url'     => 'tablespaces',
1164
                        'urlvars' => ['subject' => 'server'],
1165
                        'hide'    => !$data || !$data->hasTablespaces(),
1166
                        'help'    => 'pg.tablespace',
1167
                        'icon'    => 'Tablespaces',
1168
                    ],
1169
                    'export'      => [
1170
                        'title'   => $lang['strexport'],
1171
                        'url'     => 'alldb',
1172
                        'urlvars' => ['subject' => 'server', 'action' => 'export'],
1173
                        'hide'    => !$this->isDumpEnabled(),
1174
                        'icon'    => 'Export',
1175
                    ],
1176
                ]);
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...
1177
1178
                break;
1179
            case 'database':
1180
                $tabs = [
1181
                    'schemas'    => [
1182
                        'title'   => $lang['strschemas'],
1183
                        'url'     => 'schemas',
1184
                        'urlvars' => ['subject' => 'database'],
1185
                        'help'    => 'pg.schema',
1186
                        'icon'    => 'Schemas',
1187
                    ],
1188
                    'sql'        => [
1189
                        'title'   => $lang['strsql'],
1190
                        'url'     => 'database',
1191
                        'urlvars' => ['subject' => 'database', 'action' => 'sql', 'new' => 1],
1192
                        'help'    => 'pg.sql',
1193
                        'tree'    => false,
1194
                        'icon'    => 'SqlEditor',
1195
                    ],
1196
                    'find'       => [
1197
                        'title'   => $lang['strfind'],
1198
                        'url'     => 'database',
1199
                        'urlvars' => ['subject' => 'database', 'action' => 'find'],
1200
                        'tree'    => false,
1201
                        'icon'    => 'Search',
1202
                    ],
1203
                    'variables'  => [
1204
                        'title'   => $lang['strvariables'],
1205
                        'url'     => 'database',
1206
                        'urlvars' => ['subject' => 'database', 'action' => 'variables'],
1207
                        'help'    => 'pg.variable',
1208
                        'tree'    => false,
1209
                        'icon'    => 'Variables',
1210
                    ],
1211
                    'processes'  => [
1212
                        'title'   => $lang['strprocesses'],
1213
                        'url'     => 'database',
1214
                        'urlvars' => ['subject' => 'database', 'action' => 'processes'],
1215
                        'help'    => 'pg.process',
1216
                        'tree'    => false,
1217
                        'icon'    => 'Processes',
1218
                    ],
1219
                    'locks'      => [
1220
                        'title'   => $lang['strlocks'],
1221
                        'url'     => 'database',
1222
                        'urlvars' => ['subject' => 'database', 'action' => 'locks'],
1223
                        'help'    => 'pg.locks',
1224
                        'tree'    => false,
1225
                        'icon'    => 'Key',
1226
                    ],
1227
                    'admin'      => [
1228
                        'title'   => $lang['stradmin'],
1229
                        'url'     => 'database',
1230
                        'urlvars' => ['subject' => 'database', 'action' => 'admin'],
1231
                        'tree'    => false,
1232
                        'icon'    => 'Admin',
1233
                    ],
1234
                    'privileges' => [
1235
                        'title'   => $lang['strprivileges'],
1236
                        'url'     => 'privileges',
1237
                        'urlvars' => ['subject' => 'database'],
1238
                        'hide'    => !isset($data->privlist['database']),
1239
                        'help'    => 'pg.privilege',
1240
                        'tree'    => false,
1241
                        'icon'    => 'Privileges',
1242
                    ],
1243
                    'languages'  => [
1244
                        'title'   => $lang['strlanguages'],
1245
                        'url'     => 'languages',
1246
                        'urlvars' => ['subject' => 'database'],
1247
                        'hide'    => $hide_advanced,
1248
                        'help'    => 'pg.language',
1249
                        'icon'    => 'Languages',
1250
                    ],
1251
                    'casts'      => [
1252
                        'title'   => $lang['strcasts'],
1253
                        'url'     => 'casts',
1254
                        'urlvars' => ['subject' => 'database'],
1255
                        'hide'    => $hide_advanced,
1256
                        'help'    => 'pg.cast',
1257
                        'icon'    => 'Casts',
1258
                    ],
1259
                    'export'     => [
1260
                        'title'   => $lang['strexport'],
1261
                        'url'     => 'database',
1262
                        'urlvars' => ['subject' => 'database', 'action' => 'export'],
1263
                        'hide'    => !$this->isDumpEnabled(),
1264
                        'tree'    => false,
1265
                        'icon'    => 'Export',
1266
                    ],
1267
                ];
1268
1269
                break;
1270
            case 'schema':
1271
                $tabs = [
1272
                    'tables'      => [
1273
                        'title'   => $lang['strtables'],
1274
                        'url'     => 'tables',
1275
                        'urlvars' => ['subject' => 'schema'],
1276
                        'help'    => 'pg.table',
1277
                        'icon'    => 'Tables',
1278
                    ],
1279
                    'views'       => [
1280
                        'title'   => $lang['strviews'],
1281
                        'url'     => 'views',
1282
                        'urlvars' => ['subject' => 'schema'],
1283
                        'help'    => 'pg.view',
1284
                        'icon'    => 'Views',
1285
                    ],
1286
                    'matviews'    => [
1287
                        'title'   => 'M '.$lang['strviews'],
1288
                        'url'     => 'materializedviews',
1289
                        'urlvars' => ['subject' => 'schema'],
1290
                        'help'    => 'pg.matview',
1291
                        'icon'    => 'MViews',
1292
                    ],
1293
                    'sequences'   => [
1294
                        'title'   => $lang['strsequences'],
1295
                        'url'     => 'sequences',
1296
                        'urlvars' => ['subject' => 'schema'],
1297
                        'help'    => 'pg.sequence',
1298
                        'icon'    => 'Sequences',
1299
                    ],
1300
                    'functions'   => [
1301
                        'title'   => $lang['strfunctions'],
1302
                        'url'     => 'functions',
1303
                        'urlvars' => ['subject' => 'schema'],
1304
                        'help'    => 'pg.function',
1305
                        'icon'    => 'Functions',
1306
                    ],
1307
                    'fulltext'    => [
1308
                        'title'   => $lang['strfulltext'],
1309
                        'url'     => 'fulltext',
1310
                        'urlvars' => ['subject' => 'schema'],
1311
                        'help'    => 'pg.fts',
1312
                        'tree'    => true,
1313
                        'icon'    => 'Fts',
1314
                    ],
1315
                    'domains'     => [
1316
                        'title'   => $lang['strdomains'],
1317
                        'url'     => 'domains',
1318
                        'urlvars' => ['subject' => 'schema'],
1319
                        'help'    => 'pg.domain',
1320
                        'icon'    => 'Domains',
1321
                    ],
1322
                    'aggregates'  => [
1323
                        'title'   => $lang['straggregates'],
1324
                        'url'     => 'aggregates',
1325
                        'urlvars' => ['subject' => 'schema'],
1326
                        'hide'    => $hide_advanced,
1327
                        'help'    => 'pg.aggregate',
1328
                        'icon'    => 'Aggregates',
1329
                    ],
1330
                    'types'       => [
1331
                        'title'   => $lang['strtypes'],
1332
                        'url'     => 'types',
1333
                        'urlvars' => ['subject' => 'schema'],
1334
                        'hide'    => $hide_advanced,
1335
                        'help'    => 'pg.type',
1336
                        'icon'    => 'Types',
1337
                    ],
1338
                    'operators'   => [
1339
                        'title'   => $lang['stroperators'],
1340
                        'url'     => 'operators',
1341
                        'urlvars' => ['subject' => 'schema'],
1342
                        'hide'    => $hide_advanced,
1343
                        'help'    => 'pg.operator',
1344
                        'icon'    => 'Operators',
1345
                    ],
1346
                    'opclasses'   => [
1347
                        'title'   => $lang['stropclasses'],
1348
                        'url'     => 'opclasses',
1349
                        'urlvars' => ['subject' => 'schema'],
1350
                        'hide'    => $hide_advanced,
1351
                        'help'    => 'pg.opclass',
1352
                        'icon'    => 'OperatorClasses',
1353
                    ],
1354
                    'conversions' => [
1355
                        'title'   => $lang['strconversions'],
1356
                        'url'     => 'conversions',
1357
                        'urlvars' => ['subject' => 'schema'],
1358
                        'hide'    => $hide_advanced,
1359
                        'help'    => 'pg.conversion',
1360
                        'icon'    => 'Conversions',
1361
                    ],
1362
                    'privileges'  => [
1363
                        'title'   => $lang['strprivileges'],
1364
                        'url'     => 'privileges',
1365
                        'urlvars' => ['subject' => 'schema'],
1366
                        'help'    => 'pg.privilege',
1367
                        'tree'    => false,
1368
                        'icon'    => 'Privileges',
1369
                    ],
1370
                    'export'      => [
1371
                        'title'   => $lang['strexport'],
1372
                        'url'     => 'schemas',
1373
                        'urlvars' => ['subject' => 'schema', 'action' => 'export'],
1374
                        'hide'    => !$this->isDumpEnabled(),
1375
                        'tree'    => false,
1376
                        'icon'    => 'Export',
1377
                    ],
1378
                ];
1379
                if (!$data->hasFTS()) {
1380
                    unset($tabs['fulltext']);
1381
                }
1382
1383
                break;
1384
            case 'table':
1385
                $tabs = [
1386
                    'columns'     => [
1387
                        'title'   => $lang['strcolumns'],
1388
                        'url'     => 'tblproperties',
1389
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1390
                        'icon'    => 'Columns',
1391
                        'branch'  => true,
1392
                    ],
1393
                    'browse'      => [
1394
                        'title'   => $lang['strbrowse'],
1395
                        'icon'    => 'Columns',
1396
                        'url'     => 'display',
1397
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1398
                        'return'  => 'table',
1399
                        'branch'  => true,
1400
                    ],
1401
                    'select'      => [
1402
                        'title'   => $lang['strselect'],
1403
                        'icon'    => 'Search',
1404
                        'url'     => 'tables',
1405
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table'), 'action' => 'confselectrows'],
1406
                        'help'    => 'pg.sql.select',
1407
                    ],
1408
                    'insert'      => [
1409
                        'title'   => $lang['strinsert'],
1410
                        'url'     => 'tables',
1411
                        'urlvars' => [
1412
                            'action' => 'confinsertrow',
1413
                            'table'  => Decorator::field('table'),
1414
                        ],
1415
                        'help'    => 'pg.sql.insert',
1416
                        'icon'    => 'Operator',
1417
                    ],
1418
                    'indexes'     => [
1419
                        'title'   => $lang['strindexes'],
1420
                        'url'     => 'indexes',
1421
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1422
                        'help'    => 'pg.index',
1423
                        'icon'    => 'Indexes',
1424
                        'branch'  => true,
1425
                    ],
1426
                    'constraints' => [
1427
                        'title'   => $lang['strconstraints'],
1428
                        'url'     => 'constraints',
1429
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1430
                        'help'    => 'pg.constraint',
1431
                        'icon'    => 'Constraints',
1432
                        'branch'  => true,
1433
                    ],
1434
                    'triggers'    => [
1435
                        'title'   => $lang['strtriggers'],
1436
                        'url'     => 'triggers',
1437
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1438
                        'help'    => 'pg.trigger',
1439
                        'icon'    => 'Triggers',
1440
                        'branch'  => true,
1441
                    ],
1442
                    'rules'       => [
1443
                        'title'   => $lang['strrules'],
1444
                        'url'     => 'rules',
1445
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1446
                        'help'    => 'pg.rule',
1447
                        'icon'    => 'Rules',
1448
                        'branch'  => true,
1449
                    ],
1450
                    'admin'       => [
1451
                        'title'   => $lang['stradmin'],
1452
                        'url'     => 'tables',
1453
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table'), 'action' => 'admin'],
1454
                        'icon'    => 'Admin',
1455
                    ],
1456
                    'info'        => [
1457
                        'title'   => $lang['strinfo'],
1458
                        'url'     => 'info',
1459
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1460
                        'icon'    => 'Statistics',
1461
                    ],
1462
                    'privileges'  => [
1463
                        'title'   => $lang['strprivileges'],
1464
                        'url'     => 'privileges',
1465
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1466
                        'help'    => 'pg.privilege',
1467
                        'icon'    => 'Privileges',
1468
                    ],
1469
                    'import'      => [
1470
                        'title'   => $lang['strimport'],
1471
                        'url'     => 'tblproperties',
1472
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table'), 'action' => 'import'],
1473
                        'icon'    => 'Import',
1474
                        'hide'    => false,
1475
                    ],
1476
                    'export'      => [
1477
                        'title'   => $lang['strexport'],
1478
                        'url'     => 'tblproperties',
1479
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table'), 'action' => 'export'],
1480
                        'icon'    => 'Export',
1481
                        'hide'    => false,
1482
                    ],
1483
                ];
1484
1485
                break;
1486
            case 'view':
1487
                $tabs = [
1488
                    'columns'    => [
1489
                        'title'   => $lang['strcolumns'],
1490
                        'url'     => 'viewproperties',
1491
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view')],
1492
                        'icon'    => 'Columns',
1493
                        'branch'  => true,
1494
                    ],
1495
                    'browse'     => [
1496
                        'title'   => $lang['strbrowse'],
1497
                        'icon'    => 'Columns',
1498
                        'url'     => 'display',
1499
                        'urlvars' => [
1500
                            'action'  => 'confselectrows',
1501
                            'return'  => 'schema',
1502
                            'subject' => 'view',
1503
                            'view'    => Decorator::field('view'),
1504
                        ],
1505
                        'branch'  => true,
1506
                    ],
1507
                    'select'     => [
1508
                        'title'   => $lang['strselect'],
1509
                        'icon'    => 'Search',
1510
                        'url'     => 'views',
1511
                        'urlvars' => ['action' => 'confselectrows', 'view' => Decorator::field('view')],
1512
                        'help'    => 'pg.sql.select',
1513
                    ],
1514
                    'definition' => [
1515
                        'title'   => $lang['strdefinition'],
1516
                        'url'     => 'viewproperties',
1517
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view'), 'action' => 'definition'],
1518
                        'icon'    => 'Definition',
1519
                    ],
1520
                    'rules'      => [
1521
                        'title'   => $lang['strrules'],
1522
                        'url'     => 'rules',
1523
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view')],
1524
                        'help'    => 'pg.rule',
1525
                        'icon'    => 'Rules',
1526
                        'branch'  => true,
1527
                    ],
1528
                    'privileges' => [
1529
                        'title'   => $lang['strprivileges'],
1530
                        'url'     => 'privileges',
1531
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view')],
1532
                        'help'    => 'pg.privilege',
1533
                        'icon'    => 'Privileges',
1534
                    ],
1535
                    'export'     => [
1536
                        'title'   => $lang['strexport'],
1537
                        'url'     => 'viewproperties',
1538
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view'), 'action' => 'export'],
1539
                        'icon'    => 'Export',
1540
                        'hide'    => false,
1541
                    ],
1542
                ];
1543
1544
                break;
1545
            case 'matview':
1546
                $tabs = [
1547
                    'columns'    => [
1548
                        'title'   => $lang['strcolumns'],
1549
                        'url'     => 'materializedviewproperties',
1550
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1551
                        'icon'    => 'Columns',
1552
                        'branch'  => true,
1553
                    ],
1554
                    'browse'     => [
1555
                        'title'   => $lang['strbrowse'],
1556
                        'icon'    => 'Columns',
1557
                        'url'     => 'display',
1558
                        'urlvars' => [
1559
                            'action'  => 'confselectrows',
1560
                            'return'  => 'schema',
1561
                            'subject' => 'matview',
1562
                            'matview' => Decorator::field('matview'),
1563
                        ],
1564
                        'branch'  => true,
1565
                    ],
1566
                    'select'     => [
1567
                        'title'   => $lang['strselect'],
1568
                        'icon'    => 'Search',
1569
                        'url'     => 'materializedviews',
1570
                        'urlvars' => ['action' => 'confselectrows', 'matview' => Decorator::field('matview')],
1571
                        'help'    => 'pg.sql.select',
1572
                    ],
1573
                    'definition' => [
1574
                        'title'   => $lang['strdefinition'],
1575
                        'url'     => 'materializedviewproperties',
1576
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview'), 'action' => 'definition'],
1577
                        'icon'    => 'Definition',
1578
                    ],
1579
                    'indexes'    => [
1580
                        'title'   => $lang['strindexes'],
1581
                        'url'     => 'indexes',
1582
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1583
                        'help'    => 'pg.index',
1584
                        'icon'    => 'Indexes',
1585
                        'branch'  => true,
1586
                    ],
1587
                    /*'constraints' => [
1588
                    'title' => $lang['strconstraints'],
1589
                    'url' => 'constraints',
1590
                    'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1591
                    'help' => 'pg.constraint',
1592
                    'icon' => 'Constraints',
1593
                    'branch' => true,
1594
                     */
1595
1596
                    'rules'      => [
1597
                        'title'   => $lang['strrules'],
1598
                        'url'     => 'rules',
1599
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1600
                        'help'    => 'pg.rule',
1601
                        'icon'    => 'Rules',
1602
                        'branch'  => true,
1603
                    ],
1604
                    'privileges' => [
1605
                        'title'   => $lang['strprivileges'],
1606
                        'url'     => 'privileges',
1607
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1608
                        'help'    => 'pg.privilege',
1609
                        'icon'    => 'Privileges',
1610
                    ],
1611
                    'export'     => [
1612
                        'title'   => $lang['strexport'],
1613
                        'url'     => 'materializedviewproperties',
1614
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview'), 'action' => 'export'],
1615
                        'icon'    => 'Export',
1616
                        'hide'    => false,
1617
                    ],
1618
                ];
1619
1620
                break;
1621
            case 'function':
1622
                $tabs = [
1623
                    'definition' => [
1624
                        'title'   => $lang['strdefinition'],
1625
                        'url'     => 'functions',
1626
                        'urlvars' => [
1627
                            'subject'      => 'function',
1628
                            'function'     => Decorator::field('function'),
1629
                            'function_oid' => Decorator::field('function_oid'),
1630
                            'action'       => 'properties',
1631
                        ],
1632
                        'icon'    => 'Definition',
1633
                    ],
1634
                    'privileges' => [
1635
                        'title'   => $lang['strprivileges'],
1636
                        'url'     => 'privileges',
1637
                        'urlvars' => [
1638
                            'subject'      => 'function',
1639
                            'function'     => Decorator::field('function'),
1640
                            'function_oid' => Decorator::field('function_oid'),
1641
                        ],
1642
                        'icon'    => 'Privileges',
1643
                    ],
1644
                ];
1645
1646
                break;
1647
            case 'aggregate':
1648
                $tabs = [
1649
                    'definition' => [
1650
                        'title'   => $lang['strdefinition'],
1651
                        'url'     => 'aggregates',
1652
                        'urlvars' => [
1653
                            'subject'  => 'aggregate',
1654
                            'aggrname' => Decorator::field('aggrname'),
1655
                            'aggrtype' => Decorator::field('aggrtype'),
1656
                            'action'   => 'properties',
1657
                        ],
1658
                        'icon'    => 'Definition',
1659
                    ],
1660
                ];
1661
1662
                break;
1663
            case 'role':
1664
                $tabs = [
1665
                    'definition' => [
1666
                        'title'   => $lang['strdefinition'],
1667
                        'url'     => 'roles',
1668
                        'urlvars' => [
1669
                            'subject'  => 'role',
1670
                            'rolename' => Decorator::field('rolename'),
1671
                            'action'   => 'properties',
1672
                        ],
1673
                        'icon'    => 'Definition',
1674
                    ],
1675
                ];
1676
1677
                break;
1678
            case 'popup':
1679
                $tabs = [
1680
                    'sql'  => [
1681
                        'title'   => $lang['strsql'],
1682
                        'url'     => '/src/views/sqledit',
1683
                        'urlvars' => ['action' => 'sql', 'subject' => 'schema'],
1684
                        'help'    => 'pg.sql',
1685
                        'icon'    => 'SqlEditor',
1686
                    ],
1687
                    'find' => [
1688
                        'title'   => $lang['strfind'],
1689
                        'url'     => '/src/views/sqledit',
1690
                        'urlvars' => ['action' => 'find', 'subject' => 'schema'],
1691
                        'icon'    => 'Search',
1692
                    ],
1693
                ];
1694
1695
                break;
1696
            case 'column':
1697
                $tabs = [
1698
                    'properties' => [
1699
                        'title'   => $lang['strcolprop'],
1700
                        'url'     => 'colproperties',
1701
                        'urlvars' => [
1702
                            'subject' => 'column',
1703
                            'table'   => Decorator::field('table'),
1704
                            'column'  => Decorator::field('column'),
1705
                        ],
1706
                        'icon'    => 'Column',
1707
                    ],
1708
                    'privileges' => [
1709
                        'title'   => $lang['strprivileges'],
1710
                        'url'     => 'privileges',
1711
                        'urlvars' => [
1712
                            'subject' => 'column',
1713
                            'table'   => Decorator::field('table'),
1714
                            'column'  => Decorator::field('column'),
1715
                        ],
1716
                        'help'    => 'pg.privilege',
1717
                        'icon'    => 'Privileges',
1718
                    ],
1719
                ];
1720
1721
                break;
1722
            case 'fulltext':
1723
                $tabs = [
1724
                    'ftsconfigs' => [
1725
                        'title'   => $lang['strftstabconfigs'],
1726
                        'url'     => 'fulltext',
1727
                        'urlvars' => ['subject' => 'schema'],
1728
                        'hide'    => !$data->hasFTS(),
1729
                        'help'    => 'pg.ftscfg',
1730
                        'tree'    => true,
1731
                        'icon'    => 'FtsCfg',
1732
                    ],
1733
                    'ftsdicts'   => [
1734
                        'title'   => $lang['strftstabdicts'],
1735
                        'url'     => 'fulltext',
1736
                        'urlvars' => ['subject' => 'schema', 'action' => 'viewdicts'],
1737
                        'hide'    => !$data->hasFTS(),
1738
                        'help'    => 'pg.ftsdict',
1739
                        'tree'    => true,
1740
                        'icon'    => 'FtsDict',
1741
                    ],
1742
                    'ftsparsers' => [
1743
                        'title'   => $lang['strftstabparsers'],
1744
                        'url'     => 'fulltext',
1745
                        'urlvars' => ['subject' => 'schema', 'action' => 'viewparsers'],
1746
                        'hide'    => !$data->hasFTS(),
1747
                        'help'    => 'pg.ftsparser',
1748
                        'tree'    => true,
1749
                        'icon'    => 'FtsParser',
1750
                    ],
1751
                ];
1752
1753
                break;
1754
        }
1755
1756
        // Tabs hook's place
1757
        $plugin_functions_parameters = [
1758
            'tabs'    => &$tabs,
1759
            'section' => $section,
1760
        ];
1761
        $plugin_manager->do_hook('tabs', $plugin_functions_parameters);
1762
1763
        return $tabs;
1764
    }
1765
1766
    /**
1767
     * Get the URL for the last active tab of a particular tab bar.
1768
     *
1769
     * @param string $section
1770
     *
1771
     * @return null|mixed
1772
     */
1773
    public function getLastTabURL($section)
1774
    {
1775
        //$data = $this->getDatabaseAccessor();
1776
1777
        $tabs = $this->getNavTabs($section);
1778
1779
        if (isset($_SESSION['webdbLastTab'][$section])) {
1780
            $tab = $tabs[$_SESSION['webdbLastTab'][$section]];
1781
        } else {
1782
            $tab = reset($tabs);
1783
        }
1784
        //$this->prtrace(['section' => $section, 'tabs' => $tabs, 'tab' => $tab]);
1785
        return isset($tab['url']) ? $tab : null;
1786
    }
1787
1788
    /**
1789
     * Do multi-page navigation.  Displays the prev, next and page options.
1790
     *
1791
     * @param int    $page      - the page currently viewed
1792
     * @param int    $pages     - the maximum number of pages
1793
     * @param string $gets      -  the parameters to include in the link to the wanted page
1794
     * @param int    $max_width - the number of pages to make available at any one time (default = 20)
1795
     */
1796
    public function printPages($page, $pages, $gets, $max_width = 20)
1797
    {
1798
        $lang = $this->lang;
1799
1800
        $window = 10;
1801
1802
        if ($page < 0 || $page > $pages) {
1803
            return;
1804
        }
1805
1806
        if ($pages < 0) {
1807
            return;
1808
        }
1809
1810
        if ($max_width <= 0) {
1811
            return;
1812
        }
1813
1814
        unset($gets['page']);
1815
        $url = http_build_query($gets);
1816
1817
        if ($pages > 1) {
1818
            echo "<p style=\"text-align: center\">\n";
1819
            if ($page != 1) {
1820
                echo "<a class=\"pagenav\" href=\"?{$url}&amp;page=1\">{$lang['strfirst']}</a>\n";
1821
                $temp = $page - 1;
1822
                echo "<a class=\"pagenav\" href=\"?{$url}&amp;page={$temp}\">{$lang['strprev']}</a>\n";
1823
            }
1824
1825
            if ($page <= $window) {
1826
                $min_page = 1;
1827
                $max_page = min(2 * $window, $pages);
1828
            } elseif ($page > $window && $pages >= $page + $window) {
1829
                $min_page = ($page - $window) + 1;
1830
                $max_page = $page + $window;
1831
            } else {
1832
                $min_page = ($page - (2 * $window - ($pages - $page))) + 1;
1833
                $max_page = $pages;
1834
            }
1835
1836
            // Make sure min_page is always at least 1
1837
            // and max_page is never greater than $pages
1838
            $min_page = max($min_page, 1);
1839
            $max_page = min($max_page, $pages);
1840
1841
            for ($i = $min_page; $i <= $max_page; ++$i) {
1842
                #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...
1843
                if ($i != $page) {
1844
                    echo "<a class=\"pagenav\" href=\"display?{$url}&amp;page={$i}\">${i}</a>\n";
1845
                } else {
1846
                    echo "${i}\n";
1847
                }
1848
            }
1849
            if ($page != $pages) {
1850
                $temp = $page + 1;
1851
                echo "<a class=\"pagenav\" href=\"display?{$url}&amp;page={$temp}\">{$lang['strnext']}</a>\n";
1852
                echo "<a class=\"pagenav\" href=\"display?{$url}&amp;page={$pages}\">{$lang['strlast']}</a>\n";
1853
            }
1854
            echo "</p>\n";
1855
        }
1856
    }
1857
1858
    /**
1859
     * Converts a PHP.INI size variable to bytes.  Taken from publically available
1860
     * function by Chris DeRose, here: http://www.php.net/manual/en/configuration.directives.php#ini.file-uploads.
1861
     *
1862
     * @param mixed $strIniSize The PHP.INI variable
1863
     *
1864
     * @return float|float|int size in bytes, false on failure
1865
     */
1866
    public function inisizeToBytes($strIniSize)
1867
    {
1868
        // This function will take the string value of an ini 'size' parameter,
1869
        // and return a double (64-bit float) representing the number of bytes
1870
        // that the parameter represents. Or false if $strIniSize is unparseable.
1871
        $a_IniParts = [];
1872
1873
        if (!is_string($strIniSize)) {
1874
            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...
1875
        }
1876
1877
        if (!preg_match('/^(\d+)([bkm]*)$/i', $strIniSize, $a_IniParts)) {
1878
            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...
1879
        }
1880
1881
        $nSize   = (float) $a_IniParts[1];
1882
        $strUnit = strtolower($a_IniParts[2]);
1883
1884
        switch ($strUnit) {
1885
            case 'm':
1886
                return $nSize * (float) 1048576;
1887
            case 'k':
1888
                return $nSize * (float) 1024;
1889
            case 'b':
1890
            default:
1891
                return $nSize;
1892
        }
1893
    }
1894
1895
    public function getRequestVars($subject = '')
1896
    {
1897
        $v = [];
1898
        if (!empty($subject)) {
1899
            $v['subject'] = $subject;
1900
        }
1901
1902
        if ($this->_server_id !== null && $subject != 'root') {
1903
            $v['server'] = $this->_server_id;
1904
            if ($this->_database !== null && $subject != 'server') {
1905
                $v['database'] = $this->_database;
1906
                if (isset($_REQUEST['schema']) && $subject != 'database') {
1907
                    $v['schema'] = $_REQUEST['schema'];
1908
                }
1909
            }
1910
        }
1911
        //$this->prtrace($v);
1912
        return $v;
1913
    }
1914
1915
    public function icon($icon)
1916
    {
1917
        if (is_string($icon)) {
1918
            $path = "/images/themes/{$this->conf['theme']}/{$icon}";
1919
            if (file_exists(\BASE_PATH.$path.'.png')) {
1920
                return SUBFOLDER.$path.'.png';
1921
            }
1922
1923
            if (file_exists(\BASE_PATH.$path.'.gif')) {
1924
                return SUBFOLDER.$path.'.gif';
1925
            }
1926
1927
            if (file_exists(\BASE_PATH.$path.'.ico')) {
1928
                return SUBFOLDER.$path.'.ico';
1929
            }
1930
1931
            $path = "/images/themes/default/{$icon}";
1932
            if (file_exists(\BASE_PATH.$path.'.png')) {
1933
                return SUBFOLDER.$path.'.png';
1934
            }
1935
1936
            if (file_exists(\BASE_PATH.$path.'.gif')) {
1937
                return SUBFOLDER.$path.'.gif';
1938
            }
1939
1940
            if (file_exists(\BASE_PATH.$path.'.ico')) {
1941
                return SUBFOLDER.$path.'.ico';
1942
            }
1943
        } else {
1944
            // Icon from plugins
1945
            $path = "/plugins/{$icon[0]}/images/{$icon[1]}";
1946
            if (file_exists(\BASE_PATH.$path.'.png')) {
1947
                return SUBFOLDER.$path.'.png';
1948
            }
1949
1950
            if (file_exists(\BASE_PATH.$path.'.gif')) {
1951
                return SUBFOLDER.$path.'.gif';
1952
            }
1953
1954
            if (file_exists(\BASE_PATH.$path.'.ico')) {
1955
                return SUBFOLDER.$path.'.ico';
1956
            }
1957
        }
1958
1959
        return '';
1960
    }
1961
1962
    /**
1963
     * Function to escape command line parameters.
1964
     *
1965
     * @param string $str The string to escape
1966
     *
1967
     * @return string The escaped string
1968
     */
1969
    public function escapeShellArg($str)
1970
    {
1971
        //$data = $this->getDatabaseAccessor();
1972
        $lang = $this->lang;
1973
1974
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1975
            // Due to annoying PHP bugs, shell arguments cannot be escaped
1976
            // (command simply fails), so we cannot allow complex objects
1977
            // to be dumped.
1978
            if (preg_match('/^[_.[:alnum:]]+$/', $str)) {
1979
                return $str;
1980
            }
1981
1982
            return $this->halt($lang['strcannotdumponwindows']);
1983
        }
1984
1985
        return escapeshellarg($str);
1986
    }
1987
1988
    /**
1989
     * Function to escape command line programs.
1990
     *
1991
     * @param string $str The string to escape
1992
     *
1993
     * @return string The escaped string
1994
     */
1995
    public function escapeShellCmd($str)
1996
    {
1997
        $data = $this->getDatabaseAccessor();
1998
1999
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
2000
            $data->fieldClean($str);
2001
2002
            return '"'.$str.'"';
2003
        }
2004
2005
        return escapeshellcmd($str);
2006
    }
2007
2008
    /**
2009
     * Save the given SQL script in the history
2010
     * of the database and server.
2011
     *
2012
     * @param string $script the SQL script to save
2013
     */
2014
    public function saveScriptHistory($script)
2015
    {
2016
        list($usec, $sec)                                                           = explode(' ', microtime());
2017
        $time                                                                       = ((float) $usec + (float) $sec);
2018
        $_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']]["${time}"] = [
2019
            'query'    => $script,
2020
            'paginate' => !isset($_REQUEST['paginate']) ? 'f' : 't',
2021
            'queryid'  => $time,
2022
        ];
2023
    }
2024
2025
    /**
2026
     * 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...
2027
     * or by constraint.
2028
     *
2029
     * @param string $table The table to retrieve FK contraints from
2030
     *
2031
     * @return array|bool the array of FK definition:
2032
     *                    array(
2033
     *                    'byconstr' => array(
2034
     *                    constrain id => array(
2035
     *                    confrelid => foreign relation oid
2036
     *                    f_schema => foreign schema name
2037
     *                    f_table => foreign table name
2038
     *                    pattnums => array of parent's fields nums
2039
     *                    pattnames => array of parent's fields names
2040
     *                    fattnames => array of foreign attributes names
2041
     *                    )
2042
     *                    ),
2043
     *                    'byfield' => array(
2044
     *                    attribute num => array (constraint id, ...)
2045
     *                    ),
2046
     *                    'code' => HTML/js code to include in the page for auto-completion
2047
     *                    )
2048
     */
2049
    public function getAutocompleteFKProperties($table)
2050
    {
2051
        $data = $this->getDatabaseAccessor();
2052
2053
        $fksprops = [
2054
            'byconstr' => [],
2055
            'byfield'  => [],
2056
            'code'     => '',
2057
        ];
2058
2059
        $constrs = $data->getConstraintsWithFields($table);
2060
2061
        if (!$constrs->EOF) {
2062
            //$conrelid = $constrs->fields['conrelid'];
2063
            while (!$constrs->EOF) {
2064
                if ($constrs->fields['contype'] == 'f') {
2065
                    if (!isset($fksprops['byconstr'][$constrs->fields['conid']])) {
2066
                        $fksprops['byconstr'][$constrs->fields['conid']] = [
2067
                            'confrelid' => $constrs->fields['confrelid'],
2068
                            'f_table'   => $constrs->fields['f_table'],
2069
                            'f_schema'  => $constrs->fields['f_schema'],
2070
                            'pattnums'  => [],
2071
                            'pattnames' => [],
2072
                            'fattnames' => [],
2073
                        ];
2074
                    }
2075
2076
                    $fksprops['byconstr'][$constrs->fields['conid']]['pattnums'][]  = $constrs->fields['p_attnum'];
2077
                    $fksprops['byconstr'][$constrs->fields['conid']]['pattnames'][] = $constrs->fields['p_field'];
2078
                    $fksprops['byconstr'][$constrs->fields['conid']]['fattnames'][] = $constrs->fields['f_field'];
2079
2080
                    if (!isset($fksprops['byfield'][$constrs->fields['p_attnum']])) {
2081
                        $fksprops['byfield'][$constrs->fields['p_attnum']] = [];
2082
                    }
2083
2084
                    $fksprops['byfield'][$constrs->fields['p_attnum']][] = $constrs->fields['conid'];
2085
                }
2086
                $constrs->moveNext();
2087
            }
2088
2089
            $fksprops['code'] = "<script type=\"text/javascript\">\n";
2090
            $fksprops['code'] .= "var constrs = {};\n";
2091
            foreach ($fksprops['byconstr'] as $conid => $props) {
2092
                $fksprops['code'] .= "constrs.constr_{$conid} = {\n";
2093
                $fksprops['code'] .= 'pattnums: ['.implode(',', $props['pattnums'])."],\n";
2094
                $fksprops['code'] .= "f_table:'".addslashes(htmlentities($props['f_table'], ENT_QUOTES, 'UTF-8'))."',\n";
2095
                $fksprops['code'] .= "f_schema:'".addslashes(htmlentities($props['f_schema'], ENT_QUOTES, 'UTF-8'))."',\n";
2096
                $_ = '';
2097
                foreach ($props['pattnames'] as $n) {
2098
                    $_ .= ",'".htmlentities($n, ENT_QUOTES, 'UTF-8')."'";
2099
                }
2100
                $fksprops['code'] .= 'pattnames: ['.substr($_, 1)."],\n";
2101
2102
                $_ = '';
2103
                foreach ($props['fattnames'] as $n) {
2104
                    $_ .= ",'".htmlentities($n, ENT_QUOTES, 'UTF-8')."'";
2105
                }
2106
2107
                $fksprops['code'] .= 'fattnames: ['.substr($_, 1)."]\n";
2108
                $fksprops['code'] .= "};\n";
2109
            }
2110
2111
            $fksprops['code'] .= "var attrs = {};\n";
2112
            foreach ($fksprops['byfield'] as $attnum => $cstrs) {
2113
                $fksprops['code'] .= "attrs.attr_{$attnum} = [".implode(',', $fksprops['byfield'][$attnum])."];\n";
2114
            }
2115
2116
            $fksprops['code'] .= "var table='".addslashes(htmlentities($table, ENT_QUOTES, 'UTF-8'))."';";
2117
            $fksprops['code'] .= "var server='".htmlentities($_REQUEST['server'], ENT_QUOTES, 'UTF-8')."';";
2118
            $fksprops['code'] .= "var database='".addslashes(htmlentities($_REQUEST['database'], ENT_QUOTES, 'UTF-8'))."';";
2119
            $fksprops['code'] .= "var subfolder='".SUBFOLDER."';";
2120
            $fksprops['code'] .= "</script>\n";
2121
2122
            $fksprops['code'] .= '<div id="fkbg"></div>';
2123
            $fksprops['code'] .= '<div id="fklist"></div>';
2124
            $fksprops['code'] .= '<script src="'.SUBFOLDER.'/js/ac_insert_row.js" type="text/javascript"></script>';
2125
        } else {
2126
            /* we have no foreign keys on this table */
2127
            return false;
2128
        }
2129
2130
        return $fksprops;
2131
    }
2132
}
2133