Passed
Pull Request — develop (#92)
by Felipe
04:47
created

ViewsController::doDrop()   C

Complexity

Conditions 12
Paths 10

Size

Total Lines 67
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 48
nc 10
nop 1
dl 0
loc 67
rs 5.8429
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
3
/*
4
 * PHPPgAdmin v6.0.0-beta.30
5
 */
6
7
namespace PHPPgAdmin\Controller;
8
9
use PHPPgAdmin\Decorators\Decorator;
10
11
/**
12
 * Base controller class.
13
 */
5 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
14
class ViewsController extends BaseController
15
{
16
    public $script          = 'views.php';
17
    public $controller_name = 'ViewsController';
18
    public $table_place     = 'views-views';
19
20
    /**
21
     * Default method to render the controller according to the action parameter.
22
     */
23
    public function render()
24
    {
25
        $conf = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
26
27
        $lang   = $this->lang;
28
        $action = $this->action;
29
30
        if ('tree' == $action) {
31
            return $this->doTree();
32
        }
33
        if ('subtree' == $action) {
34
            return $this->doSubTree();
35
        }
36
37
        $data = $this->misc->getDatabaseAccessor();
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
38
39
        $this->printHeader($lang['strviews']);
40
        $this->printBody();
41
42
        switch ($action) {
43
            case 'selectrows':
44
                if (!isset($_REQUEST['cancel'])) {
45
                    $this->doSelectRows(false);
46
                } else {
47
                    $this->doDefault();
48
                }
49
50
                break;
51
            case 'confselectrows':
52
                $this->doSelectRows(true);
53
54
                break;
55
            case 'save_create_wiz':
56
                if (isset($_REQUEST['cancel'])) {
57
                    $this->doDefault();
58
                } else {
59
                    $this->doSaveCreateWiz();
60
                }
61
62
                break;
63
            case 'wiz_create':
64
                $this->doWizardCreate();
65
66
                break;
67
            case 'set_params_create':
68
                if (isset($_POST['cancel'])) {
69
                    $this->doDefault();
70
                } else {
71
                    $this->doSetParamsCreate();
72
                }
73
74
                break;
75
            case 'save_create':
76
                if (isset($_REQUEST['cancel'])) {
77
                    $this->doDefault();
78
                } else {
79
                    $this->doSaveCreate();
80
                }
81
82
                break;
83
            case 'create':
84
                $this->doCreate();
85
86
                break;
87
            case 'drop':
88
                if (isset($_POST['drop'])) {
89
                    $this->doDrop(false);
90
                } else {
91
                    $this->doDefault();
92
                }
93
94
                break;
95
            case 'confirm_drop':
96
                $this->doDrop(true);
97
98
                break;
99
            default:
100
                $this->doDefault();
101
102
                break;
103
        }
104
105
        return $this->printFooter();
106
    }
107
108
    /**
109
     * Show default list of views in the database.
110
     *
111
     * @param mixed $msg
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
112
     */
113
    public function doDefault($msg = '')
114
    {
115
        $conf = $this->conf;
116
117
        $lang = $this->lang;
118
        $data = $this->misc->getDatabaseAccessor();
119
120
        $this->printTrail('schema');
121
        $this->printTabs('schema', 'views');
122
        $this->printMsg($msg);
123
124
        $views = $data->getViews();
125
126
        $columns = [
127
            'view' => [
128
                'title' => $lang['strview'],
129
                'field' => Decorator::field('relname'),
130
                'url'   => \SUBFOLDER."/redirect/view?{$this->misc->href}&amp;",
131
                'vars'  => ['view' => 'relname'],
132
            ],
133
            'owner' => [
134
                'title' => $lang['strowner'],
135
                'field' => Decorator::field('relowner'),
136
            ],
137
            'actions' => [
138
                'title' => $lang['stractions'],
139
            ],
140
            'comment' => [
141
                'title' => $lang['strcomment'],
142
                'field' => Decorator::field('relcomment'),
143
            ],
144
        ];
145
146
        $actions = [
147
            'multiactions' => [
148
                'keycols' => ['view' => 'relname'],
149
                'url'     => 'views.php',
150
            ],
151
            'browse' => [
152
                'content' => $lang['strbrowse'],
153
                'attr'    => [
154
                    'href' => [
155
                        'url'     => 'display.php',
156
                        'urlvars' => [
157
                            'action'  => 'confselectrows',
158
                            'subject' => 'view',
159
                            'return'  => 'schema',
160
                            'view'    => Decorator::field('relname'),
161
                        ],
162
                    ],
163
                ],
164
            ],
165
            'select' => [
166
                'content' => $lang['strselect'],
167
                'attr'    => [
168
                    'href' => [
169
                        'url'     => 'views.php',
170
                        'urlvars' => [
171
                            'action' => 'confselectrows',
172
                            'view'   => Decorator::field('relname'),
173
                        ],
174
                    ],
175
                ],
176
            ],
177
178
            // Insert is possible if the relevant rule for the view has been created.
179
            //            'insert' => array(
180
            //                'title'    => $lang['strinsert'],
181
            //                'url'    => "views.php?action=confinsertrow&amp;{$this->misc->href}&amp;",
182
            //                'vars'    => array('view' => 'relname'),
183
            //            ),
184
185
            'alter' => [
186
                'content' => $lang['stralter'],
187
                'attr'    => [
188
                    'href' => [
189
                        'url'     => 'viewproperties.php',
190
                        'urlvars' => [
191
                            'action' => 'confirm_alter',
192
                            'view'   => Decorator::field('relname'),
193
                        ],
194
                    ],
195
                ],
196
            ],
197
            'drop' => [
198
                'multiaction' => 'confirm_drop',
199
                'content'     => $lang['strdrop'],
200
                'attr'        => [
201
                    'href' => [
202
                        'url'     => 'views.php',
203
                        'urlvars' => [
204
                            'action' => 'confirm_drop',
205
                            'view'   => Decorator::field('relname'),
206
                        ],
207
                    ],
208
                ],
209
            ],
210
        ];
211
212
        echo $this->printTable($views, $columns, $actions, $this->table_place, $lang['strnoviews']);
213
214
        $navlinks = [
215
            'create' => [
216
                'attr' => [
217
                    'href' => [
218
                        'url'     => 'views.php',
219
                        'urlvars' => [
220
                            'action'   => 'create',
221
                            'server'   => $_REQUEST['server'],
222
                            'database' => $_REQUEST['database'],
223
                            'schema'   => $_REQUEST['schema'],
224
                        ],
225
                    ],
226
                ],
227
                'content' => $lang['strcreateview'],
228
            ],
229
            'createwiz' => [
230
                'attr' => [
231
                    'href' => [
232
                        'url'     => 'views.php',
233
                        'urlvars' => [
234
                            'action'   => 'wiz_create',
235
                            'server'   => $_REQUEST['server'],
236
                            'database' => $_REQUEST['database'],
237
                            'schema'   => $_REQUEST['schema'],
238
                        ],
239
                    ],
240
                ],
241
                'content' => $lang['strcreateviewwiz'],
242
            ],
243
        ];
244
        $this->printNavLinks($navlinks, $this->table_place, get_defined_vars());
245
    }
246
247
    /**
248
     * Generate XML for the browser tree.
249
     */
250
    public function doTree()
251
    {
252
        $conf = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
253
254
        $lang = $this->lang;
0 ignored issues
show
Unused Code introduced by
The assignment to $lang is dead and can be removed.
Loading history...
255
        $data = $this->misc->getDatabaseAccessor();
256
257
        $views = $data->getViews();
258
259
        $reqvars = $this->misc->getRequestVars('view');
260
261
        $attrs = [
262
            'text'       => Decorator::field('relname'),
263
            'icon'       => 'View',
264
            'iconAction' => Decorator::url('display.php', $reqvars, ['view' => Decorator::field('relname')]),
265
            'toolTip'    => Decorator::field('relcomment'),
266
            'action'     => Decorator::redirecturl('redirect.php', $reqvars, ['view' => Decorator::field('relname')]),
267
            'branch'     => Decorator::url('views.php', $reqvars, ['action' => 'subtree', 'view' => Decorator::field('relname')]),
268
        ];
269
270
        return $this->printTree($views, $attrs, 'views');
271
    }
272
273
    public function doSubTree()
1 ignored issue
show
Coding Style introduced by
Missing function doc comment
Loading history...
274
    {
275
        $conf = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
276
277
        $lang = $this->lang;
0 ignored issues
show
Unused Code introduced by
The assignment to $lang is dead and can be removed.
Loading history...
278
        $data = $this->misc->getDatabaseAccessor();
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
279
280
        $tabs    = $this->misc->getNavTabs('view');
281
        $items   = $this->adjustTabsForTree($tabs);
282
        $reqvars = $this->misc->getRequestVars('view');
283
284
        $attrs = [
285
            'text'   => Decorator::field('title'),
286
            'icon'   => Decorator::field('icon'),
287
            'action' => Decorator::actionurl(Decorator::field('url'), $reqvars, Decorator::field('urlvars'), ['view' => $_REQUEST['view']]),
288
            'branch' => Decorator::ifempty(
289
                Decorator::field('branch'),
290
                '',
291
                Decorator::url(
292
                    Decorator::field('url'),
293
                    Decorator::field('urlvars'),
294
                    $reqvars,
295
                    [
296
                        'action' => 'tree',
297
                        'view'   => $_REQUEST['view'],
298
                    ]
299
                )
300
            ),
301
        ];
302
303
        return $this->printTree($items, $attrs, 'view');
304
    }
305
306
    /**
307
     * Ask for select parameters and perform select.
308
     *
309
     * @param mixed $confirm
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
310
     * @param mixed $msg
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
311
     */
312
    public function doSelectRows($confirm, $msg = '')
313
    {
314
        $conf = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
315
316
        $lang = $this->lang;
317
        $data = $this->misc->getDatabaseAccessor();
318
319
        if ($confirm) {
320
            $this->printTrail('view');
321
            $this->printTabs('view', 'select');
322
            $this->printMsg($msg);
323
324
            $attrs = $data->getTableAttributes($_REQUEST['view']);
325
326
            echo '<form action="'.\SUBFOLDER.'/src/views/'.$this->script.'" method="post" id="selectform">';
327
            echo "\n";
328
329
            if ($attrs->recordCount() > 0) {
330
                // JavaScript for select all feature
331
                echo "<script type=\"text/javascript\">\n";
332
                echo "//<![CDATA[\n";
333
                echo "	function selectAll() {\n";
334
                echo "		for (var i=0; i<document.getElementById('selectform').elements.length; i++) {\n";
335
                echo "			var e = document.getElementById('selectform').elements[i];\n";
336
                echo "			if (e.name.indexOf('show') == 0) { \n ";
337
                echo "				e.checked = document.getElementById('selectform').selectall.checked;\n";
338
                echo "			}\n";
339
                echo "		}\n";
340
                echo "	}\n";
341
                echo "//]]>\n";
342
                echo "</script>\n";
343
344
                echo "<table>\n";
345
346
                // Output table header
347
                echo "<tr><th class=\"data\">{$lang['strshow']}</th><th class=\"data\">{$lang['strcolumn']}</th>";
348
                echo "<th class=\"data\">{$lang['strtype']}</th><th class=\"data\">{$lang['stroperator']}</th>";
349
                echo "<th class=\"data\">{$lang['strvalue']}</th></tr>";
350
351
                $i = 0;
352
                while (!$attrs->EOF) {
353
                    $attrs->fields['attnotnull'] = $data->phpBool($attrs->fields['attnotnull']);
354
                    // Set up default value if there isn't one already
355
                    if (!isset($_REQUEST['values'][$attrs->fields['attname']])) {
356
                        $_REQUEST['values'][$attrs->fields['attname']] = null;
357
                    }
358
359
                    if (!isset($_REQUEST['ops'][$attrs->fields['attname']])) {
360
                        $_REQUEST['ops'][$attrs->fields['attname']] = null;
361
                    }
362
363
                    // Continue drawing row
364
                    $id = (0 == ($i % 2) ? '1' : '2');
365
                    echo "<tr class=\"data{$id}\">\n";
366
                    echo '<td style="white-space:nowrap;">';
367
                    echo '<input type="checkbox" name="show[', htmlspecialchars($attrs->fields['attname']), ']"',
368
                    isset($_REQUEST['show'][$attrs->fields['attname']]) ? ' checked="checked"' : '', ' /></td>';
369
                    echo '<td style="white-space:nowrap;">', $this->misc->printVal($attrs->fields['attname']), '</td>';
370
                    echo '<td style="white-space:nowrap;">', $this->misc->printVal($data->formatType($attrs->fields['type'], $attrs->fields['atttypmod'])), '</td>';
371
                    echo '<td style="white-space:nowrap;">';
372
                    echo "<select name=\"ops[{$attrs->fields['attname']}]\">\n";
373
                    foreach (array_keys($data->selectOps) as $v) {
374
                        echo '<option value="', htmlspecialchars($v), '"', ($_REQUEST['ops'][$attrs->fields['attname']] == $v) ? ' selected="selected"' : '',
375
                        '>', htmlspecialchars($v), "</option>\n";
376
                    }
377
                    echo "</select></td>\n";
378
                    echo '<td style="white-space:nowrap;">', $data->printField(
379
                        "values[{$attrs->fields['attname']}]",
380
                        $_REQUEST['values'][$attrs->fields['attname']],
381
                        $attrs->fields['type']
382
                    ), '</td>';
383
                    echo "</tr>\n";
384
                    ++$i;
385
                    $attrs->moveNext();
386
                }
387
                // Select all checkbox
388
                echo "<tr><td colspan=\"5\"><input type=\"checkbox\" id=\"selectall\" name=\"selectall\" accesskey=\"a\" onclick=\"javascript:selectAll()\" /><label for=\"selectall\">{$lang['strselectallfields']}</label></td></tr>";
389
                echo "</table>\n";
390
            } else {
391
                echo "<p>{$lang['strinvalidparam']}</p>\n";
392
            }
393
394
            echo "<p><input type=\"hidden\" name=\"action\" value=\"selectrows\" />\n";
395
            echo '<input type="hidden" name="view" value="', htmlspecialchars($_REQUEST['view']), "\" />\n";
396
            echo "<input type=\"hidden\" name=\"subject\" value=\"view\" />\n";
397
            echo $this->misc->form;
398
            echo "<input type=\"submit\" name=\"select\" accesskey=\"r\" value=\"{$lang['strselect']}\" />\n";
399
            echo "<input type=\"submit\" name=\"cancel\" value=\"{$lang['strcancel']}\" /></p>\n";
400
            echo "</form>\n";
401
402
            return;
403
        }
404
        if (!isset($_POST['show'])) {
405
            $_POST['show'] = [];
406
        }
407
408
        if (!isset($_POST['values'])) {
409
            $_POST['values'] = [];
410
        }
411
412
        if (!isset($_POST['nulls'])) {
413
            $_POST['nulls'] = [];
414
        }
415
416
        // Verify that they haven't supplied a value for unary operators
417
        foreach ($_POST['ops'] as $k => $v) {
418
            if ('p' == $data->selectOps[$v] && $_POST['values'][$k] != '') {
419
                $this->doSelectRows(true, $lang['strselectunary']);
420
421
                return;
422
            }
423
        }
424
425
        if (0 == sizeof($_POST['show'])) {
426
            return $this->doSelectRows(true, $lang['strselectneedscol']);
427
        }
428
        // Generate query SQL
429
        $query = $data->getSelectSQL($_REQUEST['view'], array_keys($_POST['show']), $_POST['values'], $_POST['ops']);
430
431
        $_REQUEST['query']  = $query;
432
        $_REQUEST['return'] = 'schema';
433
434
        $this->setNoOutput(true);
435
436
        $display_controller = new DisplayController($this->getContainer());
437
438
        return $display_controller->render();
439
    }
440
441
    /**
442
     * Show confirmation of drop and perform actual drop.
443
     *
444
     * @param mixed $confirm
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
445
     */
446
    public function doDrop($confirm)
447
    {
448
        $conf = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
449
450
        $lang = $this->lang;
451
        $data = $this->misc->getDatabaseAccessor();
452
453
        if (empty($_REQUEST['view']) && empty($_REQUEST['ma'])) {
454
            return $this->doDefault($lang['strspecifyviewtodrop']);
455
        }
456
457
        if ($confirm) {
458
            $this->printTrail('view');
459
            $this->printTitle($lang['strdrop'], 'pg.view.drop');
460
461
            echo '<form action="'.\SUBFOLDER."/src/views/views.php\" method=\"post\">\n";
462
463
            //If multi drop
464
            if (isset($_REQUEST['ma'])) {
465
                foreach ($_REQUEST['ma'] as $v) {
466
                    $a = unserialize(htmlspecialchars_decode($v, ENT_QUOTES));
467
                    echo '<p>', sprintf($lang['strconfdropview'], $this->misc->printVal($a['view'])), "</p>\n";
468
                    echo '<input type="hidden" name="view[]" value="', htmlspecialchars($a['view']), "\" />\n";
469
                }
470
            } else {
471
                echo '<p>', sprintf($lang['strconfdropview'], $this->misc->printVal($_REQUEST['view'])), "</p>\n";
472
                echo '<input type="hidden" name="view" value="', htmlspecialchars($_REQUEST['view']), "\" />\n";
473
            }
474
475
            echo "<input type=\"hidden\" name=\"action\" value=\"drop\" />\n";
476
477
            echo $this->misc->form;
478
            echo "<p><input type=\"checkbox\" id=\"cascade\" name=\"cascade\" /> <label for=\"cascade\">{$lang['strcascade']}</label></p>\n";
479
            echo "<input type=\"submit\" name=\"drop\" value=\"{$lang['strdrop']}\" />\n";
480
            echo "<input type=\"submit\" name=\"cancel\" value=\"{$lang['strcancel']}\" />\n";
481
            echo "</form>\n";
482
        } else {
483
            if (is_array($_POST['view'])) {
484
                $msg    = '';
485
                $status = $data->beginTransaction();
486
                if (0 == $status) {
487
                    foreach ($_POST['view'] as $s) {
488
                        $status = $data->dropView($s, isset($_POST['cascade']));
489
                        if (0 == $status) {
490
                            $msg .= sprintf('%s: %s<br />', htmlentities($s, ENT_QUOTES, 'UTF-8'), $lang['strviewdropped']);
491
                        } else {
492
                            $data->endTransaction();
493
                            $this->doDefault(sprintf('%s%s: %s<br />', $msg, htmlentities($s, ENT_QUOTES, 'UTF-8'), $lang['strviewdroppedbad']));
494
495
                            return;
496
                        }
497
                    }
498
                }
499
                if (0 == $data->endTransaction()) {
500
                    // Everything went fine, back to the Default page....
501
                    $this->misc->setReloadBrowser(true);
502
                    $this->doDefault($msg);
503
                } else {
504
                    $this->doDefault($lang['strviewdroppedbad']);
505
                }
506
            } else {
507
                $status = $data->dropView($_POST['view'], isset($_POST['cascade']));
508
                if (0 == $status) {
509
                    $this->misc->setReloadBrowser(true);
510
                    $this->doDefault($lang['strviewdropped']);
511
                } else {
512
                    $this->doDefault($lang['strviewdroppedbad']);
513
                }
514
            }
515
        }
516
    }
517
518
    /**
519
     * Sets up choices for table linkage, and which fields to select for the view we're creating.
520
     *
521
     * @param mixed $msg
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
522
     */
523
    public function doSetParamsCreate($msg = '')
524
    {
525
        $conf = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
526
527
        $lang = $this->lang;
528
        $data = $this->misc->getDatabaseAccessor();
529
530
        // Check that they've chosen tables for the view definition
531
        if (!isset($_POST['formTables'])) {
532
            $this->doWizardCreate($lang['strviewneedsdef']);
533
        } else {
534
            // Initialise variables
535
            if (!isset($_REQUEST['formView'])) {
536
                $_REQUEST['formView'] = '';
537
            }
538
539
            if (!isset($_REQUEST['formComment'])) {
540
                $_REQUEST['formComment'] = '';
541
            }
542
543
            $this->printTrail('schema');
544
            $this->printTitle($lang['strcreateviewwiz'], 'pg.view.create');
545
            $this->printMsg($msg);
546
547
            $tblCount = sizeof($_POST['formTables']);
548
            //unserialize our schema/table information and store in arrSelTables
549
            for ($i = 0; $i < $tblCount; ++$i) {
550
                $arrSelTables[] = unserialize($_POST['formTables'][$i]);
551
            }
552
553
            $linkCount = $tblCount;
0 ignored issues
show
Unused Code introduced by
The assignment to $linkCount is dead and can be removed.
Loading history...
554
555
            //get linking keys
556
            $rsLinkKeys = $data->getLinkingKeys($arrSelTables);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $arrSelTables does not seem to be defined for all execution paths leading up to this point.
Loading history...
557
            $linkCount  = $rsLinkKeys->recordCount() > $tblCount ? $rsLinkKeys->recordCount() : $tblCount;
558
559
            $arrFields = []; //array that will hold all our table/field names
560
561
            //if we have schemas we need to specify the correct schema for each table we're retrieiving
562
            //with getTableAttributes
563
            $curSchema = $data->_schema;
564
            for ($i = 0; $i < $tblCount; ++$i) {
565
                if ($arrSelTables[$i]['schemaname'] != $data->_schema) {
566
                    $data->setSchema($arrSelTables[$i]['schemaname']);
567
                }
568
569
                $attrs = $data->getTableAttributes($arrSelTables[$i]['tablename']);
570
                while (!$attrs->EOF) {
571
                    $arrFields["{$arrSelTables[$i]['schemaname']}.{$arrSelTables[$i]['tablename']}.{$attrs->fields['attname']}"] = serialize(
572
                        [
573
                            'schemaname' => $arrSelTables[$i]['schemaname'],
574
                            'tablename'  => $arrSelTables[$i]['tablename'],
575
                            'fieldname'  => $attrs->fields['attname'], ]
576
                    );
577
                    $attrs->moveNext();
578
                }
579
580
                $data->setSchema($curSchema);
581
            }
582
            asort($arrFields);
583
584
            echo '<form action="'.\SUBFOLDER."/src/views/views.php\" method=\"post\">\n";
585
            echo "<table>\n";
586
            echo "<tr><th class=\"data\">{$lang['strviewname']}</th></tr>";
587
            echo "<tr>\n<td class=\"data1\">\n";
588
            // View name
589
            echo '<input name="formView" value="', htmlspecialchars($_REQUEST['formView']), "\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" />\n";
590
            echo "</td>\n</tr>\n";
591
            echo "<tr><th class=\"data\">{$lang['strcomment']}</th></tr>";
592
            echo "<tr>\n<td class=\"data1\">\n";
593
            // View comments
594
            echo '<textarea name="formComment" rows="3" cols="32">',
595
            htmlspecialchars($_REQUEST['formComment']), "</textarea>\n";
596
            echo "</td>\n</tr>\n";
597
            echo "</table>\n";
598
599
            // Output selector for fields to be retrieved from view
600
            echo "<table>\n";
601
            echo "<tr><th class=\"data\">{$lang['strcolumns']}</th></tr>";
602
            echo "<tr>\n<td class=\"data1\">\n";
603
            echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrFields, 'formFields[]', false, '', true);
604
            echo "</td>\n</tr>";
605
            echo "<tr><td><input type=\"radio\" name=\"dblFldMeth\" id=\"dblFldMeth1\" value=\"rename\" /><label for=\"dblFldMeth1\">{$lang['strrenamedupfields']}</label>";
606
            echo "<br /><input type=\"radio\" name=\"dblFldMeth\" id=\"dblFldMeth2\" value=\"drop\" /><label for=\"dblFldMeth2\">{$lang['strdropdupfields']}</label>";
607
            echo "<br /><input type=\"radio\" name=\"dblFldMeth\" id=\"dblFldMeth3\" value=\"\" checked=\"checked\" /><label for=\"dblFldMeth3\">{$lang['strerrordupfields']}</label></td></tr></table><br />";
608
609
            // Output the Linking keys combo boxes
610
            echo "<table>\n";
611
            echo "<tr><th class=\"data\">{$lang['strviewlink']}</th></tr>";
612
            $rowClass = 'data1';
613
            for ($i = 0; $i < $linkCount; ++$i) {
614
                // Initialise variables
615
                if (!isset($formLink[$i]['operator'])) {
616
                    $formLink[$i]['operator'] = 'INNER JOIN';
617
                }
618
619
                echo "<tr>\n<td class=\"${rowClass}\">\n";
620
621
                if (!$rsLinkKeys->EOF) {
622
                    $curLeftLink  = htmlspecialchars(serialize(['schemaname' => $rsLinkKeys->fields['p_schema'], 'tablename' => $rsLinkKeys->fields['p_table'], 'fieldname' => $rsLinkKeys->fields['p_field']]));
623
                    $curRightLink = htmlspecialchars(serialize(['schemaname' => $rsLinkKeys->fields['f_schema'], 'tablename' => $rsLinkKeys->fields['f_table'], 'fieldname' => $rsLinkKeys->fields['f_field']]));
624
                    $rsLinkKeys->moveNext();
625
                } else {
626
                    $curLeftLink  = '';
627
                    $curRightLink = '';
628
                }
629
630
                echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrFields, "formLink[${i}][leftlink]", true, $curLeftLink, false);
631
                echo \PHPPgAdmin\XHtml\HTMLController::printCombo($data->joinOps, "formLink[${i}][operator]", true, $formLink[$i]['operator']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $formLink does not seem to be defined for all execution paths leading up to this point.
Loading history...
632
                echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrFields, "formLink[${i}][rightlink]", true, $curRightLink, false);
633
                echo "</td>\n</tr>\n";
634
                $rowClass = 'data1' == $rowClass ? 'data2' : 'data1';
635
            }
636
            echo "</table>\n<br />\n";
637
638
            // Build list of available operators (infix only)
639
            $arrOperators = [];
640
            foreach ($data->selectOps as $k => $v) {
641
                if ('i' == $v) {
642
                    $arrOperators[$k] = $k;
643
                }
644
            }
645
646
            // Output additional conditions, note that this portion of the wizard treats the right hand side as literal values
647
            //(not as database objects) so field names will be treated as strings, use the above linking keys section to perform joins
648
            echo "<table>\n";
649
            echo "<tr><th class=\"data\">{$lang['strviewconditions']}</th></tr>";
650
            $rowClass = 'data1';
651
            for ($i = 0; $i < $linkCount; ++$i) {
652
                echo "<tr>\n<td class=\"${rowClass}\">\n";
653
                echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrFields, "formCondition[${i}][field]");
654
                echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrOperators, "formCondition[${i}][operator]", false, false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $szDefault of PHPPgAdmin\XHtml\HTMLController::printCombo(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

654
                echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrOperators, "formCondition[${i}][operator]", false, /** @scrutinizer ignore-type */ false);
Loading history...
655
                echo "<input type=\"text\" name=\"formCondition[${i}][txt]\" />\n";
656
                echo "</td>\n</tr>\n";
657
                $rowClass = 'data1' == $rowClass ? 'data2' : 'data1';
658
            }
659
            echo "</table>\n";
660
            echo "<p><input type=\"hidden\" name=\"action\" value=\"save_create_wiz\" />\n";
661
662
            foreach ($arrSelTables as $curTable) {
663
                echo '<input type="hidden" name="formTables[]" value="'.htmlspecialchars(serialize($curTable))."\" />\n";
664
            }
665
666
            echo $this->misc->form;
667
            echo "<input type=\"submit\" value=\"{$lang['strcreate']}\" />\n";
668
            echo "<input type=\"submit\" name=\"cancel\" value=\"{$lang['strcancel']}\" /></p>\n";
669
            echo "</form>\n";
670
        }
