Test Failed
Push — master ( 34dd7c...325a03 )
by Felipe
11:17 queued 06:14
created

Misc::getDatabase()   C

Complexity

Conditions 8
Paths 5

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 5.7377
c 0
b 0
f 0
cc 8
eloc 14
nc 5
nop 1
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
 * @version $Id: Misc.php,v 1.171 2008/03/17 21:35:48 ioguix Exp $
0 ignored issues
show
Coding Style introduced by
Invalid version "$Id: Misc.php,v 1.171 2008/03/17 21:35:48 ioguix Exp $" in doc comment; consider "Release: <package_version>" instead
Loading history...
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
24
 *
25
 * @package PHPPgAdmin
26
 */
27
class Misc
28
{
29
    use \PHPPgAdmin\Traits\HelperTrait;
30
31
    private $_connection;
32
    private $_no_db_connection = false;
33
    private $_reload_browser   = false;
34
    private $_data;
35
    private $_database;
36
    private $_server_id;
37
    private $_server_info;
38
    private $_error_msg = '';
39
40
    public $appLangFiles    = [];
41
    public $appName         = '';
42
    public $appVersion      = '';
43
    public $form            = '';
44
    public $href            = '';
45
    public $controller_name = 'Misc';
46
    public $lang            = [];
47
48
    protected $container;
49
50
    /**
51
     * @param \Slim\Container $container The container
52
     */
53
    public function __construct(\Slim\Container $container)
54
    {
55
        $this->container = $container;
56
57
        $this->lang = $container->get('lang');
58
        $this->conf = $container->get('conf');
59
60
        //$this->view           = $container->get('view');
61
        $this->plugin_manager = $container->get('plugin_manager');
62
        $this->appLangFiles   = $container->get('appLangFiles');
63
64
        $this->appName          = $container->get('settings')['appName'];
65
        $this->appVersion       = $container->get('settings')['appVersion'];
66
        $this->postgresqlMinVer = $container->get('settings')['postgresqlMinVer'];
67
        $this->phpMinVer        = $container->get('settings')['phpMinVer'];
68
69
        $base_version = $container->get('settings')['base_version'];
70
71
        //$this->prtrace($base_version);
72
73
        // Check for config file version mismatch
74
        if (!isset($this->conf['version']) || $base_version > $this->conf['version']) {
75
            $container->get('utils')->addError($this->lang['strbadconfig']);
76
        }
77
78
        // Check database support is properly compiled in
79
        if (!function_exists('pg_connect')) {
80
            $container->get('utils')->addError($this->lang['strnotloaded']);
81
        }
82
83
        // Check the version of PHP
84
        if (version_compare(PHP_VERSION, $this->phpMinVer, '<')) {
85
            $container->get('utils')->addError(sprintf('Version of PHP not supported. Please upgrade to version %s or later.', $this->phpMinVer));
86
        }
87
        //$this->dumpAndDie($this);
88
89
        $this->getServerId();
90
    }
91
92
    public function serverToSha()
93
    {
94
        $request_server = $this->container->requestobj->getParam('server');
95
        if ($request_server === null) {
96
            return null;
97
        }
98
        $srv_array = explode(':', $request_server);
99
        if (count($srv_array) === 3) {
100
            return sha1($request_server);
101
        }
102
103
        return $request_server;
104
    }
105
106
    public function getServerId()
107
    {
108
        if ($this->_server_id) {
109
            return $this->_server_id;
110
        }
111
112
        $request_server = $this->serverToSha();
113
114
        if (count($this->conf['servers']) === 1) {
115
            $info             = $this->conf['servers'][0];
116
            $this->_server_id = sha1($info['host'].':'.$info['port'].':'.$info['sslmode']);
117
        } elseif ($request_server !== null) {
118
            $this->_server_id = $request_server;
119
        } elseif (isset($_SESSION['webdbLogin']) && count($_SESSION['webdbLogin']) > 0) {
120
            //$this->prtrace('webdbLogin', $_SESSION['webdbLogin']);
121
            $this->_server_id = array_keys($_SESSION['webdbLogin'])[0];
122
        }
123
124
        return $this->_server_id;
125
    }
126
127
    /**
128
     * Sets the view instance property of this class.
129
     *
130
     * @param \Slim\Views\Twig $view view instance
131
     *
132
     * @return \PHPPgAdmin\Misc this class instance
133
     */
134
    public function setView(\Slim\Views\Twig $view)
135
    {
136
        $this->view = $view;
137
138
        return $this;
139
    }
140
141
    /**
142
     * Adds or modifies a key in the $conf instance property of this class.
143
     *
144
     * @param string $key   name of the key to set
145
     * @param mixed  $value value of the key to set
146
     *
147
     * @return \PHPPgAdmin\Misc this class instance
148
     */
149
    public function setConf($key, $value)
150
    {
151
        $this->conf[$key] = $value;
152
153
        return $this;
154
    }
155
156
    /**
157
     * gets the value of a config property, or the array of all config properties.
1 ignored issue
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
158
     *
159
     * @param null|string $key value of the key to be retrieved. If null, the full array is returnes
160
     *
161
     * @return null|array|string the whole $conf array, the value of $conf[key] or null if said key does not exist
162
     */
163
    public function getConf($key = null)
164
    {
165
        if ($key === null) {
166
            return $this->conf;
167
        }
168
        if (array_key_exists($key, $this->conf)) {
169
            return $this->conf[$key];
170
        }
171
172
        return null;
173
    }
174
175
    /**
176
     * Displays link to the context help.
177
     *
178
     * @param string $str      the string that the context help is related to (already escaped)
179
     * @param string $help     help section identifier
180
     * @param bool   $do_print true to echo, false to return
181
     */
182
    public function printHelp($str, $help = null, $do_print = true)
183
    {
184
        //\PC::debug(['str' => $str, 'help' => $help], 'printHelp');
185
        if ($help !== null) {
186
            $helplink = $this->getHelpLink($help);
187
            $str .= '<a class="help" href="'.$helplink.'" title="'.$this->lang['strhelp'].'" target="phppgadminhelp">';
188
            $str .= $this->lang['strhelpicon'].'</a>';
189
        }
190
        if ($do_print) {
191
            echo $str;
192
        } else {
193
            return $str;
194
        }
195
    }
196
197
    /**
198
     * Gets the help link.
199
     *
200
     * @param string $help The help subject
201
     *
202
     * @return string the help link
203
     */
204
    public function getHelpLink($help)
205
    {
206
        return htmlspecialchars(SUBFOLDER.'/help?help='.urlencode($help).'&server='.urlencode($this->getServerId()));
207
    }
208
209
    /**
210
     * Internally sets the reload browser property.
211
     *
212
     * @param bool $flag sets internal $_reload_browser var which will be passed to the footer methods
213
     *
214
     * @return \PHPPgAdmin\Misc this class instance
215
     */
216
    public function setReloadBrowser($flag)
217
    {
218
        $this->_reload_browser = (bool) $flag;
219
220
        return $this;
221
    }
222
223
    public function getReloadBrowser()
224
    {
225
        return $this->_reload_browser;
226
    }
227
228
    public function getContainer()
229
    {
230
        return $this->container;
231
    }
232
233
    /**
234
     * sets $_no_db_connection boolean value, allows to render scripts that do not need an active session.
1 ignored issue
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
235
     *
236
     * @param bool $flag true or false to allow unconnected clients to access the view
237
     *
238
     * @return \PHPPgAdmin\Misc this class instance
239
     */
240
    public function setNoDBConnection($flag)
241
    {
242
        $this->_no_db_connection = (bool) $flag;
243
244
        return $this;
245
    }
246
247
    /**
248
     * Gets member variable $_no_db_connection.
249
     *
250
     * @return bool value of member variable $_no_db_connection
251
     */
252
    public function getNoDBConnection()
253
    {
254
        return $this->_no_db_connection;
255
    }
256
257
    /**
258
     * Sets the last error message to display afterwards instead of just dying with the error msg.
259
     *
260
     * @param string $msg error message string
261
     *
262
     * @return \PHPPgAdmin\Misc this class instance
263
     */
264
    public function setErrorMsg($msg)
265
    {
266
        $this->_error_msg = $msg;
267
268
        return $this;
269
    }
270
271
    /**
272
     * Returns the error messages stored in member variable $_error_msg.
273
     *
274
     * @return string the error message
275
     */
276
    public function getErrorMsg()
277
    {
278
        return $this->_error_msg;
279
    }
280
281
    /**
282
     * Creates a database accessor.
283
     *
284
     * @param string $database  the name of the database
285
     * @param mixed  $server_id the id of the server
286
     *
287
     * @internal mixed $plaform placeholder that will receive the value of the platform
288
     */
289
    public function getDatabaseAccessor($database = '', $server_id = null)
290
    {
291
        $lang = $this->lang;
292
293
        if ($server_id !== null) {
294
            $this->_server_id = $server_id;
295
        }
296
        //$this->prtrace($this->_server_id);
297
298
        $server_info = $this->getServerInfo($this->_server_id);
299
300
        if ($this->_no_db_connection || !isset($server_info['username'])) {
301
            return null;
302
        }
303
304
        if ($this->_data === null) {
305
            try {
306
                $_connection = $this->getConnection($database, $this->_server_id);
307
            } catch (\Exception $e) {
308
                $this->setServerInfo(null, null, $this->_server_id);
309
                $this->setNoDBConnection(true);
310
                $this->setErrorMsg($e->getMessage());
311
312
                return null;
313
            }
314
315
            //$this->prtrace('_connection', $_connection);
316
            if (!$_connection) {
317
                $this->container->utils->addError($lang['strloginfailed']);
318
                $this->setErrorMsg($lang['strloginfailed']);
319
320
                return null;
321
            }
322
            // Get the name of the database driver we need to use.
323
            // The description of the server is returned in $platform.
324
            $_type = $_connection->getDriver($platform);
1 ignored issue
show
Comprehensibility Best Practice introduced by
The variable $platform seems to be never defined.
Loading history...
325
326
            //$this->prtrace(['type' => $_type, 'platform' => $platform, 'pgVersion' => $_connection->conn->pgVersion]);
327
328
            if ($_type === null) {
329
                $errormsg = sprintf($lang['strpostgresqlversionnotsupported'], $this->postgresqlMinVer);
330
                $this->container->utils->addError($errormsg);
331
                $this->setErrorMsg($errormsg);
332
333
                return null;
334
            }
335
            $_type = '\PHPPgAdmin\Database\\'.$_type;
336
337
            $this->setServerInfo('platform', $platform, $this->_server_id);
338
            $this->setServerInfo('pgVersion', $_connection->conn->pgVersion, $this->_server_id);
339
340
            // Create a database wrapper class for easy manipulation of the
341
            // connection.
342
343
            $this->_data           = new $_type($_connection->conn, $this->container, $server_info);
344
            $this->_data->platform = $_connection->platform;
345
346
            //$this->_data->getHelpPages();
347
348
            //$this->prtrace('help_page has ' . count($this->_data->help_page) . ' items');
349
350
            /* we work on UTF-8 only encoding */
351
            $this->_data->execute("SET client_encoding TO 'UTF-8'");
352
353
            if ($this->_data->hasByteaHexDefault()) {
354
                $this->_data->execute('SET bytea_output TO escape');
355
            }
356
        }
357
358
        if ($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
        ) {
533
            $this->_database = $server_info['defaultdb'];
534
        } elseif ($database !== '') {
535
            $this->_database = $database;
536
        } elseif (isset($_REQUEST['database'])) {
537
            // Connect to the current database
538
            $this->_database = $_REQUEST['database'];
539
        } else {
540
            // or if one is not specified then connect to the default database.
541
            $this->_database = $server_info['defaultdb'];
542
        }
543
544
        return $this->_database;
545
    }
546
547
    /**
548
     * Set the current schema.
549
     *
550
     * @param string $schema The schema name
551
     *
552
     * @return int 0 on success
553
     */
554
    public function setCurrentSchema($schema)
555
    {
556
        $data = $this->getDatabaseAccessor();
557
558
        $status = $data->setSchema($schema);
559
        if ($status != 0) {
560
            return $status;
561
        }
562
563
        $_REQUEST['schema'] = $schema;
564
        $this->container->offsetSet('schema', $schema);
565
        $this->setHREF();
566
567
        return 0;
568
    }
569
570
    /**
571
     * Checks if dumps are properly set up.
572
     *
573
     * @param bool $all (optional) True to check pg_dumpall, false to just check pg_dump
574
     *
575
     * @return bool True, dumps are set up, false otherwise
576
     */
577
    public function isDumpEnabled($all = false)
578
    {
579
        $info = $this->getServerInfo();
580
581
        return !empty($info[$all ? 'pg_dumpall_path' : 'pg_dump_path']);
582
    }
583
584
    /**
585
     * Sets the href tracking variable.
586
     *
587
     * @return \PHPPgAdmin\Misc this class instance
588
     */
589
    public function setHREF()
590
    {
591
        $this->href = $this->getHREF();
592
        //\PC::debug($this->href, 'Misc::href');
593
        return $this;
594
    }
595
596
    /**
597
     * Get a href query string, excluding objects below the given object type (inclusive).
598
     *
599
     * @param null|string $exclude_from
600
     *
601
     * @return string
602
     */
603
    public function getHREF($exclude_from = null)
604
    {
605
        $href = [];
606
607
        $server   = $this->container->server || isset($_REQUEST['server']) ? $_REQUEST['server'] : null;
608
        $database = $this->container->database || isset($_REQUEST['database']) ? $_REQUEST['database'] : null;
609
        $schema   = $this->container->schema || isset($_REQUEST['schema']) ? $_REQUEST['schema'] : null;
610
611
        if ($server && $exclude_from !== 'server') {
612
            $href[] = 'server='.urlencode($server);
613
        }
614
        if ($database && $exclude_from !== 'database') {
615
            $href[] = 'database='.urlencode($database);
616
        }
617
        if ($schema && $exclude_from !== 'schema') {
618
            $href[] = 'schema='.urlencode($schema);
619
        }
620
621
        $this->href = htmlentities(implode('&', $href));
622
623
        return $this->href;
624
    }
625
626
    public function getSubjectParams($subject)
627
    {
628
        $plugin_manager = $this->plugin_manager;
629
630
        $vars = [];
631
632
        switch ($subject) {
633
            case 'root':
634
                $vars = [
635
                    'params' => [
636
                        'subject' => 'root',
637
                    ],
638
                ];
639
640
                break;
641
            case 'server':
642
                $vars = ['params' => [
643
                    'server'  => $_REQUEST['server'],
644
                    'subject' => 'server',
645
                ]];
646
647
                break;
648
            case 'role':
649
                $vars = ['params' => [
650
                    'server'   => $_REQUEST['server'],
651
                    'subject'  => 'role',
652
                    'action'   => 'properties',
653
                    'rolename' => $_REQUEST['rolename'],
654
                ]];
655
656
                break;
657
            case 'database':
658
                $vars = ['params' => [
659
                    'server'   => $_REQUEST['server'],
660
                    'subject'  => 'database',
661
                    'database' => $_REQUEST['database'],
662
                ]];
663
664
                break;
665
            case 'schema':
666
                $vars = ['params' => [
667
                    'server'   => $_REQUEST['server'],
668
                    'subject'  => 'schema',
669
                    'database' => $_REQUEST['database'],
670
                    'schema'   => $_REQUEST['schema'],
671
                ]];
672
673
                break;
674
            case 'table':
675
                $vars = ['params' => [
676
                    'server'   => $_REQUEST['server'],
677
                    'subject'  => 'table',
678
                    'database' => $_REQUEST['database'],
679
                    'schema'   => $_REQUEST['schema'],
680
                    'table'    => $_REQUEST['table'],
681
                ]];
682
683
                break;
684
            case 'selectrows':
685
                $vars = [
686
                    'url'    => 'tables',
687
                    'params' => [
688
                        'server'   => $_REQUEST['server'],
689
                        'subject'  => 'table',
690
                        'database' => $_REQUEST['database'],
691
                        'schema'   => $_REQUEST['schema'],
692
                        'table'    => $_REQUEST['table'],
693
                        'action'   => 'confselectrows',
694
                    ], ];
695
696
                break;
697
            case 'view':
698
                $vars = ['params' => [
699
                    'server'   => $_REQUEST['server'],
700
                    'subject'  => 'view',
701
                    'database' => $_REQUEST['database'],
702
                    'schema'   => $_REQUEST['schema'],
703
                    'view'     => $_REQUEST['view'],
704
                ]];
705
706
                break;
707
            case 'matview':
708
                $vars = ['params' => [
709
                    'server'   => $_REQUEST['server'],
710
                    'subject'  => 'matview',
711
                    'database' => $_REQUEST['database'],
712
                    'schema'   => $_REQUEST['schema'],
713
                    'matview'  => $_REQUEST['matview'],
714
                ]];
715
716
                break;
717
            case 'fulltext':
718
            case 'ftscfg':
719
                $vars = ['params' => [
720
                    'server'   => $_REQUEST['server'],
721
                    'subject'  => 'fulltext',
722
                    'database' => $_REQUEST['database'],
723
                    'schema'   => $_REQUEST['schema'],
724
                    'action'   => 'viewconfig',
725
                    'ftscfg'   => $_REQUEST['ftscfg'],
726
                ]];
727
728
                break;
729
            case 'function':
730
                $vars = ['params' => [
731
                    'server'       => $_REQUEST['server'],
732
                    'subject'      => 'function',
733
                    'database'     => $_REQUEST['database'],
734
                    'schema'       => $_REQUEST['schema'],
735
                    'function'     => $_REQUEST['function'],
736
                    'function_oid' => $_REQUEST['function_oid'],
737
                ]];
738
739
                break;
740
            case 'aggregate':
741
                $vars = ['params' => [
742
                    'server'   => $_REQUEST['server'],
743
                    'subject'  => 'aggregate',
744
                    'action'   => 'properties',
745
                    'database' => $_REQUEST['database'],
746
                    'schema'   => $_REQUEST['schema'],
747
                    'aggrname' => $_REQUEST['aggrname'],
748
                    'aggrtype' => $_REQUEST['aggrtype'],
749
                ]];
750
751
                break;
752
            case 'column':
753
                if (isset($_REQUEST['table'])) {
754
                    $vars = ['params' => [
755
                        'server'   => $_REQUEST['server'],
756
                        'subject'  => 'column',
757
                        'database' => $_REQUEST['database'],
758
                        'schema'   => $_REQUEST['schema'],
759
                        'table'    => $_REQUEST['table'],
760
                        'column'   => $_REQUEST['column'],
761
                    ]];
762
                } else {
763
                    $vars = ['params' => [
764
                        'server'   => $_REQUEST['server'],
765
                        'subject'  => 'column',
766
                        'database' => $_REQUEST['database'],
767
                        'schema'   => $_REQUEST['schema'],
768
                        'view'     => $_REQUEST['view'],
769
                        'column'   => $_REQUEST['column'],
770
                    ]];
771
                }
772
773
                break;
774
            case 'plugin':
775
                $vars = [
776
                    'url'    => 'plugin',
777
                    'params' => [
778
                        'server'  => $_REQUEST['server'],
779
                        'subject' => 'plugin',
780
                        'plugin'  => $_REQUEST['plugin'],
781
                    ], ];
782
783
                if (!is_null($plugin_manager->getPlugin($_REQUEST['plugin']))) {
784
                    $vars['params'] = array_merge($vars['params'], $plugin_manager->getPlugin($_REQUEST['plugin'])->get_subject_params());
785
                }
786
787
                break;
788
            default:
789
                return false;
790
        }
791
792
        if (!isset($vars['url'])) {
793
            $vars['url'] = SUBFOLDER.'/redirect';
794
        }
795
        if ($vars['url'] == SUBFOLDER.'/redirect' && isset($vars['params']['subject'])) {
796
            $vars['url'] = SUBFOLDER.'/redirect/'.$vars['params']['subject'];
797
            unset($vars['params']['subject']);
798
        }
799
800
        return $vars;
801
    }
802
803
    /**
804
     * Sets the form tracking variable.
805
     */
806
    public function setForm()
807
    {
808
        $form = [];
809
        if ($this->container->server) {
810
            $form[] = '<input type="hidden" name="server" value="'.htmlspecialchars($this->container->server).'" />';
811
        }
812
        if ($this->container->database) {
813
            $form[] = '<input type="hidden" name="database" value="'.htmlspecialchars($this->container->database).'" />';
814
        }
815
816
        if ($this->container->schema) {
817
            $form[] = '<input type="hidden" name="schema" value="'.htmlspecialchars($this->container->schema).'" />';
818
        }
819
        $this->form = implode("\n", $form);
820
821
        return $this->form;
822
        //\PC::debug($this->form, 'Misc::form');
823
    }
824
825
    /**
826
     * Render a value into HTML using formatting rules specified
827
     * by a type name and parameters.
828
     *
829
     * @param string $str    The string to change
830
     * @param string $type   Field type (optional), this may be an internal PostgreSQL type, or:
831
     *                       yesno    - same as bool, but renders as 'Yes' or 'No'.
832
     *                       pre      - render in a <pre> block.
833
     *                       nbsp     - replace all spaces with &nbsp;'s
834
     *                       verbatim - render exactly as supplied, no escaping what-so-ever.
835
     *                       callback - render using a callback function supplied in the 'function' param.
836
     * @param array  $params Type parameters (optional), known parameters:
837
     *                       null     - string to display if $str is null, or set to TRUE to use a default 'NULL' string,
838
     *                       otherwise nothing is rendered.
839
     *                       clip     - if true, clip the value to a fixed length, and append an ellipsis...
840
     *                       cliplen  - the maximum length when clip is enabled (defaults to $conf['max_chars'])
841
     *                       ellipsis - the string to append to a clipped value (defaults to $lang['strellipsis'])
842
     *                       tag      - an HTML element name to surround the value.
843
     *                       class    - a class attribute to apply to any surrounding HTML element.
844
     *                       align    - an align attribute ('left','right','center' etc.)
845
     *                       true     - (type='bool') the representation of true.
846
     *                       false    - (type='bool') the representation of false.
847
     *                       function - (type='callback') a function name, accepts args ($str, $params) and returns a rendering.
848
     *                       lineno   - prefix each line with a line number.
849
     *                       map      - an associative array.
850
     *
851
     * @return string The HTML rendered value
852
     */
853
    public function printVal($str, $type = null, $params = [])
854
    {
855
        $lang = $this->lang;
856
        $data = $this->getDatabaseAccessor();
857
858
        // Shortcircuit for a NULL value
859
        if (!$str) {
860
            return isset($params['null'])
861
            ? ($params['null'] === true ? '<i>NULL</i>' : $params['null'])
862
            : '';
863
        }
864
865
        if (isset($params['map'], $params['map'][$str])) {
866
            $str = $params['map'][$str];
867
        }
868
869
        // Clip the value if the 'clip' parameter is true.
870
        if (isset($params['clip']) && $params['clip'] === true) {
871
            $maxlen   = isset($params['cliplen']) && is_integer($params['cliplen']) ? $params['cliplen'] : $this->conf['max_chars'];
872
            $ellipsis = isset($params['ellipsis']) ? $params['ellipsis'] : $lang['strellipsis'];
873
            if (strlen($str) > $maxlen) {
874
                $str = substr($str, 0, $maxlen - 1).$ellipsis;
875
            }
876
        }
877
878
        $out   = '';
879
        $class = '';
880
881
        switch ($type) {
882
            case 'int2':
883
            case 'int4':
884
            case 'int8':
885
            case 'float4':
886
            case 'float8':
887
            case 'money':
888
            case 'numeric':
889
            case 'oid':
890
            case 'xid':
891
            case 'cid':
892
            case 'tid':
893
                $align = 'right';
894
                $out   = nl2br(htmlspecialchars(\PHPPgAdmin\Traits\HelperTrait::br2ln($str)));
895
896
                break;
897
            case 'yesno':
898
                if (!isset($params['true'])) {
899
                    $params['true'] = $lang['stryes'];
900
                }
901
902
                if (!isset($params['false'])) {
903
                    $params['false'] = $lang['strno'];
904
                }
905
906
            // no break - fall through to boolean case.
907
            case 'bool':
908
            case 'boolean':
909
                if (is_bool($str)) {
910
                    $str = $str ? 't' : 'f';
911
                }
912
913
                switch ($str) {
914
                    case 't':
915
                        $out   = (isset($params['true']) ? $params['true'] : $lang['strtrue']);
916
                        $align = 'center';
917
918
                        break;
919
                    case 'f':
920
                        $out   = (isset($params['false']) ? $params['false'] : $lang['strfalse']);
921
                        $align = 'center';
922
923
                        break;
924
                    default:
925
                        $out = htmlspecialchars($str);
926
                }
927
928
                break;
929
            case 'bytea':
930
                $tag   = 'div';
931
                $class = 'pre';
932
                $out   = $data->escapeBytea($str);
933
934
                break;
935
            case 'errormsg':
936
                $tag   = 'pre';
937
                $class = 'error';
938
                $out   = htmlspecialchars($str);
939
940
                break;
941
            case 'pre':
942
                $tag = 'pre';
943
                $out = htmlspecialchars($str);
944
945
                break;
946
            case 'prenoescape':
947
                $tag = 'pre';
948
                $out = $str;
949
950
                break;
951
            case 'nbsp':
952
                $out = nl2br(str_replace(' ', '&nbsp;', \PHPPgAdmin\Traits\HelperTrait::br2ln($str)));
953
954
                break;
955
            case 'verbatim':
956
                $out = $str;
957
958
                break;
959
            case 'callback':
960
                $out = $params['function']($str, $params);
961
962
                break;
963
            case 'prettysize':
964
                if ($str == -1) {
965
                    $out = $lang['strnoaccess'];
966
                } else {
967
                    $limit = 10 * 1024;
968
                    $mult  = 1;
969
                    if ($str < $limit * $mult) {
970
                        $out = $str.' '.$lang['strbytes'];
971
                    } else {
972
                        $mult *= 1024;
973
                        if ($str < $limit * $mult) {
974
                            $out = floor(($str + $mult / 2) / $mult).' '.$lang['strkb'];
975
                        } else {
976
                            $mult *= 1024;
977
                            if ($str < $limit * $mult) {
978
                                $out = floor(($str + $mult / 2) / $mult).' '.$lang['strmb'];
979
                            } else {
980
                                $mult *= 1024;
981
                                if ($str < $limit * $mult) {
982
                                    $out = floor(($str + $mult / 2) / $mult).' '.$lang['strgb'];
983
                                } else {
984
                                    $mult *= 1024;
985
                                    if ($str < $limit * $mult) {
986
                                        $out = floor(($str + $mult / 2) / $mult).' '.$lang['strtb'];
987
                                    }
988
                                }
989
                            }
990
                        }
991
                    }
992
                }
993
994
                break;
995
            default:
996
                // If the string contains at least one instance of >1 space in a row, a tab
997
                // character, a space at the start of a line, or a space at the start of
998
                // the whole string then render within a pre-formatted element (<pre>).
999
                if (preg_match('/(^ |  |\t|\n )/m', $str)) {
1000
                    $tag   = 'pre';
1001
                    $class = 'data';
1002
                    $out   = htmlspecialchars($str);
1003
                } else {
1004
                    $out = nl2br(htmlspecialchars(\PHPPgAdmin\Traits\HelperTrait::br2ln($str)));
1005
                }
1006
        }
1007
1008
        if (isset($params['class'])) {
1009
            $class = $params['class'];
1010
        }
1011
1012
        if (isset($params['align'])) {
1013
            $align = $params['align'];
1014
        }
1015
1016
        if (!isset($tag) && (isset($class) || isset($align))) {
1017
            $tag = 'div';
1018
        }
1019
1020
        if (isset($tag)) {
1021
            $alignattr = isset($align) ? " style=\"text-align: {$align}\"" : '';
1022
            $classattr = isset($class) ? " class=\"{$class}\"" : '';
1023
            $out       = "<{$tag}{$alignattr}{$classattr}>{$out}</{$tag}>";
1024
        }
1025
1026
        // Add line numbers if 'lineno' param is true
1027
        if (isset($params['lineno']) && $params['lineno'] === true) {
1028
            $lines = explode("\n", $str);
1029
            $num   = count($lines);
1030
            if ($num > 0) {
1031
                $temp = "<table>\n<tr><td class=\"{$class}\" style=\"vertical-align: top; padding-right: 10px;\"><pre class=\"{$class}\">";
1032
                for ($i = 1; $i <= $num; ++$i) {
1033
                    $temp .= $i."\n";
1034
                }
1035
                $temp .= "</pre></td><td class=\"{$class}\" style=\"vertical-align: top;\">{$out}</td></tr></table>\n";
1036
                $out = $temp;
1037
            }
1038
            unset($lines);
1039
        }
1040
1041
        return $out;
1042
    }
1043
1044
    /**
1045
     * A function to recursively strip slashes.  Used to
1046
     * enforce magic_quotes_gpc being off.
1047
     *
1048
     * @param mixed $var The variable to strip (passed by reference)
1049
     */
1050
    public function stripVar(&$var)
1051
    {
1052
        if (is_array($var)) {
1053
            foreach ($var as $k => $v) {
1054
                $this->stripVar($var[$k]);
1055
1056
                /* magic_quotes_gpc escape keys as well ...*/
1057
                if (is_string($k)) {
1058
                    $ek = stripslashes($k);
1059
                    if ($ek !== $k) {
1060
                        $var[$ek] = $var[$k];
1061
                        unset($var[$k]);
1062
                    }
1063
                }
1064
            }
1065
        } else {
1066
            $var = stripslashes($var);
1067
        }
1068
    }
1069
1070
    /**
1071
     * Retrieve the tab info for a specific tab bar.
1072
     *
1073
     * @param string $section the name of the tab bar
1074
     *
1075
     * @return array array of tabs
1076
     */
1077
    public function getNavTabs($section)
1078
    {
1079
        $data           = $this->getDatabaseAccessor();
1080
        $lang           = $this->lang;
1081
        $plugin_manager = $this->plugin_manager;
1082
1083
        $hide_advanced = ($this->conf['show_advanced'] === false);
1084
        $tabs          = [];
1085
1086
        switch ($section) {
1087
            case 'root':
1088
                $tabs = [
1089
                    'intro'   => [
1090
                        'title' => $lang['strintroduction'],
1091
                        'url'   => 'intro',
1092
                        'icon'  => 'Introduction',
1093
                    ],
1094
                    'servers' => [
1095
                        'title' => $lang['strservers'],
1096
                        'url'   => 'servers',
1097
                        'icon'  => 'Servers',
1098
                    ],
1099
                ];
1100
1101
                break;
1102
            case 'server':
1103
                $hide_users = true;
1104
                if ($data) {
1105
                    $hide_users = !$data->isSuperUser();
1106
                }
1107
1108
                $tabs = [
1109
                    'databases' => [
1110
                        'title'   => $lang['strdatabases'],
1111
                        'url'     => 'alldb',
1112
                        'urlvars' => ['subject' => 'server'],
1113
                        'help'    => 'pg.database',
1114
                        'icon'    => 'Databases',
1115
                    ],
1116
                ];
1117
                if ($data && $data->hasRoles()) {
1118
                    $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...
1119
                        'roles' => [
1120
                            'title'   => $lang['strroles'],
1121
                            'url'     => 'roles',
1122
                            'urlvars' => ['subject' => 'server'],
1123
                            'hide'    => $hide_users,
1124
                            'help'    => 'pg.role',
1125
                            'icon'    => 'Roles',
1126
                        ],
1127
                    ]);
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...
1128
                } else {
1129
                    $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...
1130
                        'users'  => [
1131
                            'title'   => $lang['strusers'],
1132
                            'url'     => 'users',
1133
                            'urlvars' => ['subject' => 'server'],
1134
                            'hide'    => $hide_users,
1135
                            'help'    => 'pg.user',
1136
                            'icon'    => 'Users',
1137
                        ],
1138
                        'groups' => [
1139
                            'title'   => $lang['strgroups'],
1140
                            'url'     => 'groups',
1141
                            'urlvars' => ['subject' => 'server'],
1142
                            'hide'    => $hide_users,
1143
                            'help'    => 'pg.group',
1144
                            'icon'    => 'UserGroups',
1145
                        ],
1146
                    ]);
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...
1147
                }
