Passed
Push — develop ( 4adbd4...ca4520 )
by Felipe
04:50
created

DisplayController::_unserializeIfNotArray()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 2
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
    private function _unserializeIfNotArray($the_array, $key)
697
    {
698
        if (!isset($the_array[$key])) {
699
            return [];
700
        }
701
        if (is_array($the_array[$key])) {
702
            return $the_array[$key];
703
        }
704
705
        return unserialize(urldecode($the_array[$key]));
706
    }
707
708
    /**
709
     * Show form to edit row.
710
     *
711
     * @param string $msg message to display on top of the form or after performing edition
712
     */
713
    public function formEditRow($msg = '')
714
    {
715
        $data = $this->misc->getDatabaseAccessor();
716
717
        $key = $this->_unserializeIfNotArray($_REQUEST, 'key');
718
719
        $this->printTrail($_REQUEST['subject']);
720
        $this->printTitle($this->lang['streditrow']);
721
        $this->printMsg($msg);
722
723
        $attrs     = $data->getTableAttributes($_REQUEST['table']);
724
        $resultset = $data->browseRow($_REQUEST['table'], $key);
725
726
        $fksprops = $this->_getFKProps();
727
728
        echo '<form action="'.\SUBFOLDER.'/src/views/display" method="post" id="ac_form">'."\n";
729
730
        $elements = 0;
731
        $error    = true;
732
        if (1 == $resultset->recordCount() && $attrs->recordCount() > 0) {
733
            echo '<table>'."\n";
734
735
            // Output table header
736
            echo "<tr><th class=\"data\">{$this->lang['strcolumn']}</th><th class=\"data\">{$this->lang['strtype']}</th>";
737
            echo "<th class=\"data\">{$this->lang['strformat']}</th>"."\n";
738
            echo "<th class=\"data\">{$this->lang['strnull']}</th><th class=\"data\">{$this->lang['strvalue']}</th></tr>";
739
740
            $i = 0;
741
            while (!$attrs->EOF) {
742
                $attrs->fields['attnotnull'] = $data->phpBool($attrs->fields['attnotnull']);
743
                $id                          = (0 == ($i % 2) ? '1' : '2');
744
745
                // Initialise variables
746
                if (!isset($_REQUEST['format'][$attrs->fields['attname']])) {
747
                    $_REQUEST['format'][$attrs->fields['attname']] = 'VALUE';
748
                }
749
750
                echo "<tr class=\"data{$id}\">"."\n";
751
                echo '<td style="white-space:nowrap;">', $this->misc->printVal($attrs->fields['attname']), '</td>';
752
                echo '<td style="white-space:nowrap;">'."\n";
753
                echo $this->misc->printVal($data->formatType($attrs->fields['type'], $attrs->fields['atttypmod']));
754
                echo '<input type="hidden" name="types[', htmlspecialchars($attrs->fields['attname']), ']" value="',
755
                htmlspecialchars($attrs->fields['type']), '" /></td>';
756
                ++$elements;
757
                echo '<td style="white-space:nowrap;">'."\n";
758
                echo '<select name="format['.htmlspecialchars($attrs->fields['attname']), ']">'."\n";
759
                echo '<option value="VALUE"', ($_REQUEST['format'][$attrs->fields['attname']] == 'VALUE') ? ' selected="selected"' : '', ">{$this->lang['strvalue']}</option>"."\n";
760
                $selected = ($_REQUEST['format'][$attrs->fields['attname']] == 'EXPRESSION') ? ' selected="selected"' : '';
761
                echo '<option value="EXPRESSION"'.$selected.">{$this->lang['strexpression']}</option>"."\n";
762
                echo "</select>\n</td>"."\n";
763
                ++$elements;
764
                echo '<td style="white-space:nowrap;">';
765
                // Output null box if the column allows nulls (doesn't look at CHECKs or ASSERTIONS)
766
                if (!$attrs->fields['attnotnull']) {
767
                    // Set initial null values
768
                    if ('confeditrow' == $_REQUEST['action'] && null === $resultset->fields[$attrs->fields['attname']]) {
769
                        $_REQUEST['nulls'][$attrs->fields['attname']] = 'on';
770
                    }
771
                    echo "<label><span><input type=\"checkbox\" class=\"nullcheckbox\" name=\"nulls[{$attrs->fields['attname']}]\"",
772
                    isset($_REQUEST['nulls'][$attrs->fields['attname']]) ? ' checked="checked"' : '', ' /></span></label></td>'."\n";
773
                    ++$elements;
774
                } else {
775
                    echo '&nbsp;</td>';
776
                }
777
778
                echo "<td id=\"row_att_{$attrs->fields['attnum']}\" style=\"white-space:nowrap;\">";
779
780
                $extras = [];
781
782
                // If the column allows nulls, then we put a JavaScript action on the data field to unset the
783
                // NULL checkbox as soon as anything is entered in the field.  We use the $elements variable to
784
                // keep track of which element offset we're up to.  We can't refer to the null checkbox by name
785
                // as it contains '[' and ']' characters.
786
                if (!$attrs->fields['attnotnull']) {
787
                    $extras['class'] = 'insert_row_input';
788
                }
789
790
                if ((false !== $fksprops) && isset($fksprops['byfield'][$attrs->fields['attnum']])) {
791
                    $extras['id']           = "attr_{$attrs->fields['attnum']}";
792
                    $extras['autocomplete'] = 'off';
793
                }
794
795
                echo $data->printField("values[{$attrs->fields['attname']}]", $resultset->fields[$attrs->fields['attname']], $attrs->fields['type'], $extras);
796
797
                echo '</td>';
798
                ++$elements;
799
                echo '</tr>'."\n";
800
                ++$i;
801
                $attrs->moveNext();
802
            }
803
            echo '</table>'."\n";
804
805
            $error = false;
806
        } elseif (1 != $resultset->recordCount()) {
807
            echo "<p>{$this->lang['strrownotunique']}</p>"."\n";
808
        } else {
809
            echo "<p>{$this->lang['strinvalidparam']}</p>"."\n";
810
        }
811
812
        echo '<input type="hidden" name="action" value="editrow" />'."\n";
813
        echo $this->misc->form;
814
        echo isset($_REQUEST['table']) ? sprintf('<input type="hidden" name="table" value="%s" />%s', htmlspecialchars($_REQUEST['table']), "\n") : '';
815
816
        echo isset($_REQUEST['subject']) ? sprintf('<input type="hidden" name="subject" value="%s" />%s', htmlspecialchars($_REQUEST['subject']), "\n") : '';
817
818
        echo isset($_REQUEST['query']) ? sprintf('<input type="hidden" name="query" value="%s" />%s', htmlspecialchars($_REQUEST['query']), "\n") : '';
819
820
        echo isset($_REQUEST['count']) ? sprintf('<input type="hidden" name="count" value="%s" />%s', htmlspecialchars($_REQUEST['count']), "\n") : '';
821
822
        echo isset($_REQUEST['return']) ? sprintf('<input type="hidden" name="return" value="%s" />%s', htmlspecialchars($_REQUEST['return']), "\n") : '';
823
824
        echo '<input type="hidden" name="page" value="', htmlspecialchars($_REQUEST['page']), '" />'."\n";
825
        echo '<input type="hidden" name="sortkey" value="', htmlspecialchars($_REQUEST['sortkey']), '" />'."\n";
826
        echo '<input type="hidden" name="sortdir" value="', htmlspecialchars($_REQUEST['sortdir']), '" />'."\n";
827
        echo '<input type="hidden" name="strings" value="', htmlspecialchars($_REQUEST['strings']), '" />'."\n";
828
        echo '<input type="hidden" name="key" value="', htmlspecialchars(urlencode(serialize($key))), '" />'."\n";
829
        echo '<p>';
830
        if (!$error) {
831
            echo "<input type=\"submit\" name=\"save\" accesskey=\"r\" value=\"{$this->lang['strsave']}\" />"."\n";
832
        }
833
834
        echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />"."\n";
835
836
        if (false !== $fksprops) {
837
            $autocomplete_string = "<input type=\"checkbox\" id=\"no_ac\" value=\"0\" /><label for=\"no_ac\">{$this->lang['strac']}</label>";
838
            if ('default off' != $this->conf['autocomplete']) {
839
                $autocomplete_string = "<input type=\"checkbox\" id=\"no_ac\" value=\"1\" checked=\"checked\" /><label for=\"no_ac\">{$this->lang['strac']}</label>";
840
            }
841
            echo $autocomplete_string."\n";
842
        }
843
844
        echo '</p>'."\n";
845
        echo '</form>'."\n";
846
        echo '<script src="'.\SUBFOLDER.'/assets/js/insert_or_edit_row.js" type="text/javascript"></script>';
847
    }
848
849
    /**
850
     * Performs actual edition of row.
851
     */
852
    public function doEditRow()
853
    {
854
        $data = $this->misc->getDatabaseAccessor();
855
856
        $key = $this->_unserializeIfNotArray($_REQUEST, 'key');
857
858
        $this->coalesceArr($_POST, 'values', []);
859
860
        $this->coalesceArr($_POST, 'nulls', []);
861
862
        $status = $data->editRow(
863
            $_POST['table'],
864
            $_POST['values'],
865
            $_POST['nulls'],
866
            $_POST['format'],
867
            $_POST['types'],
868
            $key
869
        );
870
        if (0 == $status) {
871
            return $this->doBrowse($this->lang['strrowupdated']);
872
        }
873
        if ($status == -2) {
874
            return $this->formEditRow($this->lang['strrownotunique']);
875
        }
876
877
        return $this->formEditRow($this->lang['strrowupdatedbad']);
878
    }
879
880
    /**
881
     * Show confirmation of drop and perform actual drop.
882
     *
883
     * @param mixed $confirm
884
     */
885
    public function doDelRow($confirm)
886
    {
887
        $data = $this->misc->getDatabaseAccessor();
888
889
        if ($confirm) {
890
            $this->printTrail($_REQUEST['subject']);
891
            $this->printTitle($this->lang['strdeleterow']);
892
893
            $resultset = $data->browseRow($_REQUEST['table'], $_REQUEST['key']);
894
895
            echo '<form action="'.\SUBFOLDER.'/src/views/display" method="post">'."\n";
896
            echo $this->misc->form;
897
898
            if (1 == $resultset->recordCount()) {
899
                echo "<p>{$this->lang['strconfdeleterow']}</p>"."\n";
900
901
                $fkinfo = [];
902
                echo '<table><tr>';
903
                $this->printTableHeaderCells($resultset, false, true);
904
                echo '</tr>';
905
                echo '<tr class="data1">'."\n";
906
                $this->printTableRowCells($resultset, $fkinfo, true);
907
                echo '</tr>'."\n";
908
                echo '</table>'."\n";
909
                echo '<br />'."\n";
910
911
                echo '<input type="hidden" name="action" value="delrow" />'."\n";
912
                echo "<input type=\"submit\" name=\"yes\" value=\"{$this->lang['stryes']}\" />"."\n";
913
                echo "<input type=\"submit\" name=\"no\" value=\"{$this->lang['strno']}\" />"."\n";
914
            } elseif (1 != $resultset->recordCount()) {
915
                echo "<p>{$this->lang['strrownotunique']}</p>"."\n";
916
                echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />"."\n";
917
            } else {
918
                echo "<p>{$this->lang['strinvalidparam']}</p>"."\n";
919
                echo "<input type=\"submit\" name=\"cancel\" value=\"{$this->lang['strcancel']}\" />"."\n";
920
            }
921
            if (isset($_REQUEST['table'])) {
922
                echo '<input type="hidden" name="table" value="', htmlspecialchars($_REQUEST['table']), '" />'."\n";
923
            }
924
925
            if (isset($_REQUEST['subject'])) {
926
                echo '<input type="hidden" name="subject" value="', htmlspecialchars($_REQUEST['subject']), '" />'."\n";
927
            }
928
929
            if (isset($_REQUEST['query'])) {
930
                echo '<input type="hidden" name="query" value="', htmlspecialchars($_REQUEST['query']), '" />'."\n";
931
            }
932
933
            if (isset($_REQUEST['count'])) {
934
                echo '<input type="hidden" name="count" value="', htmlspecialchars($_REQUEST['count']), '" />'."\n";
935
            }
936
937
            if (isset($_REQUEST['return'])) {
938
                echo '<input type="hidden" name="return" value="', htmlspecialchars($_REQUEST['return']), '" />'."\n";
939
            }
940
941
            echo '<input type="hidden" name="page" value="', htmlspecialchars($_REQUEST['page']), '" />'."\n";
942
            echo '<input type="hidden" name="sortkey" value="', htmlspecialchars($_REQUEST['sortkey']), '" />'."\n";
943
            echo '<input type="hidden" name="sortdir" value="', htmlspecialchars($_REQUEST['sortdir']), '" />'."\n";
944
            echo '<input type="hidden" name="strings" value="', htmlspecialchars($_REQUEST['strings']), '" />'."\n";
945
            echo '<input type="hidden" name="key" value="', htmlspecialchars(urlencode(serialize($_REQUEST['key']))), '" />'."\n";
946
            echo '</form>'."\n";
947
        } else {
948
            $status = $data->deleteRow($_POST['table'], unserialize(urldecode($_POST['key'])));
949
            if (0 == $status) {
950
                $this->doBrowse($this->lang['strrowdeleted']);
951
            } elseif ($status == -2) {
952
                $this->doBrowse($this->lang['strrownotunique']);
953
            } else {
954
                $this->doBrowse($this->lang['strrowdeletedbad']);
955
            }
956
        }
957
    }
