setuputils.class.inc.php 44 KB

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