<commit_before><?php
// (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

// To (re-)enable this script the file has to be named tiki-installer.php and the following four lines
// must start with two '/' and 'stopinstall:'. (Make sure there are no spaces inbetween // and stopinstall: !)

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
	header("location: index.php");
	exit;
}

require_once('tiki-filter-base.php');

// Define and load Smarty components
global $prefs;
$prefs = array();
$prefs['smarty_notice_reporting'] = 'n';
$prefs['smarty_compilation'] = 'always';
$prefs['smarty_security'] = 'y';
require_once 'lib/init/initlib.php';
set_error_handler("tiki_error_handling", error_reporting());
require_once ( 'lib/init/smarty.php');
require_once ('installer/installlib.php');

/**
 *
 */
class InstallerDatabaseErrorHandler implements TikiDb_ErrorHandler
{
    /**
     * @param TikiDb $db
     * @param $query
     * @param $values
     * @param $result
     */
    function handle(TikiDb $db, $query, $values, $result)
	{
	}
}

$dbTiki = false;
$commands = array();
@ini_set('magic_quotes_runtime', 0);

// tra() should not use $tikilib because this lib is not available in every steps of the installer
//  and because we want to be sure that translations of the installer are the original ones, even for an upgrade
$prefs['lang_use_db'] = 'n';

// Which step of the installer
if (empty($_REQUEST['install_step'])) {
	$install_step = '0';

	if (isset($_REQUEST['setdbversion'])) {
		// Sets dbversion_tiki when installing the WebDeploy package
		$db = fopen('db/'.$tikidomainslash.'local.php', 'a');
		require_once 'lib/setup/twversion.class.php';
		$TWV = new TWVersion();
		fwrite($db, "\n\$dbversion_tiki='" . $TWV->getBaseVersion() . "';\n");
		fclose($db);
	}
} else {
	$install_step = $_REQUEST['install_step'];

	if ($install_step == 3) {	// clear caches after system requirements page
		global $cachelib; include 'lib/cache/cachelib.php';
		$cachelib->empty_cache();
	}
}

// define the language to use, either from user-setting or default
if (!empty($_REQUEST['lang'])) {
	$language = $prefs['site_language'] = $prefs['language'] = $_REQUEST['lang'];
} else {
	$language = $prefs['site_language'] = $prefs['language'] = 'en';
}
include_once('lib/init/tra.php');

/**
 * @return bool
 */
function has_tiki_db()
{
	global $installer;
	return $installer->tableExists('users_users');
}

/**
 * @return bool
 */
function has_tiki_db_20()
{
	global $installer;
	return $installer->tableExists('tiki_pages_translation_bits');
}

/**
 * @param $dbb_tiki
 * @param $host_tiki
 * @param $user_tiki
 * @param $pass_tiki
 * @param $dbs_tiki
 * @param string $client_charset
 * @param string $api_tiki
 * @param string $dbversion_tiki
 */