958
959
    /**
960
     * Build & return the FK information data structure
961
     * used when deciding if a field should have a FK link or not.
962
     *
963
     * @return array associative array describing the FK
964
     */
965
    public function &getFKInfo()
966
    {
967
        $data = $this->misc->getDatabaseAccessor();
968
969
        // Get the foreign key(s) information from the current table
970
        $fkey_information = ['byconstr' => [], 'byfield' => []];
971
972
        if (isset($_REQUEST['table'])) {
973
            $constraints = $data->getConstraintsWithFields($_REQUEST['table']);
974
            if ($constraints->recordCount() > 0) {
975
                $fkey_information['common_url'] = $this->misc->getHREF('schema').'&amp;subject=table';
976
977
                // build the FK constraints data structure
978
                while (!$constraints->EOF) {
979
                    $constr = &$constraints->fields;
980
                    if ('f' == $constr['contype']) {
981
                        if (!isset($fkey_information['byconstr'][$constr['conid']])) {
982
                            $fkey_information['byconstr'][$constr['conid']] = [
983
                                'url_data' => 'table='.urlencode($constr['f_table']).'&amp;schema='.urlencode($constr['f_schema']),
984
                                'fkeys'    => [],
985
                                'consrc'   => $constr['consrc'],
986
                            ];
987
                        }
988
989
                        $fkey_information['byconstr'][$constr['conid']]['fkeys'][$constr['p_field']] = $constr['f_field'];
990
991
                        if (!isset($fkey_information['byfield'][$constr['p_field']])) {
992
                            $fkey_information['byfield'][$constr['p_field']] = [];
993
                        }
994
995
                        $fkey_information['byfield'][$constr['p_field']][] = $constr['conid'];
996
                    }
997
                    $constraints->moveNext();
998
                }
999
            }
1000
        }
1001
1002
        return $fkey_information;
1003
    }
