You know what folks, a lot of Mercurial merges failed, and I just now figured out why. So now all changes from stable are permanently synced in.
authorDan
Fri, 26 Oct 2007 19:28:54 -0400
changeset 204 473cc747022a
parent 193 ebe99e82a59a (diff)
parent 203 8e2fffc5c622 (current diff)
child 205 c4542792db2b
You know what folks, a lot of Mercurial merges failed, and I just now figured out why. So now all changes from stable are permanently synced in.
ajax.php
includes/clientside/static/misc.js
includes/pageutils.php
includes/sessions.php
includes/template.php
index.php
install.php
plugins/SpecialAdmin.php
upgrade.php
upgrade.sql
--- a/.hgtags	Tue Oct 23 12:30:08 2007 -0400
+++ b/.hgtags	Fri Oct 26 19:28:54 2007 -0400
@@ -5,3 +5,4 @@
 6f0bbf88c3251ca597cb76ac8b59a1ee61d6dd3d rebrand
 0b5244001799fa29e83bf06c5f14eb69350f171c rebrand
 42c6c83b8a004163c9cc2d85f3c8eada3b73adf6 rebrand
+d53cc29308f4f4b97fc6d054e9e0855f37137409 rebrand
--- a/ajax.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/ajax.php	Fri Oct 26 19:28:54 2007 -0400
@@ -1,425 +1,410 @@
-<?php
-
-/*
- * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
- * Copyright (C) 2006-2007 Dan Fuhry
- *
- * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
- * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
- */
- 
-  // fillusername should be done without the help of the rest of Enano - all we need is the DBAL
-  if ( isset($_GET['_mode']) && $_GET['_mode'] == 'fillusername' )
-  {
-    // setup and load a very basic, specialized instance of the Enano API
-    function dc_here($m)     { return false; }
-    function dc_dump($a, $g) { return false; }
-    function dc_watch($n)    { return false; }
-    function dc_start_timer($u) { return false; }
-    function dc_stop_timer($m) { return false; }
-    // Determine directory (special case for development servers)
-    if ( strpos(__FILE__, '/repo/') && file_exists('.enanodev') )
-    {
-      $filename = str_replace('/repo/', '/', __FILE__);
-    }
-    else
-    {
-      $filename = __FILE__;
-    }
-    define('ENANO_ROOT', dirname($filename));
-    require(ENANO_ROOT.'/includes/functions.php');
-    require(ENANO_ROOT.'/includes/dbal.php');
-    require(ENANO_ROOT.'/includes/json.php');
-    $db = new mysql();
-    $db->connect();
-    
-    // result is sent using JSON
-    $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
-    $return = Array(
-        'mode' => 'success',
-        'users_real' => Array()
-      );
-    
-    // should be connected to the DB now
-    $name = (isset($_GET['name'])) ? $db->escape($_GET['name']) : false;
-    if ( !$name )
-    {
-      $return = array(
-        'mode' => 'error',
-        'error' => 'Invalid URI'
-      );
-      die( $json->encode($return) );
-    }
-    $allowanon = ( isset($_GET['allowanon']) && $_GET['allowanon'] == '1' ) ? '' : ' AND user_id > 1';
-    $q = $db->sql_query('SELECT username FROM '.table_prefix.'users WHERE lcase(username) LIKE lcase(\'%'.$name.'%\')' . $allowanon . ' ORDER BY username ASC;');
-    if ( !$q )
-    {
-      $return = array(
-        'mode' => 'error',
-        'error' => 'MySQL error selecting username data: '.addslashes(mysql_error())
-      );
-      die( $json->encode($return) );
-    }
-    $i = 0;
-    while($r = $db->fetchrow())
-    {
-      $return['users_real'][] = $r['username'];
-      $i++;
-    }
-    $db->free_result();
-    
-    // all done! :-)
-    $db->close();
-    
-    echo $json->encode( $return );
-    
-    exit;
-  }
- 
-  require('includes/common.php');
-  
-  global $db, $session, $paths, $template, $plugins; // Common objects
-  if(!isset($_GET['_mode'])) die('This script cannot be accessed directly.');
-  
-  $_ob = '';
-  
-  switch($_GET['_mode']) {
-    case "checkusername":
-      echo PageUtils::checkusername($_GET['name']);
-      break;
-    case "getsource":
-      $p = ( isset($_GET['pagepass']) ) ? $_GET['pagepass'] : false;
-      echo PageUtils::getsource($paths->page, $p);
-      break;
-    case "getpage":
-      // echo PageUtils::getpage($paths->page, false, ( (isset($_GET['oldid'])) ? $_GET['oldid'] : false ));
-      $revision_id = ( (isset($_GET['oldid'])) ? intval($_GET['oldid']) : 0 );
-      $page = new PageProcessor( $paths->cpage['urlname_nons'], $paths->namespace, $revision_id );
-      
-      $pagepass = ( isset($_REQUEST['pagepass']) ) ? $_REQUEST['pagepass'] : '';
-      $page->password = $pagepass;
-            
-      $page->send();
-      break;
-    case "savepage":
-      $summ = ( isset($_POST['summary']) ) ? $_POST['summary'] : '';
-      $minor = isset($_POST['minor']);
-      $e = PageUtils::savepage($paths->cpage['urlname_nons'], $paths->namespace, $_POST['text'], $summ, $minor);
-      if($e=='good')
-      {
-        $page = new PageProcessor($paths->cpage['urlname_nons'], $paths->namespace);
-        $page->send();
-      }
-      else
-      {
-        echo '<p>Error saving the page: '.$e.'</p>';
-      }
-      break;
-    case "protect":
-      echo PageUtils::protect($paths->cpage['urlname_nons'], $paths->namespace, (int)$_POST['level'], $_POST['reason']);
-      break;
-    case "histlist":
-      echo PageUtils::histlist($paths->cpage['urlname_nons'], $paths->namespace);
-      break;
-    case "rollback":
-      echo PageUtils::rollback( (int)$_GET['id'] );
-      break;
-    case "comments":
-      $comments = new Comments($paths->cpage['urlname_nons'], $paths->namespace);
-      if ( isset($_POST['data']) )
-      {
-        $comments->process_json($_POST['data']);
-      }
-      else
-      {
-        die('{ "mode" : "error", "error" : "No input" }');
-      }
-      break;
-    case "rename":
-      echo PageUtils::rename($paths->cpage['urlname_nons'], $paths->namespace, $_POST['newtitle']);
-      break;
-    case "flushlogs":
-      echo PageUtils::flushlogs($paths->cpage['urlname_nons'], $paths->namespace);
-      break;
-    case "deletepage":
-      $reason = ( isset($_POST['reason']) ) ? $_POST['reason'] : false;
-      if ( empty($reason) )
-        die('Please enter a reason for deleting this page.');
-      echo PageUtils::deletepage($paths->cpage['urlname_nons'], $paths->namespace, $reason);
-      break;
-    case "delvote":
-      echo PageUtils::delvote($paths->cpage['urlname_nons'], $paths->namespace);
-      break;
-    case "resetdelvotes":
-      echo PageUtils::resetdelvotes($paths->cpage['urlname_nons'], $paths->namespace);
-      break;
-    case "getstyles":
-      echo PageUtils::getstyles($_GET['id']);
-      break;
-    case "catedit":
-      echo PageUtils::catedit($paths->cpage['urlname_nons'], $paths->namespace);
-      break;
-    case "catsave":
-      echo PageUtils::catsave($paths->cpage['urlname_nons'], $paths->namespace, $_POST);
-      break;
-    case "setwikimode":
-      echo PageUtils::setwikimode($paths->cpage['urlname_nons'], $paths->namespace, (int)$_GET['mode']);
-      break;
-    case "setpass":
-      echo PageUtils::setpass($paths->cpage['urlname_nons'], $paths->namespace, $_POST['password']);
-      break;
-    case "fillusername":
-      break;
-    case "fillpagename":
-      $name = (isset($_GET['name'])) ? $_GET['name'] : false;
-      if(!$name) die('userlist = new Array(); namelist = new Array(); errorstring=\'Invalid URI\'');
-      $nd = RenderMan::strToPageID($name);
-      $c = 0;
-      $u = Array();
-      $n = Array();
-      
-      $name = sanitize_page_id($name);
-      $name = str_replace('_', ' ', $name);
-      
-      for($i=0;$i<sizeof($paths->pages)/2;$i++)
-      {
-        if( ( 
-            preg_match('#'.preg_quote($name).'(.*)#i', $paths->pages[$i]['name']) ||
-            preg_match('#'.preg_quote($name).'(.*)#i', $paths->pages[$i]['urlname']) ||
-            preg_match('#'.preg_quote($name).'(.*)#i', $paths->pages[$i]['urlname_nons']) ||
-            preg_match('#'.preg_quote(str_replace(' ', '_', $name)).'(.*)#i', $paths->pages[$i]['name']) ||
-            preg_match('#'.preg_quote(str_replace(' ', '_', $name)).'(.*)#i', $paths->pages[$i]['urlname']) ||
-            preg_match('#'.preg_quote(str_replace(' ', '_', $name)).'(.*)#i', $paths->pages[$i]['urlname_nons'])
-            ) &&
-           ( ( $nd[1] != 'Article' && $paths->pages[$i]['namespace'] == $nd[1] ) || $nd[1] == 'Article' )
-            && $paths->pages[$i]['visible']
-           )
-        {
-          $c++;
-          $u[] = $paths->pages[$i]['name'];
-          $n[] = $paths->pages[$i]['urlname'];
-        }
-      }
-      if($c > 0)
-      {
-        echo 'userlist = new Array(); namelist = new Array(); errorstring = false; '."\n";
-        for($i=0;$i<sizeof($u);$i++) // Can't use foreach because we need the value of $i and we need to use both $u and $n
-        {
-          echo "userlist[$i] = '".addslashes($n[$i])."';\n";
-          echo "namelist[$i] = '".addslashes(htmlspecialchars($u[$i]))."';\n";
-        }
-      } else {
-        die('userlist = new Array(); namelist = new Array(); errorstring=\'No page matches found.\'');
-      }
-      break;
-    case "preview":
-      echo PageUtils::genPreview($_POST['text']);
-      break;
-    case "pagediff":
-      $id1 = ( isset($_GET['diff1']) ) ? (int)$_GET['diff1'] : false;
-      $id2 = ( isset($_GET['diff2']) ) ? (int)$_GET['diff2'] : false;
-      if(!$id1 || !$id2) { echo '<p>Invalid request.</p>'; $template->footer(); break; }
-      if(!preg_match('#^([0-9]+)$#', (string)$_GET['diff1']) ||
-         !preg_match('#^([0-9]+)$#', (string)$_GET['diff2']  )) { echo '<p>SQL injection attempt</p>'; $template->footer(); break; }
-      echo PageUtils::pagediff($paths->cpage['urlname_nons'], $paths->namespace, $id1, $id2);
-      break;
-    case "jsres":
-      die('// ERROR: this section is deprecated and has moved to includes/clientside/static/enano-lib-basic.js.');
-      break;
-    case "rdns":
-      if(!$session->get_permissions('mod_misc')) die('Go somewhere else for your reverse DNS info!');
-      $ip = $_GET['ip'];
-      $rdns = gethostbyaddr($ip);
-      if($rdns == $ip) echo 'Unable to get reverse DNS information. Perhaps the DNS server is down or the PTR record no longer exists.';
-      else echo $rdns;
-      break;
-    case 'acljson':
-      $parms = ( isset($_POST['acl_params']) ) ? rawurldecode($_POST['acl_params']) : false;
-      echo PageUtils::acl_json($parms);
-      break;
-    case "change_theme":
-      if ( !isset($_POST['theme_id']) || !isset($_POST['style_id']) )
-      {
-        die('Invalid input');
-      }
-      if ( !preg_match('/^([a-z0-9_-]+)$/i', $_POST['theme_id']) || !preg_match('/^([a-z0-9_-]+)$/i', $_POST['style_id']) )
-      {
-        die('Invalid input');
-      }
-      if ( !file_exists(ENANO_ROOT . '/themes/' . $_POST['theme_id'] . '/css/' . $_POST['style_id'] . '.css') )
-      {
-        die('Can\'t find theme file: ' . ENANO_ROOT . '/themes/' . $_POST['theme_id'] . '/css/' . $_POST['style_id'] . '.css');
-      }
-      if ( !$session->user_logged_in )
-      {
-        die('You must be logged in to change your theme');
-      }
-      // Just in case something slipped through...
-      $theme_id = $db->escape($_POST['theme_id']);
-      $style_id = $db->escape($_POST['style_id']);
-      $e = $db->sql_query('UPDATE ' . table_prefix . "users SET theme='$theme_id', style='$style_id' WHERE user_id=$session->user_id;");
-      if ( !$e )
-        die( $db->get_error() );
-      die('GOOD');
-      break;
-    case 'get_tags':
-      $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
-      
-      $ret = array('tags' => array(), 'user_level' => $session->user_level, 'can_add' => $session->get_permissions('tag_create'));
-      $q = $db->sql_query('SELECT t.tag_id, t.tag_name, pg.pg_target IS NOT NULL AS used_in_acl, t.user FROM '.table_prefix.'tags AS t
-        LEFT JOIN '.table_prefix.'page_groups AS pg
-          ON ( ( pg.pg_type = ' . PAGE_GRP_TAGGED . ' AND pg.pg_target=t.tag_name ) OR ( pg.pg_type IS NULL AND pg.pg_target IS NULL ) )
-        WHERE t.page_id=\'' . $db->escape($paths->cpage['urlname_nons']) . '\' AND t.namespace=\'' . $db->escape($paths->namespace) . '\';');
-      if ( !$q )
-        $db->_die();
-      
-      while ( $row = $db->fetchrow() )
-      {
-        $can_del = true;
-        
-        $perm = ( $row['user'] != $session->user_id ) ?
-                'tag_delete_other' :
-                'tag_delete_own';
-        
-        if ( $row['user'] == 1 && !$session->user_logged_in )
-          // anonymous user trying to delete tag (hardcode blacklisted)
-          $can_del = false;
-          
-        if ( !$session->get_permissions($perm) )
-          $can_del = false;
-        
-        if ( $row['used_in_acl'] == 1 && !$session->get_permissions('edit_acl') && $session->user_level < USER_LEVEL_ADMIN )
-          $can_del = false;
-        
-        $ret['tags'][] = array(
-          'id' => $row['tag_id'],
-          'name' => $row['tag_name'],
-          'can_del' => $can_del,
-          'acl' => ( $row['used_in_acl'] == 1 )
-        );
-      }
-      
-      echo $json->encode($ret);
-      
-      break;
-    case 'addtag':
-      $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
-      $resp = array(
-          'success' => false,
-          'error' => 'No error',
-          'can_del' => ( $session->get_permissions('tag_delete_own') && $session->user_logged_in ),
-          'in_acl' => false
-        );
-      
-      // first of course, are we allowed to tag pages?
-      if ( !$session->get_permissions('tag_create') )
-      {
-        $resp['error'] = 'You are not permitted to tag pages.';
-        die($json->encode($resp));
-      }
-      
-      // sanitize the tag name
-      $tag = sanitize_tag($_POST['tag']);
-      $tag = $db->escape($tag);
-      
-      if ( strlen($tag) < 2 )
-      {
-        $resp['error'] = 'Tags must consist of at least 2 alphanumeric characters.';
-        die($json->encode($resp));
-      }
-      
-      // check if tag is already on page
-      $q = $db->sql_query('SELECT 1 FROM '.table_prefix.'tags WHERE page_id=\'' . $db->escape($paths->cpage['urlname_nons']) . '\' AND namespace=\'' . $db->escape($paths->namespace) . '\' AND tag_name=\'' . $tag . '\';');
-      if ( !$q )
-        $db->_die();
-      if ( $db->numrows() > 0 )
-      {
-        $resp['error'] = 'This page already has this tag.';
-        die($json->encode($resp));
-      }
-      $db->free_result();
-      
-      // tricky: make sure this tag isn't being used in some page group, and thus adding it could affect page access
-      $can_edit_acl = ( $session->get_permissions('edit_acl') || $session->user_level >= USER_LEVEL_ADMIN );
-      $q = $db->sql_query('SELECT 1 FROM '.table_prefix.'page_groups WHERE pg_type=' . PAGE_GRP_TAGGED . ' AND pg_target=\'' . $tag . '\';');
-      if ( !$q )
-        $db->_die();
-      if ( $db->numrows() > 0 && !$can_edit_acl )
-      {
-        $resp['error'] = 'This tag is used in an ACL page group, and thus can\'t be added to a page by people without administrator privileges.';
-        die($json->encode($resp));
-      }
-      $resp['in_acl'] = ( $db->numrows() > 0 );
-      $db->free_result();
-      
-      // we're good
-      $q = $db->sql_query('INSERT INTO '.table_prefix.'tags(tag_name,page_id,namespace,user) VALUES(\'' . $tag . '\', \'' . $db->escape($paths->cpage['urlname_nons']) . '\', \'' . $db->escape($paths->namespace) . '\', ' . $session->user_id . ');');
-      if ( !$q )
-        $db->_die();
-      
-      $resp['success'] = true;
-      $resp['tag'] = $tag;
-      $resp['tag_id'] = $db->insert_id();
-      
-      echo $json->encode($resp);
-      break;
-    case 'deltag':
-      
-      $tag_id = intval($_POST['tag_id']);
-      if ( empty($tag_id) )
-        die('Invalid tag ID');
-      
-      $q = $db->sql_query('SELECT t.tag_id, t.user, t.page_id, t.namespace, pg.pg_target IS NOT NULL AS used_in_acl FROM '.table_prefix.'tags AS t
-  LEFT JOIN '.table_prefix.'page_groups AS pg
-    ON ( pg.pg_id IS NULL OR ( pg.pg_target = t.tag_name AND pg.pg_type = ' . PAGE_GRP_TAGGED . ' ) )
-  WHERE t.tag_id=' . $tag_id . ';');
-      
-      if ( !$q )
-        $db->_die();
-      
-      if ( $db->numrows() < 1 )
-        die('Could not find a tag with that ID');
-      
-      $row = $db->fetchrow();
-      $db->free_result();
-      
-      if ( $row['page_id'] == $paths->cpage['urlname_nons'] && $row['namespace'] == $paths->namespace )
-        $perms =& $session;
-      else
-        $perms = $session->fetch_page_acl($row['page_id'], $row['namespace']);
-        
-      $perm = ( $row['user'] != $session->user_id ) ?
-                'tag_delete_other' :
-                'tag_delete_own';
-      
-      if ( $row['user'] == 1 && !$session->user_logged_in )
-        // anonymous user trying to delete tag (hardcode blacklisted)
-        die('You are not authorized to delete this tag.');
-        
-      if ( !$perms->get_permissions($perm) )
-        die('You are not authorized to delete this tag.');
-      
-      if ( $row['used_in_acl'] == 1 && !$perms->get_permissions('edit_acl') && $session->user_level < USER_LEVEL_ADMIN )
-        die('You are not authorized to delete this tag.');
-      
-      // We're good
-      $q = $db->sql_query('DELETE FROM '.table_prefix.'tags WHERE tag_id = ' . $tag_id . ';');
-      if ( !$q )
-        $db->_die();
-      
-      echo 'success';
-      
-      break;
-    case 'ping':
-      echo 'pong';
-      break;
-    default:
-      die('Hacking attempt');
-      break;
-  }
-  
+<?php
+
+/*
+ * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
+ * Version 1.1.1
+ * Copyright (C) 2006-2007 Dan Fuhry
+ *
+ * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
+ */
+ 
+  // fillusername should be done without the help of the rest of Enano - all we need is the DBAL
+  if ( isset($_GET['_mode']) && $_GET['_mode'] == 'fillusername' )
+  {
+    // setup and load a very basic, specialized instance of the Enano API
+    function dc_here($m)     { return false; }
+    function dc_dump($a, $g) { return false; }
+    function dc_watch($n)    { return false; }
+    function dc_start_timer($u) { return false; }
+    function dc_stop_timer($m) { return false; }
+    // Determine directory (special case for development servers)
+    if ( strpos(__FILE__, '/repo/') && file_exists('.enanodev') )
+    {
+      $filename = str_replace('/repo/', '/', __FILE__);
+    }
+    else
+    {
+      $filename = __FILE__;
+    }
+    define('ENANO_ROOT', dirname($filename));
+    require(ENANO_ROOT.'/includes/functions.php');
+    require(ENANO_ROOT.'/includes/dbal.php');
+    $db = new mysql();
+    $db->connect();
+    
+    // should be connected now
+    $name = (isset($_GET['name'])) ? $db->escape($_GET['name']) : false;
+    if ( !$name )
+    {
+      die('userlist = new Array(); errorstring=\'Invalid URI\'');
+    }
+    $q = $db->sql_query('SELECT username,user_id FROM '.table_prefix.'users WHERE lcase(username) LIKE lcase(\'%'.$name.'%\');');
+    if ( !$q )
+    {
+      die('userlist = new Array(); errorstring=\'MySQL error selecting username data: '.addslashes(mysql_error()).'\'');
+    }
+    if($db->numrows() < 1)
+    {
+      die('userlist = new Array(); errorstring=\'No usernames found\';');
+    }
+    echo 'var errorstring = false; userlist = new Array();';
+    $i = 0;
+    while($r = $db->fetchrow())
+    {
+      echo "userlist[$i] = '".addslashes($r['username'])."'; ";
+      $i++;
+    }
+    $db->free_result();
+    
+    // all done! :-)
+    $db->close();
+    exit;
+  }
+ 
+  require('includes/common.php');
+  
+  global $db, $session, $paths, $template, $plugins; // Common objects
+  if(!isset($_GET['_mode'])) die('This script cannot be accessed directly.');
+  
+  $_ob = '';
+  
+  switch($_GET['_mode']) {
+    case "checkusername":
+      echo PageUtils::checkusername($_GET['name']);
+      break;
+    case "getsource":
+      $p = ( isset($_GET['pagepass']) ) ? $_GET['pagepass'] : false;
+      echo PageUtils::getsource($paths->page, $p);
+      break;
+    case "getpage":
+      // echo PageUtils::getpage($paths->page, false, ( (isset($_GET['oldid'])) ? $_GET['oldid'] : false ));
+      $revision_id = ( (isset($_GET['oldid'])) ? intval($_GET['oldid']) : 0 );
+      $page = new PageProcessor( $paths->cpage['urlname_nons'], $paths->namespace, $revision_id );
+      
+      $pagepass = ( isset($_REQUEST['pagepass']) ) ? $_REQUEST['pagepass'] : '';
+      $page->password = $pagepass;
+            
+      $page->send();
+      break;
+    case "savepage":
+      $summ = ( isset($_POST['summary']) ) ? $_POST['summary'] : '';
+      $minor = isset($_POST['minor']);
+      $e = PageUtils::savepage($paths->cpage['urlname_nons'], $paths->namespace, $_POST['text'], $summ, $minor);
+      if($e=='good')
+      {
+        $page = new PageProcessor($paths->cpage['urlname_nons'], $paths->namespace);
+        $page->send();
+      }
+      else
+      {
+        echo '<p>Error saving the page: '.$e.'</p>';
+      }
+      break;
+    case "protect":
+      echo PageUtils::protect($paths->cpage['urlname_nons'], $paths->namespace, (int)$_POST['level'], $_POST['reason']);
+      break;
+    case "histlist":
+      echo PageUtils::histlist($paths->cpage['urlname_nons'], $paths->namespace);
+      break;
+    case "rollback":
+      echo PageUtils::rollback( (int)$_GET['id'] );
+      break;
+    case "comments":
+      $comments = new Comments($paths->cpage['urlname_nons'], $paths->namespace);
+      if ( isset($_POST['data']) )
+      {
+        $comments->process_json($_POST['data']);
+      }
+      else
+      {
+        die('{ "mode" : "error", "error" : "No input" }');
+      }
+      break;
+    case "rename":
+      echo PageUtils::rename($paths->cpage['urlname_nons'], $paths->namespace, $_POST['newtitle']);
+      break;
+    case "flushlogs":
+      echo PageUtils::flushlogs($paths->cpage['urlname_nons'], $paths->namespace);
+      break;
+    case "deletepage":
+      $reason = ( isset($_POST['reason']) ) ? $_POST['reason'] : false;
+      if ( empty($reason) )
+        die('Please enter a reason for deleting this page.');
+      echo PageUtils::deletepage($paths->cpage['urlname_nons'], $paths->namespace, $reason);
+      break;
+    case "delvote":
+      echo PageUtils::delvote($paths->cpage['urlname_nons'], $paths->namespace);
+      break;
+    case "resetdelvotes":
+      echo PageUtils::resetdelvotes($paths->cpage['urlname_nons'], $paths->namespace);
+      break;
+    case "getstyles":
+      echo PageUtils::getstyles($_GET['id']);
+      break;
+    case "catedit":
+      echo PageUtils::catedit($paths->cpage['urlname_nons'], $paths->namespace);
+      break;
+    case "catsave":
+      echo PageUtils::catsave($paths->cpage['urlname_nons'], $paths->namespace, $_POST);
+      break;
+    case "setwikimode":
+      echo PageUtils::setwikimode($paths->cpage['urlname_nons'], $paths->namespace, (int)$_GET['mode']);
+      break;
+    case "setpass":
+      echo PageUtils::setpass($paths->cpage['urlname_nons'], $paths->namespace, $_POST['password']);
+      break;
+    case "fillusername":
+      break;
+    case "fillpagename":
+      $name = (isset($_GET['name'])) ? $_GET['name'] : false;
+      if(!$name) die('userlist = new Array(); namelist = new Array(); errorstring=\'Invalid URI\'');
+      $nd = RenderMan::strToPageID($name);
+      $c = 0;
+      $u = Array();
+      $n = Array();
+      
+      $name = sanitize_page_id($name);
+      $name = str_replace('_', ' ', $name);
+      
+      for($i=0;$i<sizeof($paths->pages)/2;$i++)
+      {
+        if( ( 
+            preg_match('#'.preg_quote($name).'(.*)#i', $paths->pages[$i]['name']) ||
+            preg_match('#'.preg_quote($name).'(.*)#i', $paths->pages[$i]['urlname']) ||
+            preg_match('#'.preg_quote($name).'(.*)#i', $paths->pages[$i]['urlname_nons']) ||
+            preg_match('#'.preg_quote(str_replace(' ', '_', $name)).'(.*)#i', $paths->pages[$i]['name']) ||
+            preg_match('#'.preg_quote(str_replace(' ', '_', $name)).'(.*)#i', $paths->pages[$i]['urlname']) ||
+            preg_match('#'.preg_quote(str_replace(' ', '_', $name)).'(.*)#i', $paths->pages[$i]['urlname_nons'])
+            ) &&
+           ( ( $nd[1] != 'Article' && $paths->pages[$i]['namespace'] == $nd[1] ) || $nd[1] == 'Article' )
+            && $paths->pages[$i]['visible']
+           )
+        {
+          $c++;
+          $u[] = $paths->pages[$i]['name'];
+          $n[] = $paths->pages[$i]['urlname'];
+        }
+      }
+      if($c > 0)
+      {
+        echo 'userlist = new Array(); namelist = new Array(); errorstring = false; '."\n";
+        for($i=0;$i<sizeof($u);$i++) // Can't use foreach because we need the value of $i and we need to use both $u and $n
+        {
+          echo "userlist[$i] = '".addslashes($n[$i])."';\n";
+          echo "namelist[$i] = '".addslashes(htmlspecialchars($u[$i]))."';\n";
+        }
+      } else {
+        die('userlist = new Array(); namelist = new Array(); errorstring=\'No page matches found.\'');
+      }
+      break;
+    case "preview":
+      echo PageUtils::genPreview($_POST['text']);
+      break;
+    case "pagediff":
+      $id1 = ( isset($_GET['diff1']) ) ? (int)$_GET['diff1'] : false;
+      $id2 = ( isset($_GET['diff2']) ) ? (int)$_GET['diff2'] : false;
+      if(!$id1 || !$id2) { echo '<p>Invalid request.</p>'; $template->footer(); break; }
+      if(!preg_match('#^([0-9]+)$#', (string)$_GET['diff1']) ||
+         !preg_match('#^([0-9]+)$#', (string)$_GET['diff2']  )) { echo '<p>SQL injection attempt</p>'; $template->footer(); break; }
+      echo PageUtils::pagediff($paths->cpage['urlname_nons'], $paths->namespace, $id1, $id2);
+      break;
+    case "jsres":
+      die('// ERROR: this section is deprecated and has moved to includes/clientside/static/enano-lib-basic.js.');
+      break;
+    case "rdns":
+      if(!$session->get_permissions('mod_misc')) die('Go somewhere else for your reverse DNS info!');
+      $ip = $_GET['ip'];
+      $rdns = gethostbyaddr($ip);
+      if($rdns == $ip) echo 'Unable to get reverse DNS information. Perhaps the DNS server is down or the PTR record no longer exists.';
+      else echo $rdns;
+      break;
+    case 'acljson':
+      $parms = ( isset($_POST['acl_params']) ) ? rawurldecode($_POST['acl_params']) : false;
+      echo PageUtils::acl_json($parms);
+      break;
+    case "change_theme":
+      if ( !isset($_POST['theme_id']) || !isset($_POST['style_id']) )
+      {
+        die('Invalid input');
+      }
+      if ( !preg_match('/^([a-z0-9_-]+)$/i', $_POST['theme_id']) || !preg_match('/^([a-z0-9_-]+)$/i', $_POST['style_id']) )
+      {
+        die('Invalid input');
+      }
+      if ( !file_exists(ENANO_ROOT . '/themes/' . $_POST['theme_id'] . '/css/' . $_POST['style_id'] . '.css') )
+      {
+        die('Can\'t find theme file: ' . ENANO_ROOT . '/themes/' . $_POST['theme_id'] . '/css/' . $_POST['style_id'] . '.css');
+      }
+      if ( !$session->user_logged_in )
+      {
+        die('You must be logged in to change your theme');
+      }
+      // Just in case something slipped through...
+      $theme_id = $db->escape($_POST['theme_id']);
+      $style_id = $db->escape($_POST['style_id']);
+      $e = $db->sql_query('UPDATE ' . table_prefix . "users SET theme='$theme_id', style='$style_id' WHERE user_id=$session->user_id;");
+      if ( !$e )
+        die( $db->get_error() );
+      die('GOOD');
+      break;
+    case 'get_tags':
+      $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
+      
+      $ret = array('tags' => array(), 'user_level' => $session->user_level, 'can_add' => $session->get_permissions('tag_create'));
+      $q = $db->sql_query('SELECT t.tag_id, t.tag_name, pg.pg_target IS NOT NULL AS used_in_acl, t.user FROM '.table_prefix.'tags AS t
+        LEFT JOIN '.table_prefix.'page_groups AS pg
+          ON ( ( pg.pg_type = ' . PAGE_GRP_TAGGED . ' AND pg.pg_target=t.tag_name ) OR ( pg.pg_type IS NULL AND pg.pg_target IS NULL ) )
+        WHERE t.page_id=\'' . $db->escape($paths->cpage['urlname_nons']) . '\' AND t.namespace=\'' . $db->escape($paths->namespace) . '\';');
+      if ( !$q )
+        $db->_die();
+      
+      while ( $row = $db->fetchrow() )
+      {
+        $can_del = true;
+        
+        $perm = ( $row['user'] != $session->user_id ) ?
+                'tag_delete_other' :
+                'tag_delete_own';
+        
+        if ( $row['user'] == 1 && !$session->user_logged_in )
+          // anonymous user trying to delete tag (hardcode blacklisted)
+          $can_del = false;
+          
+        if ( !$session->get_permissions($perm) )
+          $can_del = false;
+        
+        if ( $row['used_in_acl'] == 1 && !$session->get_permissions('edit_acl') && $session->user_level < USER_LEVEL_ADMIN )
+          $can_del = false;
+        
+        $ret['tags'][] = array(
+          'id' => $row['tag_id'],
+          'name' => $row['tag_name'],
+          'can_del' => $can_del,
+          'acl' => ( $row['used_in_acl'] == 1 )
+        );
+      }
+      
+      echo $json->encode($ret);
+      
+      break;
+    case 'addtag':
+      $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
+      $resp = array(
+          'success' => false,
+          'error' => 'No error',
+          'can_del' => ( $session->get_permissions('tag_delete_own') && $session->user_logged_in ),
+          'in_acl' => false
+        );
+      
+      // first of course, are we allowed to tag pages?
+      if ( !$session->get_permissions('tag_create') )
+      {
+        $resp['error'] = 'You are not permitted to tag pages.';
+        die($json->encode($resp));
+      }
+      
+      // sanitize the tag name
+      $tag = sanitize_tag($_POST['tag']);
+      $tag = $db->escape($tag);
+      
+      if ( strlen($tag) < 2 )
+      {
+        $resp['error'] = 'Tags must consist of at least 2 alphanumeric characters.';
+        die($json->encode($resp));
+      }
+      
+      // check if tag is already on page
+      $q = $db->sql_query('SELECT 1 FROM '.table_prefix.'tags WHERE page_id=\'' . $db->escape($paths->cpage['urlname_nons']) . '\' AND namespace=\'' . $db->escape($paths->namespace) . '\' AND tag_name=\'' . $tag . '\';');
+      if ( !$q )
+        $db->_die();
+      if ( $db->numrows() > 0 )
+      {
+        $resp['error'] = 'This page already has this tag.';
+        die($json->encode($resp));
+      }
+      $db->free_result();
+      
+      // tricky: make sure this tag isn't being used in some page group, and thus adding it could affect page access
+      $can_edit_acl = ( $session->get_permissions('edit_acl') || $session->user_level >= USER_LEVEL_ADMIN );
+      $q = $db->sql_query('SELECT 1 FROM '.table_prefix.'page_groups WHERE pg_type=' . PAGE_GRP_TAGGED . ' AND pg_target=\'' . $tag . '\';');
+      if ( !$q )
+        $db->_die();
+      if ( $db->numrows() > 0 && !$can_edit_acl )
+      {
+        $resp['error'] = 'This tag is used in an ACL page group, and thus can\'t be added to a page by people without administrator privileges.';
+        die($json->encode($resp));
+      }
+      $resp['in_acl'] = ( $db->numrows() > 0 );
+      $db->free_result();
+      
+      // we're good
+      $q = $db->sql_query('INSERT INTO '.table_prefix.'tags(tag_name,page_id,namespace,user) VALUES(\'' . $tag . '\', \'' . $db->escape($paths->cpage['urlname_nons']) . '\', \'' . $db->escape($paths->namespace) . '\', ' . $session->user_id . ');');
+      if ( !$q )
+        $db->_die();
+      
+      $resp['success'] = true;
+      $resp['tag'] = $tag;
+      $resp['tag_id'] = $db->insert_id();
+      
+      echo $json->encode($resp);
+      break;
+    case 'deltag':
+      
+      $tag_id = intval($_POST['tag_id']);
+      if ( empty($tag_id) )
+        die('Invalid tag ID');
+      
+      $q = $db->sql_query('SELECT t.tag_id, t.user, t.page_id, t.namespace, pg.pg_target IS NOT NULL AS used_in_acl FROM '.table_prefix.'tags AS t
+  LEFT JOIN '.table_prefix.'page_groups AS pg
+    ON ( pg.pg_id IS NULL OR ( pg.pg_target = t.tag_name AND pg.pg_type = ' . PAGE_GRP_TAGGED . ' ) )
+  WHERE t.tag_id=' . $tag_id . ';');
+      
+      if ( !$q )
+        $db->_die();
+      
+      if ( $db->numrows() < 1 )
+        die('Could not find a tag with that ID');
+      
+      $row = $db->fetchrow();
+      $db->free_result();
+      
+      if ( $row['page_id'] == $paths->cpage['urlname_nons'] && $row['namespace'] == $paths->namespace )
+        $perms =& $session;
+      else
+        $perms = $session->fetch_page_acl($row['page_id'], $row['namespace']);
+        
+      $perm = ( $row['user'] != $session->user_id ) ?
+                'tag_delete_other' :
+                'tag_delete_own';
+      
+      if ( $row['user'] == 1 && !$session->user_logged_in )
+        // anonymous user trying to delete tag (hardcode blacklisted)
+        die('You are not authorized to delete this tag.');
+        
+      if ( !$perms->get_permissions($perm) )
+        die('You are not authorized to delete this tag.');
+      
+      if ( $row['used_in_acl'] == 1 && !$perms->get_permissions('edit_acl') && $session->user_level < USER_LEVEL_ADMIN )
+        die('You are not authorized to delete this tag.');
+      
+      // We're good
+      $q = $db->sql_query('DELETE FROM '.table_prefix.'tags WHERE tag_id = ' . $tag_id . ';');
+      if ( !$q )
+        $db->_die();
+      
+      echo 'success';
+      
+      break;
+    case 'ping':
+      echo 'pong';
+      break;
+    default:
+      die('Hacking attempt');
+      break;
+  }
+  
 ?>
\ No newline at end of file
--- a/includes/captcha.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/captcha.php	Fri Oct 26 19:28:54 2007 -0400
@@ -1,7 +1,8 @@
 <?php
+
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  * captcha.php - visual confirmation system used during registration
  *
--- a/includes/clientside/jsres.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/clientside/jsres.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  * jsres.php - the Enano client-side runtime, a.k.a. AJAX on steroids
  *
@@ -40,7 +40,7 @@
 {
   echo "/*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * [Aggressively compressed] Javascript client code
  * Copyright (C) 2006-2007 Dan Fuhry
  * Enano is Free Software, licensed under the GNU General Public License; see http://enanocms.org/ for details.
--- a/includes/clientside/static/ajax.js	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/clientside/static/ajax.js	Fri Oct 26 19:28:54 2007 -0400
@@ -1184,3 +1184,33 @@
   new messagebox(MB_OK|MB_ICONINFORMATION, 'About the keep-alive feature', 'Keep-alive is a new Enano feature that keeps your administrative session from timing out while you are using the administration panel. This feature can be useful if you are editing a large page or doing something in the administration interface that will take longer than 15 minutes.<br /><br />For security reasons, Enano mandates that high-privilege logins last only 15 minutes, with the time being reset each time a page is loaded (or, more specifically, each time the session API is started). The consequence of this is that if you are performing an action in the administration panel that takes more than 15 minutes, your session may be terminated. The keep-alive feature attempts to relieve this by sending a "ping" to the server every 10 minutes.<br /><br />Please note that keep-alive state is determined by a cookie. Thus, if you log out and then back in as a different administrator, keep-alive will use the same setting that was used when you were logged in as the first administrative user. In the same way, if you log into the administration panel under your account from another computer, keep-alive will be set to "off".<br /><br /><b>For more information:</b><br /><a href="http://docs.enanocms.org/Help:Appendix_B" onclick="window.open(this.href); return false;">Overview of Enano'+"'"+'s security model');
 }
 
+function ajaxShowCaptcha(code)
+{
+  var mydiv = document.createElement('div');
+  mydiv.style.backgroundColor = '#FFFFFF';
+  mydiv.style.padding = '10px';
+  mydiv.style.position = 'absolute';
+  mydiv.style.top = '0px';
+  mydiv.id = 'autoCaptcha';
+  var img = document.createElement('img');
+  img.onload = function()
+  {
+    if ( this.loaded )
+      return true;
+    var mydiv = document.getElementById('autoCaptcha');
+    var width = getWidth();
+    var divw = $(mydiv).Width();
+    var left = ( width / 2 ) - ( divw / 2 );
+    mydiv.style.left = left + 'px';
+    fly_in_top(mydiv, false, true);
+    this.loaded = true;
+  };
+  img.src = makeUrlNS('Special', 'Captcha/' + code);
+  img.onclick = function() { this.src = this.src + '/a'; };
+  img.style.cursor = 'pointer';
+  mydiv.appendChild(img);
+  domObjChangeOpac(0, mydiv);
+  var body = document.getElementsByTagName('body')[0];
+  body.appendChild(mydiv);
+}
+
--- a/includes/clientside/static/misc.js	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/clientside/static/misc.js	Fri Oct 26 19:28:54 2007 -0400
@@ -302,6 +302,51 @@
 var ajax_auth_mb_cache = false;
 var ajax_auth_level_cache = false;
 var ajax_auth_error_string = false;
+var ajax_auth_show_captcha = false;
+
+function ajaxAuthErrorToString($data)
+{
+  var $errstring = $data.error;
+  // this was literally copied straight from the PHP code.
+  switch($data.error)
+  {
+    case 'key_not_found':
+      $errstring = 'Enano couldn\'t look up the encryption key used to encrypt your password. This most often happens if a cache rotation occurred during your login attempt, or if you refreshed the login page.';
+      break;
+    case 'key_wrong_length':
+      $errstring = 'The encryption key was the wrong length.';
+      break;
+    case 'too_big_for_britches':
+      $errstring = 'You are trying to authenticate at a level that your user account does not permit.';
+      break;
+    case 'invalid_credentials':
+      $errstring = 'You have entered an invalid username or password. Please enter your login details again.';
+      if ( $data.lockout_policy == 'lockout' )
+      {
+        $errstring += ' You have used up '+$data['lockout_fails']+' out of '+$data['lockout_threshold']+' login attempts. After you have used up all '+$data['lockout_threshold']+' login attempts, you will be locked out from logging in for '+$data['lockout_duration']+' minutes.';
+      }
+      else if ( $data.lockout_policy == 'captcha' )
+      {
+        $errstring += ' You have used up '+$data['lockout_fails']+' out of '+$data['lockout_threshold']+' login attempts. After you have used up all '+$data['lockout_threshold']+' login attempts, you will have to enter a visual confirmation code before logging in, effective for '+$data['lockout_duration']+' minutes.';
+      }
+      break;
+    case 'backend_fail':
+      $errstring = 'You entered the right credentials and everything was validated, but for some reason Enano couldn\'t register your session. This is an internal problem with the site and you are encouraged to contact site administration.';
+      break;
+    case 'locked_out':
+      $attempts = parseInt($data['lockout_fails']);
+      if ( $attempts > $data['lockout_threshold'])
+        $attempts = $data['lockout_threshold'];
+      $time_rem = $data.time_rem;
+      $s = ( $time_rem == 1 ) ? '' : 's';
+      $errstring = "You have used up all "+$data['lockout_threshold']+" allowed login attempts. Please wait "+$time_rem+" minute"+$s+" before attempting to log in again";
+      if ( $data['lockout_policy'] == 'captcha' )
+        $errstring += ', or enter the visual confirmation code shown above in the appropriate box';
+      $errstring += '.';
+      break;
+  }
+  return $errstring;
+}
 
 function ajaxPromptAdminAuth(call_on_ok, level)
 {
@@ -320,6 +365,17 @@
   var title = ( level > USER_LEVEL_MEMBER ) ? 'You are requesting a sensitive operation.' : 'Please enter your username and password to continue.';
   ajax_auth_mb_cache = new messagebox(MB_OKCANCEL|MB_ICONLOCK, title, loading_win);
   ajax_auth_mb_cache.onbeforeclick['OK'] = ajaxValidateLogin;
+  ajax_auth_mb_cache.onbeforeclick['Cancel'] = function()
+  {
+    if ( document.getElementById('autoCaptcha') )
+    {
+      var to = fly_out_top(document.getElementById('autoCaptcha'), false, true);
+      setTimeout(function() {
+          var d = document.getElementById('autoCaptcha');
+          d.parentNode.removeChild(d);
+        }, to);
+    }
+  }
   ajaxAuthLoginInnerSetup();
 }
 
@@ -335,6 +391,20 @@
           return false;
         }
         response = parseJSON(response);
+        var disable_controls = false;
+        if ( response.locked_out && !ajax_auth_error_string )
+        {
+          response.error = 'locked_out';
+          ajax_auth_error_string = ajaxAuthErrorToString(response);
+          if ( response.lockout_policy == 'captcha' )
+          {
+            ajax_auth_show_captcha = response.captcha;
+          }
+          else
+          {
+            disable_controls = true;
+          }
+        }
         var level = ajax_auth_level_cache;
         var form_html = '';
         var shown_error = false;
@@ -348,14 +418,28 @@
         {
           form_html += 'Please re-enter your login details, to verify your identity.<br /><br />';
         }
+        if ( ajax_auth_show_captcha )
+         {
+           var captcha_html = ' \
+             <tr> \
+               <td>Code in image:</td> \
+               <td><input type="hidden" id="ajaxlogin_captcha_hash" value="' + ajax_auth_show_captcha + '" /><input type="text" tabindex="3" size="25" id="ajaxlogin_captcha_code" /> \
+             </tr>';
+         }
+         else
+         {
+           var captcha_html = '';
+         }
+         var disableme = ( disable_controls ) ? 'disabled="disabled" ' : '';
         form_html += ' \
           <table border="0" align="center"> \
             <tr> \
-              <td>Username:</td><td><input tabindex="1" id="ajaxlogin_user" type="text"     size="25" /> \
+              <td>Username:</td><td><input tabindex="1" id="ajaxlogin_user" type="text"     ' + disableme + 'size="25" /> \
             </tr> \
             <tr> \
-              <td>Password:</td><td><input tabindex="2" id="ajaxlogin_pass" type="password" size="25" /> \
+              <td>Password:</td><td><input tabindex="2" id="ajaxlogin_pass" type="password" ' + disableme + 'size="25" /> \
             </tr> \
+            ' + captcha_html + ' \
             <tr> \
               <td colspan="2" style="text-align: center;"> \
                 <br /><small>Trouble logging in? Try the <a href="'+makeUrlNS('Special', 'Login/' + title, 'level=' + level)+'">full login form</a>.<br />';
@@ -383,8 +467,21 @@
         {
           $('ajaxlogin_user').object.focus();
         }
-        $('ajaxlogin_pass').object.onblur = function(e) { if ( !shift ) $('messageBox').object.nextSibling.firstChild.focus(); };
-        $('ajaxlogin_pass').object.onkeypress = function(e) { if ( !e && IE ) return true; if ( e.keyCode == 13 ) $('messageBox').object.nextSibling.firstChild.click(); };
+        if ( ajax_auth_show_captcha )
+        {
+          $('ajaxlogin_captcha_code').object.onblur = function(e) { if ( !shift ) $('messageBox').object.nextSibling.firstChild.focus(); };
+          $('ajaxlogin_captcha_code').object.onkeypress = function(e) { if ( !e && IE ) return true; if ( e.keyCode == 13 ) $('messageBox').object.nextSibling.firstChild.click(); };
+        }
+        else
+        {
+          $('ajaxlogin_pass').object.onblur = function(e) { if ( !shift ) $('messageBox').object.nextSibling.firstChild.focus(); };
+          $('ajaxlogin_pass').object.onkeypress = function(e) { if ( !e && IE ) return true; if ( e.keyCode == 13 ) $('messageBox').object.nextSibling.firstChild.click(); };
+        }
+        if ( disable_controls )
+        {
+          var panel = document.getElementById('messageBoxButtons');
+          panel.firstChild.disabled = true;
+        }
         /*
         ## This causes the background image to disappear under Fx 2
         if ( shown_error )
@@ -398,6 +495,11 @@
           fader.start();
         }
         */
+        if ( ajax_auth_show_captcha )
+        {
+          ajaxShowCaptcha(ajax_auth_show_captcha);
+          ajax_auth_show_captcha = false;
+        }
       }
     });
 }