function write_local_php($dbb_tiki, $host_tiki, $user_tiki, $pass_tiki, $dbs_tiki, $client_charset = '', $api_tiki = '', $dbversion_tiki = 'current')
{
	global $local;
	global $db_tiki;
	if ($dbs_tiki && $user_tiki) {
		$db_tiki = addslashes($dbb_tiki);
		$host_tiki = addslashes($host_tiki);
		$user_tiki = addslashes($user_tiki);
		$pass_tiki = addslashes($pass_tiki);
		$dbs_tiki = addslashes($dbs_tiki);
		$fw = fopen($local, 'w');
		$filetowrite = "<?php\n";
		$filetowrite .= "\$db_tiki='" . $db_tiki . "';\n";
		if ($dbversion_tiki == 'current') {
			require_once 'lib/setup/twversion.class.php';
			$twversion = new TWVersion();
			$dbversion_tiki = $twversion->getBaseVersion();
		}
		$filetowrite .= "\$dbversion_tiki='" . $dbversion_tiki . "';\n";
		$filetowrite .= "\$host_tiki='" . $host_tiki . "';\n";
		$filetowrite .= "\$user_tiki='" . $user_tiki . "';\n";
		$filetowrite .= "\$pass_tiki='" . $pass_tiki . "';\n";
		$filetowrite .= "\$dbs_tiki='" . $dbs_tiki . "';\n";
		if ( ! empty( $api_tiki ) ) {
			$filetowrite .= "\$api_tiki='" . $api_tiki . "';\n";
		}
		if ( ! empty( $client_charset ) ) {
			$filetowrite .= "\$client_charset='$client_charset';\n";
		}
		$filetowrite .= "// If you experience text encoding issues after updating (e.g. apostrophes etc showing up as strange characters) \n";
		$filetowrite .= "// \$client_charset='latin1';\n";
		$filetowrite .= "// \$client_charset='utf8';\n";
		$filetowrite .= "// See http://tiki.org/ReleaseNotes5.0#Known_Issues and http://doc.tiki.org/Understanding+Encoding for more info\n\n";
		$filetowrite .= "// If your php installation does not not have pdo extension\n";
		$filetowrite .= "// \$api_tiki = 'adodb';\n\n";
		$filetowrite .= "// Want configurations managed at the system level or restrict some preferences? http://doc.tiki.org/System+Configuration\n";
		$filetowrite .= "// \$system_configuration_file = '/etc/tiki.ini';\n";
		$filetowrite .= "// \$system_configuration_identifier = 'example.com';\n\n";
		fwrite($fw, $filetowrite);
		fclose($fw);
	}
}

/**
 * @param string $domain
 * @return string
 */
function create_dirs($domain='')
{
	global $tikipath;
	$dirs=array(
		'db',
		'dump',
		'img/wiki',
		'img/wiki_up',
		'img/trackers',
		'modules/cache',
		'temp',
		'temp/cache',
		'templates_c',
		'templates',
		'styles',
		'whelp');

	$ret = "";
	foreach ($dirs as $dir) {
		$dir = $dir.'/'.$domain;

		if (!is_dir($dir)) {
			$created = @mkdir($dir, 02775); // Try creating the directory
			if (!$created) {
				$ret .= "The directory '$tikipath$dir' could not be created.\n";
			}
		} else if (!TikiInit::is_writeable($dir)) {
			@chmod($dir, 02775);
			if (!TikiInit::is_writeable($dir)) {
				$ret .= "The directory '$tikipath$dir' is not writeable.\n";
			}
		}
	}
	return $ret;
}

/**
 * @return bool
 */
function isWindows()
{
	static $windows;

	if (!isset($windows)) {
		$windows = substr(PHP_OS, 0, 3) == 'WIN';
	}

	return $windows;
}

function check_session_save_path()
{
	global $errors;
	if (ini_get('session.save_handler') == 'files') {
        	$save_path = ini_get('session.save_path');
		// check if we can check it. The session.save_path can be outside
		// the open_basedir paths.
		$open_basedir=ini_get('open_basedir');
		if (empty($open_basedir)) {
        		if (!is_dir($save_path)) {
                		$errors .= "The directory '$save_path' does not exist or PHP is not allowed to access it (check open_basedir entry in php.ini).\n";
        		} else if (!TikiInit::is_writeable($save_path)) {
                		$errors .= "The directory '$save_path' is not writeable.\n";
        		}
		}

        	if ($errors) {
                	$save_path = TikiInit::tempdir();

                	if (is_dir($save_path) && TikiInit::is_writeable($save_path)) {
                        	ini_set('session.save_path', $save_path);

                        	$errors = '';
                	}
        	}
	}
}

function get_webserver_uid()
{
	global $wwwuser;
	global $wwwgroup;
	$wwwuser = '';
	$wwwgroup = '';

	if (isWindows()) {
        	$wwwuser = 'SYSTEM';

        	$wwwgroup = 'SYSTEM';
	}

	if (function_exists('posix_getuid')) {
        	$user = @posix_getpwuid(@posix_getuid());

        	$group = @posix_getpwuid(@posix_getgid());
        	$wwwuser = $user ? $user['name'] : false;
        	$wwwgroup = $group ? $group['name'] : false;
	}

	if (!$wwwuser) {
        	$wwwuser = 'nobody (or the user account the web server is running under)';
	}

	if (!$wwwgroup) {
        	$wwwgroup = 'nobody (or the group account the web server is running under)';
	}
}