1004
1005
    // Print the FK row, used in ajax requests
1006
    public function doBrowseFK()
1007
    {
1008
        $data = $this->misc->getDatabaseAccessor();
1009
1010
        $ops = [];
1011
        foreach ($_REQUEST['fkey'] as $x => $y) {
1012
            $ops[$x] = '=';
1013
        }
1014
        $query             = $data->getSelectSQL($_REQUEST['table'], [], $_REQUEST['fkey'], $ops);
1015
        $_REQUEST['query'] = $query;
1016
1017
        $fkinfo = $this->getFKInfo();
1018
1019
        $max_pages = 1;
1020
        // Retrieve page from query.  $max_pages is returned by reference.
1021
        $resultset = $data->browseQuery(
1022
            'SELECT',
1023
            $_REQUEST['table'],
1024
            $_REQUEST['query'],
1025
            null,
1026
            null,
1027
            1,
1028
            1,
1029
            $max_pages
1030
        );
1031
1032
        echo '<a href="javascript:void(0);" style="display:table-cell;" class="fk_delete"><img alt="[delete]" src="'.$this->misc->icon('Delete').'" /></a>'."\n";
1033
        echo '<div style="display:table-cell;">';
1034
1035
        if (is_object($resultset) && $resultset->recordCount() > 0) {
1036
            /* we are browsing a referenced table here
1037
             * we should show OID if show_oids is true
1038
             * so we give true to withOid in functions bellow
1039
             */
1040
            echo '<table><tr>';
1041
            $this->printTableHeaderCells($resultset, false, true);
1042
            echo '</tr>';
1043
            echo '<tr class="data1">'."\n";
1044
            $this->printTableRowCells($resultset, $fkinfo, true);
1045
            echo '</tr>'."\n";
1046
            echo '</table>'."\n";
1047
        } else {
1048
            echo $this->lang['strnodata'];
1049
        }
1050
        echo '</div>';
1051
    }
