setuputils.class.inc.php 47 KB

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