Passed
Push — develop ( ec145b...e1ceac )
by Felipe
06:24
created

ConstraintsController::formAddForeignKey()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 71
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 71
rs 8.5309
c 0
b 0
f 0
cc 5
eloc 50
nc 6
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.48
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 ConstraintsController extends BaseController
17
{
18
    use \PHPPgAdmin\Traits\FormTrait;
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->/* @scrutinizer ignore-call */doTree();
27
        }
28
29
        $this->printHeader(
30
            $this->lang['strtables'].' - '.$_REQUEST['table'].' - '.$this->lang['strconstraints'],
31
            '<script src="'.\SUBFOLDER.'/assets/js/indexes.js" type="text/javascript"></script>',
32
            true,
33
            'header_select2.twig'
34
        );
35
36
        $onloadInitActions = [
37
            'add_unique_key',
38
            'save_add_unique_key',
39
            'add_primary_key',
40
            'save_add_primary_key',
41
            'add_foreign_key',
42
            'select_referenced_columns',
43
            'save_add_foreign_key',
44
        ];
45
46
        $onloadInit = false;
47
        if (in_array($this->action, $onloadInitActions, true)) {
48
            $onloadInit = true;
49
        }
50
        $this->printBody(true, 'detailbody', $onloadInit);
51
52
        if (isset($_POST['cancel']) || ($this->action === 'drop' && !isset($_POST['drop']))) {
53
            $this->action = 'default';
54
        }
55
56
        switch ($this->action) {
57
            case 'add_foreign_key':
58
                $this->formAddForeignKey();
59
60
                break;
61
            case 'select_referenced_columns':
62
                $this->_selectFKColumns();
63
64
                break;
65
            case 'save_add_foreign_key':
66
                $this->addForeignKey();
67
68
                break;
69
            case 'add_unique_key':
70
                $this->formPrimaryOrUniqueKey('unique');
71
72
                break;
73
            case 'add_primary_key':
74
                $this->formPrimaryOrUniqueKey('primary');
75
76
                break;
77
            case 'save_add_unique_key':
78
                $this->addPrimaryOrUniqueKey('unique');
79
80
                break;
81
            case 'save_add_primary_key':
82
                $this->addPrimaryOrUniqueKey('primary');
83
84
                break;
85
            case 'add_check':
86
                $this->addCheck(true);
87
88
                break;
89
            case 'save_add_check':
90
                $this->addCheck(false);
91
92
                break;
93
            case 'drop':
94
                $this->doDrop();
95
96
                break;
97
            case 'confirm_drop':
98
                $this->printDropForm();
99
100
                break;
101
            default:
102
                $this->doDefault();
103
104
                break;
105
        }
106
107
        $this->printFooter();
108
    }
109
110
    /**
111
     * List all the constraints on the table.
112
     *
113
     * @param mixed $msg
114
     */
115
    public function doDefault($msg = '')
