Passed
Push — develop ( ef375c...6fc4d9 )
by Felipe
05:06
created

DisplayController::doBrowse()   D

Complexity

Conditions 14
Paths 60

Size

Total Lines 130
Code Lines 75

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 130
rs 4.9516
c 0
b 0
f 0
cc 14
eloc 75
nc 60
nop 1

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
3
/**
4
 * PHPPgAdmin v6.0.0-beta.48
5
 */
6
7
namespace PHPPgAdmin\Controller;
8
9
/**
10
 * Base controller class.
11
 *
12
 * @package PHPPgAdmin
13
 */
14
class DisplayController extends BaseController
15
{
16
    use \PHPPgAdmin\Traits\InsertEditRowTrait;
17
18
    /**
19
     * Default method to render the controller according to the action parameter.
20
     */
21
    public function render()
22
    {
23
        $this->misc     = $this->misc;
24
        $plugin_manager = $this->plugin_manager;
25
26
        if ('dobrowsefk' == $this->action) {
27
            return $this->doBrowseFK();
28
        }
29
30
        set_time_limit(0);
31
32
        $scripts = '<script src="'.\SUBFOLDER.'/assets/js/display.js" type="text/javascript"></script>';
33
34
        $scripts .= '<script type="text/javascript">'."\n";
35
        $scripts .= "var Display = {\n";
36
        $scripts .= "errmsg: '".str_replace("'", "\\'", $this->lang['strconnectionfail'])."'\n";
37
        $scripts .= "};\n";
38
        $scripts .= '</script>'."\n";
39
40
        $footer_template = 'footer.twig';
41
        $header_template = 'header.twig';
42
43
        ob_start();
44
        switch ($this->action) {
45
            case 'editrow':
46
                $header_template = 'header_sqledit.twig';
47
                $footer_template = 'footer_sqledit.twig';
48
                if (isset($_POST['save'])) {
49
                    $this->doEditRow();
50
                } else {
51
                    $this->doBrowse();
52
                }
53
54
                break;
55
            case 'confeditrow':
56
                $this->formEditRow();
57
58
                break;
59
            case 'delrow':
60
                $header_template = 'header_sqledit.twig';
61
                $footer_template = 'footer_sqledit.twig';
62
                if (isset($_POST['yes'])) {
63
                    $this->doDelRow(false);
64
                } else {
65
                    $this->doBrowse();
66
                }
67
68
                break;
69
            case 'confdelrow':
70
                $this->doDelRow(true);
71
72
                break;
73
            default:
74
                $header_template = 'header_sqledit.twig';
75
                $footer_template = 'footer_sqledit.twig';
76
                $this->doBrowse();
77
78
                break;
79
        }
80
        $output = ob_get_clean();
81
82
        $subject = $this->coalesceArr($_REQUEST, 'subject', 'table')['subject'];
83
84
        $object = null;
85
        $object = $this->setIfIsset($object, $_REQUEST[$subject]);
86
87
        // Set the title based on the subject of the request
88
        if ('table' == $subject) {
89
            $title = $this->headerTitle('strtables', '', $object);
90
        } elseif ('view' == $subject) {
91
            $title = $this->headerTitle('strviews', '', $object);
92
        } elseif ('matview' == $subject) {
93
            $title = $this->headerTitle('strviews', 'M', $object);
94
        } elseif ('column' == $subject) {
95
            $title = $this->headerTitle('strcolumn', '', $object);
96
        } else {
97
            $title = $this->headerTitle('strqueryresults');
98
        }
99
100
        $this->printHeader($title, $scripts, true, $header_template);
101
102
        $this->printBody();
103
104
        echo $output;
105
106
        $this->printFooter(true, $footer_template);
107
    }
108
109
    /**
110
     * Displays requested data.
111
     *
112
     * @param mixed $msg
113
     */
114
    public function doBrowse($msg = '')
115
    {
116
        $this->misc = $this->misc;
117
        $data       = $this->misc->getDatabaseAccessor();
118
119
        // If current page is not set, default to first page
120
        $page = $this->coalesceArr($_REQUEST, 'page', 1)['page'];
121
122
        $save_history = !isset($_REQUEST['nohistory']);
123
124
        $subject = $this->coalesceArr($_REQUEST, 'subject', 'table')['subject'];
125
126
        $object = $this->coalesceArr($_REQUEST, $subject)[$subject];
127
128
        if ($subject === 'column' && $object && isset($_REQUEST['f_schema'], $_REQUEST['f_table'])) {
129
            $f_schema = $_REQUEST['f_schema'];
130
            $f_table  = $_REQUEST['f_table'];
131
132
            $_REQUEST['query'] = "SELECT \"{$object}\",
133
            count(*) AS \"count\"
134
            FROM \"{$f_schema}\".\"{$f_table}\"
135
            GROUP BY \"{$object}\" ORDER BY \"{$object}\"";
136
        }
137
138
        //$object = $this->setIfIsset($object, $_REQUEST[$subject]);
139
140
        $this->printTrail($subject);
141
142
        $tabsPosition = 'browse';
143
        if ($subject === 'database') {
144
            $tabsPosition = 'sql';
145
        } elseif ($subject === 'column') {
146
            $tabsPosition = 'colproperties';
147
        }
148
149
        $this->printTabs($subject, $tabsPosition);
150
151
        list($query, $title, $type) = $this->getQueryTitleAndType($data);
152
        $this->printTitle($title);
153
154
        //$this->prtrace($subject, $object, $query, $_SESSION['sqlquery']);
155
156
        $this->printMsg($msg);
157
158
        // If 'sortkey' is not set, default to ''
159
        $sortkey = $this->coalesceArr($_REQUEST, 'sortkey', '')['sortkey'];
160
161
        // If 'sortdir' is not set, default to ''
162
        $sortdir = $this->coalesceArr($_REQUEST, 'sortdir', '')['sortdir'];
163
164
        // If 'strings' is not set, default to collapsed
165
        $strings = $this->coalesceArr($_REQUEST, 'strings', 'collapsed')['strings'];
166
167
        $this->coalesceArr($_REQUEST, 'schema')['schema'];
168
        $search_path = $this->coalesceArr($_REQUEST, 'search_path')['search_path'];
169
170
        // Set the schema search path
171
        if (isset($search_path) && (0 != $data->setSearchPath(array_map('trim', explode(',', $search_path))))) {
172
            return;
173
        }
174
175
        try {
176
            // Retrieve page from query.  $max_pages is returned by reference.
177
            $resultset = $data->browseQuery(
178
                $type,
179
                $object,
180
                $query,
181
                $sortkey,
182
                $sortdir,
183
                $page,
184
                $this->conf['max_rows'],
185
                $max_pages
186
            );
187
        } catch (\PHPPgAdmin\ADOdbException $e) {
188
            return $this->halt($e->getMessage());
189
        }
190
191
        // Build strings for GETs in array
192
        $_gets = [
193
            'server'   => $_REQUEST['server'],
194
            'database' => $_REQUEST['database'],
195
        ];
196
197
        $this->coalesceArr($_REQUEST, 'query');
198
        $this->coalesceArr($_REQUEST, 'count');
199
        $this->coalesceArr($_REQUEST, 'return');
200
        $this->coalesceArr($_REQUEST, 'table');
201
        $this->coalesceArr($_REQUEST, 'nohistory');
202
203
        $this->setIfIsset($_gets['schema'], $_REQUEST['schema'], null, false);
204
        $this->setIfIsset($_gets[$subject], $object, null, false);
205
        $this->setIfIsset($_gets['subject'], $subject, null, false);
206
        $this->setIfIsset($_gets['query'], $_REQUEST['query'], null, false);
207
        $this->setIfIsset($_gets['count'], $_REQUEST['count'], null, false);
208
        $this->setIfIsset($_gets['return'], $_REQUEST['return'], null, false);
209
        $this->setIfIsset($_gets['search_path'], $_REQUEST['search_path'], null, false);
210
        $this->setIfIsset($_gets['table'], $_REQUEST['table'], null, false);
211
        $this->setIfIsset($_gets['nohistory'], $_REQUEST['nohistory'], null, false);
212
        $_gets['sortkey'] = $sortkey;
213
        $_gets['sortdir'] = $sortdir;
214
        $_gets['strings'] = $strings;
215
216
        if ($save_history && is_object($resultset) && ('QUERY' == $type)) {
217
            //{
218
            $this->misc->saveScriptHistory($_REQUEST['query']);
219
        }
220
221
        $query = $query ? $query : sprintf('SELECT * FROM %s.%s', $_REQUEST['schema'], $object);
222
223
        //$query = isset($_REQUEST['query'])? $_REQUEST['query'] : "select * from {$_REQUEST['schema']}.{$_REQUEST['table']};";
224
        //$this->prtrace($query);
225
226
        //die(htmlspecialchars($query));
227
228
        echo '<form method="post" id="sqlform" action="'.$_SERVER['REQUEST_URI'].'">';
229
        echo $this->misc->form;
230
        if ($object) {
231
            echo '<input type="hidden" name="'.$subject.'" value="', htmlspecialchars($object), '" />'."\n";
232
        }
233
        echo '<textarea width="90%" name="query"  id="query" rows="5" cols="100" resizable="true">';
234
        echo htmlspecialchars($query);
235
        echo '</textarea><br><input type="submit"/>';
236
237
        echo '</form>';
238
239
        $this->printResultsTable($resultset, $page, $max_pages, $_gets, $object);
240
        // Navigation links
241
242
        $navlinks = $this->getBrowseNavLinks($type, $_gets, $page, $subject, $object, $resultset);
243
        $this->printNavLinks($navlinks, 'display-browse', get_defined_vars());
244
    }
245
246
    public function getQueryTitleAndType($data)
247
    {
248
        $fkey = $this->coalesceArr($_REQUEST, 'fkey')['fkey'];
249
250
        $query = $this->coalesceArr($_REQUEST, 'query')['query'];
251
        // This code is used when browsing FK in pure-xHTML (without js)
252
        if ($fkey) {
253
            $ops = [];
254
            foreach (array_keys($fkey) as $x) {
255
                $ops[$x] = '=';
256
            }
257
            $query             = $data->getSelectSQL($_REQUEST['table'], [], $fkey, $ops);
258
            $_REQUEST['query'] = $query;
259
        }
260
261
        $title = 'strqueryresults';
262
        $type  = 'QUERY';
263
264
        if ($object && $query) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $object seems to be never defined.
Loading history...
265
            $_SESSION['sqlquery'] = $query;
266
            $title                = 'strselect';
267
            $type                 = 'SELECT';
268
        } elseif ($object) {
269
            $title = 'strselect';
270
            $type  = 'TABLE';
271
        } elseif (isset($_SESSION['sqlquery'])) {
272
            $query = $_SESSION['sqlquery'];
273
        }
274
275
        return [$query, $title, $type];
276
    }