1148
1149
                $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...
1150
                    'account'     => [
1151
                        'title'   => $lang['straccount'],
1152
                        'url'     => ($data && $data->hasRoles()) ? 'roles' : 'users',
1153
                        'urlvars' => ['subject' => 'server', 'action' => 'account'],
1154
                        'hide'    => !$hide_users,
1155
                        'help'    => 'pg.role',
1156
                        'icon'    => 'User',
1157
                    ],
1158
                    'tablespaces' => [
1159
                        'title'   => $lang['strtablespaces'],
1160
                        'url'     => 'tablespaces',
1161
                        'urlvars' => ['subject' => 'server'],
1162
                        'hide'    => !$data || !$data->hasTablespaces(),
1163
                        'help'    => 'pg.tablespace',
1164
                        'icon'    => 'Tablespaces',
1165
                    ],
1166
                    'export'      => [
1167
                        'title'   => $lang['strexport'],
1168
                        'url'     => 'alldb',
1169
                        'urlvars' => ['subject' => 'server', 'action' => 'export'],
1170
                        'hide'    => !$this->isDumpEnabled(),
1171
                        'icon'    => 'Export',
1172
                    ],
1173
                ]);
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...
1174
1175
                break;
1176
            case 'database':
1177
                $tabs = [
1178
                    'schemas'    => [
1179
                        'title'   => $lang['strschemas'],
1180
                        'url'     => 'schemas',
1181
                        'urlvars' => ['subject' => 'database'],
1182
                        'help'    => 'pg.schema',
1183
                        'icon'    => 'Schemas',
1184
                    ],
1185
                    'sql'        => [
1186
                        'title'   => $lang['strsql'],
1187
                        'url'     => 'database',
1188
                        'urlvars' => ['subject' => 'database', 'action' => 'sql', 'new' => 1],
1189
                        'help'    => 'pg.sql',
1190
                        'tree'    => false,
1191
                        'icon'    => 'SqlEditor',
1192
                    ],
1193
                    'find'       => [
1194
                        'title'   => $lang['strfind'],
1195
                        'url'     => 'database',
1196
                        'urlvars' => ['subject' => 'database', 'action' => 'find'],
1197
                        'tree'    => false,
1198
                        'icon'    => 'Search',
1199
                    ],
1200
                    'variables'  => [
1201
                        'title'   => $lang['strvariables'],
1202
                        'url'     => 'database',
1203
                        'urlvars' => ['subject' => 'database', 'action' => 'variables'],
1204
                        'help'    => 'pg.variable',
1205
                        'tree'    => false,
1206
                        'icon'    => 'Variables',
1207
                    ],
1208
                    'processes'  => [
1209
                        'title'   => $lang['strprocesses'],
1210
                        'url'     => 'database',
1211
                        'urlvars' => ['subject' => 'database', 'action' => 'processes'],
1212
                        'help'    => 'pg.process',
1213
                        'tree'    => false,
1214
                        'icon'    => 'Processes',
1215
                    ],
1216
                    'locks'      => [
1217
                        'title'   => $lang['strlocks'],
1218
                        'url'     => 'database',
1219
                        'urlvars' => ['subject' => 'database', 'action' => 'locks'],
1220
                        'help'    => 'pg.locks',
1221
                        'tree'    => false,
1222
                        'icon'    => 'Key',
1223
                    ],
1224
                    'admin'      => [
1225
                        'title'   => $lang['stradmin'],
1226
                        'url'     => 'database',
1227
                        'urlvars' => ['subject' => 'database', 'action' => 'admin'],
1228
                        'tree'    => false,
1229
                        'icon'    => 'Admin',
1230
                    ],
1231
                    'privileges' => [
1232
                        'title'   => $lang['strprivileges'],
1233
                        'url'     => 'privileges',
1234
                        'urlvars' => ['subject' => 'database'],
1235
                        'hide'    => !isset($data->privlist['database']),
1236
                        'help'    => 'pg.privilege',
1237
                        'tree'    => false,
1238
                        'icon'    => 'Privileges',
1239
                    ],
1240
                    'languages'  => [
1241
                        'title'   => $lang['strlanguages'],
1242
                        'url'     => 'languages',
1243
                        'urlvars' => ['subject' => 'database'],
1244
                        'hide'    => $hide_advanced,
1245
                        'help'    => 'pg.language',
1246
                        'icon'    => 'Languages',
1247
                    ],
1248
                    'casts'      => [
1249
                        'title'   => $lang['strcasts'],
1250
                        'url'     => 'casts',
1251
                        'urlvars' => ['subject' => 'database'],
1252
                        'hide'    => $hide_advanced,
1253
                        'help'    => 'pg.cast',
1254
                        'icon'    => 'Casts',
1255
                    ],
1256
                    'export'     => [
1257
                        'title'   => $lang['strexport'],
1258
                        'url'     => 'database',
1259
                        'urlvars' => ['subject' => 'database', 'action' => 'export'],
1260
                        'hide'    => !$this->isDumpEnabled(),
1261
                        'tree'    => false,
1262
                        'icon'    => 'Export',
1263
                    ],
1264
                ];