function error_and_exit()
{
	global $errors, $tikipath;

        $PHP_CONFIG_FILE_PATH = PHP_CONFIG_FILE_PATH;

        $httpd_conf = 'httpd.conf';
/*
        ob_start();
        phpinfo (INFO_MODULES);

        if (preg_match('/Server Root<\/b><\/td><td\s+align="left">([^<]*)</', ob_get_contents(), $m)) {
                $httpd_conf = $m[1] . '/' . $httpd_conf;
        }

        ob_end_clean();
*/

        print "<html><body>\n<h2><IMG SRC=\"img/tiki/Tiki_WCG.png\" ALT=\"\" BORDER=0><br /\>
	<font color='red'>Tiki Installer cannot proceed</font></h2>\n<pre>\n$errors";

        if (!isWindows()) {
                print "<br /><br />Your options:


1- With FTP access:
	a) Change the permissions (chmod) of the directories to 777.
	b) Create any missing directories
	c) <a href='tiki-install.php'>Execute the Tiki installer again</a> (Once you have executed these commands, this message will disappear!)

or

2- With shell (SSH) access, you can run the command below.

	a) To run setup.sh, follow the instructions:
		\$ cd $tikipath
		\$ sh setup.sh

		The script will offer you options depending on your server configuration.

	b) <a href='tiki-install.php'>Execute the Tiki installer again</a> (Once you have executed these commands, this message will disappear!)


<hr>
If you have problems accessing a directory, check the open_basedir entry in
$PHP_CONFIG_FILE_PATH/php.ini or $httpd_conf.

<hr>

<a href='http://doc.tiki.org/Installation' target='_blank'>Consult the tiki.org installation guide</a> if you need more help or <a href='http://tiki.org/tiki-forums.php' target='_blank'>visit the forums</a>

";
        }
	print "</pre></body></html>";
        exit;
}



// Try to see if we have an admin account
/**
 * @param $api_tiki
 * @return string
 */
function has_admin( $api_tiki )
{
	$query = "select hash from users_users where login='admin'";
	$res = false;

	$db = TikiDb::get();
	$result = $db->fetchAll($query);

	if (is_array($result)) {
		$res = reset($result);
	}

	if ( $res && isset( $res['hash'] ) ) {
		$admin_acc = 'y';
	} else {
		$admin_acc = 'n';
	}

	return $admin_acc;
}

/**
 * @param $dbTiki
 * @return bool
 */
function get_admin_email()
{
	global $installer;
	$query = "SELECT `email` FROM `users_users` WHERE `userId`=1";
	@$result = $installer->query($query);

	if ( $result && $res = $result->fetchRow() ) {
		return $res['email'];
	}

	return false;
}

/**
 * @param $dbTiki
 * @param $prefs
 * @return bool
 */
function update_preferences( &$prefs )
{
	global $installer;
	$query = "SELECT `name`, `value` FROM `tiki_preferences`";
	@$result = $installer->query($query);

	if ( $result ) {
		while ( $res = $result->fetchRow() ) {
			if ( ! isset($prefs[$res['name']]) ) {
				$prefs[$res['name']] = $res['value'];
			}
		}
		return true;
	}

	return false;
}

/**
 * @param $account
 */
function fix_admin_account( $account )
{
	global $installer;

	$result = $installer->query('SELECT `id` FROM `users_groups` WHERE `groupName` = "Admins"');
	if ( ! $row = $result->fetchRow() ) {
		$installer->query('INSERT INTO `users_groups` (`groupName`) VALUES("Admins")');
	}

	$installer->query('INSERT IGNORE INTO `users_grouppermissions` (`groupName`, `permName`) VALUES("Admins", "tiki_p_admin")');

	$result = $installer->query('SELECT `userId` FROM `users_users` WHERE `login` = ?', array( $account ));
	if ( $row = $result->fetchRow() ) {
		$id = $row['userId'];
		$installer->query('INSERT IGNORE INTO `users_usergroups` (`userId`, `groupName`) VALUES(?, "Admins")', array( $id ));
	}
}