277
278
    public function getBrowseNavLinks($type, $_gets, $page, $subject, $object, $resultset)
279
    {
280
        $fields = [
281
            'server'   => $_REQUEST['server'],
282
            'database' => $_REQUEST['database'],
283
        ];
284
285
        $this->setIfIsset($fields['schema'], $_REQUEST['schema'], null, false);
286
287
        $navlinks = [];
288
        $strings  = $_gets['strings'];
289
        // Return
290
        if (isset($_REQUEST['return'])) {
291
            $urlvars = $this->misc->getSubjectParams($_REQUEST['return']);
292
293
            $navlinks['back'] = [
294
                'attr'    => [
295
                    'href' => [
296
                        'url'     => $urlvars['url'],
297
                        'urlvars' => $urlvars['params'],
298
                    ],
299
                ],
300
                'content' => $this->lang['strback'],
301
            ];
302
        }
303
304
        // Edit SQL link
305
        if ('QUERY' == $type) {
306
            $navlinks['edit'] = [
307
                'attr'    => [
308
                    'href' => [
309
                        'url'     => 'database',
310
                        'urlvars' => array_merge(
311
                            $fields,
312
                            [
313
                                'action'   => 'sql',
314
                                'paginate' => 'on',
315
                            ]
316
                        ),
317
                    ],
318
                ],
319
                'content' => $this->lang['streditsql'],
320
            ];
321
        }
322
323
        $navlinks['collapse'] = [
324
            'attr'    => [
325
                'href' => [
326
                    'url'     => 'display',
327
                    'urlvars' => array_merge(
328
                        $_gets,
329
                        [
330
                            'strings' => 'expanded',
331
                            'page'    => $page,
332
                        ]
333
                    ),
334
                ],
335
            ],
336
            'content' => $this->lang['strexpand'],
337
        ];
338
        // Expand/Collapse
339
        if ('expanded' == $strings) {
340
            $navlinks['collapse'] = [
341
                'attr'    => [
342
                    'href' => [
343
                        'url'     => 'display',
344
                        'urlvars' => array_merge(
345
                            $_gets,
346
                            [
347
                                'strings' => 'collapsed',
348
                                'page'    => $page,
349
                            ]
350
                        ),
351
                    ],
352
                ],
353
                'content' => $this->lang['strcollapse'],
354
            ];
355
        }
356
357
        // Create view and download
358
        if (isset($_REQUEST['query'], $resultset) && is_object($resultset) && $resultset->recordCount() > 0) {
359
            // Report views don't set a schema, so we need to disable create view in that case
360
            if (isset($_REQUEST['schema'])) {
361
                $navlinks['createview'] = [
362
                    'attr'    => [
363
                        'href' => [
364
                            'url'     => 'views',
365
                            'urlvars' => array_merge(
366
                                $fields,
367
                                [
368
                                    'action'         => 'create',
369
                                    'formDefinition' => $_REQUEST['query'],
370
                                ]
371
                            ),
372
                        ],
373
                    ],
374
                    'content' => $this->lang['strcreateview'],
375
                ];
376
            }
377
378
            $urlvars = [];
379
380
            $this->setIfIsset($urlvars['search_path'], $_REQUEST['search_path'], null, false);
381
382
            $navlinks['download'] = [
383
                'attr'    => [
384
                    'href' => [
385
                        'url'     => 'dataexport',
386
                        'urlvars' => array_merge($fields, $urlvars),
387
                    ],
388
                ],
389
                'content' => $this->lang['strdownload'],
390
            ];
391
        }
392
393
        // Insert
394
        if (isset($object) && (isset($subject) && 'table' == $subject)) {
395
            $navlinks['insert'] = [
396
                'attr'    => [
397
                    'href' => [
398
                        'url'     => 'tables',
399
                        'urlvars' => array_merge(
400
                            $fields,
401
                            [
402
                                'action' => 'confinsertrow',
403
                                'table'  => $object,
404
                            ]
405
                        ),
406
                    ],
407
                ],
408
                'content' => $this->lang['strinsert'],
409
            ];
410
        }
411
412
        // Refresh
413
        $navlinks['refresh'] = [
414
            'attr'    => [
415
                'href' => [
416
                    'url'     => 'display',
417
                    'urlvars' => array_merge(
418
                        $_gets,
419
                        [
420
                            'strings' => $strings,
421
                            'page'    => $page,
422
                        ]
423
                    ),
424
                ],
425
            ],
426
            'content' => $this->lang['strrefresh'],
427
        ];
428
429
        return $navlinks;
430
    }
