OSDN Git Service

Merge branch 'skinnable-master'
[nucleus-jp/nucleus-next.git] / nucleus / libs / backup.php
1 <<<<<<< HEAD
2 <?php\r
3 /*\r
4  * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)\r
5  * Copyright (C) 2002-2012 The Nucleus Group\r
6  *\r
7  * This program is free software; you can redistribute it and/or\r
8  * modify it under the terms of the GNU General Public License\r
9  * as published by the Free Software Foundation; either version 2\r
10  * of the License, or (at your option) any later version.\r
11  * (see nucleus/documentation/index.html#license for more info)\r
12  */\r
13 /**\r
14  * Scripts to create/restore a backup of the Nucleus database\r
15  *\r
16  * @license http://nucleuscms.org/license.txt GNU General Public License\r
17  * @copyright Copyright (C) 2002-2012 The Nucleus Group\r
18  * @version $Id: backup.php 1624 2012-01-09 11:36:20Z sakamocchi $\r
19  */\r
20 \r
21 class Backup\r
22 {\r
23         /**\r
24          * Backup::Backup()\r
25          * Constructor, just for compatibility\r
26          *\r
27          * @deprecated\r
28          * @param       void\r
29          * @return      void\r
30          *\r
31          */\r
32         public function Backup()\r
33         {\r
34                 return;\r
35         }\r
36 \r
37         /**\r
38          * Backup::do_backup()\r
39          * This function creates an sql dump of the database and sends it to\r
40          * the user as a file (can be gzipped if they want)\r
41          *\r
42          * NOTE: this remains not-static for compatibility\r
43          *\r
44          * @param boolean       $gzip   1 = compress backup file, 0 = no compression (default)\r
45          * @return      void\r
46          *\r
47          */\r
48         public function do_backup($gzip = 0)\r
49         {\r
50                 global $manager, $nucleus;\r
51 \r
52                 // tables of which backup is needed\r
53                 $tables = array(\r
54                                 sql_table('actionlog'),\r
55                                 sql_table('ban'),\r
56                                 sql_table('blog'),\r
57                                 sql_table('comment'),\r
58                                 sql_table('config'),\r
59                                 sql_table('item'),\r
60                                 sql_table('karma'),\r
61                                 sql_table('member'),\r
62                                 sql_table('skin'),\r
63                                 sql_table('skin_desc'),\r
64                                 sql_table('team'),\r
65                                 sql_table('template'),\r
66                                 sql_table('template_desc'),\r
67                                 sql_table('plugin'),\r
68                                 sql_table('plugin_event'),\r
69                                 sql_table('plugin_option'),\r
70                                 sql_table('plugin_option_desc'),\r
71                                 sql_table('category'),\r
72                                 sql_table('activation'),\r
73                                 sql_table('tickets'),\r
74                 );\r
75 \r
76                 // add tables that plugins want to backup to the list\r
77                 // catch all output generated by plugins\r
78                 ob_start();\r
79                 $query = sprintf('SELECT pfile FROM %s', sql_table('plugin'));\r
80                 $res = DB::getResult($query);\r
81                 foreach ( $res as $row )\r
82                 {\r
83                         $plug =& $manager->getPlugin($row['pfile']);\r
84                         if ( $plug )\r
85                         {\r
86                                 $tables = array_merge($tables, (array) $plug->getTableList());\r
87                         }\r
88                 }\r
89                 ob_end_clean();\r
90 \r
91                 // remove duplicates\r
92                 $tables = array_unique($tables);\r
93 \r
94                 // make sure browsers don't cache the backup\r
95                 header("Pragma: no-cache");\r
96 \r
97                 // don't allow gzip compression when extension is not loaded\r
98                 if ( ($gzip != 0) && !extension_loaded("zlib") )\r
99                 {\r
100                         $gzip = 0;\r
101                 }\r
102 \r
103                 if ( !$gzip )\r
104                 {\r
105                         $filename = 'nucleus_db_backup_' . i18n::formatted_datetime('%Y-%m-%d-%H-%M-%S', time()) . ".sql";\r
106                 }\r
107                 else\r
108                 {\r
109                         // use an output buffer\r
110                         @ob_start();\r
111                         @ob_implicit_flush(0);\r
112 \r
113                         // set filename\r
114                         $filename = 'nucleus_db_backup_' . i18n::formatted_datetime('%Y-%m-%d-%H-%M-%S', time()) . ".sql.gz";\r
115                 }\r
116 \r
117                 // send headers that tell the browser a file is coming\r
118                 header("Content-Type: text/x-delimtext; name=\"$filename\"");\r
119                 header("Content-disposition: attachment; filename=$filename");\r
120 \r
121                 // dump header\r
122                 echo "/*\n";\r
123                 echo " * This is a backup file generated by Nucleus \n";\r
124                 echo " * http://www.nucleuscms.org/\n";\r
125                 echo " * \n";\r
126                 echo " * backup-date: " . i18n::formatted_datetime('rfc822GMT', time()) . "\n";\r
127                 echo " * Nucleus CMS version: " . $nucleus['version'] . "\n";\r
128                 echo " * \n";\r
129                 echo " * WARNING: Only try to restore on servers running the exact same version of Nucleus\n";\r
130                 echo " */\n";\r
131 \r
132                 // dump all tables\r
133                 reset($tables);\r
134                 array_walk($tables, array(__CLASS__, 'dump_table'));\r
135 \r
136                 if ( $gzip )\r
137                 {\r
138                         $Size = ob_get_length();\r
139                         $Crc = crc32(ob_get_contents());\r
140                         $contents = gzcompress(ob_get_contents());\r
141                         ob_end_clean();\r
142                         echo "\x1f\x8b\x08\x00\x00\x00\x00\x00" . substr($contents, 0, strlen($contents) - 4)\r
143                         . self::gzip_print_four_characters($Crc) . self::gzip_print_four_characters($Size);\r
144                 }\r
145                 exit;\r
146         }\r
147 \r
148         /**\r
149          * Backup::dump_table()\r
150          * Creates a dump for a single table\r
151          * ($tablename and $key are filled in by array_walk)\r
152          *\r
153          * @static\r
154          * @param       string  $tablename\r
155          * @param       string  $key\r
156          */\r
157         static private function dump_table($tablename, $key)\r
158         {\r
159                 echo "/*\n";\r
160                 echo " * TABLE: " . $tablename . "\n";\r
161                 echo " */\n";\r
162 \r
163                 // dump table structure\r
164                 self::dump_structure($tablename);\r
165 \r
166                 // dump table contents\r
167                 self::dump_contents($tablename);\r
168                 return;\r
169         }\r
170 \r
171         /**\r
172          * Backup::dump_structure()\r
173          * Creates a dump of the table structure for one table\r
174          *\r
175          * @static\r
176          * @param       string  $tablename\r
177          * @return      void\r
178          *\r
179          */\r
180         static private function dump_structure($tablename)\r
181         {\r
182                 // add command to drop table on restore\r
183                 echo "DROP TABLE IF EXISTS {$tablename};\n\n";\r
184                 $result = DB::getRow("SHOW CREATE TABLE {$tablename}");\r
185                 echo $result['Create Table'];\r
186                 echo ";\n\n";\r
187                 return;\r
188         }\r
189 \r
190         /**\r
191          * Backup::get_field_names()\r
192          * Returns the field named for the given table in the\r
193          * following format:\r
194          * (column1, column2, ..., columnn)\r
195          *\r
196          * @static\r
197          * @param       resource        $result\r
198          * @param       integer $num_fields\r
199          * @return      string\r
200          */\r
201         static private function get_field_names($result, $num_fields)\r
202         {\r
203                 $fields = array();\r
204                 for ( $j = 0; $j < $num_fields; $j++ )\r
205                 {\r
206                         $col = $result->getColumnMeta($j);\r
207                         $fields[] = $col['name'];\r
208                 }\r
209 \r
210                 return '(' . implode(', ', $fields) . ')';\r
211         }\r
212 \r
213         /**\r
214          * Backup::dump_contents()\r
215          * Creates a dump of the table content for one table\r
216          *\r
217          * @static\r
218          * @param       string  $tablename\r
219          * @return      void\r
220          *\r
221          */\r
222         static private function dump_contents($tablename)\r
223         {\r
224                 /*\r
225                  * Grab the data from the table.\r
226                 */\r
227                 $result = DB::getResult("SELECT * FROM $tablename");\r
228 \r
229                 if ( $result->rowCount() > 0 )\r
230                 {\r
231                         echo "\n";\r
232                         echo "/*\n";\r
233                         echo " * Table Data for {$tablename}\n";\r
234                         echo " */\n";\r
235                 }\r
236 \r
237                 $num_fields = $result->columnCount();\r
238 \r
239                 /*\r
240                  * Compose fieldname list\r
241                 */\r
242                 $tablename_list = self::get_field_names($result, $num_fields);\r
243 \r
244                 /*\r
245                  * Loop through the resulting rows and build the sql statement.\r
246                 */\r
247                 foreach ( $result as $row )\r
248                 {\r
249                         // Start building the SQL statement.\r
250                         echo 'INSERT INTO ' . $tablename . ' ' . $tablename_list . ' VALUES(';\r
251 \r
252                         // Loop through the rows and fill in data for each column\r
253                         for ( $j = 0; $j < $num_fields; $j++ )\r
254                         {\r
255                                 if ( !isset($row[$j]) )\r
256                                 {\r
257                                         // no data for column\r
258                                         echo ' NULL';\r
259                                 }\r
260                                 elseif ( $row[$j] != '' )\r
261                                 {\r
262                                         // data\r
263                                         echo ' ' . DB::quoteValue($row[$j]);\r
264                                 }\r
265                                 else\r
266                                 {\r
267                                         // empty column (!= no data!)\r
268                                         echo "''";\r
269                                 }\r
270 \r
271                                 // only add comma when not last column\r
272                                 if ( $j != ($num_fields - 1) )\r
273                                 {\r
274                                         echo ',';\r
275                                 }\r
276                         }\r
277                         echo ");\n";\r
278                 }\r
279                 echo "\n";\r
280                 return;\r
281         }\r
282 \r
283         /**\r
284          * Backup::gzip_print_four_characters()\r
285          *\r
286          * @static\r
287          * @param       integer $val\r
288          * @return      integer\r
289          */\r
290         static private function gzip_print_four_characters($Val)\r
291         {\r
292                 for ( $i = 0; $i < 4; $i ++ )\r
293                 {\r
294                         $return .= chr($Val % 256);\r
295                         $Val = floor($Val / 256);\r
296                 }\r
297                 return $return;\r
298         }\r
299 \r
300         /**\r
301          * Backup::do_restore()\r
302          * Restores a database backup\r
303          *\r
304          * NOTE: this remains not-static for compatibility\r
305          *\r
306          * @param       void\r
307          * @return      void\r
308          */\r
309         public function do_restore()\r
310         {\r
311                 $uploadInfo = postFileInfo('backup_file');\r
312 \r
313                 // first of all: get uploaded file:\r
314                 if ( array_key_exists('name', $uploadInfo) && empty($uploadInfo['name']) )\r
315                 {\r
316                         return 'No file uploaded';\r
317                 }\r
318                 if ( !is_uploaded_file($uploadInfo['tmp_name']) )\r
319                 {\r
320                         return 'No file uploaded';\r
321                 }\r
322 \r
323                 $backup_file_name = $uploadInfo['name'];\r
324                 $backup_file_tmpname = $uploadInfo['tmp_name'];\r
325                 $backup_file_type = $uploadInfo['type'];\r
326 \r
327                 if ( !file_exists($backup_file_tmpname) )\r
328                 {\r
329                         return 'File Upload Error';\r
330                 }\r
331 \r
332                 if ( !preg_match("#^(text/[a-zA-Z]+)|(application/(x\-)?gzip(\-compressed)?)|(application/octet-stream)$#i", $backup_file_type) )\r
333                 {\r
334                         return 'The uploaded file is not of the correct type';\r
335                 }\r
336 \r
337                 $gzip = 0;\r
338                 if ( preg_match("#\.gz#i", $backup_file_name) )\r
339                 {\r
340                         $gzip = 1;\r
341                 }\r
342 \r
343                 if ( !extension_loaded("zlib") && $gzip )\r
344                 {\r
345                         return 'Cannot decompress gzipped backup (zlib package not installed)';\r
346                 }\r
347 \r
348                 // get sql query according to gzip setting (either decompress, or not)\r
349                 $contents = self::get_contents($backup_file_tmpname, $gzip);\r
350                 if ( $contents == '' )\r
351                 {\r
352                         return 'Cannot get contents from this file.';\r
353                 }\r
354 \r
355                 /* detect lines */\r
356                 $lines = preg_split('/[\r\n]/', $contents);\r
357                 if( $lines === $contents )\r
358                 {\r
359                         return 'Cannot parse contents from this file';\r
360                 }\r
361 \r
362                 /* get sql statements from each lines */\r
363                 $queries = self::get_queries($lines);\r
364                 if ( $queries === array() )\r
365                 {\r
366                         return "Cannot get SQL queries from this file.";\r
367                 }\r
368 \r
369                 /* execute sql statements */\r
370                 foreach ( $queries as $query )\r
371                 {\r
372                         if ( DB::execute($query) === FALSE )\r
373                         {\r
374                                 $error = DB::getError();\r
375                                 debug('SQL Error: ' . $error[2]);\r
376                                 break;\r
377                         }\r
378                         continue;\r
379                 }\r
380                 return;\r
381         }\r
382 \r
383         static private function get_contents($temporary_name, $gzip = 0)\r
384         {\r
385                 $contents = '';\r
386                 if ( $gzip )\r
387                 {\r
388                         // decompress and read\r
389                         $gz_ptr = gzopen($temporary_name, 'rb');\r
390                         while ( !gzeof($gz_ptr) )\r
391                         {\r
392                                 $contents .= gzgets($gz_ptr, 100000);\r
393                         }\r
394                 }\r
395                 else\r
396                 {\r
397                         // just read\r
398                         $fsize = filesize($temporary_name);\r
399                         if ( $fsize > 0 )\r
400                         {\r
401                                 $contents = fread(fopen($temporary_name, 'r'), $fsize);\r
402                         }\r
403                 }\r
404                 return $contents;\r
405         }\r
406 \r
407         static private function get_queries($lines)\r
408         {\r
409                 $query = '';\r
410                 $queries = array();\r
411                 foreach ( $lines as $line )\r
412                 {\r
413                         $line = trim($line);\r
414                         if ( !$line || $line[0] == '#' || preg_match('#^[\s|/]?\*#', $line) )\r
415                         {\r
416                                 continue;\r
417                         }\r
418 \r
419                         if ( preg_match('/^(.*);$/', $line, $matches) === 0 )\r
420                         {\r
421                                 $query .= $line;\r
422                         }\r
423                         else\r
424                         {\r
425                                 $query .= $matches[1];\r
426                                 $queries[] = $query;\r
427                                 $query = '';\r
428                         }\r
429                         continue;\r
430                 }\r
431                 return $queries;\r
432         }\r
433 =======
434 <?php
435 /*
436  * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
437  * Copyright (C) 2002-2009 The Nucleus Group
438  *
439  * This program is free software; you can redistribute it and/or
440  * modify it under the terms of the GNU General Public License
441  * as published by the Free Software Foundation; either version 2
442  * of the License, or (at your option) any later version.
443  * (see nucleus/documentation/index.html#license for more info)
444  */
445 /**
446  * Scripts to create/restore a backup of the Nucleus database
447  *
448  * @license http://nucleuscms.org/license.txt GNU General Public License
449  * @copyright Copyright (C) 2002-2009 The Nucleus Group
450  * @version $Id: backup.php 1812 2012-05-01 14:59:07Z sakamocchi $
451  */
452
453 class Backup
454 {
455         /**
456          * Backup::Backup()
457          * Constructor, just for compatibility
458          *
459          * @deprecated
460          * @param       void
461          * @return      void
462          *
463          */
464         public function Backup()
465         {
466                 return;
467         }
468
469         /**
470          * Backup::do_backup()
471          * This function creates an sql dump of the database and sends it to
472          * the user as a file (can be gzipped if they want)
473          *
474          * NOTE: this remains not-static for compatibility
475          *
476          * @param boolean       $gzip   1 = compress backup file, 0 = no compression (default)
477          * @return      void
478          *
479          */
480         public function do_backup($gzip = 0)
481         {
482                 global $manager, $nucleus;
483
484                 // tables of which backup is needed
485                 $tables = array(
486                                 sql_table('actionlog'),
487                                 sql_table('ban'),
488                                 sql_table('blog'),
489                                 sql_table('comment'),
490                                 sql_table('config'),
491                                 sql_table('item'),
492                                 sql_table('karma'),
493                                 sql_table('member'),
494                                 sql_table('skin'),
495                                 sql_table('skin_desc'),
496                                 sql_table('team'),
497                                 sql_table('template'),
498                                 sql_table('template_desc'),
499                                 sql_table('plugin'),
500                                 sql_table('plugin_event'),
501                                 sql_table('plugin_option'),
502                                 sql_table('plugin_option_desc'),
503                                 sql_table('category'),
504                                 sql_table('activation'),
505                                 sql_table('tickets'),
506                 );
507
508                 // add tables that plugins want to backup to the list
509                 // catch all output generated by plugins
510                 ob_start();
511                 $query = sprintf('SELECT pfile FROM %s', sql_table('plugin'));
512                 $res = DB::getResult($query);
513                 foreach ( $res as $row )
514                 {
515                         $plug =& $manager->getPlugin($row['pfile']);
516                         if ( $plug )
517                         {
518                                 $tables = array_merge($tables, (array) $plug->getTableList());
519                         }
520                 }
521                 ob_end_clean();
522
523                 // remove duplicates
524                 $tables = array_unique($tables);
525
526                 // make sure browsers don't cache the backup
527                 header("Pragma: no-cache");
528
529                 // don't allow gzip compression when extension is not loaded
530                 if ( ($gzip != 0) && !extension_loaded("zlib") )
531                 {
532                         $gzip = 0;
533                 }
534
535                 if ( !$gzip )
536                 {
537                         $filename = 'nucleus_db_backup_' . i18n::formatted_datetime('%Y-%m-%d-%H-%M-%S', time()) . ".sql";
538                 }
539                 else
540                 {
541                         // use an output buffer
542                         @ob_start();
543                         @ob_implicit_flush(0);
544                                 
545                         // set filename
546                         $filename = 'nucleus_db_backup_' . i18n::formatted_datetime('%Y-%m-%d-%H-%M-%S', time()) . ".sql.gz";
547                 }
548
549                 // send headers that tell the browser a file is coming
550                 header("Content-Type: text/x-delimtext; name=\"$filename\"");
551                 header("Content-disposition: attachment; filename=$filename");
552
553                 // dump header
554                 echo "/*\n";
555                 echo " * This is a backup file generated by Nucleus \n";
556                 echo " * http://www.nucleuscms.org/\n";
557                 echo " * \n";
558                 echo " * backup-date: " . i18n::formatted_datetime('rfc822GMT', time()) . "\n";
559                 echo " * Nucleus CMS version: " . $nucleus['version'] . "\n";
560                 echo " * \n";
561                 echo " * WARNING: Only try to restore on servers running the exact same version of Nucleus\n";
562                 echo " */\n";
563
564                 // dump all tables
565                 reset($tables);
566                 /* NOTE: hope to use 'self' keyword here but works bad so here use __CLASS__ macro. */
567                 array_walk($tables, array(__CLASS__, 'dump_table'));
568
569                 if ( $gzip )
570                 {
571                         $Size = ob_get_length();
572                         $Crc = crc32(ob_get_contents());
573                         $contents = gzcompress(ob_get_contents());
574                         ob_end_clean();
575                         echo "\x1f\x8b\x08\x00\x00\x00\x00\x00" . substr($contents, 0, strlen($contents) - 4)
576                         . self::gzip_print_four_characters($Crc) . self::gzip_print_four_characters($Size);
577                 }
578                 exit;
579         }
580
581         /**
582          * Backup::dump_table()
583          * Creates a dump for a single table
584          * ($tablename and $key are filled in by array_walk)
585          *
586          * @static
587          * @param       string  $tablename
588          * @param       string  $key
589          */
590         static private function dump_table($tablename, $key)
591         {
592                 echo "/*\n";
593                 echo " * TABLE: " . $tablename . "\n";
594                 echo " */\n";
595
596                 // dump table structure
597                 self::dump_structure($tablename);
598
599                 // dump table contents
600                 self::dump_contents($tablename);
601                 return;
602         }
603
604         /**
605          * Backup::dump_structure()
606          * Creates a dump of the table structure for one table
607          *
608          * @static
609          * @param       string  $tablename
610          * @return      void
611          *
612          */
613         static private function dump_structure($tablename)
614         {
615                 // add command to drop table on restore
616                 echo "DROP TABLE IF EXISTS {$tablename};\n\n";
617                 $result = DB::getRow("SHOW CREATE TABLE {$tablename}");
618                 echo $result['Create Table'];
619                 echo ";\n\n";
620                 return;
621         }
622
623         /**
624          * Backup::get_field_names()
625          * Returns the field named for the given table in the
626          * following format:
627          * (column1, column2, ..., columnn)
628          *
629          * @static
630          * @param       resource        $result
631          * @param       integer $num_fields
632          * @return      string
633          */
634         static private function get_field_names($result, $num_fields)
635         {
636                 $fields = array();
637                 for ( $j = 0; $j < $num_fields; $j++ )
638                 {
639                         $col = $result->getColumnMeta($j);
640                         $fields[] = $col['name'];
641                 }
642
643                 return '(' . implode(', ', $fields) . ')';
644         }
645
646         /**
647          * Backup::dump_contents()
648          * Creates a dump of the table content for one table
649          *
650          * @static
651          * @param       string  $tablename
652          * @return      void
653          *
654          */
655         static private function dump_contents($tablename)
656         {
657                 /*
658                  * Grab the data from the table.
659                 */
660                 $result = DB::getResult("SELECT * FROM $tablename");
661
662                 if ( $result->rowCount() > 0 )
663                 {
664                         echo "\n";
665                         echo "/*\n";
666                         echo " * Table Data for {$tablename}\n";
667                         echo " */\n";
668                 }
669
670                 $num_fields = $result->columnCount();
671
672                 /*
673                  * Compose fieldname list
674                 */
675                 $tablename_list = self::get_field_names($result, $num_fields);
676
677                 /*
678                  * Loop through the resulting rows and build the sql statement.
679                 */
680                 foreach ( $result as $row )
681                 {
682                         // Start building the SQL statement.
683                         echo 'INSERT INTO ' . $tablename . ' ' . $tablename_list . ' VALUES(';
684                                 
685                         // Loop through the rows and fill in data for each column
686                         for ( $j = 0; $j < $num_fields; $j++ )
687                         {
688                                 if ( !isset($row[$j]) )
689                                 {
690                                         // no data for column
691                                         echo ' NULL';
692                                 }
693                                 elseif ( $row[$j] != '' )
694                                 {
695                                         // data
696                                         echo ' ' . DB::quoteValue($row[$j]);
697                                 }
698                                 else
699                                 {
700                                         // empty column (!= no data!)
701                                         echo "''";
702                                 }
703
704                                 // only add comma when not last column
705                                 if ( $j != ($num_fields - 1) )
706                                 {
707                                         echo ',';
708                                 }
709                         }
710                         echo ");\n";
711                 }
712                 echo "\n";
713                 return;
714         }
715
716         /**
717          * Backup::gzip_print_four_characters()
718          *
719          * @static
720          * @param       integer $val
721          * @return      integer
722          */
723         static private function gzip_print_four_characters($Val)
724         {
725                 for ( $i = 0; $i < 4; $i ++ )
726                 {
727                         $return .= chr($Val % 256);
728                         $Val = floor($Val / 256);
729                 }
730                 return $return;
731         }
732
733         /**
734          * Backup::do_restore()
735          * Restores a database backup
736          *
737          * NOTE: this remains not-static for compatibility
738          *
739          * @param       void
740          * @return      void
741          */
742         public function do_restore()
743         {
744                 $uploadInfo = postFileInfo('backup_file');
745
746                 // first of all: get uploaded file:
747                 if ( array_key_exists('name', $uploadInfo) && empty($uploadInfo['name']) )
748                 {
749                         return 'No file uploaded';
750                 }
751                 if ( !is_uploaded_file($uploadInfo['tmp_name']) )
752                 {
753                         return 'No file uploaded';
754                 }
755
756                 $backup_file_name = $uploadInfo['name'];
757                 $backup_file_tmpname = $uploadInfo['tmp_name'];
758                 $backup_file_type = $uploadInfo['type'];
759
760                 if ( !file_exists($backup_file_tmpname) )
761                 {
762                         return 'File Upload Error';
763                 }
764
765                 if ( !preg_match("#^(text/[a-zA-Z]+)|(application/(x\-)?gzip(\-compressed)?)|(application/octet-stream)$#i", $backup_file_type) )
766                 {
767                         return 'The uploaded file is not of the correct type';
768                 }
769
770                 $gzip = 0;
771                 if ( preg_match("#\.gz#i", $backup_file_name) )
772                 {
773                         $gzip = 1;
774                 }
775
776                 if ( !extension_loaded("zlib") && $gzip )
777                 {
778                         return 'Cannot decompress gzipped backup (zlib package not installed)';
779                 }
780
781                 // get sql query according to gzip setting (either decompress, or not)
782                 $contents = self::get_contents($backup_file_tmpname, $gzip);
783                 if ( $contents == '' )
784                 {
785                         return 'Cannot get contents from this file.';
786                 }
787
788                 /* detect lines */
789                 $lines = preg_split('/[\r\n]/', $contents);
790                 if( $lines === $contents )
791                 {
792                         return 'Cannot parse contents from this file';
793                 }
794
795                 /* get sql statements from each lines */
796                 $queries = self::get_queries($lines);
797                 if ( $queries === array() )
798                 {
799                         return "Cannot get SQL queries from this file.";
800                 }
801
802                 /* execute sql statements */
803                 foreach ( $queries as $query )
804                 {
805                         if ( DB::execute($query) === FALSE )
806                         {
807                                 $error = DB::getError();
808                                 debug('SQL Error: ' . $error[2]);
809                                 break;
810                         }
811                         continue;
812                 }
813                 return;
814         }
815
816         static private function get_contents($temporary_name, $gzip = 0)
817         {
818                 $contents = '';
819                 if ( $gzip )
820                 {
821                         // decompress and read
822                         $gz_ptr = gzopen($temporary_name, 'rb');
823                         while ( !gzeof($gz_ptr) )
824                         {
825                                 $contents .= gzgets($gz_ptr, 100000);
826                         }
827                 }
828                 else
829                 {
830                         // just read
831                         $fsize = filesize($temporary_name);
832                         if ( $fsize > 0 )
833                         {
834                                 $contents = fread(fopen($temporary_name, 'r'), $fsize);
835                         }
836                 }
837                 return $contents;
838         }
839
840         static private function get_queries($lines)
841         {
842                 $query = '';
843                 $queries = array();
844                 foreach ( $lines as $line )
845                 {
846                         $line = trim($line);
847                         if ( !$line || $line[0] == '#' || preg_match('#^[\s|/]?\*#', $line) )
848                         {
849                                 continue;
850                         }
851
852                         if ( preg_match('/^(.*);$/', $line, $matches) === 0 )
853                         {
854                                 $query .= $line;
855                         }
856                         else
857                         {
858                                 $query .= $matches[1];
859                                 $queries[] = $query;
860                                 $query = '';
861                         }
862                         continue;
863                 }
864                 return $queries;
865         }
866 >>>>>>> skinnable-master
867 }