/**
* Wizard to configure and initialize the iTop application
*
* @copyright Copyright (C) 2010-2012 Combodo SARL
* @license http://opensource.org/licenses/AGPL-3.0
*/
require_once('../approot.inc.php');
require_once(APPROOT.'/application/utils.inc.php');
require_once(APPROOT.'/core/config.class.inc.php');
require_once(APPROOT.'/core/log.class.inc.php');
require_once(APPROOT.'/core/kpi.class.inc.php');
require_once(APPROOT.'/core/cmdbsource.class.inc.php');
require_once(APPROOT.'/setup/setuppage.class.inc.php');
require_once(APPROOT.'/setup/moduleinstaller.class.inc.php');
define('PHP_MIN_VERSION', '5.2.0');
define('MYSQL_MIN_VERSION', '5.0.0');
define('MIN_MEMORY_LIMIT', 32*1024*1024);
define('SUHOSIN_GET_MAX_VALUE_LENGTH', 2048);
$sOperation = Utils::ReadParam('operation', 'step0');
$oP = new SetupPage('iTop configuration wizard');
///////////////////////////////////////////////////////////////////////////////////////////////////
// Various helper function
///////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Get a nicely formatted version string
*/
function GetITopVersion($bShort = true)
{
$sVersionString = '';
if ($bShort)
{
$sVersionString = "iTop Version ".ITOP_VERSION;
}
else
{
if (ITOP_REVISION == '$WCREV$')
{
// This is NOT a version built using the buil system, just display the main version
$sVersionString = "iTop Version ".ITOP_VERSION;
}
else
{
// This is a build made from SVN, let display the full information
$sVersionString = "iTop Version ".ITOP_VERSION." revision ".ITOP_REVISION.", built on: ".ITOP_BUILD_DATE;
}
}
return $sVersionString;
}
/**
* Helper function to retrieve the system's temporary directory
* Emulates sys_get_temp_dir if neeed (PHP < 5.2.1)
* @return string Path to the system's temp directory
*/
function GetTmpDir()
{
// try to figure out what is the temporary directory
// prior to PHP 5.2.1 the function sys_get_temp_dir
// did not exist
if ( !function_exists('sys_get_temp_dir'))
{
if( $temp=getenv('TMP') ) return realpath($temp);
if( $temp=getenv('TEMP') ) return realpath($temp);
if( $temp=getenv('TMPDIR') ) return realpath($temp);
$temp=tempnam(__FILE__,'');
if (file_exists($temp))
{
unlink($temp);
return realpath(dirname($temp));
}
return null;
}
else
{
return realpath(sys_get_temp_dir());
}
}
/**
* Helper function to retrieve the directory where files are to be uploaded
* @return string Path to the temp directory used for uploading files
*/
function GetUploadTmpDir()
{
$sPath = ini_get('upload_tmp_dir');
if (empty($sPath))
{
$sPath = GetTmpDir();
}
return $sPath;
}
/**
* Helper function to check if the current version of PHP
* is compatible with the application
* @return boolean true if this is Ok, false otherwise
*/
function CheckPHPVersion(SetupPage $oP)
{
$bResult = true;
$aErrors = array();
$aWarnings = array();
$aOk = array();
$oP->log('Info - CheckPHPVersion');
if (version_compare(phpversion(), PHP_MIN_VERSION, '>='))
{
$aOk [] = "The current PHP Version (".phpversion().") is greater than the minimum required version (".PHP_MIN_VERSION.")";
}
else
{
$aErrors[] = "Error: The current PHP Version (".phpversion().") is lower than the minimum required version (".PHP_MIN_VERSION.")";
$bResult = false;
}
$aMandatoryExtensions = array('mysqli', 'iconv', 'simplexml', 'soap', 'hash', 'json', 'session', 'pcre', 'dom');
$aOptionalExtensions = array('mcrypt' => 'Strong encryption will not be used.',
'ldap' => 'LDAP authentication will be disabled.');
asort($aMandatoryExtensions); // Sort the list to look clean !
ksort($aOptionalExtensions); // Sort the list to look clean !
$aExtensionsOk = array();
$aMissingExtensions = array();
$aMissingExtensionsLinks = array();
// First check the mandatory extensions
foreach($aMandatoryExtensions as $sExtension)
{
if (extension_loaded($sExtension))
{
$aExtensionsOk[] = $sExtension;
}
else
{
$aMissingExtensions[] = $sExtension;
$aMissingExtensionsLinks[] = "$sExtension";
}
}
if (count($aExtensionsOk) > 0)
{
$aOk[] = "Required PHP extension(s): ".implode(', ', $aExtensionsOk).".";
}
if (count($aMissingExtensions) > 0)
{
$aErrors[] = "Missing PHP extension(s): ".implode(', ', $aMissingExtensionsLinks).".";
$bResult = false;
}
// Next check the optional extensions
$aExtensionsOk = array();
$aMissingExtensions = array();
foreach($aOptionalExtensions as $sExtension => $sMessage)
{
if (extension_loaded($sExtension))
{
$aExtensionsOk[] = $sExtension;
}
else
{
$aMissingExtensions[$sExtension] = $sMessage;
}
}
if (count($aExtensionsOk) > 0)
{
$aOk[] = "Optional PHP extension(s): ".implode(', ', $aExtensionsOk).".";
}
if (count($aMissingExtensions) > 0)
{
foreach($aMissingExtensions as $sExtension => $sMessage)
{
$aWarnings[] = "Missing optional PHP extension: $sExtension. ".$sMessage;
}
}
// Check some ini settings here
if (function_exists('php_ini_loaded_file')) // PHP >= 5.2.4
{
$sPhpIniFile = php_ini_loaded_file();
// Other included/scanned files
if ($sFileList = php_ini_scanned_files())
{
if (strlen($sFileList) > 0)
{
$aFiles = explode(',', $sFileList);
foreach ($aFiles as $sFile)
{
$sPhpIniFile .= ', '.trim($sFile);
}
}
}
$oP->log("Info - php.ini file(s): '$sPhpIniFile'");
}
else
{
$sPhpIniFile = 'php.ini';
}
if (!ini_get('file_uploads'))
{
$aErrors[] = "Files upload is not allowed on this server (file_uploads = ".ini_get('file_uploads').").";
$bResult = false;
}
$sUploadTmpDir = GetUploadTmpDir();
if (empty($sUploadTmpDir))
{
$sUploadTmpDir = '/tmp';
$aErrors[] = "Temporary directory for files upload is not defined (upload_tmp_dir), assuming that $sUploadTmpDir is used.";
}
// check that the upload directory is indeed writable from PHP
if (!empty($sUploadTmpDir))
{
if (!file_exists($sUploadTmpDir))
{
$aErrors[] = "Temporary directory for files upload ($sUploadTmpDir) does not exist or cannot be read by PHP.";
$bResult = false;
}
else if (!is_writable($sUploadTmpDir))
{
$aErrors[] = "Temporary directory for files upload ($sUploadTmpDir) is not writable.";
$bResult = false;
}
else
{
$oP->log("Info - Temporary directory for files upload ($sUploadTmpDir) is writable.");
}
}
if (!ini_get('upload_max_filesize'))
{
$aErrors[] = "File upload is not allowed on this server (upload_max_filesize = ".ini_get('upload_max_filesize').").";
}
$iMaxFileUploads = ini_get('max_file_uploads');
if (!empty($iMaxFileUploads) && ($iMaxFileUploads < 1))
{
$aErrors[] = "File upload is not allowed on this server (max_file_uploads = ".ini_get('max_file_uploads').").";
$bResult = false;
}
$iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
$iMaxPostSize = utils::ConvertToBytes(ini_get('post_max_size'));
if ($iMaxPostSize <= $iMaxUploadSize)
{
$aWarnings[] = "post_max_size (".ini_get('post_max_size').") must be bigger than upload_max_filesize (".ini_get('upload_max_filesize')."). You may want to check the PHP configuration file(s): '$sPhpIniFile'. Be aware that this setting can also be overridden in the apache configuration.";
}
$oP->log("Info - upload_max_filesize: ".ini_get('upload_max_filesize'));
$oP->log("Info - post_max_size: ".ini_get('post_max_size'));
$oP->log("Info - max_file_uploads: ".ini_get('max_file_uploads'));
// Check some more ini settings here, needed for file upload
if (function_exists('get_magic_quotes_gpc'))
{
if (@get_magic_quotes_gpc())
{
$aErrors[] = "'magic_quotes_gpc' is set to On. Please turn it Off before continuing. You may want to check the PHP configuration file(s): '$sPhpIniFile'. Be aware that this setting can also be overridden in the apache configuration.";
$bResult = false;
}
}
if (function_exists('magic_quotes_runtime'))
{
if (@magic_quotes_runtime())
{
$aErrors[] = "'magic_quotes_runtime' is set to On. Please turn it Off before continuing. You may want to check the PHP configuration file(s): '$sPhpIniFile'. Be aware that this setting can also be overridden in the apache configuration.";
$bResult = false;
}
}
$sMemoryLimit = trim(ini_get('memory_limit'));
if (empty($sMemoryLimit))
{
// On some PHP installations, memory_limit does not exist as a PHP setting!
// (encountered on a 5.2.0 under Windows)
// In that case, ini_set will not work, let's keep track of this and proceed anyway
$aWarnings[] = "No memory limit has been defined in this instance of PHP";
}
else
{
// Check that the limit will allow us to load the data
//
$iMemoryLimit = utils::ConvertToBytes($sMemoryLimit);
if ($iMemoryLimit < MIN_MEMORY_LIMIT)
{
$aErrors[] = "memory_limit ($iMemoryLimit) is too small, the minimum value to run iTop is ".MIN_MEMORY_LIMIT.".";
$bResult = false;
}
else
{
$oP->log_info("memory_limit is $iMemoryLimit, ok.");
}
}
// Special case for APC
if (extension_loaded('apc'))
{
$sAPCVersion = phpversion('apc');
$aOk[] = "APC detected (version $sAPCVersion). The APC cache will be used to speed-up iTop.";
}
// Special case Suhosin extension
if (extension_loaded('suhosin'))
{
$sSuhosinVersion = phpversion('suhosin');
$aOk[] = "Suhosin extension detected (version $sSuhosinVersion).";
$iGetMaxValueLength = ini_get('suhosin.get.max_value_length');
if ($iGetMaxValueLength < SUHOSIN_GET_MAX_VALUE_LENGTH)
{
$aErrors[] = "suhosin.get.max_value_length ($iGetMaxValueLength) is too small, the minimum value to run iTop is ".SUHOSIN_GET_MAX_VALUE_LENGTH.". This value is set by the PHP configuration file(s): '$sPhpIniFile'. Be aware that this setting can also be overridden in the apache configuration.";
$bResult = false;
}
else
{
$oP->log_info("suhosin.get.max_value_length = $iGetMaxValueLength, ok.");
}
}
if (!$bResult)
{
$sTitle = 'Checking prerequisites: Failed !';
}
else
{
if (count($aWarnings) > 0)
{
$sTitle = ' Checking prerequisites: Warning (show details)';
$oP->add_ready_script("$('#prereq_details').hide();\n");
}
else
{
$sTitle = ' Checking prerequisites: Ok (show details)';
$oP->add_ready_script("$('#prereq_details').hide();\n");
}
}
$oP->add("
$sTitle
\n");
$oP->add("
\n");
foreach($aErrors as $sError)
{
$oP->error($sError);
//$oP->add_ready_script("$('#prereq_details').show();");
}
foreach($aWarnings as $sWarning)
{
$oP->warning($sWarning);
}
foreach($aOk as $sOk)
{
$oP->ok($sOk);
}
$oP->add("
\n");
return $bResult;
}
/**
* Helper function check the connection to the database and (if connected) to enumerate
* the existing databases
* @return Array The list of databases found in the server
*/
function CheckServerConnection(SetupPage $oP, $sDBServer, $sDBUser, $sDBPwd)
{
$aResult = array();
$oP->log('Info - CheckServerConnection');
try
{
$oDBSource = new CMDBSource;
$oDBSource->Init($sDBServer, $sDBUser, $sDBPwd);
$oP->ok("Connection to '$sDBServer' as '$sDBUser' successful.");
$oP->log("Info - User privileges: ".($oDBSource->GetRawPrivileges()));
$sDBVersion = $oDBSource->GetDBVersion();
if (version_compare($sDBVersion, MYSQL_MIN_VERSION, '>='))
{
$oP->ok("Current MySQL version ($sDBVersion), greater than minimum required version (".MYSQL_MIN_VERSION.")");
// Check some server variables
$iMaxAllowedPacket = $oDBSource->GetServerVariable('max_allowed_packet');
$iMaxUploadSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
if ($iMaxAllowedPacket >= (500 + $iMaxUploadSize)) // Allow some space for the query + the file to upload
{
$oP->ok("MySQL server's max_allowed_packet is big enough.");
}
else if($iMaxAllowedPacket < $iMaxUploadSize)
{
$oP->warning("MySQL server's max_allowed_packet ($iMaxAllowedPacket) is not big enough. Please, consider setting it to at least ".(500 + $iMaxUploadSize).".");
}
$oP->log("Info - MySQL max_allowed_packet: $iMaxAllowedPacket");
$iMaxConnections = $oDBSource->GetServerVariable('max_connections');
if ($iMaxConnections < 5)
{
$oP->warning("MySQL server's max_connections ($iMaxConnections) is not enough. Please, consider setting it to at least 5.");
}
$oP->log("Info - MySQL max_connections: ".($oDBSource->GetServerVariable('max_connections')));
}
else
{
$oP->error("Error: Current MySQL version is ($sDBVersion), minimum required version (".MYSQL_MIN_VERSION.")");
return false;
}
try
{
$aResult = $oDBSource->ListDB();
}
catch(Exception $e)
{
$oP->warning("Warning: unable to enumerate the current databases.");
$aResult = true; // Not an array to differentiate with an empty array
}
}
catch(Exception $e)
{
$oP->error("Error: Connection to '$sDBServer' as '$sDBUser' failed.");
$oP->p($e->GetHtmlDesc());
$aResult = false;
}
return $aResult;
}
/**
* Scans the ./data directory for XML files and output them as a Javascript array
*/
function PopulateDataFilesList(SetupPage $oP, $aParamValues, $oConfig)
{
$sScript = "function PopulateDataFilesList()\n";
$sScript .= "{\n";
$sScript .= "if (aFilesToLoad.length > 0) return;"; // Populate the list only once...
$oProductionEnv = new RunTimeEnvironment();
$aAvailableModules = $oProductionEnv->AnalyzeInstallation($oConfig, $aParamValues['source_dir']);
$sMode = $aParamValues['mode'];
$aStructureDataFiles = array();
$aSampleDataFiles = array();
foreach($aAvailableModules as $sModuleId => $aModule)
{
if (($sModuleId != ROOT_MODULE))
{
if (in_array($sModuleId, $aParamValues['module']))
{
if (empty($aModule['version_db']))
{
// New installation load the data
$aModuleStruct = $aAvailableModules[$sModuleId]['data.struct'];
$aModuleSamples = $aAvailableModules[$sModuleId]['data.sample'];
$aStructureDataFiles = array_merge($aStructureDataFiles, $aModuleStruct);
$aSampleDataFiles = array_merge($aSampleDataFiles, $aModuleSamples);
}
}
}
}
// Structure data
//
foreach($aStructureDataFiles as $sFile)
{
// Under Windows, it is a must to escape backslashes (not an issue until a folder name starts with t or n, etc...)
$sFile = APPROOT.$sFile;
$sFile = str_replace('\\', '\\\\', $sFile);
$sScript .= "aFilesToLoad[aFilesToLoad.length] = '$sFile';\n";
}
// Sample data - loaded IIF wished by the user
//
if ($aParamValues['sample_data'] != 'no')
{
foreach($aSampleDataFiles as $sFile)
{
// Under Windows, it is a must to escape backslashes (not an issue until a folder name starts with t or n, etc...)
$sFile = APPROOT.$sFile;
$sFile = str_replace('\\', '\\\\', $sFile);
$sScript .= "aFilesToLoad[aFilesToLoad.length] = '$sFile';\n";
}
}
$sScript .= "}\n";
$oP->add_script($sScript);
}
/**
* Add some parameters as hidden inputs into a form
* @param SetupPage $oP The page to insert the form elements into
* @param Hash $aParamValues The pairs name/value to be stored in the form
* @param Array $aExcludeParams A list of parameters to exclude from the previous hash
*/
function AddParamsToForm(SetupPage $oP, $aParamValues, $aExcludeParams = array())
{
foreach($aParamValues as $sName => $value)
{
if(!in_array($sName, $aExcludeParams))
{
AddHiddenParam($oP, $sName, $value);
}
}
}
/**
* Add a hidden field to store the specified parameter
* @param $sName string Name of the parameter
* @param $value mixed Value of the parameter
*/
function AddHiddenParam($oP, $sName, $value)
{
if (is_array($value))
{
foreach($value as $sKey => $sItem)
{
$oP->add('');
}
}
else
{
$oP->add('');
}
}
/**
* Helper function to get the available languages from the given directory
* @param $sDir Path to the dictionary
* @return an array of language code => description
*/
function GetAvailableLanguages($sDir)
{
require_once(APPROOT.'/core/coreexception.class.inc.php');
require_once(APPROOT.'/core/dict.class.inc.php');
$aFiles = scandir($sDir);
foreach($aFiles as $sFile)
{
if ($sFile == '.' || $sFile == '..' || $sFile == '.svn')
{
// Skip
continue;
}
$sFilePath = $sDir.'/'.$sFile;
if (is_file($sFilePath) && preg_match('/^.+\.dict.*\.php$/i', $sFilePath, $aMatches))
{
require_once($sFilePath);
}
}
return Dict::GetLanguages();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Handling of the different steps of the setup wizard
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Displays the welcome screen and check some basic prerequisites
*/
function WelcomeAndCheckPrerequisites(SetupPage $oP, $aParamValues, $iCurrentStep)
{
$sNextOperation = 'step'.($iCurrentStep+1);
$aParamValues['previous_step'] = 0;
$oP->add("
iTop configuration wizard
\n");
$sVersionStringShort = GetITopVersion(true);
$sVersionStringLong = GetITopVersion(false);
$oP->set_title('Welcome to '.$sVersionStringShort);
$oP->log($sVersionStringLong);
$aPreviousParams = array();
$oP->add("\n");
}
}
function LicenceAcknowledgement($oP, $aParamValues, $iCurrentStep)
{
$sNextOperation = 'step'.($iCurrentStep+1);
$iPrevStep = 0;
$aParamValues['previous_step'] = $iCurrentStep; // Come back here
$oP->set_title('License agreement');
$oP->add('
iTop is released by Combodo SARL under the terms of the GPL V3 license. In order to use iTop you must accept the terms of this license.
');
$oP->add("\n");
$oP->add("\n");
}
/**
* Display the form for the first step of the configuration wizard
* which consists in the database server selection
*/
function DatabaseServerSelection(SetupPage $oP, $aParamValues, $iCurrentStep)
{
$sNextOperation = 'step'.($iCurrentStep+1);
$iPrevStep = 1;
$aParamValues['previous_step'] = $iCurrentStep; // Come back here
$oP->add("\n");
}
/**
* Display the form for the second step of the configuration wizard
* which consists in
* 1) Validating the parameters by connecting to the database server
* 2) Prompting to select an existing database or to create a new one
*/
function DatabaseInstanceSelection(SetupPage $oP, $aParamValues, $iCurrentStep, $oConfig)
{
$sNextOperation = 'step'.($iCurrentStep+1);
$iPrevStep = 2;
$aParamValues['previous_step'] = $iCurrentStep; // Come back here
$oP->set_title("Database instance selection\n");
$oP->add("\n");
}
/**
* Display the form to select the iTop modules to be installed
*/
function ModulesSelection(SetupPage $oP, $aParamValues, $iCurrentStep, $oConfig)
{
$sNextOperation = 'step'.($iCurrentStep+1);
$aParamValues['previous_step'] = $iCurrentStep; // Come back here
$oP->add("\n");
return;
}
$oP->ok("iTop version ".$aAvailableModules[ROOT_MODULE]['version_db']." detected.\n");
$oP->add("
Customize your iTop installation to fit your needs