431
432
    public function printResultsTable($resultset, $page, $max_pages, $_gets, $object)
433
    {
434
        if (!is_object($resultset) || $resultset->recordCount() <= 0) {
435
            echo "<p>{$this->lang['strnodata']}</p>"."\n";
436
437
            return;
438
        }
439
440
        $data           = $this->misc->getDatabaseAccessor();
441
        $plugin_manager = $this->plugin_manager;
442
        $strings        = $_gets['strings'];
443
        $key            = [];
444
445
        // Fetch unique row identifier, if this is a table browse request.
446
        if ($object) {
447
            $key = $data->getRowIdentifier($object);
448
        }
449
450
        $fkey_information = $this->getFKInfo();
451
        // Show page navigation
452
        $paginator = $this->_printPages($page, $max_pages, $_gets);
453
454
        echo $paginator;
455
        echo "<table id=\"data\">\n<tr>";
456
457
        // Check that the key is actually in the result set.  This can occur for select
458
        // operations where the key fields aren't part of the select.  XXX:  We should
459
        // be able to support this, somehow.
460
        foreach ($key as $v) {
461
            // If a key column is not found in the record set, then we
462
            // can't use the key.
463
            if (!array_key_exists($v, $resultset->fields)) {
464
                $key = [];
465
466
                break;
467
            }
468
        }
469
470
        $buttons = [
471
            'edit'   => [
472
                'content' => $this->lang['stredit'],
473
                'attr'    => [
474
                    'href' => [
475
                        'url'     => 'display',
476
                        'urlvars' => array_merge(
477
                            [
478
                                'action'  => 'confeditrow',
479
                                'strings' => $strings,
480
                                'page'    => $page,
481
                            ],
482
                            $_gets
483
                        ),
484
                    ],
485
                ],
486
            ],
487
            'delete' => [
488
                'content' => $this->lang['strdelete'],
489
                'attr'    => [
490
                    'href' => [
491
                        'url'     => 'display',
492
                        'urlvars' => array_merge(
493
                            [
494
                                'action'  => 'confdelrow',
495
                                'strings' => $strings,
496
                                'page'    => $page,
497
                            ],
498
                            $_gets
499
                        ),
500
                    ],
501
                ],
502
            ],
503
        ];
504
        $actions = [
505
            'actionbuttons' => &$buttons,
506
            'place'         => 'display-browse',
507
        ];
508
        $plugin_manager->doHook('actionbuttons', $actions);
509
510
        foreach (array_keys($actions['actionbuttons']) as $this->action) {
511
            $actions['actionbuttons'][$this->action]['attr']['href']['urlvars'] = array_merge(
512
                $actions['actionbuttons'][$this->action]['attr']['href']['urlvars'],
513
                $_gets
514
            );
515
        }
516
517
        $edit_params = isset($actions['actionbuttons']['edit']) ?
518
        $actions['actionbuttons']['edit'] : [];
519
        $delete_params = isset($actions['actionbuttons']['delete']) ?
520
        $actions['actionbuttons']['delete'] : [];
521
522
        // Display edit and delete actions if we have a key
523
        $colspan = count($buttons);
524
        if ($colspan > 0 and count($key) > 0) {
525
            echo "<th colspan=\"{$colspan}\" class=\"data\">{$this->lang['stractions']}</th>"."\n";
526
        }
527
528
        // we show OIDs only if we are in TABLE or SELECT type browsing
529
        $this->printTableHeaderCells($resultset, $_gets, isset($object));
530
531
        echo '</tr>'."\n";
532
533
        $i = 0;
534
        reset($resultset->fields);
535
        while (!$resultset->EOF) {
536
            $id = (0 == ($i % 2) ? '1' : '2');
537
            echo "<tr class=\"data{$id}\">"."\n";
538
            // Display edit and delete links if we have a key
539
            if ($colspan <= 0 || count($key) <= 0) {
540
                continue;
541
            }
542
            $keys_array = [];
543
            $has_nulls  = false;
544
            foreach ($key as $v) {
545
                if (null === $resultset->fields[$v]) {
546
                    $has_nulls = true;
547
548
                    break;
549
                }
550
                $keys_array["key[{$v}]"] = $resultset->fields[$v];
551
            }
552
            if ($has_nulls) {
553
                echo "<td colspan=\"{$colspan}\">&nbsp;</td>"."\n";
554
                $this->printTableRowCells($resultset, $fkey_information, isset($object));
555
556
                echo '</tr>'."\n";
557
                $resultset->moveNext();
558
                ++$i;
559
560
                continue;
561
            }
562
            if (isset($actions['actionbuttons']['edit'])) {
563
                $actions['actionbuttons']['edit']                            = $edit_params;
564
                $actions['actionbuttons']['edit']['attr']['href']['urlvars'] = array_merge(
565
                    $actions['actionbuttons']['edit']['attr']['href']['urlvars'],
566
                    $keys_array
567
                );
568
            }
569
570
            if (isset($actions['actionbuttons']['delete'])) {
571
                $actions['actionbuttons']['delete']                            = $delete_params;
572
                $actions['actionbuttons']['delete']['attr']['href']['urlvars'] = array_merge(
573
                    $actions['actionbuttons']['delete']['attr']['href']['urlvars'],
574
                    $keys_array
575
                );
576
            }
577
578
            foreach ($actions['actionbuttons'] as $this->action) {
579
                echo "<td class=\"opbutton{$id}\">";
580
                $this->printLink($this->action, true, __METHOD__);
581
                echo '</td>'."\n";
582
            }
583
584
            $this->printTableRowCells($resultset, $fkey_information, isset($object));
585
586
            echo '</tr>'."\n";
587
            $resultset->moveNext();
588
            ++$i;
589
        }
590
        echo '</table>'."\n";
591
592
        echo '<p>', $resultset->recordCount(), " {$this->lang['strrows']}</p>"."\n";
593
        // Show page navigation
594
        echo $paginator;
595
    }