1265
1266
                break;
1267
            case 'schema':
1268
                $tabs = [
1269
                    'tables'      => [
1270
                        'title'   => $lang['strtables'],
1271
                        'url'     => 'tables',
1272
                        'urlvars' => ['subject' => 'schema'],
1273
                        'help'    => 'pg.table',
1274
                        'icon'    => 'Tables',
1275
                    ],
1276
                    'views'       => [
1277
                        'title'   => $lang['strviews'],
1278
                        'url'     => 'views',
1279
                        'urlvars' => ['subject' => 'schema'],
1280
                        'help'    => 'pg.view',
1281
                        'icon'    => 'Views',
1282
                    ],
1283
                    'matviews'    => [
1284
                        'title'   => 'M '.$lang['strviews'],
1285
                        'url'     => 'materializedviews',
1286
                        'urlvars' => ['subject' => 'schema'],
1287
                        'help'    => 'pg.matview',
1288
                        'icon'    => 'MViews',
1289
                    ],
1290
                    'sequences'   => [
1291
                        'title'   => $lang['strsequences'],
1292
                        'url'     => 'sequences',
1293
                        'urlvars' => ['subject' => 'schema'],
1294
                        'help'    => 'pg.sequence',
1295
                        'icon'    => 'Sequences',
1296
                    ],
1297
                    'functions'   => [
1298
                        'title'   => $lang['strfunctions'],
1299
                        'url'     => 'functions',
1300
                        'urlvars' => ['subject' => 'schema'],
1301
                        'help'    => 'pg.function',
1302
                        'icon'    => 'Functions',
1303
                    ],
1304
                    'fulltext'    => [
1305
                        'title'   => $lang['strfulltext'],
1306
                        'url'     => 'fulltext',
1307
                        'urlvars' => ['subject' => 'schema'],
1308
                        'help'    => 'pg.fts',
1309
                        'tree'    => true,
1310
                        'icon'    => 'Fts',
1311
                    ],
1312
                    'domains'     => [
1313
                        'title'   => $lang['strdomains'],
1314
                        'url'     => 'domains',
1315
                        'urlvars' => ['subject' => 'schema'],
1316
                        'help'    => 'pg.domain',
1317
                        'icon'    => 'Domains',
1318
                    ],
1319
                    'aggregates'  => [
1320
                        'title'   => $lang['straggregates'],
1321
                        'url'     => 'aggregates',
1322
                        'urlvars' => ['subject' => 'schema'],
1323
                        'hide'    => $hide_advanced,
1324
                        'help'    => 'pg.aggregate',
1325
                        'icon'    => 'Aggregates',
1326
                    ],
1327
                    'types'       => [
1328
                        'title'   => $lang['strtypes'],
1329
                        'url'     => 'types',
1330
                        'urlvars' => ['subject' => 'schema'],
1331
                        'hide'    => $hide_advanced,
1332
                        'help'    => 'pg.type',
1333
                        'icon'    => 'Types',
1334
                    ],
1335
                    'operators'   => [
1336
                        'title'   => $lang['stroperators'],
1337
                        'url'     => 'operators',
1338
                        'urlvars' => ['subject' => 'schema'],
1339
                        'hide'    => $hide_advanced,
1340
                        'help'    => 'pg.operator',
1341
                        'icon'    => 'Operators',
1342
                    ],
1343
                    'opclasses'   => [
1344
                        'title'   => $lang['stropclasses'],
1345
                        'url'     => 'opclasses',
1346
                        'urlvars' => ['subject' => 'schema'],
1347
                        'hide'    => $hide_advanced,
1348
                        'help'    => 'pg.opclass',
1349
                        'icon'    => 'OperatorClasses',
1350
                    ],
1351
                    'conversions' => [
1352
                        'title'   => $lang['strconversions'],
1353
                        'url'     => 'conversions',
1354
                        'urlvars' => ['subject' => 'schema'],
1355
                        'hide'    => $hide_advanced,
1356
                        'help'    => 'pg.conversion',
1357
                        'icon'    => 'Conversions',
1358
                    ],
1359
                    'privileges'  => [
1360
                        'title'   => $lang['strprivileges'],
1361
                        'url'     => 'privileges',
1362
                        'urlvars' => ['subject' => 'schema'],
1363
                        'help'    => 'pg.privilege',
1364
                        'tree'    => false,
1365
                        'icon'    => 'Privileges',
1366
                    ],
1367
                    'export'      => [
1368
                        'title'   => $lang['strexport'],
1369
                        'url'     => 'schemas',
1370
                        'urlvars' => ['subject' => 'schema', 'action' => 'export'],
1371
                        'hide'    => !$this->isDumpEnabled(),
1372
                        'tree'    => false,
1373
                        'icon'    => 'Export',
1374
                    ],
1375
                ];
