setuputils.class.inc.php 51 KB

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