671
    }
672
673
    /**
674
     * Display a wizard where they can enter a new view.
675
     *
676
     * @param mixed $msg
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
677
     */
678
    public function doWizardCreate($msg = '')
679
    {
680
        $conf = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
681
682
        $lang = $this->lang;
683
        $data = $this->misc->getDatabaseAccessor();
684
685
        $tables = $data->getTables(true);
686
687
        $this->printTrail('schema');
688
        $this->printTitle($lang['strcreateviewwiz'], 'pg.view.create');
689
        $this->printMsg($msg);
690
691
        echo '<form action="'.\SUBFOLDER."/src/views/views.php\" method=\"post\">\n";
692
        echo "<table>\n";
693
        echo "<tr><th class=\"data\">{$lang['strtables']}</th></tr>";
694
        echo "<tr>\n<td class=\"data1\">\n";
695
696
        $arrTables = [];
697
        while (!$tables->EOF) {
698
            $arrTmp                                                               = [];
699
            $arrTmp['schemaname']                                                 = $tables->fields['nspname'];
700
            $arrTmp['tablename']                                                  = $tables->fields['relname'];
701
            $arrTables[$tables->fields['nspname'].'.'.$tables->fields['relname']] = serialize($arrTmp);
702
            $tables->moveNext();
703
        }
704
        echo \PHPPgAdmin\XHtml\HTMLController::printCombo($arrTables, 'formTables[]', false, '', true);
705
706
        echo "</td>\n</tr>\n";
707
        echo "</table>\n";
708
        echo "<p><input type=\"hidden\" name=\"action\" value=\"set_params_create\" />\n";
709
        echo $this->misc->form;
710
        echo "<input type=\"submit\" value=\"{$lang['strnext']}\" />\n";
711
        echo "<input type=\"submit\" name=\"cancel\" value=\"{$lang['strcancel']}\" /></p>\n";
712
        echo "</form>\n";
713
    }