1376
                if (!$data->hasFTS()) {
1377
                    unset($tabs['fulltext']);
1378
                }
1379
1380
                break;
1381
            case 'table':
1382
                $tabs = [
1383
                    'columns'     => [
1384
                        'title'   => $lang['strcolumns'],
1385
                        'url'     => 'tblproperties',
1386
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1387
                        'icon'    => 'Columns',
1388
                        'branch'  => true,
1389
                    ],
1390
                    'browse'      => [
1391
                        'title'   => $lang['strbrowse'],
1392
                        'icon'    => 'Columns',
1393
                        'url'     => 'display',
1394
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1395
                        'return'  => 'table',
1396
                        'branch'  => true,
1397
                    ],
1398
                    'select'      => [
1399
                        'title'   => $lang['strselect'],
1400
                        'icon'    => 'Search',
1401
                        'url'     => 'tables',
1402
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table'), 'action' => 'confselectrows'],
1403
                        'help'    => 'pg.sql.select',
1404
                    ],
1405
                    'insert'      => [
1406
                        'title'   => $lang['strinsert'],
1407
                        'url'     => 'tables',
1408
                        'urlvars' => [
1409
                            'action' => 'confinsertrow',
1410
                            'table'  => Decorator::field('table'),
1411
                        ],
1412
                        'help'    => 'pg.sql.insert',
1413
                        'icon'    => 'Operator',
1414
                    ],
1415
                    'indexes'     => [
1416
                        'title'   => $lang['strindexes'],
1417
                        'url'     => 'indexes',
1418
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1419
                        'help'    => 'pg.index',
1420
                        'icon'    => 'Indexes',
1421
                        'branch'  => true,
1422
                    ],
1423
                    'constraints' => [
1424
                        'title'   => $lang['strconstraints'],
1425
                        'url'     => 'constraints',
1426
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1427
                        'help'    => 'pg.constraint',
1428
                        'icon'    => 'Constraints',
1429
                        'branch'  => true,
1430
                    ],
1431
                    'triggers'    => [
1432
                        'title'   => $lang['strtriggers'],
1433
                        'url'     => 'triggers',
1434
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1435
                        'help'    => 'pg.trigger',
1436
                        'icon'    => 'Triggers',
1437
                        'branch'  => true,
1438
                    ],
1439
                    'rules'       => [
1440
                        'title'   => $lang['strrules'],
1441
                        'url'     => 'rules',
1442
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1443
                        'help'    => 'pg.rule',
1444
                        'icon'    => 'Rules',
1445
                        'branch'  => true,
1446
                    ],
1447
                    'admin'       => [
1448
                        'title'   => $lang['stradmin'],
1449
                        'url'     => 'tables',
1450
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table'), 'action' => 'admin'],
1451
                        'icon'    => 'Admin',
1452
                    ],
1453
                    'info'        => [
1454
                        'title'   => $lang['strinfo'],
1455
                        'url'     => 'info',
1456
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1457
                        'icon'    => 'Statistics',
1458
                    ],
1459
                    'privileges'  => [
1460
                        'title'   => $lang['strprivileges'],
1461
                        'url'     => 'privileges',
1462
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table')],
1463
                        'help'    => 'pg.privilege',
1464
                        'icon'    => 'Privileges',
1465
                    ],
1466
                    'import'      => [
1467
                        'title'   => $lang['strimport'],
1468
                        'url'     => 'tblproperties',
1469
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table'), 'action' => 'import'],
1470
                        'icon'    => 'Import',
1471
                        'hide'    => false,
1472
                    ],
1473
                    'export'      => [
1474
                        'title'   => $lang['strexport'],
1475
                        'url'     => 'tblproperties',
1476
                        'urlvars' => ['subject' => 'table', 'table' => Decorator::field('table'), 'action' => 'export'],
1477
                        'icon'    => 'Export',
1478
                        'hide'    => false,
1479
                    ],
1480
                ];
