Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DataimportController.php « controllers « src - github.com/HuasoFoundries/phpPgAdmin6.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 29ea6a8f9b03753f12be416155b662e1d12f0744 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
<?php

/**
 * PHPPgAdmin 6.0.0
 */

namespace PHPPgAdmin\Controller;

/**
 * Base controller class.
 */
class DataimportController extends BaseController
{
    public $controller_title = 'strimport';

    /**
     * Default method to render the controller according to the action parameter.
     */
    public function render()
    {
        $data = $this->misc->getDatabaseAccessor();

        // Prevent timeouts on large exports
        \set_time_limit(0);

        $this->printHeader();
        $this->printTrail('table');
        $this->printTabs('table', 'import');

        // Default state for XML parser
        $state = 'XML';
        $curr_col_name = null;
        $curr_col_val = null;
        $curr_col_null = false;
        $curr_row = [];

        /**
         * Character data handler for XML import feature.
         *
         * @param $parser
         * @param $cdata
         */
        $_charHandler = static function ($parser, $cdata) use (&$state, &$curr_col_val): void {
            if ('COLUMN' === $state) {
                $curr_col_val .= $cdata;
            }
        };

        $lang = $this->lang;
        /**
         * Open tag handler for XML import feature.
         *
         * @param resource $parser
         * @param string   $name
         * @param array    $attrs
         */
        $_startElement = function ($parser, $name, $attrs) use ($curr_row, $data, &$state, &$curr_col_name, &$curr_col_null, $lang): void {
            switch ($name) {
                case 'DATA':
                    if ('XML' !== $state) {
                        $data->rollbackTransaction();
                        $this->halt($lang['strimporterror']);
                    }
                    $state = 'DATA';

                    break;
                case 'HEADER':
                    if ('DATA' !== $state) {
                        $data->rollbackTransaction();
                        $this->halt($lang['strimporterror']);
                    }
                    $state = 'HEADER';

                    break;
                case 'RECORDS':
                    if ('READ_HEADER' !== $state) {
                        $data->rollbackTransaction();
                        $this->halt($lang['strimporterror']);
                    }
                    $state = 'RECORDS';

                    break;
                case 'ROW':
                    if ('RECORDS' !== $state) {
                        $data->rollbackTransaction();
                        $this->halt($lang['strimporterror']);
                    }
                    $state = 'ROW';
                    $curr_row = [];

                    break;
                case 'COLUMN':
                    // We handle columns in rows
                    if ('ROW' === $state) {
                        $state = 'COLUMN';
                        $curr_col_name = $attrs['NAME'];
                        $curr_col_null = isset($attrs['NULL']);
                    } elseif ('HEADER' !== $state) {
                        // And we ignore columns in headers and fail in any other context
                        $data->rollbackTransaction();
                        $this->halt($lang['strimporterror']);
                    }

                    break;

                default:
                    // An unrecognised tag means failure
                    $data->rollbackTransaction();
                    $this->halt($lang['strimporterror']);
            }
        };

        /**
         * Close tag handler for XML import feature.
         *
         * @param resource $parser
         * @param string   $name
         */
        $_endElement = function ($parser, $name) use ($curr_row, $data, &$state, &$curr_col_name, &$curr_col_null, &$curr_col_val, $lang): void {
            switch ($name) {
                case 'DATA':
                    $state = 'READ_DATA';

                    break;
                case 'HEADER':
                    $state = 'READ_HEADER';

                    break;
                case 'RECORDS':
                    $state = 'READ_RECORDS';

                    break;
                case 'ROW':
                    // Build value map in order to insert row into table
                    $fields = [];
                    $vars = [];
                    $nulls = [];
                    $format = [];
                    $types = [];
                    $i = 0;

                    foreach ($curr_row as $k => $v) {
                        $fields[$i] = $k;
                        // Check for nulls
                        if (null === $v) {
                            $nulls[$i] = 'on';
                        }

                        // Add to value array
                        $vars[$i] = $v;
                        // Format is always VALUE
                        $format[$i] = 'VALUE';
                        // Type is always text
                        $types[$i] = 'text';
                        ++$i;
                    }
                    $status = $data->insertRow($_REQUEST['table'], $fields, $vars, $nulls, $format, $types);

                    if (0 !== $status) {
                        $data->rollbackTransaction();
                        $this->halt($lang['strimporterror']);
                    }
                    $curr_row = [];
                    $state = 'RECORDS';

                    break;
                case 'COLUMN':
                    $curr_row[$curr_col_name] = ($curr_col_null ? null : $curr_col_val);
                    $curr_col_name = null;
                    $curr_col_val = null;
                    $curr_col_null = false;
                    $state = 'ROW';

                    break;

                default:
                    // An unrecognised tag means failure
                    $data->rollbackTransaction();
                    $this->halt($lang['strimporterror']);
            }
        };

        // Check that file is specified and is an uploaded file
        if (!isset($_FILES['source']) || !\is_uploaded_file($_FILES['source']['tmp_name']) || !\is_readable($_FILES['source']['tmp_name'])) {
            // Upload went wrong
            $this->printMsg($this->lang['strimporterror-uploadedfile']);

            return $this->printFooter();
        }
        $fd = \fopen($_FILES['source']['tmp_name'], 'rb');
        // Check that file was opened successfully
        if (false === $fd) {
            // File could not be opened
            $this->printMsg($this->lang['strimporterror']);

            return $this->printFooter();
        }
        $null_array = self::loadNULLArray();
        $status = $data->beginTransaction();

        if (0 !== $status) {
            $this->halt($this->lang['strimporterror']);
        }

        // If format is set to 'auto', then determine format automatically from file name
        if ('auto' === $_REQUEST['format']) {
            $extension = \mb_substr(\mb_strrchr($_FILES['source']['name'], '.'), 1);

            switch ($extension) {
                case 'csv':
                    $_REQUEST['format'] = 'csv';

                    break;
                case 'txt':
                    $_REQUEST['format'] = 'tab';

                    break;
                case 'xml':
                    $_REQUEST['format'] = 'xml';

                    break;

                default:
                    $data->rollbackTransaction();
                    $this->halt($this->lang['strimporterror-fileformat']);
            }
        }

        // Do different import technique depending on file format
        switch ($_REQUEST['format']) {
            case 'csv':
            case 'tab':
                // XXX: Length of CSV lines limited to 100k
                $csv_max_line = 100000;
                // Set delimiter to tabs or commas
                if ('csv' === $_REQUEST['format']) {
                    $csv_delimiter = ',';
                } else {
                    $csv_delimiter = "\t";
                }

                // Get first line of field names
                $fields = \fgetcsv($fd, $csv_max_line, $csv_delimiter);
                $row = 2; //We start on the line AFTER the field names
                while ($line = \fgetcsv($fd, $csv_max_line, $csv_delimiter)) {
                    // Build value map
                    $t_fields = [];
                    $vars = [];
                    $nulls = [];
                    $format = [];
                    $types = [];
                    $i = 0;

                    foreach ($fields as $f) {
                        // Check that there is a column
                        if (!isset($line[$i])) {
                            $this->halt(\sprintf($this->lang['strimporterrorline-badcolumnnum'], $row));
                        }
                        $t_fields[$i] = $f;

                        // Check for nulls
                        if (self::determineNull($line[$i], $null_array)) {
                            $nulls[$i] = 'on';
                        }
                        // Add to value array
                        $vars[$i] = $line[$i];
                        // Format is always VALUE
                        $format[$i] = 'VALUE';
                        // Type is always text
                        $types[$i] = 'text';
                        ++$i;
                    }

                    $status = $data->insertRow($_REQUEST['table'], $t_fields, $vars, $nulls, $format, $types);

                    if (0 !== $status) {
                        $data->rollbackTransaction();
                        $this->halt(\sprintf($this->lang['strimporterrorline'], $row));
                    }
                    ++$row;
                }

                break;
            case 'xml':
                $parser = \xml_parser_create();
                \xml_set_element_handler($parser, $_startElement, $_endElement);
                \xml_set_character_data_handler($parser, $_charHandler);

                while (!\feof($fd)) {
                    $line = \fgets($fd, 4096);
                    \xml_parse($parser, $line);
                }

                \xml_parser_free($parser);

                break;

            default:
                // Unknown type
                $data->rollbackTransaction();
                $this->halt($this->lang['strinvalidparam']);
        }

        $status = $data->endTransaction();

        if (0 !== $status) {
            $this->printMsg($this->lang['strimporterror']);
        }
        \fclose($fd);

        $this->printMsg($this->lang['strfileimported']);

        return $this->printFooter();
    }

    public static function loadNULLArray()
    {
        $array = [];

        if (isset($_POST['allowednulls'])) {
            foreach ($_POST['allowednulls'] as $null_char) {
                $array[] = $null_char;
            }
        }

        return $array;
    }

    /**
     * @param null|string $field
     * @param mixed       $null_array
     */
    public static function determineNull(?string $field, $null_array)
    {
        return \in_array($field, $null_array, true);
    }
}