changeset 8:4c5f651aa107

Migrate certain settings to SQL database, cleanups, etc.
author Matti Hamalainen <ccr@tnsp.org>
date Thu, 06 Dec 2012 13:30:46 +0200
parents d76020022881
children fa9b66f596bb
files admin.inc.php ajax.php compos.inc.php createdb.php index.php keygen.php msite.inc.php
diffstat 7 files changed, 290 insertions(+), 77 deletions(-) [+]
line wrap: on
line diff
--- a/admin.inc.php	Wed Dec 05 09:35:30 2012 +0200
+++ b/admin.inc.php	Thu Dec 06 13:30:46 2012 +0200
@@ -176,6 +176,12 @@
 }
 
 
+function refreshSettings()
+{
+  refreshItems("tabSettings", "settings", "General settings");
+}
+
+
 function refreshNews()
 {
   refreshItems("nnews", "news", "News list");
@@ -380,10 +386,7 @@
 
 <!-- ========================== -->
 
-<div id="tabGeneral">
-  <form method="post" action="" onsubmit="return updateGeneral()">
-  <hr />
-  </form>
+<div id="tabSettings">
 </div>
 
 <!-- ========================== -->
@@ -443,7 +446,7 @@
 <!-- ========================== -->
 
 <script type="text/javascript">
-  registerTab("tabGeneral", "Settings");
+  registerTab("tabSettings", "Settings");
   registerTab("tabNews", "News");
   registerTab("tabAttendees", "Attendees");
   registerTab("tabDump", "Dump");
--- a/ajax.php	Wed Dec 05 09:35:30 2012 +0200
+++ b/ajax.php	Thu Dec 06 13:30:46 2012 +0200
@@ -9,14 +9,15 @@
   exit;
 }
 
-header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
-header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
+stSetupCacheControl();
 
-
-// Open PDO database connection
+// Initiate SQL database connection
 if (!stConnectSQLDB())
   die("Could not connect to SQL database.");
 
+// Fetch non-"hardcoded" settings from SQL database
+stReloadSettings();
+
 
 function setStatus($val, $msg)
 {
@@ -93,6 +94,10 @@
       case "compos":
         $sql = "SELECT * FROM compos ORDER BY id DESC";
         break;
+
+      case "settings":
+        $sql = "SELECT * FROM settings";
+        break;
       
       case "entries":
         stGetCompoList(TRUE);
@@ -222,6 +227,10 @@
         }
         echo "</table>\n";
       }
+      else
+      if ($type == "settings")
+      {
+      }
     }
     break;
 
--- a/compos.inc.php	Wed Dec 05 09:35:30 2012 +0200
+++ b/compos.inc.php	Thu Dec 06 13:30:46 2012 +0200
@@ -17,7 +17,55 @@
 
 <h1>Compos</h1>
 <?