1481
1482
                break;
1483
            case 'view':
1484
                $tabs = [
1485
                    'columns'    => [
1486
                        'title'   => $lang['strcolumns'],
1487
                        'url'     => 'viewproperties',
1488
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view')],
1489
                        'icon'    => 'Columns',
1490
                        'branch'  => true,
1491
                    ],
1492
                    'browse'     => [
1493
                        'title'   => $lang['strbrowse'],
1494
                        'icon'    => 'Columns',
1495
                        'url'     => 'display',
1496
                        'urlvars' => [
1497
                            'action'  => 'confselectrows',
1498
                            'return'  => 'schema',
1499
                            'subject' => 'view',
1500
                            'view'    => Decorator::field('view'),
1501
                        ],
1502
                        'branch'  => true,
1503
                    ],
1504
                    'select'     => [
1505
                        'title'   => $lang['strselect'],
1506
                        'icon'    => 'Search',
1507
                        'url'     => 'views',
1508
                        'urlvars' => ['action' => 'confselectrows', 'view' => Decorator::field('view')],
1509
                        'help'    => 'pg.sql.select',
1510
                    ],
1511
                    'definition' => [
1512
                        'title'   => $lang['strdefinition'],
1513
                        'url'     => 'viewproperties',
1514
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view'), 'action' => 'definition'],
1515
                        'icon'    => 'Definition',
1516
                    ],
1517
                    'rules'      => [
1518
                        'title'   => $lang['strrules'],
1519
                        'url'     => 'rules',
1520
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view')],
1521
                        'help'    => 'pg.rule',
1522
                        'icon'    => 'Rules',
1523
                        'branch'  => true,
1524
                    ],
1525
                    'privileges' => [
1526
                        'title'   => $lang['strprivileges'],
1527
                        'url'     => 'privileges',
1528
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view')],
1529
                        'help'    => 'pg.privilege',
1530
                        'icon'    => 'Privileges',
1531
                    ],
1532
                    'export'     => [
1533
                        'title'   => $lang['strexport'],
1534
                        'url'     => 'viewproperties',
1535
                        'urlvars' => ['subject' => 'view', 'view' => Decorator::field('view'), 'action' => 'export'],
1536
                        'icon'    => 'Export',
1537
                        'hide'    => false,
1538
                    ],
1539
                ];