116
    {
117
        $data = $this->misc->getDatabaseAccessor();
118
119
        $cnPre = function (&$rowdata) use ($data) {
120
            if (is_null($rowdata->fields['consrc'])) {
121
                $atts                           = $data->getAttributeNames($_REQUEST['table'], explode(' ', $rowdata->fields['indkey']));
122
                $rowdata->fields['+definition'] = ('u' == $rowdata->fields['contype'] ? 'UNIQUE (' : 'PRIMARY KEY (').join(',', $atts).')';
123
            } else {
124
                $rowdata->fields['+definition'] = $rowdata->fields['consrc'];
125
            }
126
        };
127
128
        $this->printTrail('table');
129
        $this->printTabs('table', 'constraints');
130
        $this->printMsg($msg);
131
132
        $constraints = $data->getConstraints($_REQUEST['table']);
133
134
        $columns = [
135
            'constraint' => [
136
                'title' => $this->lang['strname'],
137
                'field' => Decorator::field('conname'),
138
            ],
139
            'definition' => [
140
                'title' => $this->lang['strdefinition'],
141
                'field' => Decorator::field('+definition'),
142
                'type'  => 'pre',
143
            ],
144
            'actions'    => [
145
                'title' => $this->lang['stractions'],
146
            ],
147
            'comment'    => [
148
                'title' => $this->lang['strcomment'],
149
                'field' => Decorator::field('constcomment'),
150
            ],
151
        ];
152
153
        $actions = [
154
            'drop' => [
155
                'content' => $this->lang['strdrop'],
156
                'attr'    => [
157
                    'href' => [
158
                        'url'     => 'constraints',
159
                        'urlvars' => [
160
                            'action'     => 'confirm_drop',
161
                            'table'      => $_REQUEST['table'],
162
                            'constraint' => Decorator::field('conname'),
163
                            'type'       => Decorator::field('contype'),
164
                        ],
165
                    ],
166
                ],
167
            ],
168
        ];
169
170
        echo $this->printTable($constraints, $columns, $actions, 'constraints-constraints', $this->lang['strnoconstraints'], $cnPre);
171
172
        $navlinks = [
173
            'addcheck' => [
174
                'attr'    => [
175
                    'href' => [
176
                        'url'     => 'constraints',
177
                        'urlvars' => [
178
                            'action'   => 'add_check',
179
                            'server'   => $_REQUEST['server'],
180
                            'database' => $_REQUEST['database'],
181
                            'schema'   => $_REQUEST['schema'],
182
                            'table'    => $_REQUEST['table'],
183
                        ],
184
                    ],
185
                ],
186
                'content' => $this->lang['straddcheck'],
187
            ],
188
            'adduniq'  => [
189
                'attr'    => [
190
                    'href' => [
191
                        'url'     => 'constraints',
192
                        'urlvars' => [
193
                            'action'   => 'add_unique_key',
194
                            'server'   => $_REQUEST['server'],
195
                            'database' => $_REQUEST['database'],
196
                            'schema'   => $_REQUEST['schema'],
197
                            'table'    => $_REQUEST['table'],
198
                        ],
199
                    ],
200
                ],
201
                'content' => $this->lang['stradduniq'],
202
            ],
203
            'addpk'    => [
204
                'attr'    => [
205
                    'href' => [
206
                        'url'     => 'constraints',
207
                        'urlvars' => [
208
                            'action'   => 'add_primary_key',
209
                            'server'   => $_REQUEST['server'],
210
                            'database' => $_REQUEST['database'],
211
                            'schema'   => $_REQUEST['schema'],
212
                            'table'    => $_REQUEST['table'],
213
                        ],
214
                    ],
215
                ],
216
                'content' => $this->lang['straddpk'],
217
            ],
218
            'addfk'    => [
219
                'attr'    => [
220
                    'href' => [
221
                        'url'     => 'constraints',
222
                        'urlvars' => [
223
                            'action'   => 'add_foreign_key',
224
                            'server'   => $_REQUEST['server'],
225
                            'database' => $_REQUEST['database'],
226
                            'schema'   => $_REQUEST['schema'],
227
                            'table'    => $_REQUEST['table'],
228
                        ],
229
                    ],
230
                ],
231
                'content' => $this->lang['straddfk'],
232
            ],
233
        ];
234
        $this->printNavLinks($navlinks, 'constraints-constraints', get_defined_vars());
235
    }
236
237
    /**
238
     * Prints the first step to create an FK.
239
     *
240
     * @param string $msg The message
241
     */
242
    public function formAddForeignKey($msg = '')