714
715
    /**
716
     * Displays a screen where they can enter a new view.
717
     *
718
     * @param mixed $msg
1 ignored issue
show
Coding Style introduced by
Missing parameter comment
Loading history...
719
     */
720
    public function doCreate($msg = '')
721
    {
722
        $conf = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
723
724
        $lang = $this->lang;
725
        $data = $this->misc->getDatabaseAccessor();
726
727
        if (!isset($_REQUEST['formView'])) {
728
            $_REQUEST['formView'] = '';
729
        }
730
731
        if (!isset($_REQUEST['formDefinition'])) {
732
            if (isset($_SESSION['sqlquery'])) {
733
                $_REQUEST['formDefinition'] = $_SESSION['sqlquery'];
734
            } else {
735
                $_REQUEST['formDefinition'] = 'SELECT ';
736
            }
737
        }
738
        if (!isset($_REQUEST['formComment'])) {
739
            $_REQUEST['formComment'] = '';
740
        }
741
742
        $this->printTrail('schema');
743
        $this->printTitle($lang['strcreateview'], 'pg.view.create');
744
        $this->printMsg($msg);
745
746
        echo '<form action="'.\SUBFOLDER."/src/views/views.php\" method=\"post\">\n";
747
        echo "<table style=\"width: 100%\">\n";
748
        echo "\t<tr>\n\t\t<th class=\"data left required\">{$lang['strname']}</th>\n";
749
        echo "\t<td class=\"data1\"><input name=\"formView\" size=\"32\" maxlength=\"{$data->_maxNameLen}\" value=\"",
750
        htmlspecialchars($_REQUEST['formView']), "\" /></td>\n\t</tr>\n";
751
        echo "\t<tr>\n\t\t<th class=\"data left required\">{$lang['strdefinition']}</th>\n";
752
        echo "\t<td class=\"data1\"><textarea style=\"width:100%;\" rows=\"10\" cols=\"50\" name=\"formDefinition\">",
753
        htmlspecialchars($_REQUEST['formDefinition']), "</textarea></td>\n\t</tr>\n";
754
        echo "\t<tr>\n\t\t<th class=\"data left\">{$lang['strcomment']}</th>\n";
755
        echo "\t\t<td class=\"data1\"><textarea name=\"formComment\" rows=\"3\" cols=\"32\">",
756
        htmlspecialchars($_REQUEST['formComment']), "</textarea></td>\n\t</tr>\n";
757
        echo "</table>\n";
758
        echo "<p><input type=\"hidden\" name=\"action\" value=\"save_create\" />\n";
759
        echo $this->misc->form;
760
        echo "<input type=\"submit\" value=\"{$lang['strcreate']}\" />\n";
761
        echo "<input type=\"submit\" name=\"cancel\" value=\"{$lang['strcancel']}\" /></p>\n";
762
        echo "</form>\n";
763
    }