1540
1541
                break;
1542
            case 'matview':
1543
                $tabs = [
1544
                    'columns'    => [
1545
                        'title'   => $lang['strcolumns'],
1546
                        'url'     => 'materializedviewproperties',
1547
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1548
                        'icon'    => 'Columns',
1549
                        'branch'  => true,
1550
                    ],
1551
                    'browse'     => [
1552
                        'title'   => $lang['strbrowse'],
1553
                        'icon'    => 'Columns',
1554
                        'url'     => 'display',
1555
                        'urlvars' => [
1556
                            'action'  => 'confselectrows',
1557
                            'return'  => 'schema',
1558
                            'subject' => 'matview',
1559
                            'matview' => Decorator::field('matview'),
1560
                        ],
1561
                        'branch'  => true,
1562
                    ],
1563
                    'select'     => [
1564
                        'title'   => $lang['strselect'],
1565
                        'icon'    => 'Search',
1566
                        'url'     => 'materializedviews',
1567
                        'urlvars' => ['action' => 'confselectrows', 'matview' => Decorator::field('matview')],
1568
                        'help'    => 'pg.sql.select',
1569
                    ],
1570
                    'definition' => [
1571
                        'title'   => $lang['strdefinition'],
1572
                        'url'     => 'materializedviewproperties',
1573
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview'), 'action' => 'definition'],
1574
                        'icon'    => 'Definition',
1575
                    ],
1576
                    'indexes'    => [
1577
                        'title'   => $lang['strindexes'],
1578
                        'url'     => 'indexes',
1579
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1580
                        'help'    => 'pg.index',
1581
                        'icon'    => 'Indexes',
1582
                        'branch'  => true,
1583
                    ],
1584
                    /*'constraints' => [
1585
                    'title' => $lang['strconstraints'],
1586
                    'url' => 'constraints',
1587
                    'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1588
                    'help' => 'pg.constraint',
1589
                    'icon' => 'Constraints',
1590
                    'branch' => true,
1591
                     */
1592
1593
                    'rules'      => [
1594
                        'title'   => $lang['strrules'],
1595
                        'url'     => 'rules',
1596
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1597
                        'help'    => 'pg.rule',
1598
                        'icon'    => 'Rules',
1599
                        'branch'  => true,
1600
                    ],
1601
                    'privileges' => [
1602
                        'title'   => $lang['strprivileges'],
1603
                        'url'     => 'privileges',
1604
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview')],
1605
                        'help'    => 'pg.privilege',
1606
                        'icon'    => 'Privileges',
1607
                    ],
1608
                    'export'     => [
1609
                        'title'   => $lang['strexport'],
1610
                        'url'     => 'materializedviewproperties',
1611
                        'urlvars' => ['subject' => 'matview', 'matview' => Decorator::field('matview'), 'action' => 'export'],
1612
                        'icon'    => 'Export',
1613
                        'hide'    => false,
1614
                    ],
1615
                ];
1616
1617
                break;
1618
            case 'function':
1619
                $tabs = [
1620
                    'definition' => [
1621
                        'title'   => $lang['strdefinition'],
1622
                        'url'     => 'functions',
1623
                        'urlvars' => [
1624
                            'subject'      => 'function',
1625
                            'function'     => Decorator::field('function'),
1626
                            'function_oid' => Decorator::field('function_oid'),
1627
                            'action'       => 'properties',
1628
                        ],
1629
                        'icon'    => 'Definition',
1630
                    ],
1631
                    'privileges' => [
1632
                        'title'   => $lang['strprivileges'],
1633
                        'url'     => 'privileges',
1634
                        'urlvars' => [
1635
                            'subject'      => 'function',
1636
                            'function'     => Decorator::field('function'),
1637
                            'function_oid' => Decorator::field('function_oid'),
1638
                        ],
1639
                        'icon'    => 'Privileges',
1640
                    ],
1641
                ];
1642
1643
                break;
1644
            case 'aggregate':
1645
                $tabs = [
1646
                    'definition' => [
1647
                        'title'   => $lang['strdefinition'],
1648
                        'url'     => 'aggregates',
1649
                        'urlvars' => [
1650
                            'subject'  => 'aggregate',
1651
                            'aggrname' => Decorator::field('aggrname'),
1652
                            'aggrtype' => Decorator::field('aggrtype'),
1653
                            'action'   => 'properties',
1654
                        ],
1655
                        'icon'    => 'Definition',
1656
                    ],
1657
                ];
1658
1659
                break;
1660
            case 'role':
1661
                $tabs = [
1662
                    'definition' => [
1663
                        'title'   => $lang['strdefinition'],
1664
                        'url'     => 'roles',
1665
                        'urlvars' => [
1666
                            'subject'  => 'role',
1667
                            'rolename' => Decorator::field('rolename'),
1668
                            'action'   => 'properties',
1669
                        ],
1670
                        'icon'    => 'Definition',
1671
                    ],
1672
                ];
1673
1674
                break;
1675
            case 'popup':
