Passed
Pull Request — develop (#92)
by Felipe
06:19
created

MaterializedviewsController::doSelectRows()   D

Complexity

Conditions 17
Paths 42

Size

Total Lines 127
Code Lines 85

Duplication

Lines 0
Ratio 0 %

Importance

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

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