243
    {
244
        $data = $this->misc->getDatabaseAccessor();
245
246
        $this->printTrail('table');
247
        $this->printTitle($this->lang['straddfk'], 'pg.constraint.foreign_key');
248
        $this->printMsg($msg);
249
250
        $attrs  = $data->getTableAttributes($_REQUEST['table']);
251
        $tables = $data->getTables(true);
252
253
        $selColumns = new \PHPPgAdmin\XHtml\XHtmlSelect('TableColumnList', true, 10);
254
        $selColumns->set_style('width: 15em;');
255
256
        if ($attrs->recordCount() > 0) {
257
            while (!$attrs->EOF) {
258
                $xmloption = new \PHPPgAdmin\XHtml\XHtmlOption($attrs->fields['attname']);
259
                $selColumns->add($xmloption);
260
                $attrs->moveNext();
261
            }
262
        }
263
264
        $selIndex = new \PHPPgAdmin\XHtml\XHtmlSelect('IndexColumnList[]', true, 10);
265
        $selIndex->set_style('width: 15em;');
266
        $selIndex->set_attribute('id', 'IndexColumnList');
267
        $buttonAdd = new \PHPPgAdmin\XHtml\XHtmlButton('add', '>>');
268
        $buttonAdd->set_attribute('onclick', 'buttonPressed(this);');
269
        $buttonAdd->set_attribute('type', 'button');
270
271
        $buttonRemove = new \PHPPgAdmin\XHtml\XHtmlButton('remove', '<<');
272
        $buttonRemove->set_attribute('onclick', 'buttonPressed(this);');
273
        $buttonRemove->set_attribute('type', 'button');
274
275
        echo "<form onsubmit=\"doSelectAll();\" name=\"formIndex\" action=\"constraints\" method=\"post\">\n";
276
277
        echo "<table>\n";
278
        echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strname']}</th></tr>\n";
279
        echo "<tr><td class=\"data1\" colspan=\"3\"><input type=\"text\" name=\"name\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" /></td></tr>\n";
280
        echo "<tr><th class=\"data\">{$this->lang['strtablecolumnlist']}</th><th class=\"data\">&nbsp;</th><th class=\"data required\">{$this->lang['strfkcolumnlist']}</th></tr>\n";
281
        echo '<tr><td class="data1">'.$selColumns->fetch()."</td>\n";
282
        echo '<td class="data1" style="text-align: center">'.$buttonRemove->fetch().$buttonAdd->fetch()."</td>\n";
283
        echo '<td class=data1>'.$selIndex->fetch()."</td></tr>\n";
284
        echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strfktarget']}</th></tr>";
285
        echo '<tr>';
286
        echo '<td class="data1" colspan="3"><select class="select2" name="target">';
287
        while (!$tables->EOF) {
288
            $key = ['schemaname' => $tables->fields['nspname'], 'tablename' => $tables->fields['relname']];
289
            $key = serialize($key);
290
            echo '<option value="', htmlspecialchars($key), '">';
291
            if ($tables->fields['nspname'] != $_REQUEST['schema']) {
292
                echo htmlspecialchars($tables->fields['nspname']), '.';
293
            }
294
            echo htmlspecialchars($tables->fields['relname']), "</option>\n";
295
            $tables->moveNext();
296
        }
297
        echo "</select>\n";
298
        echo '</td></tr>';
299
        echo "</table>\n";
300
301
        echo $this->getFormInputsAndButtons(
302
            [
303
                ['name' => 'action', 'type' => 'hidden', 'value' => 'select_referenced_columns'],
304
                ['name' => 'table', 'type' => 'hidden', 'value' => htmlspecialchars($_REQUEST['table'])],
305
            ],
306
            [
307
                ['type' => 'submit', 'name' => '', 'value' => $this->lang['stradd']],
308
                ['type' => 'submit', 'name' => 'cancel', 'value' => $this->lang['strcancel']],
309
            ]
310
        );
311
312
        echo sprintf('</form>%s', "\n");
313
    }
314
315
    /**
316
     * Prints second screen of FK creation, where you select which columns
317
     * to use in the referencing table.
318
     *
319
     * @param string $msg optional message to display
320
     */
321
    private function _selectFKColumns($msg = '')