/* possible error after upgrade 4 */
function fix_disable_accounts()
{
	global $installer;
	$installer->query('update `users_users` set `waiting`=NULL where `waiting` = ? and `valid` is NULL', array('a'));
}

/**
 * @return array
 */
function list_disable_accounts()
{
	global $installer;
	$result = $installer->query('select `login` from `users_users` where `waiting` = ? and `valid` is NULL', array('a'));
	$ret = array();
	while ($res = $result->fetchRow()) {
		$ret[] = $res['login'];
	}
	return $ret;
}

/**
 * @param $api
 * @param $driver
 * @param $host
 * @param $user
 * @param $pass
 * @param $dbname
 * @param $client_charset
 * @param $dbTiki
 * @return bool|int
 */
function initTikiDB( &$api, &$driver, $host, $user, $pass, $dbname, $client_charset, &$dbTiki )
{
	$initializer = new TikiDb_Initializer;
	$initializer->setPreferredConnector($driver);
	$initializer->setInitializeCallback(
		function ($db) {
			$db->setServerType('pdo');
			$db->setErrorHandler(new InstallerDatabaseErrorHandler);
		}
	);

	global $tikifeedback;
	$dbcon = false;
	try {
		$dbTiki = $initializer->getConnection(
			array(
				'host' => $host,
				'user' => $user,
				'pass' => $<PASSWORD>,
				'dbs' => $dbname,
				'charset' => $client_charset,
			)
		);
	} catch (Exception $e) {
		$tikifeedback[] = array( 'num' => 1, 'mes' => $e->getMessage() );
	}
	$dbcon = ! empty($dbTiki);

	// Attempt to create database. This might work if the $user has create database permissions.
	if ( ! $dbcon ) {
		// First first get a valid connection to the database
		try {
			$dbTiki = $initializer->getConnection(
				array(
					'host' => $host,
					'user' => $user,
					'pass' => $<PASSWORD>,
					//'dbs' => $dbname,
					'charset' => $client_charset,
				)
			);
		} catch (Exception $e) {
			$tikifeedback[] = array( 'num' => 1, 'mes' => $e->getMessage() );
		}
		$dbcon = ! empty($dbTiki);
		// First check that suggested database name will not cause issues
		$dbname_clean = preg_replace('/[^a-z0-9$_-]/', "", $dbname);
		if ($dbname_clean != $dbname) {
			$tikifeedback[] = array( 'num' => 1, 'mes'=> tra("Some invalid characters were detected in database name. Please use alphanumeric characters or _ or -.", '', false, array($dbname_clean)) );
			$dbcon = false;
		} else {
			$error = '';
			$sql="CREATE DATABASE IF NOT EXISTS `$dbname_clean` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
			$dbTiki->queryError($sql, $error);
			if ( empty($error) ) {
				$tikifeedback[] = array( 'num' => 0, 'mes'=> tra("Database `%0` was created.", '', false, array($dbname_clean)) );
			} else {
				$tikifeedback[] = array( 'num' => 1, 'mes'=> tra("Database `%0` creation failed. You need to create the database.", '', false, array($dbname_clean)) );
			}

			try {
				$dbTiki = $initializer->getConnection(
					array(
						'host' => $host,
						'user' => $user,
						'pass' => $pass,
						'dbs' => $dbname,
						'charset' => $client_charset,
					)
				);
				$dbcon = ! empty($dbTiki);
			} catch (Exception $e) {
				$tikifeedback[] = array( 'num' => 1, 'mes' => $e->getMessage() );
			}
		}
	}

	TikiDb::set($dbTiki);
<commit_msg>[bp/r48372][FIX] Installer: Handle access denied case for database connection. Thanks Arild<commit_after><?php
// (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

// To (re-)enable this script the file has to be named tiki-installer.php and the following four lines
// must start with two '/' and 'stopinstall:'. (Make sure there are no spaces inbetween // and stopinstall: !)

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
	header("location: index.php");
	exit;
}

