Passed
Push — develop ( c6c0b1...90e9a5 )
by Felipe
10:30 queued 02:43
created

SchemasController::doCreate()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 49
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 49
rs 9.2258
c 0
b 0
f 0
cc 3
eloc 35
nc 2
nop 1
1
<?php
2
3
/**
4
 * PHPPgAdmin v6.0.0-beta.45
5
 */
6
7
namespace PHPPgAdmin\Controller;
8
9
use PHPPgAdmin\Decorators\Decorator;
10
11
/**
12
 * Base controller class.
13
 *
14
 * @package PHPPgAdmin
15
 */
16
class SchemasController extends BaseController
17
{
18
    public $controller_title = 'strschemas';
19
20
    /**
21
     * Default method to render the controller according to the action parameter.
22
     */
23
    public function render()
24
    {
25
        if ('tree' == $this->action) {
26
            return $this->doTree();
27
        }
28
        if ('subtree' == $this->action) {
29
            return $this->doSubTree();
30
        }
31
32
        if (isset($_POST['cancel'])) {
33
            $this->action = '';
34
        }
35
36
        $header_template = 'header.twig';
37
        $footer_template = 'footer.twig';
0 ignored issues
show
Unused Code introduced by
The assignment to $footer_template is dead and can be removed.
Loading history...
38
39
        ob_start();
40
        switch ($this->action) {
41
            case 'create':
42
                if (isset($_POST['create'])) {
43
                    $this->doSaveCreate();
44
                } else {
45
                    $this->doCreate();
46
                }
47
48
                break;
49
            case 'alter':
50
                if (isset($_POST['alter'])) {
51
                    $this->doSaveAlter();
52
                } else {
53
                    $this->doAlter();
54
                }
55
56
                break;
57
            case 'drop':
58
                if (isset($_POST['drop'])) {
59
                    $this->doDrop(false);
60
                } else {
61
                    $this->doDrop(true);
62
                }
63
64
                break;
65
            case 'export':
66
                $this->doExport();
67
68
                break;
69
            default:
70
                $header_template = 'header_datatables.twig';
71
                $this->doDefault();
72
73
                break;
74
        }
75
76
        $output = ob_get_clean();
77
78
        $this->printHeader($this->headerTitle(), null, true, $header_template);
79
        $this->printBody();
80
81
        echo $output;
82
83
        return $this->printFooter();
84
    }
85
86
    /**
87
     * Show default list of schemas in the database.
88
     *
89
     * @param mixed $msg
90
     */
91
    public function doDefault($msg = '')
92
    {
93
        $data = $this->misc->getDatabaseAccessor();
94
95
        $this->printTrail('database');
96
        $this->printTabs('database', 'schemas');
97
        $this->printMsg($msg);
98
99
        // Check that the DB actually supports schemas
100
        $schemas = $data->getSchemas();
101
102
        $columns = [
103
            'schema'      => [
104
                'title' => $this->lang['strschema'],
105
                'field' => Decorator::field('nspname'),
106
                'url'   => \SUBFOLDER . "/redirect/schema?{$this->misc->href}&amp;",
107
                'vars'  => ['schema' => 'nspname'],
108
            ],
109
            'owner'       => [
110
                'title' => $this->lang['strowner'],
111
                'field' => Decorator::field('nspowner'),
112
            ],
113
            'schema_size' => [
114
                'title' => $this->lang['strsize'],
115
                'field' => Decorator::field('schema_size'),
116
            ],
117
            'actions'     => [
118
                'title' => $this->lang['stractions'],
119
            ],
120
            'comment'     => [
121
                'title' => $this->lang['strcomment'],
122
                'field' => Decorator::field('nspcomment'),
123
            ],
124
        ];
125
126
        $actions = [
127
            'multiactions' => [
128
                'keycols' => ['nsp' => 'nspname'],
129
                'url'     => 'schemas',
130
            ],
131
            'drop'         => [
132
                'content'     => $this->lang['strdrop'],
133
                'attr'        => [
134
                    'href' => [
135
                        'url'     => 'schemas',
136
                        'urlvars' => [
137
                            'action' => 'drop',
138
                            'nsp'    => Decorator::field('nspname'),
139
                        ],
140
                    ],
141
                ],
142
                'multiaction' => 'drop',
143
            ],
144
            'privileges'   => [
145
                'content' => $this->lang['strprivileges'],
146
                'attr'    => [
147
                    'href' => [
148
                        'url'     => 'privileges',
149
                        'urlvars' => [
150
                            'subject' => 'schema',
151
                            'schema'  => Decorator::field('nspname'),
152
                        ],
153
                    ],
154
                ],
155
            ],
156
            'alter'        => [
157
                'content' => $this->lang['stralter'],
158
                'attr'    => [
159
                    'href' => [
160
                        'url'     => 'schemas',
161
                        'urlvars' => [
162
                            'action' => 'alter',
163
                            'schema' => Decorator::field('nspname'),
164
                        ],
165
                    ],
166
                ],
167
            ],
168
        ];
169
170
        if (!$data->hasAlterSchema()) {
171
            unset($actions['alter']);
172
        }
173
174
        echo $this->printTable($schemas, $columns, $actions, 'schemas-schemas', $this->lang['strnoschemas']);
175
176
        $this->printNavLinks(['create' => [
177
            'attr'    => [
178
                'href' => [
179
                    'url'     => 'schemas',
180
                    'urlvars' => [
181
                        'action'   => 'create',
182
                        'server'   => $_REQUEST['server'],
183
                        'database' => $_REQUEST['database'],
184
                    ],
185
                ],
186
            ],
187
            'content' => $this->lang['strcreateschema'],
188
        ]], 'schemas-schemas', get_defined_vars());
189
    }
190
191
    /**
192
     * Generate XML for the browser tree.
193
     */
194
    public function doTree()
195
    {
196
        $data = $this->misc->getDatabaseAccessor();
197
198
        $schemas = $data->getSchemas();
199
200
        $reqvars = $this->misc->getRequestVars('schema');
201
202
        //$this->prtrace($reqvars);
203
204
        $attrs = [
205
            'text'    => Decorator::field('nspname'),
206
            'icon'    => 'Schema',
207
            'toolTip' => Decorator::field('nspcomment'),
208
            'action'  => Decorator::redirecturl(
209
                'redirect',
210
                $reqvars,
211
                [
212
                    'subject' => 'schema',
213
                    'schema'  => Decorator::field('nspname'),
214
                ]
215
            ),
216
            'branch'  => Decorator::url(
217
                'schemas',
218
                $reqvars,
219
                [
220
                    'action' => 'subtree',
221
                    'schema' => Decorator::field('nspname'),
222
                ]
223
            ),
224
        ];
225
226
        return $this->printTree($schemas, $attrs, 'schemas');
227
    }
228
229
    public function doSubTree()
230
    {
231
        $tabs = $this->misc->getNavTabs('schema');
232
233
        $items = $this->adjustTabsForTree($tabs);
234
235
        $reqvars = $this->misc->getRequestVars('schema');
236
237
        //$this->prtrace($reqvars);
238
239
        $attrs = [
240
            'text'   => Decorator::field('title'),
241
            'icon'   => Decorator::field('icon'),
242
            'action' => Decorator::actionurl(
243
                Decorator::field('url'),
244
                $reqvars,
245
                Decorator::field('urlvars', [])
246
            ),
247
            'branch' => Decorator::url(
248
                Decorator::field('url'),
249
                $reqvars,
250
                Decorator::field('urlvars'),
251
                ['action' => 'tree']
252
            ),
253
        ];
254
255
        return $this->printTree($items, $attrs, 'schema');
256
    }
257
258
    /**
259
     * Displays a screen where they can enter a new schema.
260
     *
261
     * @param mixed $msg
262
     */
263
    public function doCreate($msg = '')
264
    {
265
        $data = $this->misc->getDatabaseAccessor();
266
267
        $server_info = $this->misc->getServerInfo();
268
269
        $this->coalesceArr($_POST, 'formName', '');
270
271
        $this->coalesceArr($_POST, 'formAuth', $server_info['username']);
272
273
        $this->coalesceArr($_POST, 'formSpc', '');
274
275
        $this->coalesceArr($_POST, 'formComment', '');
276
277
        // Fetch all users from the database
278
        $users = $data->getUsers();
279
280
        $this->printTrail('database');
281
        $this->printTitle($this->lang['strcreateschema'], 'pg.schema.create');
282
        $this->printMsg($msg);
283
284
        echo '<form action="' . \SUBFOLDER . '/src/views/schemas" method="post">' . "\n";
285
        echo "<table style=\"width: 100%\">\n";
286
        echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strname']}</th>\n";
287
        echo "\t\t<td class=\"data1\"><input name=\"formName\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"",
288
        htmlspecialchars($_POST['formName']), "\" /></td>\n\t</tr>\n";
289
        // Owner
290
        echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strowner']}</th>\n";
291
        echo "\t\t<td class=\"data1\">\n\t\t\t<select name=\"formAuth\">\n";
292
        while (!$users->EOF) {
293
            $uname = htmlspecialchars($users->fields['usename']);
294
            echo "\t\t\t\t<option value=\"{$uname}\"",
295
            ($uname == $_POST['formAuth']) ? ' selected="selected"' : '', ">{$uname}</option>\n";
296
            $users->moveNext();
297
        }
298
        echo "\t\t\t</select>\n\t\t</td>\n\t</tr>\n";
299
        echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strcomment']}</th>\n";
300
        echo "\t\t<td class=\"data1\"><textarea name=\"formComment\" rows=\"3\" cols=\"32\">",
301
        htmlspecialchars($_POST['formComment']), "</textarea></td>\n\t</tr>\n";
302
303
        echo "</table>\n";
304
        echo "<p>\n";
305
        echo "<input type=\"hidden\" name=\"action\" value=\"create\" />\n";
306
        echo '<input type="hidden" name="database" value="', htmlspecialchars($_REQUEST['database']), "\" />\n";
307
        echo $this->misc->form;
308
        echo "<input type=\"submit\" name=\"create\" value=\"{$this->lang['strcreate']}\" />\n";
309
        echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />\n";
310
        echo "</p>\n";
311
        echo "</form>\n";
312
    }
313
314
    /**
315
     * Actually creates the new schema in the database.
316
     */
317
    public function doSaveCreate()
318
    {
319
        $data = $this->misc->getDatabaseAccessor();
320
321
        // Check that they've given a name
322
        if ('' == $_POST['formName']) {
323
            $this->doCreate($this->lang['strschemaneedsname']);
324
        } else {
325
            $status = $data->createSchema($_POST['formName'], $_POST['formAuth'], $_POST['formComment']);
326
            if (0 == $status) {
327
                $this->misc->setReloadBrowser(true);
328
                $this->doDefault($this->lang['strschemacreated']);
329
            } else {
330
                $this->doCreate($this->lang['strschemacreatedbad']);
331
            }
332
        }
333
    }
334
335
    /**
336
     * Display a form to permit editing schema properies.
337
     * TODO: permit changing owner.
338
     *
339
     * @param mixed $msg
340
     */
341
    public function doAlter($msg = '')
342
    {
343
        $data = $this->misc->getDatabaseAccessor();
344
345
        $this->printTrail('schema');
346
        $this->printTitle($this->lang['stralter'], 'pg.schema.alter');
347
        $this->printMsg($msg);
348
349
        $schema = $data->getSchemaByName($_REQUEST['schema']);
350
        if ($schema->recordCount() > 0) {
351
            $this->coalesceArr($_POST, 'comment', $schema->fields['nspcomment']);
352
353
            $this->coalesceArr($_POST, 'schema', $_REQUEST['schema']);
354
355
            $this->coalesceArr($_POST, 'name', $_REQUEST['schema']);
356
357
            $this->coalesceArr($_POST, 'owner', $schema->fields['ownername']);
358
359
            echo '<form action="' . \SUBFOLDER . '/src/views/schemas" method="post">' . "\n";
360
            echo "<table>\n";
361
362
            echo "\t<tr>\n";
363
            echo "\t\t<th class=\"data left required\">{$this->lang['strname']}</th>\n";
364
            echo "\t\t<td class=\"data1\">";
365
            echo "\t\t\t<input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"",
366
            htmlspecialchars($_POST['name']), "\" />\n";
367
            echo "\t\t</td>\n";
368
            echo "\t</tr>\n";
369
370
            if ($data->hasAlterSchemaOwner()) {
371
                $users = $data->getUsers();
372
                echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>\n";
373
                echo '<td class="data2"><select name="owner">';
374
                while (!$users->EOF) {
375
                    $uname = $users->fields['usename'];
376
                    echo '<option value="', htmlspecialchars($uname), '"',
377
                    ($uname == $_POST['owner']) ? ' selected="selected"' : '', '>', htmlspecialchars($uname), "</option>\n";
378
                    $users->moveNext();
379
                }
380
                echo "</select></td></tr>\n";
381
            } else {
382
                echo "<input name=\"owner\" value=\"{$_POST['owner']}\" type=\"hidden\" />";
383
            }
384
385
            echo "\t<tr>\n";
386
            echo "\t\t<th class=\"data\">{$this->lang['strcomment']}</th>\n";
387
            echo "\t\t<td class=\"data1\"><textarea cols=\"32\" rows=\"3\" name=\"comment\">", htmlspecialchars($_POST['comment']), "</textarea></td>\n";
388
            echo "\t</tr>\n";
389
            echo "</table>\n";
390
            echo "<p><input type=\"hidden\" name=\"action\" value=\"alter\" />\n";
391
            echo '<input type="hidden" name="schema" value="', htmlspecialchars($_POST['schema']), "\" />\n";
392
            echo $this->misc->form;
393
            echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />\n";
394
            echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>\n";
395
            echo "</form>\n";
396
        } else {
397
            echo "<p>{$this->lang['strnodata']}</p>\n";
398
        }
399
    }
400
401
    /**
402
     * Save the form submission containing changes to a schema.
403
     *
404
     * @param mixed $msg
405
     */
406
    public function doSaveAlter()
407
    {
408
        $data = $this->misc->getDatabaseAccessor();
409
410
        $status = $data->updateSchema($_POST['schema'], $_POST['comment'], $_POST['name'], $_POST['owner']);
411
        if (0 == $status) {
412
            $this->misc->setReloadBrowser(true);
413
            $this->doDefault($this->lang['strschemaaltered']);
414
        } else {
415
            $this->doAlter($this->lang['strschemaalteredbad']);
416
        }
417
    }
418
419
    /**
420
     * Show confirmation of drop and perform actual drop.
421
     *
422
     * @param mixed $confirm
423
     */
424
    public function doDrop($confirm)
425
    {
426
        $data = $this->misc->getDatabaseAccessor();
427
428
        if (empty($_REQUEST['nsp']) && empty($_REQUEST['ma'])) {
429
            return $this->doDefault($this->lang['strspecifyschematodrop']);
430
        }
431
432
        if ($confirm) {
433
            $this->printTrail('schema');
434
            $this->printTitle($this->lang['strdrop'], 'pg.schema.drop');
435
436
            echo '<form action="' . \SUBFOLDER . '/src/views/schemas" method="post">' . "\n";
437
            //If multi drop
438
            if (isset($_REQUEST['ma'])) {
439
                foreach ($_REQUEST['ma'] as $v) {
440
                    $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES));
441
                    echo '<p>', sprintf($this->lang['strconfdropschema'], $this->misc->printVal($a['nsp'])), "</p>\n";
442
                    echo '<input type="hidden" name="nsp[]" value="', htmlspecialchars($a['nsp']), "\" />\n";
443
                }
444
            } else {
445
                echo '<p>', sprintf($this->lang['strconfdropschema'], $this->misc->printVal($_REQUEST['nsp'])), "</p>\n";
446
                echo '<input type="hidden" name="nsp" value="', htmlspecialchars($_REQUEST['nsp']), "\" />\n";
447
            }
448
449
            echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>\n";
450
            echo "<p><input type=\"hidden\" name=\"action\" value=\"drop\" />\n";
451
            echo '<input type="hidden" name="database" value="', htmlspecialchars($_REQUEST['database']), "\" />\n";
452
            echo $this->misc->form;
453
            echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />\n";
454
            echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>\n";
455
            echo "</form>\n";
456
        } else {
457
            if (is_array($_POST['nsp'])) {
458
                $msg    = '';
459
                $status = $data->beginTransaction();
460
                if (0 == $status) {
461
                    foreach ($_POST['nsp'] as $s) {
462
                        $status = $data->dropSchema($s, isset($_POST['cascade']));
463
                        if (0 == $status) {
464
                            $msg .= sprintf('%s: %s<br />', htmlentities($s, ENT_QUOTES, 'UTF-8'), $this->lang['strschemadropped']);
465
                        } else {
466
                            $data->endTransaction();
467
                            $this->doDefault(sprintf('%s%s: %s<br />', $msg, htmlentities($s, ENT_QUOTES, 'UTF-8'), $this->lang['strschemadroppedbad']));
468
469
                            return;
470
                        }
471
                    }
472
                }
473
                if (0 == $data->endTransaction()) {
474
                    // Everything went fine, back to the Default page....
475
                    $this->misc->setReloadBrowser(true);
476
                    $this->doDefault($msg);
477
                } else {
478
                    $this->doDefault($this->lang['strschemadroppedbad']);
479
                }
480
            } else {
481
                $status = $data->dropSchema($_POST['nsp'], isset($_POST['cascade']));
482
                if (0 == $status) {
483
                    $this->misc->setReloadBrowser(true);
484
                    $this->doDefault($this->lang['strschemadropped']);
485
                } else {
486
                    $this->doDefault($this->lang['strschemadroppedbad']);
487
                }
488
            }
489
        }