-if (($res = stExecSQL("SELECT * FROM compos WHERE enabled<>0 ORDER BY id ASC")) !== FALSE)
+function stConvSwitchMode(&$str, &$mode, $newMode)
+{
+  if ($newMode != $mode)
+  {
+    if ($mode != "")
+      $str .= "\n</".$mode.">\n";
+
+    $mode = $newMode;
+
+    if ($mode != "")
+      $str .= "<".$mode.">\n";
+  }
+}
+
+
+function stConvertCompoDesc($desc)
+{
+  global $stDescConversion;
+  $str = "";
+  $mode = "";
+
+  foreach (explode("\n", $desc) as $line)
+  {
+    if (preg_match("/^\s*\s*\*(.+)$/", $line, $m))
+    {
+      stConvSwitchMode($str, $mode, "ol");
+      $str .= "<li>".$m[1]."</li>\n";
+    }
+    else
+    if (preg_match("/^\s*-\s*(.+)$/", $line, $m))
+    {
+      stConvSwitchMode($str, $mode, "ul");
+      $str .= "<li>".$m[1]."</li>\n";
+    }
+    else
+    {
+      stConvSwitchMode($str, $mode, "p");
+      $str .= $line;
+    }
+  }
+
+  stConvSwitchMode($str, $mode, "");
+
+  return $str;
+}
+
+$sql = "SELECT * FROM compos WHERE enabled<>0 ORDER BY id ASC";
+
+if (($res = stExecSQL($sql)) !== FALSE)
 {
   foreach ($res as $item)
   {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/createdb.php	Thu Dec 06 13:30:46 2012 +0200
@@ -0,0 +1,132 @@
+#!/usr/bin/php
+<?
+require "mconfig.inc.php";
+require "msite.inc.php";
+
+// We don't want to be run from anywhere else than commandline
+stCheckCLIOrDie();
+
+
+// The defaults we put in
+$siteDefaults = array(
+  "maxAttendees"     => array(VT_INT, 30),
+
+  "voteTimeout"      => array(VT_INT, 120*60),
+  "admTimeout"       => array(VT_INT, 15*60),
+
+  "allowRegister"    => array(VT_BOOL, false),
+  "allowVoting"      => array(VT_BOOL, false),
+  "showAttendees"    => array(VT_BOOL, false),
+  "showResults"      => array(VT_BOOL, false),
+  "showResAuthors"   => array(VT_BOOL, false),
+  "showVoteAuthors"  => array(VT_BOOL, false),
+
+  "eventDescription" => array(VT_TEXT, ""),
+  "compoDescription" => array(VT_TEXT, ""),
+  "infoBoxText"      => array(VT_TEXT, ""),
+  "newsDescription"  => array(VT_TEXT, ""),
+);
+
+$sqlTables = array(
+  "news" => "id INTEGER PRIMARY KEY AUTOINCREMENT, utime INT, title VARCHAR(128), text VARCHAR(4096), author VARCHAR(64), persist INT DEFAULT 0",
+  "attendees" => "id INTEGER PRIMARY KEY AUTOINCREMENT, regtime INT, name VARCHAR(64), groups VARCHAR(64), oneliner VARCHAR(64), email VARCHAR(80)",
+  "compos" => "id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(128), description VARCHAR(4096), enabled INT DEFAULT 0",
+  "entries" => "id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(64), author VARCHAR(64), compo_id INT DEFAULT NULL",
+  "voters" => "id INTEGER PRIMARY KEY AUTOINCREMENT, key VARCHAR(64), name VARCHAR(64), enabled INT DEFAULT 0",
+  "votes" => "id INTEGER PRIMARY KEY AUTOINCREMENT, entry_id INT DEFAULT NULL, voter_id INT DEFAULT NULL, value INT DEFAULT 0",
+  "settings" => "key VARCHAR(32) PRIMARY KEY, vtype INT, vstr VARCHAR(128), vtext TEXT, vint INT",
+);
+
+
+//
+// Check for commandline arguments
+//
+function stConnectDB($dbspec)
+{
+  global $db;
+  try {
+    $db = new PDO($dbspec);
+  }
+  catch (PDOException $e) {
+    error_log("Could not connect to SQL database '".$dbspec."': ".$e->getMessage().".");
+    return FALSE;
+  }
+  return TRUE;
+}
+
+
+function stCreateTables()
+{
+  global $sqlTables;
+  echo "Creating tables...\n";
+  foreach ($sqlTables as $name => $schema)
+  {
+    echo " - '".$name."'\n";
+    if (stExecSQL("CREATE TABLE ".$name." (".$schema.")") === FALSE)
+      return FALSE;
+  }
+  return TRUE;
+}
+
+
+function stAddSettings()
+{
+  global $siteDefaults;
+  echo "Adding settings to settings table.\n";
+  foreach ($siteDefaults as $key => $value)
+  {
+    switch ($value[0])
+    {
+      case VT_TEXT: $type = "%s"; $var = "vtext"; break;
+      case VT_STR:  $type = "%s"; $var = "vstr"; break;
+      case VT_BOOL: $type = "%B"; $var = "vint"; break;
+      case VT_INT:  $type = "%d"; $var = "vint"; break;
+    }
+
+    $sql = stPrepareSQL(
+      "INSERT INTO settings (key,vtype,".$var.") VALUES (%s,%d,".$type.")",
+      $key, $value[0], $value[1]);
+    
+    stExecSQL($sql);
+  }
+}
+
+
+if ($argc < 2)
+{
+  echo "Usage: ".$argv[0]." <mode> [args]\n".
+  "Where mode is one of following:\n".
+  "\n".
+  "  new [dbspec]      Create a new database with given PDO spec\n".
+  "                    or default to the one in mconfig.inc.php\n".
+  "\n".
+  "  reset [dbspec]    Reset settings (similar to 'new').\n".
+  "\n";
+  exit;
+}
+
+
+if (($spec = stCArg(2)) === FALSE)
+  $spec = $siteSettings["sqlDB"];
+
+
+if (!stConnectDB($spec))
+  die("Could not connect to SQL database '".$spec."'.\n");
+
+echo "Using database spec '".$spec."'.\n";
+
+switch (stCArg(1))
+{
+  case "new":
+    if (stCreateTables())
+      stAddSettings();
+    break;
+
+  case "reset":
+    echo "Deleting old settings.\n";
+    stExecSQL("DELETE FROM settings");
+    stAddSettings();
+    break;
+}
+
+?>
\ No newline at end of file
--- a/index.php	Wed Dec 05 09:35:30 2012 +0200
+++ b/index.php	Thu Dec 06 13:30:46 2012 +0200
@@ -3,6 +3,7 @@
 require "msite.inc.php";
 require "mcommon.inc.php";
 
+
 // Switch to https first, if needed
 if (!stCheckHTTPS())
 {
@@ -10,19 +11,25 @@
   exit;
 }
 
+// Check for cache-controlled pages
 if (isset($_SERVER["REQUEST_URI"]) &&
   array_key_exists($_SERVER["REQUEST_URI"], $securePages))
   stSetupCacheControl();
 
+// Start output
 printPageHeader($pageTitle,
   " <meta http-equiv=\"Pragma\" content=\"no-cache\" />");
 
+// Initiate SQL database connection
 if (!stConnectSQLDB())
 {
   printPageFooter();
   exit;
 }
 
+// Fetch non-"hardcoded" settings from SQL database
+stReloadSettings();
+
 ?>
 <div id="headerbox">
  <div id="header">
@@ -33,8 +40,10 @@
   <a href="news">News</a>
   <a href="compos">Compos</a>
   <a href="event">Event</a>
-  <a href="attendees">Attendees</a>
 <?
+if (stGetSetting("showAttendees", FALSE))
+echo "  <a href=\"attendees\">Attendees</a>\n";
+
 if (stGetSetting("allowVoting", FALSE))
 echo "  <a href=\"vote\">Vote</a>\n";
 
--- a/keygen.php	Wed Dec 05 09:35:30 2012 +0200
+++ b/keygen.php	Thu Dec 06 13:30:46 2012 +0200
@@ -3,26 +3,19 @@
 require "mconfig.inc.php";
 require "msite.inc.php";
 
+// We don't want to be run from anywhere else than commandline
+stCheckCLIOrDie();
+
+
+// Settings
 $keyChars = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ123456789";
 $maxItems = 4;
 $maxRows  = 25;
 
-function garg($index)
-{
-  global $argc, $argv;
-  if ($index < $argc)
-    return strtolower($argv[$index]);
-  else
-    return FALSE;
-}
 
-function gSQLError($sql)
-{
-  global $db;
-  echo "Error executing SQL query: ".implode("; ", $db->errorInfo())." in statement \"".$sql."\"\n";
-  exit;
-}
-
+//
+// Check for commandline arguments
+//
 if ($argc < 2)
 {
   echo "Usage: ".$argv[0]." <mode> [args]\n".
@@ -40,11 +33,11 @@
 if (!stConnectSQLDB())
   die("Could not connect to SQL database.\n");
 
-switch (substr(garg(1), 0, 2))
+switch (substr(stCArgLC(1), 0, 2))
 {
   case "ge":
     // Check arguments for sanity
-    if (($num = garg(2)) === FALSE)
+    if (($num = stCArgLC(2)) === FALSE)
     {
       echo "No number of keys specified.\n";
       exit;
@@ -78,14 +71,14 @@
             $key);
 
           if (($res = $db->query($sql)) === FALSE)
-            gSQLError($sql);
+            stCSQLError($sql);
 
           $i++;
         }
       }
       else
       {
-        gSQLError($sql);
+        stCSQLError($sql);
       }
     }
     echo "\nGenerated ".$i." new keys.\n";
@@ -93,7 +86,7 @@
   
   case "pr":
     // Print keys
-    $all = garg(2) == "all";
+    $all = stCArgLC(2) == "all";
     $sql = "SELECT * FROM voters ".($all ? "" : "WHERE enabled=0 ")."ORDER BY id ASC";
     if (($res = @$db->query($sql)) !== FALSE)
     {
@@ -127,12 +120,12 @@
     }
     else
     {
-      gSQLError($sql);
+      stCSQLError($sql);
     }
     break;
   
   default:
-    echo "Unknown operating mode '".garg(1)."'.\n";
+    echo "Unknown operating mode '".stCArg(1)."'.\n";
     break;
 }
 