596
597
    /**
598
     * Print table header cells.
599
     *
600
     * @param \PHPPgAdmin\ADORecordSet $resultset set of results from getRow operation
601
     * @param array|bool               $args      - associative array for sort link parameters, or false if there isn't any
602
     * @param bool                     $withOid   either to display OIDs or not
603
     */
604
    public function printTableHeaderCells(&$resultset, $args, $withOid)
605
    {
606
        $data = $this->misc->getDatabaseAccessor();
607
608
        if (!is_array($resultset->fields)) {
1 ignored issue
show
introduced by
The condition is_array($resultset->fields) is always false.
Loading history...
609
            return;
610
        }
611
612
        foreach (array_keys($resultset->fields) as $index => $key) {
613
            if (($key === $data->id) && (!($withOid && $this->conf['show_oids']))) {
614
                continue;
615
            }
616
            $finfo = $resultset->fetchField($index);
617
618
            if (false === $args) {
619
                echo '<th class="data">', $this->misc->printVal($finfo->name), '</th>'."\n";
620
621
                continue;
622
            }
623
            $args['page']    = $_REQUEST['page'];
624
            $args['sortkey'] = $index + 1;
625
            // Sort direction opposite to current direction, unless it's currently ''
626
            $args['sortdir'] = ('asc' == $_REQUEST['sortdir'] && $_REQUEST['sortkey'] == ($index + 1)) ? 'desc' : 'asc';
627
628
            $sortLink = http_build_query($args);
629
630
            echo "<th class=\"data\"><a href=\"?{$sortLink}\">";
631
            echo $this->misc->printVal($finfo->name);
632
            if ($_REQUEST['sortkey'] == ($index + 1)) {
633
                $icon = ('asc' == $_REQUEST['sortdir']) ? $this->misc->icon('RaiseArgument') : $this->misc->icon('LowerArgument');
634
                echo sprintf('<img src="%s" alt="%s">', $icon, $_REQUEST['sortdir']);
635
            }
636
            echo '</a></th>'."\n";
637
        }
638
639
        reset($resultset->fields);
640
    }
