PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/baser/vendors/mysqldump.php

https://github.com/hashing/basercms
PHP | 402 lines | 257 code | 31 blank | 114 comment | 63 complexity | 9c852904ef203eed69c091d633beb4c4 MD5 | raw file
Possible License(s): MIT
  1. <?php
  2. /**
  3. * Dump MySQL database
  4. *
  5. * Here is an inline example:
  6. * <code>
  7. * $connection = @mysql_connect($dbhost,$dbuser,$dbpsw);
  8. * $dumper = new MySQLDump($dbname,'filename.sql',false,false);
  9. * $dumper->doDump();
  10. * </code>
  11. *
  12. * @name MySQLDump
  13. * @author Daniele Vigan - CreativeFactory.it <daniele.vigano@creativefactory.it> - based on a version by Andrea Ingaglio <andrea@coders4fun.com>
  14. * @version 2.0 - 02/10/2007
  15. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  16. *
  17. */
  18. class MySQLDump {
  19. /**
  20. * @access private
  21. */
  22. var $database = null;
  23. /**
  24. * @access private
  25. */
  26. var $compress = false;
  27. /**
  28. * @access private
  29. */
  30. var $hexValue = false;
  31. /**
  32. * The output filename
  33. * @access private
  34. */
  35. var $filename = null;
  36. /**
  37. * The pointer of the output file
  38. * @access private
  39. */
  40. var $file = null;
  41. /**
  42. * @access private
  43. */
  44. var $isWritten = false;
  45. /**
  46. * Class constructor
  47. * @param string $db The database name
  48. * @param string $filepath The file where the dump will be written
  49. * @param boolean $compress It defines if the output file is compress (gzip) or not
  50. * @param boolean $hexValue It defines if the outup values are base-16 or not
  51. */
  52. function MYSQLDump($db = null, $filepath = 'dump.sql', $compress = false, $hexValue = false){
  53. $this->compress = $compress;
  54. if ( !$this->setOutputFile($filepath) )
  55. return false;
  56. return $this->setDatabase($db);
  57. }
  58. /**
  59. * Sets the database to work on
  60. * @param string $db The database name
  61. */
  62. function setDatabase($db){
  63. $this->database = $db;
  64. if ( !@mysql_select_db($this->database) )
  65. return false;
  66. return true;
  67. }
  68. /**
  69. * Returns the database where the class is working on
  70. * @return string
  71. */
  72. function getDatabase(){
  73. return $this->database;
  74. }
  75. /**
  76. * Sets the output file type (It can be made only if the file hasn't been already written)
  77. * @param boolean $compress If it's true, the output file will be compressed
  78. */
  79. function setCompress($compress){
  80. if ( $this->isWritten )
  81. return false;
  82. $this->compress = $compress;
  83. $this->openFile($this->filename);
  84. return true;
  85. }
  86. /**
  87. * Returns if the output file is or not compressed
  88. * @return boolean
  89. */
  90. function getCompress(){
  91. return $this->compress;
  92. }
  93. /**
  94. * Sets the output file
  95. * @param string $filepath The file where the dump will be written
  96. */
  97. function setOutputFile($filepath){
  98. if ( $this->isWritten )
  99. return false;
  100. $this->filename = $filepath;
  101. $this->file = $this->openFile($this->filename);
  102. return $this->file;
  103. }
  104. /**
  105. * Returns the output filename
  106. * @return string
  107. */
  108. function getOutputFile(){
  109. return $this->filename;
  110. }
  111. /**
  112. * Writes to file the $table's structure
  113. * @param string $table The table name
  114. */
  115. function getTableStructure($table){
  116. if ( !$this->setDatabase($this->database) )
  117. return false;
  118. // Structure Header
  119. $structure = "-- \n";
  120. $structure .= "-- Table structure for table `{$table}` \n";
  121. $structure .= "-- \n\n";
  122. // Dump Structure
  123. $structure .= 'DROP TABLE IF EXISTS `'.$table.'`;'."\n";
  124. $structure .= "CREATE TABLE `".$table."` (\n";
  125. $records = @mysql_query('SHOW FIELDS FROM `'.$table.'`');
  126. if ( @mysql_num_rows($records) == 0 )
  127. return false;
  128. while ( $record = mysql_fetch_assoc($records) ) {
  129. $structure .= '`'.$record['Field'].'` '.$record['Type'];
  130. if ( !empty($record['Default']) )
  131. $structure .= ' DEFAULT \''.$record['Default'].'\'';
  132. if ( @strcmp($record['Null'],'YES') != 0 )
  133. $structure .= ' NOT NULL';
  134. if ( !empty($record['Extra']) )
  135. $structure .= ' '.$record['Extra'];
  136. $structure .= ",\n";
  137. }
  138. $structure = @ereg_replace(",\n$", null, $structure);
  139. // Save all Column Indexes
  140. $structure .= $this->getSqlKeysTable($table);
  141. $structure .= "\n);\n\n-- --------------------------------------------------------\n\n";
  142. $this->saveToFile($this->file,$structure);
  143. }
  144. /**
  145. * Writes to file the $table's data
  146. * @param string $table The table name
  147. * @param boolean $hexValue It defines if the output is base 16 or not
  148. */
  149. function getTableData($table,$hexValue = true) {
  150. if ( !$this->setDatabase($this->database) )
  151. return false;
  152. // Header
  153. $data = "-- \n";
  154. $data .= "-- Dumping data for table `$table` \n";
  155. $data .= "-- \n\n";
  156. $records = mysql_query('SHOW FIELDS FROM `'.$table.'`');
  157. $num_fields = @mysql_num_rows($records);
  158. if ( $num_fields == 0 )
  159. return false;
  160. // Field names
  161. $selectStatement = "SELECT ";
  162. $insertStatement = "INSERT INTO `$table` (";
  163. $hexField = array();
  164. for ($x = 0; $x < $num_fields; $x++) {
  165. $record = @mysql_fetch_assoc($records);
  166. if ( ($hexValue) && ($this->isTextValue($record['Type'])) ) {
  167. $selectStatement .= 'HEX(`'.$record['Field'].'`)';
  168. $hexField [$x] = true;
  169. }
  170. else
  171. $selectStatement .= '`'.$record['Field'].'`';
  172. $insertStatement .= '`'.$record['Field'].'`';
  173. $insertStatement .= ", ";
  174. $selectStatement .= ", ";
  175. }
  176. $insertStatement = @substr($insertStatement,0,-2).') VALUES';
  177. $selectStatement = @substr($selectStatement,0,-2).' FROM `'.$table.'`';
  178. $records = @mysql_query($selectStatement);
  179. $num_rows = @mysql_num_rows($records);
  180. $num_fields = @mysql_num_fields($records);
  181. // Dump data
  182. for ($i = 0; $i < $num_rows; $i++) {
  183. $data .= $insertStatement;
  184. $record = @mysql_fetch_assoc($records);
  185. $data .= ' (';
  186. for ($j = 0; $j < $num_fields; $j++) {
  187. $field_name = @mysql_field_name($records, $j);
  188. if ( @$hexField[$j] && (@strlen($record[$field_name]) > 0) )
  189. $data .= "0x".$record[$field_name];
  190. else
  191. $data .= '\''.@str_replace('\"','"',@mysql_escape_string($record[$field_name])).'\'';
  192. $data .= ',';
  193. }
  194. $data = @substr($data,0,-1).");\n";
  195. //if data in greather than 1MB save
  196. if (strlen($data) > 1048576) {
  197. $this->saveToFile($this->file,$data);
  198. $data = '';
  199. }
  200. }
  201. $data .= "\n-- --------------------------------------------------------\n\n";
  202. $this->saveToFile($this->file,$data);
  203. }
  204. /**
  205. * Writes to file all the selected database tables structure
  206. * @return boolean
  207. */
  208. function getDatabaseStructure(){
  209. $records = @mysql_query('SHOW TABLES');
  210. if ( @mysql_num_rows($records) == 0 )
  211. return false;
  212. $structure = '';
  213. while ( $record = @mysql_fetch_row($records) ) {
  214. $structure .= $this->getTableStructure($record[0]);
  215. }
  216. return true;
  217. }
  218. /**
  219. * Writes to file all the selected database tables data
  220. * @param boolean $hexValue It defines if the output is base-16 or not
  221. */
  222. function getDatabaseData($hexValue = true){
  223. $records = @mysql_query('SHOW TABLES');
  224. if ( @mysql_num_rows($records) == 0 )
  225. return false;
  226. while ( $record = @mysql_fetch_row($records) ) {
  227. $this->getTableData($record[0],$hexValue);
  228. }
  229. }
  230. /**
  231. * Writes to file the selected database dump
  232. */
  233. function doDump() {
  234. $this->saveToFile($this->file,"SET FOREIGN_KEY_CHECKS = 0;\n\n");
  235. $this->getDatabaseStructure();
  236. $this->getDatabaseData($this->hexValue);
  237. $this->saveToFile($this->file,"SET FOREIGN_KEY_CHECKS = 1;\n\n");
  238. $this->closeFile($this->file);
  239. return true;
  240. }
  241. /**
  242. * @deprecated Look at the doDump() method
  243. */
  244. function writeDump($filename) {
  245. if ( !$this->setOutputFile($filename) )
  246. return false;
  247. $this->doDump();
  248. $this->closeFile($this->file);
  249. return true;
  250. }
  251. /**
  252. * @access private
  253. */
  254. function getSqlKeysTable ($table) {
  255. $primary = "";
  256. unset($unique);
  257. unset($index);
  258. unset($fulltext);
  259. $results = mysql_query("SHOW KEYS FROM `{$table}`");
  260. if ( @mysql_num_rows($results) == 0 )
  261. return false;
  262. while($row = mysql_fetch_object($results)) {
  263. if (($row->Key_name == 'PRIMARY') AND ($row->Index_type == 'BTREE')) {
  264. if ( $primary == "" )
  265. $primary = " PRIMARY KEY (`{$row->Column_name}`";
  266. else
  267. $primary .= ", `{$row->Column_name}`";
  268. }
  269. if (($row->Key_name != 'PRIMARY') AND ($row->Non_unique == '0') AND ($row->Index_type == 'BTREE')) {
  270. if ( (!@is_array($unique)) OR ($unique[$row->Key_name]=="") )
  271. $unique[$row->Key_name] = " UNIQUE KEY `{$row->Key_name}` (`{$row->Column_name}`";
  272. else
  273. $unique[$row->Key_name] .= ", `{$row->Column_name}`";
  274. }
  275. if (($row->Key_name != 'PRIMARY') AND ($row->Non_unique == '1') AND ($row->Index_type == 'BTREE')) {
  276. if ( (!@is_array(@$index)) OR (@$index[$row->Key_name]=="") )
  277. $index[$row->Key_name] = " KEY `{$row->Key_name}` (`{$row->Column_name}`";
  278. else
  279. $index[$row->Key_name] .= ", `{$row->Column_name}`";
  280. }
  281. if (($row->Key_name != 'PRIMARY') AND ($row->Non_unique == '1') AND ($row->Index_type == 'FULLTEXT')) {
  282. if ( (!@is_array($fulltext)) OR ($fulltext[$row->Key_name]=="") )
  283. $fulltext[$row->Key_name] = " FULLTEXT `{$row->Key_name}` (`{$row->Column_name}`";
  284. else
  285. $fulltext[$row->Key_name] .= ", `{$row->Column_name}`";
  286. }
  287. }
  288. $sqlKeyStatement = '';
  289. // generate primary, unique, key and fulltext
  290. if ( $primary != "" ) {
  291. $sqlKeyStatement .= ",\n";
  292. $primary .= ")";
  293. $sqlKeyStatement .= $primary;
  294. }
  295. if (@is_array($unique)) {
  296. foreach ($unique as $keyName => $keyDef) {
  297. $sqlKeyStatement .= ",\n";
  298. $keyDef .= ")";
  299. $sqlKeyStatement .= $keyDef;
  300. }
  301. }
  302. if (@is_array($index)) {
  303. foreach ($index as $keyName => $keyDef) {
  304. $sqlKeyStatement .= ",\n";
  305. $keyDef .= ")";
  306. $sqlKeyStatement .= $keyDef;
  307. }
  308. }
  309. if (@is_array($fulltext)) {
  310. foreach ($fulltext as $keyName => $keyDef) {
  311. $sqlKeyStatement .= ",\n";
  312. $keyDef .= ")";
  313. $sqlKeyStatement .= $keyDef;
  314. }
  315. }
  316. return $sqlKeyStatement;
  317. }
  318. /**
  319. * @access private
  320. */
  321. function isTextValue($field_type) {
  322. switch ($field_type) {
  323. case "tinytext":
  324. case "text":
  325. case "mediumtext":
  326. case "longtext":
  327. case "binary":
  328. case "varbinary":
  329. case "tinyblob":
  330. case "blob":
  331. case "mediumblob":
  332. case "longblob":
  333. return True;
  334. break;
  335. default:
  336. return False;
  337. }
  338. }
  339. /**
  340. * @access private
  341. */
  342. function openFile($filename) {
  343. $file = false;
  344. if ( $this->compress )
  345. $file = @gzopen($filename, "w9");
  346. else
  347. $file = @fopen($filename, "w");
  348. return $file;
  349. }
  350. /**
  351. * @access private
  352. */
  353. function saveToFile($file, $data) {
  354. if ( $this->compress )
  355. @gzwrite($file, $data);
  356. else
  357. @fwrite($file, $data);
  358. $this->isWritten = true;
  359. }
  360. /**
  361. * @access private
  362. */
  363. function closeFile($file) {
  364. if ( $this->compress )
  365. @gzclose($file);
  366. else
  367. @fclose($file);
  368. }
  369. }
  370. ?>