setuputils.class.inc.php 43 KB

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