setuputils.class.inc.php 44 KB

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