@@ -412,6 +514,15 @@
   password = document.getElementById('ajaxlogin_pass').value;
   auth_enabled = false;
   
+  if ( document.getElementById('autoCaptcha') )
+  {
+    var to = fly_out_top(document.getElementById('autoCaptcha'), false, true);
+    setTimeout(function() {
+        var d = document.getElementById('autoCaptcha');
+        d.parentNode.removeChild(d);
+      }, to);
+  }
+  
   disableJSONExts();
   
   //
@@ -467,6 +578,12 @@
     'level' : ajax_auth_level_cache
   };
   
+  if ( document.getElementById('ajaxlogin_captcha_hash') )
+  {
+    json_data.captcha_hash = document.getElementById('ajaxlogin_captcha_hash').value;
+    json_data.captcha_code = document.getElementById('ajaxlogin_captcha_code').value;
+  }
+  
   json_data = toJSONString(json_data);
   json_data = encodeURIComponent(json_data);
   
@@ -509,18 +626,23 @@
             }
             break;
           case 'error':
-            if ( response.error == 'The username and/or password is incorrect.' )
+            if ( response.data.error == 'invalid_credentials' || response.data.error == 'locked_out' )
             {
-              ajax_auth_error_string = response.error;
+              ajax_auth_error_string = ajaxAuthErrorToString(response.data);
               mb_current_obj.updateContent('');
               document.getElementById('messageBox').style.backgroundColor = '#C0C0C0';
               var mb_parent = document.getElementById('messageBox').parentNode;
               new Spry.Effect.Shake(mb_parent, {duration: 1500}).start();
               setTimeout("document.getElementById('messageBox').style.backgroundColor = '#FFF'; ajaxAuthLoginInnerSetup();", 2500);
+              
+              if ( response.data.lockout_policy == 'captcha' && response.data.error == 'locked_out' )
+              {
+                ajax_auth_show_captcha = response.captcha;
+              }
             }
             else
             {
-              alert(response.error);
+              ajax_auth_error_string = ajaxAuthErrorToString(response.data);
               ajaxAuthLoginInnerSetup();
             }
             break;
--- a/includes/comment.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/comment.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
--- a/includes/common.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/common.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
@@ -23,7 +23,7 @@
   exit;
 }
 
-$version = '1.0.2';
+$version = '1.1.1';
 
 function microtime_float()
 {
@@ -68,9 +68,6 @@
 if ( file_exists( ENANO_ROOT . '/_nightly.php') )
   require(ENANO_ROOT.'/_nightly.php');
 
-// List of scheduled tasks
-$cron_tasks = array();
-
 // Start including files. LOTS of files. Yeah!
 require_once(ENANO_ROOT.'/includes/constants.php');
 dc_here('Enano CMS '.$version.' (dev) - debug window<br />Powered by debugConsole');
--- a/includes/constants.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/constants.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  * constants.php - important defines used Enano-wide
  *
@@ -70,7 +70,7 @@
 define('MAX_PMS_PER_BATCH', 7); // The maximum number of users that users can send PMs to in one go; restriction does not apply to users with mod_misc rights
 define('SEARCH_RESULTS_PER_PAGE', 10);
 define('MYSQL_MAX_PACKET_SIZE', 1048576); // 1MB; this is the default in MySQL 4.x I think
-define('SEARCH_MODE', 'FULLTEXT'); // Can be FULLTEXT or BUILTIN
+define('SEARCH_MODE', 'BUILTIN'); // Can be FULLTEXT or BUILTIN
 
 // Sidebar
 
--- a/includes/dbal.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/dbal.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
--- a/includes/email.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/email.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
--- a/includes/functions.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/functions.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2796,7 +2796,7 @@
   $strip_tags = implode('|', $strip_tags);
   
   // Strip out the tags and replace with placeholders
-  preg_match_all("#<($strip_tags)([ ]+.*?)?>(.*?)</($strip_tags)>#is", $html, $matches);
+  preg_match_all("#<($strip_tags)(.*?)>(.*?)</($strip_tags)>#is", $html, $matches);
   $seed = md5(microtime() . mt_rand()); // Random value used for placeholders
   for ($i = 0;$i < sizeof($matches[1]); $i++)
   {
@@ -2804,7 +2804,7 @@
   }
   
   // Optimize (but don't obfuscate) Javascript
-  preg_match_all('/<script([ ]+.*?)?>(.*?)(\]\]>)?<\/script>/is', $html, $jscript);
+  preg_match_all('/<script(.*?)>(.+?)<\/script>/is', $html, $jscript);
   
   // list of Javascript reserved words - from about.com
   $reserved_words = array('abstract', 'as', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'continue', 'const', 'debugger', 'default', 'delete', 'do',
@@ -2819,8 +2819,6 @@
   {
     $js =& $jscript[2][$i];
     
-    // echo('<pre>' . "-----------------------------------------------------------------------------\n" . htmlspecialchars($js) . '</pre>');
-    
     // for line optimization, explode it
     $particles = explode("\n", $js);
     
@@ -3168,20 +3166,6 @@
   return $score;
 }
 
-/**
- * Registers a task that will be run every X hours. Scheduled tasks should always be scheduled at runtime - they are not stored in the DB.
- * @param string Function name to call, or array(object, string method)
- * @param int Interval between runs, in hours. Defaults to 24.
- */
-
-function register_cron_task($func, $hour_interval = 24)
-{
-  global $cron_tasks;
-  if ( !isset($cron_tasks[$hour_interval]) )
-    $cron_tasks[$hour_interval] = array();
-  $cron_tasks[$hour_interval][] = $func;
-}
-
 //die('<pre>Original:  01010101010100101010100101010101011010'."\nProcessed: ".uncompress_bitfield(compress_bitfield('01010101010100101010100101010101011010')).'</pre>');
 
 ?>
--- a/includes/graphs.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/graphs.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
--- a/includes/js-compressor.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/js-compressor.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  * Javascript compression library - used to compact the client-side Javascript code (all 72KB of it!) to save some bandwidth
  *
--- a/includes/pageprocess.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/pageprocess.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * pageprocess.php - intelligent retrieval of pages
  * Copyright (C) 2006-2007 Dan Fuhry
  *
--- a/includes/pageutils.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/pageutils.php	Fri Oct 26 19:28:54 2007 -0400
@@ -1,7 +1,8 @@
 <?php
+
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  * pageutils.php - a class that handles raw page manipulations, used mostly by AJAX requests or their old-fashioned form-based counterparts
  *
--- a/includes/paths.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/paths.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /**
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  * paths.php - The part of Enano that actually manages content. Everything related to page handling and namespaces is in here.
  *
--- a/includes/plugins.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/plugins.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
--- a/includes/render.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/render.php	Fri Oct 26 19:28:54 2007 -0400
@@ -708,7 +708,6 @@
       ':-/'     => 'face-plain.png',
       ':joke:'  => 'face-plain.png',
       ']:-&gt;' => 'face-devil-grin.png',
-      ']:->'    => 'face-devil-grin.png',
       ':kiss:'  => 'face-kiss.png',
       ':-P'     => 'face-tongue-out.png',
       ':P'      => 'face-tongue-out.png',
--- a/includes/search.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/search.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  * search.php - algorithm used to search pages
  *
--- a/includes/sessions.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/sessions.php	Fri Oct 26 19:28:54 2007 -0400
@@ -547,14 +547,55 @@
    * @param string $aes_key The MD5 hash of the encryption key, hex-encoded
    * @param string $challenge The 256-bit MD5 challenge string - first 128 bits should be the hash, the last 128 should be the challenge salt
    * @param int $level The privilege level we're authenticating for, defaults to 0
+   * @param array $captcha_hash Optional. If we're locked out and the lockout policy is captcha, this should be the identifier for the code.
+   * @param array $captcha_code Optional. If we're locked out and the lockout policy is captcha, this should be the code the user entered.
    * @return string 'success' on success, or error string on failure
    */
    
-  function login_with_crypto($username, $aes_data, $aes_key, $challenge, $level = USER_LEVEL_MEMBER)
+  function login_with_crypto($username, $aes_data, $aes_key, $challenge, $level = USER_LEVEL_MEMBER, $captcha_hash = false, $captcha_code = false)
   {
     global $db, $session, $paths, $template, $plugins; // Common objects
     
     $privcache = $this->private_key;
+
+    if ( !defined('IN_ENANO_INSTALL') )
+    {
+      // Lockout stuff
+      $threshold = ( $_ = getConfig('lockout_threshold') ) ? intval($_) : 5;
+      $duration  = ( $_ = getConfig('lockout_duration') ) ? intval($_) : 15;
+      // convert to minutes
+      $duration  = $duration * 60;
+      $policy = ( $x = getConfig('lockout_policy') && in_array(getConfig('lockout_policy'), array('lockout', 'disable', 'captcha')) ) ? getConfig('lockout_policy') : 'lockout';
+      if ( $policy == 'captcha' && $captcha_hash && $captcha_code )
+      {
+        // policy is captcha -- check if it's correct, and if so, bypass lockout check
+        $real_code = $this->get_captcha($captcha_hash);
+      }
+      if ( $policy != 'disable' && !( $policy == 'captcha' && isset($real_code) && $real_code == $captcha_code ) )
+      {
+        $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
+        $timestamp_cutoff = time() - $duration;
+        $q = $this->sql('SELECT timestamp FROM '.table_prefix.'lockout WHERE timestamp > ' . $timestamp_cutoff . ' AND ipaddr = \'' . $ipaddr . '\' ORDER BY timestamp DESC;');
+        $fails = $db->numrows();
+        if ( $fails >= $threshold )
+        {
+          // ooh boy, somebody's in trouble ;-)
+          $row = $db->fetchrow();
+          $db->free_result();
+          return array(
+              'success' => false,
+              'error' => 'locked_out',
+              'lockout_threshold' => $threshold,
+              'lockout_duration' => ( $duration / 60 ),
+              'lockout_fails' => $fails,
+              'lockout_policy' => $policy,
+              'time_rem' => ( $duration / 60 ) - round( ( time() - $row['timestamp'] ) / 60 ),
+              'lockout_last_time' => $row['timestamp']
+            );
+        }
+        $db->free_result();
+      }
+    }
     
     // Instanciate the Rijndael encryption object
     $aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
@@ -563,13 +604,19 @@
     
     $aes_key = $this->fetch_public_key($aes_key);
     if(!$aes_key)
-      return 'Couldn\'t look up public key "'.$aes_key.'" for decryption';
+      return array(
+        'success' => false,
+        'error' => 'key_not_found'
+        );
     
     // Convert the key to a binary string
     $bin_key = hexdecode($aes_key);
     
     if(strlen($bin_key) != AES_BITS / 8)
-      return 'The decryption key is the wrong length';
+      return array(
+        'success' => false,
+        'error' => 'key_wrong_length'
+        );
     
     // Decrypt our password
     $password = $aes->decrypt($aes_data, $bin_key, ENC_HEX);
@@ -590,7 +637,29 @@
         $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES(\'security\', \'admin_auth_bad\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
       else
         $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_bad\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
-      return "The username and/or password is incorrect.";  
+    
+      if ( $policy != 'disable' && !defined('IN_ENANO_INSTALL') )
+      {
+        $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
+        // increment fail count
+        $this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action) VALUES(\'' . $ipaddr . '\', UNIX_TIMESTAMP(), \'credential\');');
+        $fails++;
+        // ooh boy, somebody's in trouble ;-)
+        return array(
+            'success' => false,
+            'error' => ( $fails >= $threshold ) ? 'locked_out' : 'invalid_credentials',
+            'lockout_threshold' => $threshold,
+            'lockout_duration' => ( $duration / 60 ),
+            'lockout_fails' => $fails,
+            'time_rem' => ( $duration / 60 ),
+            'lockout_policy' => $policy
+          );
+      }
+      
+      return array(
+          'success' => false,
+          'error' => 'invalid_credentials'
+        );
     }
     $row = $db->fetchrow();
     
@@ -641,7 +710,10 @@
     if($success)
     {
       if($level > $row['user_level'])
-        return 'You are not authorized for this level of access.';
+        return array(
+          'success' => false,
+          'error' => 'too_big_for_britches'
+        );
       
       $sess = $this->register_session(intval($row['user_id']), $username, $password, $level);
       if($sess)
@@ -661,10 +733,15 @@
         {
           eval($cmd);
         }
-        return 'success';
+        return array(
+          'success' => true
+        );
       }
       else
-        return 'Your login credentials were correct, but an internal error occurred while registering the session key in the database.';
+        return array(
+          'success' => false,
+          'error' => 'backend_fail'
+        );
     }
     else
     {
@@ -673,7 +750,28 @@
       else
         $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_bad\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
         
-      return 'The username and/or password is incorrect.';
+      // Do we also need to increment the lockout countdown?
+      if ( $policy != 'disable' && !defined('IN_ENANO_INSTALL') )
+      {
+        $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
+        // increment fail count
+        $this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action) VALUES(\'' . $ipaddr . '\', UNIX_TIMESTAMP(), \'credential\');');
+        $fails++;
+        return array(
+            'success' => false,
+            'error' => ( $fails >= $threshold ) ? 'locked_out' : 'invalid_credentials',
+            'lockout_threshold' => $threshold,
+            'lockout_duration' => ( $duration / 60 ),
+            'lockout_fails' => $fails,
+            'time_rem' => ( $duration / 60 ),
+            'lockout_policy' => $policy
+          );
+      }
+        
+      return array(
+        'success' => false,
+        'error' => 'invalid_credentials'
+      );
     }
   }
   
