setuputils.class.inc.php 49 KB

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