1676
                $tabs = [
1677
                    'sql'  => [
1678
                        'title'   => $lang['strsql'],
1679
                        'url'     => '/src/views/sqledit',
1680
                        'urlvars' => ['action' => 'sql', 'subject' => 'schema'],
1681
                        'help'    => 'pg.sql',
1682
                        'icon'    => 'SqlEditor',
1683
                    ],
1684
                    'find' => [
1685
                        'title'   => $lang['strfind'],
1686
                        'url'     => '/src/views/sqledit',
1687
                        'urlvars' => ['action' => 'find', 'subject' => 'schema'],
1688
                        'icon'    => 'Search',
1689
                    ],
1690
                ];
1691
1692
                break;
1693
            case 'column':
1694
                $tabs = [
1695
                    'properties' => [
1696
                        'title'   => $lang['strcolprop'],
1697
                        'url'     => 'colproperties',
1698
                        'urlvars' => [
1699
                            'subject' => 'column',
1700
                            'table'   => Decorator::field('table'),
1701
                            'column'  => Decorator::field('column'),
1702
                        ],
1703
                        'icon'    => 'Column',
1704
                    ],
1705
                    'privileges' => [
1706
                        'title'   => $lang['strprivileges'],
1707
                        'url'     => 'privileges',
1708
                        'urlvars' => [
1709
                            'subject' => 'column',
1710
                            'table'   => Decorator::field('table'),
1711
                            'column'  => Decorator::field('column'),
1712
                        ],
1713
                        'help'    => 'pg.privilege',
1714
                        'icon'    => 'Privileges',
1715
                    ],
1716
                ];
1717
1718
                break;
1719
            case 'fulltext':
1720
                $tabs = [
1721
                    'ftsconfigs' => [
1722
                        'title'   => $lang['strftstabconfigs'],
1723
                        'url'     => 'fulltext',
1724
                        'urlvars' => ['subject' => 'schema'],
1725
                        'hide'    => !$data->hasFTS(),
1726
                        'help'    => 'pg.ftscfg',
1727
                        'tree'    => true,
1728
                        'icon'    => 'FtsCfg',
1729
                    ],
1730
                    'ftsdicts'   => [
1731
                        'title'   => $lang['strftstabdicts'],
1732
                        'url'     => 'fulltext',
1733
                        'urlvars' => ['subject' => 'schema', 'action' => 'viewdicts'],
1734
                        'hide'    => !$data->hasFTS(),
1735
                        'help'    => 'pg.ftsdict',
1736
                        'tree'    => true,
1737
                        'icon'    => 'FtsDict',
1738
                    ],
1739
                    'ftsparsers' => [
1740
                        'title'   => $lang['strftstabparsers'],
1741
                        'url'     => 'fulltext',
1742
                        'urlvars' => ['subject' => 'schema', 'action' => 'viewparsers'],
1743
                        'hide'    => !$data->hasFTS(),
1744
                        'help'    => 'pg.ftsparser',
1745
                        'tree'    => true,
1746
                        'icon'    => 'FtsParser',
1747
                    ],
1748
                ];
1749
1750
                break;
1751
        }
1752
1753
        // Tabs hook's place
1754
        $plugin_functions_parameters = [
1755
            'tabs'    => &$tabs,
1756
            'section' => $section,
1757
        ];
1758
        $plugin_manager->do_hook('tabs', $plugin_functions_parameters);
1759
1760
        return $tabs;
1761
    }
1762
1763
    /**
1764
     * Get the URL for the last active tab of a particular tab bar.
1765
     *
1766
     * @param string $section
1767
     *
1768
     * @return null|mixed
1769
     */
1770
    public function getLastTabURL($section)
1771
    {
1772
        //$data = $this->getDatabaseAccessor();
1773
1774
        $tabs = $this->getNavTabs($section);
1775
1776
        if (isset($_SESSION['webdbLastTab'][$section])) {
1777
            $tab = $tabs[$_SESSION['webdbLastTab'][$section]];
1778
        } else {
1779
            $tab = reset($tabs);
1780
        }
1781
        //$this->prtrace(['section' => $section, 'tabs' => $tabs, 'tab' => $tab]);
1782
        return isset($tab['url']) ? $tab : null;
1783
    }
1784
1785
    /**
1786
     * Do multi-page navigation.  Displays the prev, next and page options.
1787
     *
1788
     * @param int    $page      - the page currently viewed
1789
     * @param int    $pages     - the maximum number of pages
1790
     * @param string $gets      -  the parameters to include in the link to the wanted page
1791
     * @param int    $max_width - the number of pages to make available at any one time (default = 20)
1792
     */
1793
    public function printPages($page, $pages, $gets, $max_width = 20)
1794
    {
1795
        $lang = $this->lang;
1796
1797
        $window = 10;
1798
1799
        if ($page < 0 || $page > $pages) {
1800
            return;
1801
        }
1802
1803
        if ($pages < 0) {
1804
            return;
1805
        }
1806
1807
        if ($max_width <= 0) {
1808
            return;
1809
        }
1810
1811
        unset($gets['page']);
1812
        $url = http_build_query($gets);
1813
1814
        if ($pages > 1) {
1815
            echo "<p style=\"text-align: center\">\n";
1816
            if ($page != 1) {
1817
                echo "<a class=\"pagenav\" href=\"?{$url}&amp;page=1\">{$lang['strfirst']}</a>\n";
1818
                $temp = $page - 1;
1819
                echo "<a class=\"pagenav\" href=\"?{$url}&amp;page={$temp}\">{$lang['strprev']}</a>\n";
1820
            }
1821
1822
            if ($page <= $window) {
1823
                $min_page = 1;
1824
                $max_page = min(2 * $window, $pages);
1825
            } elseif ($page > $window && $pages >= $page + $window) {
1826
                $min_page = ($page - $window) + 1;
1827
                $max_page = $page + $window;
1828
            } else {
1829
                $min_page = ($page - (2 * $window - ($pages - $page))) + 1;
1830
                $max_page = $pages;
1831
            }
1832
1833
            // Make sure min_page is always at least 1
1834
            // and max_page is never greater than $pages
1835
            $min_page = max($min_page, 1);
1836
            $max_page = min($max_page, $pages);
1837
1838
            for ($i = $min_page; $i <= $max_page; ++$i) {
1839
                #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...
1840
                if ($i != $page) {
1841
                    echo "<a class=\"pagenav\" href=\"display?{$url}&amp;page={$i}\">${i}</a>\n";
1842
                } else {
1843
                    echo "${i}\n";
1844
                }
1845
            }
1846
            if ($page != $pages) {
1847
                $temp = $page + 1;
1848
                echo "<a class=\"pagenav\" href=\"display?{$url}&amp;page={$temp}\">{$lang['strnext']}</a>\n";
1849
                echo "<a class=\"pagenav\" href=\"display?{$url}&amp;page={$pages}\">{$lang['strlast']}</a>\n";
1850
            }
1851
            echo "</p>\n";
1852
        }
1853
    }
1854
1855
    /**
1856
     * Converts a PHP.INI size variable to bytes.  Taken from publically available
1857
     * function by Chris DeRose, here: http://www.php.net/manual/en/configuration.directives.php#ini.file-uploads.
1858
     *
1859
     * @param mixed $strIniSize The PHP.INI variable
1860
     *
1861
     * @return float|float|int size in bytes, false on failure
1862
     */
1863
    public function inisizeToBytes($strIniSize)
1864
    {
1865
        // This function will take the string value of an ini 'size' parameter,
1866
        // and return a double (64-bit float) representing the number of bytes
1867
        // that the parameter represents. Or false if $strIniSize is unparseable.
1868
        $a_IniParts = [];
1869
1870
        if (!is_string($strIniSize)) {
1871
            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...
1872
        }
1873
1874
        if (!preg_match('/^(\d+)([bkm]*)$/i', $strIniSize, $a_IniParts)) {
1875
            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...
1876
        }
1877
1878
        $nSize   = (float) $a_IniParts[1];
1879
        $strUnit = strtolower($a_IniParts[2]);
1880
1881
        switch ($strUnit) {
1882
            case 'm':
1883
                return $nSize * (float) 1048576;
1884
            case 'k':
1885
                return $nSize * (float) 1024;
1886
            case 'b':
1887
            default:
1888
                return $nSize;
1889
        }
1890
    }
1891
1892
    public function getRequestVars($subject = '')
1893
    {
1894
        $v = [];
1895
        if (!empty($subject)) {
1896
            $v['subject'] = $subject;
1897
        }
1898
1899
        if ($this->_server_id !== null && $subject != 'root') {
1900
            $v['server'] = $this->_server_id;
1901
            if ($this->_database !== null && $subject != 'server') {
1902
                $v['database'] = $this->_database;
1903
                if (isset($_REQUEST['schema']) && $subject != 'database') {
1904
                    $v['schema'] = $_REQUEST['schema'];
1905
                }
1906
            }
1907
        }
1908
        //$this->prtrace($v);
1909
        return $v;
1910
    }
1911
1912
    public function icon($icon)