require_once('tiki-filter-base.php');

// Define and load Smarty components
global $prefs;
$prefs = array();
$prefs['smarty_notice_reporting'] = 'n';
$prefs['smarty_compilation'] = 'always';
$prefs['smarty_security'] = 'y';
require_once 'lib/init/initlib.php';
set_error_handler("tiki_error_handling", error_reporting());
require_once ( 'lib/init/smarty.php');
require_once ('installer/installlib.php');

/**
 *
 */
class InstallerDatabaseErrorHandler implements TikiDb_ErrorHandler
{
    /**
     * @param TikiDb $db
     * @param $query
     * @param $values
     * @param $result
     */
    function handle(TikiDb $db, $query, $values, $result)
	{
	}
}

$dbTiki = false;
$commands = array();
@ini_set('magic_quotes_runtime', 0);

// tra() should not use $tikilib because this lib is not available in every steps of the installer
//  and because we want to be sure that translations of the installer are the original ones, even for an upgrade
$prefs['lang_use_db'] = 'n';

// Which step of the installer
if (empty($_REQUEST['install_step'])) {
	$install_step = '0';

	if (isset($_REQUEST['setdbversion'])) {
		// Sets dbversion_tiki when installing the WebDeploy package
		$db = fopen('db/'.$tikidomainslash.'local.php', 'a');
		require_once 'lib/setup/twversion.class.php';
		$TWV = new TWVersion();
		fwrite($db, "\n\$dbversion_tiki='" . $TWV->getBaseVersion() . "';\n");
		fclose($db);
	}
} else {
	$install_step = $_REQUEST['install_step'];

	if ($install_step == 3) {	// clear caches after system requirements page
		global $cachelib; include 'lib/cache/cachelib.php';
		$cachelib->empty_cache();
	}
}

// define the language to use, either from user-setting or default
if (!empty($_REQUEST['lang'])) {
	$language = $prefs['site_language'] = $prefs['language'] = $_REQUEST['lang'];
} else {
	$language = $prefs['site_language'] = $prefs['language'] = 'en';
}
include_once('lib/init/tra.php');

/**
 * @return bool
 */
function has_tiki_db()
{
	global $installer;
	return $installer->tableExists('users_users');
}

/**
 * @return bool
 */
function has_tiki_db_20()
{
	global $installer;
	return $installer->tableExists('tiki_pages_translation_bits');
}

/**
 * @param $dbb_tiki
 * @param $host_tiki
 * @param $user_tiki
 * @param $pass_tiki
 * @param $dbs_tiki
 * @param string $client_charset
 * @param string $api_tiki
 * @param string $dbversion_tiki
 */
function write_local_php($dbb_tiki, $host_tiki, $user_tiki, $pass_tiki, $dbs_tiki, $client_charset = '', $api_tiki = '', $dbversion_tiki = 'current')
{
	global $local;
	global $db_tiki;
	if ($dbs_tiki && $user_tiki) {
		$db_tiki = addslashes($dbb_tiki);
		$host_tiki = addslashes($host_tiki);
		$user_tiki = addslashes($user_tiki);
		$pass_tiki = addslashes($pass_tiki);
		$dbs_tiki = addslashes($dbs_tiki);
		$fw = fopen($local, 'w');
		$filetowrite = "<?php\n";
		$filetowrite .= "\$db_tiki='" . $db_tiki . "';\n";
		if ($dbversion_tiki == 'current') {
			require_once 'lib/setup/twversion.class.php';
			$twversion = new TWVersion();
			$dbversion_tiki = $twversion->getBaseVersion();
		}
		$filetowrite .= "\$dbversion_tiki='" . $dbversion_tiki . "';\n";
		$filetowrite .= "\$host_tiki='" . $host_tiki . "';\n";
		$filetowrite .= "\$user_tiki='" . $user_tiki . "';\n";
		$filetowrite .= "\$pass_tiki='" . $pass_tiki . "';\n";
		$filetowrite .= "\$dbs_tiki='" . $dbs_tiki . "';\n";
		if ( ! empty( $api_tiki ) ) {
			$filetowrite .= "\$api_tiki='" . $api_tiki . "';\n";
		}
		if ( ! empty( $client_charset ) ) {
			$filetowrite .= "\$client_charset='$client_charset';\n";
		}
		$filetowrite .= "// If you experience text encoding issues after updating (e.g. apostrophes etc showing up as strange characters) \n";
		$filetowrite .= "// \$client_charset='latin1';\n";
		$filetowrite .= "// \$client_charset='utf8';\n";
		$filetowrite .= "// See http://tiki.org/ReleaseNotes5.0#Known_Issues and http://doc.tiki.org/Understanding+Encoding for more info\n\n";
		$filetowrite .= "// If your php installation does not not have pdo extension\n";
		$filetowrite .= "// \$api_tiki = 'adodb';\n\n";
		$filetowrite .= "// Want configurations managed at the system level or restrict some preferences? http://doc.tiki.org/System+Configuration\n";
		$filetowrite .= "// \$system_configuration_file = '/etc/tiki.ini';\n";
		$filetowrite .= "// \$system_configuration_identifier = 'example.com';\n\n";
		fwrite($fw, $filetowrite);
		fclose($fw);
	}
}