322
    {
323
        $data = $this->misc->getDatabaseAccessor();
324
325
        $this->coalesceArr($_POST, 'name', '');
326
327
        $this->coalesceArr($_POST, 'target', '');
328
329
        // Check that they've given at least one source column
330
        if (!isset($_REQUEST['SourceColumnList']) && (!isset($_POST['IndexColumnList']) ||
331
            !is_array($_POST['IndexColumnList']) ||
332
            0 == sizeof($_POST['IndexColumnList']))) {
333
            return $this->formAddForeignKey($this->lang['strfkneedscols']);
334
        }
335
        // Copy the IndexColumnList variable from stage 1
336
        if (isset($_REQUEST['IndexColumnList']) && !isset($_REQUEST['SourceColumnList'])) {
337
            $_REQUEST['SourceColumnList'] = serialize($_REQUEST['IndexColumnList']);
338
        }
339
340
        // Initialise variables
341
        $this->coalesceArr($_POST, 'upd_action', null);
342
343
        $this->coalesceArr($_POST, 'del_action', null);
344
345
        $this->coalesceArr($_POST, 'match', null);
346
347
        $this->coalesceArr($_POST, 'deferrable', null);
348
349
        $this->coalesceArr($_POST, 'initially', null);
350
351
        $_REQUEST['target'] = unserialize($_REQUEST['target']);
352
353
        $this->printTrail('table');
354
        $this->printTitle($this->lang['straddfk'], 'pg.constraint.foreign_key');
355
        $this->printMsg($msg);
356
357
        // Unserialize target and fetch appropriate table. This is a bit messy
358
        // because the table could be in another schema.
359
        $data->setSchema($_REQUEST['target']['schemaname']);
360
        $attrs = $data->getTableAttributes($_REQUEST['target']['tablename']);
361
        $data->setSchema($_REQUEST['schema']);
362
363
        $selColumns = new \PHPPgAdmin\XHtml\XHtmlSelect('TableColumnList', true, 10);
364
        $selColumns->set_style('width: 15em;');
365
366
        if ($attrs->recordCount() > 0) {
367
            while (!$attrs->EOF) {
368
                $xmloption = new \PHPPgAdmin\XHtml\XHtmlOption($attrs->fields['attname']);
369
                $selColumns->add($xmloption);
370
                $attrs->moveNext();
371
            }
372
        }
373
374
        $selIndex = new \PHPPgAdmin\XHtml\XHtmlSelect('IndexColumnList[]', true, 10);
375
        $selIndex->set_style('width: 15em;');
376
        $selIndex->set_attribute('id', 'IndexColumnList');
377
        $buttonAdd = new \PHPPgAdmin\XHtml\XHtmlButton('add', '>>');
378
        $buttonAdd->set_attribute('onclick', 'buttonPressed(this);');
379
        $buttonAdd->set_attribute('type', 'button');
380
381
        $buttonRemove = new \PHPPgAdmin\XHtml\XHtmlButton('remove', '<<');
382
        $buttonRemove->set_attribute('onclick', 'buttonPressed(this);');
383
        $buttonRemove->set_attribute('type', 'button');
384
385
        echo "<form onsubmit=\"doSelectAll();\" name=\"formIndex\" action=\"constraints\" method=\"post\">\n";
386
387
        echo "<table>\n";
388
        echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strfktarget']}</th></tr>";
389
        echo "<tr><th class=\"data\">{$this->lang['strtablecolumnlist']}</th><th class=\"data\">&nbsp;</th><th class=data>{$this->lang['strfkcolumnlist']}</th></tr>\n";
390
        echo '<tr><td class="data1">'.$selColumns->fetch()."</td>\n";
391
        echo '<td class="data1" style="text-align: center">'.$buttonRemove->fetch().$buttonAdd->fetch().'</td>';
392
        echo '<td class="data1">'.$selIndex->fetch()."</td></tr>\n";
393
        echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['stractions']}</th></tr>";
394
        echo '<tr>';
395
        echo "<td class=\"data1\" colspan=\"3\">\n";
396
        // ON SELECT actions
397
        echo "{$this->lang['stronupdate']} <select name=\"upd_action\">";
398
        foreach ($data->fkactions as $v) {
399
            echo "<option value=\"{$v}\"", ($_POST['upd_action'] == $v) ? ' selected="selected"' : '', ">{$v}</option>\n";
400
        }
401
402
        echo "</select><br />\n";
403
404
        // ON DELETE actions
405
        echo "{$this->lang['strondelete']} <select name=\"del_action\">";