641
642
    /**
643
     * Print table rows.
644
     *
645
     * @param \PHPPgAdmin\ADORecordSet $resultset        The resultset
646
     * @param array                    $fkey_information The fkey information
647
     * @param bool                     $withOid          either to display OIDs or not
648
     */
649
    public function printTableRowCells(&$resultset, &$fkey_information, $withOid)
650
    {
651
        $data = $this->misc->getDatabaseAccessor();
652
        $j    = 0;
653
654
        $this->coalesceArr($_REQUEST, 'strings', 'collapsed');
655
656
        foreach ($resultset->fields as $k => $v) {
657
            $finfo = $resultset->fetchField($j++);
658
659
            if (($k === $data->id) && (!($withOid && $this->conf['show_oids']))) {
660
                continue;
661
            }
662
            $printvalOpts = ['null' => true, 'clip' => ('collapsed' == $_REQUEST['strings'])];
663
            if (null !== $v && '' == $v) {
664
                echo '<td>&nbsp;</td>';
665
            } else {
666
                echo '<td style="white-space:nowrap;">';
667
668
                if ((null !== $v) && isset($fkey_information['byfield'][$k])) {
669
                    foreach ($fkey_information['byfield'][$k] as $conid) {
670
                        $query_params = $fkey_information['byconstr'][$conid]['url_data'];
671
672
                        foreach ($fkey_information['byconstr'][$conid]['fkeys'] as $p_field => $f_field) {
673
                            $query_params .= '&amp;'.urlencode("fkey[{$f_field}]").'='.urlencode($resultset->fields[$p_field]);
674
                        }
675
676
                        // $fkey_information['common_url'] is already urlencoded
677
                        $query_params .= '&amp;'.$fkey_information['common_url'];
678
                        echo '<div style="display:inline-block;">';
679
                        echo '<a class="fk fk_'.htmlentities($conid, ENT_QUOTES, 'UTF-8')."\" href=\"display?{$query_params}\">";
680
                        echo '<img src="'.$this->misc->icon('ForeignKey').'" style="vertical-align:middle;" alt="[fk]" title="'
681
                        .htmlentities($fkey_information['byconstr'][$conid]['consrc'], ENT_QUOTES, 'UTF-8')
682
                            .'" />';
683
                        echo '</a>';
684
                        echo '</div>';
685
                    }
686
                    $printvalOpts['class'] = 'fk_value';
687
                }
688
                $val = $this->misc->printVal($v, $finfo->type, $printvalOpts);
689
690
                echo $val;
691
                echo '</td>';
692
            }
693
        }
694
    }
695
696
    /**
697
     * Show form to edit row.
698
     *
699
     * @param string $msg message to display on top of the form or after performing edition
700
     */
701
    public function formEditRow($msg = '')