1052
1053
    private function _getMinMaxPages($page, $pages)
1054
    {
1055
        $window = 10;
1056
        if ($page <= $window) {
1057
            $min_page = 1;
1058
            $max_page = min(2 * $window, $pages);
1059
        } elseif ($page > $window && $pages >= $page + $window) {
1060
            $min_page = ($page - $window) + 1;
1061
            $max_page = $page + $window;
1062
        } else {
1063
            $min_page = ($page - (2 * $window - ($pages - $page))) + 1;
1064
            $max_page = $pages;
1065
        }
1066
1067
        // Make sure min_page is always at least 1
1068
        // and max_page is never greater than $pages
1069
        $min_page = max($min_page, 1);
1070
        $max_page = min($max_page, $pages);
1071
1072
        return [$min_page, $max_page];
1073
    }
1074
1075
    /**
1076
     * Do multi-page navigation.  Displays the prev, next and page options.
1077
     *
1078
     * @param int   $page      - the page currently viewed
1079
     * @param int   $pages     - the maximum number of pages
1080
     * @param array $gets      -  the parameters to include in the link to the wanted page
1081
     * @param int   $max_width - the number of pages to make available at any one time (default = 20)
1082
     *
1083
     * @return string the pagination links
1084
     */
1085
    private function _printPages($page, $pages, $gets, $max_width = 20)
1086
    {
1087
        $lang = $this->lang;
1088
        $page = (int) $page;
1089
1090
        if ($page < 0 || $page > $pages || $pages <= 1 || $max_width <= 0) {
1091
            return;
1092
        }
1093
1094
        unset($gets['page']);
1095
        $url = http_build_query($gets);
1096
1097
        $result = '<p style="text-align: center">'."\n";
1098
        if ($page != 1) {
1099
            $result .= sprintf('<a class="pagenav" href="?%s&page=1">%s</a>%s&nbsp;', $url, $lang['strfirst'], "\n");
1100
            $result .= sprintf('<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $page - 1, $lang['strprev'], "\n");
1101
        }
1102
1103
        list($min_page, $max_page) = $this->_getMinMaxPages($page, $pages);
1104
1105
        for ($i = $min_page; $i <= $max_page; ++$i) {
1106
            $result .= (($i === $page) ? $i : sprintf('<a class="pagenav" href="display?%s&page=%s">%s</a>', $url, $i, $i))."\n";
1107
        }
1108
1109
        if ($page != $pages) {
1110
            $result .= sprintf('<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $page + 1, $lang['strnext'], "\n");
1111
            $result .= sprintf('&nbsp;<a class="pagenav" href="?%s&page=%s">%s</a>%s', $url, $pages, $lang['strlast'], "\n");
1112
        }
1113
        $result .= "</p>\n";
1114
1115
        return $result;
1116
    }
1117
}
1118