406
        foreach ($data->fkactions as $v) {
407
            echo "<option value=\"{$v}\"", ($_POST['del_action'] == $v) ? ' selected="selected"' : '', ">{$v}</option>\n";
408
        }
409
410
        echo "</select><br />\n";
411
412
        // MATCH options
413
        echo '<select name="match">';
414
        foreach ($data->fkmatches as $v) {
415
            echo "<option value=\"{$v}\"", ($_POST['match'] == $v) ? ' selected="selected"' : '', ">{$v}</option>\n";
416
        }
417
418
        echo "</select><br />\n";
419
420
        // DEFERRABLE options
421
        echo '<select name="deferrable">';
422
        foreach ($data->fkdeferrable as $v) {
423
            echo "<option value=\"{$v}\"", ($_POST['deferrable'] == $v) ? ' selected="selected"' : '', ">{$v}</option>\n";
424
        }
425
426
        echo "</select><br />\n";
427
428
        // INITIALLY options
429
        echo '<select name="initially">';
430
        foreach ($data->fkinitial as $v) {
431
            echo "<option value=\"{$v}\"", ($_POST['initially'] == $v) ? ' selected="selected"' : '', ">{$v}</option>\n";
432
        }
433
434
        echo "</select>\n";
435
        echo "</td></tr>\n";
436
        echo "</table>\n";
437
438
        echo '<p>';
439
440
        echo '<input type="hidden" name="name" value="', htmlspecialchars($_REQUEST['name']), "\" />\n";
441
        echo '<input type="hidden" name="target" value="', htmlspecialchars(serialize($_REQUEST['target'])), "\" />\n";
442
        echo '<input type="hidden" name="SourceColumnList" value="', htmlspecialchars($_REQUEST['SourceColumnList']), "\" />\n";
443
444
        echo $this->getActionTableAndButtons(
445
            'save_add_foreign_key',
446
            htmlspecialchars($_REQUEST['table']),
447
            $this->lang['stradd'],
448
            $this->lang['strcancel']
449
        );
450
451
        echo sprintf('</p>%s</form>%s', "\n", "\n");
452
    }
453
454
    /**
455
     * Perform actual creation of the FOREIGN KEY constraint.
456
     *
457
     * @param string $msg optional message to display
458
     */
459
    public function addForeignKey($msg = '')
460
    {
461
        $data = $this->misc->getDatabaseAccessor();
462
463
        $this->coalesceArr($_POST, 'name', '');
464
465
        $this->coalesceArr($_POST, 'target', '');
466
467
        $this->coalesceArr($_POST, 'SourceColumnList', 'a:0:{}');
468
469
        $this->coalesceArr($_POST, 'IndexColumnList', []);
470
471
        // Unserialize target
472
        $_POST['target'] = unserialize($_POST['target']);
473
474
        // Check that they've given at least one column
475
        $temp = unserialize($_POST['SourceColumnList']);
476
477
        // If IndexColumnList or SourceColumnList are empty, return to screen to select referencing table columns
478
        if (!is_array($_POST['IndexColumnList'])
479
            || 0 == sizeof($_POST['IndexColumnList'])
480
            || 0 == sizeof($temp)) {
481
            return $this->_selectFKColumns($this->lang['strfkneedscols']);
482
        }
483
484
        $status = $data->addForeignKey(
485
            $_POST['table'],
486
            $_POST['target']['schemaname'],
487
            $_POST['target']['tablename'],
488
            unserialize($_POST['SourceColumnList']),
489
            $_POST['IndexColumnList'],
490
            $_POST['upd_action'],
491
            $_POST['del_action'],
492
            $_POST['match'],
493
            $_POST['deferrable'],
494
            $_POST['initially'],
495
            $_POST['name']
496
        );
497
        if (0 == $status) {
498
            return $this->doDefault($this->lang['strfkadded']);
499
        }
500
501
        return $this->_selectFKColumns($this->lang['strfkaddedbad']);
502
    }