/**
 * @param string $domain
 * @return string
 */
function create_dirs($domain='')
{
	global $tikipath;
	$dirs=array(
		'db',
		'dump',
		'img/wiki',
		'img/wiki_up',
		'img/trackers',
		'modules/cache',
		'temp',
		'temp/cache',
		'templates_c',
		'templates',
		'styles',
		'whelp');

	$ret = "";
	foreach ($dirs as $dir) {
		$dir = $dir.'/'.$domain;

		if (!is_dir($dir)) {
			$created = @mkdir($dir, 02775); // Try creating the directory
			if (!$created) {
				$ret .= "The directory '$tikipath$dir' could not be created.\n";
			}
		} else if (!TikiInit::is_writeable($dir)) {
			@chmod($dir, 02775);
			if (!TikiInit::is_writeable($dir)) {
				$ret .= "The directory '$tikipath$dir' is not writeable.\n";
			}
		}
	}
	return $ret;
}

/**
 * @return bool
 */
function isWindows()
{
	static $windows;

	if (!isset($windows)) {
		$windows = substr(PHP_OS, 0, 3) == 'WIN';
	}

	return $windows;
}

function check_session_save_path()
{
	global $errors;
	if (ini_get('session.save_handler') == 'files') {
        	$save_path = ini_get('session.save_path');
		// check if we can check it. The session.save_path can be outside
		// the open_basedir paths.
		$open_basedir=ini_get('open_basedir');
		if (empty($open_basedir)) {
        		if (!is_dir($save_path)) {
                		$errors .= "The directory '$save_path' does not exist or PHP is not allowed to access it (check open_basedir entry in php.ini).\n";
        		} else if (!TikiInit::is_writeable($save_path)) {
                		$errors .= "The directory '$save_path' is not writeable.\n";
        		}
		}

        	if ($errors) {
                	$save_path = TikiInit::tempdir();

                	if (is_dir($save_path) && TikiInit::is_writeable($save_path)) {
                        	ini_set('session.save_path', $save_path);

                        	$errors = '';
                	}
        	}
	}
}

function get_webserver_uid()
{
	global $wwwuser;
	global $wwwgroup;
	$wwwuser = '';
	$wwwgroup = '';

	if (isWindows()) {
        	$wwwuser = 'SYSTEM';

        	$wwwgroup = 'SYSTEM';
	}

	if (function_exists('posix_getuid')) {
        	$user = @posix_getpwuid(@posix_getuid());

        	$group = @posix_getpwuid(@posix_getgid());
        	$wwwuser = $user ? $user['name'] : false;
        	$wwwgroup = $group ? $group['name'] : false;
	}

	if (!$wwwuser) {
        	$wwwuser = 'nobody (or the user account the web server is running under)';
	}

	if (!$wwwgroup) {
        	$wwwgroup = 'nobody (or the group account the web server is running under)';
	}
}

