backup.class.inc.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. <?php
  2. // Copyright (C) 2010-2012 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. class BackupException extends Exception
  19. {
  20. }
  21. class DBBackup
  22. {
  23. protected $sDBHost;
  24. protected $iDBPort;
  25. protected $sDBUser;
  26. protected $sDBPwd;
  27. protected $sDBName;
  28. protected $sDBSubName;
  29. /**
  30. * Connects to the database to backup
  31. * By default, connects to the current MetaModel (must be loaded)
  32. *
  33. * @param sDBHost string Database host server
  34. * @param $sDBUser string User login
  35. * @param $sDBPwd string User password
  36. * @param $sDBName string Database name
  37. * @param $sDBSubName string Prefix to the tables of itop in the database
  38. */
  39. public function __construct($sDBHost = null, $sDBUser = null, $sDBPwd = null, $sDBName = null, $sDBSubName = null)
  40. {
  41. if (is_null($sDBHost))
  42. {
  43. // Defaulting to the current config
  44. $sDBHost = MetaModel::GetConfig()->GetDBHost();
  45. $sDBUser = MetaModel::GetConfig()->GetDBUser();
  46. $sDBPwd = MetaModel::GetConfig()->GetDBPwd();
  47. $sDBName = MetaModel::GetConfig()->GetDBName();
  48. $sDBSubName = MetaModel::GetConfig()->GetDBSubName();
  49. }
  50. // Compute the port (if present in the host name)
  51. $aConnectInfo = explode(':', $sDBHost);
  52. $sDBHostName = $aConnectInfo[0];
  53. if (count($aConnectInfo) > 1)
  54. {
  55. $iDBPort = $aConnectInfo[1];
  56. }
  57. else
  58. {
  59. $iDBPort = null;
  60. }
  61. $this->sDBHost = $sDBHostName;
  62. $this->iDBPort = $iDBPort;
  63. $this->sDBUser = $sDBUser;
  64. $this->sDBPwd = $sDBPwd;
  65. $this->sDBName = $sDBName;
  66. $this->sDBSubName = $sDBSubName;
  67. }
  68. /**
  69. * Create a normalized backup name, depending on the current date/time and Database
  70. * @param sNameSpec string Name and path, eventually containing itop placeholders + time formatting specs
  71. */
  72. public function MakeName($sNameSpec = "__DB__-%Y-%m-%d")
  73. {
  74. $sFileName = $sNameSpec;
  75. $sFileName = str_replace('__HOST__', $this->sDBHost, $sFileName);
  76. $sFileName = str_replace('__DB__', $this->sDBName, $sFileName);
  77. $sFileName = str_replace('__SUBNAME__', $this->sDBSubName, $sFileName);
  78. // Transform %Y, etc.
  79. $sFileName = strftime($sFileName);
  80. return $sFileName;
  81. }
  82. public function CreateZip($sZipFile, $sSourceConfigFile = null)
  83. {
  84. // Note: the file is created by tempnam and might not be writeable by another process (Windows/IIS)
  85. // (delete it before spawning a process)
  86. $sDataFile = tempnam(SetupUtils::GetTmpDir(), 'itop-');
  87. SetupPage::log("Info - Data file: '$sDataFile'");
  88. if (is_null($sSourceConfigFile))
  89. {
  90. $sSourceConfigFile = MetaModel::GetConfig()->GetLoadedFile();
  91. }
  92. $this->DoBackup($sDataFile);
  93. $this->DoZip($sDataFile, $sSourceConfigFile, $sZipFile);
  94. // Windows/IIS: the data file has been created by the spawned process...
  95. // trying to delete it will issue a warning, itself stopping the setup abruptely
  96. @unlink($sDataFile);
  97. }
  98. protected static function EscapeShellArg($sValue)
  99. {
  100. // Note: See comment from the 23-Apr-2004 03:30 in the PHP documentation
  101. // It suggests to rely on pctnl_* function instead of using escapeshellargs
  102. return escapeshellarg($sValue);
  103. }
  104. /**
  105. * Create a backup file
  106. */
  107. public function DoBackup($sBackupFileName)
  108. {
  109. $sHost = self::EscapeShellArg($this->sDBHost);
  110. $sUser = self::EscapeShellArg($this->sDBUser);
  111. $sPwd = self::EscapeShellArg($this->sDBPwd);
  112. $sDBName = self::EscapeShellArg($this->sDBName);
  113. // Just to check the connection to the DB (better than getting the retcode of mysqldump = 1)
  114. $oMysqli = $this->DBConnect();
  115. $sTables = '';
  116. if ($this->sDBSubName != '')
  117. {
  118. // This instance of iTop uses a prefix for the tables, so there may be other tables in the database
  119. // Let's explicitely list all the tables and views to dump
  120. $aTables = $this->EnumerateTables();
  121. if (count($aTables) == 0)
  122. {
  123. // No table has been found with the given prefix
  124. throw new BackupException("No table has been found with the given prefix");
  125. }
  126. $aEscapedTables = array();
  127. foreach($aTables as $sTable)
  128. {
  129. $aEscapedTables[] = self::EscapeShellArg($sTable);
  130. }
  131. $sTables = implode(' ', $aEscapedTables);
  132. }
  133. $sMySQLBinDir = utils::ReadParam('mysql_bindir', '', true);
  134. if (empty($sMySQLBinDir))
  135. {
  136. $sMySQLDump = 'mysqldump';
  137. }
  138. else
  139. {
  140. $sMySQLDump = '"'.$sMySQLBinDir.'/mysqldump"';
  141. }
  142. // Store the results in a temporary file
  143. $sTmpFileName = self::EscapeShellArg($sBackupFileName);
  144. if (is_null($this->iDBPort))
  145. {
  146. $sPortOption = '';
  147. }
  148. else
  149. {
  150. $sPortOption = '--port='.$this->iDBPort.' ';
  151. }
  152. // Delete the file created by tempnam() so that the spawned process can write into it (Windows/IIS)
  153. unlink($sBackupFileName);
  154. $sCommand = "$sMySQLDump --opt --default-character-set=utf8 --add-drop-database --single-transaction --host=$sHost $sPortOption --user=$sUser --password=$sPwd --result-file=$sTmpFileName $sDBName $sTables 2>&1";
  155. $sCommandDisplay = "$sMySQLDump --opt --default-character-set=utf8 --add-drop-database --single-transaction --host=$sHost $sPortOption --user=xxxxx --password=xxxxx --result-file=$sTmpFileName $sDBName $sTables";
  156. // Now run the command for real
  157. SetupPage::log("Info - Executing command: $sCommandDisplay");
  158. $aOutput = array();
  159. $iRetCode = 0;
  160. exec($sCommand, $aOutput, $iRetCode);
  161. foreach($aOutput as $sLine)
  162. {
  163. SetupPage::log("Info - mysqldump said: $sLine");
  164. }
  165. if ($iRetCode != 0)
  166. {
  167. SetupPage::log("Error - retcode=".$iRetCode."\n");
  168. throw new BackupException("Failed to execute mysqldump. Return code: $iRetCode. Check the log file '".realpath(APPROOT.'/log/setup.log')."' for more information.");
  169. }
  170. }
  171. /**
  172. * Helper to create a ZIP out of a data file and the configuration file
  173. */
  174. protected function DoZip($sDataFile, $sConfigFile, $sZipArchiveFile)
  175. {
  176. if (!is_file($sConfigFile))
  177. {
  178. throw new BackupException("Configuration file '$sConfigFile' does not exist or could not be read");
  179. }
  180. // Make sure the target path exists
  181. $sZipDir = dirname($sZipArchiveFile);
  182. SetupUtils::builddir($sZipDir);
  183. $oZip = new ZipArchive();
  184. $res = $oZip->open($sZipArchiveFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
  185. if ($res === TRUE)
  186. {
  187. $oZip->addFile($sDataFile, 'itop-dump.sql');
  188. $oZip->addFile($sConfigFile, 'config-itop.php');
  189. if ($oZip->close())
  190. {
  191. SetupPage::log("Info - Archive: $sZipArchiveFile created");
  192. }
  193. else
  194. {
  195. SetupPage::log("Error - Failed to save zip archive: $sZipArchiveFile");
  196. throw new BackupException("Failed to save zip archive: $sZipArchiveFile");
  197. }
  198. }
  199. else
  200. {
  201. SetupPage::log("Error - Failed to create zip archive: $sZipArchiveFile.");
  202. throw new BackupException("Failed to create zip archive: $sZipArchiveFile.");
  203. }
  204. }
  205. /**
  206. * Helper to download the file directly from the browser
  207. */
  208. public function DownloadBackup($sFile)
  209. {
  210. $oP = new ajax_page('backup');
  211. $oP->SetContentType("multipart/x-zip");
  212. $oP->SetContentDisposition('inline', basename($sFile));
  213. $oP->add(file_get_contents($sFile));
  214. $oP->output();
  215. }
  216. /**
  217. * Helper to open a Database connection
  218. */
  219. protected function DBConnect()
  220. {
  221. if (is_null($this->iDBPort))
  222. {
  223. $oMysqli = new mysqli($this->sDBHost, $this->sDBUser, $this->sDBPwd);
  224. }
  225. else
  226. {
  227. $oMysqli = new mysqli($this->sDBHost, $this->sDBUser, $this->sDBPwd, '', $this->iDBPort);
  228. }
  229. if ($oMysqli->connect_errno)
  230. {
  231. $sHost = is_null($this->iDBPort) ? $this->sDBHost : $this->sDBHost.' on port '.$this->iDBPort;
  232. throw new BackupException("Cannot connect to the MySQL server '$this->sDBHost' (".$oMysqli->connect_errno . ") ".$oMysqli->connect_error);
  233. }
  234. if (!$oMysqli->select_db($this->sDBName))
  235. {
  236. throw new BackupException("The database '$this->sDBName' does not seem to exist");
  237. }
  238. return $oMysqli;
  239. }
  240. /**
  241. * Helper to enumerate the tables of the database
  242. */
  243. protected function EnumerateTables()
  244. {
  245. $oMysqli = $this->DBConnect();
  246. if ($this->sDBSubName != '')
  247. {
  248. $oResult = $oMysqli->query("SHOW TABLES LIKE '{$this->sDBSubName}%'");
  249. }
  250. else
  251. {
  252. $oResult = $oMysqli->query("SHOW TABLES");
  253. }
  254. if (!$oResult)
  255. {
  256. throw new BackupException("Failed to execute the SHOW TABLES query: ".$oMysqli->error);
  257. }
  258. $aTables = array();
  259. while ($aRow = $oResult->fetch_row())
  260. {
  261. $aTables[] = $aRow[0];
  262. }
  263. return $aTables;
  264. }
  265. }
  266. ?>