503
504
    /**
505
     * Print form to add a PRIMARY KEY or UNIQUE constraint.
506
     *
507
     * @param string $type either primary or unique
508
     * @param string $msg  optional message
509
     */
510
    public function formPrimaryOrUniqueKey($type, $msg = '')
511
    {
512
        $data = $this->misc->getDatabaseAccessor();
513
        $this->coalesceArr($_POST, 'name', '');
514
515
        $this->coalesceArr($_POST, 'tablespace', '');
516
517
        $this->printTrail('table');
518
519
        switch ($type) {
520
            case 'primary':
521
                $this->printTitle($this->lang['straddpk'], 'pg.constraint.primary_key');
522
523
                break;
524
            case 'unique':
525
                $this->printTitle($this->lang['stradduniq'], 'pg.constraint.unique_key');
526
527
                break;
528
            default:
529
                $this->doDefault($this->lang['strinvalidparam']);
530
531
                return;
532
        }
533
534
        $this->printMsg($msg);
535
536
        $attrs       = $data->getTableAttributes($_REQUEST['table']);
537
        $tablespaces = null;
538
        // Fetch all tablespaces from the database
539
        if ($data->hasTablespaces()) {
540
            $tablespaces = $data->getTablespaces();
541
        }
542
543
        $selColumns = new \PHPPgAdmin\XHtml\XHtmlSelect('TableColumnList', true, 10);
544
        $selColumns->set_style('width: 15em;');
545
546
        if ($attrs->recordCount() > 0) {
547
            while (!$attrs->EOF) {
548
                $new_option = new \PHPPgAdmin\XHtml\XHtmlOption($attrs->fields['attname']);
549
                $selColumns->add($new_option);
550
                $attrs->moveNext();
551
            }
552
        }
553
554
        $selIndex = new \PHPPgAdmin\XHtml\XHtmlSelect('IndexColumnList[]', true, 10);
555
        $selIndex->set_style('width: 15em;');
556
        $selIndex->set_attribute('id', 'IndexColumnList');
557
        $buttonAdd = new \PHPPgAdmin\XHtml\XHtmlButton('add', '>>');
558
        $buttonAdd->set_attribute('onclick', 'buttonPressed(this);');
559
        $buttonAdd->set_attribute('type', 'button');
560
561
        $buttonRemove = new \PHPPgAdmin\XHtml\XHtmlButton('remove', '<<');
562
        $buttonRemove->set_attribute('onclick', 'buttonPressed(this);');
563
        $buttonRemove->set_attribute('type', 'button');
564
565
        echo "<form onsubmit=\"doSelectAll();\" name=\"formIndex\" action=\"constraints\" method=\"post\">\n";
566
567
        echo "<table>\n";
568
        echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strname']}</th></tr>";
569
        echo '<tr>';
570
        echo '<td class="data1" colspan="3"><input type="text" name="name" value="', htmlspecialchars($_POST['name']),
571
            "\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" /></td></tr>";
572
        echo "<tr><th class=\"data\">{$this->lang['strtablecolumnlist']}</th><th class=\"data\">&nbsp;</th><th class=\"data required\">{$this->lang['strindexcolumnlist']}</th></tr>\n";
573
        echo '<tr><td class="data1">'.$selColumns->fetch()."</td>\n";
574
        echo '<td class="data1" style="text-align: center">'.$buttonRemove->fetch().$buttonAdd->fetch().'</td>';
575
        echo '<td class=data1>'.$selIndex->fetch()."</td></tr>\n";
576
577
        // Tablespace (if there are any)
578
        if ($data->hasTablespaces() && $tablespaces->recordCount() > 0) {
579
            echo "<tr><th class=\"data\" colspan=\"3\">{$this->lang['strtablespace']}</th></tr>";
580
            echo "<tr><td class=\"data1\" colspan=\"3\"><select name=\"tablespace\">\n";
581
            // Always offer the default (empty) option
582
            echo "\t\t\t\t<option value=\"\"",
583
            ('' == $_POST['tablespace']) ? ' selected="selected"' : '', "></option>\n";
584
            // Display all other tablespaces
585
            while (!$tablespaces->EOF) {
586
                $spcname = htmlspecialchars($tablespaces->fields['spcname']);
587
                echo "\t\t\t\t<option value=\"{$spcname}\"",
588
                ($spcname == $_POST['tablespace']) ? ' selected="selected"' : '', ">{$spcname}</option>\n";
589
                $tablespaces->moveNext();
590
            }
591
            echo "</select></td></tr>\n";
592
        }
593
594
        echo "</table>\n";
595
596
        echo $this->getFormInputsAndButtons(
597
            [
598
                ['name' => 'action', 'type' => 'hidden', 'value' => ($type === 'primary' ? 'save_add_primary_key' : 'save_add_unique_key')],
599
                ['name' => 'table', 'type' => 'hidden', 'value' => htmlspecialchars($_REQUEST['table'])],
600
            ],
601
            [
602
                ['type' => 'submit', 'name' => '', 'value' => $this->lang['stradd']],
603
                ['type' => 'submit', 'name' => 'cancel', 'value' => $this->lang['strcancel']],
604
            ]
605
        );
606
607
        echo sprintf('</form>%s', "\n");
608
    }
