install/includes/payload.php
changeset 1227 bdac73ed481e
parent 1175 1e2c9819ede3
child 1240 2b6cdff92b09
equal deleted inserted replaced
1226:de56132c008d 1227:bdac73ed481e
    12  * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
    12  * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
    13  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
    13  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
    14  */
    14  */
    15 
    15 
    16 if ( !defined('IN_ENANO_INSTALL') )
    16 if ( !defined('IN_ENANO_INSTALL') )
    17   die();
    17 	die();
    18 
    18 
    19 return true;
    19 return true;
    20 
    20 
    21 function stg_sim_good()
    21 function stg_sim_good()
    22 {
    22 {
    23   return true;
    23 	return true;
    24 }
    24 }
    25 
    25 
    26 function stg_sim_bad()
    26 function stg_sim_bad()
    27 {
    27 {
    28   return true;
    28 	return true;
    29 }
    29 }
    30 
    30 
    31 function stg_password_decode()
    31 function stg_password_decode()
    32 {
    32 {
    33   global $db;
    33 	global $db;
    34   static $pass = false;
    34 	static $pass = false;
    35   
    35 	
    36   if ( $pass )
    36 	if ( $pass )
    37     return $pass;
    37 		return $pass;
    38   
    38 	
    39   if ( !isset($_POST['crypt_data']) && !empty($_POST['password']) && $_POST['password'] === $_POST['password_confirm'] )
    39 	if ( !isset($_POST['crypt_data']) && !empty($_POST['password']) && $_POST['password'] === $_POST['password_confirm'] )
    40     $pass = $_POST['password'];
    40 		$pass = $_POST['password'];
    41   
    41 	
    42   $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
    42 	$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
    43   // retrieve encryption key
    43 	// retrieve encryption key
    44   $q = $db->sql_query('SELECT config_value FROM ' . table_prefix . 'config WHERE config_name=\'install_aes_key\';');
    44 	$q = $db->sql_query('SELECT config_value FROM ' . table_prefix . 'config WHERE config_name=\'install_aes_key\';');
    45   if ( !$q )
    45 	if ( !$q )
    46     $db->_die();
    46 		$db->_die();
    47   if ( $db->numrows() < 1 )
    47 	if ( $db->numrows() < 1 )
    48     return false;
    48 		return false;
    49   list($aes_key) = $db->fetchrow_num();
    49 	list($aes_key) = $db->fetchrow_num();
    50   $aes_key = hexdecode($aes_key);
    50 	$aes_key = hexdecode($aes_key);
    51   
    51 	
    52   $pass = $aes->decrypt($_POST['crypt_data'], $aes_key, ENC_HEX);
    52 	$pass = $aes->decrypt($_POST['crypt_data'], $aes_key, ENC_HEX);
    53   if ( !$pass )
    53 	if ( !$pass )
    54     return false;
    54 		return false;
    55   
    55 	
    56   return $pass; // Will be true if the password isn't crapped
    56 	return $pass; // Will be true if the password isn't crapped
    57 }
    57 }
    58 
    58 
    59 function stg_make_private_key()
    59 function stg_make_private_key()
    60 {
    60 {
    61   global $db;
    61 	global $db;
    62   static $site_key = false;
    62 	static $site_key = false;
    63   
    63 	
    64   if ( $site_key )
    64 	if ( $site_key )
    65     return $site_key;
    65 		return $site_key;
    66   
    66 	
    67   // Is there already a key cached in the database?
    67 	// Is there already a key cached in the database?
    68   $q = $db->sql_query('SELECT config_value FROM ' . table_prefix . 'config WHERE config_name=\'site_aes_key\';');
    68 	$q = $db->sql_query('SELECT config_value FROM ' . table_prefix . 'config WHERE config_name=\'site_aes_key\';');
    69   if ( !$q )
    69 	if ( !$q )
    70     $db->_die();
    70 		$db->_die();
    71   
    71 	
    72   if ( $db->numrows() > 0 )
    72 	if ( $db->numrows() > 0 )
    73   {
    73 	{
    74     list($site_key) = $db->fetchrow_num();
    74 		list($site_key) = $db->fetchrow_num();
    75     $db->free_result();
    75 		$db->free_result();
    76     return $site_key;
    76 		return $site_key;
    77   }
    77 	}
    78   
    78 	
    79   $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
    79 	$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
    80   // This will use /dev/urandom if possible
    80 	// This will use /dev/urandom if possible
    81   $site_key = $aes->gen_readymade_key();
    81 	$site_key = $aes->gen_readymade_key();
    82   
    82 	
    83   // Stash it in the database, don't check for errors though because we can always regenerate it
    83 	// Stash it in the database, don't check for errors though because we can always regenerate it
    84   $db->sql_query('INSERT INTO ' . table_prefix . 'config ( config_name, config_value ) VALUES ( \'site_aes_key\', \'' . $site_key . '\' );');
    84 	$db->sql_query('INSERT INTO ' . table_prefix . 'config ( config_name, config_value ) VALUES ( \'site_aes_key\', \'' . $site_key . '\' );');
    85   
    85 	
    86   return $site_key;
    86 	return $site_key;
    87 }
    87 }
    88 
    88 
    89 function stg_load_schema()
    89 function stg_load_schema()
    90 {
    90 {
    91   global $db, $dbdriver, $installer_version, $lang_id, $languages;
    91 	global $db, $dbdriver, $installer_version, $lang_id, $languages;
    92   static $sql_parser = false;
    92 	static $sql_parser = false;
    93   
    93 	
    94   if ( is_object($sql_parser) )
    94 	if ( is_object($sql_parser) )
    95     return $sql_parser->parse();
    95 		return $sql_parser->parse();
    96   
    96 	
    97   $aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
    97 	$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
    98   $hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
    98 	$hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
    99   
    99 	
   100   $site_key = stg_make_private_key();
   100 	$site_key = stg_make_private_key();
   101   $site_key = hexdecode($site_key);
   101 	$site_key = hexdecode($site_key);
   102   $admin_pass_clean = stg_password_decode();
   102 	$admin_pass_clean = stg_password_decode();
   103   $admin_pass = hmac_sha1($admin_pass_clean, $hmac_secret);
   103 	$admin_pass = hmac_sha1($admin_pass_clean, $hmac_secret);
   104   
   104 	
   105   unset($admin_pass_clean); // Security
   105 	unset($admin_pass_clean); // Security
   106   
   106 	
   107   try
   107 	try
   108   {
   108 	{
   109     $sql_parser = new SQL_Parser( ENANO_ROOT . "/install/schemas/{$dbdriver}_stage2.sql" );
   109 		$sql_parser = new SQL_Parser( ENANO_ROOT . "/install/schemas/{$dbdriver}_stage2.sql" );
   110   }
   110 	}
   111   catch ( Exception $e )
   111 	catch ( Exception $e )
   112   {
   112 	{
   113     echo "<pre>$e</pre>";
   113 		echo "<pre>$e</pre>";
   114     return false;
   114 		return false;
   115   }
   115 	}
   116   
   116 	
   117   $vars = array(
   117 	$vars = array(
   118       'TABLE_PREFIX'         => table_prefix,
   118 			'TABLE_PREFIX'         => table_prefix,
   119       'SITE_NAME'            => $db->escape($_POST['site_name']),
   119 			'SITE_NAME'            => $db->escape($_POST['site_name']),
   120       'SITE_DESC'            => $db->escape($_POST['site_desc']),
   120 			'SITE_DESC'            => $db->escape($_POST['site_desc']),
   121       'COPYRIGHT'            => $db->escape($_POST['copyright']),
   121 			'COPYRIGHT'            => $db->escape($_POST['copyright']),
   122       // FIXME: update form
   122 			// FIXME: update form
   123       'WIKI_MODE'            => ( isset($_POST['wiki_mode']) ? '1' : '0' ),
   123 			'WIKI_MODE'            => ( isset($_POST['wiki_mode']) ? '1' : '0' ),
   124       'ENABLE_CACHE'         => ( is_writable( ENANO_ROOT . '/cache/' ) ? '1' : '0' ),
   124 			'ENABLE_CACHE'         => ( is_writable( ENANO_ROOT . '/cache/' ) ? '1' : '0' ),
   125       'VERSION'              => $installer_version['version'],
   125 			'VERSION'              => $installer_version['version'],
   126       'ADMIN_USER'           => $db->escape($_POST['username']),
   126 			'ADMIN_USER'           => $db->escape($_POST['username']),
   127       'ADMIN_PASS'           => $admin_pass,
   127 			'ADMIN_PASS'           => $admin_pass,
   128       'ADMIN_PASS_SALT'      => $hmac_secret,
   128 			'ADMIN_PASS_SALT'      => $hmac_secret,
   129       'ADMIN_EMAIL'          => $db->escape($_POST['email']),
   129 			'ADMIN_EMAIL'          => $db->escape($_POST['email']),
   130       'REAL_NAME'            => '', // This has always been stubbed.
   130 			'REAL_NAME'            => '', // This has always been stubbed.
   131       'ADMIN_EMBED_PHP'      => strval(AUTH_DISALLOW),
   131 			'ADMIN_EMBED_PHP'      => strval(AUTH_DISALLOW),
   132       'UNIX_TIME'            => strval(time()),
   132 			'UNIX_TIME'            => strval(time()),
   133       'IP_ADDRESS'           => $db->escape($_SERVER['REMOTE_ADDR'])
   133 			'IP_ADDRESS'           => $db->escape($_SERVER['REMOTE_ADDR'])
   134     );
   134 		);
   135   
   135 	
   136   $sql_parser->assign_vars($vars);
   136 	$sql_parser->assign_vars($vars);
   137   return true;
   137 	return true;
   138 }
   138 }
   139 
   139 
   140 function stg_deliver_payload()
   140 function stg_deliver_payload()
   141 {
   141 {
   142   global $db;
   142 	global $db;
   143   $schema = stg_load_schema();
   143 	$schema = stg_load_schema();
   144   foreach ( $schema as $sql )
   144 	foreach ( $schema as $sql )
   145   {
   145 	{
   146     if ( !$db->sql_query($sql) )
   146 		if ( !$db->sql_query($sql) )
   147     {
   147 		{
   148       echo $db->get_error();
   148 			echo $db->get_error();
   149       return false;
   149 			return false;
   150     }
   150 		}
   151   }
   151 	}
   152   return true;
   152 	return true;
   153 }
   153 }
   154 
   154 
   155 function stg_write_config()
   155 function stg_write_config()
   156 {
   156 {
   157   global $dbhost, $dbuser, $dbpasswd, $dbname, $dbdriver, $dbport;
   157 	global $dbhost, $dbuser, $dbpasswd, $dbname, $dbdriver, $dbport;
   158   $db_data = array(
   158 	$db_data = array(
   159       'host' => str_replace("'", "\\'", $dbhost),
   159 			'host' => str_replace("'", "\\'", $dbhost),
   160       'user' => str_replace("'", "\\'", $dbuser),
   160 			'user' => str_replace("'", "\\'", $dbuser),
   161       'pass' => str_replace("'", "\\'", $dbpasswd),
   161 			'pass' => str_replace("'", "\\'", $dbpasswd),
   162       'name' => str_replace("'", "\\'", $dbname),
   162 			'name' => str_replace("'", "\\'", $dbname),
   163       'port' => intval($dbport),
   163 			'port' => intval($dbport),
   164       'tp' => table_prefix,
   164 			'tp' => table_prefix,
   165       'drv' => $dbdriver
   165 			'drv' => $dbdriver
   166     );
   166 		);
   167   
   167 	
   168   // Retrieves the existing key
   168 	// Retrieves the existing key
   169   $site_key = stg_make_private_key();
   169 	$site_key = stg_make_private_key();
   170   
   170 	
   171   // Determine contentPath
   171 	// Determine contentPath
   172   switch ( @$_POST['url_scheme'] )
   172 	switch ( @$_POST['url_scheme'] )
   173   {
   173 	{
   174     case 'standard':
   174 		case 'standard':
   175     default:
   175 		default:
   176       $sp_append = '/index.php?title=';
   176 			$sp_append = '/index.php?title=';
   177       break;
   177 			break;
   178     case 'shortened':
   178 		case 'shortened':
   179       $sp_append = '/index.php/';
   179 			$sp_append = '/index.php/';
   180       break;
   180 			break;
   181     case 'tiny':
   181 		case 'tiny':
   182       $sp_append = '/?/';
   182 			$sp_append = '/?/';
   183       break;
   183 			break;
   184     case 'rewrite':
   184 		case 'rewrite':
   185       $sp_append = '/';
   185 			$sp_append = '/';
   186       break;
   186 			break;
   187   }
   187 	}
   188   
   188 	
   189   $scriptpath = scriptPath;
   189 	$scriptpath = scriptPath;
   190   $contentpath = $scriptpath . $sp_append;
   190 	$contentpath = $scriptpath . $sp_append;
   191   
   191 	
   192   $config_file = <<<EOF
   192 	$config_file = <<<EOF
   193 <?php
   193 <?php
   194 
   194 
   195 /**
   195 /**
   196  * Enano site configuration
   196  * Enano site configuration
   197  * NOTE ON EDITING: You should almost never need to change anything in this
   197  * NOTE ON EDITING: You should almost never need to change anything in this
   225 //
   225 //
   226 
   226 
   227 // if they're already defined, no use re-defining them
   227 // if they're already defined, no use re-defining them
   228 if ( !defined('ENANO_CONSTANTS') )
   228 if ( !defined('ENANO_CONSTANTS') )
   229 {
   229 {
   230   // The prefix for the tables in the database. Useful for holding more than
   230 	// The prefix for the tables in the database. Useful for holding more than
   231   // one Enano installation in the same database.
   231 	// one Enano installation in the same database.
   232   define('table_prefix', '{$db_data['tp']}');
   232 	define('table_prefix', '{$db_data['tp']}');
   233   
   233 	
   234   // The path to Enano's files on your server, from the document root. If
   234 	// The path to Enano's files on your server, from the document root. If
   235   // Enano is installed in your document root this will be blank; installing
   235 	// Enano is installed in your document root this will be blank; installing
   236   // Enano in /enano/ will result in "/enano" here, etc.
   236 	// Enano in /enano/ will result in "/enano" here, etc.
   237   define('scriptPath', '$scriptpath');
   237 	define('scriptPath', '$scriptpath');
   238   
   238 	
   239   // The authoritative prefix for pages. This should be very literal: to
   239 	// The authoritative prefix for pages. This should be very literal: to
   240   // generate a URL on the site, the format is basically
   240 	// generate a URL on the site, the format is basically
   241   // contentPath . \$page_name. This is based off of scriptPath and the URL
   241 	// contentPath . \$page_name. This is based off of scriptPath and the URL
   242   // scheme selected during installation. Pattern:
   242 	// scheme selected during installation. Pattern:
   243   //
   243 	//
   244   //    * Standard URLs:  scriptPath . '/index.php?title='
   244 	//    * Standard URLs:  scriptPath . '/index.php?title='
   245   //    * Shortened URLs: scriptPath . '/index.php/'
   245 	//    * Shortened URLs: scriptPath . '/index.php/'
   246   //    * mod_rewrite:    scriptPath . '/'
   246 	//    * mod_rewrite:    scriptPath . '/'
   247   
   247 	
   248   define('contentPath', '$contentpath');
   248 	define('contentPath', '$contentpath');
   249   
   249 	
   250   // Tell the Enano API that we're installed and that this file is complete
   250 	// Tell the Enano API that we're installed and that this file is complete
   251   define('ENANO_INSTALLED', 'You bet!');
   251 	define('ENANO_INSTALLED', 'You bet!');
   252   
   252 	
   253   define('ENANO_CONSTANTS', '');
   253 	define('ENANO_CONSTANTS', '');
   254 }
   254 }
   255 
   255 
   256 // The AES encryption key used for encrypting various bits of information,
   256 // The AES encryption key used for encrypting various bits of information,
   257 // such as cookies, that should not be editable by users. Read about
   257 // such as cookies, that should not be editable by users. Read about
   258 // Enano's security model at:
   258 // Enano's security model at:
   260 // This key was at one point used for passwords as well, but this is no
   260 // This key was at one point used for passwords as well, but this is no
   261 // longer true.
   261 // longer true.
   262 \$crypto_key = '$site_key';
   262 \$crypto_key = '$site_key';
   263 
   263 
   264 EOF;
   264 EOF;
   265   
   265 	
   266   // Write config file
   266 	// Write config file
   267   
   267 	
   268   $ch = @fopen ( ENANO_ROOT . '/config.new.php', 'w' );
   268 	$ch = @fopen ( ENANO_ROOT . '/config.new.php', 'w' );
   269   if ( !$ch )
   269 	if ( !$ch )
   270     return false;
   270 		return false;
   271   
   271 	
   272   fwrite($ch, $config_file);
   272 	fwrite($ch, $config_file);
   273   fclose($ch);
   273 	fclose($ch);
   274   
   274 	
   275   // If we are using mod_rewrite, also append any existing .htaccess
   275 	// If we are using mod_rewrite, also append any existing .htaccess
   276   if ( @$_POST['url_scheme'] === 'rewrite' )
   276 	if ( @$_POST['url_scheme'] === 'rewrite' )
   277   {
   277 	{
   278     $hh = @fopen ( ENANO_ROOT . '/.htaccess.new', 'w' );
   278 		$hh = @fopen ( ENANO_ROOT . '/.htaccess.new', 'w' );
   279     if ( !$hh )
   279 		if ( !$hh )
   280       return false;
   280 			return false;
   281     $hhc = <<<EOF
   281 		$hhc = <<<EOF
   282 #
   282 #
   283 # START ENANO RULES
   283 # START ENANO RULES
   284 #
   284 #
   285 
   285 
   286 # Enable mod_rewrite
   286 # Enable mod_rewrite
   295 
   295 
   296 # Main rule - short and sweet
   296 # Main rule - short and sweet
   297 RewriteRule (.*) index.php?title=\$1 [L,QSA]
   297 RewriteRule (.*) index.php?title=\$1 [L,QSA]
   298 
   298 
   299 EOF;
   299 EOF;
   300     fwrite($hh, $hhc);
   300 		fwrite($hh, $hhc);
   301     fclose($hh);
   301 		fclose($hh);
   302   }
   302 	}
   303   
   303 	
   304   return true;
   304 	return true;
   305 }
   305 }
   306 
   306 
   307 function stg_language_setup()
   307 function stg_language_setup()
   308 {
   308 {
   309   global $languages, $db;
   309 	global $languages, $db;
   310   global $lang_id;
   310 	global $lang_id;
   311   $lang_info =& $languages[$lang_id];
   311 	$lang_info =& $languages[$lang_id];
   312   if ( !is_array($lang_info) )
   312 	if ( !is_array($lang_info) )
   313     return false;
   313 		return false;
   314   
   314 	
   315   // Install the language
   315 	// Install the language
   316   // ($lang_code, $lang_name_neutral, $lang_name_local, $lang_file = false)
   316 	// ($lang_code, $lang_name_neutral, $lang_name_local, $lang_file = false)
   317   $result = install_language($lang_id, $lang_info['name_eng'], $lang_info['name'], ENANO_ROOT . "/language/{$lang_info['dir']}/core.json");
   317 	$result = install_language($lang_id, $lang_info['name_eng'], $lang_info['name'], ENANO_ROOT . "/language/{$lang_info['dir']}/core.json");
   318   if ( !$result )
   318 	if ( !$result )
   319     return false;
   319 		return false;
   320   
   320 	
   321   $lang_local = new Language($lang_id);
   321 	$lang_local = new Language($lang_id);
   322   
   322 	
   323   $lang_local->import( ENANO_ROOT . "/language/{$lang_info['dir']}/user.json" );
   323 	$lang_local->import( ENANO_ROOT . "/language/{$lang_info['dir']}/user.json" );
   324   $lang_local->import( ENANO_ROOT . "/language/{$lang_info['dir']}/tools.json" );
   324 	$lang_local->import( ENANO_ROOT . "/language/{$lang_info['dir']}/tools.json" );
   325   $lang_local->import( ENANO_ROOT . "/language/{$lang_info['dir']}/admin.json" );
   325 	$lang_local->import( ENANO_ROOT . "/language/{$lang_info['dir']}/admin.json" );
   326   
   326 	
   327   $q = $db->sql_query('SELECT lang_id FROM ' . table_prefix . 'language ORDER BY lang_id DESC LIMIT 1;');
   327 	$q = $db->sql_query('SELECT lang_id FROM ' . table_prefix . 'language ORDER BY lang_id DESC LIMIT 1;');
   328   if ( !$q )
   328 	if ( !$q )
   329     $db->_die();
   329 		$db->_die();
   330   
   330 	
   331   list($lang_id_int) = $db->fetchrow_num();
   331 	list($lang_id_int) = $db->fetchrow_num();
   332   $db->free_result();
   332 	$db->free_result();
   333   setConfig('default_language', $lang_id_int);
   333 	setConfig('default_language', $lang_id_int);
   334   
   334 	
   335   return true;
   335 	return true;
   336 }
   336 }
   337 
   337 
   338 function stg_add_content()
   338 function stg_add_content()
   339 {
   339 {
   340   global $db, $session, $paths, $template, $plugins; // Common objects
   340 	global $db, $session, $paths, $template, $plugins; // Common objects
   341   global $cache;
   341 	global $cache;
   342   
   342 	
   343   global $languages;
   343 	global $languages;
   344   global $lang_id;
   344 	global $lang_id;
   345   $lang_info =& $languages[$lang_id];
   345 	$lang_info =& $languages[$lang_id];
   346   if ( !is_array($lang_info) )
   346 	if ( !is_array($lang_info) )
   347     return false;
   347 		return false;
   348   
   348 	
   349   if ( $_POST['default_content_type'] === 'tutorial' )
   349 	if ( $_POST['default_content_type'] === 'tutorial' )
   350   {
   350 	{
   351     $dir = ENANO_ROOT . "/language/{$lang_info['dir']}/install/default-tutorial";
   351 		$dir = ENANO_ROOT . "/language/{$lang_info['dir']}/install/default-tutorial";
   352   }
   352 	}
   353   else
   353 	else
   354   {
   354 	{
   355     $dir = ENANO_ROOT . "/language/{$lang_info['dir']}/install/default-blank";
   355 		$dir = ENANO_ROOT . "/language/{$lang_info['dir']}/install/default-blank";
   356   }
   356 	}
   357   
   357 	
   358   if ( !$dr = @opendir($dir) )
   358 	if ( !$dr = @opendir($dir) )
   359     return false;
   359 		return false;
   360   
   360 	
   361   while ( $dh = @readdir($dr) )
   361 	while ( $dh = @readdir($dr) )
   362   {
   362 	{
   363     if ( !preg_match('/\.txt$/', $dh) )
   363 		if ( !preg_match('/\.txt$/', $dh) )
   364       continue;
   364 			continue;
   365     
   365 		
   366     $page_contents = @file_get_contents("$dir/$dh");
   366 		$page_contents = @file_get_contents("$dir/$dh");
   367     if ( empty($page_contents) )
   367 		if ( empty($page_contents) )
   368       return false;
   368 			return false;
   369     
   369 		
   370     $page_name = preg_replace('/\.txt$/', '', $dh);
   370 		$page_name = preg_replace('/\.txt$/', '', $dh);
   371     
   371 		
   372     if ( !install_primitive_page_creator($page_name, 'Article', $page_contents) )
   372 		if ( !install_primitive_page_creator($page_name, 'Article', $page_contents) )
   373       return false;
   373 			return false;
   374   }
   374 	}
   375   
   375 	
   376   closedir($dr);
   376 	closedir($dr);
   377   
   377 	
   378   $cache->purge('page_meta');
   378 	$cache->purge('page_meta');
   379   
   379 	
   380   return true;
   380 	return true;
   381 }
   381 }
   382 
   382 
   383 function install_primitive_page_creator($page_id, $namespace, $content)
   383 function install_primitive_page_creator($page_id, $namespace, $content)
   384 {
   384 {
   385   global $db, $session, $paths, $template, $plugins; // Common objects
   385 	global $db, $session, $paths, $template, $plugins; // Common objects
   386   
   386 	
   387   $page_title = $db->escape(str_replace('_', ' ', dirtify_page_id($page_id)));
   387 	$page_title = $db->escape(str_replace('_', ' ', dirtify_page_id($page_id)));
   388   $author = $db->escape($_POST['username']);
   388 	$author = $db->escape($_POST['username']);
   389   $page_id = $db->escape($page_id);
   389 	$page_id = $db->escape($page_id);
   390   $namespace = $db->escape($namespace);
   390 	$namespace = $db->escape($namespace);
   391   // yes, we do probably want strip_all_php ON.
   391 	// yes, we do probably want strip_all_php ON.
   392   $content = RenderMan::preprocess_text($content, true, true);
   392 	$content = RenderMan::preprocess_text($content, true, true);
   393   $now = time();
   393 	$now = time();
   394   
   394 	
   395   // query 1: logs
   395 	// query 1: logs
   396   $q = $db->sql_query('INSERT INTO ' . table_prefix . "logs(time_id, date_string, log_type, action, page_id, namespace, author, page_text) VALUES\n"
   396 	$q = $db->sql_query('INSERT INTO ' . table_prefix . "logs(time_id, date_string, log_type, action, page_id, namespace, author, page_text) VALUES\n"
   397                     . "  ( $now, 'DEPRECATED', 'page', 'edit', '$page_id', '$namespace', '$author', '$content');");
   397 										. "  ( $now, 'DEPRECATED', 'page', 'edit', '$page_id', '$namespace', '$author', '$content');");
   398   if ( !$q )
   398 	if ( !$q )
   399   {
   399 	{
   400     echo $db->get_error();
   400 		echo $db->get_error();
   401     return false;
   401 		return false;
   402   }
   402 	}
   403   
   403 	
   404   // query 2: page_text
   404 	// query 2: page_text
   405   $q = $db->sql_query('INSERT INTO ' . table_prefix . "page_text(page_id, namespace, page_text) VALUES\n"
   405 	$q = $db->sql_query('INSERT INTO ' . table_prefix . "page_text(page_id, namespace, page_text) VALUES\n"
   406                     . "  ( '$page_id', '$namespace', '$content');");
   406 										. "  ( '$page_id', '$namespace', '$content');");
   407   if ( !$q )
   407 	if ( !$q )
   408   {
   408 	{
   409     echo $db->get_error();
   409 		echo $db->get_error();
   410     return false;
   410 		return false;
   411   }
   411 	}
   412   
   412 	
   413   // query 3: pages
   413 	// query 3: pages
   414   $q = $db->sql_query('INSERT INTO ' . table_prefix . "pages(page_order, name, urlname, namespace, special, visible, comments_on, protected, delvotes, delvote_ips) VALUES\n"
   414 	$q = $db->sql_query('INSERT INTO ' . table_prefix . "pages(page_order, name, urlname, namespace, special, visible, comments_on, protected, delvotes, delvote_ips) VALUES\n"
   415                     . "  (NULL, '$page_title', '$page_id', '$namespace', 0, 1, 1, 1, 0, '');");
   415 										. "  (NULL, '$page_title', '$page_id', '$namespace', 0, 1, 1, 1, 0, '');");
   416   if ( !$q )
   416 	if ( !$q )
   417   {
   417 	{
   418     echo $db->get_error();
   418 		echo $db->get_error();
   419     return false;
   419 		return false;
   420   }
   420 	}
   421   
   421 	
   422   return true;
   422 	return true;
   423 }
   423 }
   424 
   424 
   425 function stg_init_logs()
   425 function stg_init_logs()
   426 {
   426 {
   427   global $db, $session, $paths, $template, $plugins; // Common objects
   427 	global $db, $session, $paths, $template, $plugins; // Common objects
   428   global $installer_version;
   428 	global $installer_version;
   429   
   429 	
   430   $q = $db->sql_query('INSERT INTO ' . table_prefix . 'logs(log_type,action,time_id,date_string,author,author_uid,page_text,edit_summary) VALUES(\'security\', \'install_enano\', ' . time() . ', \'' . enano_date(ED_DATE | ED_TIME) . '\', \'' . $db->escape($_POST['username']) . '\', 2, \'' . $db->escape(enano_version()) . '\', \'' . $db->escape($_SERVER['REMOTE_ADDR']) . '\');');
   430 	$q = $db->sql_query('INSERT INTO ' . table_prefix . 'logs(log_type,action,time_id,date_string,author,author_uid,page_text,edit_summary) VALUES(\'security\', \'install_enano\', ' . time() . ', \'' . enano_date(ED_DATE | ED_TIME) . '\', \'' . $db->escape($_POST['username']) . '\', 2, \'' . $db->escape(enano_version()) . '\', \'' . $db->escape($_SERVER['REMOTE_ADDR']) . '\');');
   431   if ( !$q )
   431 	if ( !$q )
   432   {
   432 	{
   433     echo '<p><tt>MySQL return: ' . $db->sql_error() . '</tt></p>';
   433 		echo '<p><tt>MySQL return: ' . $db->sql_error() . '</tt></p>';
   434     return false;
   434 		return false;
   435   }
   435 	}
   436   
   436 	
   437   return true;
   437 	return true;
   438 }
   438 }
   439 
   439 
   440 function stg_aes_cleanup()
   440 function stg_aes_cleanup()
   441 {
   441 {
   442   global $db, $session, $paths, $template, $plugins; // Common objects
   442 	global $db, $session, $paths, $template, $plugins; // Common objects
   443   $q = $db->sql_query('DELETE FROM ' . table_prefix . 'config WHERE config_name = \'install_aes_key\' OR config_name = \'site_aes_key\';');
   443 	$q = $db->sql_query('DELETE FROM ' . table_prefix . 'config WHERE config_name = \'install_aes_key\' OR config_name = \'site_aes_key\';');
   444   if ( !$q )
   444 	if ( !$q )
   445     $db->_die();
   445 		$db->_die();
   446   return true;
   446 	return true;
   447 }
   447 }
   448 
   448 
   449 function _stg_rename_config_revert()
   449 function _stg_rename_config_revert()
   450 {
   450 {
   451   if ( file_exists('./config.php') )
   451 	if ( file_exists('./config.php') )
   452   {
   452 	{
   453     @rename('./config.php', './config.new.php');
   453 		@rename('./config.php', './config.new.php');
   454   }
   454 	}
   455   
   455 	
   456   $handle = @fopen('./config.php.new', 'w');
   456 	$handle = @fopen('./config.php.new', 'w');
   457   if ( !$handle )
   457 	if ( !$handle )
   458     return false;
   458 		return false;
   459   $contents = '<?php $cryptkey = \'' . _INSTRESUME_AES_KEYBACKUP . '\'; ?>';
   459 	$contents = '<?php $cryptkey = \'' . _INSTRESUME_AES_KEYBACKUP . '\'; ?>';
   460   fwrite($handle, $contents);
   460 	fwrite($handle, $contents);
   461   fclose($handle);
   461 	fclose($handle);
   462   return true;
   462 	return true;
   463 }
   463 }
   464 
   464 
   465 function stg_build_index()
   465 function stg_build_index()
   466 {
   466 {
   467   global $db, $session, $paths, $template, $plugins; // Common objects
   467 	global $db, $session, $paths, $template, $plugins; // Common objects
   468   if ( $paths->rebuild_search_index() )
   468 	if ( $paths->rebuild_search_index() )
   469     return true;
   469 		return true;
   470   return false;
   470 	return false;
   471 }
   471 }
   472 
   472 
   473 function stg_rename_config()
   473 function stg_rename_config()
   474 {
   474 {
   475   if ( !@rename(ENANO_ROOT . '/config.new.php', ENANO_ROOT . '/config.php') )
   475 	if ( !@rename(ENANO_ROOT . '/config.new.php', ENANO_ROOT . '/config.php') )
   476   {
   476 	{
   477     echo '<p>Can\'t rename config.php</p>';
   477 		echo '<p>Can\'t rename config.php</p>';
   478     _stg_rename_config_revert();
   478 		_stg_rename_config_revert();
   479     return false;
   479 		return false;
   480   }
   480 	}
   481   
   481 	
   482   if ( @filesize(ENANO_ROOT . '/.htaccess.new') > 1 )
   482 	if ( @filesize(ENANO_ROOT . '/.htaccess.new') > 1 )
   483   {
   483 	{
   484     // rename/possibly concatenate .htaccess.new
   484 		// rename/possibly concatenate .htaccess.new
   485     $htaccess_base = '';
   485 		$htaccess_base = '';
   486     if ( file_exists(ENANO_ROOT . '/.htaccess') )
   486 		if ( file_exists(ENANO_ROOT . '/.htaccess') )
   487       $htaccess_base .= @file_get_contents(ENANO_ROOT . '/.htaccess');
   487 			$htaccess_base .= @file_get_contents(ENANO_ROOT . '/.htaccess');
   488     if ( strlen($htaccess_base) > 0 && !preg_match("/\n$/", $htaccess_base) )
   488 		if ( strlen($htaccess_base) > 0 && !preg_match("/\n$/", $htaccess_base) )
   489       $htaccess_base .= "\n\n";
   489 			$htaccess_base .= "\n\n";
   490     $htaccess_base .= @file_get_contents(ENANO_ROOT . '/.htaccess.new');
   490 		$htaccess_base .= @file_get_contents(ENANO_ROOT . '/.htaccess.new');
   491     if ( file_exists(ENANO_ROOT . '/.htaccess') )
   491 		if ( file_exists(ENANO_ROOT . '/.htaccess') )
   492     {
   492 		{
   493       $hh = @fopen(ENANO_ROOT . '/.htaccess', 'w');
   493 			$hh = @fopen(ENANO_ROOT . '/.htaccess', 'w');
   494       if ( !$hh )
   494 			if ( !$hh )
   495         return false;
   495 				return false;
   496       fwrite($hh, $htaccess_base);
   496 			fwrite($hh, $htaccess_base);
   497       fclose($hh);
   497 			fclose($hh);
   498       @unlink(ENANO_ROOT . '/.htaccess.new');
   498 			@unlink(ENANO_ROOT . '/.htaccess.new');
   499       return true;
   499 			return true;
   500     }
   500 		}
   501     else
   501 		else
   502     {
   502 		{
   503       return @rename(ENANO_ROOT . '/.htaccess.new', ENANO_ROOT . '/.htaccess');
   503 			return @rename(ENANO_ROOT . '/.htaccess.new', ENANO_ROOT . '/.htaccess');
   504     }
   504 		}
   505   }
   505 	}
   506   else
   506 	else
   507   {
   507 	{
   508     @unlink(ENANO_ROOT . '/.htaccess.new');
   508 		@unlink(ENANO_ROOT . '/.htaccess.new');
   509   }
   509 	}
   510   return true;
   510 	return true;
   511 }
   511 }
   512 
   512 
   513 /**
   513 /**
   514  * UPGRADE STAGES
   514  * UPGRADE STAGES
   515  */
   515  */
   516 
   516 
   517 function stg_lang_import()
   517 function stg_lang_import()
   518 {
   518 {
   519   global $db, $languages, $do_langimport;
   519 	global $db, $languages, $do_langimport;
   520   
   520 	
   521   define('IN_ENANO_UPGRADE_POST', 1);
   521 	define('IN_ENANO_UPGRADE_POST', 1);
   522   
   522 	
   523   //
   523 	//
   524   // IMPORT NEW STRINGS
   524 	// IMPORT NEW STRINGS
   525   //
   525 	//
   526   
   526 	
   527   // for each installed language, look for the json files in the filesystem and if they're ok, import new strings from them
   527 	// for each installed language, look for the json files in the filesystem and if they're ok, import new strings from them
   528   $q = $db->sql_query('SELECT lang_id, lang_code FROM ' . table_prefix . "language;");
   528 	$q = $db->sql_query('SELECT lang_id, lang_code FROM ' . table_prefix . "language;");
   529   if ( !$q )
   529 	if ( !$q )
   530     $db->_die();
   530 		$db->_die();
   531   
   531 	
   532   while ( $row = $db->fetchrow($q) )
   532 	while ( $row = $db->fetchrow($q) )
   533   {
   533 	{
   534     if ( isset($languages[$row['lang_code']]) )
   534 		if ( isset($languages[$row['lang_code']]) )
   535     {
   535 		{
   536       // found a language and it's good on the filesystem; load it and call a reimport
   536 			// found a language and it's good on the filesystem; load it and call a reimport
   537       $lang_local = new Language($row['lang_id']);
   537 			$lang_local = new Language($row['lang_id']);
   538       // call fetch to make sure we're up to date
   538 			// call fetch to make sure we're up to date
   539       $lang_local->fetch();
   539 			$lang_local->fetch();
   540       // import
   540 			// import
   541       foreach ( array('core', 'admin', 'user', 'tools') as $language_file )
   541 			foreach ( array('core', 'admin', 'user', 'tools') as $language_file )
   542       {
   542 			{
   543         // generate full path
   543 				// generate full path
   544         $language_file = ENANO_ROOT . "/language/{$languages[$row['lang_code']]['dir']}/$language_file.json";
   544 				$language_file = ENANO_ROOT . "/language/{$languages[$row['lang_code']]['dir']}/$language_file.json";
   545         // setting the second parameter to bool(true) causes it to skip existing strings
   545 				// setting the second parameter to bool(true) causes it to skip existing strings
   546         if ( !$lang_local->import($language_file, ( !$do_langimport )) )
   546 				if ( !$lang_local->import($language_file, ( !$do_langimport )) )
   547           // on failure, report failure to libenanoinstall
   547 					// on failure, report failure to libenanoinstall
   548           return false;
   548 					return false;
   549       }
   549 			}
   550       // unload this lang_local object to save memory
   550 			// unload this lang_local object to save memory
   551       unset($lang_local);
   551 			unset($lang_local);
   552     }
   552 		}
   553   }
   553 	}
   554   
   554 	
   555   return true;
   555 	return true;
   556 }
   556 }
   557 
   557 
   558 function stg_flush_cache()
   558 function stg_flush_cache()
   559 {
   559 {
   560   return purge_all_caches();
   560 	return purge_all_caches();
   561 }
   561 }
   562 
   562 
   563 function stg_set_version()
   563 function stg_set_version()
   564 {
   564 {
   565   global $db, $session, $paths, $template, $plugins; // Common objects
   565 	global $db, $session, $paths, $template, $plugins; // Common objects
   566   // log the upgrade
   566 	// log the upgrade
   567   $q = $db->sql_query('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,author_uid,page_text,edit_summary) VALUES'
   567 	$q = $db->sql_query('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,author_uid,page_text,edit_summary) VALUES'
   568          . '(\'security\', \'upgrade_enano\', ' . time() . ', \'[DEPRECATED]\', \'' . $db->escape($session->username) . '\', ' . $session->user_id . ', \'' . $db->escape(installer_enano_version()) . '\', \'' . $db->escape($_SERVER['REMOTE_ADDR']) . '\');');
   568  				. '(\'security\', \'upgrade_enano\', ' . time() . ', \'[DEPRECATED]\', \'' . $db->escape($session->username) . '\', ' . $session->user_id . ', \'' . $db->escape(installer_enano_version()) . '\', \'' . $db->escape($_SERVER['REMOTE_ADDR']) . '\');');
   569   if ( !$q )
   569 	if ( !$q )
   570   {
   570 	{
   571     $db->_die();
   571 		$db->_die();
   572     return false;
   572 		return false;
   573   }
   573 	}
   574   setConfig('enano_version', installer_enano_version());
   574 	setConfig('enano_version', installer_enano_version());
   575   return true;
   575 	return true;
   576 }
   576 }