Passed
Push — develop ( 39eda0...90489b )
by Felipe
04:51
created

DisplayController::_printPages()   D

Complexity

Conditions 9
Paths 13

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 4.909
c 0
b 0
f 0
cc 9
eloc 18
nc 13
nop 4
1
<?php
2
3
/**
4
 * PHPPgAdmin v6.0.0-beta.44
5
 */
6
7
namespace PHPPgAdmin\Controller;
8
9
/**
10
 * Base controller class.
11
 *
12
 * @package PHPPgAdmin
13
 */
14
class DisplayController extends BaseController
15
{
16
    /**
17
     * Default method to render the controller according to the action parameter.
18
     */
19
    public function render()
20
    {
21
        $conf           = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
22
        $this->misc     = $this->misc;
23
        $plugin_manager = $this->plugin_manager;
24
25
        if ('dobrowsefk' == $this->action) {
26
            return $this->doBrowseFK();
27
        }
28
29
        set_time_limit(0);
30
31
        $scripts = '<script src="'.\SUBFOLDER.'/assets/js/display.js" type="text/javascript"></script>';
32
33
        $scripts .= '<script type="text/javascript">'."\n";
34
        $scripts .= "var Display = {\n";
35
        $scripts .= "errmsg: '".str_replace("'", "\\'", $this->lang['strconnectionfail'])."'\n";
36
        $scripts .= "};\n";
37
        $scripts .= '</script>'."\n";
38
39
        $footer_template = 'footer.twig';
40
        $header_template = 'header.twig';
41
42
        ob_start();
43
        switch ($this->action) {
44
            case 'editrow':
45
                $header_template = 'header_sqledit.twig';
46
                $footer_template = 'footer_sqledit.twig';
47
                if (isset($_POST['save'])) {
48
                    $this->doEditRow(false);
49
                } else {
50
                    $this->doBrowse();
51
                }
52
53
                break;
54
            case 'confeditrow':
55
                $this->doEditRow(true);
56
57
                break;
58
            case 'delrow':
59
                $header_template = 'header_sqledit.twig';
60
                $footer_template = 'footer_sqledit.twig';
61
                if (isset($_POST['yes'])) {
62
                    $this->doDelRow(false);
63
                } else {
64
                    $this->doBrowse();
65
                }
66
67
                break;
68
            case 'confdelrow':
69
                $this->doDelRow(true);
70
71
                break;
72
            default:
73
                $header_template = 'header_sqledit.twig';
74
                $footer_template = 'footer_sqledit.twig';
75
                $this->doBrowse();
76
77
                break;
78
        }
79
        $output = ob_get_clean();
80
81
        $subject = $this->coalesceArr($_REQUEST, 'subject', 'table')['subject'];
82
83
        $object = null;
84
        $object = $this->setIfIsset($object, $_REQUEST[$subject]);
85
86
        // Set the title based on the subject of the request
87
        if (!isset($subject) || !isset($object)) {
88
            $this->printHeader($this->lang['strqueryresults'], $scripts, true, $header_template);
89
        } elseif ('table' == $subject) {
90
            $this->printHeader($this->lang['strtables'].': '.$object, $scripts, true, $header_template);
91
        } elseif ('view' == $subject) {
92
            $this->printHeader($this->lang['strviews'].': '.$object, $scripts, true, $header_template);
93
        } elseif ('matview' == $subject) {
94
            $this->printHeader('M'.$this->lang['strviews'].': '.$object, $scripts, true, $header_template);
95
        } elseif ('column' == $subject) {
96
            $this->printHeader($this->lang['strcolumn'].': '.$object, $scripts, true, $header_template);
97
        }
98
99
        $this->printBody();
100
101
        echo $output;
102
103
        $this->printFooter(true, $footer_template);
104
    }
105
106
    /**
107
     * Displays requested data.
108
     *
109
     * @param mixed $msg
110
     */
111
    public function doBrowse($msg = '')
112
    {
113
        $conf           = $this->conf;
114
        $this->misc     = $this->misc;
115
        $plugin_manager = $this->plugin_manager;
116
        $data           = $this->misc->getDatabaseAccessor();
117
118
        // If current page is not set, default to first page
119
        $page = $this->coalesceArr($_REQUEST, 'page', 1)['page'];
120
121
        $save_history = !isset($_REQUEST['nohistory']);
122
123
        $subject = $this->coalesceArr($_REQUEST, 'subject', 'table')['subject'];
124
125
        $object = null;
126
        $object = $this->setIfIsset($object, $_REQUEST[$subject]);
127
128
        //$this->prtrace($subject, $object);
129
130
        $this->printTrail($subject);
131
132
        $this->printTabs($subject, $subject === 'database' ? 'sql' : 'browse');
133
134
        $fkey = $this->coalesceArr($_REQUEST, 'fkey')['fkey'];
135
136
        $query = $this->coalesceArr($_REQUEST, 'query')['query'];
137
        // This code is used when browsing FK in pure-xHTML (without js)
138
        if ($fkey) {
139
            $ops = [];
140
            foreach ($fkey as $x => $y) {
141
                $ops[$x] = '=';
142
            }
143
            $query             = $data->getSelectSQL($_REQUEST['table'], [], $fkey, $ops);
144
            $_REQUEST['query'] = $query;
145
        }
146
147
        if ($object && $query) {
148
            $_SESSION['sqlquery'] = $query;
149
            $this->printTitle($this->lang['strselect']);
150
            $type = 'SELECT';
151
        } elseif ($object) {
152
            $type = 'TABLE';
153
        } else {
154
            $this->printTitle($this->lang['strqueryresults']);
155
            // we come from sql, $_SESSION['sqlquery'] has been set there
156
            $type = 'QUERY';
157
        }
158
159
        $this->printMsg($msg);
160
161
        // If 'sortkey' is not set, default to ''
162
        $sortkey = $this->coalesceArr($_REQUEST, 'sortkey', '')['sortkey'];
163
164
        // If 'sortdir' is not set, default to ''
165
        $sortdir = $this->coalesceArr($_REQUEST, 'sortdir', '')['sortdir'];
166
167
        // If 'strings' is not set, default to collapsed
168
        $strings = $this->coalesceArr($_REQUEST, 'strings', 'collapsed')['strings'];
169
170
        $schema      = $this->coalesceArr($_REQUEST, 'schema')['schema'];
171
        $search_path = $this->coalesceArr($_REQUEST, 'search_path')['search_path'];
172
173
        // Fetch unique row identifier, if this is a table browse request.
174
        if ($object) {
175
            $key = $data->getRowIdentifier($object);
176
        } else {
177
            $key = [];
178
        }
179
180
        // Set the schema search path
181
        if (isset($search_path) && (0 != $data->setSearchPath(array_map('trim', explode(',', $search_path))))) {
182
            return;
183
        }
184
185
        try {
186
            // Retrieve page from query.  $max_pages is returned by reference.
187
            $resultset = $data->browseQuery(
188
                $type,
189
                $object,
190
                $query,
191
                $sortkey,
192
                $sortdir,
193
                $page,
194
                $this->conf['max_rows'],
195
                $max_pages
196
            );
197
        } catch (\PHPPgAdmin\ADOdbException $e) {
198
            return;
199
        }
200
201
        $fkey_information = $this->getFKInfo();
202
203
        // Build strings for GETs in array
204
        $_gets = [
205
            'server'   => $_REQUEST['server'],
206
            'database' => $_REQUEST['database'],
207
        ];
208
209
        $this->coalesceArr($_REQUEST, 'query');
210
        $this->coalesceArr($_REQUEST, 'count');
211
        $this->coalesceArr($_REQUEST, 'return');
212
        $this->coalesceArr($_REQUEST, 'table');
213
        $this->coalesceArr($_REQUEST, 'nohistory');
214
215
        $this->setIfIsset($_gets['schema'], $_REQUEST['schema'], null, false);
216
        $this->setIfIsset($_gets[$subject], $object, null, false);
217
        $this->setIfIsset($_gets['subject'], $subject, null, false);
218
        $this->setIfIsset($_gets['query'], $_REQUEST['query'], null, false);
219
        $this->setIfIsset($_gets['count'], $_REQUEST['count'], null, false);
220
        $this->setIfIsset($_gets['return'], $_REQUEST['return'], null, false);
221
        $this->setIfIsset($_gets['search_path'], $_REQUEST['search_path'], null, false);
222
        $this->setIfIsset($_gets['table'], $_REQUEST['table'], null, false);
223
        $this->setIfIsset($_gets['nohistory'], $_REQUEST['nohistory'], null, false);
224
        $_gets['sortkey'] = $sortkey;
225
        $_gets['sortdir'] = $sortdir;
226
        $_gets['strings'] = $strings;
227
228
        if ($save_history && is_object($resultset) && ('QUERY' == $type)) {
229
            //{
230
            $this->misc->saveScriptHistory($_REQUEST['query']);
231
        }
232
233
        $query = $query ? $query : sprintf('SELECT * FROM %s.%s', $_REQUEST['schema'], $subject);
234
235
        //$query = isset($_REQUEST['query'])? $_REQUEST['query'] : "select * from {$_REQUEST['schema']}.{$_REQUEST['table']};";
236
        $this->prtrace($query);
237
        //die(htmlspecialchars($query));
238
239
        echo '<form method="post" id="sqlform" action="'.str_replace('?', '?', $_SERVER['REQUEST_URI']).'">';
240
        echo '<textarea width="90%" name="query"  id="query" rows="5" cols="100" resizable="true">';
241
242
        echo htmlspecialchars($query);
243
        echo '</textarea><br><input type="submit"/></form>';
244
245
        if (is_object($resultset) && $resultset->recordCount() > 0) {
246
            // Show page navigation
247
            $paginator = $this->_printPages($page, $max_pages, $_gets);
0 ignored issues
show
Bug introduced by
$_gets of type array is incompatible with the type string expected by parameter $gets of PHPPgAdmin\Controller\Di...ntroller::_printPages(). ( Ignorable by Annotation )

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

247
            $paginator = $this->_printPages($page, $max_pages, /** @scrutinizer ignore-type */ $_gets);
Loading history...
248
249
            echo $paginator;
250
            echo "<table id=\"data\">\n<tr>";
251
252
            // Check that the key is actually in the result set.  This can occur for select
253
            // operations where the key fields aren't part of the select.  XXX:  We should
254
            // be able to support this, somehow.
255
            foreach ($key as $v) {
256
                // If a key column is not found in the record set, then we
257
                // can't use the key.
258
                if (!array_key_exists($v, $resultset->fields)) {
259
                    $key = [];
260
261
                    break;
262
                }
263
            }
264
265
            $buttons = [
266
                'edit'   => [
267
                    'content' => $this->lang['stredit'],
268
                    'attr'    => [
269
                        'href' => [
270
                            'url'     => 'display',
271
                            'urlvars' => array_merge(
272
                                [
273
                                    'action'  => 'confeditrow',
274
                                    'strings' => $strings,
275
                                    'page'    => $page,
276
                                ],
277
                                $_gets
278
                            ),
279
                        ],
280
                    ],
281
                ],
282
                'delete' => [
283
                    'content' => $this->lang['strdelete'],
284
                    'attr'    => [
285
                        'href' => [
286
                            'url'     => 'display',
287
                            'urlvars' => array_merge(
288
                                [
289
                                    'action'  => 'confdelrow',
290
                                    'strings' => $strings,
291
                                    'page'    => $page,
292
                                ],
293
                                $_gets
294
                            ),
295
                        ],
296
                    ],
297
                ],
298
            ];
299
            $actions = [
300
                'actionbuttons' => &$buttons,
301
                'place'         => 'display-browse',
302
            ];
303
            $plugin_manager->doHook('actionbuttons', $actions);
304
305
            foreach (array_keys($actions['actionbuttons']) as $this->action) {
306
                $actions['actionbuttons'][$this->action]['attr']['href']['urlvars'] = array_merge(
307
                    $actions['actionbuttons'][$this->action]['attr']['href']['urlvars'],
308
                    $_gets
309
                );
310
            }
311
312
            $edit_params = isset($actions['actionbuttons']['edit']) ?
313
            $actions['actionbuttons']['edit'] : [];
314
            $delete_params = isset($actions['actionbuttons']['delete']) ?
315
            $actions['actionbuttons']['delete'] : [];
316
317
            // Display edit and delete actions if we have a key
318
            $colspan = count($buttons);
319
            if ($colspan > 0 and count($key) > 0) {
320
                echo "<th colspan=\"{$colspan}\" class=\"data\">{$this->lang['stractions']}</th>"."\n";
321
            }
322
323
            // we show OIDs only if we are in TABLE or SELECT type browsing
324
            $this->printTableHeaderCells($resultset, $_gets, isset($object));
325
326
            echo '</tr>'."\n";
327
328
            $i = 0;
329
            reset($resultset->fields);
330
            while (!$resultset->EOF) {
331
                $id = (0 == ($i % 2) ? '1' : '2');
332
                echo "<tr class=\"data{$id}\">"."\n";
333
                // Display edit and delete links if we have a key
334
                if ($colspan > 0 and count($key) > 0) {
335
                    $keys_array = [];
336
                    $has_nulls  = false;
337
                    foreach ($key as $v) {
338
                        if (null === $resultset->fields[$v]) {
339
                            $has_nulls = true;
340
341
                            break;
342
                        }
343
                        $keys_array["key[{$v}]"] = $resultset->fields[$v];
344
                    }
345
                    if ($has_nulls) {
346
                        echo "<td colspan=\"{$colspan}\">&nbsp;</td>"."\n";
347
                    } else {
348
                        if (isset($actions['actionbuttons']['edit'])) {
349
                            $actions['actionbuttons']['edit']                            = $edit_params;
350
                            $actions['actionbuttons']['edit']['attr']['href']['urlvars'] = array_merge(
351
                                $actions['actionbuttons']['edit']['attr']['href']['urlvars'],
352
                                $keys_array
353
                            );
354
                        }
355
356
                        if (isset($actions['actionbuttons']['delete'])) {
357
                            $actions['actionbuttons']['delete']                            = $delete_params;
358
                            $actions['actionbuttons']['delete']['attr']['href']['urlvars'] = array_merge(
359
                                $actions['actionbuttons']['delete']['attr']['href']['urlvars'],
360
                                $keys_array
361
                            );
362
                        }
363
364
                        foreach ($actions['actionbuttons'] as $this->action) {
365
                            echo "<td class=\"opbutton{$id}\">";
366
                            $this->printLink($this->action, true, __METHOD__);
367
                            echo '</td>'."\n";
368
                        }
369
                    }
370
                }
371
372
                $this->printTableRowCells($resultset, $fkey_information, isset($object));
373
374
                echo '</tr>'."\n";
375
                $resultset->moveNext();
376
                ++$i;
377
            }
378
            echo '</table>'."\n";
379
380
            echo '<p>', $resultset->recordCount(), " {$this->lang['strrows']}</p>"."\n";
381
            // Show page navigation
382
            echo $paginator;
383
        } else {
384
            echo "<p>{$this->lang['strnodata']}</p>"."\n";
385
        }
386
387
        // Navigation links
388
        $navlinks = [];
389
390
        $fields = [
391
            'server'   => $_REQUEST['server'],
392
            'database' => $_REQUEST['database'],
393
        ];
394
395
        $this->setIfIsset($fields['schema'], $_REQUEST['schema'], null, false);
396
397
        // Return
398
        if (isset($_REQUEST['return'])) {
399
            $urlvars = $this->misc->getSubjectParams($_REQUEST['return']);
400
401
            $navlinks['back'] = [
402
                'attr'    => [
403
                    'href' => [
404
                        'url'     => $urlvars['url'],
405
                        'urlvars' => $urlvars['params'],
406
                    ],
407
                ],
408
                'content' => $this->lang['strback'],
409
            ];
410
        }
411
412
        // Edit SQL link
413
        if ('QUERY' == $type) {
414
            $navlinks['edit'] = [
415
                'attr'    => [
416
                    'href' => [
417
                        'url'     => 'database',
418
                        'urlvars' => array_merge(
419
                            $fields,
420
                            [
421
                                'action'   => 'sql',
422
                                'paginate' => 'on',
423
                            ]
424
                        ),
425
                    ],
426
                ],
427
                'content' => $this->lang['streditsql'],
428
            ];
429
        }
430
431
        // Expand/Collapse
432
        if ('expanded' == $strings) {
433
            $navlinks['collapse'] = [
434
                'attr'    => [
435
                    'href' => [
436
                        'url'     => 'display',
437
                        'urlvars' => array_merge(
438
                            $_gets,
439
                            [
440
                                'strings' => 'collapsed',
441
                                'page'    => $page,
442
                            ]
443
                        ),
444
                    ],
445
                ],
446
                'content' => $this->lang['strcollapse'],
447
            ];
448
        } else {
449
            $navlinks['collapse'] = [
450
                'attr'    => [
451
                    'href' => [
452
                        'url'     => 'display',
453
                        'urlvars' => array_merge(
454
                            $_gets,
455
                            [
456
                                'strings' => 'expanded',
457
                                'page'    => $page,
458
                            ]
459
                        ),
460
                    ],
461
                ],
462
                'content' => $this->lang['strexpand'],
463
            ];
464
        }
465
466
        // Create view and download
467
        if (isset($_REQUEST['query'], $resultset) && is_object($resultset) && $resultset->recordCount() > 0) {
468
            // Report views don't set a schema, so we need to disable create view in that case
469
            if (isset($_REQUEST['schema'])) {
470
                $navlinks['createview'] = [
471
                    'attr'    => [
472
                        'href' => [
473
                            'url'     => 'views',
474
                            'urlvars' => array_merge(
475
                                $fields,
476
                                [
477
                                    'action'         => 'create',
478
                                    'formDefinition' => $_REQUEST['query'],
479
                                ]
480
                            ),
481
                        ],
482
                    ],
483
                    'content' => $this->lang['strcreateview'],
484
                ];
485
            }
486
487
            $urlvars = [];
488
489
            $this->setIfIsset($urlvars['search_path'], $_REQUEST['search_path'], null, false);
490
491
            $navlinks['download'] = [
492
                'attr'    => [
493
                    'href' => [
494
                        'url'     => 'dataexport',
495
                        'urlvars' => array_merge($fields, $urlvars),
496
                    ],
497
                ],
498
                'content' => $this->lang['strdownload'],
499
            ];
500
        }
501
502
        // Insert
503
        if (isset($object) && (isset($subject) && 'table' == $subject)) {
504
            $navlinks['insert'] = [
505
                'attr'    => [
506
                    'href' => [
507
                        'url'     => 'tables',
508
                        'urlvars' => array_merge(
509
                            $fields,
510
                            [
511
                                'action' => 'confinsertrow',
512
                                'table'  => $object,
513
                            ]
514
                        ),
515
                    ],
516
                ],
517
                'content' => $this->lang['strinsert'],
518
            ];
519
        }
520
521
        // Refresh
522
        $navlinks['refresh'] = [
523
            'attr'    => [
524
                'href' => [
525
                    'url'     => 'display',
526
                    'urlvars' => array_merge(
527
                        $_gets,
528
                        [
529
                            'strings' => $strings,
530
                            'page'    => $page,
531
                        ]
532
                    ),
533
                ],
534
            ],
535
            'content' => $this->lang['strrefresh'],
536
        ];
537
538
        $this->printNavLinks($navlinks, 'display-browse', get_defined_vars());
539
    }
540
541
    /**
542
     * Show confirmation of edit and perform actual update.
543
     *
544
     * @param mixed $confirm
545
     * @param mixed $msg
546
     */
547
    public function doEditRow($confirm, $msg = '')
548
    {
549
        $data = $this->misc->getDatabaseAccessor();
550
551
        if (is_array($_REQUEST['key'])) {
552
            $key = $_REQUEST['key'];
553
        } else {
554
            $key = unserialize(urldecode($_REQUEST['key']));
555
        }
556
557
        if ($confirm) {
558
            $this->printTrail($_REQUEST['subject']);
559
            $this->printTitle($this->lang['streditrow']);
560
            $this->printMsg($msg);
561
562
            $attrs     = $data->getTableAttributes($_REQUEST['table']);
563
            $resultset = $data->browseRow($_REQUEST['table'], $key);
564
565
            if (('disable' != $this->conf['autocomplete'])) {
566
                $fksprops = $this->misc->getAutocompleteFKProperties($_REQUEST['table']);
567
                if (false !== $fksprops) {
568
                    echo $fksprops['code'];
569
                }
570
            } else {
571
                $fksprops = false;
572
            }
573
574
            echo '<form action="'.\SUBFOLDER.'/src/views/display" method="post" id="ac_form">'."\n";
575
576
            /*echo '<p>';
577
            if (!$error) {
578
            echo "<input type=\"submit\" name=\"save\" accesskey=\"r\" value=\"{$this->lang['strsave']}\" />" . "\n";
579
            }
580
581
            echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />" . "\n";
582
583
            echo '</p>' . "\n";*/
584
585
            $elements = 0;
586
            $error    = true;
587
            if (1 == $resultset->recordCount() && $attrs->recordCount() > 0) {
588
                echo '<table>'."\n";
589
590
                // Output table header
591
                echo "<tr><th class=\"data\">{$this->lang['strcolumn']}</th><th class=\"data\">{$this->lang['strtype']}</th>";
592
                echo "<th class=\"data\">{$this->lang['strformat']}</th>"."\n";
593
                echo "<th class=\"data\">{$this->lang['strnull']}</th><th class=\"data\">{$this->lang['strvalue']}</th></tr>";
594
595
                $i = 0;
596
                while (!$attrs->EOF) {
597
                    $attrs->fields['attnotnull'] = $data->phpBool($attrs->fields['attnotnull']);
598
                    $id                          = (0 == ($i % 2) ? '1' : '2');
599
600
                    // Initialise variables
601
                    if (!isset($_REQUEST['format'][$attrs->fields['attname']])) {
602
                        $_REQUEST['format'][$attrs->fields['attname']] = 'VALUE';
603
                    }
604
605
                    echo "<tr class=\"data{$id}\">"."\n";
606
                    echo '<td style="white-space:nowrap;">', $this->misc->printVal($attrs->fields['attname']), '</td>';
607
                    echo '<td style="white-space:nowrap;">'."\n";
608
                    echo $this->misc->printVal($data->formatType($attrs->fields['type'], $attrs->fields['atttypmod']));
609
                    echo '<input type="hidden" name="types[', htmlspecialchars($attrs->fields['attname']), ']" value="',
610
                    htmlspecialchars($attrs->fields['type']), '" /></td>';
611
                    ++$elements;
612
                    echo '<td style="white-space:nowrap;">'."\n";
613
                    echo '<select name="format['.htmlspecialchars($attrs->fields['attname']), ']">'."\n";
614
                    echo '<option value="VALUE"', ($_REQUEST['format'][$attrs->fields['attname']] == 'VALUE') ? ' selected="selected"' : '', ">{$this->lang['strvalue']}</option>"."\n";
615
                    $selected = ($_REQUEST['format'][$attrs->fields['attname']] == 'EXPRESSION') ? ' selected="selected"' : '';
616
                    echo '<option value="EXPRESSION"'.$selected.">{$this->lang['strexpression']}</option>"."\n";
617
                    echo "</select>\n</td>"."\n";
618
                    ++$elements;
619
                    echo '<td style="white-space:nowrap;">';
620
                    // Output null box if the column allows nulls (doesn't look at CHECKs or ASSERTIONS)
621
                    if (!$attrs->fields['attnotnull']) {
622
                        // Set initial null values
623
                        if ('confeditrow' == $_REQUEST['action'] && null === $resultset->fields[$attrs->fields['attname']]) {
624
                            $_REQUEST['nulls'][$attrs->fields['attname']] = 'on';
625
                        }
626
                        echo "<label><span><input type=\"checkbox\" name=\"nulls[{$attrs->fields['attname']}]\"",
627
                        isset($_REQUEST['nulls'][$attrs->fields['attname']]) ? ' checked="checked"' : '', ' /></span></label></td>'."\n";
628
                        ++$elements;
629
                    } else {
630
                        echo '&nbsp;</td>';
631
                    }
632
633
                    echo "<td id=\"row_att_{$attrs->fields['attnum']}\" style=\"white-space:nowrap;\">";
634
635
                    $extras = [];
636
637
                    // If the column allows nulls, then we put a JavaScript action on the data field to unset the
638
                    // NULL checkbox as soon as anything is entered in the field.  We use the $elements variable to
639
                    // keep track of which element offset we're up to.  We can't refer to the null checkbox by name
640
                    // as it contains '[' and ']' characters.
641
                    if (!$attrs->fields['attnotnull']) {
642
                        $extras['onChange'] = 'elements['.($elements - 1).'].checked = false;';
643
                    }
644
645
                    if ((false !== $fksprops) && isset($fksprops['byfield'][$attrs->fields['attnum']])) {
646
                        $extras['id']           = "attr_{$attrs->fields['attnum']}";
647
                        $extras['autocomplete'] = 'off';
648
                    }
649
650
                    echo $data->printField("values[{$attrs->fields['attname']}]", $resultset->fields[$attrs->fields['attname']], $attrs->fields['type'], $extras);
651
652
                    echo '</td>';
653
                    ++$elements;
654
                    echo '</tr>'."\n";
655
                    ++$i;
656
                    $attrs->moveNext();
657
                }
658
                echo '</table>'."\n";
659
660
                $error = false;
661
            } elseif (1 != $resultset->recordCount()) {
662
                echo "<p>{$this->lang['strrownotunique']}</p>"."\n";
663
            } else {
664
                echo "<p>{$this->lang['strinvalidparam']}</p>"."\n";
665
            }
666
667
            echo '<input type="hidden" name="action" value="editrow" />'."\n";
668
            echo $this->misc->form;
669
            if (isset($_REQUEST['table'])) {
670
                echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'."\n";
671
            }
672
673
            if (isset($_REQUEST['subject'])) {
674
                echo '<input type="hidden" name="subject" value="', htmlspecialchars($_REQUEST['subject']), '" />'."\n";
675
            }
676
677
            if (isset($_REQUEST['query'])) {
678
                echo '<input type="hidden" name="query" value="', htmlspecialchars($_REQUEST['query']), '" />'."\n";
679
            }
680
681
            if (isset($_REQUEST['count'])) {
682
                echo '<input type="hidden" name="count" value="', htmlspecialchars($_REQUEST['count']), '" />'."\n";
683
            }
684
685
            if (isset($_REQUEST['return'])) {
686
                echo '<input type="hidden" name="return" value="', htmlspecialchars($_REQUEST['return']), '" />'."\n";
687
            }
688
689
            echo '<input type="hidden" name="page" value="', htmlspecialchars($_REQUEST['page']), '" />'."\n";
690
            echo '<input type="hidden" name="sortkey" value="', htmlspecialchars($_REQUEST['sortkey']), '" />'."\n";
691
            echo '<input type="hidden" name="sortdir" value="', htmlspecialchars($_REQUEST['sortdir']), '" />'."\n";
692
            echo '<input type="hidden" name="strings" value="', htmlspecialchars($_REQUEST['strings']), '" />'."\n";
693
            echo '<input type="hidden" name="key" value="', htmlspecialchars(urlencode(serialize($key))), '" />'."\n";
694
            echo '<p>';
695
            if (!$error) {
696
                echo "<input type=\"submit\" name=\"save\" accesskey=\"r\" value=\"{$this->lang['strsave']}\" />"."\n";
697
            }
698
699
            echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />"."\n";
700
701
            if (false !== $fksprops) {
702
                if ('default off' != $this->conf['autocomplete']) {
703
                    echo "<input type=\"checkbox\" id=\"no_ac\" value=\"1\" checked=\"checked\" /><label for=\"no_ac\">{$this->lang['strac']}</label>"."\n";
704
                } else {
705
                    echo "<input type=\"checkbox\" id=\"no_ac\" value=\"0\" /><label for=\"no_ac\">{$this->lang['strac']}</label>"."\n";
706
                }
707
            }
708
709
            echo '</p>'."\n";
710
            echo '</form>'."\n";
711
        } else {
712
            if (!isset($_POST['values'])) {
713
                $_POST['values'] = [];
714
            }
715
716
            if (!isset($_POST['nulls'])) {
717
                $_POST['nulls'] = [];
718
            }
719
720
            $status = $data->editRow(
721
                $_POST['table'],
722
                $_POST['values'],
723
                $_POST['nulls'],
724
                $_POST['format'],
725
                $_POST['types'],
726
                $key
727
            );
728
            if (0 == $status) {
729
                $this->doBrowse($this->lang['strrowupdated']);
730
            } elseif ($status == -2) {
731
                $this->doEditRow(true, $this->lang['strrownotunique']);
732
            } else {
733
                $this->doEditRow(true, $this->lang['strrowupdatedbad']);
734
            }
735
        }
736
    }
737
738
    /**
739
     * Show confirmation of drop and perform actual drop.
740
     *
741
     * @param mixed $confirm
742
     */
743
    public function doDelRow($confirm)
744
    {
745
        $data = $this->misc->getDatabaseAccessor();
746
747
        if ($confirm) {
748
            $this->printTrail($_REQUEST['subject']);
749
            $this->printTitle($this->lang['strdeleterow']);
750
751
            $resultset = $data->browseRow($_REQUEST['table'], $_REQUEST['key']);
752
753
            echo '<form action="'.\SUBFOLDER.'/src/views/display" method="post">'."\n";
754
            echo $this->misc->form;
755
756
            if (1 == $resultset->recordCount()) {
757
                echo "<p>{$this->lang['strconfdeleterow']}</p>"."\n";
758
759
                $fkinfo = [];
760
                echo '<table><tr>';
761
                $this->printTableHeaderCells($resultset, false, true);
762
                echo '</tr>';
763
                echo '<tr class="data1">'."\n";
764
                $this->printTableRowCells($resultset, $fkinfo, true);
765
                echo '</tr>'."\n";
766
                echo '</table>'."\n";
767
                echo '<br />'."\n";
768
769
                echo '<input type="hidden" name="action" value="delrow" />'."\n";
770
                echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />"."\n";
771
                echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />"."\n";
772
            } elseif (1 != $resultset->recordCount()) {
773
                echo "<p>{$this->lang['strrownotunique']}</p>"."\n";
774
                echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />"."\n";
775
            } else {
776
                echo "<p>{$this->lang['strinvalidparam']}</p>"."\n";
777
                echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />"."\n";
778
            }
779
            if (isset($_REQUEST['table'])) {
780
                echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'."\n";
781
            }
782
783
            if (isset($_REQUEST['subject'])) {
784
                echo '<input type="hidden" name="subject" value="', htmlspecialchars($_REQUEST['subject']), '" />'."\n";
785
            }
786
787
            if (isset($_REQUEST['query'])) {
788
                echo '<input type="hidden" name="query" value="', htmlspecialchars($_REQUEST['query']), '" />'."\n";
789
            }
790
791
            if (isset($_REQUEST['count'])) {
792
                echo '<input type="hidden" name="count" value="', htmlspecialchars($_REQUEST['count']), '" />'."\n";
793
            }
794
795
            if (isset($_REQUEST['return'])) {
796
                echo '<input type="hidden" name="return" value="', htmlspecialchars($_REQUEST['return']), '" />'."\n";
797
            }
798
799
            echo '<input type="hidden" name="page" value="', htmlspecialchars($_REQUEST['page']), '" />'."\n";
800
            echo '<input type="hidden" name="sortkey" value="', htmlspecialchars($_REQUEST['sortkey']), '" />'."\n";
801
            echo '<input type="hidden" name="sortdir" value="', htmlspecialchars($_REQUEST['sortdir']), '" />'."\n";
802
            echo '<input type="hidden" name="strings" value="', htmlspecialchars($_REQUEST['strings']), '" />'."\n";
803
            echo '<input type="hidden" name="key" value="', htmlspecialchars(urlencode(serialize($_REQUEST['key']))), '" />'."\n";
804
            echo '</form>'."\n";
805
        } else {
806
            $status = $data->deleteRow($_POST['table'], unserialize(urldecode($_POST['key'])));
807
            if (0 == $status) {
808
                $this->doBrowse($this->lang['strrowdeleted']);
809
            } elseif ($status == -2) {
810
                $this->doBrowse($this->lang['strrownotunique']);
811
            } else {
812
                $this->doBrowse($this->lang['strrowdeletedbad']);
813
            }
814
        }
815
    }
816
817
    /**
818
     * Build & return the FK information data structure
819
     * used when deciding if a field should have a FK link or not.
820
     *
821
     * @return [type] [description]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
822
     */
823
    public function &getFKInfo()
824
    {
825
        $data = $this->misc->getDatabaseAccessor();
826
827
        // Get the foreign key(s) information from the current table
828
        $fkey_information = ['byconstr' => [], 'byfield' => []];
829
830
        if (isset($_REQUEST['table'])) {
831
            $constraints = $data->getConstraintsWithFields($_REQUEST['table']);
832
            if ($constraints->recordCount() > 0) {
833
                $fkey_information['common_url'] = $this->misc->getHREF('schema').'&amp;subject=table';
834
835
                // build the FK constraints data structure
836
                while (!$constraints->EOF) {
837
                    $constr = &$constraints->fields;
838
                    if ('f' == $constr['contype']) {
839
                        if (!isset($fkey_information['byconstr'][$constr['conid']])) {
840
                            $fkey_information['byconstr'][$constr['conid']] = [
841
                                'url_data' => 'table='.urlencode($constr['f_table']).'&amp;schema='.urlencode($constr['f_schema']),
842
                                'fkeys'    => [],
843
                                'consrc'   => $constr['consrc'],
844
                            ];
845
                        }
846
847
                        $fkey_information['byconstr'][$constr['conid']]['fkeys'][$constr['p_field']] = $constr['f_field'];
848
849
                        if (!isset($fkey_information['byfield'][$constr['p_field']])) {
850
                            $fkey_information['byfield'][$constr['p_field']] = [];
851
                        }
852
853
                        $fkey_information['byfield'][$constr['p_field']][] = $constr['conid'];
854
                    }
855
                    $constraints->moveNext();
856
                }
857
            }
858
        }
859
860
        return $fkey_information;
861
    }
862
863
    /**
864
     * Print table header cells.
865
     *
866
     * @param $args - associative array for sort link parameters
0 ignored issues
show
Documentation Bug introduced by
The doc comment - at position 0 could not be parsed: Unknown type name '-' at position 0 in -.
Loading history...
867
     * @param mixed $withOid
0 ignored issues
show
Coding Style introduced by
Doc comment for parameter $withOid does not match actual variable name $args
Loading history...
868
     */
869
    public function printTableHeaderCells(&$resultset, $args, $withOid)
870
    {
871
        $data = $this->misc->getDatabaseAccessor();
872
        $j    = 0;
873
874
        foreach ($resultset->fields as $k => $v) {
875
            if (($k === $data->id) && (!($withOid && $this->conf['show_oids']))) {
876
                ++$j;
877
878
                continue;
879
            }
880
            $finfo = $resultset->fetchField($j);
881
882
            if (false === $args) {
883
                echo '<th class="data">', $this->misc->printVal($finfo->name), '</th>'."\n";
884
            } else {
885
                $args['page']    = $_REQUEST['page'];
886
                $args['sortkey'] = $j + 1;
887
                // Sort direction opposite to current direction, unless it's currently ''
888
                $args['sortdir'] = (
889
                    'asc' == $_REQUEST['sortdir']
890
                    and $_REQUEST['sortkey'] == ($j + 1)
891
                ) ? 'desc' : 'asc';
892
893
                $sortLink = http_build_query($args);
894
895
                echo "<th class=\"data\"><a href=\"?{$sortLink}\">"
896
                , $this->misc->printVal($finfo->name);
897
                if ($_REQUEST['sortkey'] == ($j + 1)) {
898
                    if ('asc' == $_REQUEST['sortdir']) {
899
                        echo '<img src="'.$this->misc->icon('RaiseArgument').'" alt="asc">';
900
                    } else {
901
                        echo '<img src="'.$this->misc->icon('LowerArgument').'" alt="desc">';
902
                    }
903
                }
904
                echo '</a></th>'."\n";
905
            }
906
            ++$j;
907
        }
908
909
        reset($resultset->fields);
910
    }
911
912
    // Print data-row cells
913
    public function printTableRowCells(&$resultset, &$fkey_information, $withOid)
1 ignored issue
show
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
914
    {
915
        $data = $this->misc->getDatabaseAccessor();
916
        $j    = 0;
917
918
        if (!isset($_REQUEST['strings'])) {
919
            $_REQUEST['strings'] = 'collapsed';
920
        }
921
922
        foreach ($resultset->fields as $k => $v) {
923
            $finfo = $resultset->fetchField($j++);
924
925
            if (($k === $data->id) && (!($withOid && $this->conf['show_oids']))) {
926
                continue;
927
            }
928
            if (null !== $v && '' == $v) {
929
                echo '<td>&nbsp;</td>';
930
            } else {
931
                echo '<td style="white-space:nowrap;">';
932
933
                if ((null !== $v) && isset($fkey_information['byfield'][$k])) {
934
                    foreach ($fkey_information['byfield'][$k] as $conid) {
935
                        $query_params = $fkey_information['byconstr'][$conid]['url_data'];
936
937
                        foreach ($fkey_information['byconstr'][$conid]['fkeys'] as $p_field => $f_field) {
938
                            $query_params .= '&amp;'.urlencode("fkey[{$f_field}]").'='.urlencode($resultset->fields[$p_field]);
939
                        }
940
941
                        // $fkey_information['common_url'] is already urlencoded
942
                        $query_params .= '&amp;'.$fkey_information['common_url'];
943
                        echo '<div style="display:inline-block;">';
944
                        echo '<a class="fk fk_'.htmlentities($conid, ENT_QUOTES, 'UTF-8')."\" href=\"display?{$query_params}\">";
945
                        echo '<img src="'.$this->misc->icon('ForeignKey').'" style="vertical-align:middle;" alt="[fk]" title="'
946
                        .htmlentities($fkey_information['byconstr'][$conid]['consrc'], ENT_QUOTES, 'UTF-8')
947
                            .'" />';
948
                        echo '</a>';
949
                        echo '</div>';
950
                    }
951
                    echo $this->misc->printVal($v, $finfo->type, ['null' => true, 'clip' => ('collapsed' == $_REQUEST['strings']), 'class' => 'fk_value']);
952
                } else {
953
                    echo $this->misc->printVal($v, $finfo->type, ['null' => true, 'clip' => ('collapsed' == $_REQUEST['strings'])]);
954
                }
955
                echo '</td>';
956
            }
957
        }
958
    }
959
960
    // Print the FK row, used in ajax requests
961
    public function doBrowseFK()
1 ignored issue
show
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
962
    {
963
        $data = $this->misc->getDatabaseAccessor();
964
965
        $ops = [];
966
        foreach ($_REQUEST['fkey'] as $x => $y) {
967
            $ops[$x] = '=';
968
        }
969
        $query             = $data->getSelectSQL($_REQUEST['table'], [], $_REQUEST['fkey'], $ops);
970
        $_REQUEST['query'] = $query;
971
972
        $fkinfo = $this->getFKInfo();
973
974
        $max_pages = 1;
975
        // Retrieve page from query.  $max_pages is returned by reference.
976
        $resultset = $data->browseQuery(
977
            'SELECT',
978
            $_REQUEST['table'],
979
            $_REQUEST['query'],
980
            null,
981
            null,
982
            1,
983
            1,
984
            $max_pages
985
        );
986
987
        echo '<a href="javascript:void(0);" style="display:table-cell;" class="fk_delete"><img alt="[delete]" src="'.$this->misc->icon('Delete').'" /></a>'."\n";
988
        echo '<div style="display:table-cell;">';
989
990
        if (is_object($resultset) && $resultset->recordCount() > 0) {
991
            /* we are browsing a referenced table here
992
             * we should show OID if show_oids is true
993
             * so we give true to withOid in functions bellow
994
             */
995
            echo '<table><tr>';
996
            $this->printTableHeaderCells($resultset, false, true);
997
            echo '</tr>';
998
            echo '<tr class="data1">'."\n";
999
            $this->printTableRowCells($resultset, $fkinfo, true);
1000
            echo '</tr>'."\n";
1001
            echo '</table>'."\n";
1002
        } else {
1003
            echo $this->lang['strnodata'];
1004
        }
1005
        echo '</div>';
1006
    }
1007
1008
    private function _getMinMaxPages($page, $pages)
1009
    {
1010
        $window = 10;
1011
        if ($page <= $window) {
1012
            $min_page = 1;
1013
            $max_page = min(2 * $window, $pages);
1014
        } elseif ($page > $window && $pages >= $page + $window) {
1015
            $min_page = ($page - $window) + 1;
1016
            $max_page = $page + $window;
1017
        } else {
1018
            $min_page = ($page - (2 * $window - ($pages - $page))) + 1;
1019
            $max_page = $pages;
1020
        }
1021
1022
        // Make sure min_page is always at least 1
1023
        // and max_page is never greater than $pages
1024
        $min_page = max($min_page, 1);
1025
        $max_page = min($max_page, $pages);
1026
1027
        return [$min_page, $max_page];
1028
    }
1029
1030
    /**
1031
     * Do multi-page navigation.  Displays the prev, next and page options.
1032
     *
1033
     * @param int    $page      - the page currently viewed
1034
     * @param int    $pages     - the maximum number of pages
1035
     * @param string $gets      -  the parameters to include in the link to the wanted page
1036
     * @param int    $max_width - the number of pages to make available at any one time (default = 20)
1037
     *
1038
     * @return string the pagination links
1039
     */
1040
    private function _printPages($page, $pages, $gets, $max_width = 20)
1041
    {
1042
        $lang = $this->lang;
1043
        $page = (int) $page;
1044
1045
        if ($page < 0 || $page > $pages || $pages <= 1 || $max_width <= 0) {
1046
            return;
1047
        }
1048
1049
        unset($gets['page']);
1050
        $url = http_build_query($gets);
1051
1052
        $result = '<p style="text-align: center">'."\n";
1053
        if ($page != 1) {
1054
            $result .= sprintf('<a class="pagenav" href="?%s&page=1">%s</a>%s&nbsp;', $url, $lang['strfirst'], "\n");
1055
            $result .= sprintf('<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $page - 1, $lang['strprev'], "\n");
1056
        }
1057
1058
        list($min_page, $max_page) = $this->_getMinMaxPages($page, $pages);
1059
1060
        for ($i = $min_page; $i <= $max_page; ++$i) {
1061
            $result .= (($i === $page) ? $i : sprintf('<a class="pagenav" href="display?%s&page=%s">%s</a>', $url, $i, $i))."\n";
1062
        }
1063
1064
        if ($page != $pages) {
1065
            $result .= sprintf('<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $page + 1, $lang['strnext'], "\n");
1066
            $result .= sprintf('&nbsp;<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $pages, $lang['strlast'], "\n");
1067
        }
1068
        $result .= "</p>\n";
1069
1070
        return $result;
1071
    }
1072
}
1073