702
    {
703
        $data = $this->misc->getDatabaseAccessor();
704
705
        if (is_array($_REQUEST['key'])) {
706
            $key = $_REQUEST['key'];
707
        } else {
708
            $key = unserialize(urldecode($_REQUEST['key']));
709
        }
710
711
        $this->printTrail($_REQUEST['subject']);
712
        $this->printTitle($this->lang['streditrow']);
713
        $this->printMsg($msg);
714
715
        $attrs     = $data->getTableAttributes($_REQUEST['table']);
716
        $resultset = $data->browseRow($_REQUEST['table'], $key);
717
718
        $fksprops = $this->_getFKProps();
719
720
        echo '<form action="'.\SUBFOLDER.'/src/views/display" method="post" id="ac_form">'."\n";
721
722
        $elements = 0;
723
        $error    = true;
724
        if (1 == $resultset->recordCount() && $attrs->recordCount() > 0) {
725
            echo '<table>'."\n";
726
727
            // Output table header
728
            echo "<tr><th class=\"data\">{$this->lang['strcolumn']}</th><th class=\"data\">{$this->lang['strtype']}</th>";
729
            echo "<th class=\"data\">{$this->lang['strformat']}</th>"."\n";
730
            echo "<th class=\"data\">{$this->lang['strnull']}</th><th class=\"data\">{$this->lang['strvalue']}</th></tr>";
731
732
            $i = 0;
733
            while (!$attrs->EOF) {
734
                $attrs->fields['attnotnull'] = $data->phpBool($attrs->fields['attnotnull']);
735
                $id                          = (0 == ($i % 2) ? '1' : '2');
736
737
                // Initialise variables
738
                if (!isset($_REQUEST['format'][$attrs->fields['attname']])) {
739
                    $_REQUEST['format'][$attrs->fields['attname']] = 'VALUE';
740
                }
741
742
                echo "<tr class=\"data{$id}\">"."\n";
743
                echo '<td style="white-space:nowrap;">', $this->misc->printVal($attrs->fields['attname']), '</td>';
744
                echo '<td style="white-space:nowrap;">'."\n";
745
                echo $this->misc->printVal($data->formatType($attrs->fields['type'], $attrs->fields['atttypmod']));
746
                echo '<input type="hidden" name="types[', htmlspecialchars($attrs->fields['attname']), ']" value="',
747
                htmlspecialchars($attrs->fields['type']), '" /></td>';
748
                ++$elements;
749
                echo '<td style="white-space:nowrap;">'."\n";
750
                echo '<select name="format['.htmlspecialchars($attrs->fields['attname']), ']">'."\n";
751
                echo '<option value="VALUE"', ($_REQUEST['format'][$attrs->fields['attname']] == 'VALUE') ? ' selected="selected"' : '', ">{$this->lang['strvalue']}</option>"."\n";
752
                $selected = ($_REQUEST['format'][$attrs->fields['attname']] == 'EXPRESSION') ? ' selected="selected"' : '';
753
                echo '<option value="EXPRESSION"'.$selected.">{$this->lang['strexpression']}</option>"."\n";
754
                echo "</select>\n</td>"."\n";
755
                ++$elements;
756
                echo '<td style="white-space:nowrap;">';
757
                // Output null box if the column allows nulls (doesn't look at CHECKs or ASSERTIONS)
758
                if (!$attrs->fields['attnotnull']) {
759
                    // Set initial null values
760
                    if ('confeditrow' == $_REQUEST['action'] && null === $resultset->fields[$attrs->fields['attname']]) {
761
                        $_REQUEST['nulls'][$attrs->fields['attname']] = 'on';
762
                    }
763
                    echo "<label><span><input type=\"checkbox\" class=\"nullcheckbox\" name=\"nulls[{$attrs->fields['attname']}]\"",
764
                    isset($_REQUEST['nulls'][$attrs->fields['attname']]) ? ' checked="checked"' : '', ' /></span></label></td>'."\n";
765
                    ++$elements;
766
                } else {
767
                    echo '&nbsp;</td>';
768
                }
769
770
                echo "<td id=\"row_att_{$attrs->fields['attnum']}\" style=\"white-space:nowrap;\">";
771
772
                $extras = [];
773
774
                // If the column allows nulls, then we put a JavaScript action on the data field to unset the
775
                // NULL checkbox as soon as anything is entered in the field.  We use the $elements variable to
776
                // keep track of which element offset we're up to.  We can't refer to the null checkbox by name
777
                // as it contains '[' and ']' characters.
778
                if (!$attrs->fields['attnotnull']) {
779
                    $extras['class'] = 'insert_row_input';
780
                }
781
782
                if ((false !== $fksprops) && isset($fksprops['byfield'][$attrs->fields['attnum']])) {
783
                    $extras['id']           = "attr_{$attrs->fields['attnum']}";
784
                    $extras['autocomplete'] = 'off';
785
                }
786
787
                echo $data->printField("values[{$attrs->fields['attname']}]", $resultset->fields[$attrs->fields['attname']], $attrs->fields['type'], $extras);
788
789
                echo '</td>';
790
                ++$elements;
791
                echo '</tr>'."\n";
792
                ++$i;
793
                $attrs->moveNext();
794
            }
795
            echo '</table>'."\n";
796
797
            $error = false;
798
        } elseif (1 != $resultset->recordCount()) {
799
            echo "<p>{$this->lang['strrownotunique']}</p>"."\n";
800
        } else {
801
            echo "<p>{$this->lang['strinvalidparam']}</p>"."\n";
802
        }
803
804
        echo '<input type="hidden" name="action" value="editrow" />'."\n";
805
        echo $this->misc->form;
806
        if (isset($_REQUEST['table'])) {
807
            echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'."\n";
808
        }
809
810
        if (isset($_REQUEST['subject'])) {
811
            echo '<input type="hidden" name="subject" value="', htmlspecialchars($_REQUEST['subject']), '" />'."\n";
812
        }
813
814
        if (isset($_REQUEST['query'])) {
815
            echo '<input type="hidden" name="query" value="', htmlspecialchars($_REQUEST['query']), '" />'."\n";
816
        }
817
818
        if (isset($_REQUEST['count'])) {
819
            echo '<input type="hidden" name="count" value="', htmlspecialchars($_REQUEST['count']), '" />'."\n";
820
        }
821
822
        if (isset($_REQUEST['return'])) {
823
            echo '<input type="hidden" name="return" value="', htmlspecialchars($_REQUEST['return']), '" />'."\n";
824
        }
825
826
        echo '<input type="hidden" name="page" value="', htmlspecialchars($_REQUEST['page']), '" />'."\n";
827
        echo '<input type="hidden" name="sortkey" value="', htmlspecialchars($_REQUEST['sortkey']), '" />'."\n";
828
        echo '<input type="hidden" name="sortdir" value="', htmlspecialchars($_REQUEST['sortdir']), '" />'."\n";
829
        echo '<input type="hidden" name="strings" value="', htmlspecialchars($_REQUEST['strings']), '" />'."\n";
830
        echo '<input type="hidden" name="key" value="', htmlspecialchars(urlencode(serialize($key))), '" />'."\n";
831
        echo '<p>';
832
        if (!$error) {
833
            echo "<input type=\"submit\" name=\"save\" accesskey=\"r\" value=\"{$this->lang['strsave']}\" />"."\n";
834
        }
835
836
        echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />"."\n";
837
838
        if (false !== $fksprops) {
839
            if ('default off' != $this->conf['autocomplete']) {
840
                echo "<input type=\"checkbox\" id=\"no_ac\" value=\"1\" checked=\"checked\" /><label for=\"no_ac\">{$this->lang['strac']}</label>"."\n";
841
            } else {
842
                echo "<input type=\"checkbox\" id=\"no_ac\" value=\"0\" /><label for=\"no_ac\">{$this->lang['strac']}</label>"."\n";
843
            }
844
        }
845
846
        echo '</p>'."\n";
847
        echo '</form>'."\n";
848
        echo '<script src="'.\SUBFOLDER.'/assets/js/insert_or_edit_row.js" type="text/javascript"></script>';
849
    }