@@ -699,6 +797,45 @@
       return $this->login_compat($username, $pass_hashed, $level);
     }
     
+    if ( !defined('IN_ENANO_INSTALL') )
+    {
+      // Lockout stuff
+      $threshold = ( $_ = getConfig('lockout_threshold') ) ? intval($_) : 5;
+      $duration  = ( $_ = getConfig('lockout_duration') ) ? intval($_) : 15;
+      // convert to minutes
+      $duration  = $duration * 60;
+      $policy = ( $x = getConfig('lockout_policy') && in_array(getConfig('lockout_policy'), array('lockout', 'disable', 'captcha')) ) ? getConfig('lockout_policy') : 'lockout';
+      if ( $policy == 'captcha' && $captcha_hash && $captcha_code )
+      {
+        // policy is captcha -- check if it's correct, and if so, bypass lockout check
+        $real_code = $this->get_captcha($captcha_hash);
+      }
+      if ( $policy != 'disable' && !( $policy == 'captcha' && isset($real_code) && $real_code == $captcha_code ) )
+      {
+        $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
+        $timestamp_cutoff = time() - $duration;
+        $q = $this->sql('SELECT timestamp FROM '.table_prefix.'lockout WHERE timestamp > ' . $timestamp_cutoff . ' AND ipaddr = \'' . $ipaddr . '\' ORDER BY timestamp DESC;');
+        $fails = $db->numrows();
+        if ( $fails > $threshold )
+        {
+          // ooh boy, somebody's in trouble ;-)
+          $row = $db->fetchrow();
+          $db->free_result();
+          return array(
+              'success' => false,
+              'error' => 'locked_out',
+              'lockout_threshold' => $threshold,
+              'lockout_duration' => ( $duration / 60 ),
+              'lockout_fails' => $fails,
+              'lockout_policy' => $policy,
+              'time_rem' => $duration - round( ( time() - $row['timestamp'] ) / 60 ),
+              'lockout_last_time' => $row['timestamp']
+            );
+        }
+        $db->free_result();
+      }
+    }
+    
     // Instanciate the Rijndael encryption object
     $aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
     
@@ -707,14 +844,35 @@
     
     // Retrieve the real password from the database
     $this->sql('SELECT password,old_encryption,user_id,user_level,temp_password,temp_password_time FROM '.table_prefix.'users WHERE lcase(username)=\''.$this->prepare_text(strtolower($username)).'\';');
-    if ( $db->numrows() < 1 )
+    if($db->numrows() < 1)
     {
       // This wasn't logged in <1.0.2, dunno how it slipped through
       if($level > USER_LEVEL_MEMBER)
         $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES(\'security\', \'admin_auth_bad\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
       else
         $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_bad\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
-      return "The username and/or password is incorrect.";  
+      
+      // Do we also need to increment the lockout countdown?
+      if ( $policy != 'disable' && !defined('IN_ENANO_INSTALL') )
+      {
+        $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
+        // increment fail count
+        $this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action) VALUES(\'' . $ipaddr . '\', UNIX_TIMESTAMP(), \'credential\');');
+        $fails++;
+        return array(
+            'success' => false,
+            'error' => ( $fails >= $threshold ) ? 'locked_out' : 'invalid_credentials',
+            'lockout_threshold' => $threshold,
+            'lockout_duration' => ( $duration / 60 ),
+            'lockout_fails' => $fails,
+            'lockout_policy' => $policy
+          );
+      }
+      
+      return array(
+        'success' => false,
+        'error' => 'invalid_credentials'
+      );
     }
     $row = $db->fetchrow();
     
@@ -764,7 +922,10 @@
     if($success)
     {
       if((int)$level > (int)$row['user_level'])
-        return 'You are not authorized for this level of access.';
+        return array(
+          'success' => false,
+          'error' => 'too_big_for_britches'
+        );
       $sess = $this->register_session(intval($row['user_id']), $username, $real_pass, $level);
       if($sess)
       {
@@ -779,10 +940,15 @@
           eval($cmd);
         }
         
-        return 'success';
+        return array(
+          'success' => true
+          );
       }
       else
-        return 'Your login credentials were correct, but an internal error occured while registering the session key in the database.';
+        return array(
+          'success' => false,
+          'error' => 'backend_fail'
+        );
     }
     else
     {
@@ -791,7 +957,27 @@
       else
         $this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_bad\', '.time().', \''.date('d M Y h:i a').'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
         
-      return 'The username and/or password is incorrect.';
+      // Do we also need to increment the lockout countdown?
+      if ( $policy != 'disable' && !defined('IN_ENANO_INSTALL') )
+      {
+        $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
+        // increment fail count
+        $this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action) VALUES(\'' . $ipaddr . '\', UNIX_TIMESTAMP(), \'credential\');');
+        $fails++;
+        return array(
+            'success' => false,
+            'error' => ( $fails >= $threshold ) ? 'locked_out' : 'invalid_credentials',
+            'lockout_threshold' => $threshold,
+            'lockout_duration' => ( $duration / 60 ),
+            'lockout_fails' => $fails,
+            'lockout_policy' => $policy
+          );
+      }
+        
+      return array(
+        'success' => false,
+        'error' => 'invalid_credentials'
+      );
     }
   }
   
--- a/includes/stats.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/stats.php	Fri Oct 26 19:28:54 2007 -0400
@@ -1,7 +1,8 @@
 <?php
+
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  * stats.php - handles statistics for pages (disablable in the admin CP)
  *
--- a/includes/tagcloud.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/tagcloud.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
--- a/includes/template.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/template.php	Fri Oct 26 19:28:54 2007 -0400
@@ -958,7 +958,6 @@
   
   function compile_tpl_code($text)
   {
-    global $db, $session, $paths, $template, $plugins; // Common objects
     // A random seed used to salt tags
     $seed = md5 ( microtime() . mt_rand() );
     
@@ -987,88 +986,29 @@
     // Conditionals
     //
     
-    $keywords = array('BEGIN', 'BEGINNOT', 'IFSET', 'IFPLUGIN');
-    $code = $plugins->setHook('template_compile_logic_keyword');
-    foreach ( $code as $cmd )
-    {
-      eval($cmd);
-    }
+    // If-else-end
+    $text = preg_replace('/<!-- BEGIN ([A-z0-9_-]+?) -->(.*?)<!-- BEGINELSE \\1 -->(.*?)<!-- END \\1 -->/is', '\'; if ( $this->tpl_bool[\'\\1\'] ) { echo \'\\2\'; } else { echo \'\\3\'; } echo \'', $text);
+    
+    // If-end
+    $text = preg_replace('/<!-- BEGIN ([A-z0-9_-]+?) -->(.*?)<!-- END \\1 -->/is', '\'; if ( $this->tpl_bool[\'\\1\'] ) { echo \'\\2\'; } echo \'', $text);
     
-    $keywords = implode('|', $keywords);
+    // If not-else-end
+    $text = preg_replace('/<!-- BEGINNOT ([A-z0-9_-]+?) -->(.*?)<!-- BEGINELSE \\1 -->(.*?)<!-- END \\1 -->/is', '\'; if ( !$this->tpl_bool[\'\\1\'] ) { echo \'\\2\'; } else { echo \'\\3\'; } echo \'', $text);
     
-    // Matches
-    //          1     2                               3                 4   56                       7     8
-    $regexp = '/(<!-- ('. $keywords .') ([A-z0-9_-]+) -->)(.*)((<!-- BEGINELSE \\3 -->)(.*))?(<!-- END \\3 -->)/isU';
-    
-    /*
-    The way this works is: match all blocks using the standard form with a different keyword in the block each time,
-    and replace them with appropriate PHP logic. Plugin-extensible now. :-)
+    // If not-end
+    $text = preg_replace('/<!-- BEGINNOT ([A-z0-9_-]+?) -->(.*?)<!-- END \\1 -->/is', '\'; if ( !$this->tpl_bool[\'\\1\'] ) { echo \'\\2\'; } echo \'', $text);
     
-    The while-loop is to bypass what is apparently a PCRE bug. It's hackish but it works. Properly written plugins should only need
-    to compile templates (using this method) once for each time the template file is changed.
-    */
-    while ( preg_match($regexp, $text) )
-    {
-      preg_match_all($regexp, $text, $matches);
-      for ( $i = 0; $i < count($matches[0]); $i++ )
-      {
-        $start_tag =& $matches[1][$i];
-        $type =& $matches[2][$i];
-        $test =& $matches[3][$i];
-        $particle_true  =& $matches[4][$i];
-        $else_tag =& $matches[6][$i];
-        $particle_else =& $matches[7][$i];
-        $end_tag =& $matches[8][$i];
-        
-        switch($type)
-        {
-          case 'BEGIN':
-            $cond = "isset(\$this->tpl_bool['$test']) && \$this->tpl_bool['$test']";
-            break;
-          case 'BEGINNOT':
-            $cond = "!isset(\$this->tpl_bool['$test']) || ( isset(\$this->tpl_bool['$test']) && !\$this->tpl_bool['$test'] )";
-            break;
-          case 'IFPLUGIN':
-            $cond = "getConfig('plugin_$test') == '1'";
-            break;
-          case 'IFSET':
-            $cond = "isset(\$this->tpl_strings['$test'])";
-            break;
-          default:
-            $code = $plugins->setHook('template_compile_logic_cond');
-            foreach ( $code as $cmd )
-            {
-              eval($cmd);
-            }
-            break;
-        }
-        
-        if ( !isset($cond) || ( isset($cond) && !is_string($cond) ) )
-          continue;
-        
-        $tag_complete = <<<TPLCODE
-        ';
-        /* START OF CONDITION: $type ($test) */
-        if ( $cond )
-        {
-          echo '$particle_true';
-        /* ELSE OF CONDITION: $type ($test) */
-        }
-        else
-        {
-          echo '$particle_else';
-        /* END OF CONDITION: $type ($test) */
-        }
-        echo '
-TPLCODE;
-        
-        $text = str_replace_once($matches[0][$i], $tag_complete, $text);
-        
-      }
-    }
+    // If set-else-end
+    $text = preg_replace('/<!-- IFSET ([A-z0-9_-]+?) -->(.*?)<!-- BEGINELSE \\1 -->(.*?)<!-- END \\1 -->/is', '\'; if ( isset($this->tpl_strings[\'\\1\']) ) { echo \'\\2\'; } else { echo \'\\3\'; } echo \'', $text);
+    
+    // If set-end
+    $text = preg_replace('/<!-- IFSET ([A-z0-9_-]+?) -->(.*?)<!-- END \\1 -->/is', '\'; if ( isset($this->tpl_strings[\'\\1\']) ) { echo \'\\2\'; } echo \'', $text);
     
-    // For debugging ;-)
-    // die("<pre>&lt;?php\n" . htmlspecialchars($text."\n\n".print_r($matches,true)) . "\n\n?&gt;</pre>");
+    // If plugin loaded-else-end
+    $text = preg_replace('/<!-- IFPLUGIN ([A-z0-9_\.-]+?) -->(.*?)<!-- BEGINELSE \\1 -->(.*?)<!-- END \\1 -->/is', '\'; if ( getConfig(\'plugin_\\1\') == \'1\' ) { echo \'\\2\'; } else { echo \'\\3\'; } echo \'', $text);
+    
+    // If plugin loaded-end
+    $text = preg_replace('/<!-- IFPLUGIN ([A-z0-9_\.-]+?) -->(.*?)<!-- END \\1 -->/is', '\'; if ( getConfig(\'plugin_\\1\') == \'1\' ) { echo \'\\2\'; } echo \'', $text);
     
     //
     // Data substitution/variables
@@ -1089,8 +1029,6 @@
       $text = str_replace_once($tag, "'; $match echo '", $text);
     }
     
-    // echo('<pre>' . htmlspecialchars($text) . '</pre>');
-    
     return $text;  
     
   }
