setuputils.class.inc.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  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. * The standardized result of any pass/fail check performed by the setup
  20. * @copyright Copyright (C) 2010-2012 Combodo SARL
  21. * @license http://opensource.org/licenses/AGPL-3.0
  22. */
  23. class CheckResult
  24. {
  25. // Severity levels
  26. const ERROR = 0;
  27. const WARNING = 1;
  28. const INFO = 2;
  29. public $iSeverity;
  30. public $sLabel;
  31. public $sDescription;
  32. public function __construct($iSeverity, $sLabel, $sDescription = '')
  33. {
  34. $this->iSeverity = $iSeverity;
  35. $this->sLabel = $sLabel;
  36. $this->sDescription = $sDescription;
  37. }
  38. }
  39. /**
  40. * Namespace for storing all the functions/utilities needed by both
  41. * the setup wizard and the installation process
  42. * @copyright Copyright (C) 2010-2012 Combodo SARL
  43. * @license http://opensource.org/licenses/AGPL-3.0
  44. */
  45. class SetupUtils
  46. {
  47. const PHP_MIN_VERSION = '5.2.0';
  48. const MYSQL_MIN_VERSION = '5.0.0';
  49. const MIN_MEMORY_LIMIT = 33554432; // = 32*1024*1024 Beware: Computations are not allowed in defining constants
  50. const SUHOSIN_GET_MAX_VALUE_LENGTH = 2048;
  51. /**
  52. * Check the version of PHP, the needed PHP extension and a number
  53. * of configuration parameters (memory_limit, max_upload_file_size, etc...)
  54. * @param SetupPage $oP The page used only for its 'log' method
  55. * @return array An array of CheckResults objects
  56. */
  57. static function CheckPHPVersion()
  58. {
  59. $aResult = array();
  60. SetupPage::log('Info - CheckPHPVersion');
  61. if (version_compare(phpversion(), self::PHP_MIN_VERSION, '>='))
  62. {
  63. $aResult[] = new CheckResult(CheckResult::INFO, "The current PHP Version (".phpversion().") is greater than the minimum version required to run ".ITOP_APPLICATION.", which is (".self::PHP_MIN_VERSION.")");
  64. }
  65. else
  66. {
  67. $aResult[] = new CheckResult(CheckResult::ERROR, "Error: The current PHP Version (".phpversion().") is lower than the minimum version required to run ".ITOP_APPLICATION.", which is (".self::PHP_MIN_VERSION.")");
  68. }
  69. $aMandatoryExtensions = array('mysqli', 'iconv', 'simplexml', 'soap', 'hash', 'json', 'session', 'pcre', 'dom');
  70. $aOptionalExtensions = array('mcrypt' => 'Strong encryption will not be used.',
  71. 'ldap' => 'LDAP authentication will be disabled.');
  72. asort($aMandatoryExtensions); // Sort the list to look clean !
  73. ksort($aOptionalExtensions); // Sort the list to look clean !
  74. $aExtensionsOk = array();
  75. $aMissingExtensions = array();
  76. $aMissingExtensionsLinks = array();
  77. // First check the mandatory extensions
  78. foreach($aMandatoryExtensions as $sExtension)
  79. {
  80. if (extension_loaded($sExtension))
  81. {
  82. $aExtensionsOk[] = $sExtension;
  83. }
  84. else
  85. {
  86. $aMissingExtensions[] = $sExtension;
  87. $aMissingExtensionsLinks[] = "<a href=\"http://www.php.net/manual/en/book.$sExtension.php\" target=\"_blank\">$sExtension</a>";
  88. }
  89. }
  90. if (count($aExtensionsOk) > 0)
  91. {
  92. $aResult[] = new CheckResult(CheckResult::INFO, "Required PHP extension(s): ".implode(', ', $aExtensionsOk).".");
  93. }
  94. if (count($aMissingExtensions) > 0)
  95. {
  96. $aResult[] = new CheckResult(CheckResult::ERROR, "Missing PHP extension(s): ".implode(', ', $aMissingExtensionsLinks).".");
  97. }
  98. // Next check the optional extensions
  99. $aExtensionsOk = array();
  100. $aMissingExtensions = array();
  101. foreach($aOptionalExtensions as $sExtension => $sMessage)
  102. {
  103. if (extension_loaded($sExtension))
  104. {
  105. $aExtensionsOk[] = $sExtension;
  106. }
  107. else
  108. {
  109. $aMissingExtensions[$sExtension] = $sMessage;
  110. }
  111. }
  112. if (count($aExtensionsOk) > 0)
  113. {
  114. $aResult[] = new CheckResult(CheckResult::INFO, "Optional PHP extension(s): ".implode(', ', $aExtensionsOk).".");
  115. }
  116. if (count($aMissingExtensions) > 0)
  117. {
  118. foreach($aMissingExtensions as $sExtension => $sMessage)
  119. {
  120. $aResult[] = new CheckResult(CheckResult::WARNING, "Missing optional PHP extension: $sExtension. ".$sMessage);
  121. }
  122. }
  123. // Check some ini settings here
  124. if (function_exists('php_ini_loaded_file')) // PHP >= 5.2.4
  125. {
  126. $sPhpIniFile = php_ini_loaded_file();
  127. // Other included/scanned files
  128. if ($sFileList = php_ini_scanned_files())
  129. {
  130. if (strlen($sFileList) > 0)
  131. {
  132. $aFiles = explode(',', $sFileList);
  133. foreach ($aFiles as $sFile)
  134. {
  135. $sPhpIniFile .= ', '.trim($sFile);
  136. }
  137. }
  138. }
  139. SetupPage::log("Info - php.ini file(s): '$sPhpIniFile'");
  140. }
  141. else
  142. {
  143. $sPhpIniFile = 'php.ini';
  144. }
  145. if (!ini_get('file_uploads'))
  146. {
  147. $aResult[] = new CheckResult(CheckResult::ERROR, "Files upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').").");
  148. }
  149. $sUploadTmpDir = self::GetUploadTmpDir();
  150. if (empty($sUploadTmpDir))
  151. {
  152. $sUploadTmpDir = '/tmp';
  153. $aResult[] = new CheckResult(CheckResult::WARNING, "Temporary directory for files upload is not defined (upload_tmp_dir), assuming that $sUploadTmpDir is used.");
  154. }
  155. // check that the upload directory is indeed writable from PHP
  156. if (!empty($sUploadTmpDir))
  157. {
  158. if (!file_exists($sUploadTmpDir))
  159. {
  160. $aResult[] = new CheckResult(CheckResult::ERROR, "Temporary directory for files upload ($sUploadTmpDir) does not exist or cannot be read by PHP.");
  161. }
  162. else if (!is_writable($sUploadTmpDir))
  163. {
  164. $aResult[] = new CheckResult(CheckResult::ERROR, "Temporary directory for files upload ($sUploadTmpDir) is not writable.");
  165. }
  166. else
  167. {
  168. SetupPage::log("Info - Temporary directory for files upload ($sUploadTmpDir) is writable.");
  169. }
  170. }
  171. if (!ini_get('upload_max_filesize'))
  172. {
  173. $aResult[] = new CheckResult(CheckResult::ERROR, "File upload is not allowed on this server (upload_max_filesize = ".ini_get('upload_max_filesize').").");
  174. }
  175. $iMaxFileUploads = ini_get('max_file_uploads');
  176. if (!empty($iMaxFileUploads) && ($iMaxFileUploads < 1))
  177. {
  178. $aResult[] = new CheckResult(CheckResult::ERROR, "File upload is not allowed on this server (max_file_uploads = ".ini_get('max_file_uploads').").");
  179. }
  180. $iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  181. $iMaxPostSize = utils::ConvertToBytes(ini_get('post_max_size'));
  182. if ($iMaxPostSize <= $iMaxUploadSize)
  183. {
  184. $aResult[] = new CheckResult(CheckResult::WARNING, "post_max_size (".ini_get('post_max_size').") in php.ini should be bigger than upload_max_filesize (".ini_get('upload_max_filesize').") otherwise you cannot upload files of the maximun size.");
  185. }
  186. SetupPage::log("Info - upload_max_filesize: ".ini_get('upload_max_filesize'));
  187. SetupPage::log("Info - post_max_size: ".ini_get('post_max_size'));
  188. SetupPage::log("Info - max_file_uploads: ".ini_get('max_file_uploads'));
  189. // Check some more ini settings here, needed for file upload
  190. if (function_exists('get_magic_quotes_gpc'))
  191. {
  192. if (@get_magic_quotes_gpc())
  193. {
  194. $aResult[] = new CheckResult(CheckResult::ERROR, "'magic_quotes_gpc' is set to On. Please turn it Off in php.ini before continuing.");
  195. }
  196. }
  197. if (function_exists('magic_quotes_runtime'))
  198. {
  199. if (@magic_quotes_runtime())
  200. {
  201. $aResult[] = new CheckResult(CheckResult::ERROR, "'magic_quotes_runtime' is set to On. Please turn it Off in php.ini before continuing.");
  202. }
  203. }
  204. $sMemoryLimit = trim(ini_get('memory_limit'));
  205. if (empty($sMemoryLimit))
  206. {
  207. // On some PHP installations, memory_limit does not exist as a PHP setting!
  208. // (encountered on a 5.2.0 under Windows)
  209. // In that case, ini_set will not work, let's keep track of this and proceed anyway
  210. $aResult[] = new CheckResult(CheckResult::WARNING, "No memory limit has been defined in this instance of PHP");
  211. }
  212. else
  213. {
  214. // Check that the limit will allow us to load the data
  215. //
  216. $iMemoryLimit = utils::ConvertToBytes($sMemoryLimit);
  217. if ($iMemoryLimit < self::MIN_MEMORY_LIMIT)
  218. {
  219. $aResult[] = new CheckResult(CheckResult::ERROR, "memory_limit ($iMemoryLimit) is too small, the minimum value to run the application is ".self::MIN_MEMORY_LIMIT.".");
  220. }
  221. else
  222. {
  223. SetupPage::log("Info - memory_limit is $iMemoryLimit, ok.");
  224. }
  225. }
  226. // Special case for APC
  227. if (extension_loaded('apc'))
  228. {
  229. $sAPCVersion = phpversion('apc');
  230. $aResult[] = new CheckResult(CheckResult::INFO, "APC detected (version $sAPCVersion). The APC cache will be used to speed-up ".ITOP_APPLICATION.".");
  231. }
  232. // Special case Suhosin extension
  233. if (extension_loaded('suhosin'))
  234. {
  235. $sSuhosinVersion = phpversion('suhosin');
  236. $aOk[] = "Suhosin extension detected (version $sSuhosinVersion).";
  237. $iGetMaxValueLength = ini_get('suhosin.get.max_value_length');
  238. if ($iGetMaxValueLength < self::SUHOSIN_GET_MAX_VALUE_LENGTH)
  239. {
  240. $aResult[] = new CheckResult(CheckResult::WARNING, "suhosin.get.max_value_length ($iGetMaxValueLength) is too small, the minimum value recommended to run the application is ".self::SUHOSIN_GET_MAX_VALUE_LENGTH.".");
  241. }
  242. else
  243. {
  244. SetupPage::log("Info - suhosin.get.max_value_length = $iGetMaxValueLength, ok.");
  245. }
  246. }
  247. if (function_exists('php_ini_loaded_file')) // PHP >= 5.2.4
  248. {
  249. $sPhpIniFile = php_ini_loaded_file();
  250. // Other included/scanned files
  251. if ($sFileList = php_ini_scanned_files())
  252. {
  253. if (strlen($sFileList) > 0)
  254. {
  255. $aFiles = explode(',', $sFileList);
  256. foreach ($aFiles as $sFile)
  257. {
  258. $sPhpIniFile .= ', '.trim($sFile);
  259. }
  260. }
  261. }
  262. $aResult[] = new CheckResult(CheckResult::INFO, "Loaded php.ini files: $sPhpIniFile");
  263. }
  264. return $aResult;
  265. }
  266. /**
  267. * Check that the backup could be executed
  268. * @param Page $oP The page used only for its 'log' method
  269. * @return array An array of CheckResults objects
  270. */
  271. static function CheckBackupPrerequisites($sDestDir)
  272. {
  273. $aResult = array();
  274. SetupPage::log('Info - CheckBackupPrerequisites');
  275. // zip extension
  276. //
  277. if (!extension_loaded('zip'))
  278. {
  279. $sMissingExtensionLink = "<a href=\"http://www.php.net/manual/en/book.zip.php\" target=\"_blank\">zip</a>";
  280. $aResult[] = new CheckResult(CheckResult::ERROR, "Missing PHP extension: zip", $sMissingExtensionLink);
  281. }
  282. // availability of exec()
  283. //
  284. $aDisabled = explode(', ', ini_get('disable_functions'));
  285. SetupPage::log('Info - PHP functions disabled: '.implode(', ', $aDisabled));
  286. if (in_array('exec', $aDisabled))
  287. {
  288. $aResult[] = new CheckResult(CheckResult::ERROR, "The PHP exec() function has been disabled on this server");
  289. }
  290. // availability of mysqldump
  291. $sMySQLBinDir = utils::ReadParam('mysql_bindir', '', true);
  292. if (empty($sMySQLBinDir))
  293. {
  294. $sMySQLDump = 'mysqldump';
  295. }
  296. else
  297. {
  298. SetupPage::log('Info - Found mysql_bindir: '.$sMySQLBinDir);
  299. $sMySQLDump = '"'.$sMySQLBinDir.'/mysqldump"';
  300. }
  301. $sCommand = "$sMySQLDump -V 2>&1";
  302. $aOutput = array();
  303. $iRetCode = 0;
  304. exec($sCommand, $aOutput, $iRetCode);
  305. if ($iRetCode == 0)
  306. {
  307. $aResult[] = new CheckResult(CheckResult::INFO, "mysqldump is present: ".$aOutput[0]);
  308. }
  309. elseif ($iRetCode == 1)
  310. {
  311. $aResult[] = new CheckResult(CheckResult::ERROR, "mysqldump could not be found: ".implode(' ', $aOutput)." - Please make sure it is installed and in the path.");
  312. }
  313. else
  314. {
  315. $aResult[] = new CheckResult(CheckResult::ERROR, "mysqldump could not be executed (retcode=$iRetCode): Please make sure it is installed and in the path");
  316. }
  317. foreach($aOutput as $sLine)
  318. {
  319. SetupPage::log('Info - mysqldump -V said: '.$sLine);
  320. }
  321. // check disk space
  322. // to do... evaluate how we can correlate the DB size with the size of the dump (and the zip!)
  323. // E.g. 2,28 Mb after a full install, giving a zip of 26 Kb (data = 26 Kb)
  324. // Example of query (DB without a suffix)
  325. //$sDBSize = "SELECT SUM(ROUND(DATA_LENGTH/1024/1024, 2)) AS size_mb FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = `$sDBName`";
  326. return $aResult;
  327. }
  328. /**
  329. * Helper function to retrieve the system's temporary directory
  330. * Emulates sys_get_temp_dir if neeed (PHP < 5.2.1)
  331. * @return string Path to the system's temp directory
  332. */
  333. static function GetTmpDir()
  334. {
  335. // try to figure out what is the temporary directory
  336. // prior to PHP 5.2.1 the function sys_get_temp_dir
  337. // did not exist
  338. if ( !function_exists('sys_get_temp_dir'))
  339. {
  340. if( $temp=getenv('TMP') ) return realpath($temp);
  341. if( $temp=getenv('TEMP') ) return realpath($temp);
  342. if( $temp=getenv('TMPDIR') ) return realpath($temp);
  343. $temp=tempnam(__FILE__,'');
  344. if (file_exists($temp))
  345. {
  346. unlink($temp);
  347. return realpath(dirname($temp));
  348. }
  349. return null;
  350. }
  351. else
  352. {
  353. return realpath(sys_get_temp_dir());
  354. }
  355. }
  356. /**
  357. * Helper function to retrieve the directory where files are to be uploaded
  358. * @return string Path to the temp directory used for uploading files
  359. */
  360. static function GetUploadTmpDir()
  361. {
  362. $sPath = ini_get('upload_tmp_dir');
  363. if (empty($sPath))
  364. {
  365. $sPath = self::GetTmpDir();
  366. }
  367. return $sPath;
  368. }
  369. /**
  370. * Helper to recursively remove a directory
  371. */
  372. public static function rrmdir($dir)
  373. {
  374. if ((strlen(trim($dir)) == 0) || ($dir == '/') || ($dir == '\\'))
  375. {
  376. throw new Exception("Attempting to delete directory: '$dir'");
  377. }
  378. self::tidydir($dir);
  379. rmdir($dir);
  380. }
  381. /**
  382. * Helper to recursively cleanup a directory
  383. */
  384. public static function tidydir($dir)
  385. {
  386. if ((strlen(trim($dir)) == 0) || ($dir == '/') || ($dir == '\\'))
  387. {
  388. throw new Exception("Attempting to delete directory: '$dir'");
  389. }
  390. foreach(glob($dir . '/*') as $file)
  391. {
  392. if(is_dir($file))
  393. {
  394. self::tidydir($file);
  395. rmdir($file);
  396. }
  397. else
  398. {
  399. unlink($file);
  400. }
  401. }
  402. }
  403. /**
  404. * Helper to build the full path of a new directory
  405. */
  406. public static function builddir($dir)
  407. {
  408. $parent = dirname($dir);
  409. if(!is_dir($parent))
  410. {
  411. self::builddir($parent);
  412. }
  413. if (!is_dir($dir))
  414. {
  415. mkdir($dir);
  416. }
  417. }
  418. /**
  419. * Helper to copy a directory to a target directory, skipping .SVN files (for developer's comfort!)
  420. * Returns true if successfull
  421. */
  422. public static function copydir($sSource, $sDest, $bUseSymbolicLinks = false)
  423. {
  424. if (is_dir($sSource))
  425. {
  426. if (!is_dir($sDest))
  427. {
  428. mkdir($sDest);
  429. }
  430. $aFiles = scandir($sSource);
  431. if(sizeof($aFiles) > 0 )
  432. {
  433. foreach($aFiles as $sFile)
  434. {
  435. if ($sFile == '.' || $sFile == '..' || $sFile == '.svn')
  436. {
  437. // Skip
  438. continue;
  439. }
  440. if (is_dir($sSource.'/'.$sFile))
  441. {
  442. // Recurse
  443. self::copydir($sSource.'/'.$sFile, $sDest.'/'.$sFile, $bUseSymbolicLinks);
  444. }
  445. else
  446. {
  447. if ($bUseSymbolicLinks)
  448. {
  449. if (function_exists('symlink'))
  450. {
  451. symlink($sSource.'/'.$sFile, $sDest.'/'.$sFile);
  452. }
  453. else
  454. {
  455. throw(new Exception("Error, cannot *copy* '$sSource/$sFile' to '$sDest/$sFile' using symbolic links, 'symlink' is not supported on this system."));
  456. }
  457. }
  458. else
  459. {
  460. copy($sSource.'/'.$sFile, $sDest.'/'.$sFile);
  461. }
  462. }
  463. }
  464. }
  465. return true;
  466. }
  467. elseif (is_file($sSource))
  468. {
  469. if ($bUseSymbolicLinks)
  470. {
  471. if (function_exists('symlink'))
  472. {
  473. return symlink($sSource, $sDest);
  474. }
  475. else
  476. {
  477. throw(new Exception("Error, cannot *copy* '$sSource' to '$sDest' using symbolic links, 'symlink' is not supported on this system."));
  478. }
  479. }
  480. else
  481. {
  482. return copy($sSource, $sDest);
  483. }
  484. }
  485. else
  486. {
  487. return false;
  488. }
  489. }
  490. static function GetPreviousInstance($sDir)
  491. {
  492. $bFound = false;
  493. $sSourceDir = '';
  494. $sSourceEnvironement = '';
  495. $sConfigFile = '';
  496. $aResult = array(
  497. 'found' => false,
  498. );
  499. if (file_exists($sDir.'/config-itop.php'))
  500. {
  501. $sSourceDir = $sDir;
  502. $sSourceEnvironment = '';
  503. $sConfigFile = $sDir.'/config-itop.php';
  504. $aResult['found'] = true;
  505. }
  506. else if (file_exists($sDir.'/conf/production/config-itop.php'))
  507. {
  508. $sSourceDir = $sDir;
  509. $sSourceEnvironment = 'production';
  510. $sConfigFile = $sDir.'/conf/production/config-itop.php';
  511. $aResult['found'] = true;
  512. }
  513. if ($aResult['found'])
  514. {
  515. $oPrevConf = new Config($sConfigFile);
  516. $aResult = array(
  517. 'found' => true,
  518. 'source_dir' => $sSourceDir,
  519. 'source_environment' => $sSourceEnvironment,
  520. 'configuration_file' => $sConfigFile,
  521. 'db_server' => $oPrevConf->GetDBHost(),
  522. 'db_user' => $oPrevConf->GetDBUser(),
  523. 'db_pwd' => $oPrevConf->GetDBPwd(),
  524. 'db_name' => $oPrevConf->GetDBName(),
  525. 'db_prefix' => $oPrevConf->GetDBSubname(),
  526. );
  527. }
  528. return $aResult;
  529. }
  530. static function CheckDiskSpace($sDir)
  531. {
  532. while(($f = @disk_free_space($sDir)) == false)
  533. {
  534. if ($sDir == dirname($sDir)) break;
  535. if ($sDir == '.') break;
  536. $sDir = dirname($sDir);
  537. }
  538. return $f;
  539. }
  540. static function HumanReadableSize($fBytes)
  541. {
  542. $aSizes = array('bytes', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Hb');
  543. $index = 0;
  544. while (($fBytes > 1000) && ($index < count($aSizes)))
  545. {
  546. $index++;
  547. $fBytes = $fBytes / 1000;
  548. }
  549. return sprintf('%.2f %s', $fBytes, $aSizes[$index]);
  550. }
  551. static function DisplayDBParameters($oPage, $bAllowDBCreation, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sNewDBName = '')
  552. {
  553. $oPage->add('<tr><td colspan="2">');
  554. $oPage->add('<fieldset><legend>Database Server Connection</legend>');
  555. $oPage->add('<table>');
  556. $oPage->add('<tr><td>Server Name:</td><td><input id="db_server" type="text" name="db_server" value="'.htmlentities($sDBServer, ENT_QUOTES, 'UTF-8').'" size="15"/></td><td>E.g. "localhost", "dbserver.mycompany.com" or "192.142.10.23"</td></tr>');
  557. $oPage->add('<tr><td>Login:</td><td><input id="db_user" type="text" name="db_user" value="'.htmlentities($sDBUser, ENT_QUOTES, 'UTF-8').'" size="15"/></td><td rowspan="2" style="vertical-align:top">The account must have the following privileges on the database: SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, CREATE VIEW, SUPER, TRIGGER</td></tr>');
  558. $oPage->add('<tr><td>Password:</td><td><input id="db_pwd" type="password" name="db_pwd" value="'.htmlentities($sDBPwd, ENT_QUOTES, 'UTF-8').'" size="15"/></td></tr>');
  559. $oPage->add('</table>');
  560. $oPage->add('</fieldset>');
  561. $oPage->add('</td></tr>');
  562. $oPage->add('<tr><td colspan="2"><span id="db_info"></span></td></tr>');
  563. $oPage->add('<tr><td colspan="2">');
  564. $oPage->add('<fieldset><legend>Database</legend>');
  565. $oPage->add('<table>');
  566. if ($bAllowDBCreation)
  567. {
  568. $oPage->add('<tr><td><input type="radio" id="create_db" name="create_db" value="yes"/><label for="create_db">&nbsp;Create a new database:</label></td>');
  569. $oPage->add('<td><input id="db_new_name" type="text" name="db_new_name" value="'.htmlentities($sNewDBName, ENT_QUOTES, 'UTF-8').'" size="15" maxlength="32"/><span style="width:20px;" id="v_db_new_name"></span></td></tr>');
  570. $oPage->add('<tr><td><input type="radio" id="existing_db" name="create_db" value="no"/><label for="existing_db">&nbsp;Use the existing database:</label></td>');
  571. $oPage->add('<td id="db_name_container"><input id="db_name" name="db_name" size="15" maxlen="32" value="'.htmlentities($sDBName, ENT_QUOTES, 'UTF-8').'"/><span style="width:20px;" id="v_db_name"></span></td></tr>');
  572. $oPage->add('<tr><td>Use a prefix for the tables:</td><td><input id="db_prefix" type="text" name="db_prefix" value="'.htmlentities($sDBPrefix, ENT_QUOTES, 'UTF-8').'" size="15" maxlength="32"/><span style="width:20px;" id="v_db_prefix"></span></td></tr>');
  573. }
  574. else
  575. {
  576. $oPage->add('<tr><td>Database Name:</td><td id="db_name_container"><input id="db_name" name="db_name" size="15" maxlen="32" value="'.htmlentities($sDBName, ENT_QUOTES, 'UTF-8').'"/><span style="width:20px;" id="v_db_name"></span></td></tr>');
  577. $oPage->add('<tr><td>Use a prefix for the tables:</td><td><input id="db_prefix" type="text" name="db_prefix" value="'.htmlentities($sDBPrefix, ENT_QUOTES, 'UTF-8').'" size="15"/><span style="width:20px;" id="v_db_prefix"></span></td></tr>');
  578. }
  579. $oPage->add('</table>');
  580. $oPage->add('</fieldset>');
  581. $oPage->add('<tr><td colspan="2"><span id="table_info">&nbsp;</span></td></tr>');
  582. $oPage->add('</td></tr>');
  583. $oPage->add_script(
  584. <<<EOF
  585. var iCheckDBTimer = null;
  586. var oXHRCheckDB = null;
  587. function CheckDBConnection()
  588. {
  589. // Don't call the server too often...
  590. if (iCheckDBTimer !== null)
  591. {
  592. clearTimeout(iCheckDBTimer);
  593. iCheckDBTimer = null;
  594. }
  595. iCheckDBTimer = setTimeout(DoCheckDBConnection, 500);
  596. }
  597. function DoCheckDBConnection()
  598. {
  599. iCheckDBTimer = null;
  600. var oParams = {
  601. 'db_server': $("#db_server").val(),
  602. 'db_user': $("#db_user").val(),
  603. 'db_pwd': $("#db_pwd").val(),
  604. 'db_name': $("#db_name").val()
  605. }
  606. if ((oXHRCheckDB != null) && (oXHRCheckDB != undefined))
  607. {
  608. oXHRCheckDB.abort();
  609. oXHRCheckDB = null;
  610. }
  611. oXHRCheckDB = WizardAsyncAction("check_db", oParams);
  612. }
  613. function ValidateField(sFieldId, bUsed)
  614. {
  615. var sValue = new String($("#"+sFieldId).val());
  616. var bMandatory = false;
  617. if (bUsed)
  618. {
  619. if (sFieldId == 'db_name')
  620. {
  621. bUsed = ($("#existing_db").attr("checked") == "checked");
  622. bMandatory = true;
  623. }
  624. if (sFieldId == 'db_new_name')
  625. {
  626. bUsed = ($("#create_db").attr("checked") == "checked");
  627. bMandatory = true;
  628. }
  629. }
  630. if (!bUsed)
  631. {
  632. $("#v_"+sFieldId).html("");
  633. return true;
  634. }
  635. else
  636. {
  637. if (sValue != "")
  638. {
  639. if (sValue.match(/^[A-Za-z][A-Za-z0-9_]*$/))
  640. {
  641. var bCollision = false;
  642. if (sFieldId == 'db_new_name')
  643. {
  644. // check that the "new name" does not correspond to an existing database
  645. var sNewName = $('#db_new_name').val();
  646. $('#db_name option').each( function() {
  647. if ($(this).attr('value') == sNewName)
  648. {
  649. bCollision = true;
  650. }
  651. });
  652. }
  653. if (bCollision)
  654. {
  655. $("#v_"+sFieldId).html('<img src="../images/validation_error.png" title="A database with the same name already exists"/>');
  656. return false;
  657. }
  658. else
  659. {
  660. $("#v_"+sFieldId).html("");
  661. return true;
  662. }
  663. }
  664. else
  665. {
  666. $("#v_"+sFieldId).html('<img src="../images/validation_error.png" title="Only the characters [A-Za-z0-9_] are allowed"/>');
  667. return false;
  668. }
  669. }
  670. else if (bMandatory)
  671. {
  672. $("#v_"+sFieldId).html('<img src="../images/validation_error.png" title="This field cannot be empty"/>');
  673. return false;
  674. }
  675. else
  676. {
  677. $("#v_"+sFieldId).html("");
  678. return true;
  679. }
  680. }
  681. }
  682. EOF
  683. );
  684. $oPage->add_ready_script(
  685. <<<EOF
  686. DoCheckDBConnection(); // Validate the initial values immediately
  687. $("#db_server").bind("keyup change", function() { CheckDBConnection(); });
  688. $("#db_user").bind("keyup change", function() { CheckDBConnection(); });
  689. $("#db_pwd").bind("keyup change", function() { CheckDBConnection(); });
  690. $("#db_new_name").bind("click keyup change", function() { $("#create_db").attr("checked", "checked"); WizardUpdateButtons(); });
  691. $("#db_name").bind("click keyup change", function() { $("#existing_db").attr("checked", "checked"); WizardUpdateButtons(); });
  692. $("#db_prefix").bind("keyup change", function() { WizardUpdateButtons(); });
  693. $("#existing_db").bind("click change", function() { WizardUpdateButtons(); });
  694. $("#create_db").bind("click change", function() { WizardUpdateButtons(); });
  695. EOF
  696. );
  697. }
  698. /**
  699. * Helper function check the connection to the database, verify a few conditions (minimum version, etc...) and (if connected)
  700. * enumerate the existing databases (if possible)
  701. * @return mixed false if the connection failed or array('checks' => Array of CheckResult, 'databases' => Array of database names (as strings) or null if not allowed)
  702. */
  703. static function CheckServerConnection($sDBServer, $sDBUser, $sDBPwd)
  704. {
  705. $aResult = array('checks' => array(), 'databases' => null);
  706. try
  707. {
  708. $oDBSource = new CMDBSource;
  709. $oDBSource->Init($sDBServer, $sDBUser, $sDBPwd);
  710. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Connection to '$sDBServer' as '$sDBUser' successful.");
  711. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Info - User privileges: ".($oDBSource->GetRawPrivileges()));
  712. $sDBVersion = $oDBSource->GetDBVersion();
  713. if (version_compare($sDBVersion, self::MYSQL_MIN_VERSION, '>='))
  714. {
  715. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Current MySQL version ($sDBVersion), greater than minimum required version (".self::MYSQL_MIN_VERSION.")");
  716. // Check some server variables
  717. $iMaxAllowedPacket = $oDBSource->GetServerVariable('max_allowed_packet');
  718. $iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  719. if ($iMaxAllowedPacket >= (500 + $iMaxUploadSize)) // Allow some space for the query + the file to upload
  720. {
  721. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "MySQL server's max_allowed_packet ($iMaxAllowedPacket) is big enough compared to upload_max_filesize ($iMaxUploadSize).");
  722. }
  723. else if($iMaxAllowedPacket < $iMaxUploadSize)
  724. {
  725. $aResult['checks'][] = new CheckResult(CheckResult::WARNING, "MySQL server's max_allowed_packet ($iMaxAllowedPacket) is not big enough. Please, consider setting it to at least ".(500 + $iMaxUploadSize).".");
  726. }
  727. $iMaxConnections = $oDBSource->GetServerVariable('max_connections');
  728. if ($iMaxConnections < 5)
  729. {
  730. $aResult['checks'][] = new CheckResult(CheckResult::WARNING, "MySQL server's max_connections ($iMaxConnections) is not enough. Please, consider setting it to at least 5.");
  731. }
  732. else
  733. {
  734. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "MySQL server's max_connections is set to $iMaxConnections.");
  735. }
  736. }
  737. else
  738. {
  739. $aResult['checks'][] = new CheckResult(CheckResult::ERROR, "Error: Current MySQL version is ($sDBVersion), minimum required version (".self::MYSQL_MIN_VERSION.")");
  740. }
  741. try
  742. {
  743. $aResult['databases'] = $oDBSource->ListDB();
  744. }
  745. catch(Exception $e)
  746. {
  747. $aResult['databases'] = null;
  748. }
  749. }
  750. catch(Exception $e)
  751. {
  752. return false;
  753. }
  754. return $aResult;
  755. }
  756. static public function AsyncCheckDB($oPage, $aParameters)
  757. {
  758. $sDBServer = $aParameters['db_server'];
  759. $sDBUser = $aParameters['db_user'];
  760. $sDBPwd = $aParameters['db_pwd'];
  761. $sDBName = $aParameters['db_name'];
  762. $oPage->add_ready_script('oXHRCheckDB = null;');
  763. $checks = SetupUtils::CheckServerConnection($sDBServer, $sDBUser, $sDBPwd);
  764. if ($checks === false)
  765. {
  766. // Connection failed, disable the "Next" button
  767. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "error");');
  768. $oPage->add_ready_script('$("#db_info").html("No connection to the database...");');
  769. }
  770. else
  771. {
  772. $aErrors = array();
  773. $aWarnings = array();
  774. foreach($checks['checks'] as $oCheck)
  775. {
  776. if ($oCheck->iSeverity == CheckResult::ERROR)
  777. {
  778. $aErrors[] = $oCheck->sLabel;
  779. }
  780. else if ($oCheck->iSeverity == CheckResult::WARNING)
  781. {
  782. $aWarnings[] = $oCheck->sLabel;
  783. }
  784. }
  785. if (count($aErrors) > 0)
  786. {
  787. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "error");');
  788. $oPage->add_ready_script('$("#db_info").html(\'<img src="../images/validation_error.png"/>&nbsp;<b>Error:</b> '.htmlentities(implode('<br/>', $aErrors), ENT_QUOTES, 'UTF-8').'\');');
  789. }
  790. else if (count($aWarnings) > 0)
  791. {
  792. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "");');
  793. $oPage->add_ready_script('$("#db_info").html(\'<img src="../images/error.png"/>&nbsp;<b>Warning:</b> '.htmlentities(implode('<br/>', $aWarnings), ENT_QUOTES, 'UTF-8').'\');');
  794. }
  795. else
  796. {
  797. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "");');
  798. $oPage->add_ready_script('$("#db_info").html(\'<img src="../images/validation_ok.png"/>&nbsp;Database server connection Ok.\');');
  799. }
  800. if ($checks['databases'] == null)
  801. {
  802. $sDBNameInput = '<input id="db_name" name="db_name" size="15" maxlen="32" value="'.htmlentities($sDBName, ENT_QUOTES, 'UTF-8').'"/><span style="width:20px;" id="v_db_name"></span>';
  803. $oPage->add_ready_script('$("#table_info").html(\'<img src="../images/error.png"/>&nbsp;Not enough rights to enumerate the databases\');');
  804. }
  805. else
  806. {
  807. $sDBNameInput = '<select id="db_name" name="db_name">';
  808. foreach($checks['databases'] as $sDatabaseName)
  809. {
  810. if ($sDatabaseName != 'information_schema')
  811. {
  812. $sEncodedName = htmlentities($sDatabaseName, ENT_QUOTES, 'UTF-8');
  813. $sSelected = ($sDatabaseName == $sDBName) ? ' selected ' : '';
  814. $sDBNameInput .= '<option value="'.$sEncodedName.'"'.$sSelected.'>'.$sEncodedName.'</option>';
  815. }
  816. }
  817. $sDBNameInput .= '</select>';
  818. }
  819. $oPage->add_ready_script('$("#db_name_container").html("'.addslashes($sDBNameInput).'");');
  820. $oPage->add_ready_script('$("#db_name").bind("click keyup change", function() { $("#existing_db").attr("checked", "checked"); WizardUpdateButtons(); });');
  821. }
  822. $oPage->add_ready_script('WizardUpdateButtons();');
  823. }
  824. /**
  825. * Helper function to get the available languages from the given directory
  826. * @param $sDir Path to the dictionary
  827. * @return an array of language code => description
  828. */
  829. static public function GetAvailableLanguages($sDir)
  830. {
  831. require_once(APPROOT.'/core/coreexception.class.inc.php');
  832. require_once(APPROOT.'/core/dict.class.inc.php');
  833. $aFiles = scandir($sDir);
  834. foreach($aFiles as $sFile)
  835. {
  836. if ($sFile == '.' || $sFile == '..' || $sFile == '.svn')
  837. {
  838. // Skip
  839. continue;
  840. }
  841. $sFilePath = $sDir.'/'.$sFile;
  842. if (is_file($sFilePath) && preg_match('/^.+\.dict.*\.php$/i', $sFilePath, $aMatches))
  843. {
  844. require_once($sFilePath);
  845. }
  846. }
  847. return Dict::GetLanguages();
  848. }
  849. static public function GetLanguageSelect($sSourceDir, $sInputName, $sDefaultLanguageCode)
  850. {
  851. $sHtml = '<select id="'.$sInputName.'" name="'.$sInputName.'">';
  852. $sSourceDir = APPROOT.'dictionaries/';
  853. $aLanguages = SetupUtils::GetAvailableLanguages($sSourceDir);
  854. foreach($aLanguages as $sCode => $aInfo)
  855. {
  856. $sSelected = ($sCode == $sDefaultLanguageCode) ? ' selected ' : '';
  857. $sHtml .= '<option value="'.$sCode.'"'.$sSelected.'>'.htmlentities($aInfo['description'], ENT_QUOTES, 'UTF-8').' ('.htmlentities($aInfo['localized_description'], ENT_QUOTES, 'UTF-8').')</option>';
  858. }
  859. $sHtml .= '</select></td></tr>';
  860. return $sHtml;
  861. }
  862. public static function AnalyzeInstallation($oWizard)
  863. {
  864. require_once(APPROOT.'/setup/moduleinstaller.class.inc.php');
  865. $oConfig = new Config();
  866. $sSourceDir = $oWizard->GetParameter('source_dir', '');
  867. if (strpos($sSourceDir, APPROOT) !== false)
  868. {
  869. $sRelativeSourceDir = str_replace(APPROOT, '', $sSourceDir);
  870. }
  871. else if (strpos($sSourceDir, $oWizard->GetParameter('previous_version_dir')) !== false)
  872. {
  873. $sRelativeSourceDir = str_replace($oWizard->GetParameter('previous_version_dir'), '', $sSourceDir);
  874. }
  875. else
  876. {
  877. throw(new Exception('Internal error: AnalyzeInstallation: source_dir is neither under APPROOT nor under previous_installation_dir ???'));
  878. }
  879. $aParamValues = array(
  880. 'db_server' => $oWizard->GetParameter('db_server', ''),
  881. 'db_user' => $oWizard->GetParameter('db_user', ''),
  882. 'db_pwd' => $oWizard->GetParameter('db_pwd', ''),
  883. 'db_name' => $oWizard->GetParameter('db_name', ''),
  884. 'db_prefix' => $oWizard->GetParameter('db_prefix', ''),
  885. 'source_dir' => $sRelativeSourceDir,
  886. );
  887. $oConfig->UpdateFromParams($aParamValues, null);
  888. $aDirsToScan = array($sSourceDir);
  889. if (is_dir(APPROOT.'extensions'))
  890. {
  891. $aDirsToScan[] = APPROOT.'extensions';
  892. }
  893. if (is_dir($oWizard->GetParameter('copy_extensions_from')))
  894. {
  895. $aDirsToScan[] = $oWizard->GetParameter('copy_extensions_from');
  896. }
  897. $oProductionEnv = new RunTimeEnvironment();
  898. $aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, $aDirsToScan);
  899. return $aAvailableModules;
  900. }
  901. public static function GetApplicationVersion($oWizard)
  902. {
  903. require_once(APPROOT.'/setup/moduleinstaller.class.inc.php');
  904. $oConfig = new Config();
  905. $aParamValues = array(
  906. 'db_server' => $oWizard->GetParameter('db_server', ''),
  907. 'db_user' => $oWizard->GetParameter('db_user', ''),
  908. 'db_pwd' => $oWizard->GetParameter('db_pwd', ''),
  909. 'db_name' => $oWizard->GetParameter('db_name', ''),
  910. 'db_prefix' => $oWizard->GetParameter('db_prefix', ''),
  911. 'source_dir' => '',
  912. );
  913. $oConfig->UpdateFromParams($aParamValues, null);
  914. $oProductionEnv = new RunTimeEnvironment();
  915. return $oProductionEnv->GetApplicationVersion($oConfig);
  916. }
  917. /**
  918. * Checks if the content of a directory matches the given manifest
  919. * @param string $sBaseDir Path to the root directory of iTop
  920. * @param string $sSourceDir Relative path to the directory to check under $sBaseDir
  921. * @param Array $aDOMManifest Array of array('path' => relative_path 'size'=> iSize, 'md5' => sHexMD5)
  922. * @param Hash $aResult Used for recursion
  923. * @return hash Hash array ('added' => array(), 'removed' => array(), 'modified' => array())
  924. */
  925. public static function CheckDirAgainstManifest($sBaseDir, $sSourceDir, $aManifest, $aExcludeNames = array('.svn'), $aResult = null)
  926. {
  927. //echo "CheckDirAgainstManifest($sBaseDir, $sSourceDir ...)\n";
  928. if ($aResult === null)
  929. {
  930. $aResult = array('added' => array(), 'removed' => array(), 'modified' => array());
  931. }
  932. if (substr($sSourceDir, 0, 1) == '/')
  933. {
  934. $sSourceDir = substr($sSourceDir, 1);
  935. }
  936. // Manifest limited to all the files supposed to be located in this directory
  937. $aDirManifest = array();
  938. foreach($aManifest as $aFileInfo)
  939. {
  940. $sDir = dirname($aFileInfo['path']);
  941. if ($sDir == '.')
  942. {
  943. // Hmm... the file seems located at the root of iTop
  944. $sDir = '';
  945. }
  946. if ($sDir == $sSourceDir)
  947. {
  948. $aDirManifest[basename($aFileInfo['path'])] = $aFileInfo;
  949. }
  950. }
  951. //echo "The manifest contains ".count($aDirManifest)." files for the directory '$sSourceDir' (and below)\n";
  952. // Read the content of the directory
  953. foreach(glob($sBaseDir.'/'.$sSourceDir .'/*') as $sFilePath)
  954. {
  955. $sFile = basename($sFilePath);
  956. //echo "Checking $sFile ($sFilePath)\n";
  957. if (in_array(basename($sFile), $aExcludeNames)) continue;
  958. if(is_dir($sFilePath))
  959. {
  960. $aResult = self::CheckDirAgainstManifest($sBaseDir, $sSourceDir.'/'.$sFile, $aManifest, $aExcludeNames, $aResult);
  961. }
  962. else
  963. {
  964. if (!array_key_exists($sFile, $aDirManifest))
  965. {
  966. //echo "New file ".$sFile." in $sSourceDir\n";
  967. $aResult['added'][$sSourceDir.'/'.$sFile] = true;
  968. }
  969. else
  970. {
  971. $aStats = stat($sFilePath);
  972. if ($aStats['size'] != $aDirManifest[$sFile]['size'])
  973. {
  974. // Different sizes
  975. $aResult['modified'][$sSourceDir.'/'.$sFile] = 'Different sizes. Original size: '.$aDirManifest[$sFile]['size'].' bytes, actual file size on disk: '.$aStats['size'].' bytes.';
  976. }
  977. else
  978. {
  979. // Same size, compare the md5 signature
  980. $sMD5 = md5_file($sFilePath);
  981. if ($sMD5 != $aDirManifest[$sFile]['md5'])
  982. {
  983. $aResult['modified'][$sSourceDir.'/'.$sFile] = 'Content modified (MD5 checksums differ).';
  984. //echo $sSourceDir.'/'.$sFile." modified ($sMD5 == {$aDirManifest[$sFile]['md5']})\n";
  985. }
  986. //else
  987. //{
  988. // echo $sSourceDir.'/'.$sFile." unmodified ($sMD5 == {$aDirManifest[$sFile]['md5']})\n";
  989. //}
  990. }
  991. //echo "Removing ".$sFile." from aDirManifest\n";
  992. unset($aDirManifest[$sFile]);
  993. }
  994. }
  995. }
  996. // What remains in the array are files that were deleted
  997. foreach($aDirManifest as $sDeletedFile => $void)
  998. {
  999. $aResult['removed'][$sSourceDir.'/'.$sDeletedFile] = true;
  1000. }
  1001. return $aResult;
  1002. }
  1003. public static function CheckDataModelFiles($sManifestFile, $sBaseDir)
  1004. {
  1005. $oXML = simplexml_load_file($sManifestFile);
  1006. $aManifest = array();
  1007. foreach($oXML as $oFileInfo)
  1008. {
  1009. $aManifest[] = array('path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5);
  1010. }
  1011. $sBaseDir = preg_replace('|modules/?$|', '', $sBaseDir);
  1012. $aResults = self::CheckDirAgainstManifest($sBaseDir, 'modules', $aManifest);
  1013. // echo "<pre>Comparison of ".dirname($sBaseDir)."/modules against $sManifestFile:\n".print_r($aResults, true)."</pre>";
  1014. return $aResults;
  1015. }
  1016. public static function CheckPortalFiles($sManifestFile, $sBaseDir)
  1017. {
  1018. $oXML = simplexml_load_file($sManifestFile);
  1019. $aManifest = array();
  1020. foreach($oXML as $oFileInfo)
  1021. {
  1022. $aManifest[] = array('path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5);
  1023. }
  1024. $aResults = self::CheckDirAgainstManifest($sBaseDir, 'portal', $aManifest);
  1025. // echo "<pre>Comparison of ".dirname($sBaseDir)."/portal:\n".print_r($aResults, true)."</pre>";
  1026. return $aResults;
  1027. }
  1028. public static function CheckApplicationFiles($sManifestFile, $sBaseDir)
  1029. {
  1030. $oXML = simplexml_load_file($sManifestFile);
  1031. $aManifest = array();
  1032. foreach($oXML as $oFileInfo)
  1033. {
  1034. $aManifest[] = array('path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5);
  1035. }
  1036. $aResults = array('added' => array(), 'removed' => array(), 'modified' => array());
  1037. foreach(array('addons', 'core', 'dictionaries', 'js', 'application', 'css', 'pages', 'synchro', 'webservices') as $sDir)
  1038. {
  1039. $aTmp = self::CheckDirAgainstManifest($sBaseDir, $sDir, $aManifest);
  1040. $aResults['added'] = array_merge($aResults['added'], $aTmp['added']);
  1041. $aResults['modified'] = array_merge($aResults['modified'], $aTmp['modified']);
  1042. $aResults['removed'] = array_merge($aResults['removed'], $aTmp['removed']);
  1043. }
  1044. // echo "<pre>Comparison of ".dirname($sBaseDir)."/portal:\n".print_r($aResults, true)."</pre>";
  1045. return $aResults;
  1046. }
  1047. public static function CheckVersion($sInstalledVersion, $sSourceDir)
  1048. {
  1049. $sManifestFilePath = self::GetVersionManifest($sInstalledVersion);
  1050. if ($sSourceDir != '')
  1051. {
  1052. if (file_exists($sManifestFilePath))
  1053. {
  1054. $aDMchanges = self::CheckDataModelFiles($sManifestFilePath, $sSourceDir);
  1055. //$aPortalChanges = self::CheckPortalFiles($sManifestFilePath, $sSourceDir);
  1056. //$aCodeChanges = self::CheckApplicationFiles($sManifestFilePath, $sSourceDir);
  1057. //echo("Changes detected compared to $sInstalledVersion:<br/>DataModel:<br/><pre>".print_r($aDMchanges, true)."</pre>");
  1058. //echo("Changes detected compared to $sInstalledVersion:<br/>DataModel:<br/><pre>".print_r($aDMchanges, true)."</pre><br/>Portal:<br/><pre>".print_r($aPortalChanges, true)."</pre><br/>Code:<br/><pre>".print_r($aCodeChanges, true)."</pre>");
  1059. return $aDMchanges;
  1060. }
  1061. else
  1062. {
  1063. return false;
  1064. }
  1065. }
  1066. else
  1067. {
  1068. throw(new Exception("Cannot check version '$sInstalledVersion', no source directory provided to check the files."));
  1069. }
  1070. }
  1071. public static function GetVersionManifest($sInstalledVersion)
  1072. {
  1073. if (preg_match('/^([0-9]+)\./', $sInstalledVersion, $aMatches))
  1074. {
  1075. return APPROOT.'datamodels/'.$aMatches[1].'.x/manifest-'.$sInstalledVersion.'.xml';
  1076. }
  1077. return false;
  1078. }
  1079. public static function CheckWritableDirs($aWritableDirs)
  1080. {
  1081. $aNonWritableDirs = array();
  1082. foreach($aWritableDirs as $sDir)
  1083. {
  1084. $sFullPath = APPROOT.$sDir;
  1085. if (is_dir($sFullPath) && !is_writable($sFullPath))
  1086. {
  1087. $aNonWritableDirs[APPROOT.$sDir] = new CheckResult(CheckResult::ERROR, "The directory '".APPROOT.$sDir."' exists but is not writable for the application.");
  1088. }
  1089. else if (file_exists($sFullPath) && !is_dir($sFullPath))
  1090. {
  1091. $aNonWritableDirs[APPROOT.$sDir] = new CheckResult(CheckResult::ERROR, "A file with the same name as '".APPROOT.$sDir."' exists.");
  1092. }
  1093. else if (!is_dir($sFullPath) && !is_writable(APPROOT))
  1094. {
  1095. $aNonWritableDirs[APPROOT] = new CheckResult(CheckResult::ERROR, "The directory '".APPROOT."' is not writable, the application cannot create the directory '$sDir' inside it.");
  1096. }
  1097. }
  1098. return $aNonWritableDirs;
  1099. }
  1100. public static function GetLatestDataModelDir()
  1101. {
  1102. $sBaseDir = APPROOT.'datamodels';
  1103. $aDirs = glob($sBaseDir.'/*', GLOB_MARK | GLOB_ONLYDIR);
  1104. if ($aDirs !== false)
  1105. {
  1106. sort($aDirs);
  1107. return array_pop($aDirs);
  1108. }
  1109. return false;
  1110. }
  1111. public static function GetCompatibleDataModelDir($sInstalledVersion)
  1112. {
  1113. if (preg_match('/^([0-9]+)\./', $sInstalledVersion, $aMatches))
  1114. {
  1115. $sMajorVersion = $aMatches[1];
  1116. $sDir = APPROOT.'datamodels/'.$sMajorVersion.'.x/';
  1117. if (is_dir($sDir))
  1118. {
  1119. return $sDir;
  1120. }
  1121. }
  1122. return false;
  1123. }
  1124. static public function GetDataModelVersion($sDatamodelDir)
  1125. {
  1126. $sVersionFile = $sDatamodelDir.'version.xml';
  1127. if (file_exists($sVersionFile))
  1128. {
  1129. $oParams = new XMLParameters($sVersionFile);
  1130. return $oParams->Get('version');
  1131. }
  1132. return false;
  1133. }
  1134. }