490
    }
491
492
    /**
493
     * Displays options for database download.
494
     *
495
     * @param mixed $msg
496
     */
497
    public function doExport($msg = '')
498
    {
499
        $data = $this->misc->getDatabaseAccessor();
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
500
501
        $this->printTrail('schema');
502
        $this->printTabs('schema', 'export');
503
        $this->printMsg($msg);
504
505
        echo '<form action="' . \SUBFOLDER . '/src/views/dbexport" method="post">' . "\n";
506
507
        echo "<table>\n";
508
        echo "<tr><th class=\"data\">{$this->lang['strformat']}</th><th class=\"data\" colspan=\"2\">{$this->lang['stroptions']}</th></tr>\n";
509
        // Data only
510
        echo '<tr><th class="data left" rowspan="2">';
511
        echo "<input type=\"radio\" id=\"what1\" name=\"what\" value=\"dataonly\" checked=\"checked\" /><label for=\"what1\">{$this->lang['strdataonly']}</label></th>\n";
512
        echo "<td>{$this->lang['strformat']}</td>\n";
513
        echo "<td><select name=\"d_format\">\n";
514
        echo "<option value=\"copy\">COPY</option>\n";
515
        echo "<option value=\"sql\">SQL</option>\n";
516
        echo "</select>\n</td>\n</tr>\n";
517
        echo "<tr><td><label for=\"d_oids\">{$this->lang['stroids']}</label></td><td><input type=\"checkbox\" id=\"d_oids\" name=\"d_oids\" /></td>\n</tr>\n";
518
        // Structure only
519
        echo "<tr><th class=\"data left\"><input type=\"radio\" id=\"what2\" name=\"what\" value=\"structureonly\" /><label for=\"what2\">{$this->lang['strstructureonly']}</label></th>\n";
520
        echo "<td><label for=\"s_clean\">{$this->lang['strdrop']}</label></td><td><input type=\"checkbox\" id=\"s_clean\" name=\"s_clean\" /></td>\n</tr>\n";
521
        // Structure and data
522
        echo '<tr><th class="data left" rowspan="3">';
523
        echo "<input type=\"radio\" id=\"what3\" name=\"what\" value=\"structureanddata\" /><label for=\"what3\">{$this->lang['strstructureanddata']}</label></th>\n";
524
        echo "<td>{$this->lang['strformat']}</td>\n";
525
        echo "<td><select name=\"sd_format\">\n";
526
        echo "<option value=\"copy\">COPY</option>\n";
527
        echo "<option value=\"sql\">SQL</option>\n";
528
        echo "</select>\n</td>\n</tr>\n";
529
        echo "<tr><td><label for=\"sd_clean\">{$this->lang['strdrop']}</label></td><td><input type=\"checkbox\" id=\"sd_clean\" name=\"sd_clean\" /></td>\n</tr>\n";
530
        echo "<tr><td><label for=\"sd_oids\">{$this->lang['stroids']}</label></td><td><input type=\"checkbox\" id=\"sd_oids\" name=\"sd_oids\" /></td>\n</tr>\n";
531
        echo "</table>\n";
532
533
        echo "<h3>{$this->lang['stroptions']}</h3>\n";
534
        echo "<p><input type=\"radio\" id=\"output1\" name=\"output\" value=\"show\" checked=\"checked\" /><label for=\"output1\">{$this->lang['strshow']}</label>\n";
535
        echo "<br/><input type=\"radio\" id=\"output2\" name=\"output\" value=\"download\" /><label for=\"output2\">{$this->lang['strdownload']}</label>\n";
536
        // MSIE cannot download gzip in SSL mode - it's just broken
537
        if (!(strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && isset($_SERVER['HTTPS']))) {
538
            echo "<br /><input type=\"radio\" id=\"output3\" name=\"output\" value=\"gzipped\" /><label for=\"output3\">{$this->lang['strdownloadgzipped']}</label>\n";
539
        }
540
        echo "</p>\n";
541
        echo "<p><input type=\"hidden\" name=\"action\" value=\"export\" />\n";
542
        echo "<input type=\"hidden\" name=\"subject\" value=\"schema\" />\n";
543
        echo '<input type="hidden" name="database" value="', htmlspecialchars($_REQUEST['database']), "\" />\n";
544
        echo '<input type="hidden" name="schema" value="', htmlspecialchars($_REQUEST['schema']), "\" />\n";
545
        echo $this->misc->form;
546
        echo "<input type=\"submit\" value=\"{$this->lang['strexport']}\" /></p>\n";
547
        echo "</form>\n";
548
    }
549
}
550