backpack::restore_data()   F
last analyzed

Complexity

Conditions 17
Paths 277

Size

Total Lines 78
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 17
eloc 44
c 3
b 0
f 0
nc 277
nop 5
dl 0
loc 78
rs 3.4208

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
***													***
5
*** backpack										***
6
*** Cedric MONTUY pour CHG-WEB                      ***
7
*** Original author : Yoshi Sakai					***
8
***													***
9
*******************************************************
10
*/
11
12
class backpack
13
{
14
    private $debug          = 0;        // Define this to enable debugging
15
    public  $backup_dir;
16
    public  $dump_size      = 0;
17
    public  $dump_line      = 0;
18
    public  $dump_buffer;
19
    public  $query_res      = [];
20
    public  $download_count = 0;
21
    public  $download_fname = [];
22
    public  $mime_type      = '';
23
    public  $time_start;
24
    public  $xoopsModuleConfig;
25
    public  $err_msg;
26
27
    public function __construct()
28
    {
29
        global $xoopsModuleConfig, $xoopsModule;
30
        if (defined('XOOPS_VAR_PATH')) {
31
            $backup_dir = XOOPS_VAR_PATH . '/caches/';
32
        } else {
33
            $backup_dir = XOOPS_ROOT_PATH . '/cache/';
34
        }
35
        $this->xoopsModuleConfig = $xoopsModuleConfig;
36
        $this->backup_dir        = $backup_dir;
37
    }
38
39
    public function backpack($dirname = '', $purgeBefore = '')
40
    {
41
        global $xoopsModuleConfig, $xoopsModule;
42
        if (empty($dirname)) {
43
            $this->xoopsModuleConfig = $xoopsModuleConfig;
44
            $dirname                 = $xoopsModule->dirname();
45
        } else {
46
            $this->xoopsModuleConfig($dirname);
47
        }
48
        $this->set_backup_dir($dirname);
49
        $this->time_start  = time();
50
        $this->dump_buffer = null;
51
        if (!empty($purgeBefore)) {
52
            $this->purge_allfiles($purgeBefore);
53
        }
54
    }
55
56
    public function set_backup_dir($dirname)
0 ignored issues
show
Unused Code introduced by
The parameter $dirname is not used and could be removed. ( Ignorable by Annotation )

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

56
    public function set_backup_dir(/** @scrutinizer ignore-unused */ $dirname)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
57
    {
58
        if (defined('XOOPS_VAR_PATH')) {
59
            $backup_dir = XOOPS_VAR_PATH . '/caches/';
60
        } else {
61
            $backup_dir = XOOPS_ROOT_PATH . '/cache/';
62
        }
63
        $this->backup_dir = $backup_dir;
64
    }
65
66
    public function xoopsModuleConfig($dirname)
67
    {
68
        $moduleHandler           = xoops_getHandler('module');
69
        $this_module             = $moduleHandler->getByDirname($dirname);
0 ignored issues
show
Bug introduced by
The method getByDirname() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsModuleHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

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

69
        /** @scrutinizer ignore-call */ 
70
        $this_module             = $moduleHandler->getByDirname($dirname);
Loading history...
70
        $mid                     = $this_module->getVar('mid');
71
        $configHandler           = xoops_getHandler('config');
72
        $this->xoopsModuleConfig = $configHandler->getConfigsByCat(0, $mid);
0 ignored issues
show
Bug introduced by
The method getConfigsByCat() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsPersistableObjectHandler. ( Ignorable by Annotation )

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

72
        /** @scrutinizer ignore-call */ 
73
        $this->xoopsModuleConfig = $configHandler->getConfigsByCat(0, $mid);
Loading history...
73
    }
74
75
    public function PMA_backquote($a_name, $do_it = true)
76
    {
77
        if ($do_it
78
            && PMA_MYSQL_INT_VERSION >= 32306
79
            && !empty($a_name)
80
            && '*' != $a_name) {
81
            return '`' . $a_name . '`';
82
        }
83
84
        return $a_name;
85
    } // end of the 'PMA_backquote()' function
86
87
    public function create_table_sql_string($tablename)
88
    {
89
        global $xoopsDB;
90
        $crlf = "\r\n";
91
92
        // Start the SQL string for this table
93
        $field_header = 'CREATE TABLE `' . $tablename . '` (';
94
        $field_string = '';
95
96
        // Get the field info and output to a string in the correct MySQL syntax
97
        $result = $xoopsDB->queryF('DESCRIBE ' . $tablename);
98
        if ($this->debug) {
99
            echo $tablename . " .field_info\n\n";
100
        }
101
        while (false !== ($field_info = $xoopsDB->fetchBoth($result))) {
102
            if ($this->debug) {
103
                $iMax = count($field_info);
104
                for ($i = 0;  $i < $iMax; ++$i) {
105
                    echo $i . ': ' . $field_info[$i] . "\n";
106
                }
107
            }
108
            $field_name     = $field_info[0];
109
            $field_type     = $field_info[1];
110
            $field_not_null = ('YES' == $field_info[2]) ? '' : ' NOT NULL';
111
            $field_default  = (null === $field_info[4]) ? '' : sprintf(' default \'%s\'', $field_info[4]);;
112
            $field_auto_increment = (null === $field_info[5]) ? '' : sprintf(' %s', $field_info[5]);
113
            $field_string         .= $field_string ? ',' : $field_header;
114
            $field_string         .= $crlf . sprintf('  `%s` %s%s%s%s', $field_name, $field_type, $field_not_null, $field_auto_increment, $field_default);
115
        }
116
        // Get the index info and output to a string in the correct MySQL syntax
117
        $result = $xoopsDB->queryF('SHOW KEYS FROM ' . $tablename);
118
        if ($this->debug) {
119
            echo "\nindex_info\n\n";
120
        }
121
        while (false !== ($row = $xoopsDB->fetchBoth($result))) {
122
            $kname = $row['Key_name'];
123
            $ktype = $row['Index_type'] ?? '';
124
            if (!$ktype && (isset($row['Comment']))) {
125
                $ktype = $row['Comment'];
126
            } // For Under MySQL v4.0.2
127
            $sub_part = $row['Sub_part'] ?? '';
128
            if ('PRIMARY' != $kname && 0 == $row['Non_unique']) {
129
                $kname = 'UNIQUE KEY `' . $kname . '`';
130
            }
131
            if ('FULLTEXT' == $ktype) {
132
                $kname = 'FULLTEXT KEY `' . $kname . '`';
133
            }
134
            if (!isset($index[$kname])) {
135
                $index[$kname] = [];
136
            }
137
            if ($sub_part > 1) {
138
                $index[$kname][] = $this->PMA_backquote($row['Column_name'], 0) . '(' . $sub_part . ')';
139
            } else {
140
                $index[$kname][] = $this->PMA_backquote($row['Column_name'], 0);
141
            }
142
        } // end while
143
        $xoopsDB->freeRecordSet($result);
144
        $index_string = '';
145
        foreach ($index as $x => $columns) {
146
            $index_string .= ',' . $crlf;
147
            if ('PRIMARY' == $x) {
148
                $index_string .= '   PRIMARY KEY (';
149
            } elseif (0 === strpos($x, 'UNIQUE')) {
150
                $index_string .= '   UNIQUE ' . substr($x, 7) . ' (';
151
            } elseif (0 === strpos($x, 'FULLTEXT')) {
152
                $index_string .= '   FULLTEXT ' . substr($x, 9) . ' (';
153
            } else {
154
                $index_string .= '   KEY `' . $x . '` (';
155
            }
156
            $index_string .= implode(', ', $columns) . ')';
157
        } // foreach
158
        $index_string .= $crlf;
159
160
        // Get the table type and output it to a string in the correct MySQL syntax
161
        //$result = mysqli_query("SHOW TABLE STATUS");
162
        $result = $xoopsDB->query('SHOW TABLE STATUS');
163
        if ($this->debug) {
164
            echo "\nstatus_info\n\n";
165
        }
166
        while (false !== ($status_info = $xoopsDB->fetchBoth($result))) {
167
            $iMax = count($status_info);
168
            for ($i = 0; $i < $iMax; ++$i) {
169
                if ($this->debug) {
170
                    echo "$i: $status_info[$i]\n";
171
                }
172
                if ($status_info[0] == $tablename) {
173
                    $table_type = sprintf('TYPE=%s', $status_info[1]);
174
                }
175
            }
176
        }
177
178
        // Append the index string to the field string
179
        $field_string = sprintf('%s%s', $field_string, $index_string);
180
181
        // Put the field string in parantheses
182
        $field_string = sprintf('%s)', $field_string);
183
184
        // Finalise the MySQL create table string
185
        $field_string      .= $table_type . ';';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $table_type does not seem to be defined for all execution paths leading up to this point.
Loading history...
186
        $field_string      = "-- \r\n-- " . $tablename . " structure.\r\n-- " . $crlf . $field_string . $crlf;
187
        $this->dump_buffer .= $field_string;
188
        preg_match_all("/\r\n/", $field_string, $c);
189
        $this->dump_line += count($c[0]);
190
        $this->dump_size += strlen(bin2hex($field_string)) / 2;
191
    }
192
193
    public function create_data_sql_string($tablename, $filename, $cfgZipType)
194
    {
195
        global $xoopsModuleConfig, $xoopsDB;
196
        // Get field names from MySQL and output to a string in the correct MySQL syntax
197
        $this->query_res = $xoopsDB->query("SELECT * FROM $tablename");
198
199
        // Get table data from MySQL and output to a string in the correct MySQL syntax
200
        $this->dump_buffer .= "-- \r\n-- " . $tablename . " dump.\r\n-- \r\n";
201
        $this->dump_line   += 3;
202
        while (false !== ($row = $xoopsDB->fetchRow($this->query_res))) {
203
            // Initialise the data string
204
            $data_string = '';
205
            // Loop through the records and append data to the string after escaping
206
            for ($i = 0; $i < $xoopsDB->getFieldsNum($this->query_res); ++$i) {
207
                if ('' != $data_string) {
208
                    $data_string .= ',';
209
                }
210
                if (!isset($row[$i]) || null === $row[$i]) {
211
                    $data_string .= 'NULL';
212
                } else {
213
                    //$data_string .= '"'.$GLOBALS['xoopsDB']->escape($row[$i]).'"';
214
                    $data_string .= '"' . $xoopsDB->escape($row[$i]) . '"';
215
                }
216
                //$data_string = str_replace("`","\'",$data_string);
217
            }
218
            //die($data_string);
219
            // URL change
220
            if (0 <> strcmp($xoopsModuleConfig['xoopsurlto'], XOOPS_URL)) {
221
                $data_string = preg_replace('/' . preg_quote(XOOPS_URL, '/') . '/', $xoopsModuleConfig['xoopsurlto'], $data_string);
222
            }
223
            // Encoding change
224
            /*
225
            if(extension_loaded("mbstring") && function_exists("mb_convert_encoding")){
226
                if ( strcmp( $xoopsModuleConfig['encodingto'], _CHARSET)<>0 )
227
                    $data_string = mb_convert_encoding($data_string, $xoopsModuleConfig['encodingto'],_CHARSET);
228
            }*/
229
            // Put the data string in parantheses and prepend "VALUES "
230
            $data_string = sprintf('VALUES (%s)', $data_string);
231
            // Finalise the MySQL insert into string for this record
232
            $field_string      = sprintf("INSERT INTO `%s` %s;\r\n", $tablename, $data_string);
233
            $this->dump_buffer .= $field_string;
234
            $this->dump_size   += strlen(bin2hex($field_string)) / 2;
235
            $this->dump_line++;
236
            $this->check_dump_buffer($filename, $cfgZipType);
237
        }
238
    }
239
240
    public function make_download($filename, $cfgZipType)
241
    {
242
        if (('bzip' == $cfgZipType) && function_exists('bzcompress')) {    // (PMA_PHP_INT_VERSION >= 40004 &&
243
            $filename        .= $this->download_count > 0 ? '-' . $this->download_count . '.sql' : '.sql';
244
            $ext             = 'bz2';
245
            $this->mime_type = 'application/x-bzip';
246
            $op_buffer       = bzcompress($this->dump_buffer);
247
        } elseif (('gzip' == $cfgZipType) && function_exists('gzencode')) {    // (PMA_PHP_INT_VERSION >= 40004 &&
248
            $filename         .= $this->download_count > 0 ? '-' . $this->download_count . '.sql' : '.sql';
249
            $ext              = 'gz';
250
            $content_encoding = 'x-gzip';
0 ignored issues
show
Unused Code introduced by
The assignment to $content_encoding is dead and can be removed.
Loading history...
251
            $this->mime_type  = 'application/x-gzip';
252
            // without the optional parameter level because it bug
253
            $op_buffer = gzencode($this->dump_buffer, 9);
254
        } elseif (('zip' == $cfgZipType) && function_exists('gzcompress')) {    // (PMA_PHP_INT_VERSION >= 40000 &&
255
            $filename        .= $this->download_count > 0 ? '-' . $this->download_count : '';
256
            $ext             = 'zip';
257
            $this->mime_type = 'application/x-zip';
258
            $extbis          = '.sql';
259
            $zipfile         = new zipfile();
260
            $zipfile->addFile($this->dump_buffer, $filename . $extbis);
261
            $op_buffer = $zipfile->file();
262
        } else {
263
            $filename        .= $this->download_count > 0 ? '-' . $this->download_count : '';
264
            $ext             = 'sql';
265
            $cfgZipType      = 'none';
0 ignored issues
show
Unused Code introduced by
The assignment to $cfgZipType is dead and can be removed.
Loading history...
266
            $this->mime_type = 'text/plain';
267
            $op_buffer       = $this->dump_buffer;
268
        }
269
        $fpathname = $this->backup_dir . $filename . '.' . $ext;
270
        if ($this->debug) {
271
            echo $fpathname . '<br>';
272
        }
273
        $fp = fopen($fpathname, 'w');
274
        fwrite($fp, $op_buffer);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

274
        fwrite(/** @scrutinizer ignore-type */ $fp, $op_buffer);
Loading history...
275
        fclose($fp);
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

275
        fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
276
        unset($op_buffer);
277
        if (!is_file($fpathname)) {
278
            print("Error - $filename does not exist.");
279
            return false;
280
        }
281
        $this->download_fname[$this->download_count]['filename'] = $filename . '.' . $ext;
282
        $this->download_fname[$this->download_count]['line']     = $this->dump_line;
283
        $this->download_fname[$this->download_count]['size']     = filesize($fpathname);
284
        $this->download_count++;
285
    }
286
287
    /*
288
    ** $beforeDays : You can purge before N days
289
    */
290
    public function purge_allfiles($beforeDays = null)
291
    {
292
        if ($handle = opendir($this->backup_dir)) {
293
            while (false !== ($file = readdir($handle))) {
294
                if (preg_match('/sql/', $file)) {
295
                    $fileDate = filemtime($this->backup_dir . $file);
296
                    if ($beforeDays) {
297
                        $beforeDate = time() - 86400 * (int)$beforeDays;
298
                        if ($fileDate < $beforeDate) {
299
                            if ($this->debug) {
300
                                echo "DELETE - $file $fileDate\n<BR>";
301
                            }
302
                            unlink($this->backup_dir . $file);
303
                        }
304
                    } else {
305
                        if ($this->debug) {
306
                            echo "DELETE - $file $fileDate\n<BR>";
307
                        }
308
                        unlink($this->backup_dir . $file);
309
                    }
310
                }
311
            }
312
            closedir($handle);
313
        }
314
    }
315
316
    public function check_dump_buffer($filename, $cfgZipType)
317
    {
318
        //var_dump($this->xoopsModuleConfig);
319
        $max_dumpsize = $this->xoopsModuleConfig['max_dumpsize'];//max_dumpsize
320
        if (!$max_dumpsize) {
321
            $max_dumpsize = MAX_DUMPSIZE;
322
        }
323
        //echo $this->dump_line . " - " .strlen( bin2hex( $this->dump_buffer)) / 2  . "byte<br>";
324
        if ($this->dump_line >= MAX_DUMPLINE || $this->dump_size >= $max_dumpsize) {
325
            $this->make_download($filename, $cfgZipType);
326
            //unset($GLOBALS['dump_buffer']);
327
            //unset($GLOBALS['$this->dump_line']);
328
            $this->dump_buffer = '';
329
            $this->dump_line   = 0;
330
            $this->dump_size   = 0;
331
        }
332
    }
333
334
    public function Lock_Tables($tablename_array)
335
    {
336
        global $xoopsDB;
337
        if (!is_array($tablename_array) || empty($tablename_array)) {
338
            return false;
339
        }
340
        $q = 'LOCK TABLES';
341
        foreach ($tablename_array as $iValue) {
342
            $q .= ' ' . $iValue . ' read,';
343
        }
344
        $q = substr($q, 0, strlen($q) - 1);
345
        $xoopsDB->queryF($q);
346
    }
347
348
    public function backup_data($tablename_array, $backup_structure, $backup_data, $filename, $cfgZipType)
349
    {
350
        global $xoopsDB;
351
        $field_string      = "-- CHG-WEB.Xoops Backup/Restore Module\r\n-- BackPack\r\n-- https://store.chg-web.com/\r\n" . "-- --------------------------------------------\r\n";
352
        $this->dump_buffer = $field_string;
353
        $this->dump_size   += strlen(bin2hex($field_string)) / 2;
354
        preg_match_all("/\r\n/", $this->dump_buffer, $c);
355
        $this->dump_line += count($c[0]);
356
        //mysqli_query($xoopsDB->conn,'FLUSH TABLES');
357
        $xoopsDB->queryF('FLUSH TABLES');
358
        $this->Lock_Tables($tablename_array);
359
        foreach ($tablename_array as $iValue) {
360
            if ($backup_structure) {
361
                $this->create_table_sql_string($iValue);
362
            }
363
            if ($backup_data) {
364
                $this->create_data_sql_string($iValue, $filename, $cfgZipType);
365
            }
366
            $this->check_dump_buffer($filename, $cfgZipType);
367
            $time_now = time();
368
            if ($this->time_start >= $time_now + 30) {
369
                $this->time_start = $time_now;
370
                header('X-pmaPing: Pong');
371
            }
372
        }
373
        $xoopsDB->queryF('UNLOCK TABLES');
374
        if ($this->dump_buffer) {
375
            $this->make_download($filename, $cfgZipType);
376
        }
377
    }
378
379
    public function restore_data($filename, $restore_structure, $restore_data, $db_selected, $replace_url = '')
380
    {
381
        global $xoopsDB;
382
        if (!is_file($filename)) {
383
            exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
384
        }
385
        $handle = fopen($filename, 'r');
386
387
        $prefix = '';
388
        mysqli_set_charset('utf8');
0 ignored issues
show
Bug introduced by
'utf8' of type string is incompatible with the type mysqli expected by parameter $link of mysqli_set_charset(). ( Ignorable by Annotation )

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

388
        mysqli_set_charset(/** @scrutinizer ignore-type */ 'utf8');
Loading history...
Bug introduced by
The call to mysqli_set_charset() has too few arguments starting with charset. ( Ignorable by Annotation )

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

388
        /** @scrutinizer ignore-call */ 
389
        mysqli_set_charset('utf8');

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
389
        while (!feof($handle)) {
0 ignored issues
show
Bug introduced by
It seems like $handle can also be of type false; however, parameter $handle of feof() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

389
        while (!feof(/** @scrutinizer ignore-type */ $handle)) {
Loading history...
390
            $buffer = '';
391
            while (!feof($handle)) {
392
                //$cbuff = ereg_replace("\n|\r|\t","",fgets($handle));
393
                $cbuff = preg_replace('/\n|\r|\t/', '', fgets($handle));
0 ignored issues
show
Bug introduced by
It seems like $handle can also be of type false; however, parameter $handle of fgets() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

393
                $cbuff = preg_replace('/\n|\r|\t/', '', fgets(/** @scrutinizer ignore-type */ $handle));
Loading history...
394
                // print (ereg('--',$cbuff)?"true<br>":"false<br>");
395
                //if (!ereg('^--',$cbuff)) $buffer .= $cbuff;
396
                if (!preg_match('/^--/', $cbuff)) {
397
                    $buffer .= $cbuff;
398
                }
399
                if (false !== preg_match('/;/', $cbuff)) {
400
                    break;
401
                }
402
            }
403
            if (preg_match('/^CREATE TABLE|^INSERT INTO|^DELETE/i', $buffer)) {
404
                if (!$prefix) {
405
                    $match  = explode(' ', $buffer);
406
                    $prefix = explode('_', $match[2]);
407
                    $prefix = preg_replace('/^`/', '', $prefix[0]);
408
                }
409
                $buffer = preg_replace('/' . $prefix . '_/', XOOPS_DB_PREFIX . '_', $buffer);
410
                if ($replace_url) {
411
                    $pattern = 'http://' . $replace_url;
412
                    $buffer  = preg_replace('/' . preg_quote($pattern, '/') . '/', XOOPS_URL, $buffer);
413
                }
414
            }
415
            // 20100218
416
            $buffer = preg_replace("/on update CURRENT_TIMESTAMP default \'CURRENT_TIMESTAMP\'/i", '', $buffer);
417
            if ($buffer) {
418
                // if this line is a create table query then check if the table already exists
419
420
                //if (eregi("^CREATE TABLE",$buffer) ) {
421
                if (preg_match('/^CREATE TABLE/i', $buffer)) {
422
                    if ($restore_structure) {
423
                        $tablename = explode(' ', $buffer);
424
                        $tablename = preg_replace('/`/', '', $tablename[2]);
425
//                        $result    = mysqli_list_tables($db_selected);
426
                        $sql = "SHOW TABLES FROM $db_selected";
427
                        $result = $xoopsDB->query($sql);
428
                        for ($i = 0; $i < $GLOBALS['xoopsDB']->getRowsNum($result); ++$i) {
429
                            if (mysqli_tablename($result, $i) == $tablename) {
430
                                //$rand = substr(md5(time()), 0, 8);
431
                                //$random_tablename = sprintf("%s_bak_%s", $tablename, $rand);
432
                                //mysqli_query("DROP TABLE IF EXISTS $tablename");
433
                                $xoopsDB->queryF('DROP TABLE IF EXISTS ' . $tablename);
434
                                //mysqli_query("RENAME TABLE $tablename TO $random_tablename");
435
                                //echo "Backed up $tablename to $random_tablename.<br>\n";
436
                            }
437
                        }
438
                        //$result = mysqli_query($buffer);
439
                        $xoopsDB->queryF($buffer);
440
                        if (!$result) {
441
                            echo $GLOBALS['xoopsDB']->error() . "<br>\n";
442
                        } else {
443
                            echo "Table '$tablename' successfully recreated.<br>\n";
444
                        }
445
                    }
446
                    //echo "[".$buffer."]";die;
447
                } elseif ($restore_data) {
448
                    //$result = mysqli_query($buffer);
449
                    $xoopsDB->queryF($buffer);
450
                    if (!$result) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.
Loading history...
451
                        echo $GLOBALS['xoopsDB']->error() . "<br>\n";
452
                    }
453
                }
454
            }
455
        }
456
        fclose($handle);
0 ignored issues
show
Bug introduced by
It seems like $handle can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

456
        fclose(/** @scrutinizer ignore-type */ $handle);
Loading history...
457
    }
458
459
    public function get_module_tables($dirname)
460
    {
461
        global $xoopsConfig, $xoopsDB;
462
        if (!$dirname) {
463
            return;
464
        }
465
        $moduleHandler = xoops_getHandler('module');
466
        $module        = $moduleHandler->getByDirname($dirname);
467
        // Get tables used by this module
468
        $modtables = $module->getInfo('tables');
469
        if (false !== $modtables && is_array($modtables)) {
470
            return $modtables;
471
        }
472
473
        // TABLES (loading mysql.sql)
474
        $sql_file_path = XOOPS_TRUST_PATH . '/modules/' . $dirname . '/sql/mysql.sql';
475
        $prefix_mod    = $dirname;
476
        if (is_file($sql_file_path)) {
477
            $sql_lines = file($sql_file_path);
478
            foreach ($sql_lines as $sql_line) {
479
                if (preg_match('/^CREATE TABLE \`?([a-zA-Z0-9_-]+)\`? /i', $sql_line, $regs)) {
480
                    $modtables[] = $prefix_mod . '_' . $regs[1];
481
                }
482
            }
483
            return $modtables;
484
        }
485
486
        //die( "No Table" );
487
        redirect_header('./index.php', 1, _AM_NO_TABLE);
488
    }
489
490
    public function make_module_selection($select_dirname = '', $addblank = 0)
491
    {
492
        global $xoopsDB;
493
        $sql = 'SELECT name,dirname FROM ' . $xoopsDB->prefix('modules');
494
        if (!$result = $xoopsDB->queryF($sql)) {
495
            return false;
496
        }
497
        $mod_selections = '<select name="dirname">';
498
        $mod_selections .= $addblank ? '<option value=""></option>' : '';
499
        while (list($name, $dirname) = $xoopsDB->fetchRow($result)) {
500
            if (0 == strcmp($dirname, $select_dirname)) {
501
                $opt = 'selected';
502
            } else {
503
                $opt = '';
504
            }
505
            $mod_selections .= '<option value="' . $dirname . '" ' . $opt . '>' . $name . '</option>';
506
        }
507
        $mod_selections .= '</select>';
508
        return $mod_selections;
509
    }
510
511
    /**
512
     * Maximum upload size as limited by PHP
513
     * Used with permission from Moodle (http://moodle.org) by Martin Dougiamas
514
     *
515
     * this section generates $max_upload_size in bytes
516
     * @param int $size
517
     * @return float|int|mixed
518
     */
519
520
    public function get_real_size($size = 0)
521
    {
522
        /// Converts numbers like 10M into bytes
523
        if (!$size) {
524
            return 0;
525
        }
526
        $scan['MB'] = 1048576;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$scan was never initialized. Although not strictly required by PHP, it is generally a good practice to add $scan = array(); before regardless.
Loading history...
527
        $scan['Mb'] = 1048576;
528
        $scan['M']  = 1048576;
529
        $scan['m']  = 1048576;
530
        $scan['KB'] = 1024;
531
        $scan['Kb'] = 1024;
532
        $scan['K']  = 1024;
533
        $scan['k']  = 1024;
534
535
//        while (list($key) = each($scan)) {
536
        foreach (array_keys($scan) as $key) {
537
            if ((strlen($size) > strlen($key)) && (substr($size, strlen($size) - strlen($key)) == $key)) {
538
                $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
539
                break;
540
            }
541
        }
542
        /*foreach($scan as $key=>$value){
543
            if ((strlen($size)>strlen($value))&&(substr($size, strlen($size) - strlen($key))==$key)) {
544
                $size = substr($size, 0, strlen($size) - strlen($key)) * $value;
545
                break;
546
            }
547
        }*/
548
        return $size;
549
    }
550
551
    /**
552
     * Displays the maximum size for an upload
553
     *
554
     * @param int  the size
555
     *
556
     * @return  string   the message
557
     *
558
     * @access  public
559
     */
560
    public function PMA_displayMaximumUploadSize($max_upload_size)
561
    {
562
        [$max_size, $max_unit] = $this->PMA_formatByteDown($max_upload_size);
563
        return '(' . sprintf(_AM_SELECTAFILE_DESC, $max_size, $max_unit) . ')';
564
    }
565
566
    /**
567
     * Formats $value to byte view
568
     *
569
     * @param double   the value to format
570
     * @param int  the sensitiveness
571
     * @param int  the number of decimals to retain
572
     *
573
     * @return   array    the formatted value and its unit
574
     *
575
     * @access   public
576
     *
577
     * @author   staybyte
578
     * @version  1.2 - 18 July 2002
579
     */
580
    public function PMA_formatByteDown($value, $limes = 6, $comma = 0)
581
    {
582
        $dh                         = pow(10, $comma);
583
        $li                         = pow(10, $limes);
584
        $return_value               = $value;
0 ignored issues
show
Unused Code introduced by
The assignment to $return_value is dead and can be removed.
Loading history...
585
        $byteunits                  = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
586
        $unit                       = $byteunits[0];
587
        $number_thousands_separator = ',';
588
        $number_decimal_separator   = '.';
589
590
        for ($d = 6, $ex = 15; $d >= 1; $d--, $ex -= 3) {
591
            if (isset($byteunits[$d]) && $value >= $li * pow(10, $ex)) {
592
                $value = round($value / (pow(1024, $d) / $dh)) / $dh;
593
                $unit  = $byteunits[$d];
594
                break 1;
595
            } // end if
596
        } // end for
597
598
        if ($unit != $byteunits[0]) {
599
            $return_value = number_format($value, $comma, $number_decimal_separator, $number_thousands_separator);
600
        } else {
601
            $return_value = number_format($value, 0, $number_decimal_separator, $number_thousands_separator);
602
        }
603
604
        return [$return_value, $unit];
605
    } // end of the 'PMA_formatByteDown' function
606
607
    public function download_fname()
608
    {
609
        return $this->download_fname;
610
    }
611
    // end function
612
}
613