@@ -1473,7 +1411,7 @@
   function username_field($name, $value = false)
   {
     $randomid = md5( time() . microtime() . mt_rand() );
-    $text = '<input name="'.$name.'" onkeyup="new AutofillUsername(this);" autocomplete="off" type="text" size="30" id="userfield_'.$randomid.'"';
+    $text = '<input name="'.$name.'" onkeyup="ajaxUserNameComplete(this)" autocomplete="off" type="text" size="30" id="userfield_'.$randomid.'"';
     if($value) $text .= ' value="'.$value.'"';
     $text .= ' />';
     return $text;
--- a/includes/wikiengine/Tables.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/includes/wikiengine/Tables.php	Fri Oct 26 19:28:54 2007 -0400
@@ -1,8 +1,8 @@
 <?php
 
-/**
+/*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
--- a/index.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/index.php	Fri Oct 26 19:28:54 2007 -0400
@@ -15,7 +15,7 @@
 
   // Set up gzip encoding before any output is sent
   
-  $aggressive_optimize_html = true;
+  $aggressive_optimize_html = false;
   
   global $do_gzip;
   $do_gzip = true;
--- a/install.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/install.php	Fri Oct 26 19:28:54 2007 -0400
@@ -1,1216 +1,1215 @@
-<?php
-
-/*
- * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
- * Copyright (C) 2006-2007 Dan Fuhry
- * install.php - handles everything related to installation and initial configuration
- *
- * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
- * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
- */
- 
-@include('config.php');
-if( ( defined('ENANO_INSTALLED') || defined('MIDGET_INSTALLED') ) && ((isset($_GET['mode']) && ($_GET['mode']!='finish' && $_GET['mode']!='css')) || !isset($_GET['mode'])))
-{
-  $_GET['title'] = 'Enano:Installation_locked';
-  require('includes/common.php');
-  die_friendly('Installation locked', '<p>The Enano installer has found a Enano installation in this directory. You MUST delete config.php if you want to re-install Enano.</p><p>If you wish to upgrade an older Enano installation to this version, please use the <a href="upgrade.php">upgrade script</a>.</p>');
-  exit;
-}
-
-define('IN_ENANO_INSTALL', 'true');
-
-define('ENANO_VERSION', '1.0.2');
-// In beta versions, define ENANO_BETA_VERSION here
-
-if(!defined('scriptPath')) {
-  $sp = dirname($_SERVER['REQUEST_URI']);
-  if($sp == '/' || $sp == '\\') $sp = '';
-  define('scriptPath', $sp);
-}
-
-if(!defined('contentPath')) {
-  $sp = dirname($_SERVER['REQUEST_URI']);
-  if($sp == '/' || $sp == '\\') $sp = '';
-  define('contentPath', $sp);
-}
-global $_starttime, $this_page, $sideinfo;
-$_starttime = microtime(true);
-
-// Determine directory (special case for development servers)
-if ( strpos(__FILE__, '/repo/') && file_exists('.enanodev') )
-{
-  $filename = str_replace('/repo/', '/', __FILE__);
-}
-else
-{
-  $filename = __FILE__;
-}
-
-define('ENANO_ROOT', dirname($filename));
-
-function is_page($p)
-{
-  return true;
-}
-
-require('includes/wikiformat.php');
-require('includes/constants.php');
-require('includes/rijndael.php');
-require('includes/functions.php');
-
-strip_magic_quotes_gpc();
-
-//die('Key size: ' . AES_BITS . '<br />Block size: ' . AES_BLOCKSIZE);
-
-if(!function_exists('wikiFormat'))
-{
-  function wikiFormat($message, $filter_links = true)
-  {
-    $wiki = & Text_Wiki::singleton('Mediawiki');
-    $wiki->setRenderConf('Xhtml', 'code', 'css_filename', 'codefilename');
-    $wiki->setRenderConf('Xhtml', 'wikilink', 'view_url', contentPath);
-    $result = $wiki->transform($message, 'Xhtml');
-    
-    // HTML fixes
-    $result = preg_replace('#<tr>([\s]*?)<\/tr>#is', '', $result);
-    $result = preg_replace('#<p>([\s]*?)<\/p>#is', '', $result);
-    $result = preg_replace('#<br />([\s]*?)<table#is', '<table', $result);
-    
-    return $result;
-  }
-}
-
-global $failed, $warned;
-
-$failed = false;
-$warned = false;
-
-function not($var)
-{
-  if($var)
-  {
-    return false;
-  } 
-  else
-  {
-    return true;
-  }
-}
-
-function run_test($code, $desc, $extended_desc, $warn = false)
-{
-  global $failed, $warned;
-  static $cv = true;
-  $cv = not($cv);
-  $val = eval($code);
-  if($val)
-  {
-    if($cv) $color='CCFFCC'; else $color='AAFFAA';
-    echo "<tr><td style='background-color: #$color; width: 500px;'>$desc</td><td style='padding-left: 10px;'><img alt='Test passed' src='images/good.gif' /></td></tr>";
-  } elseif(!$val && $warn) {
-    if($cv) $color='FFFFCC'; else $color='FFFFAA';
-    echo "<tr><td style='background-color: #$color; width: 500px;'>$desc<br /><b>$extended_desc</b></td><td style='padding-left: 10px;'><img alt='Test passed with warning' src='images/unknown.gif' /></td></tr>";
-    $warned = true;
-  } else {
-    if($cv) $color='FFCCCC'; else $color='FFAAAA';
-    echo "<tr><td style='background-color: #$color; width: 500px;'>$desc<br /><b>$extended_desc</b></td><td style='padding-left: 10px;'><img alt='Test failed' src='images/bad.gif' /></td></tr>";
-    $failed = true;
-  }
-}
-function is_apache() { $r = strstr($_SERVER['SERVER_SOFTWARE'], 'Apache') ? true : false; return $r; }
-
-require_once('includes/template.php');
-
-if(!isset($_GET['mode'])) $_GET['mode'] = 'welcome';
-switch($_GET['mode'])
-{
-  case 'mysql_test':
-    error_reporting(0);
-    $dbhost     = rawurldecode($_POST['host']);
-    $dbname     = rawurldecode($_POST['name']);
-    $dbuser     = rawurldecode($_POST['user']);
-    $dbpass     = rawurldecode($_POST['pass']);
-    $dbrootuser = rawurldecode($_POST['root_user']);
-    $dbrootpass = rawurldecode($_POST['root_pass']);
-    if($dbrootuser != '')
-    {
-      $conn = mysql_connect($dbhost, $dbrootuser, $dbrootpass);
-      if(!$conn)
-      {
-        $e = mysql_error();
-        if(strstr($e, "Lost connection"))
-          die('host'.$e);
-        else
-          die('root'.$e);
-      }
-      $rsp = 'good';
-      $q = mysql_query('USE '.$dbname, $conn);
-      if(!$q)
-      {
-        $e = mysql_error();
-        if(strstr($e, 'Unknown database'))
-        {
-          $rsp .= '_creating_db';
-        }
-      }
-      mysql_close($conn);
-      $conn = mysql_connect($dbhost, $dbuser, $dbpass);
-      if(!$conn)
-      {
-        $e = mysql_error();
-        if(strstr($e, "Lost connection"))
-          die('host'.$e);
-        else
-          $rsp .= '_creating_user';
-      }
-      mysql_close($conn);
-      die($rsp);
-    }
-    else
-    {
-      $conn = mysql_connect($dbhost, $dbuser, $dbpass);
-      if(!$conn)
-      {
-        $e = mysql_error();
-        if(strstr($e, "Lost connection"))
-          die('host'.$e);
-        else
-          die('auth'.$e);
-      }
-      $q = mysql_query('USE '.$dbname, $conn);
-      if(!$q)
-      {
-        $e = mysql_error();
-        if(strstr($e, 'Unknown database'))
-        {
-          die('name'.$e);
-        }
-        else
-        {
-          die('perm'.$e);
-        }
-      }
-    }
-    $v = mysql_get_server_info();
-    if(version_compare($v, '4.1.17', '<')) die('vers'.$v);
-    mysql_close($conn);
-    die('good');
-    break;
-  case 'pophelp':
-    $topic = ( isset($_GET['topic']) ) ? $_GET['topic'] : 'invalid';
-    switch($topic)
-    {
-      case 'admin_embed_php':
-        $title = 'Allow administrators to embed PHP';
-        $content = '<p>This option allows you to control whether anything between the standard &lt;?php and ?&gt; tags will be treated as
-                        PHP code by Enano. If this option is enabled, and members of the Administrators group use these tags, Enano will
-                        execute that code when the page is loaded. There are obvious potential security implications here, which should
-                        be carefully considered before enabling this option.</p>
-                    <p>If you are the only administrator of this site, or if you have a high level of trust for those will be administering
-                       the site with you, you should enable this to allow extreme customization of pages.</p>
-                    <p>Leave this option off if you are at all concerned about security – if your account is compromised and PHP embedding
-                       is enabled, an attacker can run arbitrary code on your server! Enabling this will also allow administrators to
-                       embed Javascript and arbitrary HTML and CSS.</p>
-                    <p>If you don\'t have experience coding in PHP, you can safely disable this option. You may change this at any time
-                       using the ACL editor by selecting the Administrators group and This Entire Website under the scope selection. <!-- , or by
-                       using the "embedded PHP kill switch" in the administration panel. --></p>';
-        break;
-      default:
-        $title = 'Invalid topic';
-        $content = 'Invalid help topic.';
-        break;
-    }
-    echo <<<EOF
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
-<html>
-  <head>
-    <title>Enano installation quick help &bull; {$title}</title>
-    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
-    <style type="text/css">
-      body {
-        font-family: trebuchet ms, verdana, arial, helvetica, sans-serif;
-        font-size: 9pt;
-      }
-      h2          { border-bottom: 1px solid #90B0D0; margin-bottom: 0; }
-      h3          { font-size: 11pt; font-weight: bold; }
-      li          { list-style: url(../images/bullet.gif); }
-      p           { margin: 1.0em; }
-      blockquote  { background-color: #F4F4F4; border: 1px dotted #406080; margin: 1em; padding: 10px; max-height: 250px; overflow: auto; }
-      a           { color: #7090B0; }
-      a:hover     { color: #90B0D0; }
-    </style>
-  </head>
-  <body>
-    <h2>{$title}</h2>
-    {$content}
-    <p style="text-align: right;">
-      <a href="#" onclick="window.close(); return false;">Close window</a>
-    </p>
-  </body>
-</html>
-EOF;
-    exit;
-    break;
-  default:
-    break;
-}
-
-$template = new template_nodb();
-$template->load_theme('oxygen', 'bleu', false);
-
-$modestrings = Array(
-              'welcome' => 'Welcome',
-              'license' => 'License Agreement',
-              'sysreqs' => 'Server requirements',
-              'database'=> 'Database information',
-              'website' => 'Website configuration',
-              'login'   => 'Administration login',
-              'confirm' => 'Confirm installation',
-              'install' => 'Database installation',
-              'finish'  => 'Installation complete'
-            );
-
-$sideinfo = '';
-$vars = $template->extract_vars('elements.tpl');
-$p = $template->makeParserText($vars['sidebar_button']);
-foreach ( $modestrings as $id => $str )
-{
-  if ( $_GET['mode'] == $id )
-  {
-    $flags = 'style="font-weight: bold; text-decoration: underline;"';
-    $this_page = $str;
-  }
-  else
-  {
-    $flags = '';
-  }
-  $p->assign_vars(Array(
-      'HREF' => '#',
-      'FLAGS' => $flags . ' onclick="return false;"',
-      'TEXT' => $str
-    ));
-  $sideinfo .= $p->run();
-}
-
-$template->init_vars();
-
-if(isset($_GET['mode']) && $_GET['mode'] == 'css')
-{
-  header('Content-type: text/css');
-  echo $template->get_css();
-  exit;
-}
-
-$template->header();
-if(!isset($_GET['mode'])) $_GET['mode'] = 'license';
-switch($_GET['mode'])
-{ 
-  default:
-  case 'welcome':
-    ?>
-    <div style="text-align: center; margin-top: 10px;">
-      <img alt="[ Enano CMS Project logo ]" src="images/enano-artwork/installer-greeting-blue.png" style="display: block; margin: 0 auto; padding-left: 100px;" />
-      <h2>Welcome to Enano</h2>
-      <h3>version 1.0.2 &ndash; stable<br />
-      <span style="font-weight: normal;">also affectionately known as "coblynau" <tt>:)</tt></span></h3>
-      <?php
-      if ( file_exists('./_nightly.php') )
-      {
-        echo '<div class="warning-box" style="text-align: left; margin: 10px 0;"><b>You are about to install a NIGHTLY BUILD of Enano.</b><br />Nightly builds are NOT upgradeable and may contain serious flaws, security problems, or extraneous debugging information. Installing this version of Enano on a production site is NOT recommended.</div>';
-      }
-      ?>
-      <form action="install.php?mode=license" method="post">
-        <input type="submit" value="Start installation" />
-      </form>
-    </div>
-    <?php
-    break;
-  case "license":
-    ?>
-    <h3>Welcome to the Enano installer.</h3>
-     <p>Thank you for choosing Enano as your CMS. You've selected the finest in design, the strongest in security, and the latest in Web 2.0 toys. Trust us, you'll like it.</p>
-     <p>To get started, please read and accept the following license agreement. You've probably seen it before.</p>
-     <div style="height: 500px; clip: rect(0px,auto,500px,auto); overflow: auto; padding: 10px; border: 1px dashed #456798; margin: 1em;">
-       <h2>GNU General Public License</h2>
-       <h3>Declaration of license usage</h3>
-       <p>Enano is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.</p>
-       <p>This program is distributed in the hope that it will be useful, but <u>without any warranty</u>; without even the implied warranty of <u>merchantability</u> or <u>fitness for a particular purpose</u>. See the GNU General Public License (below) for more details.</p>
-       <p><b>By clicking the button below or otherwise continuing the installation, you indicate your acceptance of this license agreement.</b></p>
-       <h3>Human-readable version</h3>
-       <p>Enano is distributed under certain licensing terms that we believe make it of the greatest possible use to the public. The license we distribute it under, the GNU General Public License, provides certain terms and conditions that, rather than limit your use of Enano, allow you to get the most out of it. If you would like to read the full text, it can be found below. Here is a human-readable version that we think is a little easier to understand.</p>
-       <ul>
-       <li>You may to run Enano for any purpose.</li>
-       <li>You may study how Enano works and adapt it to your needs.</li>
-       <li>You may redistribute copies so you can help your neighbor.</li>
-       <li>You may improve Enano and release your improvements to the public, so that the whole community benefits.</li>
-       </ul>
-       <p>You may exercise the freedoms specified here provided that you comply with the express conditions of this license. The principal conditions are:</p>
-       <ul>
-       <li>You must conspicuously and appropriately publish on each copy distributed an appropriate copyright notice and disclaimer of warranty and keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of Enano a copy of the GNU General Public License along with Enano. Any translation of the GNU General Public License must be accompanied by the GNU General Public License.</li>
-       <li>If you modify your copy or copies of Enano or any portion of it, or develop a program based upon it, you may distribute the resulting work provided you do so under the GNU General Public License. Any translation of the GNU General Public License must be accompanied by the GNU General Public License.</li>
-       <li>If you copy or distribute Enano, you must accompany it with the complete corresponding machine-readable source code or with a written offer, valid for at least three years, to furnish the complete corresponding machine-readable source code.</li>
-       </ul>
-       <p><b>Disclaimer</b>: The above text is not a license. It is simply a handy reference for understanding the Legal Code (the full license) &ndash; it is a human-readable expression of some of its key terms. Think of it as the user-friendly interface to the Legal Code beneath. The above text itself has no legal value, and its contents do not appear in the actual license.<br /><span style="color: #CCC">Text copied from the <a href="http://creativecommons.org/licenses/GPL/2.0/">Creative Commons GPL Deed page</a></span></p>
-       <?php
-       if ( defined('ENANO_BETA_VERSION') )
-       {
-         ?>
-         <h3>Notice for prerelease versions</h3>
-         <p>This version of Enano is designed only for testing and evaluation purposes. <b>It is not yet completely stable, and should not be used on production websites.</b> As with any Enano version, Dan Fuhry and the Enano team cannot be responsible for any damage, physical or otherwise, to any property as a result of the use of Enano. While security is a number one priority, sometimes things slip through.</p>
-         <?php
-       }
-       ?>
-       <h3>Lawyer-readable version</h3>
-       <?php echo wikiFormat(file_get_contents(ENANO_ROOT . '/GPL')); ?>
-     </div>
-     <div class="pagenav">
-       <form action="install.php?mode=sysreqs" method="post">
-         <table border="0">
-         <tr>
-         <td><input type="submit" value="I agree to the license terms" /></td><td><p><span style="font-weight: bold;">Before clicking continue:</span><br />&bull; Ensure that you agree with the terms of the license<br />&bull; Have your database host, name, username, and password available</p></td>
-         </tr>
-         </table>
-       </form>
-     </div>
-    <?php
-    break;
-  case "sysreqs":
-    error_reporting(E_ALL);
-    ?>
-    <h3>Checking your server</h3>
-     <p>Enano has several requirements that must be met before it can be installed. If all is good then note any warnings and click Continue below.</p>
-    <table border="0" cellspacing="0" cellpadding="0">
-    <?php
-    run_test('return version_compare(\'4.3.0\', PHP_VERSION, \'<\');', 'PHP Version >=4.3.0', 'It seems that the version of PHP that your server is running is too old to support Enano properly. If this is your server, please upgrade to the most recent version of PHP, remembering to use the --with-mysql configure option if you compile it yourself. If this is not your server, please contact your webhost and ask them if it would be possible to upgrade PHP. If this is not possible, you will need to switch to a different webhost in order to use Enano.');
-    run_test('return function_exists(\'mysql_connect\');', 'MySQL extension for PHP', 'It seems that your PHP installation does not have the MySQL extension enabled. If this is your own server, you may need to just enable the "libmysql.so" extension in php.ini. If you do not have the MySQL extension installed, you will need to either use your distribution\'s package manager to install it, or you will have to compile PHP from source. If you compile PHP from source, please remember to use the "--with-mysql" configure option, and you will have to have the MySQL development files installed (they usually are). If this is not your server, please contact your hosting company and ask them to install the PHP MySQL extension.');
-    run_test('return @ini_get(\'file_uploads\');', 'File upload support', 'It seems that your server does not support uploading files. Enano *requires* this functionality in order to work properly. Please ask your server administrator to set the "file_uploads" option in php.ini to "On".');
-    run_test('return is_apache();', 'Apache HTTP Server', 'Apparently your server is running a web server other than Apache. Enano will work nontheless, but there are some known bugs with non-Apache servers, and the "fancy" URLs will not work properly. The "Standard URLs" option will be set on the website configuration page, only change it if you are absolutely certain that your server is running Apache.', true);
-    //run_test('return function_exists(\'finfo_file\');', 'Fileinfo PECL extension', 'The MIME magic PHP extension is used to determine the type of a file by looking for a certain "magic" string of characters inside it. This functionality is used by Enano to more effectively prevent malicious file uploads. The MIME magic option will be disabled by default.', true);
-    run_test('return is_writable(ENANO_ROOT.\'/config.php\');', 'Configuration file writable', 'It looks like the configuration file, config.php, is not writable. Enano needs to be able to write to this file in order to install.<br /><br /><b>If you are installing Enano on a SourceForge web site:</b><br />SourceForge mounts the web partitions read-only now, so you will need to use the project shell service to symlink config.php to a file in the /tmp/persistent directory.');
-    run_test('return file_exists(\'/usr/bin/convert\');', 'ImageMagick support', 'Enano uses ImageMagick to scale images into thumbnails. Because ImageMagick was not found on your server, Enano will use the width= and height= attributes on the &lt;img&gt; tag to scale images. This can cause somewhat of a performance increase, but bandwidth usage will be higher, especially if you use high-resolution images on your site.<br /><br />If you are sure that you have ImageMagick, you can set the location of the "convert" program using the administration panel after installation is complete.', true);
-    run_test('return is_writable(ENANO_ROOT.\'/cache/\');', 'Cache directory writable', 'Apparently the cache/ directory is not writable. Enano will still work, but you will not be able to cache thumbnails, meaning the server will need to re-render them each time they are requested. In some cases, this can cause a significant slowdown.', true);
-    run_test('return is_writable(ENANO_ROOT.\'/files/\');', 'File uploads directory writable', 'It seems that the directory where uploaded files are stored (' . ENANO_ROOT . '/files) cannot be written by the server. Enano will still function, but file uploads will not function, and will be disabled by default.', true);
-    echo '</table>';
-    if(!$failed)
-    {
-      ?>
-      
-      <div class="pagenav">
-      <?php
-      if($warned) {
-        echo '<table border="0" cellspacing="0" cellpadding="0">';
-        run_test('return false;', 'Some scalebacks were made due to your server configuration.', 'Enano has detected that some of the features or configuration settings on your server are not optimal for the best behavior and/or performance for Enano. As a result, certain features or enhancements that are part of Enano have been disabled to prevent further errors. You have seen those "fatal error" notices that spew from PHP, haven\'t you?<br /><br />Fatal error:</b> call to undefined function wannahokaloogie() in file <b>'.__FILE__.'</b> on line <b>'.__LINE__.'', true);
-        echo '</table>';
-      } else {
-        echo '<table border="0" cellspacing="0" cellpadding="0">';
-        run_test('return true;', '<b>Your server meets all the requirements for running Enano.</b><br />Click the button below to continue the installation.', 'You should never see this text. Congratulations for being an Enano hacker!');
-        echo '</table>';
-      }
-      ?>
-       <form action="install.php?mode=database" method="post">
-         <table border="0">
-         <tr>
-         <td><input type="submit" value="Continue" /></td><td><p><span style="font-weight: bold;">Before clicking continue:</span><br />&bull; Ensure that you are satisfied with any scalebacks that may have been made to accomodate your server configuration<br />&bull; Have your database host, name, username, and password available</p></td>
-         </tr>
-         </table>
-       </form>
-     </div>
-     <?php
-    } else {
-      if($failed) {
-        echo '<div class="pagenav"><table border="0" cellspacing="0" cellpadding="0">';
-        run_test('return false;', 'Your server does not meet the requirements for Enano to run.', 'As a precaution, Enano will not install until the above requirements have been met. Contact your server administrator or hosting company and convince them to upgrade. Good luck.');
-        echo '</table></div>';
-      }
-    }
-    ?>
-    <?php
-    break;
-  case "database":
-    ?>
-    <script type="text/javascript">
-      function ajaxGet(uri, f) {
-        if (window.XMLHttpRequest) {
-          ajax = new XMLHttpRequest();
-        } else {
-          if (window.ActiveXObject) {           
-            ajax = new ActiveXObject("Microsoft.XMLHTTP");
-          } else {
-            alert('Enano client-side runtime error: No AJAX support, unable to continue');
-            return;
-          }
-        }
-        ajax.onreadystatechange = f;
-        ajax.open('GET', uri, true);
-        ajax.send(null);
-      }
-      
-      function ajaxPost(uri, parms, f) {
-        if (window.XMLHttpRequest) {
-          ajax = new XMLHttpRequest();
-        } else {
-          if (window.ActiveXObject) {           
-            ajax = new ActiveXObject("Microsoft.XMLHTTP");
-          } else {
-            alert('Enano client-side runtime error: No AJAX support, unable to continue');
-            return;
-          }
-        }
-        ajax.onreadystatechange = f;
-        ajax.open('POST', uri, true);
-        ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
-        ajax.setRequestHeader("Content-length", parms.length);
-        ajax.setRequestHeader("Connection", "close");
-        ajax.send(parms);
-      }
-      function ajaxTestConnection()
-      {
-        v = verify();
-        if(!v)
-        {
-          alert('One or more of the form fields is incorrect. Please correct any information in the form that has an "X" next to it.');
-          return false;
-        }
-        var frm = document.forms.dbinfo;
-        db_host      = escape(frm.db_host.value.replace('+', '%2B'));
-        db_name      = escape(frm.db_name.value.replace('+', '%2B'));
-        db_user      = escape(frm.db_user.value.replace('+', '%2B'));
-        db_pass      = escape(frm.db_pass.value.replace('+', '%2B'));
-        db_root_user = escape(frm.db_root_user.value.replace('+', '%2B'));
-        db_root_pass = escape(frm.db_root_pass.value.replace('+', '%2B'));
-        
-        parms = 'host='+db_host+'&name='+db_name+'&user='+db_user+'&pass='+db_pass+'&root_user='+db_root_user+'&root_pass='+db_root_pass;
-        ajaxPost('<?php echo scriptPath; ?>/install.php?mode=mysql_test', parms, function() {
-            if(ajax.readyState==4)
-            {
-              s = ajax.responseText.substr(0, 4);
-              t = ajax.responseText.substr(4, ajax.responseText.length);
-              if(s.substr(0, 4)=='good')
-              {
-                document.getElementById('s_db_host').src='images/good.gif';
-                document.getElementById('s_db_name').src='images/good.gif';
-                document.getElementById('s_db_auth').src='images/good.gif';
-                document.getElementById('s_db_root').src='images/good.gif';
-                if(t.match(/_creating_db/)) document.getElementById('e_db_name').innerHTML = '<b>Warning:<\/b> The database you specified does not exist. It will be created during installation.';
-                if(t.match(/_creating_user/)) document.getElementById('e_db_auth').innerHTML = '<b>Warning:<\/b> The specified regular user does not exist or the password is incorrect. The user will be created during installation. If the user already exists, the password will be reset.';
-                document.getElementById('s_mysql_version').src='images/good.gif';
-                document.getElementById('e_mysql_version').innerHTML = 'Your version of MySQL meets Enano requirements.';
-              }
-              else
-              {
-                switch(s)
-                {
-                case 'host':
-                  document.getElementById('s_db_host').src='images/bad.gif';
-                  document.getElementById('s_db_name').src='images/unknown.gif';
-                  document.getElementById('s_db_auth').src='images/unknown.gif';
-                  document.getElementById('s_db_root').src='images/unknown.gif';
-                  document.getElementById('e_db_host').innerHTML = '<b>Error:<\/b> The database server "'+document.forms.dbinfo.db_host.value+'" couldn\'t be contacted.<br \/>'+t;
-                  document.getElementById('e_mysql_version').innerHTML = 'The MySQL version that your server is running could not be determined.';
-                  break;
-                case 'auth':
-                  document.getElementById('s_db_host').src='images/good.gif';
-                  document.getElementById('s_db_name').src='images/unknown.gif';
-                  document.getElementById('s_db_auth').src='images/bad.gif';
-                  document.getElementById('s_db_root').src='images/unknown.gif';
-                  document.getElementById('e_db_auth').innerHTML = '<b>Error:<\/b> Access to MySQL under the specified credentials was denied.<br \/>'+t;
-                  document.getElementById('e_mysql_version').innerHTML = 'The MySQL version that your server is running could not be determined.';
-                  break;
-                case 'perm':
-                  document.getElementById('s_db_host').src='images/good.gif';
-                  document.getElementById('s_db_name').src='images/bad.gif';
-                  document.getElementById('s_db_auth').src='images/good.gif';
-                  document.getElementById('s_db_root').src='images/unknown.gif';
-                  document.getElementById('e_db_name').innerHTML = '<b>Error:<\/b> Access to the specified database using those login credentials was denied.<br \/>'+t;
-                  document.getElementById('e_mysql_version').innerHTML = 'The MySQL version that your server is running could not be determined.';
-                  break;
-                case 'name':
-                  document.getElementById('s_db_host').src='images/good.gif';
-                  document.getElementById('s_db_name').src='images/bad.gif';
-                  document.getElementById('s_db_auth').src='images/good.gif';
-                  document.getElementById('s_db_root').src='images/unknown.gif';
-                  document.getElementById('e_db_name').innerHTML = '<b>Error:<\/b> The specified database does not exist<br \/>'+t;
-                  document.getElementById('e_mysql_version').innerHTML = 'The MySQL version that your server is running could not be determined.';
-                  break;
-                case 'root':
-                  document.getElementById('s_db_host').src='images/good.gif';
-                  document.getElementById('s_db_name').src='images/unknown.gif';
-                  document.getElementById('s_db_auth').src='images/unknown.gif';
-                  document.getElementById('s_db_root').src='images/bad.gif';
-                  document.getElementById('e_db_root').innerHTML = '<b>Error:<\/b> Access to MySQL under the specified credentials was denied.<br \/>'+t;
-                  document.getElementById('e_mysql_version').innerHTML = 'The MySQL version that your server is running could not be determined.';
-                  break;
-                case 'vers':
-                  document.getElementById('s_db_host').src='images/good.gif';
-                  document.getElementById('s_db_name').src='images/good.gif';
-                  document.getElementById('s_db_auth').src='images/good.gif';
-                  document.getElementById('s_db_root').src='images/good.gif';
-                  if(t.match(/_creating_db/)) document.getElementById('e_db_name').innerHTML = '<b>Warning:<\/b> The database you specified does not exist. It will be created during installation.';
-                  if(t.match(/_creating_user/)) document.getElementById('e_db_auth').innerHTML = '<b>Warning:<\/b> The specified regular user does not exist or the password is incorrect. The user will be created during installation. If the user already exists, the password will be reset.';
-                  
-                  document.getElementById('e_mysql_version').innerHTML = '<b>Error:<\/b> Your version of MySQL ('+t+') is older than 4.1.17. Enano will still work, but there is a known bug with the comment system and MySQL 4.1.11 that involves some comments not being displayed, due to an issue with the PHP function mysql_fetch_row().';
-                  document.getElementById('s_mysql_version').src='images/bad.gif';
-                default:
-                  alert(t);
-                  break;
-                }
-              }
-            }
-          });
-      }
-      function verify()
-      {
-        document.getElementById('e_db_host').innerHTML = '';
-        document.getElementById('e_db_auth').innerHTML = '';
-        document.getElementById('e_db_name').innerHTML = '';
-        document.getElementById('e_db_root').innerHTML = '';
-        var frm = document.forms.dbinfo;
-        ret = true;
-        if(frm.db_host.value != '')
-        {
-          document.getElementById('s_db_host').src='images/unknown.gif';
-        }
-        else
-        {
-          document.getElementById('s_db_host').src='images/bad.gif';
-          ret = false;
-        }
-        if(frm.db_name.value.match(/^([a-z0-9_]+)$/g))
-        {
-          document.getElementById('s_db_name').src='images/unknown.gif';
-        }
-        else
-        {
-          document.getElementById('s_db_name').src='images/bad.gif';
-          ret = false;
-        }
-        if(frm.db_user.value != '')
-        {
-          document.getElementById('s_db_auth').src='images/unknown.gif';
-        }
-        else
-        {
-          document.getElementById('s_db_auth').src='images/bad.gif';
-          ret = false;
-        }
-        if(frm.table_prefix.value.match(/^([a-z0-9_]*)$/g))
-        {
-          document.getElementById('s_table_prefix').src='images/good.gif';
-        }
-        else
-        {
-          document.getElementById('s_table_prefix').src='images/bad.gif';
-          ret = false;
-        }
-        if(frm.db_root_user.value == '')
-        {
-          document.getElementById('s_db_root').src='images/good.gif';
-        }
-        else if(frm.db_root_user.value != '' && frm.db_root_pass.value == '')
-        {
-          document.getElementById('s_db_root').src='images/bad.gif';
-          ret = false;
-        }
-        else
-        {
-          document.getElementById('s_db_root').src='images/unknown.gif';
-        }
-        if(ret) frm._cont.disabled = false;
-        else    frm._cont.disabled = true;
-        return ret;
-      }
-      window.onload = verify;
-    </script>
-    <p>Now we need some information that will allow Enano to contact your database server. Enano uses MySQL as a data storage backend,
-       and we need to have access to a MySQL server in order to continue.</p>
-    <p>If you do not have access to a MySQL server, and you are using your own server, you can download MySQL for free from
-       <a href="http://www.mysql.com/">MySQL.com</a>. <b>Please note that, like Enano, MySQL is licensed under the GNU GPL.</b>
-       If you need to modify MySQL and then distribute your modifications, you must either distribute them under the terms of the GPL
-       or purchase a proprietary license.</p>
-    <?php
-    if ( file_exists('/etc/enano-is-virt-appliance') )
-    {
-      echo '<p><b>MySQL login information for this virtual appliance:</b><br /><br />Database hostname: localhost<br />Database login: username "enano", password: "clurichaun" (without quotes)<br />Database name: enano_www1</p>';
-    }
-    ?>
-    <form name="dbinfo" action="install.php?mode=website" method="post">
-      <table border="0">
-        <tr><td colspan="3" style="text-align: center"><h3>Database information</h3></td></tr>
-        <tr><td><b>Database hostname</b><br />This is the hostname (or sometimes the IP address) of your MySQL server. In many cases, this is "localhost".<br /><span style="color: #993300" id="e_db_host"></span></td><td><input onkeyup="verify();" name="db_host" size="30" type="text" /></td><td><img id="s_db_host" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
-        <tr><td><b>Database name</b><br />The name of the actual database. If you don't already have a database, you can create one here, if you have the username and password of a MySQL user with administrative rights.<br /><span style="color: #993300" id="e_db_name"></span></td><td><input onkeyup="verify();" name="db_name" size="30" type="text" /></td><td><img id="s_db_name" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
-        <tr><td rowspan="2"><b>Database login</b><br />These fields should be the username and password of a user with "select", "insert", "update", "delete", "create table", and "replace" privileges for your database.<br /><span style="color: #993300" id="e_db_auth"></span></td><td><input onkeyup="verify();" name="db_user" size="30" type="text" /></td><td rowspan="2"><img id="s_db_auth" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
-        <tr><td><input name="db_pass" size="30" type="password" /></td></tr>
-        <tr><td colspan="3" style="text-align: center"><h3>Optional information</h3></td></tr>
-        <tr><td><b>Table prefix</b><br />The value that you enter here will be added to the beginning of the name of each Enano table. You may use lowercase letters (a-z), numbers (0-9), and underscores (_).</td><td><input onkeyup="verify();" name="table_prefix" size="30" type="text" /></td><td><img id="s_table_prefix" alt="Good/bad icon" src="images/good.gif" /></td></tr>
-        <tr><td rowspan="2"><b>Database administrative login</b><br />If the MySQL database or username that you entered above does not exist yet, you can create them here, assuming that you have the login information for an administrative user (such as root). Leave these fields blank unless you need to use them.<br /><span style="color: #993300" id="e_db_root"></span></td><td><input onkeyup="verify();" name="db_root_user" size="30" type="text" /></td><td rowspan="2"><img id="s_db_root" alt="Good/bad icon" src="images/good.gif" /></td></tr>
-        <tr><td><input onkeyup="verify();" name="db_root_pass" size="30" type="password" /></td></tr>
-        <tr><td><b>MySQL version</b></td><td id="e_mysql_version">MySQL version information will be checked when you click "Test Connection".</td><td><img id="s_mysql_version" alt="Good/bad icon" src="images/unknown.gif" /></td></tr>
-        <tr><td><b>Delete existing tables?</b><br />If this option is checked, all the tables that will be used by Enano will be dropped (deleted) before the schema is executed. Do NOT use this option unless specifically instructed to.</td><td><input type="checkbox" name="drop_tables" id="dtcheck" />  <label for="dtcheck">Drop existing tables</label></td></tr>
-        <tr><td colspan="3" style="text-align: center"><input type="button" value="Test connection" onclick="ajaxTestConnection();" /></td></tr>
-      </table>
-      <div class="pagenav">
-       <table border="0">
-       <tr>
-       <td><input type="submit" value="Continue" onclick="return verify();" name="_cont" /></td><td><p><span style="font-weight: bold;">Before clicking continue:</span><br />&bull; Check your MySQL connection using the "Test Connection" button.<br />&bull; Be aware that your database information will be transmitted unencrypted several times.</p></td>
-       </tr>
-       </table>
-     </div>
-    </form>
-    <?php
-    break;
-  case "website":
-    if(!isset($_POST['_cont'])) {
-      echo 'No POST data signature found. Please <a href="install.php?mode=license">restart the installation</a>.';
-      $template->footer();
-      exit;
-    }
-    unset($_POST['_cont']);
-    ?>
-    <script type="text/javascript">
-      function verify()
-      {
-        var frm = document.forms.siteinfo;
-        ret = true;
-        if(frm.sitename.value.match(/^(.+)$/g) && frm.sitename.value != 'Enano')
-        {
-          document.getElementById('s_name').src='images/good.gif';
-        }
-        else
-        {
-          document.getElementById('s_name').src='images/bad.gif';
-          ret = false;
-        }
-        if(frm.sitedesc.value.match(/^(.+)$/g))
-        {
-          document.getElementById('s_desc').src='images/good.gif';
-        }
-        else
-        {
-          document.getElementById('s_desc').src='images/bad.gif';
-          ret = false;
-        }
-        if(frm.copyright.value.match(/^(.+)$/g))
-        {
-          document.getElementById('s_copyright').src='images/good.gif';
-        }
-        else
-        {
-          document.getElementById('s_copyright').src='images/bad.gif';
-          ret = false;
-        }
-        if(ret) frm._cont.disabled = false;
-        else    frm._cont.disabled = true;
-        return ret;
-      }
-      window.onload = verify;
-    </script>
-    <form name="siteinfo" action="install.php?mode=login" method="post">
-      <?php
-        $k = array_keys($_POST);
-        for($i=0;$i<sizeof($_POST);$i++) {
-          echo '<input type="hidden" name="'.htmlspecialchars($k[$i]).'" value="'.htmlspecialchars($_POST[$k[$i]]).'" />'."\n";
-        }
-      ?>
-      <p>The next step is to enter some information about your website. You can always change this information later, using the administration panel.</p>
-      <table border="0">
-        <tr><td><b>Website name</b><br />The display name of your website. Allowed characters are uppercase and lowercase letters, numerals, and spaces. This must not be blank or "Enano".</td><td><input onkeyup="verify();" name="sitename" type="text" size="30" /></td><td><img id="s_name" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
-        <tr><td><b>Website description</b><br />This text will be shown below the name of your website.</td><td><input onkeyup="verify();" name="sitedesc" type="text" size="30" /></td><td><img id="s_desc" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
-        <tr><td><b>Copyright info</b><br />This should be a one-line legal notice that will appear at the bottom of all your pages.</td><td><input onkeyup="verify();" name="copyright" type="text" size="30" /></td><td><img id="s_copyright" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
-        <tr><td><b>Wiki mode</b><br />This feature allows people to create and edit pages on your site. Enano keeps a history of all page modifications, and you can protect pages to prevent editing.</td><td><input name="wiki_mode" type="checkbox" id="wmcheck" />  <label for="wmcheck">Yes, make my website a wiki.</label></td><td></td></tr>
-        <tr><td><b>URL scheme</b><br />Choose how the page URLs will look. Depending on your server configuration, you may need to select the first option. If you don't know, select the first option, and you can always change it later.</td><td colspan="2"><input type="radio" <?php if(!is_apache()) echo 'checked="checked" '; ?>name="urlscheme" value="ugly" id="ugly">  <label for="ugly">Standard URLs - compatible with any web server (www.example.com/index.php?title=Page_name)</label><br /><input type="radio" <?php if(is_apache()) echo 'checked="checked" '; ?>name="urlscheme" value="short" id="short">  <label for="short">Short URLs - requires Apache with a PHP module (www.example.com/index.php/Page_name)</label><br /><input type="radio" name="urlscheme" value="tiny" id="petite">  <label for="petite">Tiny URLs - requires Apache on Linux/Unix/BSD with PHP module and mod_rewrite enabled (www.example.com/Page_name)</label></td></tr>
-      </table>
-      <div class="pagenav">
-       <table border="0">
-       <tr>
-       <td><input type="submit" value="Continue" onclick="return verify();" name="_cont" /></td><td><p><span style="font-weight: bold;">Before clicking continue:</span><br />&bull; Verify that your site information is correct. Again, all of the above settings can be changed from the administration panel.</p></td>
-       </tr>
-       </table>
-     </div>
-    </form>
-    <?php
-    break;
-  case "login":
-    if(!isset($_POST['_cont'])) {
-      echo 'No POST data signature found. Please <a href="install.php?mode=license">restart the installation</a>.';
-      $template->footer();
-      exit;
-    }
-    unset($_POST['_cont']);
-    require('config.php');
-    $aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
-    if ( isset($crypto_key) )
-    {
-      $cryptkey = $crypto_key;
-    }
-    if(!isset($cryptkey) || ( isset($cryptkey) && strlen($cryptkey) != AES_BITS / 4) )
-    {
-      $cryptkey = $aes->gen_readymade_key();
-      $handle = @fopen(ENANO_ROOT.'/config.php', 'w');
-      if(!$handle)
-      {
-        echo '<p>ERROR: Cannot open config.php for writing - exiting!</p>';
-        $template->footer();
-        exit;
-      }
-      fwrite($handle, '<?php $cryptkey = \''.$cryptkey.'\'; ?>');
-      fclose($handle);
-    }
-    ?>
-    <script type="text/javascript">
-      function verify()
-      {
-        var frm = document.forms.login;
-        ret = true;
-        if ( frm.admin_user.value.match(/^([A-z0-9 \-\.]+)$/g) && !frm.admin_user.value.match(/^(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/) && frm.admin_user.value.toLowerCase() != 'anonymous' )
-        {
-          document.getElementById('s_user').src = 'images/good.gif';
-        }
-        else
-        {
-          document.getElementById('s_user').src = 'images/bad.gif';
-          ret = false;
-        }
-        if(frm.admin_pass.value.length >= 6 && frm.admin_pass.value == frm.admin_pass_confirm.value)
-        {
-          document.getElementById('s_password').src = 'images/good.gif';
-        }
-        else
-        {
-          document.getElementById('s_password').src = 'images/bad.gif';
-          ret = false;
-        }
-        if(frm.admin_email.value.match(/^(?:[\w\d]+\.?)+@(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/))
-        {
-          document.getElementById('s_email').src = 'images/good.gif';
-        }
-        else
-        {
-          document.getElementById('s_email').src = 'images/bad.gif';
-          ret = false;
-        }
-        if(ret) frm._cont.disabled = false;
-        else    frm._cont.disabled = true;
-        return ret;
-      }
-      window.onload = verify;
-      
-      function cryptdata() 
-      {
-        if(!verify()) return false;
-      }
-    </script>
-    <form name="login" action="install.php?mode=confirm" method="post" onsubmit="runEncryption();">
-      <?php
-        $k = array_keys($_POST);
-        for($i=0;$i<sizeof($_POST);$i++) {
-          echo '<input type="hidden" name="'.htmlspecialchars($k[$i]).'" value="'.htmlspecialchars($_POST[$k[$i]]).'" />'."\n";
-        }
-      ?>
-      <p>Next, enter your desired username and password. The account you create here will be used to administer your site.</p>
-      <table border="0">
-        <tr><td><b>Administration username</b><br /><small>The administration username you will use to log into your site.<br />This cannot be "anonymous" or in the form of an IP address.</small></td><td><input onkeyup="verify();" name="admin_user" type="text" size="30" /></td><td><img id="s_user" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
-        <tr><td>Administration password:</td><td><input onkeyup="verify();" name="admin_pass" type="password" size="30" /></td><td rowspan="2"><img id="s_password" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
-        <tr><td>Enter it again to confirm:</td><td><input onkeyup="verify();" name="admin_pass_confirm" type="password" size="30" /></td></tr>
-        <tr><td>Your e-mail address:</td><td><input onkeyup="verify();" name="admin_email" type="text" size="30" /></td><td><img id="s_email" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
-        <tr>
-          <td>
-            Allow administrators to embed PHP code into pages:<br />
-            <small><span style="color: #D84308">Do not under any circumstances enable this option without reading these
-                   <a href="install.php?mode=pophelp&amp;topic=admin_embed_php"
-                      onclick="window.open(this.href, 'pophelpwin', 'width=550,height=400,status=no,toolbars=no,toolbar=no,address=no,scroll=yes'); return false;"
-                      style="color: #D84308; text-decoration: underline;">important security implications</a>.
-            </span></small>
-          </td>
-          <td>
-            <label><input type="radio" name="admin_embed_php" value="2" checked="checked" /> Disabled</label>&nbsp;&nbsp;
-            <label><input type="radio" name="admin_embed_php" value="4" /> Enabled</label>
-          </td>
-          <td></td>
-        </tr>
-        <tr><td colspan="3">If your browser supports Javascript, the password you enter here will be encrypted with AES before it is sent to the server.</td></tr>
-      </table>
-      <div class="pagenav">
-       <table border="0">
-       <tr>
-       <td><input type="submit" value="Continue" onclick="return cryptdata();" name="_cont" /></td><td><p><span style="font-weight: bold;">Before clicking continue:</span><br />&bull; Remember the username and password you enter here! You will not be able to administer your site without the information you enter on this page.</p></td>
-       </tr>
-       </table>
-      </div>
-      <div id="cryptdebug"></div>
-     <input type="hidden" name="use_crypt" value="no" />
-     <input type="hidden" name="crypt_key" value="<?php echo $cryptkey; ?>" />
-     <input type="hidden" name="crypt_data" value="" />
-    </form>
-    <script type="text/javascript">
-    // <![CDATA[
-      frm.admin_user.focus();
-      function runEncryption()
-      {
-        str = '';
-        for(i=0;i<keySizeInBits/4;i++) str+='0';
-        var key = hexToByteArray(str);
-        var pt = hexToByteArray(str);
-        var ct = rijndaelEncrypt(pt, key, "ECB");
-        var ect = byteArrayToHex(ct);
-        switch(keySizeInBits)
-        {
-          case 128:
-            v = '66e94bd4ef8a2c3b884cfa59ca342b2e';
-            break;
-          case 192:
-            v = 'aae06992acbf52a3e8f4a96ec9300bd7aae06992acbf52a3e8f4a96ec9300bd7';
-            break;
-          case 256:
-            v = 'dc95c078a2408989ad48a21492842087dc95c078a2408989ad48a21492842087';
-            break;
-        }
-        var testpassed = ( ect == v && md5_vm_test() );
-        var frm = document.forms.login;
-        if(testpassed)
-        {
-          // alert('encryption self-test passed');
-          frm.use_crypt.value = 'yes';
-          var cryptkey = frm.crypt_key.value;
-          frm.crypt_key.value = '';
-          if(cryptkey != byteArrayToHex(hexToByteArray(cryptkey)))
-          {
-            alert('Byte array conversion SUCKS');
-            testpassed = false;
-          }
-          cryptkey = hexToByteArray(cryptkey);
-          if(!cryptkey || ( ( typeof cryptkey == 'string' || typeof cryptkey == 'object' ) ) && cryptkey.length != keySizeInBits / 8 )
-          {
-            frm._cont.disabled = true;
-            len = ( typeof cryptkey == 'string' || typeof cryptkey == 'object' ) ? '\nLen: '+cryptkey.length : '';
-            alert('The key is messed up\nType: '+typeof(cryptkey)+len);
-          }
-        }
-        else
-        {
-          // alert('encryption self-test FAILED');
-        }
-        if(testpassed)
-        {
-          pass = frm.admin_pass.value;
-          pass = stringToByteArray(pass);
-          cryptstring = rijndaelEncrypt(pass, cryptkey, 'ECB');
-          //decrypted = rijndaelDecrypt(cryptstring, cryptkey, 'ECB');
-          //decrypted = byteArrayToString(decrypted);
-          //return false;
-          if(!cryptstring)
-          {
-            return false;
-          }
-          cryptstring = byteArrayToHex(cryptstring);
-          // document.getElementById('cryptdebug').innerHTML = '<pre>Data: '+cryptstring+'<br />Key:  '+byteArrayToHex(cryptkey)+'</pre>';
-          frm.crypt_data.value = cryptstring;
-          frm.admin_pass.value = '';
-          frm.admin_pass_confirm.value = '';
-        }
-        return false;
-      }
-      // ]]>
-    </script>
-    <?php
-    break;
-  case "confirm":
-    if(!isset($_POST['_cont'])) {
-      echo 'No POST data signature found. Please <a href="install.php?mode=license">restart the installation</a>.';
-      $template->footer();
-      exit;
-    }
-    unset($_POST['_cont']);
-    ?>
-    <form name="confirm" action="install.php?mode=install" method="post">
-      <?php
-        $k = array_keys($_POST);
-        for($i=0;$i<sizeof($_POST);$i++) {
-          echo '<input type="hidden" name="'.htmlspecialchars($k[$i]).'" value="'.htmlspecialchars($_POST[$k[$i]]).'" />'."\n";
-        }
-      ?>
-      <h3>Enano is ready to install.</h3>
-       <p>The wizard has finished collecting information and is ready to install the database schema. Please review the information below,
-          and then click the button below to install the database.</p>
-      <ul>
-        <li>Database hostname: <?php echo $_POST['db_host']; ?></li>
-        <li>Database name: <?php echo $_POST['db_name']; ?></li>
-        <li>Database user: <?php echo $_POST['db_user']; ?></li>
-        <li>Database password: &lt;hidden&gt;</li>
-        <li>Site name: <?php echo $_POST['sitename']; ?></li>
-        <li>Site description: <?php echo $_POST['sitedesc']; ?></li>
-        <li>Administration username: <?php echo $_POST['admin_user']; ?></li>
-        <li>Cipher strength: <?php echo (string)AES_BITS; ?>-bit AES<br /><small>Cipher strength is defined in the file constants.php; if you desire to change the cipher strength, you may do so and then restart installation. Unless your site is mission-critical, changing the cipher strength is not necessary.</small></li>
-      </ul>
-      <div class="pagenav">
-        <table border="0">
-          <tr>
-            <td><input type="submit" value="Install Enano!" name="_cont" /></td><td><p><span style="font-weight: bold;">Before clicking continue:</span><br />&bull; Pray.</p></td>
-          </tr>
-        </table>
-      </div>
-    </form>
-    <?php
-    break;
-  case "install":
-    if(!isset($_POST['db_host']) ||
-       !isset($_POST['db_name']) ||
-       !isset($_POST['db_user']) ||
-       !isset($_POST['db_pass']) ||
-       !isset($_POST['sitename']) ||
-       !isset($_POST['sitedesc']) ||
-       !isset($_POST['copyright']) ||
-       !isset($_POST['admin_user']) ||
-       !isset($_POST['admin_pass']) ||
-       !isset($_POST['admin_embed_php']) || ( isset($_POST['admin_embed_php']) && !in_array($_POST['admin_embed_php'], array('2', '4')) ) ||
-       !isset($_POST['urlscheme'])
-       )
-    {
-      echo 'The installer has detected that one or more required form values is not set. Please <a href="install.php?mode=license">restart the installation</a>.';
-      $template->footer();
-      exit;
-    }
-    switch($_POST['urlscheme'])
-    {
-      case "ugly":
-      default:
-        $cp = scriptPath.'/index.php?title=';
-        break;
-      case "short":
-        $cp = scriptPath.'/index.php/';
-        break;
-      case "tiny":
-        $cp = scriptPath.'/';
-        break;
-    }
-    function err($t) { global $template; echo $t; $template->footer(); exit; }
-    
-      echo 'Connecting to MySQL...';
-      if($_POST['db_root_user'] != '')
-      {
-        $conn = mysql_connect($_POST['db_host'], $_POST['db_root_user'], $_POST['db_root_pass']);
-        if(!$conn) err('Error connecting to MySQL: '.mysql_error());
-        $q = mysql_query('USE '.$_POST['db_name']);
-        if(!$q)
-        {
-          $q = mysql_query('CREATE DATABASE '.$_POST['db_name']);
-          if(!$q) err('Error initializing database: '.mysql_error());
-        }
-        $q = mysql_query('GRANT ALL PRIVILEGES ON '.$_POST['db_name'].'.* TO \''.$_POST['db_user'].'\'@\'localhost\' IDENTIFIED BY \''.$_POST['db_pass'].'\' WITH GRANT OPTION;');
-        if(!$q) err('Could not create the user account');
-        $q = mysql_query('GRANT ALL PRIVILEGES ON '.$_POST['db_name'].'.* TO \''.$_POST['db_user'].'\'@\'%\' IDENTIFIED BY \''.$_POST['db_pass'].'\' WITH GRANT OPTION;');
-        if(!$q) err('Could not create the user account');
-        mysql_close($conn);
-      }
-      $conn = mysql_connect($_POST['db_host'], $_POST['db_user'], $_POST['db_pass']);
-      if(!$conn) err('Error connecting to MySQL: '.mysql_error());
-      $q = mysql_query('USE '.$_POST['db_name']);
-      if(!$q) err('Error selecting database: '.mysql_error());
-      echo 'done!<br />';
-      
-      // Are we supposed to drop any existing tables? If so, do it now
-      if(isset($_POST['drop_tables']))
-      {
-        echo 'Dropping existing Enano tables...';
-        // Our list of tables included in Enano
-        $tables = Array( 'mdg_categories', 'mdg_comments', 'mdg_config', 'mdg_logs', 'mdg_page_text', 'mdg_session_keys', 'mdg_pages', 'mdg_users', 'mdg_users_extra', 'mdg_themes', 'mdg_buddies', 'mdg_banlist', 'mdg_files', 'mdg_privmsgs', 'mdg_sidebar', 'mdg_hits', 'mdg_search_index', 'mdg_groups', 'mdg_group_members', 'mdg_acl', 'mdg_search_cache', 'mdg_tags', 'mdg_page_groups', 'mdg_page_group_members' );
-        $tables = implode(', ', $tables);
-        $tables = str_replace('mdg_', $_POST['table_prefix'], $tables);
-        $query_of_death = 'DROP TABLE '.$tables.';';
-        mysql_query($query_of_death); // We won't check for errors here because if this operation fails it probably means the tables didn't exist
-        echo 'done!<br />';
-      }
-      
-      $cacheonoff = is_writable(ENANO_ROOT.'/cache/') ? '1' : '0';
-      
-      echo 'Decrypting administration password...';
-      
-      $aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
-      
-      if ( !empty($_POST['crypt_data']) )
-      {
-        require('config.php');
-        if ( !isset($cryptkey) )
-        {
-          echo 'failed!<br />Cannot get the key from config.php';
-          break;
-        }
-        $key = hexdecode($cryptkey);
-        
-        $dec = $aes->decrypt($_POST['crypt_data'], $key, ENC_HEX);
-        
-      }
-      else
-      {
-        $dec = $_POST['admin_pass'];
-      }
-      echo 'done!<br />Generating '.AES_BITS.'-bit AES private key...';
-      $privkey = $aes->gen_readymade_key();
-      $pkba = hexdecode($privkey);
-      $encpass = $aes->encrypt($dec, $pkba, ENC_HEX);
-      
-      echo 'done!<br />Preparing for schema execution...';
-      $schema = file_get_contents('schema.sql');
-      $schema = str_replace('{{SITE_NAME}}',    mysql_real_escape_string($_POST['sitename']   ), $schema);
-      $schema = str_replace('{{SITE_DESC}}',    mysql_real_escape_string($_POST['sitedesc']   ), $schema);
-      $schema = str_replace('{{COPYRIGHT}}',    mysql_real_escape_string($_POST['copyright']  ), $schema);
-      $schema = str_replace('{{ADMIN_USER}}',   mysql_real_escape_string($_POST['admin_user'] ), $schema);
-      $schema = str_replace('{{ADMIN_PASS}}',   mysql_real_escape_string($encpass             ), $schema);
-      $schema = str_replace('{{ADMIN_EMAIL}}',  mysql_real_escape_string($_POST['admin_email']), $schema);
-      $schema = str_replace('{{ENABLE_CACHE}}', mysql_real_escape_string($cacheonoff          ), $schema);
-      $schema = str_replace('{{REAL_NAME}}',    '',                                              $schema);
-      $schema = str_replace('{{TABLE_PREFIX}}', $_POST['table_prefix'],                          $schema);
-      $schema = str_replace('{{VERSION}}',      ENANO_VERSION,                                   $schema);
-      $schema = str_replace('{{ADMIN_EMBED_PHP}}', $_POST['admin_embed_php'],                    $schema);
-      // Not anymore!! :-D
-      // $schema = str_replace('{{BETA_VERSION}}', ENANO_BETA_VERSION,                              $schema);
-      
-      if(isset($_POST['wiki_mode']))
-      {
-        $schema = str_replace('{{WIKI_MODE}}', '1', $schema);
-      }
-      else
-      {
-        $schema = str_replace('{{WIKI_MODE}}', '0', $schema);
-      }
-      
-      // Build an array of queries      
-      $schema = explode("\n", $schema);
-      
-      foreach ( $schema as $i => $sql )
-      {
-        $query =& $schema[$i];
-        $t = trim($query);
-        if ( empty($t) || preg_match('/^(\#|--)/i', $t) )
-        {
-          unset($schema[$i]);
-          unset($query);
-        }
-      }
-      
-      $schema = array_values($schema);
-      $schema = implode("\n", $schema);
-      $schema = explode(";\n", $schema);
-      
-      foreach ( $schema as $i => $sql )
-      {
-        $query =& $schema[$i];
-        if ( substr($query, ( strlen($query) - 1 ), 1 ) != ';' )
-        {
-          $query .= ';';
-        }
-      }
-      
-      // echo '<pre>' . htmlspecialchars(print_r($schema, true)) . '</pre>';
-      // break;
-      
-      echo 'done!<br />Executing schema.sql...';
-      
-      // OK, do the loop, baby!!!
-      foreach($schema as $q)
-      {
-        $r = mysql_query($q, $conn);
-        if(!$r) err('Error during mainstream installation: '.mysql_error());
-      }
-      
-      echo 'done!<br />Writing configuration files...';
-      if($_POST['urlscheme']=='tiny')
-      {
-        $ht = fopen(ENANO_ROOT.'/.htaccess', 'a+');
-        if(!$ht) err('Error opening file .htaccess for writing');
-        fwrite($ht, '
-RewriteEngine on
-RewriteCond %{REQUEST_FILENAME} !-d
-RewriteCond %{REQUEST_FILENAME} !-f
-RewriteRule ^(.+) '.scriptPath.'/index.php?title=$1 [L,QSA]
-RewriteRule \.(php|html|gif|jpg|png|css|js)$ - [L]
-');
-        fclose($ht);
-      }
-  
-      $config_file = '<?php
-/* Enano auto-generated configuration file - editing not recommended! */
-$dbhost   = \''.addslashes($_POST['db_host']).'\';
-$dbname   = \''.addslashes($_POST['db_name']).'\';
-$dbuser   = \''.addslashes($_POST['db_user']).'\';
-$dbpasswd = \''.addslashes($_POST['db_pass']).'\';
-if(!defined(\'ENANO_CONSTANTS\')) {
-define(\'ENANO_CONSTANTS\', \'\');
-define(\'table_prefix\', \''.$_POST['table_prefix'].'\');
-define(\'scriptPath\', \''.scriptPath.'\');
-define(\'contentPath\', \''.$cp.'\');
-define(\'ENANO_INSTALLED\', \'true\');
-}
-$crypto_key = \''.$privkey.'\';
-?>';
-
-      $cf_handle = fopen(ENANO_ROOT.'/config.php', 'w');
-      if(!$cf_handle) err('Couldn\'t open file config.php for writing');
-      fwrite($cf_handle, $config_file);
-      fclose($cf_handle);
-      
-      echo 'done!<br />Starting the Enano API...';
-      
-      $template_bak = $template;
-      
-      // Get Enano loaded
-      $_GET['title'] = 'Main_Page';
-      require('includes/common.php');
-      
-      // We need to be logged in (with admin rights) before logs can be flushed
-      $session->login_without_crypto($_POST['admin_user'], $dec, false);
-      
-      // Now that login cookies are set, initialize the session manager and ACLs
-      $session->start();
-      $paths->init();
-      
-      unset($template);
-      $template =& $template_bak;
-      
-      echo 'done!<br />Initializing logs...';
-      
-      $q = $db->sql_query('INSERT INTO ' . $_POST['table_prefix'] . 'logs(log_type,action,time_id,date_string,author,page_text,edit_summary) VALUES(\'security\', \'install_enano\', ' . time() . ', \'' . date('d M Y h:i a') . '\', \'' . mysql_real_escape_string($_POST['admin_user']) . '\', \'' . mysql_real_escape_string(ENANO_VERSION) . '\', \'' . mysql_real_escape_string($_SERVER['REMOTE_ADDR']) . '\');', $conn);
-      if ( !$q )
-        err('Error setting up logs: '.$db->get_error());
-      
-      if ( !$session->get_permissions('clear_logs') )
-      {
-        echo '<br />Error: session manager won\'t permit flushing logs, these is a bug.';
-        break;
-      }
-      
-      // unset($session);
-      // $session = new sessionManager();
-      // $session->start();
-      
-      PageUtils::flushlogs('Main_Page', 'Article');
-      
-      echo 'done!<h3>Installation of Enano is complete.</h3><p>Review any warnings above, and then <a href="install.php?mode=finish">click here to finish the installation</a>.';
-      
-      // echo '<script type="text/javascript">window.location="'.scriptPath.'/install.php?mode=finish";</script>';
-      
-    break;
-  case "finish":
-    echo '<h3>Congratulations!</h3>
-           <p>You have finished installing Enano on this server.</p>
-          <h3>Now what?</h3>
-           <p>Click the link below to see the main page for your website. Where to go from here:</p>
-           <ul>
-             <li>The first thing you should do is log into your site using the Log in link on the sidebar.</li>
-             <li>Go into the Administration panel, expand General, and click General Configuration. There you will be able to configure some basic information about your site.</li>
-             <li>Visit the <a href="http://enanocms.org/Category:Plugins" onclick="window.open(this.href); return false;">Enano Plugin Gallery</a> to download and use plugins on your site.</li>
-             <li>Periodically create a backup of your database and filesystem, in case something goes wrong. This should be done at least once a week &ndash; more for wiki-based sites.</li>
-             <li>Hire some moderators, to help you keep rowdy users tame.</li>
-             <li>Tell the <a href="http://enanocms.org/Contact_us">Enano team</a> what you think.</li>
-             <li><b>Spread the word about Enano by adding a link to the Enano homepage on your sidebar!</b> You can enable this option in the General Configuration section of the administration panel.</li>
-           </ul>
-           <p><a href="index.php">Go to your website...</a></p>';
-    break;
-}
-$template->footer();
- 
-?>
+<?php
+
+/*
+ * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
+ * Version 1.1.1
+ * Copyright (C) 2006-2007 Dan Fuhry
+ * install.php - handles everything related to installation and initial configuration
+ *
+ * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
+ */
+ 
+@include('config.php');
+if( ( defined('ENANO_INSTALLED') || defined('MIDGET_INSTALLED') ) && ((isset($_GET['mode']) && ($_GET['mode']!='finish' && $_GET['mode']!='css')) || !isset($_GET['mode'])))
+{
+  $_GET['title'] = 'Enano:Installation_locked';
+  require('includes/common.php');
+  die_friendly('Installation locked', '<p>The Enano installer has found a Enano installation in this directory. You MUST delete config.php if you want to re-install Enano.</p><p>If you wish to upgrade an older Enano installation to this version, please use the <a href="upgrade.php">upgrade script</a>.</p>');
+  exit;
+}
+
+define('IN_ENANO_INSTALL', 'true');
+
+define('ENANO_VERSION', '1.1.1');
+// In beta versions, define ENANO_BETA_VERSION here
+
+if(!defined('scriptPath')) {
+  $sp = dirname($_SERVER['REQUEST_URI']);
+  if($sp == '/' || $sp == '\\') $sp = '';
+  define('scriptPath', $sp);
+}
+
+if(!defined('contentPath')) {
+  $sp = dirname($_SERVER['REQUEST_URI']);
+  if($sp == '/' || $sp == '\\') $sp = '';
+  define('contentPath', $sp);
+}
+global $_starttime, $this_page, $sideinfo;
+$_starttime = microtime(true);
+
+// Determine directory (special case for development servers)
+if ( strpos(__FILE__, '/repo/') && file_exists('.enanodev') )
+{
+  $filename = str_replace('/repo/', '/', __FILE__);
+}
+else
+{
+  $filename = __FILE__;
+}
+
+define('ENANO_ROOT', dirname($filename));
+
+function is_page($p)
+{
+  return true;
+}
+
+require('includes/wikiformat.php');
+require('includes/constants.php');
+require('includes/rijndael.php');
+require('includes/functions.php');
+
+strip_magic_quotes_gpc();
+
+//die('Key size: ' . AES_BITS . '<br />Block size: ' . AES_BLOCKSIZE);
+
+if(!function_exists('wikiFormat'))
+{
+  function wikiFormat($message, $filter_links = true)
+  {
+    $wiki = & Text_Wiki::singleton('Mediawiki');
+    $wiki->setRenderConf('Xhtml', 'code', 'css_filename', 'codefilename');
+    $wiki->setRenderConf('Xhtml', 'wikilink', 'view_url', contentPath);
+    $result = $wiki->transform($message, 'Xhtml');
+    
+    // HTML fixes
+    $result = preg_replace('#<tr>([\s]*?)<\/tr>#is', '', $result);
+    $result = preg_replace('#<p>([\s]*?)<\/p>#is', '', $result);
+    $result = preg_replace('#<br />([\s]*?)<table#is', '<table', $result);
+    
+    return $result;
+  }
+}
+
+global $failed, $warned;
+
+$failed = false;
+$warned = false;
+
+function not($var)
+{
+  if($var)
+  {
+    return false;
+  } 
+  else
+  {
+    return true;
+  }
+}
+
+function run_test($code, $desc, $extended_desc, $warn = false)
+{
+  global $failed, $warned;
+  static $cv = true;
+  $cv = not($cv);
+  $val = eval($code);
+  if($val)
+  {
+    if($cv) $color='CCFFCC'; else $color='AAFFAA';
+    echo "<tr><td style='background-color: #$color; width: 500px;'>$desc</td><td style='padding-left: 10px;'><img alt='Test passed' src='images/good.gif' /></td></tr>";
+  } elseif(!$val && $warn) {
+    if($cv) $color='FFFFCC'; else $color='FFFFAA';
+    echo "<tr><td style='background-color: #$color; width: 500px;'>$desc<br /><b>$extended_desc</b></td><td style='padding-left: 10px;'><img alt='Test passed with warning' src='images/unknown.gif' /></td></tr>";
+    $warned = true;
+  } else {
+    if($cv) $color='FFCCCC'; else $color='FFAAAA';
+    echo "<tr><td style='background-color: #$color; width: 500px;'>$desc<br /><b>$extended_desc</b></td><td style='padding-left: 10px;'><img alt='Test failed' src='images/bad.gif' /></td></tr>";
+    $failed = true;
+  }
+}
+function is_apache() { $r = strstr($_SERVER['SERVER_SOFTWARE'], 'Apache') ? true : false; return $r; }
+
+require_once('includes/template.php');
+
+if(!isset($_GET['mode'])) $_GET['mode'] = 'welcome';
+switch($_GET['mode'])
+{
+  case 'mysql_test':
+    error_reporting(0);
+    $dbhost     = rawurldecode($_POST['host']);
+    $dbname     = rawurldecode($_POST['name']);
+    $dbuser     = rawurldecode($_POST['user']);
+    $dbpass     = rawurldecode($_POST['pass']);
+    $dbrootuser = rawurldecode($_POST['root_user']);
+    $dbrootpass = rawurldecode($_POST['root_pass']);
+    if($dbrootuser != '')
+    {
+      $conn = mysql_connect($dbhost, $dbrootuser, $dbrootpass);
+      if(!$conn)
+      {
+        $e = mysql_error();
+        if(strstr($e, "Lost connection"))
+          die('host'.$e);
+        else
+          die('root'.$e);
+      }
+      $rsp = 'good';
+      $q = mysql_query('USE '.$dbname, $conn);
+      if(!$q)
+      {
+        $e = mysql_error();
+        if(strstr($e, 'Unknown database'))
+        {
+          $rsp .= '_creating_db';
+        }
+      }
+      mysql_close($conn);
+      $conn = mysql_connect($dbhost, $dbuser, $dbpass);
+      if(!$conn)
+      {
+        $e = mysql_error();
+        if(strstr($e, "Lost connection"))
+          die('host'.$e);
+        else
+          $rsp .= '_creating_user';
+      }
+      mysql_close($conn);
+      die($rsp);
+    }
+    else
+    {
+      $conn = mysql_connect($dbhost, $dbuser, $dbpass);
+      if(!$conn)
+      {
+        $e = mysql_error();
+        if(strstr($e, "Lost connection"))
+          die('host'.$e);
+        else
+          die('auth'.$e);
+      }
+      $q = mysql_query('USE '.$dbname, $conn);
+      if(!$q)
+      {
+        $e = mysql_error();
+        if(strstr($e, 'Unknown database'))
+        {
+          die('name'.$e);
+        }
+        else
+        {
+          die('perm'.$e);
+        }
+      }
+    }
+    $v = mysql_get_server_info();
+    if(version_compare($v, '4.1.17', '<')) die('vers'.$v);
+    mysql_close($conn);
+    die('good');
+    break;
+  case 'pophelp':
+    $topic = ( isset($_GET['topic']) ) ? $_GET['topic'] : 'invalid';
+    switch($topic)
+    {
+      case 'admin_embed_php':
+        $title = 'Allow administrators to embed PHP';
+        $content = '<p>This option allows you to control whether anything between the standard &lt;?php and ?&gt; tags will be treated as
+                        PHP code by Enano. If this option is enabled, and members of the Administrators group use these tags, Enano will
+                        execute that code when the page is loaded. There are obvious potential security implications here, which should
+                        be carefully considered before enabling this option.</p>
+                    <p>If you are the only administrator of this site, or if you have a high level of trust for those will be administering
+                       the site with you, you should enable this to allow extreme customization of pages.</p>
+                    <p>Leave this option off if you are at all concerned about security – if your account is compromised and PHP embedding
+                       is enabled, an attacker can run arbitrary code on your server! Enabling this will also allow administrators to
+                       embed Javascript and arbitrary HTML and CSS.</p>
+                    <p>If you don\'t have experience coding in PHP, you can safely disable this option. You may change this at any time
+                       using the ACL editor by selecting the Administrators group and This Entire Website under the scope selection. <!-- , or by
+                       using the "embedded PHP kill switch" in the administration panel. --></p>';
+        break;
+      default:
+        $title = 'Invalid topic';
+        $content = 'Invalid help topic.';
+        break;
+    }
+    echo <<<EOF
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+<html>
+  <head>
+    <title>Enano installation quick help &bull; {$title}</title>
+    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
+    <style type="text/css">
+      body {
+        font-family: trebuchet ms, verdana, arial, helvetica, sans-serif;
+        font-size: 9pt;
+      }
+      h2          { border-bottom: 1px solid #90B0D0; margin-bottom: 0; }
+      h3          { font-size: 11pt; font-weight: bold; }
+      li          { list-style: url(../images/bullet.gif); }
+      p           { margin: 1.0em; }
+      blockquote  { background-color: #F4F4F4; border: 1px dotted #406080; margin: 1em; padding: 10px; max-height: 250px; overflow: auto; }
+      a           { color: #7090B0; }
+      a:hover     { color: #90B0D0; }
+    </style>
+  </head>
+  <body>
+    <h2>{$title}</h2>
+    {$content}
+    <p style="text-align: right;">
+      <a href="#" onclick="window.close(); return false;">Close window</a>
+    </p>
+  </body>
+</html>
+EOF;
+    exit;
+    break;
+  default:
+    break;
+}
+
+$template = new template_nodb();
+$template->load_theme('stpatty', 'shamrock', false);
+
+$modestrings = Array(
+              'welcome' => 'Welcome',
+              'license' => 'License Agreement',
+              'sysreqs' => 'Server requirements',
+              'database'=> 'Database information',
+              'website' => 'Website configuration',
+              'login'   => 'Administration login',
+              'confirm' => 'Confirm installation',
+              'install' => 'Database installation',
+              'finish'  => 'Installation complete'
+            );
+
+$sideinfo = '';
+$vars = $template->extract_vars('elements.tpl');
+$p = $template->makeParserText($vars['sidebar_button']);
+foreach ( $modestrings as $id => $str )
+{
+  if ( $_GET['mode'] == $id )
+  {
+    $flags = 'style="font-weight: bold; text-decoration: underline;"';
+    $this_page = $str;
+  }
+  else
+  {
+    $flags = '';
+  }
+  $p->assign_vars(Array(
+      'HREF' => '#',
+      'FLAGS' => $flags . ' onclick="return false;"',
+      'TEXT' => $str
+    ));
+  $sideinfo .= $p->run();
+}
+
+$template->init_vars();
+
+if(isset($_GET['mode']) && $_GET['mode'] == 'css')
+{
+  header('Content-type: text/css');
+  echo $template->get_css();
+  exit;
+}
+
+$template->header();
+if(!isset($_GET['mode'])) $_GET['mode'] = 'license';
+switch($_GET['mode'])
+{ 
+  default:
+  case 'welcome':
+    ?>
+    <div style="text-align: center; margin-top: 10px;">
+      <img alt="[ Enano CMS Project logo ]" src="images/enano-artwork/installer-greeting-green.png" style="display: block; margin: 0 auto; padding-left: 100px;" />
+      <h2>Welcome to Enano</h2>
+      <h3>version 1.1.1 &ndash; unstable</h3>
+      <?php
+      if ( file_exists('./_nightly.php') )
+      {
+        echo '<div class="warning-box" style="text-align: left; margin: 10px 0;"><b>You are about to install a NIGHTLY BUILD of Enano.</b><br />Nightly builds are NOT upgradeable and may contain serious flaws, security problems, or extraneous debugging information. Installing this version of Enano on a production site is NOT recommended.</div>';
+      }
+      ?>
+      <form action="install.php?mode=license" method="post">
+        <input type="submit" value="Start installation" />
+      </form>
+    </div>
+    <?php
+    break;
+  case "license":
+    ?>
+    <h3>Welcome to the Enano installer.</h3>
+     <p>Thank you for choosing Enano as your CMS. You've selected the finest in design, the strongest in security, and the latest in Web 2.0 toys. Trust us, you'll like it.</p>
+     <p>To get started, please read and accept the following license agreement. You've probably seen it before.</p>
+     <div style="height: 500px; clip: rect(0px,auto,500px,auto); overflow: auto; padding: 10px; border: 1px dashed #456798; margin: 1em;">
+       <h2>GNU General Public License</h2>
+       <h3>Declaration of license usage</h3>
+       <p>Enano is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.</p>
+       <p>This program is distributed in the hope that it will be useful, but <u>without any warranty</u>; without even the implied warranty of <u>merchantability</u> or <u>fitness for a particular purpose</u>. See the GNU General Public License (below) for more details.</p>
+       <p><b>By clicking the button below or otherwise continuing the installation, you indicate your acceptance of this license agreement.</b></p>
+       <h3>Human-readable version</h3>
+       <p>Enano is distributed under certain licensing terms that we believe make it of the greatest possible use to the public. The license we distribute it under, the GNU General Public License, provides certain terms and conditions that, rather than limit your use of Enano, allow you to get the most out of it. If you would like to read the full text, it can be found below. Here is a human-readable version that we think is a little easier to understand.</p>
+       <ul>
+       <li>You may to run Enano for any purpose.</li>
+       <li>You may study how Enano works and adapt it to your needs.</li>
+       <li>You may redistribute copies so you can help your neighbor.</li>
+       <li>You may improve Enano and release your improvements to the public, so that the whole community benefits.</li>
+       </ul>
+       <p>You may exercise the freedoms specified here provided that you comply with the express conditions of this license. The principal conditions are:</p>
+       <ul>
+       <li>You must conspicuously and appropriately publish on each copy distributed an appropriate copyright notice and disclaimer of warranty and keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of Enano a copy of the GNU General Public License along with Enano. Any translation of the GNU General Public License must be accompanied by the GNU General Public License.</li>
+       <li>If you modify your copy or copies of Enano or any portion of it, or develop a program based upon it, you may distribute the resulting work provided you do so under the GNU General Public License. Any translation of the GNU General Public License must be accompanied by the GNU General Public License.</li>
+       <li>If you copy or distribute Enano, you must accompany it with the complete corresponding machine-readable source code or with a written offer, valid for at least three years, to furnish the complete corresponding machine-readable source code.</li>
+       </ul>
+       <p><b>Disclaimer</b>: The above text is not a license. It is simply a handy reference for understanding the Legal Code (the full license) &ndash; it is a human-readable expression of some of its key terms. Think of it as the user-friendly interface to the Legal Code beneath. The above text itself has no legal value, and its contents do not appear in the actual license.<br /><span style="color: #CCC">Text copied from the <a href="http://creativecommons.org/licenses/GPL/2.0/">Creative Commons GPL Deed page</a></span></p>
+       <?php
+       if ( defined('ENANO_BETA_VERSION') )
+       {
+         ?>
+         <h3>Notice for prerelease versions</h3>
+         <p>This version of Enano is designed only for testing and evaluation purposes. <b>It is not yet completely stable, and should not be used on production websites.</b> As with any Enano version, Dan Fuhry and the Enano team cannot be responsible for any damage, physical or otherwise, to any property as a result of the use of Enano. While security is a number one priority, sometimes things slip through.</p>
+         <?php
+       }
+       ?>
+       <h3>Lawyer-readable version</h3>
+       <?php echo wikiFormat(file_get_contents(ENANO_ROOT . '/GPL')); ?>
+     </div>
+     <div class="pagenav">
+       <form action="install.php?mode=sysreqs" method="post">
+         <table border="0">
+         <tr>
+         <td><input type="submit" value="I agree to the license terms" /></td><td><p><span style="font-weight: bold;">Before clicking continue:</span><br />&bull; Ensure that you agree with the terms of the license<br />&bull; Have your database host, name, username, and password available</p></td>
+         </tr>
+         </table>
+       </form>
+     </div>
+    <?php
+    break;
+  case "sysreqs":
+    error_reporting(E_ALL);
+    ?>
+    <h3>Checking your server</h3>
+     <p>Enano has several requirements that must be met before it can be installed. If all is good then note any warnings and click Continue below.</p>
+    <table border="0" cellspacing="0" cellpadding="0">
+    <?php
+    run_test('return version_compare(\'4.3.0\', PHP_VERSION, \'<\');', 'PHP Version >=4.3.0', 'It seems that the version of PHP that your server is running is too old to support Enano properly. If this is your server, please upgrade to the most recent version of PHP, remembering to use the --with-mysql configure option if you compile it yourself. If this is not your server, please contact your webhost and ask them if it would be possible to upgrade PHP. If this is not possible, you will need to switch to a different webhost in order to use Enano.');
+    run_test('return function_exists(\'mysql_connect\');', 'MySQL extension for PHP', 'It seems that your PHP installation does not have the MySQL extension enabled. If this is your own server, you may need to just enable the "libmysql.so" extension in php.ini. If you do not have the MySQL extension installed, you will need to either use your distribution\'s package manager to install it, or you will have to compile PHP from source. If you compile PHP from source, please remember to use the "--with-mysql" configure option, and you will have to have the MySQL development files installed (they usually are). If this is not your server, please contact your hosting company and ask them to install the PHP MySQL extension.');
+    run_test('return @ini_get(\'file_uploads\');', 'File upload support', 'It seems that your server does not support uploading files. Enano *requires* this functionality in order to work properly. Please ask your server administrator to set the "file_uploads" option in php.ini to "On".');
+    run_test('return is_apache();', 'Apache HTTP Server', 'Apparently your server is running a web server other than Apache. Enano will work nontheless, but there are some known bugs with non-Apache servers, and the "fancy" URLs will not work properly. The "Standard URLs" option will be set on the website configuration page, only change it if you are absolutely certain that your server is running Apache.', true);
+    //run_test('return function_exists(\'finfo_file\');', 'Fileinfo PECL extension', 'The MIME magic PHP extension is used to determine the type of a file by looking for a certain "magic" string of characters inside it. This functionality is used by Enano to more effectively prevent malicious file uploads. The MIME magic option will be disabled by default.', true);
+    run_test('return is_writable(ENANO_ROOT.\'/config.php\');', 'Configuration file writable', 'It looks like the configuration file, config.php, is not writable. Enano needs to be able to write to this file in order to install.<br /><br /><b>If you are installing Enano on a SourceForge web site:</b><br />SourceForge mounts the web partitions read-only now, so you will need to use the project shell service to symlink config.php to a file in the /tmp/persistent directory.');
+    run_test('return file_exists(\'/usr/bin/convert\');', 'ImageMagick support', 'Enano uses ImageMagick to scale images into thumbnails. Because ImageMagick was not found on your server, Enano will use the width= and height= attributes on the &lt;img&gt; tag to scale images. This can cause somewhat of a performance increase, but bandwidth usage will be higher, especially if you use high-resolution images on your site.<br /><br />If you are sure that you have ImageMagick, you can set the location of the "convert" program using the administration panel after installation is complete.', true);
+    run_test('return is_writable(ENANO_ROOT.\'/cache/\');', 'Cache directory writable', 'Apparently the cache/ directory is not writable. Enano will still work, but you will not be able to cache thumbnails, meaning the server will need to re-render them each time they are requested. In some cases, this can cause a significant slowdown.', true);
+    run_test('return is_writable(ENANO_ROOT.\'/files/\');', 'File uploads directory writable', 'It seems that the directory where uploaded files are stored (' . ENANO_ROOT . '/files) cannot be written by the server. Enano will still function, but file uploads will not function, and will be disabled by default.', true);
+    echo '</table>';
+    if(!$failed)
+    {
+      ?>
+      
+      <div class="pagenav">
+      <?php
+      if($warned) {
+        echo '<table border="0" cellspacing="0" cellpadding="0">';
+        run_test('return false;', 'Some scalebacks were made due to your server configuration.', 'Enano has detected that some of the features or configuration settings on your server are not optimal for the best behavior and/or performance for Enano. As a result, certain features or enhancements that are part of Enano have been disabled to prevent further errors. You have seen those "fatal error" notices that spew from PHP, haven\'t you?<br /><br />Fatal error:</b> call to undefined function wannahokaloogie() in file <b>'.__FILE__.'</b> on line <b>'.__LINE__.'', true);
+        echo '</table>';
+      } else {
+        echo '<table border="0" cellspacing="0" cellpadding="0">';
+        run_test('return true;', '<b>Your server meets all the requirements for running Enano.</b><br />Click the button below to continue the installation.', 'You should never see this text. Congratulations for being an Enano hacker!');
+        echo '</table>';
+      }
+      ?>
+       <form action="install.php?mode=database" method="post">
+         <table border="0">
+         <tr>
+         <td><input type="submit" value="Continue" /></td><td><p><span style="font-weight: bold;">Before clicking continue:</span><br />&bull; Ensure that you are satisfied with any scalebacks that may have been made to accomodate your server configuration<br />&bull; Have your database host, name, username, and password available</p></td>
+         </tr>
+         </table>
+       </form>
+     </div>
+     <?php
+    } else {
+      if($failed) {
+        echo '<div class="pagenav"><table border="0" cellspacing="0" cellpadding="0">';
+        run_test('return false;', 'Your server does not meet the requirements for Enano to run.', 'As a precaution, Enano will not install until the above requirements have been met. Contact your server administrator or hosting company and convince them to upgrade. Good luck.');
+        echo '</table></div>';
+      }
+    }
+    ?>
+    <?php
+    break;
+  case "database":
+    ?>
+    <script type="text/javascript">
+      function ajaxGet(uri, f) {
+        if (window.XMLHttpRequest) {
+          ajax = new XMLHttpRequest();
+        } else {
+          if (window.ActiveXObject) {           
+            ajax = new ActiveXObject("Microsoft.XMLHTTP");
+          } else {
+            alert('Enano client-side runtime error: No AJAX support, unable to continue');
+            return;
+          }
+        }
+        ajax.onreadystatechange = f;
+        ajax.open('GET', uri, true);
+        ajax.send(null);
+      }
+      
+      function ajaxPost(uri, parms, f) {
+        if (window.XMLHttpRequest) {
+          ajax = new XMLHttpRequest();
+        } else {
+          if (window.ActiveXObject) {           
+            ajax = new ActiveXObject("Microsoft.XMLHTTP");
+          } else {
+            alert('Enano client-side runtime error: No AJAX support, unable to continue');
+            return;
+          }
+        }
+        ajax.onreadystatechange = f;
+        ajax.open('POST', uri, true);
+        ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
+        ajax.setRequestHeader("Content-length", parms.length);
+        ajax.setRequestHeader("Connection", "close");
+        ajax.send(parms);
+      }
+      function ajaxTestConnection()
+      {
+        v = verify();
+        if(!v)
+        {
+          alert('One or more of the form fields is incorrect. Please correct any information in the form that has an "X" next to it.');
+          return false;
+        }
+        var frm = document.forms.dbinfo;
+        db_host      = escape(frm.db_host.value.replace('+', '%2B'));
+        db_name      = escape(frm.db_name.value.replace('+', '%2B'));
+        db_user      = escape(frm.db_user.value.replace('+', '%2B'));
+        db_pass      = escape(frm.db_pass.value.replace('+', '%2B'));
+        db_root_user = escape(frm.db_root_user.value.replace('+', '%2B'));
+        db_root_pass = escape(frm.db_root_pass.value.replace('+', '%2B'));
+        
+        parms = 'host='+db_host+'&name='+db_name+'&user='+db_user+'&pass='+db_pass+'&root_user='+db_root_user+'&root_pass='+db_root_pass;
+        ajaxPost('<?php echo scriptPath; ?>/install.php?mode=mysql_test', parms, function() {
+            if(ajax.readyState==4)
+            {
+              s = ajax.responseText.substr(0, 4);
+              t = ajax.responseText.substr(4, ajax.responseText.length);
+              if(s.substr(0, 4)=='good')
+              {
+                document.getElementById('s_db_host').src='images/good.gif';
+                document.getElementById('s_db_name').src='images/good.gif';
+                document.getElementById('s_db_auth').src='images/good.gif';
+                document.getElementById('s_db_root').src='images/good.gif';
+                if(t.match(/_creating_db/)) document.getElementById('e_db_name').innerHTML = '<b>Warning:<\/b> The database you specified does not exist. It will be created during installation.';
+                if(t.match(/_creating_user/)) document.getElementById('e_db_auth').innerHTML = '<b>Warning:<\/b> The specified regular user does not exist or the password is incorrect. The user will be created during installation. If the user already exists, the password will be reset.';
+                document.getElementById('s_mysql_version').src='images/good.gif';
+                document.getElementById('e_mysql_version').innerHTML = 'Your version of MySQL meets Enano requirements.';
+              }
+              else
+              {
+                switch(s)
+                {
+                case 'host':
+                  document.getElementById('s_db_host').src='images/bad.gif';
+                  document.getElementById('s_db_name').src='images/unknown.gif';
+                  document.getElementById('s_db_auth').src='images/unknown.gif';
+                  document.getElementById('s_db_root').src='images/unknown.gif';
+                  document.getElementById('e_db_host').innerHTML = '<b>Error:<\/b> The database server "'+document.forms.dbinfo.db_host.value+'" couldn\'t be contacted.<br \/>'+t;
+                  document.getElementById('e_mysql_version').innerHTML = 'The MySQL version that your server is running could not be determined.';
+                  break;
+                case 'auth':
+                  document.getElementById('s_db_host').src='images/good.gif';
+                  document.getElementById('s_db_name').src='images/unknown.gif';
+                  document.getElementById('s_db_auth').src='images/bad.gif';
+                  document.getElementById('s_db_root').src='images/unknown.gif';
+                  document.getElementById('e_db_auth').innerHTML = '<b>Error:<\/b> Access to MySQL under the specified credentials was denied.<br \/>'+t;
+                  document.getElementById('e_mysql_version').innerHTML = 'The MySQL version that your server is running could not be determined.';
+                  break;
+                case 'perm':
+                  document.getElementById('s_db_host').src='images/good.gif';
+                  document.getElementById('s_db_name').src='images/bad.gif';
+                  document.getElementById('s_db_auth').src='images/good.gif';
+                  document.getElementById('s_db_root').src='images/unknown.gif';
+                  document.getElementById('e_db_name').innerHTML = '<b>Error:<\/b> Access to the specified database using those login credentials was denied.<br \/>'+t;
+                  document.getElementById('e_mysql_version').innerHTML = 'The MySQL version that your server is running could not be determined.';
+                  break;
+                case 'name':
+                  document.getElementById('s_db_host').src='images/good.gif';
+                  document.getElementById('s_db_name').src='images/bad.gif';
+                  document.getElementById('s_db_auth').src='images/good.gif';
+                  document.getElementById('s_db_root').src='images/unknown.gif';
+                  document.getElementById('e_db_name').innerHTML = '<b>Error:<\/b> The specified database does not exist<br \/>'+t;
+                  document.getElementById('e_mysql_version').innerHTML = 'The MySQL version that your server is running could not be determined.';
+                  break;
+                case 'root':
+                  document.getElementById('s_db_host').src='images/good.gif';
+                  document.getElementById('s_db_name').src='images/unknown.gif';
+                  document.getElementById('s_db_auth').src='images/unknown.gif';
+                  document.getElementById('s_db_root').src='images/bad.gif';
+                  document.getElementById('e_db_root').innerHTML = '<b>Error:<\/b> Access to MySQL under the specified credentials was denied.<br \/>'+t;
+                  document.getElementById('e_mysql_version').innerHTML = 'The MySQL version that your server is running could not be determined.';
+                  break;
+                case 'vers':
+                  document.getElementById('s_db_host').src='images/good.gif';
+                  document.getElementById('s_db_name').src='images/good.gif';
+                  document.getElementById('s_db_auth').src='images/good.gif';
+                  document.getElementById('s_db_root').src='images/good.gif';
+                  if(t.match(/_creating_db/)) document.getElementById('e_db_name').innerHTML = '<b>Warning:<\/b> The database you specified does not exist. It will be created during installation.';
+                  if(t.match(/_creating_user/)) document.getElementById('e_db_auth').innerHTML = '<b>Warning:<\/b> The specified regular user does not exist or the password is incorrect. The user will be created during installation. If the user already exists, the password will be reset.';
+                  
+                  document.getElementById('e_mysql_version').innerHTML = '<b>Error:<\/b> Your version of MySQL ('+t+') is older than 4.1.17. Enano will still work, but there is a known bug with the comment system and MySQL 4.1.11 that involves some comments not being displayed, due to an issue with the PHP function mysql_fetch_row().';
+                  document.getElementById('s_mysql_version').src='images/bad.gif';
+                default:
+                  alert(t);
+                  break;
+                }
+              }
+            }
+          });
+      }
+      function verify()
+      {
+        document.getElementById('e_db_host').innerHTML = '';
+        document.getElementById('e_db_auth').innerHTML = '';
+        document.getElementById('e_db_name').innerHTML = '';
+        document.getElementById('e_db_root').innerHTML = '';
+        var frm = document.forms.dbinfo;
+        ret = true;
+        if(frm.db_host.value != '')
+        {
+          document.getElementById('s_db_host').src='images/unknown.gif';
+        }
+        else
+        {
+          document.getElementById('s_db_host').src='images/bad.gif';
+          ret = false;
+        }
+        if(frm.db_name.value.match(/^([a-z0-9_]+)$/g))
+        {
+          document.getElementById('s_db_name').src='images/unknown.gif';
+        }
+        else
+        {
+          document.getElementById('s_db_name').src='images/bad.gif';
+          ret = false;
+        }
+        if(frm.db_user.value != '')
+        {
+          document.getElementById('s_db_auth').src='images/unknown.gif';
+        }
+        else
+        {
+          document.getElementById('s_db_auth').src='images/bad.gif';
+          ret = false;
+        }
+        if(frm.table_prefix.value.match(/^([a-z0-9_]*)$/g))
+        {
+          document.getElementById('s_table_prefix').src='images/good.gif';
+        }
+        else
+        {
+          document.getElementById('s_table_prefix').src='images/bad.gif';
+          ret = false;
+        }
+        if(frm.db_root_user.value == '')
+        {
+          document.getElementById('s_db_root').src='images/good.gif';
+        }
+        else if(frm.db_root_user.value != '' && frm.db_root_pass.value == '')
+        {
+          document.getElementById('s_db_root').src='images/bad.gif';
+          ret = false;
+        }
+        else
+        {
+          document.getElementById('s_db_root').src='images/unknown.gif';
+        }
+        if(ret) frm._cont.disabled = false;
+        else    frm._cont.disabled = true;
+        return ret;
+      }
+      window.onload = verify;
+    </script>
+    <p>Now we need some information that will allow Enano to contact your database server. Enano uses MySQL as a data storage backend,
+       and we need to have access to a MySQL server in order to continue.</p>
+    <p>If you do not have access to a MySQL server, and you are using your own server, you can download MySQL for free from
+       <a href="http://www.mysql.com/">MySQL.com</a>. <b>Please note that, like Enano, MySQL is licensed under the GNU GPL.</b>
+       If you need to modify MySQL and then distribute your modifications, you must either distribute them under the terms of the GPL
+       or purchase a proprietary license.</p>
+    <?php
+    if ( file_exists('/etc/enano-is-virt-appliance') )
+    {
+      echo '<p><b>MySQL login information for this virtual appliance:</b><br /><br />Database hostname: localhost<br />Database login: username "enano", password: "clurichaun" (without quotes)<br />Database name: enano_www1</p>';
+    }
+    ?>
+    <form name="dbinfo" action="install.php?mode=website" method="post">
+      <table border="0">
+        <tr><td colspan="3" style="text-align: center"><h3>Database information</h3></td></tr>
+        <tr><td><b>Database hostname</b><br />This is the hostname (or sometimes the IP address) of your MySQL server. In many cases, this is "localhost".<br /><span style="color: #993300" id="e_db_host"></span></td><td><input onkeyup="verify();" name="db_host" size="30" type="text" /></td><td><img id="s_db_host" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
+        <tr><td><b>Database name</b><br />The name of the actual database. If you don't already have a database, you can create one here, if you have the username and password of a MySQL user with administrative rights.<br /><span style="color: #993300" id="e_db_name"></span></td><td><input onkeyup="verify();" name="db_name" size="30" type="text" /></td><td><img id="s_db_name" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
+        <tr><td rowspan="2"><b>Database login</b><br />These fields should be the username and password of a user with "select", "insert", "update", "delete", "create table", and "replace" privileges for your database.<br /><span style="color: #993300" id="e_db_auth"></span></td><td><input onkeyup="verify();" name="db_user" size="30" type="text" /></td><td rowspan="2"><img id="s_db_auth" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
+        <tr><td><input name="db_pass" size="30" type="password" /></td></tr>
+        <tr><td colspan="3" style="text-align: center"><h3>Optional information</h3></td></tr>
+        <tr><td><b>Table prefix</b><br />The value that you enter here will be added to the beginning of the name of each Enano table. You may use lowercase letters (a-z), numbers (0-9), and underscores (_).</td><td><input onkeyup="verify();" name="table_prefix" size="30" type="text" /></td><td><img id="s_table_prefix" alt="Good/bad icon" src="images/good.gif" /></td></tr>
+        <tr><td rowspan="2"><b>Database administrative login</b><br />If the MySQL database or username that you entered above does not exist yet, you can create them here, assuming that you have the login information for an administrative user (such as root). Leave these fields blank unless you need to use them.<br /><span style="color: #993300" id="e_db_root"></span></td><td><input onkeyup="verify();" name="db_root_user" size="30" type="text" /></td><td rowspan="2"><img id="s_db_root" alt="Good/bad icon" src="images/good.gif" /></td></tr>
+        <tr><td><input onkeyup="verify();" name="db_root_pass" size="30" type="password" /></td></tr>
+        <tr><td><b>MySQL version</b></td><td id="e_mysql_version">MySQL version information will be checked when you click "Test Connection".</td><td><img id="s_mysql_version" alt="Good/bad icon" src="images/unknown.gif" /></td></tr>
+        <tr><td><b>Delete existing tables?</b><br />If this option is checked, all the tables that will be used by Enano will be dropped (deleted) before the schema is executed. Do NOT use this option unless specifically instructed to.</td><td><input type="checkbox" name="drop_tables" id="dtcheck" />  <label for="dtcheck">Drop existing tables</label></td></tr>
+        <tr><td colspan="3" style="text-align: center"><input type="button" value="Test connection" onclick="ajaxTestConnection();" /></td></tr>
+      </table>
+      <div class="pagenav">
+       <table border="0">
+       <tr>
+       <td><input type="submit" value="Continue" onclick="return verify();" name="_cont" /></td><td><p><span style="font-weight: bold;">Before clicking continue:</span><br />&bull; Check your MySQL connection using the "Test Connection" button.<br />&bull; Be aware that your database information will be transmitted unencrypted several times.</p></td>
+       </tr>
+       </table>
+     </div>
+    </form>
+    <?php
+    break;
+  case "website":
+    if(!isset($_POST['_cont'])) {
+      echo 'No POST data signature found. Please <a href="install.php?mode=license">restart the installation</a>.';
+      $template->footer();
+      exit;
+    }
+    unset($_POST['_cont']);
+    ?>
+    <script type="text/javascript">
+      function verify()
+      {
+        var frm = document.forms.siteinfo;
+        ret = true;
+        if(frm.sitename.value.match(/^(.+)$/g) && frm.sitename.value != 'Enano')
+        {
+          document.getElementById('s_name').src='images/good.gif';
+        }
+        else
+        {
+          document.getElementById('s_name').src='images/bad.gif';
+          ret = false;
+        }
+        if(frm.sitedesc.value.match(/^(.+)$/g))
+        {
+          document.getElementById('s_desc').src='images/good.gif';
+        }
+        else
+        {
+          document.getElementById('s_desc').src='images/bad.gif';
+          ret = false;
+        }
+        if(frm.copyright.value.match(/^(.+)$/g))
+        {
+          document.getElementById('s_copyright').src='images/good.gif';
+        }
+        else
+        {
+          document.getElementById('s_copyright').src='images/bad.gif';
+          ret = false;
+        }
+        if(ret) frm._cont.disabled = false;
+        else    frm._cont.disabled = true;
+        return ret;
+      }
+      window.onload = verify;
+    </script>
+    <form name="siteinfo" action="install.php?mode=login" method="post">
+      <?php
+        $k = array_keys($_POST);
+        for($i=0;$i<sizeof($_POST);$i++) {
+          echo '<input type="hidden" name="'.htmlspecialchars($k[$i]).'" value="'.htmlspecialchars($_POST[$k[$i]]).'" />'."\n";
+        }
+      ?>
+      <p>The next step is to enter some information about your website. You can always change this information later, using the administration panel.</p>
+      <table border="0">
+        <tr><td><b>Website name</b><br />The display name of your website. Allowed characters are uppercase and lowercase letters, numerals, and spaces. This must not be blank or "Enano".</td><td><input onkeyup="verify();" name="sitename" type="text" size="30" /></td><td><img id="s_name" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
+        <tr><td><b>Website description</b><br />This text will be shown below the name of your website.</td><td><input onkeyup="verify();" name="sitedesc" type="text" size="30" /></td><td><img id="s_desc" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
+        <tr><td><b>Copyright info</b><br />This should be a one-line legal notice that will appear at the bottom of all your pages.</td><td><input onkeyup="verify();" name="copyright" type="text" size="30" /></td><td><img id="s_copyright" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
+        <tr><td><b>Wiki mode</b><br />This feature allows people to create and edit pages on your site. Enano keeps a history of all page modifications, and you can protect pages to prevent editing.</td><td><input name="wiki_mode" type="checkbox" id="wmcheck" />  <label for="wmcheck">Yes, make my website a wiki.</label></td><td></td></tr>
+        <tr><td><b>URL scheme</b><br />Choose how the page URLs will look. Depending on your server configuration, you may need to select the first option. If you don't know, select the first option, and you can always change it later.</td><td colspan="2"><input type="radio" <?php if(!is_apache()) echo 'checked="checked" '; ?>name="urlscheme" value="ugly" id="ugly">  <label for="ugly">Standard URLs - compatible with any web server (www.example.com/index.php?title=Page_name)</label><br /><input type="radio" <?php if(is_apache()) echo 'checked="checked" '; ?>name="urlscheme" value="short" id="short">  <label for="short">Short URLs - requires Apache with a PHP module (www.example.com/index.php/Page_name)</label><br /><input type="radio" name="urlscheme" value="tiny" id="petite">  <label for="petite">Tiny URLs - requires Apache on Linux/Unix/BSD with PHP module and mod_rewrite enabled (www.example.com/Page_name)</label></td></tr>
+      </table>
+      <div class="pagenav">
+       <table border="0">
+       <tr>
+       <td><input type="submit" value="Continue" onclick="return verify();" name="_cont" /></td><td><p><span style="font-weight: bold;">Before clicking continue:</span><br />&bull; Verify that your site information is correct. Again, all of the above settings can be changed from the administration panel.</p></td>
+       </tr>
+       </table>
+     </div>
+    </form>
+    <?php
+    break;
+  case "login":
+    if(!isset($_POST['_cont'])) {
+      echo 'No POST data signature found. Please <a href="install.php?mode=license">restart the installation</a>.';
+      $template->footer();
+      exit;
+    }
+    unset($_POST['_cont']);
+    require('config.php');
+    $aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+    if ( isset($crypto_key) )
+    {
+      $cryptkey = $crypto_key;
+    }
+    if(!isset($cryptkey) || ( isset($cryptkey) && strlen($cryptkey) != AES_BITS / 4) )
+    {
+      $cryptkey = $aes->gen_readymade_key();
+      $handle = @fopen(ENANO_ROOT.'/config.php', 'w');
+      if(!$handle)
+      {
+        echo '<p>ERROR: Cannot open config.php for writing - exiting!</p>';
+        $template->footer();
+        exit;
+      }
+      fwrite($handle, '<?php $cryptkey = \''.$cryptkey.'\'; ?>');
+      fclose($handle);
+    }
+    ?>
+    <script type="text/javascript">
+      function verify()
+      {
+        var frm = document.forms.login;
+        ret = true;
+        if ( frm.admin_user.value.match(/^([A-z0-9 \-\.]+)$/g) && !frm.admin_user.value.match(/^(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/) && frm.admin_user.value.toLowerCase() != 'anonymous' )
+        {
+          document.getElementById('s_user').src = 'images/good.gif';
+        }
+        else
+        {
+          document.getElementById('s_user').src = 'images/bad.gif';
+          ret = false;
+        }
+        if(frm.admin_pass.value.length >= 6 && frm.admin_pass.value == frm.admin_pass_confirm.value)
+        {
+          document.getElementById('s_password').src = 'images/good.gif';
+        }
+        else
+        {
+          document.getElementById('s_password').src = 'images/bad.gif';
+          ret = false;
+        }
+        if(frm.admin_email.value.match(/^(?:[\w\d]+\.?)+@(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/))
+        {
+          document.getElementById('s_email').src = 'images/good.gif';
+        }
+        else
+        {
+          document.getElementById('s_email').src = 'images/bad.gif';
+          ret = false;
+        }
+        if(ret) frm._cont.disabled = false;
+        else    frm._cont.disabled = true;
+        return ret;
+      }
+      window.onload = verify;
+      
+      function cryptdata() 
+      {
+        if(!verify()) return false;
+      }
+    </script>
+    <form name="login" action="install.php?mode=confirm" method="post" onsubmit="runEncryption();">
+      <?php
+        $k = array_keys($_POST);
+        for($i=0;$i<sizeof($_POST);$i++) {
+          echo '<input type="hidden" name="'.htmlspecialchars($k[$i]).'" value="'.htmlspecialchars($_POST[$k[$i]]).'" />'."\n";
+        }
+      ?>
+      <p>Next, enter your desired username and password. The account you create here will be used to administer your site.</p>
+      <table border="0">
+        <tr><td><b>Administration username</b><br /><small>The administration username you will use to log into your site.<br />This cannot be "anonymous" or in the form of an IP address.</small></td><td><input onkeyup="verify();" name="admin_user" type="text" size="30" /></td><td><img id="s_user" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
+        <tr><td>Administration password:</td><td><input onkeyup="verify();" name="admin_pass" type="password" size="30" /></td><td rowspan="2"><img id="s_password" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
+        <tr><td>Enter it again to confirm:</td><td><input onkeyup="verify();" name="admin_pass_confirm" type="password" size="30" /></td></tr>
+        <tr><td>Your e-mail address:</td><td><input onkeyup="verify();" name="admin_email" type="text" size="30" /></td><td><img id="s_email" alt="Good/bad icon" src="images/bad.gif" /></td></tr>
+        <tr>
+          <td>
+            Allow administrators to embed PHP code into pages:<br />
+            <small><span style="color: #D84308">Do not under any circumstances enable this option without reading these
+                   <a href="install.php?mode=pophelp&amp;topic=admin_embed_php"
+                      onclick="window.open(this.href, 'pophelpwin', 'width=550,height=400,status=no,toolbars=no,toolbar=no,address=no,scroll=yes'); return false;"
+                      style="color: #D84308; text-decoration: underline;">important security implications</a>.
+            </span></small>
+          </td>
+          <td>
+            <label><input type="radio" name="admin_embed_php" value="2" checked="checked" /> Disabled</label>&nbsp;&nbsp;
+            <label><input type="radio" name="admin_embed_php" value="4" /> Enabled</label>
+          </td>
+          <td></td>
+        </tr>
+        <tr><td colspan="3">If your browser supports Javascript, the password you enter here will be encrypted with AES before it is sent to the server.</td></tr>
+      </table>
+      <div class="pagenav">
+       <table border="0">
+       <tr>
+       <td><input type="submit" value="Continue" onclick="return cryptdata();" name="_cont" /></td><td><p><span style="font-weight: bold;">Before clicking continue:</span><br />&bull; Remember the username and password you enter here! You will not be able to administer your site without the information you enter on this page.</p></td>
+       </tr>
+       </table>
+      </div>
+      <div id="cryptdebug"></div>
+     <input type="hidden" name="use_crypt" value="no" />
+     <input type="hidden" name="crypt_key" value="<?php echo $cryptkey; ?>" />
+     <input type="hidden" name="crypt_data" value="" />
+    </form>
+    <script type="text/javascript">
+    // <![CDATA[
+      frm.admin_user.focus();
+      function runEncryption()
+      {
+        str = '';
+        for(i=0;i<keySizeInBits/4;i++) str+='0';
+        var key = hexToByteArray(str);
+        var pt = hexToByteArray(str);
+        var ct = rijndaelEncrypt(pt, key, "ECB");
+        var ect = byteArrayToHex(ct);
+        switch(keySizeInBits)
+        {
+          case 128:
+            v = '66e94bd4ef8a2c3b884cfa59ca342b2e';
+            break;
+          case 192:
+            v = 'aae06992acbf52a3e8f4a96ec9300bd7aae06992acbf52a3e8f4a96ec9300bd7';
+            break;
+          case 256:
+            v = 'dc95c078a2408989ad48a21492842087dc95c078a2408989ad48a21492842087';
+            break;
+        }
+        var testpassed = ( ect == v && md5_vm_test() );
+        var frm = document.forms.login;
+        if(testpassed)
+        {
+          // alert('encryption self-test passed');
+          frm.use_crypt.value = 'yes';
+          var cryptkey = frm.crypt_key.value;
+          frm.crypt_key.value = '';
+          if(cryptkey != byteArrayToHex(hexToByteArray(cryptkey)))
+          {
+            alert('Byte array conversion SUCKS');
+            testpassed = false;
+          }
+          cryptkey = hexToByteArray(cryptkey);
+          if(!cryptkey || ( ( typeof cryptkey == 'string' || typeof cryptkey == 'object' ) ) && cryptkey.length != keySizeInBits / 8 )
+          {
+            frm._cont.disabled = true;
+            len = ( typeof cryptkey == 'string' || typeof cryptkey == 'object' ) ? '\nLen: '+cryptkey.length : '';
+            alert('The key is messed up\nType: '+typeof(cryptkey)+len);
+          }
+        }
+        else
+        {
+          // alert('encryption self-test FAILED');
+        }
+        if(testpassed)
+        {
+          pass = frm.admin_pass.value;
+          pass = stringToByteArray(pass);
+          cryptstring = rijndaelEncrypt(pass, cryptkey, 'ECB');
+          //decrypted = rijndaelDecrypt(cryptstring, cryptkey, 'ECB');
+          //decrypted = byteArrayToString(decrypted);
+          //return false;
+          if(!cryptstring)
+          {
+            return false;
+          }
+          cryptstring = byteArrayToHex(cryptstring);
+          // document.getElementById('cryptdebug').innerHTML = '<pre>Data: '+cryptstring+'<br />Key:  '+byteArrayToHex(cryptkey)+'</pre>';
+          frm.crypt_data.value = cryptstring;
+          frm.admin_pass.value = '';
+          frm.admin_pass_confirm.value = '';
+        }
+        return false;
+      }
+      // ]]>
+    </script>
+    <?php
+    break;
+  case "confirm":
+    if(!isset($_POST['_cont'])) {
+      echo 'No POST data signature found. Please <a href="install.php?mode=license">restart the installation</a>.';
+      $template->footer();
+      exit;
+    }
+    unset($_POST['_cont']);
+    ?>
+    <form name="confirm" action="install.php?mode=install" method="post">
+      <?php
+        $k = array_keys($_POST);
+        for($i=0;$i<sizeof($_POST);$i++) {
+          echo '<input type="hidden" name="'.htmlspecialchars($k[$i]).'" value="'.htmlspecialchars($_POST[$k[$i]]).'" />'."\n";
+        }
+      ?>
+      <h3>Enano is ready to install.</h3>
+       <p>The wizard has finished collecting information and is ready to install the database schema. Please review the information below,
+          and then click the button below to install the database.</p>
+      <ul>
+        <li>Database hostname: <?php echo $_POST['db_host']; ?></li>
+        <li>Database name: <?php echo $_POST['db_name']; ?></li>
+        <li>Database user: <?php echo $_POST['db_user']; ?></li>
+        <li>Database password: &lt;hidden&gt;</li>
+        <li>Site name: <?php echo $_POST['sitename']; ?></li>
+        <li>Site description: <?php echo $_POST['sitedesc']; ?></li>
+        <li>Administration username: <?php echo $_POST['admin_user']; ?></li>
+        <li>Cipher strength: <?php echo (string)AES_BITS; ?>-bit AES<br /><small>Cipher strength is defined in the file constants.php; if you desire to change the cipher strength, you may do so and then restart installation. Unless your site is mission-critical, changing the cipher strength is not necessary.</small></li>
+      </ul>
+      <div class="pagenav">
+        <table border="0">
+          <tr>
+            <td><input type="submit" value="Install Enano!" name="_cont" /></td><td><p><span style="font-weight: bold;">Before clicking continue:</span><br />&bull; Pray.</p></td>
+          </tr>
+        </table>
+      </div>
+    </form>
+    <?php
+    break;
+  case "install":
+    if(!isset($_POST['db_host']) ||
+       !isset($_POST['db_name']) ||
+       !isset($_POST['db_user']) ||
+       !isset($_POST['db_pass']) ||
+       !isset($_POST['sitename']) ||
+       !isset($_POST['sitedesc']) ||
+       !isset($_POST['copyright']) ||
+       !isset($_POST['admin_user']) ||
+       !isset($_POST['admin_pass']) ||
+       !isset($_POST['admin_embed_php']) || ( isset($_POST['admin_embed_php']) && !in_array($_POST['admin_embed_php'], array('2', '4')) ) ||
+       !isset($_POST['urlscheme'])
+       )
+    {
+      echo 'The installer has detected that one or more required form values is not set. Please <a href="install.php?mode=license">restart the installation</a>.';
+      $template->footer();
+      exit;
+    }
+    switch($_POST['urlscheme'])
+    {
+      case "ugly":
+      default:
+        $cp = scriptPath.'/index.php?title=';
+        break;
+      case "short":
+        $cp = scriptPath.'/index.php/';
+        break;
+      case "tiny":
+        $cp = scriptPath.'/';
+        break;
+    }
+    function err($t) { global $template; echo $t; $template->footer(); exit; }
+    
+      echo 'Connecting to MySQL...';
+      if($_POST['db_root_user'] != '')
+      {
+        $conn = mysql_connect($_POST['db_host'], $_POST['db_root_user'], $_POST['db_root_pass']);
+        if(!$conn) err('Error connecting to MySQL: '.mysql_error());
+        $q = mysql_query('USE '.$_POST['db_name']);
+        if(!$q)
+        {
+          $q = mysql_query('CREATE DATABASE '.$_POST['db_name']);
+          if(!$q) err('Error initializing database: '.mysql_error());
+        }
+        $q = mysql_query('GRANT ALL PRIVILEGES ON '.$_POST['db_name'].'.* TO \''.$_POST['db_user'].'\'@\'localhost\' IDENTIFIED BY \''.$_POST['db_pass'].'\' WITH GRANT OPTION;');
+        if(!$q) err('Could not create the user account');
+        $q = mysql_query('GRANT ALL PRIVILEGES ON '.$_POST['db_name'].'.* TO \''.$_POST['db_user'].'\'@\'%\' IDENTIFIED BY \''.$_POST['db_pass'].'\' WITH GRANT OPTION;');
+        if(!$q) err('Could not create the user account');
+        mysql_close($conn);
+      }
+      $conn = mysql_connect($_POST['db_host'], $_POST['db_user'], $_POST['db_pass']);
+      if(!$conn) err('Error connecting to MySQL: '.mysql_error());
+      $q = mysql_query('USE '.$_POST['db_name']);
+      if(!$q) err('Error selecting database: '.mysql_error());
+      echo 'done!<br />';
+      
+      // Are we supposed to drop any existing tables? If so, do it now
+      if(isset($_POST['drop_tables']))
+      {
+        echo 'Dropping existing Enano tables...';
+        // Our list of tables included in Enano
+        $tables = Array( 'mdg_categories', 'mdg_comments', 'mdg_config', 'mdg_logs', 'mdg_page_text', 'mdg_session_keys', 'mdg_pages', 'mdg_users', 'mdg_users_extra', 'mdg_themes', 'mdg_buddies', 'mdg_banlist', 'mdg_files', 'mdg_privmsgs', 'mdg_sidebar', 'mdg_hits', 'mdg_search_index', 'mdg_groups', 'mdg_group_members', 'mdg_acl', 'mdg_search_cache', 'mdg_tags', 'mdg_page_groups', 'mdg_page_group_members' );
+        $tables = implode(', ', $tables);
+        $tables = str_replace('mdg_', $_POST['table_prefix'], $tables);
+        $query_of_death = 'DROP TABLE '.$tables.';';
+        mysql_query($query_of_death); // We won't check for errors here because if this operation fails it probably means the tables didn't exist
+        echo 'done!<br />';
+      }
+      
+      $cacheonoff = is_writable(ENANO_ROOT.'/cache/') ? '1' : '0';
+      
+      echo 'Decrypting administration password...';
+      
+      $aes = new AESCrypt(AES_BITS, AES_BLOCKSIZE);
+      
+      if ( !empty($_POST['crypt_data']) )
+      {
+        require('config.php');
+        if ( !isset($cryptkey) )
+        {
+          echo 'failed!<br />Cannot get the key from config.php';
+          break;
+        }
+        $key = hexdecode($cryptkey);
+        
+        $dec = $aes->decrypt($_POST['crypt_data'], $key, ENC_HEX);
+        
+      }
+      else
+      {
+        $dec = $_POST['admin_pass'];
+      }
+      echo 'done!<br />Generating '.AES_BITS.'-bit AES private key...';
+      $privkey = $aes->gen_readymade_key();
+      $pkba = hexdecode($privkey);
+      $encpass = $aes->encrypt($dec, $pkba, ENC_HEX);
+      
+      echo 'done!<br />Preparing for schema execution...';
+      $schema = file_get_contents('schema.sql');
+      $schema = str_replace('{{SITE_NAME}}',    mysql_real_escape_string($_POST['sitename']   ), $schema);
+      $schema = str_replace('{{SITE_DESC}}',    mysql_real_escape_string($_POST['sitedesc']   ), $schema);
+      $schema = str_replace('{{COPYRIGHT}}',    mysql_real_escape_string($_POST['copyright']  ), $schema);
+      $schema = str_replace('{{ADMIN_USER}}',   mysql_real_escape_string($_POST['admin_user'] ), $schema);
+      $schema = str_replace('{{ADMIN_PASS}}',   mysql_real_escape_string($encpass             ), $schema);
+      $schema = str_replace('{{ADMIN_EMAIL}}',  mysql_real_escape_string($_POST['admin_email']), $schema);
+      $schema = str_replace('{{ENABLE_CACHE}}', mysql_real_escape_string($cacheonoff          ), $schema);
+      $schema = str_replace('{{REAL_NAME}}',    '',                                              $schema);
+      $schema = str_replace('{{TABLE_PREFIX}}', $_POST['table_prefix'],                          $schema);
+      $schema = str_replace('{{VERSION}}',      ENANO_VERSION,                                   $schema);
+      $schema = str_replace('{{ADMIN_EMBED_PHP}}', $_POST['admin_embed_php'],                    $schema);
+      // Not anymore!! :-D
+      // $schema = str_replace('{{BETA_VERSION}}', ENANO_BETA_VERSION,                              $schema);
+      
+      if(isset($_POST['wiki_mode']))
+      {
+        $schema = str_replace('{{WIKI_MODE}}', '1', $schema);
+      }
+      else
+      {
+        $schema = str_replace('{{WIKI_MODE}}', '0', $schema);
+      }
+      
+      // Build an array of queries      
+      $schema = explode("\n", $schema);
+      
+      foreach ( $schema as $i => $sql )
+      {
+        $query =& $schema[$i];
+        $t = trim($query);
+        if ( empty($t) || preg_match('/^(\#|--)/i', $t) )
+        {
+          unset($schema[$i]);
+          unset($query);
+        }
+      }
+      
+      $schema = array_values($schema);
+      $schema = implode("\n", $schema);
+      $schema = explode(";\n", $schema);
+      
+      foreach ( $schema as $i => $sql )
+      {
+        $query =& $schema[$i];
+        if ( substr($query, ( strlen($query) - 1 ), 1 ) != ';' )
+        {
+          $query .= ';';
+        }
+      }
+      
+      // echo '<pre>' . htmlspecialchars(print_r($schema, true)) . '</pre>';
+      // break;
+      
+      echo 'done!<br />Executing schema.sql...';
+      
+      // OK, do the loop, baby!!!
+      foreach($schema as $q)
+      {
+        $r = mysql_query($q, $conn);
+        if(!$r) err('Error during mainstream installation: '.mysql_error());
+      }
+      
+      echo 'done!<br />Writing configuration files...';
+      if($_POST['urlscheme']=='tiny')
+      {
+        $ht = fopen(ENANO_ROOT.'/.htaccess', 'a+');
+        if(!$ht) err('Error opening file .htaccess for writing');
+        fwrite($ht, '
+RewriteEngine on
+RewriteCond %{REQUEST_FILENAME} !-d
+RewriteCond %{REQUEST_FILENAME} !-f
+RewriteRule ^(.+) '.scriptPath.'/index.php?title=$1 [L,QSA]
+RewriteRule \.(php|html|gif|jpg|png|css|js)$ - [L]
+');
+        fclose($ht);
+      }
+  
+      $config_file = '<?php
+/* Enano auto-generated configuration file - editing not recommended! */
+$dbhost   = \''.addslashes($_POST['db_host']).'\';
+$dbname   = \''.addslashes($_POST['db_name']).'\';
+$dbuser   = \''.addslashes($_POST['db_user']).'\';
+$dbpasswd = \''.addslashes($_POST['db_pass']).'\';
+if(!defined(\'ENANO_CONSTANTS\')) {
+define(\'ENANO_CONSTANTS\', \'\');
+define(\'table_prefix\', \''.$_POST['table_prefix'].'\');
+define(\'scriptPath\', \''.scriptPath.'\');
+define(\'contentPath\', \''.$cp.'\');
+define(\'ENANO_INSTALLED\', \'true\');
+}
+$crypto_key = \''.$privkey.'\';
+?>';
+
+      $cf_handle = fopen(ENANO_ROOT.'/config.php', 'w');
+      if(!$cf_handle) err('Couldn\'t open file config.php for writing');
+      fwrite($cf_handle, $config_file);
+      fclose($cf_handle);
+      
+      echo 'done!<br />Starting the Enano API...';
+      
+      $template_bak = $template;
+      
+      // Get Enano loaded
+      $_GET['title'] = 'Main_Page';
+      require('includes/common.php');
+      
+      // We need to be logged in (with admin rights) before logs can be flushed
+      $session->login_without_crypto($_POST['admin_user'], $dec, false);
+      
+      // Now that login cookies are set, initialize the session manager and ACLs
+      $session->start();
+      $paths->init();
+      
+      unset($template);
+      $template =& $template_bak;
+      
+      echo 'done!<br />Initializing logs...';
+      
+      $q = $db->sql_query('INSERT INTO ' . $_POST['table_prefix'] . 'logs(log_type,action,time_id,date_string,author,page_text,edit_summary) VALUES(\'security\', \'install_enano\', ' . time() . ', \'' . date('d M Y h:i a') . '\', \'' . mysql_real_escape_string($_POST['admin_user']) . '\', \'' . mysql_real_escape_string(ENANO_VERSION) . '\', \'' . mysql_real_escape_string($_SERVER['REMOTE_ADDR']) . '\');', $conn);
+      if ( !$q )
+        err('Error setting up logs: '.$db->get_error());
+      
+      if ( !$session->get_permissions('clear_logs') )
+      {
+        echo '<br />Error: session manager won\'t permit flushing logs, these is a bug.';
+        break;
+      }
+      
+      // unset($session);
+      // $session = new sessionManager();
+      // $session->start();
+      
+      PageUtils::flushlogs('Main_Page', 'Article');
+      
+      echo 'done!<h3>Installation of Enano is complete.</h3><p>Review any warnings above, and then <a href="install.php?mode=finish">click here to finish the installation</a>.';
+      
+      // echo '<script type="text/javascript">window.location="'.scriptPath.'/install.php?mode=finish";</script>';
+      
+    break;
+  case "finish":
+    echo '<h3>Congratulations!</h3>
+           <p>You have finished installing Enano on this server.</p>
+          <h3>Now what?</h3>
+           <p>Click the link below to see the main page for your website. Where to go from here:</p>
+           <ul>
+             <li>The first thing you should do is log into your site using the Log in link on the sidebar.</li>
+             <li>Go into the Administration panel, expand General, and click General Configuration. There you will be able to configure some basic information about your site.</li>
+             <li>Visit the <a href="http://enanocms.org/Category:Plugins" onclick="window.open(this.href); return false;">Enano Plugin Gallery</a> to download and use plugins on your site.</li>
+             <li>Periodically create a backup of your database and filesystem, in case something goes wrong. This should be done at least once a week &ndash; more for wiki-based sites.</li>
+             <li>Hire some moderators, to help you keep rowdy users tame.</li>
+             <li>Tell the <a href="http://enanocms.org/Contact_us">Enano team</a> what you think.</li>
+             <li><b>Spread the word about Enano by adding a link to the Enano homepage on your sidebar!</b> You can enable this option in the General Configuration section of the administration panel.</li>
+           </ul>
+           <p><a href="index.php">Go to your website...</a></p>';
+    break;
+}
+$template->footer();
+ 
+?>
--- a/plugins/SpecialAdmin.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/plugins/SpecialAdmin.php	Fri Oct 26 19:28:54 2007 -0400
@@ -10,7 +10,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
@@ -203,6 +203,16 @@
       setConfig('pw_strength_minimum', $strength);
     }
     
+    // Account lockout policy
+    if ( preg_match('/^[0-9]+$/', $_POST['lockout_threshold']) )
+      setConfig('lockout_threshold', $_POST['lockout_threshold']);
+    
+    if ( preg_match('/^[0-9]+$/', $_POST['lockout_duration']) )
+      setConfig('lockout_duration', $_POST['lockout_duration']);
+    
+    if ( in_array($_POST['lockout_policy'], array('disable', 'captcha', 'lockout')) )
+      setConfig('lockout_policy', $_POST['lockout_policy']);
+    
     echo '<div class="info-box">Your changes to the site configuration have been saved.</div><br />';
     
   }
@@ -351,6 +361,43 @@
         </td>
       </tr>
       
+    <!-- Account lockout -->
+    
+      <tr><th colspan="2">Account lockouts</th></tr>
+      
+      <tr><td class="row3" colspan="2">Configure Enano to prevent or restrict logins for a specified period of time if a user enters an incorrect password a specific number of times.</td></tr>
+      
+      <tr>
+        <td class="row2">Lockout threshold:<br />
+          <small>How many times can a user enter wrong credentials before a lockout goes into effect?</small>
+        </td>
+        <td class="row2">
+          <input type="text" name="lockout_threshold" value="<?php echo ( $_ = getConfig('lockout_threshold') ) ? $_ : '5' ?>" />
+        </td>
+      </tr>
+      
+      <tr>
+        <td class="row1">Lockout duration:<br />
+          <small>This is how long an account lockout should last, in minutes.</small>
+        </td>
+        <td class="row1">
+          <input type="text" name="lockout_duration" value="<?php echo ( $_ = getConfig('lockout_duration') ) ? $_ : '15' ?>" />
+        </td>
+      </tr>
+      
+      <tr>
+        <td class="row2">Lockout policy:<br />
+          <small>What should be done when a lockout goes into effect?</small>
+        </td>
+        <td class="row2">
+          <label><input type="radio" name="lockout_policy" value="disable" <?php if ( getConfig('lockout_policy') == 'disable' ) echo 'checked="checked"'; ?> /> Don't do anything</label><br />
+          <label><input type="radio" name="lockout_policy" value="captcha" <?php if ( getConfig('lockout_policy') == 'captcha' ) echo 'checked="checked"'; ?> /> Require visual confirmation</label><br />
+          <label><input type="radio" name="lockout_policy" value="lockout" <?php if ( getConfig('lockout_policy') == 'lockout' || !getConfig('lockout_policy') ) echo 'checked="checked"'; ?> /> Prevent all login attempts</label>
+        </td>
+      </tr>
+      
+    <!-- Password strength -->
+      
       <tr><th colspan="2">Password strength</th></tr>
       
       <tr>
@@ -2685,7 +2732,7 @@
           } 
           else 
           {
-            echo '<div class="wait-box">Please wait while the administration panel loads. You need to be using a recent browser with AJAX support in order to use Runt.</div>';
+            echo '<script type="text/javascript">document.write(\'<div class="wait-box">Please wait while the administration panel loads. You need to be using a recent browser with AJAX support in order to use Runt.</div>\');</script><noscript><div class="error-box">It looks like Javascript isn\'t enabled in your browser. Please enable Javascript or use a different browser to continue.</div></noscript>';
           }
           ?>
           </div>
@@ -2979,7 +3026,7 @@
             echo '<div class="warning-box" style="margin: 10px 0;">$_GET[\'side\'] contained an SQL injection attempt</div>';
             break;
           }
-          $query = $db->sql_query('UPDATE '.table_prefix.'sidebar SET sidebar_id=' . $db->escape($_GET['side']) . ' WHERE item_id=' . intval($_GET['id']) . ';');
+          $query = $db->sql_query('UPDATE '.table_prefix.'sidebar SET sidebar_id=' . $db->escape($_GET['side']) . ' WHERE item_id=' . $db->escape($_GET['id']) . ';');
           if(!$query)
           {
             echo $db->get_error();
@@ -2989,7 +3036,7 @@
           echo '<div class="info-box" style="margin: 10px 0;">Item moved.</div>';
           break;
         case 'delete':
-          $query = $db->sql_query('DELETE FROM '.table_prefix.'sidebar WHERE item_id=' . intval($_GET['id']) . ';'); // Already checked for injection attempts ;-)
+          $query = $db->sql_query('DELETE FROM '.table_prefix.'sidebar WHERE item_id=' . $db->escape($_GET['id']) . ';'); // Already checked for injection attempts ;-)
           if(!$query)
           {
             echo $db->get_error();
@@ -3004,7 +3051,7 @@
           echo '<div class="error-box" style="margin: 10px 0;">Item deleted.</div>';
           break;
         case 'disenable';
-          $q = $db->sql_query('SELECT item_enabled FROM '.table_prefix.'sidebar WHERE item_id=' . intval($_GET['id']) . ';');
+          $q = $db->sql_query('SELECT item_enabled FROM '.table_prefix.'sidebar WHERE item_id=' . $db->escape($_GET['id']) . ';');
           if(!$q)
           {
             echo $db->get_error();
@@ -3014,22 +3061,7 @@
           $r = $db->fetchrow();
           $db->free_result();
           $e = ( $r['item_enabled'] == 1 ) ? '0' : '1';
-          $q = $db->sql_query('UPDATE '.table_prefix.'sidebar SET item_enabled='.$e.' WHERE item_id=' . intval($_GET['id']) . ';');
-          if(!$q)
-          {
-            echo $db->get_error();
-            $template->footer();
-            exit;
-          }
-          if(isset($_GET['ajax']))
-          {
-            ob_end_clean();
-            die('GOOD');
-          }
-          break;
-        case 'rename';
-          $newname = $db->escape($_POST['newname']);
-          $q = $db->sql_query('UPDATE '.table_prefix.'sidebar SET block_name=\''.$newname.'\' WHERE item_id=' . intval($_GET['id']) . ';');
+          $q = $db->sql_query('UPDATE '.table_prefix.'sidebar SET item_enabled='.$e.' WHERE item_id=' . $db->escape($_GET['id']) . ';');
           if(!$q)
           {
             echo $db->get_error();
@@ -3043,7 +3075,7 @@
           }
           break;
         case 'getsource':
-          $q = $db->sql_query('SELECT block_content,block_type FROM '.table_prefix.'sidebar WHERE item_id=' . intval($_GET['id']) . ';');
+          $q = $db->sql_query('SELECT block_content,block_type FROM '.table_prefix.'sidebar WHERE item_id=' . $db->escape($_GET['id']) . ';');
           if(!$q)
           {
             echo $db->get_error();
@@ -3059,7 +3091,7 @@
         case 'save':
           if ( defined('ENANO_DEMO_MODE') )
           {
-            $q = $db->sql_query('SELECT block_type FROM '.table_prefix.'sidebar WHERE item_id=' . intval($_GET['id']) . ';');
+            $q = $db->sql_query('SELECT block_type FROM '.table_prefix.'sidebar WHERE item_id=' . $db->escape($_GET['id']) . ';');
             if(!$q)
             {
               echo 'var status=unescape(\''.hexencode($db->get_error()).'\');';
@@ -3075,13 +3107,13 @@
               $_POST['content'] = sanitize_html($_POST['content'], true);
             }
           }
-          $q = $db->sql_query('UPDATE '.table_prefix.'sidebar SET block_content=\''.$db->escape(rawurldecode($_POST['content'])).'\' WHERE item_id=' . intval($_GET['id']) . ';');
+          $q = $db->sql_query('UPDATE '.table_prefix.'sidebar SET block_content=\''.$db->escape(rawurldecode($_POST['content'])).'\' WHERE item_id=' . $db->escape($_GET['id']) . ';');
           if(!$q)
           {
             echo 'var status=unescape(\''.hexencode($db->get_error()).'\');';
             exit;
           }
-          $q = $db->sql_query('SELECT block_type,block_content FROM '.table_prefix.'sidebar WHERE item_id=' . intval($_GET['id']) . ';');
+          $q = $db->sql_query('SELECT block_type,block_content FROM '.table_prefix.'sidebar WHERE item_id=' . $db->escape($_GET['id']) . ';');
           if(!$q)
           {
             echo 'var status=unescape(\''.hexencode($db->get_error()).'\');';
@@ -3173,8 +3205,6 @@
           $parser = $template->makeParserText($vars['sidebar_section']);
           $c = $template->tplWikiFormat($row['block_content'], false, 'sidebar-editor.tpl');
           $c = preg_replace('#<a (.*?)>(.*?)</a>#is', '<a href="#" onclick="return false;">\\2</a>', $c);
-          // fix for the "Administration" link that somehow didn't get rendered properly
-          $c = preg_replace("/(^|\n)([ ]*)<a([ ]+.*)?>(.+)<\/a>(<br(.*)\/>)([\r\n]+|$)/isU", '\\1\\2<li><a\\3>\\4</a></li>\\7', $c);
           break;
         case BLOCK_HTML:
           $parser = $template->makeParserText($vars['sidebar_section_raw']);
--- a/plugins/SpecialUserFuncs.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/plugins/SpecialUserFuncs.php	Fri Oct 26 19:28:54 2007 -0400
@@ -4,13 +4,13 @@
 Plugin URI: http://enanocms.org/
 Description: Provides the pages Special:Login, Special:Logout, Special:Register, and Special:Preferences.
 Author: Dan Fuhry
-Version: 1.0.2
+Version: 1.0.1
 Author URI: http://enanocms.org/
 */
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2
+ * Version 1.0 release candidate 2
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
@@ -104,14 +104,60 @@
   $pubkey = $session->rijndael_genkey();
   $challenge = $session->dss_rand();
   
+  $locked_out = false;
+  // are we locked out?
+  $threshold = ( $_ = getConfig('lockout_threshold') ) ? intval($_) : 5;
+  $duration  = ( $_ = getConfig('lockout_duration') ) ? intval($_) : 15;
+  // convert to minutes
+  $duration  = $duration * 60;
+  $policy = ( $x = getConfig('lockout_policy') && in_array(getConfig('lockout_policy'), array('lockout', 'disable', 'captcha')) ) ? getConfig('lockout_policy') : 'lockout';
+  if ( $policy != 'disable' )
+  {
+    $ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
+    $timestamp_cutoff = time() - $duration;
+    $q = $session->sql('SELECT timestamp FROM '.table_prefix.'lockout WHERE timestamp > ' . $timestamp_cutoff . ' AND ipaddr = \'' . $ipaddr . '\' ORDER BY timestamp DESC;');
+    $fails = $db->numrows();
+    if ( $fails >= $threshold )
+    {
+      $row = $db->fetchrow();
+      $locked_out = true;
+      $lockdata = array(
+          'locked_out' => true,
+          'lockout_threshold' => $threshold,
+          'lockout_duration' => ( $duration / 60 ),
+          'lockout_fails' => $fails,
+          'lockout_policy' => $policy,
+          'lockout_last_time' => $row['timestamp'],
+          'time_rem' => ( $duration / 60 ) - round( ( time() - $row['timestamp'] ) / 60 ),
+          'captcha' => ''
+        );
+      if ( $policy == 'captcha' )
+      {
+        $lockdata['captcha'] = $session->make_captcha();
+      }
+    }
+    $db->free_result();
+  }
+  
   if ( isset($_GET['act']) && $_GET['act'] == 'getkey' )
   {
     $username = ( $session->user_logged_in ) ? $session->username : false;
     $response = Array(
       'username' => $username,
       'key' => $pubkey,
-      'challenge' => $challenge
+      'challenge' => $challenge,
+      'locked_out' => false
       );
+    
+    if ( $locked_out )
+    {
+      foreach ( $lockdata as $x => $y )
+      {
+        $response[$x] = $y;
+      }
+      unset($x, $y);
+    }
+    
     $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
     $response = $json->encode($response);
     echo $response;
@@ -138,7 +184,48 @@
   $header = ( $level > USER_LEVEL_MEMBER ) ? 'Please re-enter your login details' : 'Please enter your username and password to log in.';
   if ( isset($_POST['login']) )
   {
-    echo '<p>'.$__login_status.'</p>';
+    $errstring = $__login_status['error'];
+    switch($__login_status['error'])
+    {
+      case 'key_not_found':
+        $errstring = 'Enano couldn\'t look up the encryption key used to encrypt your password. This most often happens if a cache rotation occurred during your login attempt, or if you refreshed the login page.';
+        break;
+      case 'key_wrong_length':
+        $errstring = 'The encryption key was the wrong length.';
+        break;
+      case 'too_big_for_britches':
+        $errstring = 'You are trying to authenticate at a level that your user account does not permit.';
+        break;
+      case 'invalid_credentials':
+        $errstring = 'You have entered an invalid username or password. Please enter your login details again.';
+        if ( $__login_status['lockout_policy'] == 'lockout' )
+        {
+          $errstring .= ' You have used up '.$__login_status['lockout_fails'].' out of '.$__login_status['lockout_threshold'].' login attempts. After you have used up all '.$data['lockout_threshold'].' login attempts, you will be locked out from logging in for '.$__login_status['lockout_duration'].' minutes.';
+        }
+        else if ( $__login_status['lockout_policy'] == 'captcha' )
+        {
+          $errstring .= ' You have used up '.$__login_status['lockout_fails'].' out of '.$__login_status['lockout_threshold'].' login attempts. After you have used up all '.$data['lockout_threshold'].' login attempts, you will have to enter a visual confirmation code before logging in, effective for '.$__login_status['lockout_duration'].' minutes.';
+        }
+        break;
+      case 'backend_fail':
+        $errstring = 'You entered the right credentials and everything was validated, but for some reason Enano couldn\'t register your session. This is an internal problem with the site and you are encouraged to contact site administration.';
+        break;
+      case 'locked_out':
+        $attempts = intval($__login_status['lockout_fails']);
+        if ( $attempts > $__login_status['lockout_threshold'])
+          $attempts = $__login_status['lockout_threshold'];
+        
+        $server_time = time();
+        $time_rem = $__login_status['lockout_duration'] - round( ( $server_time - $__login_status['lockout_last_time'] ) / 60 );
+        
+        $s = ( $time_rem == 1 ) ? '' : 's';
+        $errstring = "You have used up all {$__login_status['lockout_threshold']} allowed login attempts. Please wait {$time_rem} minute$s before attempting to log in again";
+        if ( $__login_status['lockout_policy'] == 'captcha' )
+        $errstring .= ', or enter the visual confirmation code shown above in the appropriate box';
+        $errstring .= '.';
+        break;
+    }
+    echo '<div class="error-box-mini">'.$errstring.'</div>';
   }
   if ( $p = $paths->getAllParams() )
   {
@@ -189,7 +276,7 @@
               ?> />
           </td>
           <?php if ( $level <= USER_LEVEL_MEMBER ) { ?>
-          <td rowspan="2" class="row3">
+          <td rowspan="<?php echo ( ( $locked_out && $lockdata['lockout_policy'] == 'captcha' ) ) ? '4' : '2'; ?>" class="row3">
             <small>Forgot your password? <a href="<?php echo makeUrlNS('Special', 'PasswordReset'); ?>">No problem.</a><br />
             Maybe you need to <a href="<?php echo makeUrlNS('Special', 'Register'); ?>">create an account</a>.</small>
           </td>
@@ -198,6 +285,21 @@
         <tr>
           <td class="row2">Password:<br /></td><td class="row1"><input name="pass" size="25" type="password" tabindex="<?php echo ( $level <= USER_LEVEL_MEMBER ) ? '2' : '1'; ?>" /></td>
          </tr>
+         <?php
+         if ( $locked_out && $lockdata['lockout_policy'] == 'captcha' )
+         {
+           ?>
+           <tr>
+             <td class="row2" rowspan="2">Code in image:<br /></td><td class="row1"><input type="hidden" name="captcha_hash" value="<?php echo $lockdata['captcha']; ?>" /><input name="captcha_code" size="25" type="text" tabindex="<?php echo ( $level <= USER_LEVEL_MEMBER ) ? '3' : '4'; ?>" /></td>
+           </tr>
+           <tr>
+             <td class="row3">
+               <img src="<?php echo makeUrlNS('Special', 'Captcha/' . $lockdata['captcha']) ?>" onclick="this.src=this.src+'/a';" style="cursor: pointer;" />
+             </td>
+           </tr>
+           <?php
+         }
+         ?>
          <?php if ( $level <= USER_LEVEL_MEMBER ) { ?>
          <tr>
            <td class="row3" colspan="3">
@@ -242,12 +344,12 @@
     $plugins->attachHook('login_password_reset', 'SpecialLogin_SendResponse_PasswordReset($row[\'user_id\'], $row[\'temp_password\']);');
     $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
     $data = $json->decode($_POST['params']);
+    $captcha_hash = ( isset($data['captcha_hash']) ) ? $data['captcha_hash'] : false;
+    $captcha_code = ( isset($data['captcha_code']) ) ? $data['captcha_code'] : false;
     $level = ( isset($data['level']) ) ? intval($data['level']) : USER_LEVEL_MEMBER;
-    $result = $session->login_with_crypto($data['username'], $data['crypt_data'], $data['crypt_key'], $data['challenge'], $level);
+    $result = $session->login_with_crypto($data['username'], $data['crypt_data'], $data['crypt_key'], $data['challenge'], $level, $captcha_hash, $captcha_code);
     $session->start();
-    //echo "$result\n$session->sid_super";
-    //exit;
-    if ( $result == 'success' )
+    if ( $result['success'] )
     {
       $response = Array(
           'result' => 'success',
@@ -256,9 +358,16 @@
     }
     else
     {
+      $captcha = '';
+      if ( $result['error'] == 'locked_out' && $result['lockout_policy'] == 'captcha' )
+      {
+        $session->kill_captcha();
+        $captcha = $session->make_captcha();
+      }
       $response = Array(
           'result' => 'error',
-          'error' => $result
+          'data' => $result,
+          'captcha' => $captcha
         );
     }
     $response = $json->encode($response);
@@ -267,17 +376,19 @@
     exit;
   }
   if(isset($_POST['login'])) {
+    $captcha_hash = ( isset($_POST['captcha_hash']) ) ? $_POST['captcha_hash'] : false;
+    $captcha_code = ( isset($_POST['captcha_code']) ) ? $_POST['captcha_code'] : false;
     if($_POST['use_crypt'] == 'yes')
     {
-      $result = $session->login_with_crypto($_POST['username'], $_POST['crypt_data'], $_POST['crypt_key'], $_POST['challenge_data'], intval($_POST['auth_level']));
+      $result = $session->login_with_crypto($_POST['username'], $_POST['crypt_data'], $_POST['crypt_key'], $_POST['challenge_data'], intval($_POST['auth_level']), $captcha_hash, $captcha_code);
     }
     else
     {
-      $result = $session->login_without_crypto($_POST['username'], $_POST['pass'], false, intval($_POST['auth_level']));
+      $result = $session->login_without_crypto($_POST['username'], $_POST['pass'], false, intval($_POST['auth_level']), $captcha_hash, $captcha_code);
     }
     $session->start();
     $paths->init();
-    if($result == 'success')
+    if($result['success'])
     {
       $template->load_theme($session->theme, $session->style);
       if(isset($_POST['return_to']))
--- a/plugins/admin/PageGroups.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/plugins/admin/PageGroups.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
@@ -602,23 +602,6 @@
                   echo '<div class="info-box">The affecting tag was updated.</div>';
               }
             }
-            else if ( $_POST['pg_type'] == PAGE_GRP_REGEX )
-            {
-              $target = $_POST['pg_target'];
-              if ( empty($target) )
-              {
-                echo '<div class="error-box">Please enter an expression to match against..</div>';
-              }
-              else
-              {
-                $target = $db->escape($target);
-                $q = $db->sql_query('UPDATE '.table_prefix.'page_groups SET pg_target=\'' . $target . '\' WHERE pg_id=' . $edit_id . ';');
-                if ( !$q )
-                  $db->_die();
-                else
-                  echo '<div class="info-box">The expression to match against was updated.</div>';
-              }
-            }
             else if ( $_POST['pg_type'] == PAGE_GRP_CATLINK )
             {
               $target = $_POST['pg_target'];
@@ -877,22 +860,6 @@
                   </td>
                 </tr>';
           break;
-        case PAGE_GRP_REGEX:
-          echo '<tr>
-                  <td class="row2">
-                    Regular expression to use:<br />
-                    <small>Be sure to include the starting and ending delimiters and any flags you might need.<br />
-                           These pages might help: <a href="http://us.php.net/manual/en/reference.pcre.pattern.modifiers.php">Pattern modifiers</a> &bull;
-                           <a href="http://us.php.net/manual/en/reference.pcre.pattern.syntax.php">Pattern syntax</a><br />
-                           Examples: <tt>/^(Special|Admin):/i</tt> &bull; <tt>/^Image:([0-9]+)$/</tt><br />
-                           Developers, remember that this will be matched against the full page identifier string. This means that <tt>/^About_Enano$/</tt>
-                           will NOT match the page Special:About_Enano.</small>
-                  </td>
-                  <td class="row1">
-                    <input type="text" name="pg_target" value="' . htmlspecialchars($row['pg_target']) . '" size="30" />
-                  </td>
-                </tr>';
-          break;
         case PAGE_GRP_CATLINK:
           
           // Build category list
--- a/plugins/admin/SecurityLog.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/plugins/admin/SecurityLog.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
--- a/plugins/admin/UserManager.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/plugins/admin/UserManager.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * Copyright (C) 2006-2007 Dan Fuhry
  *
  * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
--- a/schema.sql	Tue Oct 23 12:30:08 2007 -0400
+++ b/schema.sql	Fri Oct 26 19:28:54 2007 -0400
@@ -254,6 +254,16 @@
   PRIMARY KEY ( tag_id )
 ) CHARACTER SET `utf8`;
 
+-- Added in 1.1.1
+
+CREATE TABLE {{TABLE_PREFIX}}lockout(
+  id int(12) NOT NULL auto_increment,
+  ipaddr varchar(40) NOT NULL,
+  action ENUM('credential', 'level') NOT NULL DEFAULT 'credential',
+  timestamp int(12) NOT NULL DEFAULT 0,
+  PRIMARY KEY ( id )
+) CHARACTER SET `utf8`;
+
 INSERT INTO {{TABLE_PREFIX}}config(config_name, config_value) VALUES
   ('site_name', '{{SITE_NAME}}'),
   ('main_page', 'Main_Page'),
--- a/upgrade.php	Tue Oct 23 12:30:08 2007 -0400
+++ b/upgrade.php	Fri Oct 26 19:28:54 2007 -0400
@@ -2,7 +2,7 @@
 
 /*
  * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
- * Version 1.0.2 (Coblynau)
+ * Version 1.1.1
  * upgrade.php - upgrade script
  * Copyright (C) 2006-2007 Dan Fuhry
  *
@@ -61,7 +61,7 @@
 // Everything related to versions goes here!
 
 // Valid versions to upgrade from
-$valid_versions = Array('1.0b1', '1.0b2', '1.0b3', '1.0b4', '1.0RC1', '1.0RC2', '1.0RC3', '1.0', '1.0.1', '1.0.1.1', '1.0.2b1');
+$valid_versions = Array('1.0b1', '1.0b2', '1.0b3', '1.0b4', '1.0RC1', '1.0RC2', '1.0RC3', '1.0', '1.0.1', '1.0.1.1', '1.0.2b1', '1.0.2', 'Stable1.0ToUnstable1.1');
 
 // Basically a list of dependencies, which should be resolved automatically
 // If, for example, upgrading from 1.0b1 to 1.0RC1 requires one extra query that would not
@@ -76,9 +76,11 @@
     '1.0RC3' => Array('1.0'),
     '1.0' => Array('1.0.1'),
     '1.0.1' => Array('1.0.1.1'),
-    '1.0.1.1' => Array('1.0.2b1')
+    '1.0.1.1' => Array('1.0.2b1'),
+    '1.0.2b1' => Array('Stable1.0ToUnstable1.1'),
+    'Stable1.0ToUnstable1.1' => Array('1.1.1')
   );
-$this_version   = '1.0.2';
+$this_version   = '1.1.1';
 $func_list = Array(
     '1.0' => Array('u_1_0_1_update_del_votes'),
     '1.0b4' => Array('u_1_0_RC1_update_user_ids', 'u_1_0_RC1_add_admins_to_group', 'u_1_0_RC1_alter_files_table', 'u_1_0_RC1_destroy_session_cookie', 'u_1_0_RC1_set_contact_email', 'u_1_0_RC1_update_page_text'), // ,
@@ -445,7 +447,7 @@
     {
       if(isset($_POST['login']))
       {
-        $session->login_without_crypto($_POST['username'], $_POST['password'], false, $ul_admin);
+        $result = $session->login_without_crypto($_POST['username'], $_POST['password'], false, $ul_admin);
         if($session->sid_super)
         {
           header('Location: upgrade.php?mode=welcome&auth='.$session->sid_super);
@@ -462,7 +464,7 @@
         <?php
         if(isset($_POST['login']))
         {
-          echo '<tr><td colspan="2"><p style="color: red;">Login failed. Bad password?</p></td></tr>';
+          echo '<tr><td colspan="2"><p style="color: red;">Login failed: '. $result['error'] . '</p></td></tr>';
         }
         ?>
         <tr>
--- a/upgrade.sql	Tue Oct 23 12:30:08 2007 -0400
+++ b/upgrade.sql	Fri Oct 26 19:28:54 2007 -0400
@@ -3,7 +3,15 @@
 -- ALL NON-SQL LINES, even otherwise blank lines, must start with "--" or they will get sent to MySQL!
 -- Common tasks (version numbers)
 DELETE FROM {{TABLE_PREFIX}}config WHERE config_name='enano_version' OR config_name='enano_beta_version' OR config_name='enano_alpha_version' OR config_name='enano_rc_version';
-INSERT INTO {{TABLE_PREFIX}}config (config_name, config_value) VALUES( 'enano_version', '1.0.2' );
+INSERT INTO {{TABLE_PREFIX}}config (config_name, config_value) VALUES( 'enano_version', '1.1.1' );
+---BEGIN Stable1.0ToUnstable1.1---
+-- UPDATE {{TABLE_PREFIX}}groups SET group_id=9998 WHERE group_id=4;
+-- UPDATE {{TABLE_PREFIX}}group_members SET group_id=9998 WHERE group_id=4;
+-- INSERT INTO {{TABLE_PREFIX}}groups(group_id,group_name,group_type,system_group) VALUES(4, 'Regular members', 3, 1);
+CREATE TABLE {{TABLE_PREFIX}}lockout( id int(12) NOT NULL auto_increment, ipaddr varchar(40) NOT NULL, action ENUM('credential', 'level') NOT NULL DEFAULT 'credential', timestamp int(12) NOT NULL DEFAULT 0, PRIMARY KEY ( id ) ) CHARACTER SET `utf8`;
+---END Stable1.0ToUnstable1.1---
+---BEGIN 1.0.2---
+---END 1.0.2---
 ---BEGIN 1.0.2b1---
 -- This is really optional, but could reduce confusion if regex page groups get truncated for no apparent reason.
 ALTER TABLE {{TABLE_PREFIX}}page_groups MODIFY COLUMN pg_target text DEFAULT NULL;