Advertisement
vermontdevil

MySQL Big File Dump

Aug 30th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 39.37 KB | None | 0 0
  1. <?php
  2.  
  3. error_reporting(E_ALL);
  4.  
  5. // BigDump ver. 0.36b from 2015-04-30
  6. // Staggered import of an large MySQL Dump (like phpMyAdmin 2.x Dump)
  7. // Even through the webservers with hard runtime limit and those in safe mode
  8. // Works fine with latest Chrome, Internet Explorer and Firefox
  9.  
  10. // Author:       Alexey Ozerov (alexey at ozerov dot de)
  11. //               AJAX & CSV functionalities: Krzysiek Herod (kr81uni at wp dot pl)
  12. // Copyright:    GPL (C) 2003-2015
  13. // More Infos:   http://www.ozerov.de/bigdump
  14.  
  15. // This program is free software; you can redistribute it and/or modify it under the
  16. // terms of the GNU General Public License as published by the Free Software Foundation;
  17. // either version 2 of the License, or (at your option) any later version.
  18.  
  19. // THIS SCRIPT IS PROVIDED AS IS, WITHOUT ANY WARRANTY OR GUARANTEE OF ANY KIND
  20.  
  21. // USAGE
  22.  
  23. // 1. Adjust the database configuration and charset in this file
  24. // 2. Remove the old tables on the target database if your dump doesn't contain "DROP TABLE"
  25. // 3. Create the working directory (e.g. dump) on your web server
  26. // 4. Upload bigdump.php and your dump files (.sql, .gz) via FTP to the working directory
  27. // 5. Run the bigdump.php from your browser via URL like http://www.yourdomain.com/dump/bigdump.php
  28. // 6. BigDump can start the next import session automatically if you enable the JavaScript
  29. // 7. Wait for the script to finish, do not close the browser window
  30. // 8. IMPORTANT: Remove bigdump.php and your dump files from the web server
  31.  
  32. // If Timeout errors still occure you may need to adjust the $linepersession setting in this file
  33.  
  34. // LAST CHANGES
  35.  
  36. // *** Fix a typo in HTML code
  37. // *** Change from mySQL to mySQLi
  38.  
  39. // Database configuration
  40.  
  41. $db_server   = 'localhost';
  42. $db_name     = '';
  43. $db_username = '';
  44. $db_password = '';
  45.  
  46. // Connection charset should be the same as the dump file charset (utf8, latin1, cp1251, koi8r etc.)
  47. // See http://dev.mysql.com/doc/refman/5.0/en/charset-charsets.html for the full list
  48. // Change this if you have problems with non-latin letters
  49.  
  50. $db_connection_charset = 'utf8';
  51.  
  52. // OPTIONAL SETTINGS
  53.  
  54. $filename           = '';     // Specify the dump filename to suppress the file selection dialog
  55. $ajax               = true;   // AJAX mode: import will be done without refreshing the website
  56. $linespersession    = 3000;   // Lines to be executed per one import session
  57. $delaypersession    = 0;      // You can specify a sleep time in milliseconds after each session
  58.                               // Works only if JavaScript is activated. Use to reduce server overrun
  59.  
  60. // CSV related settings (only if you use a CSV dump)
  61.  
  62. $csv_insert_table   = '';     // Destination table for CSV files
  63. $csv_preempty_table = false;  // true: delete all entries from table specified in $csv_insert_table before processing
  64. $csv_delimiter      = ',';    // Field delimiter in CSV file
  65. $csv_add_quotes     = true;   // If your CSV data already have quotes around each field set it to false
  66. $csv_add_slashes    = true;   // If your CSV data already have slashes in front of ' and " set it to false
  67.  
  68. // Allowed comment markers: lines starting with these strings will be ignored by BigDump
  69.  
  70. $comment[]='#';                       // Standard comment lines are dropped by default
  71. $comment[]='-- ';
  72. $comment[]='DELIMITER';               // Ignore DELIMITER switch as it's not a valid SQL statement
  73. // $comment[]='---';                  // Uncomment this line if using proprietary dump created by outdated mysqldump
  74. // $comment[]='CREATE DATABASE';      // Uncomment this line if your dump contains create database queries in order to ignore them
  75. $comment[]='/*!';                     // Or add your own string to leave out other proprietary things
  76.  
  77. // Pre-queries: SQL queries to be executed at the beginning of each import session
  78.  
  79. // $pre_query[]='SET foreign_key_checks = 0';
  80. // $pre_query[]='Add additional queries if you want here';
  81.  
  82. // Default query delimiter: this character at the line end tells Bigdump where a SQL statement ends
  83. // Can be changed by DELIMITER statement in the dump file (normally used when defining procedures/functions)
  84.  
  85. $delimiter = ';';
  86.  
  87. // String quotes character
  88.  
  89. $string_quotes = '\'';                  // Change to '"' if your dump file uses double qoutes for strings
  90.  
  91. // How many lines may be considered to be one query (except text lines)
  92.  
  93. $max_query_lines = 300;
  94.  
  95. // Where to put the upload files into (default: bigdump folder)
  96.  
  97. $upload_dir = dirname(__FILE__);
  98.  
  99. // *******************************************************************************************
  100. // If not familiar with PHP please don't change anything below this line
  101. // *******************************************************************************************
  102.  
  103. if ($ajax)
  104.   ob_start();
  105.  
  106. define ('VERSION','0.36b');
  107. define ('DATA_CHUNK_LENGTH',16384);  // How many chars are read per time
  108. define ('TESTMODE',false);           // Set to true to process the file without actually accessing the database
  109. define ('BIGDUMP_DIR',dirname(__FILE__));
  110. define ('PLUGIN_DIR',BIGDUMP_DIR.'/plugins/');
  111.  
  112. header("Expires: Mon, 1 Dec 2003 01:00:00 GMT");
  113. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  114. header("Cache-Control: no-store, no-cache, must-revalidate");
  115. header("Cache-Control: post-check=0, pre-check=0", false);
  116. header("Pragma: no-cache");
  117.  
  118. @ini_set('auto_detect_line_endings', true);
  119. @set_time_limit(0);
  120.  
  121. if (function_exists("date_default_timezone_set") && function_exists("date_default_timezone_get"))
  122.   @date_default_timezone_set(@date_default_timezone_get());
  123.  
  124. // Clean and strip anything we don't want from user's input [0.27b]
  125.  
  126. foreach ($_REQUEST as $key => $val)
  127. {
  128.   $val = preg_replace("/[^_A-Za-z0-9-\.&= ;\$]/i",'', $val);
  129.   $_REQUEST[$key] = $val;
  130. }
  131.  
  132. // Plugin handling is still EXPERIMENTAL and DISABLED
  133. // Register plugins by including plugin_name.php from each ./plugins/plugin_name
  134. /*
  135. if (is_dir(PLUGIN_DIR))
  136. { if ($dh = opendir(PLUGIN_DIR))
  137.     {
  138.     while (($file = readdir($dh)) !== false)
  139.     { if (is_dir(PLUGIN_DIR.$file) && $file!='.' && $file!='..' && file_exists(PLUGIN_DIR.$file.'/'.$file.'.php'))
  140.        include (PLUGIN_DIR.$file.'/'.$file.'.php');
  141.     }
  142.     closedir($dh);
  143.   }
  144. }
  145. */
  146.  
  147. do_action('header');
  148.  
  149. ?>
  150. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  151. <html>
  152. <head>
  153. <title>BigDump ver. <?php echo (VERSION); ?></title>
  154. <meta http-equiv="CONTENT-TYPE" content="text/html; charset=iso-8859-1"/>
  155. <meta http-equiv="CONTENT-LANGUAGE" content="EN"/>
  156.  
  157. <meta http-equiv="Cache-Control" content="no-cache/"/>
  158. <meta http-equiv="Pragma" content="no-cache"/>
  159. <meta http-equiv="Expires" content="-1"/>
  160. <meta name="robots" content="noindex, nofollow">
  161.  
  162. <?php do_action('head_meta'); ?>
  163.  
  164. <style type="text/css">
  165. <!--
  166.  
  167. body
  168. { background-color:#FFFFF0;
  169. }
  170.  
  171. h1
  172. { font-size:20px;
  173.   line-height:24px;
  174.   font-family:Arial,Helvetica,sans-serif;
  175.   margin-top:5px;
  176.   margin-bottom:5px;
  177. }
  178.  
  179. p,td,th
  180. { font-size:14px;
  181.   line-height:18px;
  182.   font-family:Arial,Helvetica,sans-serif;
  183.   margin-top:5px;
  184.   margin-bottom:5px;
  185.   text-align:justify;
  186.   vertical-align:top;
  187. }
  188.  
  189. p.centr
  190. {
  191.   text-align:center;
  192. }
  193.  
  194. p.smlcentr
  195. { font-size:10px;
  196.   line-height:14px;
  197.   text-align:center;
  198. }
  199.  
  200. p.error
  201. { color:#FF0000;
  202.   font-weight:bold;
  203. }
  204.  
  205. p.success
  206. { color:#00DD00;
  207.   font-weight:bold;
  208. }
  209.  
  210. p.successcentr
  211. { color:#00DD00;
  212.   background-color:#DDDDFF;
  213.   font-weight:bold;
  214.   text-align:center;
  215. }
  216.  
  217. td
  218. { background-color:#F8F8F8;
  219.   text-align:left;
  220. }
  221.  
  222. td.transparent
  223. { background-color:#FFFFF0;
  224. }
  225.  
  226. th
  227. { font-weight:bold;
  228.   color:#FFFFFF;
  229.   background-color:#AAAAEE;
  230.   text-align:left;
  231. }
  232.  
  233. td.right
  234. { text-align:right;
  235. }
  236.  
  237. form
  238. { margin-top:5px;
  239.   margin-bottom:5px;
  240. }
  241.  
  242. div.skin1
  243. {
  244.   border-color:#3333EE;
  245.   border-width:5px;
  246.   border-style:solid;
  247.   background-color:#AAAAEE;
  248.   text-align:center;
  249.   vertical-align:middle;
  250.   padding:3px;
  251.   margin:1px;
  252. }
  253.  
  254. td.bg3
  255. { background-color:#EEEE99;
  256.   text-align:left;
  257.   vertical-align:top;
  258.   width:20%;
  259. }
  260.  
  261. th.bg4
  262. { background-color:#EEAA55;
  263.   text-align:left;
  264.   vertical-align:top;
  265.   width:20%;
  266. }
  267.  
  268. td.bgpctbar
  269. { background-color:#EEEEAA;
  270.   text-align:left;
  271.   vertical-align:middle;
  272.   width:80%;
  273. }
  274.  
  275. <?php do_action('head_style'); ?>
  276.  
  277. -->
  278. </style>
  279.  
  280. </head>
  281.  
  282. <body>
  283.  
  284. <center>
  285.  
  286. <table width="780" cellspacing="0" cellpadding="0">
  287. <tr><td class="transparent">
  288.  
  289. <!-- <h1>BigDump: Staggered MySQL Dump Importer ver. <?php echo (VERSION); ?></h1> -->
  290.  
  291. <?php
  292.  
  293. function skin_open()
  294. {
  295.   echo ('<div class="skin1">');
  296. }
  297.  
  298. function skin_close()
  299. {
  300.   echo ('</div>');
  301. }
  302.  
  303. skin_open();
  304. echo ('<h1>BigDump: Staggered MySQL Dump Importer v'.VERSION.'</h1>');
  305. skin_close();
  306.  
  307. do_action('after_headline');
  308.  
  309. $error = false;
  310. $file  = false;
  311.  
  312. // Check PHP version
  313.  
  314. if (!$error && !function_exists('version_compare'))
  315. { echo ("<p class=\"error\">PHP version 4.1.0 is required for BigDump to proceed. You have PHP ".phpversion()." installed. Sorry!</p>\n");
  316.   $error=true;
  317. }
  318.  
  319. // Check if mysql extension is available
  320.  
  321. if (!$error && !function_exists('mysqli_connect'))
  322. { echo ("<p class=\"error\">There is no mySQLi extension found in your PHP installation. You can use an older Bigdump version if your PHP supports mySQL extension.</p>\n");
  323.   $error=true;
  324. }
  325.  
  326. // Calculate PHP max upload size (handle settings like 10M or 100K)
  327.  
  328. if (!$error)
  329. { $upload_max_filesize=ini_get("upload_max_filesize");
  330.   if (preg_match("/([0-9]+)K/i",$upload_max_filesize,$tempregs)) $upload_max_filesize=$tempregs[1]*1024;
  331.   if (preg_match("/([0-9]+)M/i",$upload_max_filesize,$tempregs)) $upload_max_filesize=$tempregs[1]*1024*1024;
  332.   if (preg_match("/([0-9]+)G/i",$upload_max_filesize,$tempregs)) $upload_max_filesize=$tempregs[1]*1024*1024*1024;
  333. }
  334.  
  335. // Get the current directory
  336. /*
  337. if (isset($_SERVER["CGIA"]))
  338.   $upload_dir=dirname($_SERVER["CGIA"]);
  339. else if (isset($_SERVER["ORIG_PATH_TRANSLATED"]))
  340.   $upload_dir=dirname($_SERVER["ORIG_PATH_TRANSLATED"]);
  341. else if (isset($_SERVER["ORIG_SCRIPT_FILENAME"]))
  342.   $upload_dir=dirname($_SERVER["ORIG_SCRIPT_FILENAME"]);
  343. else if (isset($_SERVER["PATH_TRANSLATED"]))
  344.   $upload_dir=dirname($_SERVER["PATH_TRANSLATED"]);
  345. else
  346.   $upload_dir=dirname($_SERVER["SCRIPT_FILENAME"]);
  347. */
  348.  
  349. do_action ('script_runs');
  350.  
  351. // Handle file upload
  352.  
  353. if (!$error && isset($_REQUEST["uploadbutton"]))
  354. { if (is_uploaded_file($_FILES["dumpfile"]["tmp_name"]) && ($_FILES["dumpfile"]["error"])==0)
  355.   {
  356.     $uploaded_filename=str_replace(" ","_",$_FILES["dumpfile"]["name"]);
  357.     $uploaded_filename=preg_replace("/[^_A-Za-z0-9-\.]/i",'',$uploaded_filename);
  358.     $uploaded_filepath=str_replace("\\","/",$upload_dir."/".$uploaded_filename);
  359.  
  360.     do_action('file_uploaded');
  361.  
  362.     if (file_exists($uploaded_filename))
  363.     { echo ("<p class=\"error\">File $uploaded_filename already exist! Delete and upload again!</p>\n");
  364.     }
  365.     else if (!preg_match("/(\.(sql|gz|csv))$/i",$uploaded_filename))
  366.     { echo ("<p class=\"error\">You may only upload .sql .gz or .csv files.</p>\n");
  367.     }
  368.     else if (!@move_uploaded_file($_FILES["dumpfile"]["tmp_name"],$uploaded_filepath))
  369.     { echo ("<p class=\"error\">Error moving uploaded file ".$_FILES["dumpfile"]["tmp_name"]." to the $uploaded_filepath</p>\n");
  370.       echo ("<p>Check the directory permissions for $upload_dir (must be 777)!</p>\n");
  371.     }
  372.     else
  373.     { echo ("<p class=\"success\">Uploaded file saved as $uploaded_filename</p>\n");
  374.     }
  375.   }
  376.   else
  377.   { echo ("<p class=\"error\">Error uploading file ".$_FILES["dumpfile"]["name"]."</p>\n");
  378.   }
  379. }
  380.  
  381.  
  382. // Handle file deletion (delete only in the current directory for security reasons)
  383.  
  384. if (!$error && isset($_REQUEST["delete"]) && $_REQUEST["delete"]!=basename($_SERVER["SCRIPT_FILENAME"]))
  385. { if (preg_match("/(\.(sql|gz|csv))$/i",$_REQUEST["delete"]) && @unlink($upload_dir.'/'.$_REQUEST["delete"]))
  386.     echo ("<p class=\"success\">".$_REQUEST["delete"]." was removed successfully</p>\n");
  387.   else
  388.     echo ("<p class=\"error\">Can't remove ".$_REQUEST["delete"]."</p>\n");
  389. }
  390.  
  391. // Connect to the database, set charset and execute pre-queries
  392.  
  393. if (!$error && !TESTMODE)
  394. { $mysqli = new mysqli($db_server, $db_username, $db_password, $db_name);
  395.  
  396.   if (mysqli_connect_error())
  397.   { echo ("<p class=\"error\">Database connection failed due to ".mysqli_connect_error()."</p>\n");
  398.     echo ("<p>Edit the database settings in BigDump configuration, or contact your database provider.</p>\n");
  399.     $error=true;
  400.   }
  401.   if (!$error && $db_connection_charset!=='')
  402.     $mysqli->query("SET NAMES $db_connection_charset");
  403.  
  404.   if (!$error && isset ($pre_query) && sizeof ($pre_query)>0)
  405.   { reset($pre_query);
  406.     foreach ($pre_query as $pre_query_value)
  407.     {   if (!$mysqli->query($pre_query_value))
  408.         { echo ("<p class=\"error\">Error with pre-query.</p>\n");
  409.         echo ("<p>Query: ".trim(nl2br(htmlentities($pre_query_value)))."</p>\n");
  410.         echo ("<p>MySQL: ".$mysqli->error."</p>\n");
  411.         $error=true;
  412.         break;
  413.      }
  414.     }
  415.   }
  416. }
  417. else
  418. { $dbconnection = false;
  419. }
  420.  
  421. do_action('database_connected');
  422.  
  423. // DIAGNOSTIC
  424. // echo("<h1>Checkpoint!</h1>");
  425.  
  426. // List uploaded files in multifile mode
  427.  
  428. if (!$error && !isset($_REQUEST["fn"]) && $filename=="")
  429. { if ($dirhandle = opendir($upload_dir))
  430.   {
  431.     $files=array();
  432.     while (false !== ($files[] = readdir($dirhandle)));
  433.     closedir($dirhandle);
  434.     $dirhead=false;
  435.  
  436.     if (sizeof($files)>0)
  437.     {
  438.       sort($files);
  439.       foreach ($files as $dirfile)
  440.       {
  441.         if ($dirfile != "." && $dirfile != ".." && $dirfile!=basename($_SERVER["SCRIPT_FILENAME"]) && preg_match("/\.(sql|gz|csv)$/i",$dirfile))
  442.         { if (!$dirhead)
  443.           { echo ("<table width=\"100%\" cellspacing=\"2\" cellpadding=\"2\">\n");
  444.             echo ("<tr><th>Filename</th><th>Size</th><th>Date&amp;Time</th><th>Type</th><th>&nbsp;</th><th>&nbsp;</th>\n");
  445.             $dirhead=true;
  446.           }
  447.           echo ("<tr><td>$dirfile</td><td class=\"right\">".filesize($upload_dir.'/'.$dirfile)."</td><td>".date ("Y-m-d H:i:s", filemtime($upload_dir.'/'.$dirfile))."</td>");
  448.  
  449.           if (preg_match("/\.sql$/i",$dirfile))
  450.             echo ("<td>SQL</td>");
  451.           elseif (preg_match("/\.gz$/i",$dirfile))
  452.             echo ("<td>GZip</td>");
  453.           elseif (preg_match("/\.csv$/i",$dirfile))
  454.             echo ("<td>CSV</td>");
  455.           else
  456.             echo ("<td>Misc</td>");
  457.  
  458.           if ((preg_match("/\.gz$/i",$dirfile) && function_exists("gzopen")) || preg_match("/\.sql$/i",$dirfile) || preg_match("/\.csv$/i",$dirfile))
  459.             echo ("<td><a href=\"".$_SERVER["PHP_SELF"]."?start=1&amp;fn=".urlencode($dirfile)."&amp;foffset=0&amp;totalqueries=0&amp;delimiter=".urlencode($delimiter)."\">Start Import</a> into $db_name at $db_server</td>\n <td><a href=\"".$_SERVER["PHP_SELF"]."?delete=".urlencode($dirfile)."\">Delete file</a></td></tr>\n");
  460. // TODO: echo ("<td><a href=\"".$_SERVER["PHP_SELF"]."?start=1&amp;fn=".urlencode($dirfile)."&amp;foffset=0&amp;totalqueries=0&amp;delimiter=".urlencode($delimiter)."\">Start Import</a></td>\n <td><a href=\"".$_SERVER["PHP_SELF"]."?delete=".urlencode($dirfile)."\">Delete file</a></td></tr>\n");
  461.           else
  462.             echo ("<td>&nbsp;</td>\n <td>&nbsp;</td></tr>\n");
  463.         }
  464.       }
  465.     }
  466.  
  467.     if ($dirhead)
  468.       echo ("</table>\n");
  469.     else
  470.       echo ("<p>No uploaded SQL, GZ or CSV files found in the working directory</p>\n");
  471.   }
  472.   else
  473.   { echo ("<p class=\"error\">Error listing directory $upload_dir</p>\n");
  474.     $error=true;
  475.   }
  476. }
  477.  
  478.  
  479. // Single file mode
  480.  
  481. if (!$error && !isset ($_REQUEST["fn"]) && $filename!="")
  482. { echo ("<p><a href=\"".$_SERVER["PHP_SELF"]."?start=1&amp;fn=".urlencode($filename)."&amp;foffset=0&amp;totalqueries=0\">Start Import</a> from $filename into $db_name at $db_server</p>\n");
  483. }
  484.  
  485.  
  486. // File Upload Form
  487.  
  488. if (!$error && !isset($_REQUEST["fn"]) && $filename=="")
  489. {
  490.  
  491. // Test permissions on working directory
  492.  
  493.   do { $tempfilename=$upload_dir.'/'.time().".tmp"; } while (file_exists($tempfilename));
  494.   if (!($tempfile=@fopen($tempfilename,"w")))
  495.   { echo ("<p>Upload form disabled. Permissions for the working directory <i>$upload_dir</i> <b>must be set writable for the webserver</b> in order ");
  496.     echo ("to upload files here. Alternatively you can upload your dump files via FTP.</p>\n");
  497.   }
  498.   else
  499.   { fclose($tempfile);
  500.     unlink ($tempfilename);
  501.  
  502.     echo ("<p>You can now upload your dump file up to $upload_max_filesize bytes (".round ($upload_max_filesize/1024/1024)." Mbytes)  ");
  503.     echo ("directly from your browser to the server. Alternatively you can upload your dump files of any size via FTP.</p>\n");
  504. ?>
  505. <form method="POST" action="<?php echo ($_SERVER["PHP_SELF"]); ?>" enctype="multipart/form-data">
  506. <input type="hidden" name="MAX_FILE_SIZE" value="$upload_max_filesize">
  507. <p>Dump file: <input type="file" name="dumpfile" accept="*/*" size="60"></p>
  508. <p><input type="submit" name="uploadbutton" value="Upload"></p>
  509. </form>
  510. <?php
  511.   }
  512. }
  513.  
  514. // Print the current mySQL connection charset
  515.  
  516. if (!$error && !TESTMODE && !isset($_REQUEST["fn"]))
  517. {
  518.   $result = $mysqli->query("SHOW VARIABLES LIKE 'character_set_connection';");
  519.   if ($result)
  520.   { $row = $result->fetch_assoc();
  521.     if ($row)
  522.     { $charset = $row['Value'];
  523.       echo ("<p>Note: The current mySQL connection charset is <i>$charset</i>. Your dump file must be encoded in <i>$charset</i> in order to avoid problems with non-latin characters. You can change the connection charset using the \$db_connection_charset variable in bigdump.php</p>\n");
  524.     }
  525.     $result->free();
  526.   }
  527. }
  528.  
  529. // Open the file
  530.  
  531. if (!$error && isset($_REQUEST["start"]))
  532. {
  533.  
  534. // Set current filename ($filename overrides $_REQUEST["fn"] if set)
  535.  
  536.   if ($filename!="")
  537.     $curfilename=$filename;
  538.   else if (isset($_REQUEST["fn"]))
  539.     $curfilename=urldecode($_REQUEST["fn"]);
  540.   else
  541.     $curfilename="";
  542.  
  543. // Recognize GZip filename
  544.  
  545.   if (preg_match("/\.gz$/i",$curfilename))
  546.     $gzipmode=true;
  547.   else
  548.     $gzipmode=false;
  549.  
  550.   if ((!$gzipmode && !$file=@fopen($upload_dir.'/'.$curfilename,"r")) || ($gzipmode && !$file=@gzopen($upload_dir.'/'.$curfilename,"r")))
  551.   { echo ("<p class=\"error\">Can't open ".$curfilename." for import</p>\n");
  552.     echo ("<p>Please, check that your dump file name contains only alphanumerical characters, and rename it accordingly, for example: $curfilename.".
  553.            "<br>Or, specify \$filename in bigdump.php with the full filename. ".
  554.            "<br>Or, you have to upload the $curfilename to the server first.</p>\n");
  555.     $error=true;
  556.   }
  557.  
  558. // Get the file size (can't do it fast on gzipped files, no idea how)
  559.  
  560.   else if ((!$gzipmode && @fseek($file, 0, SEEK_END)==0) || ($gzipmode && @gzseek($file, 0)==0))
  561.   { if (!$gzipmode) $filesize = ftell($file);
  562.     else $filesize = gztell($file);                   // Always zero, ignore
  563.   }
  564.   else
  565.   { echo ("<p class=\"error\">I can't seek into $curfilename</p>\n");
  566.     $error=true;
  567.   }
  568.  
  569. // Stop if csv file is used, but $csv_insert_table is not set
  570.  
  571.   if (!$error && ($csv_insert_table == "") && (preg_match("/(\.csv)$/i",$curfilename)))
  572.   { echo ("<p class=\"error\">You have to specify \$csv_insert_table when using a CSV file. </p>\n");
  573.     $error=true;
  574.   }
  575. }
  576.  
  577.  
  578. // *******************************************************************************************
  579. // START IMPORT SESSION HERE
  580. // *******************************************************************************************
  581.  
  582. if (!$error && isset($_REQUEST["start"]) && isset($_REQUEST["foffset"]) && preg_match("/(\.(sql|gz|csv))$/i",$curfilename))
  583. {
  584.  
  585.   do_action('session_start');
  586.  
  587. // Check start and foffset are numeric values
  588.  
  589.   if (!is_numeric($_REQUEST["start"]) || !is_numeric($_REQUEST["foffset"]))
  590.   { echo ("<p class=\"error\">UNEXPECTED: Non-numeric values for start and foffset</p>\n");
  591.     $error=true;
  592.   }
  593.   else
  594.   { $_REQUEST["start"]   = floor($_REQUEST["start"]);
  595.     $_REQUEST["foffset"] = floor($_REQUEST["foffset"]);
  596.   }
  597.  
  598. // Set the current delimiter if defined
  599.  
  600.   if (isset($_REQUEST["delimiter"]))
  601.     $delimiter = $_REQUEST["delimiter"];
  602.  
  603. // Empty CSV table if requested
  604.  
  605.   if (!$error && $_REQUEST["start"]==1 && $csv_insert_table != "" && $csv_preempty_table)
  606.   {
  607.     $query = "DELETE FROM `$csv_insert_table`";
  608.     if (!TESTMODE && !$mysqli->query(trim($query)))
  609.     { echo ("<p class=\"error\">Error when deleting entries from $csv_insert_table.</p>\n");
  610.       echo ("<p>Query: ".trim(nl2br(htmlentities($query)))."</p>\n");
  611.       echo ("<p>MySQL: ".$mysqli->error."</p>\n");
  612.       $error=true;
  613.     }
  614.   }
  615.  
  616. // Print start message
  617.  
  618.   if (!$error)
  619.   { skin_open();
  620.     if (TESTMODE)
  621.       echo ("<p class=\"centr\">TEST MODE ENABLED</p>\n");
  622.     echo ("<p class=\"centr\">Processing file: <b>".$curfilename."</b></p>\n");
  623.     echo ("<p class=\"smlcentr\">Starting from line: ".$_REQUEST["start"]."</p>\n");   
  624.     skin_close();
  625.   }
  626.  
  627. // Check $_REQUEST["foffset"] upon $filesize (can't do it on gzipped files)
  628.  
  629.   if (!$error && !$gzipmode && $_REQUEST["foffset"]>$filesize)
  630.   { echo ("<p class=\"error\">UNEXPECTED: Can't set file pointer behind the end of file</p>\n");
  631.     $error=true;
  632.   }
  633.  
  634. // Set file pointer to $_REQUEST["foffset"]
  635.  
  636.   if (!$error && ((!$gzipmode && fseek($file, $_REQUEST["foffset"])!=0) || ($gzipmode && gzseek($file, $_REQUEST["foffset"])!=0)))
  637.   { echo ("<p class=\"error\">UNEXPECTED: Can't set file pointer to offset: ".$_REQUEST["foffset"]."</p>\n");
  638.     $error=true;
  639.   }
  640.  
  641. // Start processing queries from $file
  642.  
  643.   if (!$error)
  644.   { $query="";
  645.     $queries=0;
  646.     $totalqueries=$_REQUEST["totalqueries"];
  647.     $linenumber=$_REQUEST["start"];
  648.     $querylines=0;
  649.     $inparents=false;
  650.  
  651. // Stay processing as long as the $linespersession is not reached or the query is still incomplete
  652.  
  653.     while ($linenumber<$_REQUEST["start"]+$linespersession || $query!="")
  654.     {
  655.  
  656. // Read the whole next line
  657.  
  658.       $dumpline = "";
  659.       while (!feof($file) && substr ($dumpline, -1) != "\n" && substr ($dumpline, -1) != "\r")
  660.       { if (!$gzipmode)
  661.           $dumpline .= fgets($file, DATA_CHUNK_LENGTH);
  662.         else
  663.           $dumpline .= gzgets($file, DATA_CHUNK_LENGTH);
  664.       }
  665.       if ($dumpline==="") break;
  666.  
  667. // Remove UTF8 Byte Order Mark at the file beginning if any
  668.  
  669.       if ($_REQUEST["foffset"]==0)
  670.         $dumpline=preg_replace('|^\xEF\xBB\xBF|','',$dumpline);
  671.  
  672. // Create an SQL query from CSV line
  673.  
  674.       if (($csv_insert_table != "") && (preg_match("/(\.csv)$/i",$curfilename)))
  675.       {
  676.         if ($csv_add_slashes)
  677.           $dumpline = addslashes($dumpline);
  678.         $dumpline = explode($csv_delimiter,$dumpline);
  679.         if ($csv_add_quotes)
  680.           $dumpline = "'".implode("','",$dumpline)."'";
  681.         else
  682.           $dumpline = implode(",",$dumpline);
  683.         $dumpline = 'INSERT INTO '.$csv_insert_table.' VALUES ('.$dumpline.');';
  684.       }
  685.  
  686. // Handle DOS and Mac encoded linebreaks (I don't know if it really works on Win32 or Mac Servers)
  687.  
  688.       $dumpline=str_replace("\r\n", "\n", $dumpline);
  689.       $dumpline=str_replace("\r", "\n", $dumpline);
  690.            
  691. // DIAGNOSTIC
  692. // echo ("<p>Line $linenumber: $dumpline</p>\n");
  693.  
  694. // Recognize delimiter statement
  695.  
  696.       if (!$inparents && strpos ($dumpline, "DELIMITER ") === 0)
  697.         $delimiter = str_replace ("DELIMITER ","",trim($dumpline));
  698.  
  699. // Skip comments and blank lines only if NOT in parents
  700.  
  701.       if (!$inparents)
  702.       { $skipline=false;
  703.         reset($comment);
  704.         foreach ($comment as $comment_value)
  705.         {
  706.  
  707. // DIAGNOSTIC
  708. //          echo ($comment_value);
  709.           if (trim($dumpline)=="" || strpos (trim($dumpline), $comment_value) === 0)
  710.           { $skipline=true;
  711.             break;
  712.           }
  713.         }
  714.         if ($skipline)
  715.         { $linenumber++;
  716.  
  717. // DIAGNOSTIC
  718. // echo ("<p>Comment line skipped</p>\n");
  719.  
  720.           continue;
  721.         }
  722.       }
  723.  
  724. // Remove double back-slashes from the dumpline prior to count the quotes ('\\' can only be within strings)
  725.      
  726.       $dumpline_deslashed = str_replace ("\\\\","",$dumpline);
  727.  
  728. // Count ' and \' (or " and \") in the dumpline to avoid query break within a text field ending by $delimiter
  729.  
  730.       $parents=substr_count ($dumpline_deslashed, $string_quotes)-substr_count ($dumpline_deslashed, "\\$string_quotes");
  731.       if ($parents % 2 != 0)
  732.         $inparents=!$inparents;
  733.  
  734. // Add the line to query
  735.  
  736.       $query .= $dumpline;
  737.  
  738. // Don't count the line if in parents (text fields may include unlimited linebreaks)
  739.      
  740.       if (!$inparents)
  741.         $querylines++;
  742.      
  743. // Stop if query contains more lines as defined by $max_query_lines
  744.  
  745.       if ($querylines>$max_query_lines)
  746.       {
  747.         echo ("<p class=\"error\">Stopped at the line $linenumber. </p>");
  748.         echo ("<p>At this place the current query includes more than ".$max_query_lines." dump lines. That can happen if your dump file was ");
  749.         echo ("created by some tool which doesn't place a semicolon followed by a linebreak at the end of each query, or if your dump contains ");
  750.         echo ("extended inserts or very long procedure definitions. Please read the <a href=\"http://www.ozerov.de/bigdump/usage/\">BigDump usage notes</a> ");
  751.         echo ("for more infos. Ask for our support services ");
  752.         echo ("in order to handle dump files containing extended inserts.</p>\n");
  753.         $error=true;
  754.         break;
  755.       }
  756.  
  757. // Execute query if end of query detected ($delimiter as last character) AND NOT in parents
  758.  
  759. // DIAGNOSTIC
  760. // echo ("<p>Regex: ".'/'.preg_quote($delimiter).'$/'."</p>\n");
  761. // echo ("<p>In Parents: ".($inparents?"true":"false")."</p>\n");
  762. // echo ("<p>Line: $dumpline</p>\n");
  763.  
  764.       if ((preg_match('/'.preg_quote($delimiter,'/').'$/',trim($dumpline)) || $delimiter=='') && !$inparents)
  765.       {
  766.  
  767. // Cut off delimiter of the end of the query
  768.  
  769.         $query = substr(trim($query),0,-1*strlen($delimiter));
  770.  
  771. // DIAGNOSTIC
  772. // echo ("<p>Query: ".trim(nl2br(htmlentities($query)))."</p>\n");
  773.  
  774.         if (!TESTMODE && !$mysqli->query($query))
  775.         { echo ("<p class=\"error\">Error at the line $linenumber: ". trim($dumpline)."</p>\n");
  776.           echo ("<p>Query: ".trim(nl2br(htmlentities($query)))."</p>\n");
  777.           echo ("<p>MySQL: ".$mysqli->error."</p>\n");
  778.           $error=true;
  779.           break;
  780.         }
  781.         $totalqueries++;
  782.         $queries++;
  783.         $query="";
  784.         $querylines=0;
  785.       }
  786.       $linenumber++;
  787.     }
  788.   }
  789.  
  790. // Get the current file position
  791.  
  792.   if (!$error)
  793.   { if (!$gzipmode)
  794.       $foffset = ftell($file);
  795.     else
  796.       $foffset = gztell($file);
  797.     if (!$foffset)
  798.     { echo ("<p class=\"error\">UNEXPECTED: Can't read the file pointer offset</p>\n");
  799.       $error=true;
  800.     }
  801.   }
  802.  
  803. // Print statistics
  804.  
  805. skin_open();
  806.  
  807. // echo ("<p class=\"centr\"><b>Statistics</b></p>\n");
  808.  
  809.   if (!$error)
  810.   {
  811.     $lines_this   = $linenumber-$_REQUEST["start"];
  812.     $lines_done   = $linenumber-1;
  813.     $lines_togo   = ' ? ';
  814.     $lines_tota   = ' ? ';
  815.    
  816.     $queries_this = $queries;
  817.     $queries_done = $totalqueries;
  818.     $queries_togo = ' ? ';
  819.     $queries_tota = ' ? ';
  820.  
  821.     $bytes_this   = $foffset-$_REQUEST["foffset"];
  822.     $bytes_done   = $foffset;
  823.     $kbytes_this  = round($bytes_this/1024,2);
  824.     $kbytes_done  = round($bytes_done/1024,2);
  825.     $mbytes_this  = round($kbytes_this/1024,2);
  826.     $mbytes_done  = round($kbytes_done/1024,2);
  827.    
  828.     if (!$gzipmode)
  829.     {
  830.       $bytes_togo  = $filesize-$foffset;
  831.       $bytes_tota  = $filesize;
  832.       $kbytes_togo = round($bytes_togo/1024,2);
  833.       $kbytes_tota = round($bytes_tota/1024,2);
  834.       $mbytes_togo = round($kbytes_togo/1024,2);
  835.       $mbytes_tota = round($kbytes_tota/1024,2);
  836.      
  837.       $pct_this   = ceil($bytes_this/$filesize*100);
  838.       $pct_done   = ceil($foffset/$filesize*100);
  839.       $pct_togo   = 100 - $pct_done;
  840.       $pct_tota   = 100;
  841.  
  842.       if ($bytes_togo==0)
  843.       { $lines_togo   = '0';
  844.         $lines_tota   = $linenumber-1;
  845.         $queries_togo = '0';
  846.         $queries_tota = $totalqueries;
  847.       }
  848.  
  849.       $pct_bar    = "<div style=\"height:15px;width:$pct_done%;background-color:#000080;margin:0px;\"></div>";
  850.     }
  851.     else
  852.     {
  853.       $bytes_togo  = ' ? ';
  854.       $bytes_tota  = ' ? ';
  855.       $kbytes_togo = ' ? ';
  856.       $kbytes_tota = ' ? ';
  857.       $mbytes_togo = ' ? ';
  858.       $mbytes_tota = ' ? ';
  859.      
  860.       $pct_this    = ' ? ';
  861.       $pct_done    = ' ? ';
  862.       $pct_togo    = ' ? ';
  863.       $pct_tota    = 100;
  864.       $pct_bar     = str_replace(' ','&nbsp;','<tt>[         Not available for gzipped files          ]</tt>');
  865.     }
  866.    
  867.     echo ("
  868.    <center>
  869.    <table width=\"520\" border=\"0\" cellpadding=\"3\" cellspacing=\"1\">
  870.    <tr><th class=\"bg4\"> </th><th class=\"bg4\">Session</th><th class=\"bg4\">Done</th><th class=\"bg4\">To go</th><th class=\"bg4\">Total</th></tr>
  871.    <tr><th class=\"bg4\">Lines</th><td class=\"bg3\">$lines_this</td><td class=\"bg3\">$lines_done</td><td class=\"bg3\">$lines_togo</td><td class=\"bg3\">$lines_tota</td></tr>
  872.    <tr><th class=\"bg4\">Queries</th><td class=\"bg3\">$queries_this</td><td class=\"bg3\">$queries_done</td><td class=\"bg3\">$queries_togo</td><td class=\"bg3\">$queries_tota</td></tr>
  873.    <tr><th class=\"bg4\">Bytes</th><td class=\"bg3\">$bytes_this</td><td class=\"bg3\">$bytes_done</td><td class=\"bg3\">$bytes_togo</td><td class=\"bg3\">$bytes_tota</td></tr>
  874.    <tr><th class=\"bg4\">KB</th><td class=\"bg3\">$kbytes_this</td><td class=\"bg3\">$kbytes_done</td><td class=\"bg3\">$kbytes_togo</td><td class=\"bg3\">$kbytes_tota</td></tr>
  875.    <tr><th class=\"bg4\">MB</th><td class=\"bg3\">$mbytes_this</td><td class=\"bg3\">$mbytes_done</td><td class=\"bg3\">$mbytes_togo</td><td class=\"bg3\">$mbytes_tota</td></tr>
  876.    <tr><th class=\"bg4\">%</th><td class=\"bg3\">$pct_this</td><td class=\"bg3\">$pct_done</td><td class=\"bg3\">$pct_togo</td><td class=\"bg3\">$pct_tota</td></tr>
  877.    <tr><th class=\"bg4\">% bar</th><td class=\"bgpctbar\" colspan=\"4\">$pct_bar</td></tr>
  878.    </table>
  879.    </center>
  880.    \n");
  881.  
  882. // Finish message and restart the script
  883.  
  884.     if ($linenumber<$_REQUEST["start"]+$linespersession)
  885.     { echo ("<p class=\"successcentr\">Congratulations: End of file reached, assuming OK</p>\n");
  886.       echo ("<p class=\"successcentr\">IMPORTANT: REMOVE YOUR DUMP FILE and BIGDUMP SCRIPT FROM SERVER NOW!</p>\n");
  887.       echo ("<p class=\"centr\">Thank you for using this tool! Please rate <a href=\"http://www.hotscripts.com/listing/bigdump/?RID=403\" target=\"_blank\">Bigdump at Hotscripts.com</a></p>\n");
  888.       echo ("<p class=\"centr\">You can send me some bucks or euros as appreciation via PayPal. Thank you!</p>\n");
  889. ?>
  890.  
  891. <!-- Start Paypal donation code -->
  892. <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
  893. <input type="hidden" name="cmd" value="_xclick" />
  894. <input type="hidden" name="business" value="alexey@ozerov.de" />
  895. <input type="hidden" name="item_name" value="BigDump Donation" />
  896. <input type="hidden" name="no_shipping" value="1" />
  897. <input type="hidden" name="no_note" value="0" />
  898. <input type="hidden" name="tax" value="0" />
  899. <input type="hidden" name="bn" value="PP-DonationsBF" />
  900. <input type="hidden" name="lc" value="US" />
  901. <input type="image" src="https://www.paypal.com/en_US/i/btn/x-click-but04.gif" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!" />
  902. <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" />
  903. </form>
  904. <!-- End Paypal donation code -->
  905.  
  906. <?php      
  907.       do_action('script_finished');
  908.       $error=true; // This is a semi-error telling the script is finished
  909.     }
  910.     else
  911.     { if ($delaypersession!=0)
  912.         echo ("<p class=\"centr\">Now I'm <b>waiting $delaypersession milliseconds</b> before starting next session...</p>\n");
  913.       if (!$ajax)
  914.         echo ("<script language=\"JavaScript\" type=\"text/javascript\">window.setTimeout('location.href=\"".$_SERVER["PHP_SELF"]."?start=$linenumber&fn=".urlencode($curfilename)."&foffset=$foffset&totalqueries=$totalqueries&delimiter=".urlencode($delimiter)."\";',500+$delaypersession);</script>\n");
  915.  
  916.       echo ("<noscript>\n");
  917.       echo ("<p class=\"centr\"><a href=\"".$_SERVER["PHP_SELF"]."?start=$linenumber&amp;fn=".urlencode($curfilename)."&amp;foffset=$foffset&amp;totalqueries=$totalqueries&amp;delimiter=".urlencode($delimiter)."\">Continue from the line $linenumber</a> (Enable JavaScript to do it automatically)</p>\n");
  918.       echo ("</noscript>\n");
  919.    
  920.       echo ("<p class=\"centr\">Press <b><a href=\"".$_SERVER["PHP_SELF"]."\">STOP</a></b> to abort the import <b>OR WAIT!</b></p>\n");
  921.     }
  922.   }
  923.   else
  924.     echo ("<p class=\"error\">Stopped on error</p>\n");
  925.  
  926. skin_close();
  927.  
  928. }
  929.  
  930. if ($error)
  931.   echo ("<p class=\"centr\"><a href=\"".$_SERVER["PHP_SELF"]."\">Start from the beginning</a> (DROP the old tables before restarting)</p>\n");
  932.  
  933. if ($mysqli) $mysqli->close();
  934. if ($file && !$gzipmode) fclose($file);
  935. else if ($file && $gzipmode) gzclose($file);
  936.  
  937. ?>
  938.  
  939. <p class="centr">&copy; 2003-2015 <a href="mailto:alexey@ozerov.de">Alexey Ozerov</a></p>
  940.  
  941. </td></tr></table>
  942.  
  943. </center>
  944. <?php do_action('end_of_body'); ?>
  945. </body>
  946. </html>
  947.  
  948. <?php
  949.  
  950. // If error or finished put out the whole output from above and stop
  951.  
  952. if ($error)
  953. {
  954.   $out1 = ob_get_contents();
  955.   ob_end_clean();
  956.   echo $out1;
  957.   die;
  958. }
  959.  
  960. // If Ajax enabled and in import progress creates responses  (XML response or script for the initial page)
  961.  
  962. if ($ajax && isset($_REQUEST['start']))
  963. {
  964.   if (isset($_REQUEST['ajaxrequest']))
  965.   { ob_end_clean();
  966.       create_xml_response();
  967.       die;
  968.   }
  969.   else
  970.     create_ajax_script();    
  971. }
  972.  
  973. // Anyway put out the output from above
  974.  
  975. ob_flush();
  976.  
  977. // THE MAIN SCRIPT ENDS HERE
  978.  
  979. // *******************************************************************************************
  980. // Plugin handling (EXPERIMENTAL)
  981. // *******************************************************************************************
  982.  
  983. function do_action($tag)
  984. { global $plugin_actions;
  985.  
  986.   if (isset($plugin_actions[$tag]))
  987.   { reset ($plugin_actions[$tag]);
  988.     foreach ($plugin_actions[$tag] as $action)
  989.       call_user_func_array($action, array());
  990.   }
  991. }
  992.  
  993. function add_action($tag, $function)
  994. {
  995.     global $plugin_actions;
  996.     $plugin_actions[$tag][] = $function;
  997. }
  998.  
  999. // *******************************************************************************************
  1000. //              AJAX utilities
  1001. // *******************************************************************************************
  1002.  
  1003. function create_xml_response()
  1004. {
  1005.   global $linenumber, $foffset, $totalqueries, $curfilename, $delimiter,
  1006.                  $lines_this, $lines_done, $lines_togo, $lines_tota,
  1007.                  $queries_this, $queries_done, $queries_togo, $queries_tota,
  1008.                  $bytes_this, $bytes_done, $bytes_togo, $bytes_tota,
  1009.                  $kbytes_this, $kbytes_done, $kbytes_togo, $kbytes_tota,
  1010.                  $mbytes_this, $mbytes_done, $mbytes_togo, $mbytes_tota,
  1011.                  $pct_this, $pct_done, $pct_togo, $pct_tota,$pct_bar;
  1012.  
  1013.     header('Content-Type: application/xml');
  1014.     header('Cache-Control: no-cache');
  1015.    
  1016.     echo '<?xml version="1.0" encoding="ISO-8859-1"?>';
  1017.     echo "<root>";
  1018.  
  1019. // data - for calculations
  1020.  
  1021.     echo "<linenumber>$linenumber</linenumber>";
  1022.     echo "<foffset>$foffset</foffset>";
  1023.     echo "<fn>$curfilename</fn>";
  1024.     echo "<totalqueries>$totalqueries</totalqueries>";
  1025.     echo "<delimiter>$delimiter</delimiter>";
  1026.  
  1027. // results - for page update
  1028.  
  1029.     echo "<elem1>$lines_this</elem1>";
  1030.     echo "<elem2>$lines_done</elem2>";
  1031.     echo "<elem3>$lines_togo</elem3>";
  1032.     echo "<elem4>$lines_tota</elem4>";
  1033.    
  1034.     echo "<elem5>$queries_this</elem5>";
  1035.     echo "<elem6>$queries_done</elem6>";
  1036.     echo "<elem7>$queries_togo</elem7>";
  1037.     echo "<elem8>$queries_tota</elem8>";
  1038.    
  1039.     echo "<elem9>$bytes_this</elem9>";
  1040.     echo "<elem10>$bytes_done</elem10>";
  1041.     echo "<elem11>$bytes_togo</elem11>";
  1042.     echo "<elem12>$bytes_tota</elem12>";
  1043.            
  1044.     echo "<elem13>$kbytes_this</elem13>";
  1045.     echo "<elem14>$kbytes_done</elem14>";
  1046.     echo "<elem15>$kbytes_togo</elem15>";
  1047.     echo "<elem16>$kbytes_tota</elem16>";
  1048.    
  1049.     echo "<elem17>$mbytes_this</elem17>";
  1050.     echo "<elem18>$mbytes_done</elem18>";
  1051.     echo "<elem19>$mbytes_togo</elem19>";
  1052.     echo "<elem20>$mbytes_tota</elem20>";
  1053.    
  1054.     echo "<elem21>$pct_this</elem21>";
  1055.     echo "<elem22>$pct_done</elem22>";
  1056.     echo "<elem23>$pct_togo</elem23>";
  1057.     echo "<elem24>$pct_tota</elem24>";
  1058.     echo "<elem_bar>".htmlentities($pct_bar)."</elem_bar>";
  1059.                
  1060.     echo "</root>";    
  1061. }
  1062.  
  1063.  
  1064. function create_ajax_script()
  1065. {
  1066.   global $linenumber, $foffset, $totalqueries, $delaypersession, $curfilename, $delimiter;
  1067. ?>
  1068.  
  1069.     <script type="text/javascript" language="javascript">          
  1070.  
  1071.     // creates next action url (upload page, or XML response)
  1072.     function get_url(linenumber,fn,foffset,totalqueries,delimiter) {
  1073.         return "<?php echo $_SERVER['PHP_SELF'] ?>?start="+linenumber+"&fn="+fn+"&foffset="+foffset+"&totalqueries="+totalqueries+"&delimiter="+delimiter+"&ajaxrequest=true";
  1074.     }
  1075.    
  1076.     // extracts text from XML element (itemname must be unique)
  1077.     function get_xml_data(itemname,xmld) {
  1078.         return xmld.getElementsByTagName(itemname).item(0).firstChild.data;
  1079.     }
  1080.    
  1081.     function makeRequest(url) {
  1082.         http_request = false;
  1083.         if (window.XMLHttpRequest) {
  1084.         // Mozilla etc.
  1085.             http_request = new XMLHttpRequest();
  1086.             if (http_request.overrideMimeType) {
  1087.                 http_request.overrideMimeType("text/xml");
  1088.             }
  1089.         } else if (window.ActiveXObject) {
  1090.         // IE
  1091.             try {
  1092.                 http_request = new ActiveXObject("Msxml2.XMLHTTP");
  1093.             } catch(e) {
  1094.                 try {
  1095.                     http_request = new ActiveXObject("Microsoft.XMLHTTP");
  1096.                 } catch(e) {}
  1097.             }
  1098.         }
  1099.         if (!http_request) {
  1100.                 alert("Cannot create an XMLHTTP instance");
  1101.                 return false;
  1102.         }
  1103.         http_request.onreadystatechange = server_response;
  1104.         http_request.open("GET", url, true);
  1105.         http_request.send(null);
  1106.     }
  1107.    
  1108.     function server_response()
  1109.     {
  1110.  
  1111.       // waiting for correct response
  1112.       if (http_request.readyState != 4)
  1113.         return;
  1114.  
  1115.       if (http_request.status != 200)
  1116.       {
  1117.         alert("Page unavailable, or wrong url!")
  1118.         return;
  1119.       }
  1120.        
  1121.         // r = xml response
  1122.         var r = http_request.responseXML;
  1123.        
  1124.         //if received not XML but HTML with new page to show
  1125.         if (!r || r.getElementsByTagName('root').length == 0)
  1126.         {   var text = http_request.responseText;
  1127.             document.open();
  1128.             document.write(text);      
  1129.             document.close();  
  1130.             return;    
  1131.         }
  1132.        
  1133.         // update "Starting from line: "
  1134.         document.getElementsByTagName('p').item(1).innerHTML =
  1135.             "Starting from line: " +
  1136.                r.getElementsByTagName('linenumber').item(0).firstChild.nodeValue;
  1137.        
  1138.         // update table with new values
  1139.         for(i = 1; i <= 24; i++)
  1140.             document.getElementsByTagName('td').item(i).firstChild.data = get_xml_data('elem'+i,r);
  1141.        
  1142.         // update color bar
  1143.         document.getElementsByTagName('td').item(25).innerHTML =
  1144.             r.getElementsByTagName('elem_bar').item(0).firstChild.nodeValue;
  1145.              
  1146.         // action url (XML response)     
  1147.         url_request =  get_url(
  1148.             get_xml_data('linenumber',r),
  1149.             get_xml_data('fn',r),
  1150.             get_xml_data('foffset',r),
  1151.             get_xml_data('totalqueries',r),
  1152.             get_xml_data('delimiter',r));
  1153.        
  1154.         // ask for XML response
  1155.         window.setTimeout("makeRequest(url_request)",500+<?php echo $delaypersession; ?>);
  1156.     }
  1157.  
  1158.     // First Ajax request from initial page
  1159.  
  1160.     var http_request = false;
  1161.     var url_request =  get_url(<?php echo ($linenumber.',"'.urlencode($curfilename).'",'.$foffset.','.$totalqueries.',"'.urlencode($delimiter).'"') ;?>);
  1162.     window.setTimeout("makeRequest(url_request)",500+<?php echo $delaypersession; ?>);
  1163.     </script>
  1164.  
  1165. <?php
  1166. }
  1167.  
  1168. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement