setuputils.class.inc.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. <?php
  2. // Copyright (C) 2012 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * The standardized result of any pass/fail check performed by the setup
  18. * @author Erwan Taloc <erwan.taloc@combodo.com>
  19. * @author Romain Quetiez <romain.quetiez@combodo.com>
  20. * @author Denis Flaven <denis.flaven@combodo.com>
  21. * @license http://www.opensource.org/licenses/gpl-3.0.html GPL
  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. * @author Erwan Taloc <erwan.taloc@combodo.com>
  43. * @author Romain Quetiez <romain.quetiez@combodo.com>
  44. * @author Denis Flaven <denis.flaven@combodo.com>
  45. * @license http://www.opensource.org/licenses/gpl-3.0.html GPL
  46. */
  47. class SetupUtils
  48. {
  49. const PHP_MIN_VERSION = '5.2.0';
  50. const MYSQL_MIN_VERSION = '5.0.0';
  51. const MIN_MEMORY_LIMIT = 33554432; // = 32*1024*1024 Beware: Computations are not allowed in defining constants
  52. const SUHOSIN_GET_MAX_VALUE_LENGTH = 2048;
  53. /**
  54. * Check the version of PHP, the needed PHP extension and a number
  55. * of configuration parameters (memory_limit, max_upload_file_size, etc...)
  56. * @param SetupPage $oP The page used only for its 'log' method
  57. * @return array An array of CheckResults objects
  58. */
  59. static function CheckPHPVersion()
  60. {
  61. $aResult = array();
  62. SetupPage::log('Info - CheckPHPVersion');
  63. if (version_compare(phpversion(), self::PHP_MIN_VERSION, '>='))
  64. {
  65. $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.")");
  66. }
  67. else
  68. {
  69. $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.")");
  70. }
  71. $aMandatoryExtensions = array('mysqli', 'iconv', 'simplexml', 'soap', 'hash', 'json', 'session', 'pcre', 'dom');
  72. $aOptionalExtensions = array('mcrypt' => 'Strong encryption will not be used.',
  73. 'ldap' => 'LDAP authentication will be disabled.');
  74. asort($aMandatoryExtensions); // Sort the list to look clean !
  75. ksort($aOptionalExtensions); // Sort the list to look clean !
  76. $aExtensionsOk = array();
  77. $aMissingExtensions = array();
  78. $aMissingExtensionsLinks = array();
  79. // First check the mandatory extensions
  80. foreach($aMandatoryExtensions as $sExtension)
  81. {
  82. if (extension_loaded($sExtension))
  83. {
  84. $aExtensionsOk[] = $sExtension;
  85. }
  86. else
  87. {
  88. $aMissingExtensions[] = $sExtension;
  89. $aMissingExtensionsLinks[] = "<a href=\"http://www.php.net/manual/en/book.$sExtension.php\" target=\"_blank\">$sExtension</a>";
  90. }
  91. }
  92. if (count($aExtensionsOk) > 0)
  93. {
  94. $aResult[] = new CheckResult(CheckResult::INFO, "Required PHP extension(s): ".implode(', ', $aExtensionsOk).".");
  95. }
  96. if (count($aMissingExtensions) > 0)
  97. {
  98. $aResult[] = new CheckResult(CheckResult::ERROR, "Missing PHP extension(s): ".implode(', ', $aMissingExtensionsLinks).".");
  99. }
  100. // Next check the optional extensions
  101. $aExtensionsOk = array();
  102. $aMissingExtensions = array();
  103. foreach($aOptionalExtensions as $sExtension => $sMessage)
  104. {
  105. if (extension_loaded($sExtension))
  106. {
  107. $aExtensionsOk[] = $sExtension;
  108. }
  109. else
  110. {
  111. $aMissingExtensions[$sExtension] = $sMessage;
  112. }
  113. }
  114. if (count($aExtensionsOk) > 0)
  115. {
  116. $aResult[] = new CheckResult(CheckResult::INFO, "Optional PHP extension(s): ".implode(', ', $aExtensionsOk).".");
  117. }
  118. if (count($aMissingExtensions) > 0)
  119. {
  120. foreach($aMissingExtensions as $sExtension => $sMessage)
  121. {
  122. $aResult[] = new CheckResult(CheckResult::WARNING, "Missing optional PHP extension: $sExtension. ".$sMessage);
  123. }
  124. }
  125. // Check some ini settings here
  126. if (function_exists('php_ini_loaded_file')) // PHP >= 5.2.4
  127. {
  128. $sPhpIniFile = php_ini_loaded_file();
  129. // Other included/scanned files
  130. if ($sFileList = php_ini_scanned_files())
  131. {
  132. if (strlen($sFileList) > 0)
  133. {
  134. $aFiles = explode(',', $sFileList);
  135. foreach ($aFiles as $sFile)
  136. {
  137. $sPhpIniFile .= ', '.trim($sFile);
  138. }
  139. }
  140. }
  141. SetupPage::log("Info - php.ini file(s): '$sPhpIniFile'");
  142. }
  143. else
  144. {
  145. $sPhpIniFile = 'php.ini';
  146. }
  147. if (!ini_get('file_uploads'))
  148. {
  149. $aResult[] = new CheckResult(CheckResult::ERROR, "Files upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').").");
  150. }
  151. $sUploadTmpDir = self::GetUploadTmpDir();
  152. if (empty($sUploadTmpDir))
  153. {
  154. $sUploadTmpDir = '/tmp';
  155. $aResult[] = new CheckResult(CheckResult::WARNING, "Temporary directory for files upload is not defined (upload_tmp_dir), assuming that $sUploadTmpDir is used.");
  156. }
  157. // check that the upload directory is indeed writable from PHP
  158. if (!empty($sUploadTmpDir))
  159. {
  160. if (!file_exists($sUploadTmpDir))
  161. {
  162. $aResult[] = new CheckResult(CheckResult::ERROR, "Temporary directory for files upload ($sUploadTmpDir) does not exist or cannot be read by PHP.");
  163. }
  164. else if (!is_writable($sUploadTmpDir))
  165. {
  166. $aResult[] = new CheckResult(CheckResult::ERROR, "Temporary directory for files upload ($sUploadTmpDir) is not writable.");
  167. }
  168. else
  169. {
  170. SetupPage::log("Info - Temporary directory for files upload ($sUploadTmpDir) is writable.");
  171. }
  172. }
  173. if (!ini_get('upload_max_filesize'))
  174. {
  175. $aResult[] = new CheckResult(CheckResult::ERROR, "File upload is not allowed on this server (upload_max_filesize = ".ini_get('upload_max_filesize').").");
  176. }
  177. $iMaxFileUploads = ini_get('max_file_uploads');
  178. if (!empty($iMaxFileUploads) && ($iMaxFileUploads < 1))
  179. {
  180. $aResult[] = new CheckResult(CheckResult::ERROR, "File upload is not allowed on this server (max_file_uploads = ".ini_get('max_file_uploads').").");
  181. }
  182. $iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  183. $iMaxPostSize = utils::ConvertToBytes(ini_get('post_max_size'));
  184. if ($iMaxPostSize <= $iMaxUploadSize)
  185. {
  186. $aResult[] = new CheckResult(CheckResult::WARNING, "post_max_size (".ini_get('post_max_size').") in php.ini should be bigger than upload_max_filesize (".ini_get('upload_max_filesize').") otherwise you cannot upload files of the maximun size.");
  187. }
  188. SetupPage::log("Info - upload_max_filesize: ".ini_get('upload_max_filesize'));
  189. SetupPage::log("Info - post_max_size: ".ini_get('post_max_size'));
  190. SetupPage::log("Info - max_file_uploads: ".ini_get('max_file_uploads'));
  191. // Check some more ini settings here, needed for file upload
  192. if (function_exists('get_magic_quotes_gpc'))
  193. {
  194. if (@get_magic_quotes_gpc())
  195. {
  196. $aResult[] = new CheckResult(CheckResult::ERROR, "'magic_quotes_gpc' is set to On. Please turn it Off in php.ini before continuing.");
  197. }
  198. }
  199. if (function_exists('magic_quotes_runtime'))
  200. {
  201. if (@magic_quotes_runtime())
  202. {
  203. $aResult[] = new CheckResult(CheckResult::ERROR, "'magic_quotes_runtime' is set to On. Please turn it Off in php.ini before continuing.");
  204. }
  205. }
  206. $sMemoryLimit = trim(ini_get('memory_limit'));
  207. if (empty($sMemoryLimit))
  208. {
  209. // On some PHP installations, memory_limit does not exist as a PHP setting!
  210. // (encountered on a 5.2.0 under Windows)
  211. // In that case, ini_set will not work, let's keep track of this and proceed anyway
  212. $aResult[] = new CheckResult(CheckResult::WARNING, "No memory limit has been defined in this instance of PHP");
  213. }
  214. else
  215. {
  216. // Check that the limit will allow us to load the data
  217. //
  218. $iMemoryLimit = utils::ConvertToBytes($sMemoryLimit);
  219. if ($iMemoryLimit < self::MIN_MEMORY_LIMIT)
  220. {
  221. $aResult[] = new CheckResult(CheckResult::ERROR, "memory_limit ($iMemoryLimit) is too small, the minimum value to run the application is ".self::MIN_MEMORY_LIMIT.".");
  222. }
  223. else
  224. {
  225. SetupPage::log("Info - memory_limit is $iMemoryLimit, ok.");
  226. }
  227. }
  228. // Special case for APC
  229. if (extension_loaded('apc'))
  230. {
  231. $sAPCVersion = phpversion('apc');
  232. $aResult[] = new CheckResult(CheckResult::INFO, "APC detected (version $sAPCVersion). The APC cache will be used to speed-up ".ITOP_APPLICATION.".");
  233. }
  234. // Special case Suhosin extension
  235. if (extension_loaded('suhosin'))
  236. {
  237. $sSuhosinVersion = phpversion('suhosin');
  238. $aOk[] = "Suhosin extension detected (version $sSuhosinVersion).";
  239. $iGetMaxValueLength = ini_get('suhosin.get.max_value_length');
  240. if ($iGetMaxValueLength < self::SUHOSIN_GET_MAX_VALUE_LENGTH)
  241. {
  242. $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.".");
  243. }
  244. else
  245. {
  246. SetupPage::log("Info - suhosin.get.max_value_length = $iGetMaxValueLength, ok.");
  247. }
  248. }
  249. if (function_exists('php_ini_loaded_file')) // PHP >= 5.2.4
  250. {
  251. $sPhpIniFile = php_ini_loaded_file();
  252. // Other included/scanned files
  253. if ($sFileList = php_ini_scanned_files())
  254. {
  255. if (strlen($sFileList) > 0)
  256. {
  257. $aFiles = explode(',', $sFileList);
  258. foreach ($aFiles as $sFile)
  259. {
  260. $sPhpIniFile .= ', '.trim($sFile);
  261. }
  262. }
  263. }
  264. $aResult[] = new CheckResult(CheckResult::INFO, "Loaded php.ini files: $sPhpIniFile");
  265. }
  266. return $aResult;
  267. }
  268. /**
  269. * Check that the backup could be executed
  270. * @param Page $oP The page used only for its 'log' method
  271. * @return array An array of CheckResults objects
  272. */
  273. static function CheckBackupPrerequisites($sDestDir)
  274. {
  275. $aResult = array();
  276. SetupPage::log('Info - CheckBackupPrerequisites');
  277. // zip extension
  278. //
  279. if (!extension_loaded('zip'))
  280. {
  281. $sMissingExtensionLink = "<a href=\"http://www.php.net/manual/en/book.zip.php\" target=\"_blank\">zip</a>";
  282. $aResult[] = new CheckResult(CheckResult::ERROR, "Missing PHP extension: zip", $sMissingExtensionLink);
  283. }
  284. // availability of exec()
  285. //
  286. $aDisabled = explode(', ', ini_get('disable_functions'));
  287. SetupPage::log('Info - PHP functions disabled: '.implode(', ', $aDisabled));
  288. if (in_array('exec', $aDisabled))
  289. {
  290. $aResult[] = new CheckResult(CheckResult::ERROR, "The PHP exec() function has been disabled on this server");
  291. }
  292. // availability of mysqldump
  293. $sMySQLBinDir = utils::ReadParam('mysql_bindir', '', true);
  294. if (empty($sMySQLBinDir))
  295. {
  296. $sMySQLDump = 'mysqldump';
  297. }
  298. else
  299. {
  300. SetupPage::log('Info - Found mysql_bindir: '.$sMySQLBinDir);
  301. $sMySQLDump = '"'.$sMySQLBinDir.'/mysqldump"';
  302. }
  303. $sCommand = "$sMySQLDump -V 2>&1";
  304. $aOutput = array();
  305. $iRetCode = 0;
  306. exec($sCommand, $aOutput, $iRetCode);
  307. if ($iRetCode == 0)
  308. {
  309. $aResult[] = new CheckResult(CheckResult::INFO, "mysqldump is present: ".$aOutput[0]);
  310. }
  311. elseif ($iRetCode == 1)
  312. {
  313. $aResult[] = new CheckResult(CheckResult::ERROR, "mysqldump could not be found: ".implode(' ', $aOutput)." - Please make sure it is installed and in the path.");
  314. }
  315. else
  316. {
  317. $aResult[] = new CheckResult(CheckResult::ERROR, "mysqldump could not be executed (retcode=$iRetCode): Please make sure it is installed and in the path");
  318. }
  319. foreach($aOutput as $sLine)
  320. {
  321. SetupPage::log('Info - mysqldump -V said: '.$sLine);
  322. }
  323. // check disk space
  324. // to do... evaluate how we can correlate the DB size with the size of the dump (and the zip!)
  325. // E.g. 2,28 Mb after a full install, giving a zip of 26 Kb (data = 26 Kb)
  326. // Example of query (DB without a suffix)
  327. //$sDBSize = "SELECT SUM(ROUND(DATA_LENGTH/1024/1024, 2)) AS size_mb FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = `$sDBName`";
  328. return $aResult;
  329. }
  330. /**
  331. * Helper function to retrieve the system's temporary directory
  332. * Emulates sys_get_temp_dir if neeed (PHP < 5.2.1)
  333. * @return string Path to the system's temp directory
  334. */
  335. static function GetTmpDir()
  336. {
  337. // try to figure out what is the temporary directory
  338. // prior to PHP 5.2.1 the function sys_get_temp_dir
  339. // did not exist
  340. if ( !function_exists('sys_get_temp_dir'))
  341. {
  342. if( $temp=getenv('TMP') ) return realpath($temp);
  343. if( $temp=getenv('TEMP') ) return realpath($temp);
  344. if( $temp=getenv('TMPDIR') ) return realpath($temp);
  345. $temp=tempnam(__FILE__,'');
  346. if (file_exists($temp))
  347. {
  348. unlink($temp);
  349. return realpath(dirname($temp));
  350. }
  351. return null;
  352. }
  353. else
  354. {
  355. return realpath(sys_get_temp_dir());
  356. }
  357. }
  358. /**
  359. * Helper function to retrieve the directory where files are to be uploaded
  360. * @return string Path to the temp directory used for uploading files
  361. */
  362. static function GetUploadTmpDir()
  363. {
  364. $sPath = ini_get('upload_tmp_dir');
  365. if (empty($sPath))
  366. {
  367. $sPath = self::GetTmpDir();
  368. }
  369. return $sPath;
  370. }
  371. /**
  372. * Helper to recursively remove a directory
  373. */
  374. public static function rrmdir($dir)
  375. {
  376. if ((strlen(trim($dir)) == 0) || ($dir == '/') || ($dir == '\\'))
  377. {
  378. throw new Exception("Attempting to delete directory: '$dir'");
  379. }
  380. self::tidydir($dir);
  381. rmdir($dir);
  382. }
  383. /**
  384. * Helper to recursively cleanup a directory
  385. */
  386. public static function tidydir($dir)
  387. {
  388. if ((strlen(trim($dir)) == 0) || ($dir == '/') || ($dir == '\\'))
  389. {
  390. throw new Exception("Attempting to delete directory: '$dir'");
  391. }
  392. foreach(glob($dir . '/*') as $file)
  393. {
  394. if(is_dir($file))
  395. {
  396. self::tidydir($file);
  397. rmdir($file);
  398. }
  399. else
  400. {
  401. unlink($file);
  402. }
  403. }
  404. }
  405. /**
  406. * Helper to build the full path of a new directory
  407. */
  408. public static function builddir($dir)
  409. {
  410. $parent = dirname($dir);
  411. if(!is_dir($parent))
  412. {
  413. self::builddir($parent);
  414. }
  415. if (!is_dir($dir))
  416. {
  417. mkdir($dir);
  418. }
  419. }
  420. /**
  421. * Helper to copy a directory to a target directory, skipping .SVN files (for developer's comfort!)
  422. * Returns true if successfull
  423. */
  424. public static function copydir($sSource, $sDest)
  425. {
  426. if (is_dir($sSource))
  427. {
  428. if (!is_dir($sDest))
  429. {
  430. mkdir($sDest);
  431. }
  432. $aFiles = scandir($sSource);
  433. if(sizeof($aFiles) > 0 )
  434. {
  435. foreach($aFiles as $sFile)
  436. {
  437. if ($sFile == '.' || $sFile == '..' || $sFile == '.svn')
  438. {
  439. // Skip
  440. continue;
  441. }
  442. if (is_dir($sSource.'/'.$sFile))
  443. {
  444. // Recurse
  445. self::copydir($sSource.'/'.$sFile, $sDest.'/'.$sFile);
  446. }
  447. else
  448. {
  449. copy($sSource.'/'.$sFile, $sDest.'/'.$sFile);
  450. }
  451. }
  452. }
  453. return true;
  454. }
  455. elseif (is_file($sSource))
  456. {
  457. return copy($sSource, $sDest);
  458. }
  459. else
  460. {
  461. return false;
  462. }
  463. }
  464. static function GetPreviousInstance($sDir)
  465. {
  466. $bFound = false;
  467. $sSourceDir = '';
  468. $sSourceEnvironement = '';
  469. $sConfigFile = '';
  470. $aResult = array(
  471. 'found' => false,
  472. );
  473. if (file_exists($sDir.'/config-itop.php'))
  474. {
  475. $sSourceDir = $sDir;
  476. $sSourceEnvironment = '';
  477. $sConfigFile = $sDir.'/config-itop.php';
  478. $aResult['found'] = true;
  479. }
  480. else if (file_exists($sDir.'/conf/production/config-itop.php'))
  481. {
  482. $sSourceDir = $sDir;
  483. $sSourceEnvironment = 'production';
  484. $sConfigFile = $sDir.'/conf/production/config-itop.php';
  485. $aResult['found'] = true;
  486. }
  487. if ($aResult['found'])
  488. {
  489. $oPrevConf = new Config($sConfigFile);
  490. $aResult = array(
  491. 'found' => true,
  492. 'source_dir' => $sSourceDir,
  493. 'source_environment' => $sSourceEnvironment,
  494. 'configuration_file' => $sConfigFile,
  495. 'db_server' => $oPrevConf->GetDBHost(),
  496. 'db_user' => $oPrevConf->GetDBUser(),
  497. 'db_pwd' => $oPrevConf->GetDBPwd(),
  498. 'db_name' => $oPrevConf->GetDBName(),
  499. 'db_prefix' => $oPrevConf->GetDBSubname(),
  500. );
  501. }
  502. return $aResult;
  503. }
  504. static function CheckDiskSpace($sDir)
  505. {
  506. while(($f = @disk_free_space($sDir)) == false)
  507. {
  508. if ($sDir == dirname($sDir)) break;
  509. if ($sDir == '.') break;
  510. $sDir = dirname($sDir);
  511. }
  512. return $f;
  513. }
  514. static function HumanReadableSize($fBytes)
  515. {
  516. $aSizes = array('bytes', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Hb');
  517. $index = 0;
  518. while (($fBytes > 1000) && ($index < count($aSizes)))
  519. {
  520. $index++;
  521. $fBytes = $fBytes / 1000;
  522. }
  523. return sprintf('%.2f %s', $fBytes, $aSizes[$index]);
  524. }
  525. static function DisplayDBParameters($oPage, $bAllowDBCreation, $sDBServer, $sDBUser, $sDBPwd, $sDBName, $sDBPrefix, $sNewDBName = '')
  526. {
  527. $oPage->add('<tr><td colspan="2">');
  528. $oPage->add('<fieldset><legend>Database Server Connection</legend>');
  529. $oPage->add('<table>');
  530. $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>');
  531. $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, CREATE, ALTER, CREATE VIEW, SUPER, TRIGGER</td></tr>');
  532. $oPage->add('<tr><td>Password:</td><td><input id="db_pwd" type="password" name="db_pwd" value="'.htmlentities($sDBPwd, ENT_QUOTES, 'UTF-8').'" size="15"/></td></tr>');
  533. $oPage->add('</table>');
  534. $oPage->add('</fieldset>');
  535. $oPage->add('</td></tr>');
  536. $oPage->add('<tr><td colspan="2"><span id="db_info"></span></td></tr>');
  537. $oPage->add('<tr><td colspan="2">');
  538. $oPage->add('<fieldset><legend>Database</legend>');
  539. $oPage->add('<table>');
  540. if ($bAllowDBCreation)
  541. {
  542. $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>');
  543. $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>');
  544. $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>');
  545. $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>');
  546. $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>');
  547. }
  548. else
  549. {
  550. $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>');
  551. $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>');
  552. }
  553. $oPage->add('</table>');
  554. $oPage->add('</fieldset>');
  555. $oPage->add('<tr><td colspan="2"><span id="table_info">&nbsp;</span></td></tr>');
  556. $oPage->add('</td></tr>');
  557. $oPage->add_script(
  558. <<<EOF
  559. var iCheckDBTimer = null;
  560. var oXHRCheckDB = null;
  561. function CheckDBConnection()
  562. {
  563. // Don't call the server too often...
  564. if (iCheckDBTimer !== null)
  565. {
  566. clearTimeout(iCheckDBTimer);
  567. iCheckDBTimer = null;
  568. }
  569. iCheckDBTimer = setTimeout(DoCheckDBConnection, 500);
  570. }
  571. function DoCheckDBConnection()
  572. {
  573. iCheckDBTimer = null;
  574. var oParams = {
  575. 'db_server': $("#db_server").val(),
  576. 'db_user': $("#db_user").val(),
  577. 'db_pwd': $("#db_pwd").val(),
  578. 'db_name': $("#db_name").val()
  579. }
  580. if (oXHRCheckDB !== null)
  581. {
  582. oXHRCheckDB.abort();
  583. oXHRCheckDB = null;
  584. }
  585. oXHRCheckDB = WizardAsyncAction("check_db", oParams);
  586. }
  587. function ValidateField(sFieldId, bUsed)
  588. {
  589. var sValue = new String($("#"+sFieldId).val());
  590. var bMandatory = false;
  591. if (bUsed)
  592. {
  593. if (sFieldId == 'db_name')
  594. {
  595. bUsed = ($("#existing_db").attr("checked") == "checked");
  596. bMandatory = true;
  597. }
  598. if (sFieldId == 'db_new_name')
  599. {
  600. bUsed = ($("#create_db").attr("checked") == "checked");
  601. bMandatory = true;
  602. }
  603. }
  604. if (!bUsed)
  605. {
  606. $("#v_"+sFieldId).html("");
  607. return true;
  608. }
  609. else
  610. {
  611. if (sValue != "")
  612. {
  613. if (sValue.match(/^[A-Za-z][A-Za-z0-9_]*$/))
  614. {
  615. var bCollision = false;
  616. if (sFieldId == 'db_new_name')
  617. {
  618. // check that the "new name" does not correspond to an existing database
  619. var sNewName = $('#db_new_name').val();
  620. $('#db_name option').each( function() {
  621. if ($(this).attr('value') == sNewName)
  622. {
  623. bCollision = true;
  624. }
  625. });
  626. }
  627. if (bCollision)
  628. {
  629. $("#v_"+sFieldId).html('<img src="../images/validation_error.png" title="A database with the same name already exists"/>');
  630. return false;
  631. }
  632. else
  633. {
  634. $("#v_"+sFieldId).html("");
  635. return true;
  636. }
  637. }
  638. else
  639. {
  640. $("#v_"+sFieldId).html('<img src="../images/validation_error.png" title="Only the characters [A-Za-z0-9_] are allowed"/>');
  641. return false;
  642. }
  643. }
  644. else if (bMandatory)
  645. {
  646. $("#v_"+sFieldId).html('<img src="../images/validation_error.png" title="This field cannot be empty"/>');
  647. return false;
  648. }
  649. else
  650. {
  651. $("#v_"+sFieldId).html("");
  652. return true;
  653. }
  654. }
  655. }
  656. EOF
  657. );
  658. $oPage->add_ready_script(
  659. <<<EOF
  660. DoCheckDBConnection(); // Validate the initial values immediately
  661. $("#db_server").bind("keyup change", function() { CheckDBConnection(); });
  662. $("#db_user").bind("keyup change", function() { CheckDBConnection(); });
  663. $("#db_pwd").bind("keyup change", function() { CheckDBConnection(); });
  664. $("#db_new_name").bind("click keyup change", function() { $("#create_db").attr("checked", "checked"); WizardUpdateButtons(); });
  665. $("#db_name").bind("click keyup change", function() { $("#existing_db").attr("checked", "checked"); WizardUpdateButtons(); });
  666. $("#db_prefix").bind("keyup change", function() { WizardUpdateButtons(); });
  667. $("#existing_db").bind("click change", function() { WizardUpdateButtons(); });
  668. $("#create_db").bind("click change", function() { WizardUpdateButtons(); });
  669. EOF
  670. );
  671. }
  672. /**
  673. * Helper function check the connection to the database, verify a few conditions (minimum version, etc...) and (if connected)
  674. * enumerate the existing databases (if possible)
  675. * @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)
  676. */
  677. static function CheckServerConnection($sDBServer, $sDBUser, $sDBPwd)
  678. {
  679. $aResult = array('checks' => array(), 'databases' => null);
  680. try
  681. {
  682. $oDBSource = new CMDBSource;
  683. $oDBSource->Init($sDBServer, $sDBUser, $sDBPwd);
  684. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Connection to '$sDBServer' as '$sDBUser' successful.");
  685. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Info - User privileges: ".($oDBSource->GetRawPrivileges()));
  686. $sDBVersion = $oDBSource->GetDBVersion();
  687. if (version_compare($sDBVersion, self::MYSQL_MIN_VERSION, '>='))
  688. {
  689. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "Current MySQL version ($sDBVersion), greater than minimum required version (".self::MYSQL_MIN_VERSION.")");
  690. // Check some server variables
  691. $iMaxAllowedPacket = $oDBSource->GetServerVariable('max_allowed_packet');
  692. $iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  693. if ($iMaxAllowedPacket >= (500 + $iMaxUploadSize)) // Allow some space for the query + the file to upload
  694. {
  695. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "MySQL server's max_allowed_packet ($iMaxAllowedPacket) is big enough compared to upload_max_filesize ($iMaxUploadSize).");
  696. }
  697. else if($iMaxAllowedPacket < $iMaxUploadSize)
  698. {
  699. $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).".");
  700. }
  701. $iMaxConnections = $oDBSource->GetServerVariable('max_connections');
  702. if ($iMaxConnections < 5)
  703. {
  704. $aResult['checks'][] = new CheckResult(CheckResult::WARNING, "MySQL server's max_connections ($iMaxConnections) is not enough. Please, consider setting it to at least 5.");
  705. }
  706. else
  707. {
  708. $aResult['checks'][] = new CheckResult(CheckResult::INFO, "MySQL server's max_connections is set to $iMaxConnections.");
  709. }
  710. }
  711. else
  712. {
  713. $aResult['checks'][] = new CheckResult(CheckResult::ERROR, "Error: Current MySQL version is ($sDBVersion), minimum required version (".self::MYSQL_MIN_VERSION.")");
  714. }
  715. try
  716. {
  717. $aResult['databases'] = $oDBSource->ListDB();
  718. }
  719. catch(Exception $e)
  720. {
  721. $aResult['databases'] = null;
  722. }
  723. }
  724. catch(Exception $e)
  725. {
  726. return false;
  727. }
  728. return $aResult;
  729. }
  730. static public function AsyncCheckDB($oPage, $aParameters)
  731. {
  732. $sDBServer = $aParameters['db_server'];
  733. $sDBUser = $aParameters['db_user'];
  734. $sDBPwd = $aParameters['db_pwd'];
  735. $sDBName = $aParameters['db_name'];
  736. $oPage->add_ready_script('oXHRCheckDB = null;');
  737. $checks = SetupUtils::CheckServerConnection($sDBServer, $sDBUser, $sDBPwd);
  738. if ($checks === false)
  739. {
  740. // Connection failed, disable the "Next" button
  741. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "error");');
  742. $oPage->add_ready_script('$("#db_info").html("No connection to the database...");');
  743. }
  744. else
  745. {
  746. $aErrors = array();
  747. $aWarnings = array();
  748. foreach($checks['checks'] as $oCheck)
  749. {
  750. if ($oCheck->iSeverity == CheckResult::ERROR)
  751. {
  752. $aErrors[] = $oCheck->sLabel;
  753. }
  754. else if ($oCheck->iSeverity == CheckResult::WARNING)
  755. {
  756. $aWarnings[] = $oCheck->sLabel;
  757. }
  758. }
  759. if (count($aErrors) > 0)
  760. {
  761. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "error");');
  762. $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').'\');');
  763. }
  764. else if (count($aWarnings) > 0)
  765. {
  766. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "");');
  767. $oPage->add_ready_script('$("#db_info").html(\'<img src="../images/error.png"/>&nbsp;<b>Warning:</b> '.htmlentities(implode('<br/>', $aWarnings), ENT_QUOTES, 'UTF-8').'\');');
  768. }
  769. else
  770. {
  771. $oPage->add_ready_script('$("#wiz_form").data("db_connection", "");');
  772. $oPage->add_ready_script('$("#db_info").html(\'<img src="../images/validation_ok.png"/>&nbsp;Database server connection Ok.\');');
  773. }
  774. if ($checks['databases'] == null)
  775. {
  776. $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>';
  777. $oPage->add_ready_script('$("#table_info").html(\'<img src="../images/error.png"/>&nbsp;Not enough rights to enumerate the databases\');');
  778. }
  779. else
  780. {
  781. $sDBNameInput = '<select id="db_name" name="db_name">';
  782. foreach($checks['databases'] as $sDatabaseName)
  783. {
  784. if ($sDatabaseName != 'information_schema')
  785. {
  786. $sEncodedName = htmlentities($sDatabaseName, ENT_QUOTES, 'UTF-8');
  787. $sSelected = ($sDatabaseName == $sDBName) ? ' selected ' : '';
  788. $sDBNameInput .= '<option value="'.$sEncodedName.'"'.$sSelected.'>'.$sEncodedName.'</option>';
  789. }
  790. }
  791. $sDBNameInput .= '</select>';
  792. }
  793. $oPage->add_ready_script('$("#db_name_container").html("'.addslashes($sDBNameInput).'");');
  794. $oPage->add_ready_script('$("#db_name").bind("click keyup change", function() { $("#existing_db").attr("checked", "checked"); WizardUpdateButtons(); });');
  795. }
  796. $oPage->add_ready_script('WizardUpdateButtons();');
  797. }
  798. /**
  799. * Helper function to get the available languages from the given directory
  800. * @param $sDir Path to the dictionary
  801. * @return an array of language code => description
  802. */
  803. static public function GetAvailableLanguages($sDir)
  804. {
  805. require_once(APPROOT.'/core/coreexception.class.inc.php');
  806. require_once(APPROOT.'/core/dict.class.inc.php');
  807. $aFiles = scandir($sDir);
  808. foreach($aFiles as $sFile)
  809. {
  810. if ($sFile == '.' || $sFile == '..' || $sFile == '.svn')
  811. {
  812. // Skip
  813. continue;
  814. }
  815. $sFilePath = $sDir.'/'.$sFile;
  816. if (is_file($sFilePath) && preg_match('/^.+\.dict.*\.php$/i', $sFilePath, $aMatches))
  817. {
  818. require_once($sFilePath);
  819. }
  820. }
  821. return Dict::GetLanguages();
  822. }
  823. static public function GetLanguageSelect($sSourceDir, $sInputName, $sDefaultLanguageCode)
  824. {
  825. $sHtml = '<select id="'.$sInputName.'" name="'.$sInputName.'">';
  826. $sSourceDir = APPROOT.'dictionaries/';
  827. $aLanguages = SetupUtils::GetAvailableLanguages($sSourceDir);
  828. foreach($aLanguages as $sCode => $aInfo)
  829. {
  830. $sSelected = ($sCode == $sDefaultLanguageCode) ? ' selected ' : '';
  831. $sHtml .= '<option value="'.$sCode.'"'.$sSelected.'>'.htmlentities($aInfo['description'], ENT_QUOTES, 'UTF-8').' ('.htmlentities($aInfo['localized_description'], ENT_QUOTES, 'UTF-8').')</option>';
  832. }
  833. $sHtml .= '</select></td></tr>';
  834. return $sHtml;
  835. }
  836. public static function AnalyzeInstallation($oWizard)
  837. {
  838. require_once(APPROOT.'/setup/moduleinstaller.class.inc.php');
  839. $oConfig = new Config();
  840. $aParamValues = array(
  841. 'db_server' => $oWizard->GetParameter('db_server', ''),
  842. 'db_user' => $oWizard->GetParameter('db_user', ''),
  843. 'db_pwd' => $oWizard->GetParameter('db_pwd', ''),
  844. 'db_name' => $oWizard->GetParameter('db_name', ''),
  845. 'db_prefix' => $oWizard->GetParameter('db_prefix', ''),
  846. 'source_dir' => APPROOT.'datamodel',
  847. );
  848. $oConfig->UpdateFromParams($aParamValues, 'datamodel');
  849. $oProductionEnv = new RunTimeEnvironment();
  850. $aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, 'datamodel');
  851. return $aAvailableModules;
  852. }
  853. /**
  854. * Checks if the content of a directory matches the given manifest
  855. * @param string $sBaseDir Path to the root directory of iTop
  856. * @param string $sSourceDir Relative path to the directory to check under $sBaseDir
  857. * @param Array $aDOMManifest Array of array('path' => relative_path 'size'=> iSize, 'md5' => sHexMD5)
  858. * @param Hash $aResult Used for recursion
  859. * @return hash Hash array ('added' => array(), 'removed' => array(), 'modified' => array())
  860. */
  861. public static function CheckDirAgainstManifest($sBaseDir, $sSourceDir, $aManifest, $aExcludeNames = array('.svn'), $aResult = null)
  862. {
  863. if ($aResult === null)
  864. {
  865. $aResult = array('added' => array(), 'removed' => array(), 'modified' => array());
  866. }
  867. if (substr($sSourceDir, 0, 1) == '/')
  868. {
  869. $sSourceDir = substr($sSourceDir, 1);
  870. }
  871. // Manifest limited to all the files supposed to be located in this directory
  872. $aDirManifest = array();
  873. foreach($aManifest as $aFileInfo)
  874. {
  875. $sDir = dirname($aFileInfo['path']);
  876. if ($sDir == '.')
  877. {
  878. // Hmm... the file seems located at the root of iTop
  879. $sDir = '';
  880. }
  881. if ($sDir == $sSourceDir)
  882. {
  883. $aDirManifest[basename($aFileInfo['path'])] = $aFileInfo;
  884. }
  885. }
  886. // Read the content of the directory
  887. foreach(glob($sBaseDir.'/'.$sSourceDir .'/*') as $sFilePath)
  888. {
  889. $sFile = basename($sFilePath);
  890. if (in_array(basename($sFile), $aExcludeNames)) continue;
  891. if(is_dir($sFilePath))
  892. {
  893. $aResult = self::CheckDirAgainstManifest($sBaseDir, $sSourceDir.'/'.$sFile, $aManifest, $aExcludeNames, $aResult);
  894. }
  895. else
  896. {
  897. if (!array_key_exists($sFile, $aDirManifest))
  898. {
  899. //echo "New file ".$sFile." in $sSourceDir\n";
  900. $aResult['added'][$sSourceDir.'/'.$sFile] = true;
  901. }
  902. else
  903. {
  904. $aStats = stat($sFilePath);
  905. if ($aStats['size'] != $aDirManifest[$sFile]['size'])
  906. {
  907. // Different sizes
  908. $aResult['modified'][$sSourceDir.'/'.$sFile] = 'Different sizes. Original size: '.$aDirManifest[$sFile]['size'].' bytes, actual file size on disk: '.$aStats['size'].' bytes.';
  909. }
  910. else
  911. {
  912. // Same size, compare the md5 signature
  913. $sMD5 = md5_file($sFilePath);
  914. if ($sMD5 != $aDirManifest[$sFile]['md5'])
  915. {
  916. $aResult['modified'][$sSourceDir.'/'.$sFile] = 'Content modified (MD5 checksums differ).';
  917. }
  918. //else
  919. //{
  920. // echo $sSourceDir.'/'.$sFile." unmodified ($sMD5 == {$aDirManifest[$sFile]['md5']})\n";
  921. //}
  922. }
  923. //echo "Removing ".$sFile." from aDirManifest\n";
  924. unset($aDirManifest[$sFile]);
  925. }
  926. }
  927. }
  928. // What remains in the array are files that were deleted
  929. foreach($aDirManifest as $sDeletedFile => $void)
  930. {
  931. $aResult['removed'][$sSourceDir.'/'.$sDeletedFile] = true;
  932. }
  933. return $aResult;
  934. }
  935. public static function CheckDataModelFiles($sManifestFile, $sBaseDir)
  936. {
  937. $oXML = simplexml_load_file($sManifestFile);
  938. $aManifest = array();
  939. foreach($oXML as $oFileInfo)
  940. {
  941. $aManifest[] = array('path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5);
  942. }
  943. $aResults = self::CheckDirAgainstManifest($sBaseDir, 'modules', $aManifest);
  944. // echo "<pre>Comparison of ".dirname($sBaseDir)."/modules:\n".print_r($aResults, true)."</pre>";
  945. return $aResults;
  946. }
  947. public static function CheckPortalFiles($sManifestFile, $sBaseDir)
  948. {
  949. $oXML = simplexml_load_file($sManifestFile);
  950. $aManifest = array();
  951. foreach($oXML as $oFileInfo)
  952. {
  953. $aManifest[] = array('path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5);
  954. }
  955. $aResults = self::CheckDirAgainstManifest($sBaseDir, 'portal', $aManifest);
  956. // echo "<pre>Comparison of ".dirname($sBaseDir)."/portal:\n".print_r($aResults, true)."</pre>";
  957. return $aResults;
  958. }
  959. public static function CheckApplicationFiles($sManifestFile, $sBaseDir)
  960. {
  961. $oXML = simplexml_load_file($sManifestFile);
  962. $aManifest = array();
  963. foreach($oXML as $oFileInfo)
  964. {
  965. $aManifest[] = array('path' => (string)$oFileInfo->path, 'size' => (int)$oFileInfo->size, 'md5' => (string)$oFileInfo->md5);
  966. }
  967. $aResults = array('added' => array(), 'removed' => array(), 'modified' => array());
  968. foreach(array('addons', 'core', 'dictionaries', 'js', 'application', 'css', 'pages', 'synchro', 'webservices') as $sDir)
  969. {
  970. $aTmp = self::CheckDirAgainstManifest($sBaseDir, 'portal', $aManifest);
  971. $aResults['added'] = array_merge($aResults['added'], $aTmp['added']);
  972. $aResults['modified'] = array_merge($aResults['modified'], $aTmp['modified']);
  973. $aResults['removed'] = array_merge($aResults['removed'], $aTmp['removed']);
  974. }
  975. // echo "<pre>Comparison of ".dirname($sBaseDir)."/portal:\n".print_r($aResults, true)."</pre>";
  976. return $aResults;
  977. }
  978. }