Passed
Push — develop ( 442876...34732b )
by Felipe
46s
created

MaterializedviewsController::render()   C

Complexity

Conditions 17
Paths 17

Size

Total Lines 79
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

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

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