764
765
    /**
766
     * Actually creates the new view in the database.
767
     */
768
    public function doSaveCreate()
769
    {
770
        $conf = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
771
772
        $lang = $this->lang;
773
        $data = $this->misc->getDatabaseAccessor();
774
775
        // Check that they've given a name and a definition
776
        if ('' == $_POST['formView']) {
777
            $this->doCreate($lang['strviewneedsname']);
778
        } elseif ('' == $_POST['formDefinition']) {
779
            $this->doCreate($lang['strviewneedsdef']);
780
        } else {
781
            $status = $data->createView($_POST['formView'], $_POST['formDefinition'], false, $_POST['formComment']);
782
            if (0 == $status) {
783
                $this->misc->setReloadBrowser(true);
784
                $this->doDefault($lang['strviewcreated']);
785
            } else {
786
                $this->doCreate($lang['strviewcreatedbad']);
787
            }
788
        }
789
    }
790
791
    /**
792
     * Actually creates the new wizard view in the database.
793
     */
794
    public function doSaveCreateWiz()
795
    {
796
        $conf = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
797
798
        $lang = $this->lang;
799
        $data = $this->misc->getDatabaseAccessor();
800
801
        // Check that they've given a name and fields they want to select
802
803
        if (!strlen($_POST['formView'])) {
804
            $this->doSetParamsCreate($lang['strviewneedsname']);
805
        } elseif (!isset($_POST['formFields']) || !count($_POST['formFields'])) {
806
            $this->doSetParamsCreate($lang['strviewneedsfields']);
807
        } else {
808
            $selFields = '';
809
810
            if (!empty($_POST['dblFldMeth'])) {
811
                $tmpHsh = [];
812
            }
813
814
            foreach ($_POST['formFields'] as $curField) {
815
                $arrTmp = unserialize($curField);
816
                $data->fieldArrayClean($arrTmp);
817
                if (!empty($_POST['dblFldMeth'])) {
818
                    // doublon control
819
                    if (empty($tmpHsh[$arrTmp['fieldname']])) {
820
                        // field does not exist
821
                        $selFields .= "\"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\".\"{$arrTmp['fieldname']}\", ";
822
                        $tmpHsh[$arrTmp['fieldname']] = 1;
823
                    } elseif ('rename' == $_POST['dblFldMeth']) {
824
                        // field exist and must be renamed
825
                        ++$tmpHsh[$arrTmp['fieldname']];
826
                        $selFields .= "\"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\".\"{$arrTmp['fieldname']}\" AS \"{$arrTmp['schemaname']}_{$arrTmp['tablename']}_{$arrTmp['fieldname']}{$tmpHsh[$arrTmp['fieldname']]}\", ";
827
                    }
828
                    // field already exist, just ignore this one
829
                } else {
830
                    // no doublon control
831
                    $selFields .= "\"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\".\"{$arrTmp['fieldname']}\", ";
832
                }
833
            }
834
835
            $selFields = substr($selFields, 0, -2);
836
            unset($arrTmp, $tmpHsh);
837
            $linkFields = '';
838
839
            // If we have links, out put the JOIN ... ON statements
840
            if (is_array($_POST['formLink'])) {
841
                // Filter out invalid/blank entries for our links
842
                $arrLinks = [];
843
                foreach ($_POST['formLink'] as $curLink) {
844
                    if (strlen($curLink['leftlink']) && strlen($curLink['rightlink']) && strlen($curLink['operator'])) {
845
                        $arrLinks[] = $curLink;
846
                    }
847
                }
848
                // We must perform some magic to make sure that we have a valid join order
849
                $count       = sizeof($arrLinks);
850
                $arrJoined   = [];
851
                $arrUsedTbls = [];
852
853
                // If we have at least one join condition, output it
854
                if ($count > 0) {
855
                    $j = 0;
856
                    while ($j < $count) {
857
                        foreach ($arrLinks as $curLink) {
858
                            $arrLeftLink  = unserialize($curLink['leftlink']);
859
                            $arrRightLink = unserialize($curLink['rightlink']);
860
                            $data->fieldArrayClean($arrLeftLink);
861
                            $data->fieldArrayClean($arrRightLink);
862
863
                            $tbl1 = "\"{$arrLeftLink['schemaname']}\".\"{$arrLeftLink['tablename']}\"";
864
                            $tbl2 = "\"{$arrRightLink['schemaname']}\".\"{$arrRightLink['tablename']}\"";
865
866
                            if ((!in_array($curLink, $arrJoined, true) && in_array($tbl1, $arrUsedTbls, true)) || !count($arrJoined)) {
867
                                // Make sure for multi-column foreign keys that we use a table alias tables joined to more than once
868
                                // This can (and should be) more optimized for multi-column foreign keys
869
                                $adj_tbl2 = in_array($tbl2, $arrUsedTbls, true) ? "${tbl2} AS alias_ppa_".mktime() : $tbl2;
870
871
                                $linkFields .= strlen($linkFields) ? "{$curLink['operator']} ${adj_tbl2} ON (\"{$arrLeftLink['schemaname']}\".\"{$arrLeftLink['tablename']}\".\"{$arrLeftLink['fieldname']}\" = \"{$arrRightLink['schemaname']}\".\"{$arrRightLink['tablename']}\".\"{$arrRightLink['fieldname']}\") "
872
                                : "${tbl1} {$curLink['operator']} ${adj_tbl2} ON (\"{$arrLeftLink['schemaname']}\".\"{$arrLeftLink['tablename']}\".\"{$arrLeftLink['fieldname']}\" = \"{$arrRightLink['schemaname']}\".\"{$arrRightLink['tablename']}\".\"{$arrRightLink['fieldname']}\") ";
873
874
                                $arrJoined[] = $curLink;
875
                                if (!in_array($tbl1, $arrUsedTbls, true)) {
876
                                    $arrUsedTbls[] = $tbl1;
877
                                }
878
879
                                if (!in_array($tbl2, $arrUsedTbls, true)) {
880
                                    $arrUsedTbls[] = $tbl2;
881
                                }
882
                            }
883
                        }
884
                        ++$j;
885
                    }
886
                }
887
            }
888
889
            //if linkfields has no length then either _POST['formLink'] was not set, or there were no join conditions
890
            //just select from all seleted tables - a cartesian join do a
891
            if (!strlen($linkFields)) {
892
                foreach ($_POST['formTables'] as $curTable) {
893
                    $arrTmp = unserialize($curTable);
894
                    $data->fieldArrayClean($arrTmp);
895
                    $linkFields .= strlen($linkFields) ? ", \"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\"" : "\"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\"";
896
                }
897
            }
898
899
            $addConditions = '';
900
            if (is_array($_POST['formCondition'])) {
901
                foreach ($_POST['formCondition'] as $curCondition) {
902
                    if (strlen($curCondition['field']) && strlen($curCondition['txt'])) {
903
                        $arrTmp = unserialize($curCondition['field']);
904
                        $data->fieldArrayClean($arrTmp);
905
                        $addConditions .= strlen($addConditions) ? " AND \"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\".\"{$arrTmp['fieldname']}\" {$curCondition['operator']} '{$curCondition['txt']}' "
906
                        : " \"{$arrTmp['schemaname']}\".\"{$arrTmp['tablename']}\".\"{$arrTmp['fieldname']}\" {$curCondition['operator']} '{$curCondition['txt']}' ";
907
                    }
908
                }
909
            }
910
911
            $viewQuery = "SELECT ${selFields} FROM ${linkFields} ";
912
913
            //add where from additional conditions
914
            if (strlen($addConditions)) {
915
                $viewQuery .= ' WHERE '.$addConditions;
916
            }
917
918
            $status = $data->createView($_POST['formView'], $viewQuery, false, $_POST['formComment']);
919
            if (0 == $status) {
920
                $this->misc->setReloadBrowser(true);
921
                $this->doDefault($lang['strviewcreated']);
922
            } else {
923
                $this->doSetParamsCreate($lang['strviewcreatedbad']);
924
            }
925
        }
926
    }
927
}
928