setuputils.class.inc.php 40 KB

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