backup.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. /**
  19. * Handles adding directories into a Zip archive
  20. */
  21. class ZipArchiveEx extends ZipArchive
  22. {
  23. public function addDir($sDir, $sZipDir = '')
  24. {
  25. if (is_dir($sDir))
  26. {
  27. if ($dh = opendir($sDir))
  28. {
  29. // Add the directory
  30. if (!empty($sZipDir)) $this->addEmptyDir($sZipDir);
  31. // Loop through all the files
  32. while (($sFile = readdir($dh)) !== false)
  33. {
  34. // If it's a folder, run the function again!
  35. if (!is_file($sDir.$sFile))
  36. {
  37. // Skip parent and root directories
  38. if (($sFile !== ".") && ($sFile !== ".."))
  39. {
  40. $this->addDir($sDir.$sFile."/", $sZipDir.$sFile."/");
  41. }
  42. }
  43. else
  44. {
  45. // Add the files
  46. $this->addFile($sDir.$sFile, $sZipDir.$sFile);
  47. }
  48. }
  49. }
  50. }
  51. }
  52. /**
  53. * Extract a whole directory from the archive.
  54. * Usage: $oZip->extractDirTo('/var/www/html/itop/data', '/production-modules/')
  55. * @param string $sDestinationDir
  56. * @param string $sZipDir Must start and end with a slash !!
  57. * @return boolean
  58. */
  59. public function extractDirTo($sDestinationDir, $sZipDir)
  60. {
  61. $aFiles = array();
  62. for($i = 0; $i < $this->numFiles; $i++)
  63. {
  64. $sEntry = $this->getNameIndex($i);
  65. //Use strpos() to check if the entry name contains the directory we want to extract
  66. if (strpos($sEntry, $sZipDir) === 0)
  67. {
  68. //Add the entry to our array if it in in our desired directory
  69. $aFiles[] = $sEntry;
  70. }
  71. }
  72. // Extract only the selcted files
  73. if ((count($aFiles) > 0) && ($this->extractTo($sDestinationDir, $aFiles) === true))
  74. {
  75. return true;
  76. }
  77. return false;
  78. }
  79. } // class ZipArchiveEx
  80. class BackupException extends Exception
  81. {
  82. }
  83. class DBBackup
  84. {
  85. // To be overriden depending on the expected usages
  86. protected function LogInfo($sMsg)
  87. {
  88. }
  89. protected function LogError($sMsg)
  90. {
  91. }
  92. protected $sDBHost;
  93. protected $iDBPort;
  94. protected $sDBUser;
  95. protected $sDBPwd;
  96. protected $sDBName;
  97. protected $sDBSubName;
  98. /**
  99. * Connects to the database to backup
  100. * By default, connects to the current MetaModel (must be loaded)
  101. *
  102. * @param sDBHost string Database host server
  103. * @param $sDBUser string User login
  104. * @param $sDBPwd string User password
  105. * @param $sDBName string Database name
  106. * @param $sDBSubName string Prefix to the tables of itop in the database
  107. */
  108. public function __construct($sDBHost = null, $sDBUser = null, $sDBPwd = null, $sDBName = null, $sDBSubName = null)
  109. {
  110. if (is_null($sDBHost))
  111. {
  112. // Defaulting to the current config
  113. $sDBHost = MetaModel::GetConfig()->GetDBHost();
  114. $sDBUser = MetaModel::GetConfig()->GetDBUser();
  115. $sDBPwd = MetaModel::GetConfig()->GetDBPwd();
  116. $sDBName = MetaModel::GetConfig()->GetDBName();
  117. $sDBSubName = MetaModel::GetConfig()->GetDBSubName();
  118. }
  119. // Compute the port (if present in the host name)
  120. $aConnectInfo = explode(':', $sDBHost);
  121. $sDBHostName = $aConnectInfo[0];
  122. if (count($aConnectInfo) > 1)
  123. {
  124. $iDBPort = $aConnectInfo[1];
  125. }
  126. else
  127. {
  128. $iDBPort = null;
  129. }
  130. $this->sDBHost = $sDBHostName;
  131. $this->iDBPort = $iDBPort;
  132. $this->sDBUser = $sDBUser;
  133. $this->sDBPwd = $sDBPwd;
  134. $this->sDBName = $sDBName;
  135. $this->sDBSubName = $sDBSubName;
  136. }
  137. protected $sMySQLBinDir = '';
  138. /**
  139. * Create a normalized backup name, depending on the current date/time and Database
  140. * @param sNameSpec string Name and path, eventually containing itop placeholders + time formatting specs
  141. */
  142. public function SetMySQLBinDir($sMySQLBinDir)
  143. {
  144. $this->sMySQLBinDir = $sMySQLBinDir;
  145. }
  146. /**
  147. * Create a normalized backup name, depending on the current date/time and Database
  148. * @param sNameSpec string Name and path, eventually containing itop placeholders + time formatting specs
  149. */
  150. public function MakeName($sNameSpec = "__DB__-%Y-%m-%d")
  151. {
  152. $sFileName = $sNameSpec;
  153. $sFileName = str_replace('__HOST__', $this->sDBHost, $sFileName);
  154. $sFileName = str_replace('__DB__', $this->sDBName, $sFileName);
  155. $sFileName = str_replace('__SUBNAME__', $this->sDBSubName, $sFileName);
  156. // Transform %Y, etc.
  157. $sFileName = strftime($sFileName);
  158. return $sFileName;
  159. }
  160. public function CreateZip($sZipFile, $sSourceConfigFile = null)
  161. {
  162. // Note: the file is created by tempnam and might not be writeable by another process (Windows/IIS)
  163. // (delete it before spawning a process)
  164. $sDataFile = tempnam(SetupUtils::GetTmpDir(), 'itop-');
  165. $this->LogInfo("Data file: '$sDataFile'");
  166. $aContents = array();
  167. $aContents[] = array(
  168. 'source' => $sDataFile,
  169. 'dest' => 'itop-dump.sql',
  170. );
  171. if (is_null($sSourceConfigFile))
  172. {
  173. $sSourceConfigFile = MetaModel::GetConfig()->GetLoadedFile();
  174. }
  175. if (!empty($sSourceConfigFile))
  176. {
  177. $aContents[] = array(
  178. 'source' => $sSourceConfigFile,
  179. 'dest' => 'config-itop.php',
  180. );
  181. }
  182. $this->DoBackup($sDataFile);
  183. $sDeltaFile = APPROOT.'data/'.utils::GetCurrentEnvironment().'.delta.xml';
  184. if (file_exists($sDeltaFile))
  185. {
  186. $aContents[] = array(
  187. 'source' => $sDeltaFile,
  188. 'dest' => 'delta.xml',
  189. );
  190. }
  191. $sExtraDir = APPROOT.'data/'.utils::GetCurrentEnvironment().'-modules/';
  192. if (is_dir($sExtraDir))
  193. {
  194. $aContents[] = array(
  195. 'source' => $sExtraDir,
  196. 'dest' => utils::GetCurrentEnvironment().'-modules/',
  197. );
  198. }
  199. $this->DoZip($aContents, $sZipFile);
  200. // Windows/IIS: the data file has been created by the spawned process...
  201. // trying to delete it will issue a warning, itself stopping the setup abruptely
  202. @unlink($sDataFile);
  203. }
  204. protected static function EscapeShellArg($sValue)
  205. {
  206. // Note: See comment from the 23-Apr-2004 03:30 in the PHP documentation
  207. // It suggests to rely on pctnl_* function instead of using escapeshellargs
  208. return escapeshellarg($sValue);
  209. }
  210. /**
  211. * Create a backup file
  212. */
  213. public function DoBackup($sBackupFileName)
  214. {
  215. $sHost = self::EscapeShellArg($this->sDBHost);
  216. $sUser = self::EscapeShellArg($this->sDBUser);
  217. $sPwd = self::EscapeShellArg($this->sDBPwd);
  218. $sDBName = self::EscapeShellArg($this->sDBName);
  219. // Just to check the connection to the DB (better than getting the retcode of mysqldump = 1)
  220. $oMysqli = $this->DBConnect();
  221. $sTables = '';
  222. if ($this->sDBSubName != '')
  223. {
  224. // This instance of iTop uses a prefix for the tables, so there may be other tables in the database
  225. // Let's explicitely list all the tables and views to dump
  226. $aTables = $this->EnumerateTables();
  227. if (count($aTables) == 0)
  228. {
  229. // No table has been found with the given prefix
  230. throw new BackupException("No table has been found with the given prefix");
  231. }
  232. $aEscapedTables = array();
  233. foreach($aTables as $sTable)
  234. {
  235. $aEscapedTables[] = self::EscapeShellArg($sTable);
  236. }
  237. $sTables = implode(' ', $aEscapedTables);
  238. }
  239. $this->LogInfo("Starting backup of $this->sDBHost/$this->sDBName(suffix:'$this->sDBSubName')");
  240. $sMySQLBinDir = utils::ReadParam('mysql_bindir', $this->sMySQLBinDir, true);
  241. if (empty($sMySQLBinDir))
  242. {
  243. $sMySQLDump = 'mysqldump';
  244. }
  245. else
  246. {
  247. $sMySQLDump = '"'.$sMySQLBinDir.'/mysqldump"';
  248. }
  249. // Store the results in a temporary file
  250. $sTmpFileName = self::EscapeShellArg($sBackupFileName);
  251. if (is_null($this->iDBPort))
  252. {
  253. $sPortOption = '';
  254. }
  255. else
  256. {
  257. $sPortOption = '--port='.$this->iDBPort.' ';
  258. }
  259. // Delete the file created by tempnam() so that the spawned process can write into it (Windows/IIS)
  260. unlink($sBackupFileName);
  261. $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";
  262. $sCommandDisplay = "$sMySQLDump --opt --default-character-set=utf8 --add-drop-database --single-transaction --host=$sHost $sPortOption --user=xxxxx --password=xxxxx --result-file=$sTmpFileName $sDBName $sTables";
  263. // Now run the command for real
  264. $this->LogInfo("Executing command: $sCommandDisplay");
  265. $aOutput = array();
  266. $iRetCode = 0;
  267. exec($sCommand, $aOutput, $iRetCode);
  268. foreach($aOutput as $sLine)
  269. {
  270. $this->LogInfo("mysqldump said: $sLine");
  271. }
  272. if ($iRetCode != 0)
  273. {
  274. $this->LogError("Failed to execute: $sCommandDisplay. The command returned:$iRetCode");
  275. foreach($aOutput as $sLine)
  276. {
  277. $this->LogError("mysqldump said: $sLine");
  278. }
  279. if (count($aOutput) == 1)
  280. {
  281. $sMoreInfo = trim($aOutput[0]);
  282. }
  283. else
  284. {
  285. $sMoreInfo = "Check the log files '".realpath(APPROOT.'/log/setup.log or error.log')."' for more information.";
  286. }
  287. throw new BackupException("Failed to execute mysqldump: ".$sMoreInfo);
  288. }
  289. }
  290. /**
  291. * Helper to create a ZIP out of a data file and the configuration file
  292. */
  293. protected function DoZip($aFiles, $sZipArchiveFile)
  294. {
  295. foreach ($aFiles as $aFile)
  296. {
  297. $sFile = $aFile['source'];
  298. if (!is_file($sFile) && !is_dir($sFile))
  299. {
  300. throw new BackupException("File '$sFile' does not exist or could not be read");
  301. }
  302. }
  303. // Make sure the target path exists
  304. $sZipDir = dirname($sZipArchiveFile);
  305. SetupUtils::builddir($sZipDir);
  306. $oZip = new ZipArchiveEx();
  307. $res = $oZip->open($sZipArchiveFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
  308. if ($res === TRUE)
  309. {
  310. foreach ($aFiles as $aFile)
  311. {
  312. if (is_dir($aFile['source']))
  313. {
  314. $oZip->addDir($aFile['source'], $aFile['dest']);
  315. }
  316. else
  317. {
  318. $oZip->addFile($aFile['source'], $aFile['dest']);
  319. }
  320. }
  321. if ($oZip->close())
  322. {
  323. $this->LogInfo("Archive: $sZipArchiveFile created");
  324. }
  325. else
  326. {
  327. $this->LogError("Failed to save zip archive: $sZipArchiveFile");
  328. throw new BackupException("Failed to save zip archive: $sZipArchiveFile");
  329. }
  330. }
  331. else
  332. {
  333. $this->LogError("Failed to create zip archive: $sZipArchiveFile.");
  334. throw new BackupException("Failed to create zip archive: $sZipArchiveFile.");
  335. }
  336. }
  337. /**
  338. * Helper to download the file directly from the browser
  339. */
  340. public function DownloadBackup($sFile)
  341. {
  342. $oP = new ajax_page('backup');
  343. $oP->SetContentType("multipart/x-zip");
  344. $oP->SetContentDisposition('inline', basename($sFile));
  345. $oP->add(file_get_contents($sFile));
  346. $oP->output();
  347. }
  348. /**
  349. * Helper to open a Database connection
  350. */
  351. protected function DBConnect()
  352. {
  353. if (is_null($this->iDBPort))
  354. {
  355. $oMysqli = new mysqli($this->sDBHost, $this->sDBUser, $this->sDBPwd);
  356. }
  357. else
  358. {
  359. $oMysqli = new mysqli($this->sDBHost, $this->sDBUser, $this->sDBPwd, '', $this->iDBPort);
  360. }
  361. if ($oMysqli->connect_errno)
  362. {
  363. $sHost = is_null($this->iDBPort) ? $this->sDBHost : $this->sDBHost.' on port '.$this->iDBPort;
  364. throw new BackupException("Cannot connect to the MySQL server '$this->sDBHost' (".$oMysqli->connect_errno . ") ".$oMysqli->connect_error);
  365. }
  366. if (!$oMysqli->select_db($this->sDBName))
  367. {
  368. throw new BackupException("The database '$this->sDBName' does not seem to exist");
  369. }
  370. return $oMysqli;
  371. }
  372. /**
  373. * Helper to enumerate the tables of the database
  374. */
  375. protected function EnumerateTables()
  376. {
  377. $oMysqli = $this->DBConnect();
  378. if ($this->sDBSubName != '')
  379. {
  380. $oResult = $oMysqli->query("SHOW TABLES LIKE '{$this->sDBSubName}%'");
  381. }
  382. else
  383. {
  384. $oResult = $oMysqli->query("SHOW TABLES");
  385. }
  386. if (!$oResult)
  387. {
  388. throw new BackupException("Failed to execute the SHOW TABLES query: ".$oMysqli->error);
  389. }
  390. $aTables = array();
  391. while ($aRow = $oResult->fetch_row())
  392. {
  393. $aTables[] = $aRow[0];
  394. }
  395. return $aTables;
  396. }
  397. }
  398. ?>