609
610
    /**
611
     * Try to add a PRIMARY KEY or UNIQUE constraint.
612
     *
613
     * @param string $type either primary or unique
614
     */
615
    public function addPrimaryOrUniqueKey($type)
616
    {
617
        $data = $this->misc->getDatabaseAccessor();
618
619
        $this->coalesceArr($_POST, 'name', '');
620
621
        // Default tablespace to empty if it isn't set
622
        $this->coalesceArr($_POST, 'tablespace', '');
623
624
        if ('primary' == $type) {
625
            // Check that they've given at least one column
626
            if (!isset($_POST['IndexColumnList']) || !is_array($_POST['IndexColumnList'])
627
                || 0 == sizeof($_POST['IndexColumnList'])
628
            ) {
629
                $this->formPrimaryOrUniqueKey($type, $this->lang['strpkneedscols']);
630
            } else {
631
                $status = $data->addPrimaryKey($_POST['table'], $_POST['IndexColumnList'], $_POST['name'], $_POST['tablespace']);
632
                if (0 == $status) {
633
                    return $this->doDefault($this->lang['strpkadded']);
634
                }
635
636
                return $this->formPrimaryOrUniqueKey($type, $this->lang['strpkaddedbad']);
637
            }
638
        } elseif ('unique' == $type) {
639
            // Check that they've given at least one column
640
            if (!isset($_POST['IndexColumnList']) || !is_array($_POST['IndexColumnList'])
641
                || 0 == sizeof($_POST['IndexColumnList'])
642
            ) {
643
                $this->formPrimaryOrUniqueKey($type, $this->lang['struniqneedscols']);
644
            } else {
645
                $status = $data->addUniqueKey($_POST['table'], $_POST['IndexColumnList'], $_POST['name'], $_POST['tablespace']);
646
                if (0 == $status) {
647
                    return $this->doDefault($this->lang['struniqadded']);
648
                }
649
650
                return $this->formPrimaryOrUniqueKey($type, $this->lang['struniqaddedbad']);
651
            }
652
        } else {
653
            return $this->doDefault($this->lang['strinvalidparam']);
654
        }
655
    }
656
657
    /**
658
     * Confirm and then actually add a CHECK constraint.
659
     *
660
     * @param mixed $confirm
661
     * @param mixed $msg
662
     */
663
    public function addCheck($confirm, $msg = '')
664
    {
665
        $data = $this->misc->getDatabaseAccessor();
666
667
        $this->coalesceArr($_POST, 'name', '');
668
669
        $this->coalesceArr($_POST, 'definition', '');
670
671
        if ($confirm) {
672
            $this->printTrail('table');
673
            $this->printTitle($this->lang['straddcheck'], 'pg.constraint.check');
674
            $this->printMsg($msg);
675
676
            echo '<form action="'.\SUBFOLDER."/src/views/constraints\" method=\"post\">\n";
677
            echo "<table>\n";
678
            echo "<tr><th class=\"data\">{$this->lang['strname']}</th>\n";
679
            echo "<th class=\"data required\">{$this->lang['strdefinition']}</th></tr>\n";
680
681
            echo "<tr><td class=\"data1\"><input name=\"name\" size=\"24\" maxlength=\"{$data->_maxNameLen}\" value=\"",
682
            htmlspecialchars($_POST['name']), "\" /></td>\n";
683
684
            echo '<td class="data1">(<input name="definition" size="64" value="',
685
            htmlspecialchars($_POST['definition']), "\" />)</td></tr>\n";
686
            echo "</table>\n";
687
688
            echo $this->getFormInputsAndButtons(
689
                [
690
                    ['name' => 'action', 'type' => 'hidden', 'value' => 'save_add_check'],
691
                    ['name' => 'table', 'type' => 'hidden', 'value' => htmlspecialchars($_REQUEST['table'])],
692
                ],
693
                [
694
                    ['type' => 'submit', 'name' => '', 'value' => $this->lang['stradd']],
695
                    ['type' => 'submit', 'name' => 'cancel', 'value' => $this->lang['strcancel']],
696
                ]
697
            );
698
699
            echo sprintf('</form>%s', "\n");
700
        } else {
701
            if ('' == trim($_POST['definition'])) {
702
                $this->addCheck(true, $this->lang['strcheckneedsdefinition']);
703
            } else {
704
                $status = $data->addCheckConstraint(
705
                    $_POST['table'],
706
                    $_POST['definition'],
707
                    $_POST['name']
708
                );
709
                if (0 == $status) {
710
                    return $this->doDefault($this->lang['strcheckadded']);
711
                }
712
713
                return $this->addCheck(true, $this->lang['strcheckaddedbad']);
714
            }
715
        }
716
    }
717
718
    /**
719
     * Prints the drop form.
720
     */
721
    public function printDropForm()
722
    {
723
        $data = $this->misc->getDatabaseAccessor();
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
724
        $this->printTrail('constraint');
725
        $this->printTitle($this->lang['strdrop'], 'pg.constraint.drop');
726
727
        echo '<p>', sprintf(
728
            $this->lang['strconfdropconstraint'],
729
            $this->misc->printVal($_REQUEST['constraint']),
730
            $this->misc->printVal($_REQUEST['table'])
731
        ), "</p>\n";
732
733
        echo sprintf('<form action="constraints" method="post">%s', "\n");
734
735
        echo $this->getFormInputsAndButtons(
736
            [
737
                ['name' => 'action', 'value' => 'drop', 'type' => 'hidden'],
738
                ['name' => 'table', 'value' => htmlspecialchars($_REQUEST['table']), 'type' => 'hidden'],
739
                ['name' => 'constraint', 'value' => htmlspecialchars($_REQUEST['constraint']), 'type' => 'hidden'],
740
                ['name' => 'type', 'value' => htmlspecialchars($_REQUEST['type']), 'type' => 'hidden'],
741
            ],
742
            [
743
                ['type' => 'submit', 'name' => 'drop', 'value' => $this->lang['strdrop']],
744
                ['type' => 'submit', 'name' => 'cancel', 'value' => $this->lang['strcancel']],
745
            ],
746
            [
747
                ['type' => 'checkbox', 'name' => 'cascade', 'id' => 'cascade', 'checked' => false, 'labeltext' => $this->lang['strcascade']],
748
            ]
749
        );
750
751
        echo sprintf('</form>%s', "\n");
752
    }
753
754
    /**
755
     * Try to perform actual drop.
756
     */
757
    public function doDrop()
758
    {
759
        $data = $this->misc->getDatabaseAccessor();
760
761
        $status = $data->dropConstraint($_POST['constraint'], $_POST['table'], $_POST['type'], isset($_POST['cascade']));
762
        if (0 == $status) {
763
            return $this->doDefault($this->lang['strconstraintdropped']);
764
        }
765
766
        return $this->doDefault($this->lang['strconstraintdroppedbad']);
767
    }
768
}
769