function error_and_exit()
{
	global $errors, $tikipath;

        $PHP_CONFIG_FILE_PATH = PHP_CONFIG_FILE_PATH;

        $httpd_conf = 'httpd.conf';
/*
        ob_start();
        phpinfo (INFO_MODULES);

        if (preg_match('/Server Root<\/b><\/td><td\s+align="left">([^<]*)</', ob_get_contents(), $m)) {
                $httpd_conf = $m[1] . '/' . $httpd_conf;
        }

        ob_end_clean();
*/

        print "<html><body>\n<h2><IMG SRC=\"img/tiki/Tiki_WCG.png\" ALT=\"\" BORDER=0><br /\>
	<font color='red'>Tiki Installer cannot proceed</font></h2>\n<pre>\n$errors";

        if (!isWindows()) {
                print "<br /><br />Your options:


1- With FTP access:
	a) Change the permissions (chmod) of the directories to 777.
	b) Create any missing directories
	c) <a href='tiki-install.php'>Execute the Tiki installer again</a> (Once you have executed these commands, this message will disappear!)

or

2- With shell (SSH) access, you can run the command below.

	a) To run setup.sh, follow the instructions:
		\$ cd $tikipath
		\$ sh setup.sh

		The script will offer you options depending on your server configuration.

	b) <a href='tiki-install.php'>Execute the Tiki installer again</a> (Once you have executed these commands, this message will disappear!)


<hr>
If you have problems accessing a directory, check the open_basedir entry in
$PHP_CONFIG_FILE_PATH/php.ini or $httpd_conf.

<hr>

<a href='http://doc.tiki.org/Installation' target='_blank'>Consult the tiki.org installation guide</a> if you need more help or <a href='http://tiki.org/tiki-forums.php' target='_blank'>visit the forums</a>

";
        }
	print "</pre></body></html>";
        exit;
}



// Try to see if we have an admin account
/**
 * @param $api_tiki
 * @return string
 */
function has_admin( $api_tiki )
{
	$query = "select hash from users_users where login='admin'";
	$res = false;

	$db = TikiDb::get();
	$result = $db->fetchAll($query);

	if (is_array($result)) {
		$res = reset($result);
	}

	if ( $res && isset( $res['hash'] ) ) {
		$admin_acc = 'y';
	} else {
		$admin_acc = 'n';
	}

	return $admin_acc;
}

/**
 * @param $dbTiki
 * @return bool
 */
function get_admin_email()
{
	global $installer;
	$query = "SELECT `email` FROM `users_users` WHERE `userId`=1";
	@$result = $installer->query($query);

	if ( $result && $res = $result->fetchRow() ) {
		return $res['email'];
	}

	return false;
}

/**
 * @param $dbTiki
 * @param $prefs
 * @return bool
 */
function update_preferences( &$prefs )
{
	global $installer;
	$query = "SELECT `name`, `value` FROM `tiki_preferences`";
	@$result = $installer->query($query);

	if ( $result ) {
		while ( $res = $result->fetchRow() ) {
			if ( ! isset($prefs[$res['name']]) ) {
				$prefs[$res['name']] = $res['value'];
			}
		}
		return true;
	}

	return false;
}

/**
 * @param $account
 */
function fix_admin_account( $account )
{
	global $installer;

	$result = $installer->query('SELECT `id` FROM `users_groups` WHERE `groupName` = "Admins"');
	if ( ! $row = $result->fetchRow() ) {
		$installer->query('INSERT INTO `users_groups` (`groupName`) VALUES("Admins")');
	}

	$installer->query('INSERT IGNORE INTO `users_grouppermissions` (`groupName`, `permName`) VALUES("Admins", "tiki_p_admin")');

	$result = $installer->query('SELECT `userId` FROM `users_users` WHERE `login` = ?', array( $account ));
	if ( $row = $result->fetchRow() ) {
		$id = $row['userId'];
		$installer->query('INSERT IGNORE INTO `users_usergroups` (`userId`, `groupName`) VALUES(?, "Admins")', array( $id ));
	}
}

/* possible error after upgrade 4 */
function fix_disable_accounts()
{
	global $installer;
	$installer->query('update `users_users` set `waiting`=NULL where `waiting` = ? and `valid` is NULL', array('a'));
}

