Passed
Push — develop ( 7eecac...7414a0 )
by Felipe
03:57
created

TblpropertiesController::doDefault()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 131
Code Lines 91

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 91
dl 0
loc 131
rs 8.1963
c 0
b 0
f 0
cc 2
nc 2
nop 1

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * PHPPgAdmin v6.0.0-beta.50
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 TblpropertiesController extends BaseController
17
{
18
    use \PHPPgAdmin\Traits\ExportTrait;
19
    public $controller_title = 'strtables';
20
21
    /**
22
     * Default method to render the controller according to the action parameter.
23
     */
24
    public function render()
25
    {
26
        if ('tree' == $this->action) {
27
            return $this->doTree();
28
        }
29
30
        $header_template = 'header.twig';
31
32
        ob_start();
33
        switch ($this->action) {
34
            case 'alter':
35
                if (isset($_POST['alter'])) {
36
                    $this->doSaveAlter();
37
                } else {
38
                    $this->doDefault();
39
                }
40
41
                break;
42
            case 'confirm_alter':
43
                $this->doAlter();
44
45
                break;
46
            case 'import':
47
                $this->doImport();
48
49
                break;
50
            case 'export':
51
                $this->doExport();
52
53
                break;
54
            case 'add_column':
55
                if (isset($_POST['cancel'])) {
56
                    $this->doDefault();
57
                } else {
58
                    $header_template = 'header_select2.twig';
59
                    $this->doAddColumn();
60
                }
61
62
                break;
63
                /*case 'properties':
64
                if (isset($_POST['cancel'])) {
65
                $this->doDefault();
66
                } else {
67
                $this->doProperties();
68
                }*/
69
70
                break;
71
            case 'drop':
72
                if (isset($_POST['drop'])) {
73
                    $this->doDrop(false);
74
                } else {
75
                    $this->doDefault();
76
                }
77
78
                break;
79
            case 'confirm_drop':
80
                $this->doDrop(true);
81
82
                break;
83
            default:
84
                $this->doDefault();
85
86
                break;
87
        }
88
89
        $output = ob_get_clean();
90
91
        $this->printHeader($this->headerTitle('', '', $_REQUEST['table']), null, true, $header_template);
92
        $this->printBody();
93
94
        echo $output;
95
96
        return $this->printFooter();
97
    }
98
99
    /**
100
     * Show default list of columns in the table.
101
     *
102
     * @param mixed $msg
103
     */
104
    public function doDefault($msg = '')
105
    {
106
        $misc       = $this->misc;
107
        $this->data = $misc->getDatabaseAccessor();
108
109
        $this->printTrail('table');
110
        $this->printTabs('table', 'columns');
111
        $this->printMsg($msg);
112
113
        // Get table
114
        $tdata = $this->data->getTable($_REQUEST['table']);
115
        // Get columns
116
        $attrs = $this->data->getTableAttributes($_REQUEST['table']);
117
        // Get constraints keys
118
        $ck = $this->data->getConstraintsWithFields($_REQUEST['table']);
119
120
        // Show comment if any
121
        if (null !== $tdata->fields['relcomment']) {
122
            echo '<p class="comment">', $misc->printVal($tdata->fields['relcomment']), '</p>'.PHP_EOL;
123
        }
124
        $this->_printTable($ck, $attrs);
125
126
        $navlinks = [
127
            'browse'    => [
128
                'attr'    => [
129
                    'href' => [
130
                        'url'     => 'display',
131
                        'urlvars' => [
132
                            'server'   => $_REQUEST['server'],
133
                            'database' => $_REQUEST['database'],
134
                            'schema'   => $_REQUEST['schema'],
135
                            'table'    => $_REQUEST['table'],
136
                            'subject'  => 'table',
137
                            'return'   => 'table',
138
                        ],
139
                    ],
140
                ],
141
                'content' => $this->lang['strbrowse'],
142
            ],
143
            'select'    => [
144
                'attr'    => [
145
                    'href' => [
146
                        'url'     => 'tables',
147
                        'urlvars' => [
148
                            'action'   => 'confselectrows',
149
                            'server'   => $_REQUEST['server'],
150
                            'database' => $_REQUEST['database'],
151
                            'schema'   => $_REQUEST['schema'],
152
                            'table'    => $_REQUEST['table'],
153
                        ],
154
                    ],
155
                ],
156
                'content' => $this->lang['strselect'],
157
            ],
158
            'insert'    => [
159
                'attr'    => [
160
                    'href' => [
161
                        'url'     => 'tables',
162
                        'urlvars' => [
163
                            'action'   => 'confinsertrow',
164
                            'server'   => $_REQUEST['server'],
165
                            'database' => $_REQUEST['database'],
166
                            'schema'   => $_REQUEST['schema'],
167
                            'table'    => $_REQUEST['table'],
168
                        ],
169
                    ],
170
                ],
171
                'content' => $this->lang['strinsert'],
172
            ],
173
            'empty'     => [
174
                'attr'    => [
175
                    'href' => [
176
                        'url'     => 'tables',
177
                        'urlvars' => [
178
                            'action'   => 'confirm_empty',
179
                            'server'   => $_REQUEST['server'],
180
                            'database' => $_REQUEST['database'],
181
                            'schema'   => $_REQUEST['schema'],
182
                            'table'    => $_REQUEST['table'],
183
                        ],
184
                    ],
185
                ],
186
                'content' => $this->lang['strempty'],
187
            ],
188
            'drop'      => [
189
                'attr'    => [
190
                    'href' => [
191
                        'url'     => 'tables',
192
                        'urlvars' => [
193
                            'action'   => 'confirm_drop',
194
                            'server'   => $_REQUEST['server'],
195
                            'database' => $_REQUEST['database'],
196
                            'schema'   => $_REQUEST['schema'],
197
                            'table'    => $_REQUEST['table'],
198
                        ],
199
                    ],
200
                ],
201
                'content' => $this->lang['strdrop'],
202
            ],
203
            'addcolumn' => [
204
                'attr'    => [
205
                    'href' => [
206
                        'url'     => 'tblproperties',
207
                        'urlvars' => [
208
                            'action'   => 'add_column',
209
                            'server'   => $_REQUEST['server'],
210
                            'database' => $_REQUEST['database'],
211
                            'schema'   => $_REQUEST['schema'],
212
                            'table'    => $_REQUEST['table'],
213
                        ],
214
                    ],
215
                ],
216
                'content' => $this->lang['straddcolumn'],
217
            ],
218
            'alter'     => [
219
                'attr'    => [
220
                    'href' => [
221
                        'url'     => 'tblproperties',
222
                        'urlvars' => [
223
                            'action'   => 'confirm_alter',
224
                            'server'   => $_REQUEST['server'],
225
                            'database' => $_REQUEST['database'],
226
                            'schema'   => $_REQUEST['schema'],
227
                            'table'    => $_REQUEST['table'],
228
                        ],
229
                    ],
230
                ],
231
                'content' => $this->lang['stralter'],
232
            ],
233
        ];
234
        $this->printNavLinks($navlinks, 'tblproperties-tblproperties', get_defined_vars());
235
    }
236
237
    public function doTree()
238
    {
239
        $misc = $this->misc;
240
        $data = $misc->getDatabaseAccessor();
241
242
        $columns = $data->getTableAttributes($_REQUEST['table']);
243
        $reqvars = $misc->getRequestVars('column');
244
245
        $attrs = [
246
            'text'       => Decorator::field('attname'),
247
            'action'     => Decorator::actionurl(
248
                'colproperties',
249
                $reqvars,
250
                [
251
                    'table'  => $_REQUEST['table'],
252
                    'column' => Decorator::field('attname'),
253
                ]
254
            ),
255
            'icon'       => 'Column',
256
            'iconAction' => Decorator::url(
257
                'display',
258
                $reqvars,
259
                [
260
                    'table'  => $_REQUEST['table'],
261
                    'column' => Decorator::field('attname'),
262
                    'query'  => Decorator::replace(
263
                        'SELECT "%column%", count(*) AS "count" FROM "%table%" GROUP BY "%column%" ORDER BY "%column%"',
264
                        [
265
                            '%column%' => Decorator::field('attname'),
266
                            '%table%'  => $_REQUEST['table'],
267
                        ]
268
                    ),
269
                ]
270
            ),
271
            'toolTip'    => Decorator::field('comment'),
272
        ];
273
274
        return $this->printTree($columns, $attrs, 'tblcolumns');
275
    }
276
277
    public function doSaveAlter()
278
    {
279
        $misc = $this->misc;
280
        $data = $misc->getDatabaseAccessor();
281
282
        // For databases that don't allow owner change
283
        $this->coalesceArr($_POST, 'owner', '');
284
285
        // Default tablespace to null if it isn't set
286
        $this->coalesceArr($_POST, 'tablespace', null);
287
288
        $this->coalesceArr($_POST, 'newschema', null);
289
290
        $status = $data->alterTable($_POST['table'], $_POST['name'], $_POST['owner'], $_POST['newschema'], $_POST['comment'], $_POST['tablespace']);
291
        if (0 == $status) {
292
            // If table has been renamed, need to change to the new name and
293
            // reload the browser frame.
294
            if ($_POST['table'] != $_POST['name']) {
295
                // Jump them to the new table name
296
                $_REQUEST['table'] = $_POST['name'];
297
                // Force a browser reload
298
                $misc->setReloadBrowser(true);
299
            }
300
            // If schema has changed, need to change to the new schema and reload the browser
301
            if (!empty($_POST['newschema']) && ($_POST['newschema'] != $data->_schema)) {
302
                // Jump them to the new sequence schema
303
                $misc->setCurrentSchema($_POST['newschema']);
304
                $misc->setReloadBrowser(true);
305
            }
306
            $this->doDefault($this->lang['strtablealtered']);
307
        } else {
308
            $this->doAlter($this->lang['strtablealteredbad']);
309
        }
310
    }
311
312
    /**
313
     * Function to allow altering of a table.
314
     *
315
     * @param mixed $msg
316
     */
317
    public function doAlter($msg = '')
318
    {
319
        $misc = $this->misc;
320
        $data = $misc->getDatabaseAccessor();
321
322
        $this->printTrail('table');
323
        $this->printTitle($this->lang['stralter'], 'pg.table.alter');
324
        $this->printMsg($msg);
325
326
        // Fetch table info
327
        $table = $data->getTable($_REQUEST['table']);
328
        // Fetch all users
329
        $users       = $data->getUsers();
330
        $tablespaces = null;
331
        // Fetch all tablespaces from the database
332
        if ($data->hasTablespaces()) {
333
            $tablespaces = $data->getTablespaces(true);
334
        }
335
336
        if ($table->recordCount() > 0) {
337
            $this->coalesceArr($_POST, 'name', $table->fields['relname']);
338
339
            $this->coalesceArr($_POST, 'owner', $table->fields['relowner']);
340
341
            $this->coalesceArr($_POST, 'newschema', $table->fields['nspname']);
342
343
            $this->coalesceArr($_POST, 'comment', $table->fields['relcomment']);
344
345
            if ($data->hasTablespaces() && !isset($_POST['tablespace'])) {
346
                $_POST['tablespace'] = $table->fields['tablespace'];
347
            }
348
349
            echo '<form action="'.\SUBFOLDER.'/src/views/tblproperties" method="post">'.PHP_EOL;
350
            echo '<table>'.PHP_EOL;
351
            echo "<tr><th class=\"data left required\">{$this->lang['strname']}</th>".PHP_EOL;
352
            echo '<td class="data1">';
353
            echo "<input name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"",
354
            htmlspecialchars($_POST['name'], ENT_QUOTES), '" /></td></tr>'.PHP_EOL;
355
356
            if ($data->isSuperUser()) {
357
                echo "<tr><th class=\"data left required\">{$this->lang['strowner']}</th>".PHP_EOL;
358
                echo '<td class="data1"><select name="owner">';
359
                while (!$users->EOF) {
360
                    $uname = $users->fields['usename'];
361
                    echo '<option value="', htmlspecialchars($uname), '"',
362
                    ($uname == $_POST['owner']) ? ' selected="selected"' : '', '>', htmlspecialchars($uname), '</option>'.PHP_EOL;
363
                    $users->moveNext();
364
                }
365
                echo '</select></td></tr>'.PHP_EOL;
366
            }
367
368
            if ($data->hasAlterTableSchema()) {
369
                $schemas = $data->getSchemas();
370
                echo "<tr><th class=\"data left required\">{$this->lang['strschema']}</th>".PHP_EOL;
371
                echo '<td class="data1"><select name="newschema">';
372
                while (!$schemas->EOF) {
373
                    $schema = $schemas->fields['nspname'];
374
                    echo '<option value="', htmlspecialchars($schema), '"',
375
                    ($schema == $_POST['newschema']) ? ' selected="selected"' : '', '>', htmlspecialchars($schema), '</option>'.PHP_EOL;
376
                    $schemas->moveNext();
377
                }
378
                echo '</select></td></tr>'.PHP_EOL;
379
            }
380
381
            // Tablespace (if there are any)
382
            if ($data->hasTablespaces() && $tablespaces->recordCount() > 0) {
383
                echo "\t<tr>\n\t\t<th class=\"data left\">{$this->lang['strtablespace']}</th>".PHP_EOL;
384
                echo "\t\t<td class=\"data1\">\n\t\t\t<select name=\"tablespace\">".PHP_EOL;
385
                // Always offer the default (empty) option
386
                echo "\t\t\t\t<option value=\"\"",
387
                ('' == $_POST['tablespace']) ? ' selected="selected"' : '', '></option>'.PHP_EOL;
388
                // Display all other tablespaces
389
                while (!$tablespaces->EOF) {
390
                    $spcname = htmlspecialchars($tablespaces->fields['spcname']);
391
                    echo "\t\t\t\t<option value=\"{$spcname}\"",
392
                    ($spcname == $_POST['tablespace']) ? ' selected="selected"' : '', ">{$spcname}</option>".PHP_EOL;
393
                    $tablespaces->moveNext();
394
                }
395
                echo "\t\t\t</select>\n\t\t</td>\n\t</tr>".PHP_EOL;
396
            }
397
398
            echo "<tr><th class=\"data left\">{$this->lang['strcomment']}</th>".PHP_EOL;
399
            echo '<td class="data1">';
400
            echo '<textarea rows="3" cols="32" name="comment">',
401
            htmlspecialchars($_POST['comment']), '</textarea></td></tr>'.PHP_EOL;
402
            echo '</table>'.PHP_EOL;
403
            echo '<p><input type="hidden" name="action" value="alter" />'.PHP_EOL;
404
            echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL;
405
            echo $misc->form;
406
            echo "<input type=\"submit\" name=\"alter\" value=\"{$this->lang['stralter']}\" />".PHP_EOL;
407
            echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL;
408
            echo '</form>'.PHP_EOL;
409
        } else {
410
            echo "<p>{$this->lang['strnodata']}</p>".PHP_EOL;
411
        }
412
    }
413
414
    public function doExport($msg = '')
415
    {
416
        $data    = $this->misc->getDatabaseAccessor();
417
        $subject = 'table';
418
        $object  = $_REQUEST['table'];
419
        // Determine whether or not the table has an object ID
420
        $hasID = $data->hasObjectID($object);
421
        $this->prtrace('$hasID', $hasID);
422
        $this->printTrail('table');
423
        $this->printTabs('table', 'export');
424
        $this->printMsg($msg);
425
426
        echo $this->formHeader();
427
428
        // Data only
429
        echo $this->dataOnly($hasID);
430
431
        // Structure only
432
        echo $this->structureOnly();
433
        // Structure and data
434
        echo $this->structureAndData($hasID);
435
436
        echo $this->displayOrDownload();
437
438
        echo $this->formFooter($subject, $object);
439
    }
440
441
    public function doImport($msg = '')
442
    {
443
        $misc = $this->misc;
444
445
        $this->printTrail('table');
446
        $this->printTabs('table', 'import');
447
        $this->printMsg($msg);
448
449
        // Check that file uploads are enabled
450
        if (!ini_get('file_uploads')) {
451
            echo "<p>{$this->lang['strnouploads']}</p>".PHP_EOL;
452
453
            return;
454
        }
455
        // Don't show upload option if max size of uploads is zero
456
        $max_size = $misc->inisizeToBytes(ini_get('upload_max_filesize'));
457
        if (is_double($max_size) && $max_size > 0) {
458
            echo '<form action="'.\SUBFOLDER.'/src/views/dataimport" method="post" enctype="multipart/form-data">'.PHP_EOL;
459
            echo '<table>'.PHP_EOL;
460
            echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strformat']}</th>".PHP_EOL;
461
            echo "\t\t<td><select name=\"format\">".PHP_EOL;
462
            echo "\t\t\t<option value=\"auto\">{$this->lang['strauto']}</option>".PHP_EOL;
463
            echo "\t\t\t<option value=\"csv\">CSV</option>".PHP_EOL;
464
            echo "\t\t\t<option value=\"tab\">{$this->lang['strtabbed']}</option>".PHP_EOL;
465
            if (function_exists('xml_parser_create')) {
466
                echo "\t\t\t<option value=\"xml\">XML</option>".PHP_EOL;
467
            }
468
            echo "\t\t</select></td>\n\t</tr>".PHP_EOL;
469
            echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strallowednulls']}</th>".PHP_EOL;
470
            echo "\t\t<td><label><input type=\"checkbox\" name=\"allowednulls[0]\" value=\"\\N\" checked=\"checked\" />{$this->lang['strbackslashn']}</label><br />".PHP_EOL;
471
            echo "\t\t<label><input type=\"checkbox\" name=\"allowednulls[1]\" value=\"NULL\" />NULL</label><br />".PHP_EOL;
472
            echo "\t\t<label><input type=\"checkbox\" name=\"allowednulls[2]\" value=\"\" />{$this->lang['stremptystring']}</label></td>\n\t</tr>".PHP_EOL;
473
            echo "\t<tr>\n\t\t<th class=\"data left required\">{$this->lang['strfile']}</th>".PHP_EOL;
474
            echo "\t\t<td><input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"{$max_size}\" />";
475
            echo "<input type=\"file\" name=\"source\" /></td>\n\t</tr>".PHP_EOL;
476
            echo '</table>'.PHP_EOL;
477
            echo '<p><input type="hidden" name="action" value="import" />'.PHP_EOL;
478
            echo $misc->form;
479
            echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL;
480
            echo "<input type=\"submit\" value=\"{$this->lang['strimport']}\" /></p>".PHP_EOL;
481
            echo '</form>'.PHP_EOL;
482
        }
483
    }
484
485
    /**
486
     * Displays a screen where they can add a column.
487
     *
488
     * @param mixed $msg
489
     */
490
    public function doAddColumn($msg = '')
491
    {
492
        $misc = $this->misc;
493
        $data = $misc->getDatabaseAccessor();
494
495
        $this->coalesceArr($_REQUEST, 'stage', 1);
496
497
        switch ($_REQUEST['stage']) {
498
            case 1:
499
                // Set variable defaults
500
                $this->coalesceArr($_POST, 'field', '');
501
502
                $this->coalesceArr($_POST, 'type', '');
503
504
                $this->coalesceArr($_POST, 'array', '');
505
506
                $this->coalesceArr($_POST, 'length', '');
507
508
                $this->coalesceArr($_POST, 'default', '');
509
510
                $this->coalesceArr($_POST, 'comment', '');
511
512
                // Fetch all available types
513
                $types        = $data->getTypes(true, false, true);
514
                $types_for_js = [];
515
516
                $this->printTrail('table');
517
                $this->printTitle($this->lang['straddcolumn'], 'pg.column.add');
518
                $this->printMsg($msg);
519
520
                echo '<script src="'.\SUBFOLDER.'/assets/js/tables.js" type="text/javascript"></script>';
521
                echo '<form action="'.\SUBFOLDER.'/src/views/tblproperties" method="post">'.PHP_EOL;
522
523
                // Output table header
524
                echo '<table>'.PHP_EOL;
525
                echo "<tr><th class=\"data required\">{$this->lang['strname']}</th>\n<th colspan=\"2\" class=\"data required\">{$this->lang['strtype']}</th>".PHP_EOL;
526
                echo "<th class=\"data\">{$this->lang['strlength']}</th>".PHP_EOL;
527
                if ($data->hasCreateFieldWithConstraints()) {
528
                    echo "<th class=\"data\">{$this->lang['strnotnull']}</th>\n<th class=\"data\">{$this->lang['strdefault']}</th>".PHP_EOL;
529
                }
530
531
                echo "<th class=\"data\">{$this->lang['strcomment']}</th></tr>".PHP_EOL;
532
533
                echo "<tr><td><input name=\"field\" size=\"16\" maxlength=\"{$data->_maxNameLen}\" value=\"",
534
                htmlspecialchars($_POST['field']), '" /></td>'.PHP_EOL;
535
                echo "<td><select  class=\"select2\" name=\"type\" id=\"type\" onchange=\"checkLengths(document.getElementById('type').value,'');\">".PHP_EOL;
536
                // Output any "magic" types.  This came in with the alter column type so we'll check that
537
                if ($data->hasMagicTypes()) {
538
                    foreach ($data->extraTypes as $v) {
539
                        $types_for_js[] = strtolower($v);
540
                        echo "\t<option value=\"", htmlspecialchars($v), '"',
541
                        ($v == $_POST['type']) ? ' selected="selected"' : '', '>',
542
                        $misc->printVal($v), '</option>'.PHP_EOL;
543
                    }
544
                }
545
                while (!$types->EOF) {
546
                    $typname        = $types->fields['typname'];
547
                    $types_for_js[] = $typname;
548
                    echo "\t<option value=\"", htmlspecialchars($typname), '"', ($typname == $_POST['type']) ? ' selected="selected"' : '', '>',
549
                    $misc->printVal($typname), '</option>'.PHP_EOL;
550
                    $types->moveNext();
551
                }
552
                echo '</select></td>'.PHP_EOL;
553
554
                // Output array type selector
555
                echo '<td><select name="array">'.PHP_EOL;
556
                echo "\t<option value=\"\"", ('' == $_POST['array']) ? ' selected="selected"' : '', '></option>'.PHP_EOL;
557
                echo "\t<option value=\"[]\"", ('[]' == $_POST['array']) ? ' selected="selected"' : '', '>[ ]</option>'.PHP_EOL;
558
                echo '</select></td>'.PHP_EOL;
559
                $predefined_size_types = array_intersect($data->predefined_size_types, $types_for_js);
560
                $escaped_predef_types  = []; // the JS escaped array elements
561
                foreach ($predefined_size_types as $value) {
562
                    $escaped_predef_types[] = "'{$value}'";
563
                }
564
565
                echo '<td><input name="length" id="lengths" size="8" value="',
566
                htmlspecialchars($_POST['length']), '" /></td>'.PHP_EOL;
567
                // Support for adding column with not null and default
568
                if ($data->hasCreateFieldWithConstraints()) {
569
                    echo '<td><input type="checkbox" name="notnull"',
570
                    (isset($_REQUEST['notnull'])) ? ' checked="checked"' : '', ' /></td>'.PHP_EOL;
571
                    echo '<td><input name="default" size="20" value="',
572
                    htmlspecialchars($_POST['default']), '" /></td>'.PHP_EOL;
573
                }
574
                echo '<td><input name="comment" size="40" value="',
575
                htmlspecialchars($_POST['comment']), '" /></td></tr>'.PHP_EOL;
576
                echo '</table>'.PHP_EOL;
577
                echo '<p><input type="hidden" name="action" value="add_column" />'.PHP_EOL;
578
                echo '<input type="hidden" name="stage" value="2" />'.PHP_EOL;
579
                echo $misc->form;
580
                echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL;
581
                if (!$data->hasCreateFieldWithConstraints()) {
582
                    echo '<input type="hidden" name="default" value="" />'.PHP_EOL;
583
                }
584
                echo "<input type=\"submit\" value=\"{$this->lang['stradd']}\" />".PHP_EOL;
585
                echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" /></p>".PHP_EOL;
586
                echo '</form>'.PHP_EOL;
587
                echo '<script type="text/javascript">predefined_lengths = new Array('.implode(',', $escaped_predef_types).");checkLengths(document.getElementById('type').value,'');</script>".PHP_EOL;
588
589
                break;
590
            case 2:
591
                // Check inputs
592
                if ('' == trim($_POST['field'])) {
593
                    $_REQUEST['stage'] = 1;
594
                    $this->doAddColumn($this->lang['strcolneedsname']);
595
596
                    return;
597
                }
598
                $this->coalesceArr($_POST, 'length', '');
599
600
                list($status, $sql) = $data->addColumn(
601
                    $_POST['table'],
602
                    $_POST['field'],
603
                    $_POST['type'],
604
                    '' != $_POST['array'],
605
                    $_POST['length'],
606
                    isset($_POST['notnull']),
607
                    $_POST['default'],
608
                    $_POST['comment']
609
                );
610
                if (0 == $status) {
611
                    $misc->setReloadBrowser(true);
612
                    $this->doDefault(sprintf('%s %s %s', $sql, PHP_EOL, $this->lang['strcolumnadded']));
613
                } else {
614
                    $_REQUEST['stage'] = 1;
615
                    $this->doAddColumn($this->lang['strcolumnaddedbad']);
616
617
                    return;
618
                }
619
620
                break;
621
            default:
622
                echo "<p>{$this->lang['strinvalidparam']}</p>".PHP_EOL;
623
        }
624
    }
625
626
    /**
627
     * Show confirmation of drop column and perform actual drop.
628
     *
629
     * @param bool $confirm true to ask for confirmation, false to actually drop
630
     */
631
    public function doDrop($confirm = true)
632
    {
633
        $misc = $this->misc;
634
        $data = $misc->getDatabaseAccessor();
635
636
        if ($confirm) {
637
            $this->printTrail('column');
638
            $this->printTitle($this->lang['strdrop'], 'pg.column.drop');
639
640
            echo '<p>'.sprintf($this->lang['strconfdropcolumn'], $misc->printVal($_REQUEST['column']), $misc->printVal($_REQUEST['table'])).'</p>'.PHP_EOL;
641
642
            echo '<form action="'.\SUBFOLDER.'/src/views/tblproperties" method="post">'.PHP_EOL;
643
            echo '<input type="hidden" name="action" value="drop" />'.PHP_EOL;
644
            echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'.PHP_EOL;
645
            echo '<input type="hidden" name="column" value="', htmlspecialchars($_REQUEST['column']), '" />'.PHP_EOL;
646
            echo $misc->form;
647
            echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\"> <label for=\"cascade\">{$this->lang['strcascade']}</label></p>".PHP_EOL;
648
            echo "<input type=\"submit\" name=\"drop\" value=\"{$this->lang['strdrop']}\" />".PHP_EOL;
649
            echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />".PHP_EOL;
650
            echo '</form>'.PHP_EOL;
651
        } else {
652
            list($status, $sql) = $data->dropColumn($_POST['table'], $_POST['column'], isset($_POST['cascade']));
653
            if (0 == $status) {
654
                $misc->setReloadBrowser(true);
655
                $this->doDefault(sprintf('%s %s %s', $sql, PHP_EOL, $this->lang['strcolumndropped']));
656
            } else {
657
                $this->doDefault($this->lang['strcolumndroppedbad']);
658
            }
659
        }
660
    }
661
662
    private function _getAttPre($data)
663
    {
664
        $attPre = function (&$rowdata, $actions) use ($data) {
665
            $rowdata->fields['+type'] = $data->formatType($rowdata->fields['type'], $rowdata->fields['atttypmod']);
666
            $attname                  = $rowdata->fields['attname'];
667
            $table                    = $_REQUEST['table'];
668
            $data->fieldClean($attname);
669
            $data->fieldClean($table);
670
671
            $actions['browse']['attr']['href']['urlvars']['query'] = "SELECT \"{$attname}\", count(*) AS \"count\"
672
                FROM \"{$table}\" GROUP BY \"{$attname}\" ORDER BY \"{$attname}\"";
673
674
            return $actions;
675
        };
676
677
        return $attPre;
678
    }
679
680
    private function _getCstrRender($misc, $data)
681
    {
682
        $cstrRender = function ($s, $p) use ($misc, $data) {
683
            $str = '';
684
            foreach ($p['keys'] as $k => $c) {
685
                if (is_null($p['keys'][$k]['consrc'])) {
686
                    $atts        = $data->getAttributeNames($_REQUEST['table'], explode(' ', $p['keys'][$k]['indkey']));
687
                    $c['consrc'] = ('u' == $c['contype'] ? 'UNIQUE (' : 'PRIMARY KEY (').join(',', $atts).')';
688
                }
689
690
                if ($c['p_field'] == $s) {
691
                    switch ($c['contype']) {
692
                        case 'p':
693
                            $str .= '<a href="constraints?'.$misc->href.'&amp;table='.urlencode($c['p_table']).'&amp;schema='.urlencode($c['p_schema']).'"><img src="'.
694
                            $misc->icon('PrimaryKey').'" alt="[pk]" title="'.htmlentities($c['consrc'], ENT_QUOTES, 'UTF-8').'" /></a>';
695
696
                            break;
697
                        case 'f':
698
                            $str .= '<a href="tblproperties?'.$misc->href.'&amp;table='.urlencode($c['f_table']).'&amp;schema='.urlencode($c['f_schema']).'"><img src="'.
699
                            $misc->icon('ForeignKey').'" alt="[fk]" title="'.htmlentities($c['consrc'], ENT_QUOTES, 'UTF-8').'" /></a>';
700
701
                            break;
702
                        case 'u':
703
                            $str .= '<a href="constraints?'.$misc->href.'&amp;table='.urlencode($c['p_table']).'&amp;schema='.urlencode($c['p_schema']).'"><img src="'.
704
                            $misc->icon('UniqueConstraint').'" alt="[uniq]" title="'.htmlentities($c['consrc'], ENT_QUOTES, 'UTF-8').'" /></a>';
705
706
                            break;
707
                        case 'c':
708
                            $str .= '<a href="constraints?'.$misc->href.'&amp;table='.urlencode($c['p_table']).'&amp;schema='.urlencode($c['p_schema']).'"><img src="'.
709
                            $misc->icon('CheckConstraint').'" alt="[check]" title="'.htmlentities($c['consrc'], ENT_QUOTES, 'UTF-8').'" /></a>';
710
                    }
711
                }
712
            }
713
714
            return $str;
715
        };
716
717
        return $cstrRender;
718
    }
719
720
    private function _printTable($ck, $attrs)
721
    {
722
        $misc = $this->misc;
723
724
        $data = $this->data;
725
726
        $attPre = $this->_getAttPre($data);
727
728
        $cstrRender = $this->_getCstrRender($misc, $data);
729
730
        $columns = [
731
            'column'  => [
732
                'title' => $this->lang['strcolumn'],
733
                'field' => Decorator::field('attname'),
734
                'url'   => "colproperties?subject=column&amp;{$misc->href}&amp;table=".urlencode($_REQUEST['table']).'&amp;',
735
                'vars'  => ['column' => 'attname'],
736
            ],
737
            'type'    => [
738
                'title' => $this->lang['strtype'],
739
                'field' => Decorator::field('+type'),
740
            ],
741
            'notnull' => [
742
                'title'  => $this->lang['strnotnull'],
743
                'field'  => Decorator::field('attnotnull'),
744
                'type'   => 'bool',
745
                'params' => ['true' => 'NOT NULL', 'false' => ''],
746
            ],
747
            'default' => [
748
                'title' => $this->lang['strdefault'],
749
                'field' => Decorator::field('adsrc'),
750
            ],
751
            'keyprop' => [
752
                'title'  => $this->lang['strconstraints'],
753
                'class'  => 'constraint_cell',
754
                'field'  => Decorator::field('attname'),
755
                'type'   => 'callback',
756
                'params' => [
757
                    'function' => $cstrRender,
758
                    'keys'     => $ck->getArray(),
759
                ],
760
            ],
761
            'actions' => [
762
                'title' => $this->lang['stractions'],
763
            ],
764
            'comment' => [
765
                'title' => $this->lang['strcomment'],
766
                'field' => Decorator::field('comment'),
767
            ],
768
        ];
769
770
        $actions = [
771
            'browse'     => [
772
                'content' => $this->lang['strbrowse'],
773
                'attr'    => [
774
                    'href' => [
775
                        'url'     => 'display',
776
                        'urlvars' => [
777
                            'table'   => $_REQUEST['table'],
778
                            'subject' => 'column',
779
                            'return'  => 'table',
780
                            'column'  => Decorator::field('attname'),
781
                        ],
782
                    ],
783
                ],
784
            ],
785
            'alter'      => [
786
                'content' => $this->lang['stralter'],
787
                'attr'    => [
788
                    'href' => [
789
                        'url'     => 'colproperties',
790
                        'urlvars' => [
791
                            'subject' => 'column',
792
                            'action'  => 'properties',
793
                            'table'   => $_REQUEST['table'],
794
                            'column'  => Decorator::field('attname'),
795
                        ],
796
                    ],
797
                ],
798
            ],
799
            'privileges' => [
800
                'content' => $this->lang['strprivileges'],
801
                'attr'    => [
802
                    'href' => [
803
                        'url'     => 'privileges',
804
                        'urlvars' => [
805
                            'subject' => 'column',
806
                            'table'   => $_REQUEST['table'],
807
                            'column'  => Decorator::field('attname'),
808
                        ],
809
                    ],
810
                ],
811
            ],
812
            'drop'       => [
813
                'content' => $this->lang['strdrop'],
814
                'attr'    => [
815
                    'href' => [
816
                        'url'     => 'tblproperties',
817
                        'urlvars' => [
818
                            'subject' => 'column',
819
                            'action'  => 'confirm_drop',
820
                            'table'   => $_REQUEST['table'],
821
                            'column'  => Decorator::field('attname'),
822
                        ],
823
                    ],
824
                ],
825
            ],
826
        ];
827
828
        echo $this->printTable($attrs, $columns, $actions, 'tblproperties-tblproperties', $this->lang['strnodata'], $attPre);
829
    }
830
}
831