--- a/msite.inc.php	Wed Dec 05 09:35:30 2012 +0200
+++ b/msite.inc.php	Thu Dec 06 13:30:46 2012 +0200
@@ -5,6 +5,13 @@
 $errorSet = FALSE;
 $errorMsg = "";
 
+
+define("VT_STR", 1);
+define("VT_INT", 2);
+define("VT_BOOL", 3);
+define("VT_TEXT", 4);
+
+
 function stError($msg)
 {
   global $errorSet, $errorMsg;
@@ -21,9 +28,8 @@
 
 function stSetupCacheControl()
 {
-  header("Cache-Control: private");
-  header("Cache-Control: must-revalidate");
-  header("Cache-Control: no-store");
+  header("Cache-Control: must-revalidate, no-store, private");
+  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
 }
 
 
@@ -125,16 +131,36 @@
 }
 
 
+function stReloadSettings()
+{
+  global $siteSettings;
+  $res = stExecSQL("SELECT * FROM settings");
+  if ($res !== FALSE)
+  {
+    foreach ($res as $row)
+    {
+      switch ($row["vtype"])
+      {
+        case VT_INT:  $val = intval($row["vint"]); break;
+        case VT_BOOL: $val = intval($row["vint"]) ? true : false; break;
+        case VT_STR:  $val = $row["vstr"]; break;
+        case VT_TEXT: $val = $row["vtext"]; break;
+      }
+      $siteSettings[$row["key"]] = $val;
+    }
+  }
+  else
+    die("Error fetching site settings.");
+}
+
+
 function stGetSetting($name)
 {
-  global $siteSettings, $siteDefaults;
+  global $siteSettings;
   if (isset($siteSettings[$name]))
     return $siteSettings[$name];
   else
-  if (isset($siteDefaults[$name]))
-    return $siteDefaults[$name];
-  else
-    die("No config value or default for '".$name."'.\n");
+    die("No config value for '".$name."'.\n");
 }
 
 
