setuputils.class.inc.php 49 KB

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