850
851
    /**
852
     * Performs actual edition of row.
853
     */
854
    public function doEditRow()
855
    {
856
        $data = $this->misc->getDatabaseAccessor();
857
858
        if (is_array($_REQUEST['key'])) {
859
            $key = $_REQUEST['key'];
860
        } else {
861
            $key = unserialize(urldecode($_REQUEST['key']));
862
        }
863
864
        $this->coalesceArr($_POST, 'values', []);
865
866
        $this->coalesceArr($_POST, 'nulls', []);
867
868
        $status = $data->editRow(
869
            $_POST['table'],
870
            $_POST['values'],
871
            $_POST['nulls'],
872
            $_POST['format'],
873
            $_POST['types'],
874
            $key
875
        );
876
        if (0 == $status) {
877
            return $this->doBrowse($this->lang['strrowupdated']);
878
        }
879
        if ($status == -2) {
880
            return $this->formEditRow($this->lang['strrownotunique']);
881
        }
882
883
        return $this->formEditRow($this->lang['strrowupdatedbad']);
884
    }
885
886
    /**
887
     * Show confirmation of drop and perform actual drop.
888
     *
889
     * @param mixed $confirm
890
     */
891
    public function doDelRow($confirm)
892
    {
893
        $data = $this->misc->getDatabaseAccessor();
894
895
        if ($confirm) {
896
            $this->printTrail($_REQUEST['subject']);
897
            $this->printTitle($this->lang['strdeleterow']);
898
899
            $resultset = $data->browseRow($_REQUEST['table'], $_REQUEST['key']);
900
901
            echo '<form action="'.\SUBFOLDER.'/src/views/display" method="post">'."\n";
902
            echo $this->misc->form;
903
904
            if (1 == $resultset->recordCount()) {
905
                echo "<p>{$this->lang['strconfdeleterow']}</p>"."\n";
906
907
                $fkinfo = [];
908
                echo '<table><tr>';
909
                $this->printTableHeaderCells($resultset, false, true);
910
                echo '</tr>';
911
                echo '<tr class="data1">'."\n";
912
                $this->printTableRowCells($resultset, $fkinfo, true);
913
                echo '</tr>'."\n";
914
                echo '</table>'."\n";
915
                echo '<br />'."\n";
916
917
                echo '<input type="hidden" name="action" value="delrow" />'."\n";
918
                echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />"."\n";
919
                echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />"."\n";
920
            } elseif (1 != $resultset->recordCount()) {
921
                echo "<p>{$this->lang['strrownotunique']}</p>"."\n";
922
                echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />"."\n";
923
            } else {
924
                echo "<p>{$this->lang['strinvalidparam']}</p>"."\n";
925
                echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />"."\n";
926
            }
927
            if (isset($_REQUEST['table'])) {
928
                echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'."\n";
929
            }
930
931
            if (isset($_REQUEST['subject'])) {
932
                echo '<input type="hidden" name="subject" value="', htmlspecialchars($_REQUEST['subject']), '" />'."\n";
933
            }
934
935
            if (isset($_REQUEST['query'])) {
936
                echo '<input type="hidden" name="query" value="', htmlspecialchars($_REQUEST['query']), '" />'."\n";
937
            }
938
939
            if (isset($_REQUEST['count'])) {
940
                echo '<input type="hidden" name="count" value="', htmlspecialchars($_REQUEST['count']), '" />'."\n";
941
            }
942
943
            if (isset($_REQUEST['return'])) {
944
                echo '<input type="hidden" name="return" value="', htmlspecialchars($_REQUEST['return']), '" />'."\n";
945
            }
946
947
            echo '<input type="hidden" name="page" value="', htmlspecialchars($_REQUEST['page']), '" />'."\n";
948
            echo '<input type="hidden" name="sortkey" value="', htmlspecialchars($_REQUEST['sortkey']), '" />'."\n";
949
            echo '<input type="hidden" name="sortdir" value="', htmlspecialchars($_REQUEST['sortdir']), '" />'."\n";
950
            echo '<input type="hidden" name="strings" value="', htmlspecialchars($_REQUEST['strings']), '" />'."\n";
951
            echo '<input type="hidden" name="key" value="', htmlspecialchars(urlencode(serialize($_REQUEST['key']))), '" />'."\n";
952
            echo '</form>'."\n";
953
        } else {
954
            $status = $data->deleteRow($_POST['table'], unserialize(urldecode($_POST['key'])));
955
            if (0 == $status) {
956
                $this->doBrowse($this->lang['strrowdeleted']);
957
            } elseif ($status == -2) {
958
                $this->doBrowse($this->lang['strrownotunique']);
959
            } else {
960
                $this->doBrowse($this->lang['strrowdeletedbad']);
961
            }
962
        }
963
    }
964
965
    /**
966
     * Build & return the FK information data structure
967
     * used when deciding if a field should have a FK link or not.
968
     *
969
     * @return array associative array describing the FK
970
     */
971
    public function &getFKInfo()