1913
    {
1914
        if (is_string($icon)) {
1915
            $path = "/images/themes/{$this->conf['theme']}/{$icon}";
1916
            if (file_exists(\BASE_PATH.$path.'.png')) {
1917
                return SUBFOLDER.$path.'.png';
1918
            }
1919
1920
            if (file_exists(\BASE_PATH.$path.'.gif')) {
1921
                return SUBFOLDER.$path.'.gif';
1922
            }
1923
1924
            if (file_exists(\BASE_PATH.$path.'.ico')) {
1925
                return SUBFOLDER.$path.'.ico';
1926
            }
1927
1928
            $path = "/images/themes/default/{$icon}";
1929
            if (file_exists(\BASE_PATH.$path.'.png')) {
1930
                return SUBFOLDER.$path.'.png';
1931
            }
1932
1933
            if (file_exists(\BASE_PATH.$path.'.gif')) {
1934
                return SUBFOLDER.$path.'.gif';
1935
            }
1936
1937
            if (file_exists(\BASE_PATH.$path.'.ico')) {
1938
                return SUBFOLDER.$path.'.ico';
1939
            }
1940
        } else {
1941
            // Icon from plugins
1942
            $path = "/plugins/{$icon[0]}/images/{$icon[1]}";
1943
            if (file_exists(\BASE_PATH.$path.'.png')) {
1944
                return SUBFOLDER.$path.'.png';
1945
            }
1946
1947
            if (file_exists(\BASE_PATH.$path.'.gif')) {
1948
                return SUBFOLDER.$path.'.gif';
1949
            }
1950
1951
            if (file_exists(\BASE_PATH.$path.'.ico')) {
1952
                return SUBFOLDER.$path.'.ico';
1953
            }
1954
        }
1955
1956
        return '';
1957
    }
1958
1959
    /**
1960
     * Function to escape command line parameters.
1961
     *
1962
     * @param string $str The string to escape
1963
     *
1964
     * @return string The escaped string
1965
     */
1966
    public function escapeShellArg($str)
1967
    {
1968
        //$data = $this->getDatabaseAccessor();
1969
        $lang = $this->lang;
1970
1971
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1972
            // Due to annoying PHP bugs, shell arguments cannot be escaped
1973
            // (command simply fails), so we cannot allow complex objects
1974
            // to be dumped.
1975
            if (preg_match('/^[_.[:alnum:]]+$/', $str)) {
1976
                return $str;
1977
            }
1978
1979
            return $this->halt($lang['strcannotdumponwindows']);
1980
        }
1981
1982
        return escapeshellarg($str);
1983
    }
1984
1985
    /**
1986
     * Function to escape command line programs.
1987
     *
1988
     * @param string $str The string to escape
1989
     *
1990
     * @return string The escaped string
1991
     */
1992
    public function escapeShellCmd($str)
1993
    {
1994
        $data = $this->getDatabaseAccessor();
1995
1996
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1997
            $data->fieldClean($str);
1998
1999
            return '"'.$str.'"';
2000
        }
2001
2002
        return escapeshellcmd($str);
2003
    }
2004
2005
    /**
2006
     * Save the given SQL script in the history
2007
     * of the database and server.
2008
     *
2009
     * @param string $script the SQL script to save
2010
     */
2011
    public function saveScriptHistory($script)
2012
    {
2013
        list($usec, $sec)                                                           = explode(' ', microtime());
2014
        $time                                                                       = ((float) $usec + (float) $sec);
2015
        $_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']]["${time}"] = [
2016
            'query'    => $script,
2017
            'paginate' => !isset($_REQUEST['paginate']) ? 'f' : 't',
2018
            'queryid'  => $time,
2019
        ];
2020
    }
2021
2022
    /**
2023
     * 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...
2024
     * or by constraint.
2025
     *
2026
     * @param string $table The table to retrieve FK contraints from
2027
     *
2028
     * @return array|bool the array of FK definition:
2029
     *                    array(
2030
     *                    'byconstr' => array(
2031
     *                    constrain id => array(
2032
     *                    confrelid => foreign relation oid
2033
     *                    f_schema => foreign schema name
2034
     *                    f_table => foreign table name
2035
     *                    pattnums => array of parent's fields nums
2036
     *                    pattnames => array of parent's fields names
2037
     *                    fattnames => array of foreign attributes names
2038
     *                    )
2039
     *                    ),
2040
     *                    'byfield' => array(
2041
     *                    attribute num => array (constraint id, ...)
2042
     *                    ),
2043
     *                    'code' => HTML/js code to include in the page for auto-completion
2044
     *                    )
2045
     */
2046
    public function getAutocompleteFKProperties($table)
2047
    {
2048
        $data = $this->getDatabaseAccessor();
2049
2050
        $fksprops = [
2051
            'byconstr' => [],
2052
            'byfield'  => [],
2053
            'code'     => '',
2054
        ];
2055
2056
        $constrs = $data->getConstraintsWithFields($table);
2057
2058
        if (!$constrs->EOF) {
2059
            //$conrelid = $constrs->fields['conrelid'];
2060
            while (!$constrs->EOF) {
2061
                if ($constrs->fields['contype'] == 'f') {
2062
                    if (!isset($fksprops['byconstr'][$constrs->fields['conid']])) {
2063
                        $fksprops['byconstr'][$constrs->fields['conid']] = [
2064
                            'confrelid' => $constrs->fields['confrelid'],
2065
                            'f_table'   => $constrs->fields['f_table'],
2066
                            'f_schema'  => $constrs->fields['f_schema'],
2067
                            'pattnums'  => [],
2068
                            'pattnames' => [],
2069
                            'fattnames' => [],
2070
                        ];
2071
                    }
2072
2073
                    $fksprops['byconstr'][$constrs->fields['conid']]['pattnums'][]  = $constrs->fields['p_attnum'];
2074
                    $fksprops['byconstr'][$constrs->fields['conid']]['pattnames'][] = $constrs->fields['p_field'];
2075
                    $fksprops['byconstr'][$constrs->fields['conid']]['fattnames'][] = $constrs->fields['f_field'];
2076
2077
                    if (!isset($fksprops['byfield'][$constrs->fields['p_attnum']])) {
2078
                        $fksprops['byfield'][$constrs->fields['p_attnum']] = [];
2079
                    }
2080
2081
                    $fksprops['byfield'][$constrs->fields['p_attnum']][] = $constrs->fields['conid'];
2082
                }
2083
                $constrs->moveNext();
2084
            }
2085
2086
            $fksprops['code'] = "<script type=\"text/javascript\">\n";
2087
            $fksprops['code'] .= "var constrs = {};\n";
2088
            foreach ($fksprops['byconstr'] as $conid => $props) {
2089
                $fksprops['code'] .= "constrs.constr_{$conid} = {\n";
2090
                $fksprops['code'] .= 'pattnums: ['.implode(',', $props['pattnums'])."],\n";
2091
                $fksprops['code'] .= "f_table:'".addslashes(htmlentities($props['f_table'], ENT_QUOTES, 'UTF-8'))."',\n";
2092
                $fksprops['code'] .= "f_schema:'".addslashes(htmlentities($props['f_schema'], ENT_QUOTES, 'UTF-8'))."',\n";
2093
                $_ = '';
2094
                foreach ($props['pattnames'] as $n) {
2095
                    $_ .= ",'".htmlentities($n, ENT_QUOTES, 'UTF-8')."'";
2096
                }
2097
                $fksprops['code'] .= 'pattnames: ['.substr($_, 1)."],\n";
2098
2099
                $_ = '';
2100
                foreach ($props['fattnames'] as $n) {
2101
                    $_ .= ",'".htmlentities($n, ENT_QUOTES, 'UTF-8')."'";
2102
                }
2103
2104
                $fksprops['code'] .= 'fattnames: ['.substr($_, 1)."]\n";
2105
                $fksprops['code'] .= "};\n";
2106
            }
2107
2108
            $fksprops['code'] .= "var attrs = {};\n";
2109
            foreach ($fksprops['byfield'] as $attnum => $cstrs) {
2110
                $fksprops['code'] .= "attrs.attr_{$attnum} = [".implode(',', $fksprops['byfield'][$attnum])."];\n";
2111
            }
2112
2113
            $fksprops['code'] .= "var table='".addslashes(htmlentities($table, ENT_QUOTES, 'UTF-8'))."';";
2114
            $fksprops['code'] .= "var server='".htmlentities($_REQUEST['server'], ENT_QUOTES, 'UTF-8')."';";
2115
            $fksprops['code'] .= "var database='".addslashes(htmlentities($_REQUEST['database'], ENT_QUOTES, 'UTF-8'))."';";
2116
            $fksprops['code'] .= "var subfolder='".SUBFOLDER."';";
2117
            $fksprops['code'] .= "</script>\n";
2118
2119
            $fksprops['code'] .= '<div id="fkbg"></div>';
2120
            $fksprops['code'] .= '<div id="fklist"></div>';
2121
            $fksprops['code'] .= '<script src="'.SUBFOLDER.'/js/ac_insert_row.js" type="text/javascript"></script>';
2122
        } else {
2123
            /* we have no foreign keys on this table */
2124
            return false;
2125
        }
2126
2127
        return $fksprops;
2128
    }
2129
}
2130