@@ -321,7 +347,7 @@
 {
   global $db;
   try {
-    $db = new PDO("sqlite:".stGetSetting("sqlDBfilename"));
+    $db = new PDO(stGetSetting("sqlDB"));
   }
   catch (PDOException $e) {
     error_log("Could not connect to SQL database: ".$e->getMessage().".");
@@ -477,50 +503,43 @@
 }
 
 
-function stConvSwitchMode(&$str, &$mode, $newMode)
+//
+// CLI utility helper functions
+//
+function stCArg($index)
 {
-  if ($newMode != $mode)
-  {
-    if ($mode != "")
-      $str .= "\n</".$mode.">\n";
+  global $argc, $argv;
+  if ($index < $argc)
+    return $argv[$index];
+  else
+    return FALSE;
+}
 
-    $mode = $newMode;
-
-    if ($mode != "")
-      $str .= "<".$mode.">\n";
-  }
+function stCArgLC($index)
+{
+  global $argc, $argv;
+  if ($index < $argc)
+    return strtolower($argv[$index]);
+  else
+    return FALSE;
 }
 
 
-function stConvertCompoDesc($desc)
+function stCSQLError($sql)
 {
-  global $stDescConversion;
-  $str = "";
-  $mode = "";
+  global $db;
+  die("Error executing SQL query: ".implode("; ", $db->errorInfo())." in statement \"".$sql."\"\n");
+  exit;
+}
 
-  foreach (explode("\n", $desc) as $line)
+
+function stCheckCLIOrDie()
+{
+  if (php_sapi_name() != "cli" || !empty($_SERVER["REMOTE_ADDR"]))
   {
-    if (preg_match("/^\s*\s*\*(.+)$/", $line, $m))
-    {
-      stConvSwitchMode($str, $mode, "ol");
-      $str .= "<li>".$m[1]."</li>\n";
-    }
-    else
-    if (preg_match("/^\s*-\s*(.+)$/", $line, $m))
-    {
-      stConvSwitchMode($str, $mode, "ul");
-      $str .= "<li>".$m[1]."</li>\n";
-    }
-    else
-    {
-      stConvSwitchMode($str, $mode, "p");
-      $str .= $line;
-    }
+    header("Status: 404 Not Found");
+    die();
   }
-
-  stConvSwitchMode($str, $mode, "");
-
-  return $str;
 }
 
 ?>
\ No newline at end of file