archive.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Utility to import/export the DB from/to a ZIP file
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. /**
  25. * iTopArchive a class to manipulate (read/write) iTop archives with their catalog
  26. * Each iTop archive is a zip file that contains (at the root of the archive)
  27. * a file called catalog.xml holding the description of the archive
  28. */
  29. class iTopArchive
  30. {
  31. const read = 0;
  32. const create = ZipArchive::CREATE;
  33. protected $m_sZipPath;
  34. protected $m_oZip;
  35. protected $m_sVersion;
  36. protected $m_sTitle;
  37. protected $m_sDescription;
  38. protected $m_aPackages;
  39. protected $m_aErrorMessages;
  40. /**
  41. * Construct an iTopArchive object
  42. * @param $sArchivePath string The full path the archive file
  43. * @param $iMode integrer Either iTopArchive::read for reading an existing archive or iTopArchive::create for creating a new one. Updating is not supported (yet)
  44. */
  45. public function __construct($sArchivePath, $iMode = iTopArchive::read)
  46. {
  47. $this->m_sZipPath = $sArchivePath;
  48. $this->m_oZip = new ZipArchive();
  49. $this->m_oZip->open($this->m_sZipPath, $iMode);
  50. $this->m_aErrorMessages = array();
  51. $this->m_sVersion = '1.0';
  52. $this->m_sTitle = '';
  53. $this->m_sDescription = '';
  54. $this->m_aPackages = array();
  55. }
  56. public function SetTitle($sTitle)
  57. {
  58. $this->m_sTitle = $sTitle;
  59. }
  60. public function SetDescription($sDescription)
  61. {
  62. $this->m_sDescription = $sDescription;
  63. }
  64. public function GetTitle()
  65. {
  66. return $this->m_sTitle;
  67. }
  68. public function GetDescription()
  69. {
  70. return $this->m_sDescription;
  71. }
  72. public function GetPackages()
  73. {
  74. return $this->m_aPackages;
  75. }
  76. public function __destruct()
  77. {
  78. $this->m_oZip->close();
  79. }
  80. /**
  81. * Get the error message explaining the latest error encountered
  82. * @return array All the error messages encountered during the validation
  83. */
  84. public function GetErrors()
  85. {
  86. return $this->m_aErrorMessages;
  87. }
  88. /**
  89. * Read the catalog from the archive (zip) file
  90. * @param sPath string Path the the zip file
  91. * @return boolean True in case of success, false otherwise
  92. */
  93. public function ReadCatalog()
  94. {
  95. if ($this->IsValid())
  96. {
  97. $sXmlCatalog = $this->m_oZip->getFromName('catalog.xml');
  98. $oParser = xml_parser_create();
  99. xml_parse_into_struct($oParser, $sXmlCatalog, $aValues, $aIndexes);
  100. xml_parser_free($oParser);
  101. $iIndex = $aIndexes['ARCHIVE'][0];
  102. $this->m_sVersion = $aValues[$iIndex]['attributes']['VERSION'];
  103. $iIndex = $aIndexes['TITLE'][0];
  104. $this->m_sTitle = $aValues[$iIndex]['value'];
  105. $iIndex = $aIndexes['DESCRIPTION'][0];
  106. if (array_key_exists('value', $aValues[$iIndex]))
  107. {
  108. // #@# implement a get_array_value(array, key, default) ?
  109. $this->m_sDescription = $aValues[$iIndex]['value'];
  110. }
  111. foreach($aIndexes['PACKAGE'] as $iIndex)
  112. {
  113. $this->m_aPackages[$aValues[$iIndex]['attributes']['HREF']] = array( 'type' => $aValues[$iIndex]['attributes']['TYPE'], 'title'=> $aValues[$iIndex]['attributes']['TITLE'], 'description' => $aValues[$iIndex]['value']);
  114. }
  115. //echo "Archive path: {$this->m_sZipPath}<br/>\n";
  116. //echo "Archive format version: {$this->m_sVersion}<br/>\n";
  117. //echo "Title: {$this->m_sTitle}<br/>\n";
  118. //echo "Description: {$this->m_sDescription}<br/>\n";
  119. //foreach($this->m_aPackages as $aFile)
  120. //{
  121. // echo "{$aFile['title']} ({$aFile['type']}): {$aFile['description']}<br/>\n";
  122. //}
  123. }
  124. return true;
  125. }
  126. public function WriteCatalog()
  127. {
  128. $sXml = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?".">\n"; // split the XML closing tag that disturbs PSPad's syntax coloring
  129. $sXml .= "<archive version=\"1.0\">\n";
  130. $sXml .= "<title>{$this->m_sTitle}</title>\n";
  131. $sXml .= "<description>{$this->m_sDescription}</description>\n";
  132. foreach($this->m_aPackages as $sFileName => $aFile)
  133. {
  134. $sXml .= "<package title=\"{$aFile['title']}\" type=\"{$aFile['type']}\" href=\"$sFileName\">{$aFile['description']}</package>\n";
  135. }
  136. $sXml .= "</archive>";
  137. $this->m_oZip->addFromString('catalog.xml', $sXml);
  138. }
  139. /**
  140. * Add a package to the archive
  141. * @param string $sExternalFilePath The path to the file to be added to the archive as a package (directories are not yet implemented)
  142. * @param string $sFilePath The name of the file inside the archive
  143. * @param string $sTitle A short title for this package
  144. * @param string $sType Type of the package. SQL scripts must be of type 'text/sql'
  145. * @param string $sDescription A longer description of the purpose of this package
  146. * @return none
  147. */
  148. public function AddPackage($sExternalFilePath, $sFilePath, $sTitle, $sType, $sDescription)
  149. {
  150. $this->m_aPackages[$sFilePath] = array('title' => $sTitle, 'type' => $sType, 'description' => $sDescription);
  151. $this->m_oZip->addFile($sExternalFilePath, $sFilePath);
  152. }
  153. /**
  154. * Reads the contents of the given file from the archive
  155. * @param string $sFileName The path to the file inside the archive
  156. * @return string The content of the file read from the archive
  157. */
  158. public function GetFileContents($sFileName)
  159. {
  160. return $this->m_oZip->getFromName($sFileName);
  161. }
  162. /**
  163. * Extracts the contents of the given file from the archive
  164. * @param string $sFileName The path to the file inside the archive
  165. * @param string $sDestinationFileName The path of the file to write
  166. * @return none
  167. */
  168. public function ExtractToFile($sFileName, $sDestinationFileName)
  169. {
  170. $iBufferSize = 64 * 1024; // Read 64K at a time
  171. $oZipStream = $this->m_oZip->getStream($sFileName);
  172. $oDestinationStream = fopen($sDestinationFileName, 'wb');
  173. while (!feof($oZipStream)) {
  174. $sContents = fread($oZipStream, $iBufferSize);
  175. fwrite($oDestinationStream, $sContents);
  176. }
  177. fclose($oZipStream);
  178. fclose($oDestinationStream);
  179. }
  180. /**
  181. * Apply a SQL script taken from the archive. The package must be listed in the catalog and of type text/sql
  182. * @param string $sFileName The path to the SQL package inside the archive
  183. * @return boolean false in case of error, true otherwise
  184. */
  185. public function ImportSql($sFileName, $sDatabase = 'itop')
  186. {
  187. if ( ($this->m_oZip->locateName($sFileName) == false) || (!isset($this->m_aPackages[$sFileName])) || ($this->m_aPackages[$sFileName]['type'] != 'text/sql'))
  188. {
  189. // invalid type or not listed in the catalog
  190. return false;
  191. }
  192. $sTempName = tempnam("../tmp/", "sql");
  193. //echo "Extracting to: '$sTempName'<br/>\n";
  194. $this->ExtractToFile($sFileName, $sTempName);
  195. // Note: the command line below works on Windows with the right path to mysql !!!
  196. $sCommandLine = 'type "'.$sTempName.'" | "/iTop/MySQL Server 5.0/bin/mysql.exe" -u root '.$sDatabase;
  197. //echo "Executing: '$sCommandLine'<br/>\n";
  198. exec($sCommandLine, $aOutput, $iRet);
  199. //echo "Return code: $iRet<br/>\n";
  200. //echo "Output:<br/><pre>\n";
  201. //print_r($aOutput);
  202. //echo "</pre><br/>\n";
  203. unlink($sTempName);
  204. return ($iRet == 0);
  205. }
  206. /**
  207. * Dumps some part of the specified MySQL database into the archive as a text/sql package
  208. * @param $sTitle string A short title for this SQL script
  209. * @param $sDescription string A longer description of the purpose of this SQL script
  210. * @param $sFileName string The name of the package inside the archive
  211. * @param $sDatabase string name of the database
  212. * @param $aTables array array or table names. If empty, all tables are dumped
  213. * @param $bStructureOnly boolean Whether or not to dump the data or just the schema
  214. * @return boolean False in case of error, true otherwise
  215. */
  216. public function AddDatabaseDump($sTitle, $sDescription, $sFileName, $sDatabase = 'itop', $aTables = array(), $bStructureOnly = true)
  217. {
  218. $sTempName = tempnam("../tmp/", "sql");
  219. $sNoData = $bStructureOnly ? "--no-data" : "";
  220. $sCommandLine = "\"/iTop/MySQL Server 5.0/bin/mysqldump.exe\" --user=root --opt $sNoData --result-file=$sTempName $sDatabase ".implode(" ", $aTables);
  221. //echo "Executing command: '$sCommandLine'<br/>\n";
  222. exec($sCommandLine, $aOutput, $iRet);
  223. //echo "Return code: $iRet<br/>\n";
  224. //echo "Output:<br/><pre>\n";
  225. //print_r($aOutput);
  226. //echo "</pre><br/>\n";
  227. if ($iRet == 0)
  228. {
  229. $this->AddPackage($sTempName, $sFileName, $sTitle, 'text/sql', $sDescription);
  230. }
  231. //unlink($sTempName);
  232. return ($iRet == 0);
  233. }
  234. /**
  235. * Check the consistency of the archive
  236. * @return boolean True if the archive file is consistent
  237. */
  238. public function IsValid()
  239. {
  240. // TO DO: use a DTD to validate the XML instead of this hand-made validation
  241. $bResult = true;
  242. $aMandatoryTags = array('ARCHIVE' => array('VERSION'),
  243. 'TITLE' => array(),
  244. 'DESCRIPTION' => array(),
  245. 'PACKAGE' => array('TYPE', 'HREF', 'TITLE'));
  246. $sXmlCatalog = $this->m_oZip->getFromName('catalog.xml');
  247. $oParser = xml_parser_create();
  248. xml_parse_into_struct($oParser, $sXmlCatalog, $aValues, $aIndexes);
  249. xml_parser_free($oParser);
  250. foreach($aMandatoryTags as $sTag => $aAttributes)
  251. {
  252. // Check that all the required tags are present
  253. if (!isset($aIndexes[$sTag]))
  254. {
  255. $this->m_aErrorMessages[] = "The XML catalog does not contain the mandatory tag $sTag.";
  256. $bResult = false;
  257. }
  258. else
  259. {
  260. foreach($aIndexes[$sTag] as $iIndex)
  261. {
  262. switch($aValues[$iIndex]['type'])
  263. {
  264. case 'complete':
  265. case 'open':
  266. // Check that all the required attributes are present
  267. foreach($aAttributes as $sAttribute)
  268. {
  269. if (!isset($aValues[$iIndex]['attributes'][$sAttribute]))
  270. {
  271. $this->m_aErrorMessages[] = "The tag $sTag ($iIndex) does not contain the required attribute $sAttribute.";
  272. }
  273. }
  274. break;
  275. default:
  276. // ignore other type of tags: close or cdata
  277. }
  278. }
  279. }
  280. }
  281. return $bResult;
  282. }
  283. }
  284. /*
  285. // Unit test - reading an archive
  286. $sArchivePath = '../tmp/archive.zip';
  287. $oArchive = new iTopArchive($sArchivePath, iTopArchive::read);
  288. $oArchive->ReadCatalog();
  289. $oArchive->ImportSql('full_backup.sql');
  290. // Writing an archive --
  291. $sArchivePath = '../tmp/archive2.zip';
  292. $oArchive = new iTopArchive($sArchivePath, iTopArchive::create);
  293. $oArchive->SetTitle('First Archive !');
  294. $oArchive->SetDescription('This is just a test. Does not contain a lot of useful data.');
  295. $oArchive->AddPackage('../tmp/schema.sql', 'test.sql', 'this is just a test', 'text/sql', 'My first attempt at creating an archive from PHP...');
  296. $oArchive->WriteCatalog();
  297. $sArchivePath = '../tmp/archive2.zip';
  298. $oArchive = new iTopArchive($sArchivePath, iTopArchive::create);
  299. $oArchive->SetTitle('First Archive !');
  300. $oArchive->SetDescription('This is just a test. Does not contain a lot of useful data.');
  301. $oArchive->AddDatabaseDump('Test', 'This is my first automatic dump', 'schema.sql', 'itop', array('objects'));
  302. $oArchive->WriteCatalog();
  303. */
  304. ?>