/**
 * @return array
 */
function list_disable_accounts()
{
	global $installer;
	$result = $installer->query('select `login` from `users_users` where `waiting` = ? and `valid` is NULL', array('a'));
	$ret = array();
	while ($res = $result->fetchRow()) {
		$ret[] = $res['login'];
	}
	return $ret;
}

/**
 * @param $api
 * @param $driver
 * @param $host
 * @param $user
 * @param $pass
 * @param $dbname
 * @param $client_charset
 * @param $dbTiki
 * @return bool|int
 */
function initTikiDB( &$api, &$driver, $host, $user, $pass, $dbname, $client_charset, &$dbTiki )
{
	$initializer = new TikiDb_Initializer;
	$initializer->setPreferredConnector($driver);
	$initializer->setInitializeCallback(
		function ($db) {
			$db->setServerType('pdo');
			$db->setErrorHandler(new InstallerDatabaseErrorHandler);
		}
	);

	global $tikifeedback;
	$dbcon = false;
	try {
		$dbTiki = $initializer->getConnection(
			array(
				'host' => $host,
				'user' => $user,
				'pass' => $pass,
				'dbs' => $dbname,
				'charset' => $client_charset,
			)
		);
	} catch (Exception $e) {
		$tikifeedback[] = array( 'num' => 1, 'mes' => $e->getMessage() );
	}
	$dbcon = ! empty($dbTiki);

	// Attempt to create database. This might work if the $user has create database permissions.
	if ( ! $dbcon ) {
		// First first get a valid connection to the database
		try {
			$dbTiki = $initializer->getConnection(
				array(
					'host' => $host,
					'user' => $user,
					'pass' => $pass,
					//'dbs' => $dbname,
					'charset' => $client_charset,
				)
			);
		} catch (Exception $e) {
			$tikifeedback[] = array( 'num' => 1, 'mes' => $e->getMessage() );
		}
		$dbcon = ! empty($dbTiki);
		// First check that suggested database name will not cause issues
		$dbname_clean = preg_replace('/[^a-z0-9$_-]/', "", $dbname);
		if ($dbname_clean != $dbname) {
			$tikifeedback[] = array( 'num' => 1, 'mes'=> tra("Some invalid characters were detected in database name. Please use alphanumeric characters or _ or -.", '', false, array($dbname_clean)) );
			$dbcon = false;
		} elseif ($dbcon) {
			$error = '';
			$sql="CREATE DATABASE IF NOT EXISTS `$dbname_clean` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
			$dbTiki->queryError($sql, $error);
			if ( empty($error) ) {
				$tikifeedback[] = array( 'num' => 0, 'mes'=> tra("Database `%0` was created.", '', false, array($dbname_clean)) );
			} else {
				$tikifeedback[] = array( 'num' => 1, 'mes'=> tra("Database `%0` creation failed. You need to create the database.", '', false, array($dbname_clean)) );
			}

			try {
				$dbTiki = $initializer->getConnection(
					array(
							'host' => $host,
							'user' => $user,
							'pass' => $<PASSWORD>,
							'dbs' => $dbname,
							'charset' => $client_charset,
							)
						);
				$dbcon = ! empty($dbTiki);
			} catch (Exception $e) {
				$tikifeedback[] = array( 'num' => 1, 'mes' => $e->getMessage() );
			}
		} else {
			$tikifeedback[] = array( 'num' => 1, 'mes'=> tra("Database `%0`. Unable to connect to database.", '', false, array($dbname_clean)) );
		}
	}

	if (isset($dbTiki)) {
		TikiDb::set($dbTiki);
	}
	
{'fraction_non_alphanumeric': 0.18104285119955624, 'fraction_numerical': 0.0038482873387879627, 'mean_word_length': 3.5851216022889845, 'pattern_counts': {'":': 0, '<': 68, '<?xml version=': 0, '>': 178, 'https://': 0, 'lorem ipsum': 0, 'www.': 24, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7459220', 'n_tokens_mistral': 11135, 'n_tokens_neox': 10300, 'n_words': 2482}