972
    {
973
        $data = $this->misc->getDatabaseAccessor();
974
975
        // Get the foreign key(s) information from the current table
976
        $fkey_information = ['byconstr' => [], 'byfield' => []];
977
978
        if (isset($_REQUEST['table'])) {
979
            $constraints = $data->getConstraintsWithFields($_REQUEST['table']);
980
            if ($constraints->recordCount() > 0) {
981
                $fkey_information['common_url'] = $this->misc->getHREF('schema').'&amp;subject=table';
982
983
                // build the FK constraints data structure
984
                while (!$constraints->EOF) {
985
                    $constr = &$constraints->fields;
986
                    if ('f' == $constr['contype']) {
987
                        if (!isset($fkey_information['byconstr'][$constr['conid']])) {
988
                            $fkey_information['byconstr'][$constr['conid']] = [
989
                                'url_data' => 'table='.urlencode($constr['f_table']).'&amp;schema='.urlencode($constr['f_schema']),
990
                                'fkeys'    => [],
991
                                'consrc'   => $constr['consrc'],
992
                            ];
993
                        }
994
995
                        $fkey_information['byconstr'][$constr['conid']]['fkeys'][$constr['p_field']] = $constr['f_field'];
996
997
                        if (!isset($fkey_information['byfield'][$constr['p_field']])) {
998
                            $fkey_information['byfield'][$constr['p_field']] = [];
999
                        }
1000
1001
                        $fkey_information['byfield'][$constr['p_field']][] = $constr['conid'];
1002
                    }
1003
                    $constraints->moveNext();
1004
                }
1005
            }
1006
        }
1007
1008
        return $fkey_information;
1009
    }
1010
1011
    // Print the FK row, used in ajax requests
1012
    public function doBrowseFK()
1013
    {
1014
        $data = $this->misc->getDatabaseAccessor();
1015
1016
        $ops = [];
1017
        foreach ($_REQUEST['fkey'] as $x => $y) {
1018
            $ops[$x] = '=';
1019
        }
1020
        $query             = $data->getSelectSQL($_REQUEST['table'], [], $_REQUEST['fkey'], $ops);
1021
        $_REQUEST['query'] = $query;
1022
1023
        $fkinfo = $this->getFKInfo();
1024
1025
        $max_pages = 1;
1026
        // Retrieve page from query.  $max_pages is returned by reference.
1027
        $resultset = $data->browseQuery(
1028
            'SELECT',
1029
            $_REQUEST['table'],
1030
            $_REQUEST['query'],
1031
            null,
1032
            null,
1033
            1,
1034
            1,
1035
            $max_pages
1036
        );
1037
1038
        echo '<a href="javascript:void(0);" style="display:table-cell;" class="fk_delete"><img alt="[delete]" src="'.$this->misc->icon('Delete').'" /></a>'."\n";
1039
        echo '<div style="display:table-cell;">';
1040
1041
        if (is_object($resultset) && $resultset->recordCount() > 0) {
1042
            /* we are browsing a referenced table here
1043
             * we should show OID if show_oids is true
1044
             * so we give true to withOid in functions bellow
1045
             */
1046
            echo '<table><tr>';
1047
            $this->printTableHeaderCells($resultset, false, true);
1048
            echo '</tr>';
1049
            echo '<tr class="data1">'."\n";
1050
            $this->printTableRowCells($resultset, $fkinfo, true);
1051
            echo '</tr>'."\n";
1052
            echo '</table>'."\n";
1053
        } else {
1054
            echo $this->lang['strnodata'];
1055
        }
1056
        echo '</div>';
1057
    }
1058
1059
    private function _getMinMaxPages($page, $pages)
1060
    {
1061
        $window = 10;
1062
        if ($page <= $window) {
1063
            $min_page = 1;
1064
            $max_page = min(2 * $window, $pages);
1065
        } elseif ($page > $window && $pages >= $page + $window) {
1066
            $min_page = ($page - $window) + 1;
1067
            $max_page = $page + $window;
1068
        } else {
1069
            $min_page = ($page - (2 * $window - ($pages - $page))) + 1;
1070
            $max_page = $pages;
1071
        }
1072
1073
        // Make sure min_page is always at least 1
1074
        // and max_page is never greater than $pages
1075
        $min_page = max($min_page, 1);
1076
        $max_page = min($max_page, $pages);
1077
1078
        return [$min_page, $max_page];
1079
    }
1080
1081
    /**
1082
     * Do multi-page navigation.  Displays the prev, next and page options.
1083
     *
1084
     * @param int   $page      - the page currently viewed
1085
     * @param int   $pages     - the maximum number of pages
1086
     * @param array $gets      -  the parameters to include in the link to the wanted page
1087
     * @param int   $max_width - the number of pages to make available at any one time (default = 20)
1088
     *
1089
     * @return string the pagination links
1090
     */
1091
    private function _printPages($page, $pages, $gets, $max_width = 20)
1092
    {
1093
        $lang = $this->lang;
1094
        $page = (int) $page;
1095
1096
        if ($page < 0 || $page > $pages || $pages <= 1 || $max_width <= 0) {
1097
            return;
1098
        }
1099
1100
        unset($gets['page']);
1101
        $url = http_build_query($gets);
1102
1103
        $result = '<p style="text-align: center">'."\n";
1104
        if ($page != 1) {
1105
            $result .= sprintf('<a class="pagenav" href="?%s&page=1">%s</a>%s&nbsp;', $url, $lang['strfirst'], "\n");
1106
            $result .= sprintf('<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $page - 1, $lang['strprev'], "\n");
1107
        }
1108
1109
        list($min_page, $max_page) = $this->_getMinMaxPages($page, $pages);
1110
1111
        for ($i = $min_page; $i <= $max_page; ++$i) {
1112
            $result .= (($i === $page) ? $i : sprintf('<a class="pagenav" href="display?%s&page=%s">%s</a>', $url, $i, $i))."\n";
1113
        }
1114
1115
        if ($page != $pages) {
1116
            $result .= sprintf('<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $page + 1, $lang['strnext'], "\n");
1117
            $result .= sprintf('&nbsp;<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $pages, $lang['strlast'], "\n");
1118
        }
1119
        $result .= "</p>\n";
1120
1121
        return $result;
1122
    }
1123
}
1124