view msite.inc.php @ 840:3b9ccc10c9a0

Few 10L's
author Matti Hamalainen <ccr@tnsp.org>
date Tue, 25 Nov 2014 20:42:37 +0200
parents 43e4a73deaf3
children f007e63f82d6
line wrap: on
line source

<?
//
// FAPWeb - Simple Web-based Demoparty Management System
// Generic and miscellaneous site support code
// (C) Copyright 2012-2014 Tecnic Software productions (TNSP)
//
require_once "msitegen.inc.php";

// Define modes of party information display system
define("SMODE_DISABLED", 0);
define("SMODE_ROTATE", 1);
define("SMODE_COMPO", 2);


// Define sizes of database fields, see createdb.php
// and also the places where input is validated.
define("SET_LEN_USERNAME", 32);
define("SET_LEN_GROUPS", 64);
define("SET_LEN_ONELINER", 64);
define("SET_LEN_EMAIL", 80);
define("SET_LEN_REGHOST", 128);

define("SET_LEN_NEWS_TITLE", 128);
define("SET_LEN_NEWS_TEXT", 4096);
define("SET_LEN_NEWS_AUTHOR", 64);

define("SET_LEN_COMPO_NAME", 128);
define("SET_LEN_COMPO_DESC", 4096);
define("SET_LEN_COMPO_PATH", 128);

define("SET_LEN_ENTRY_NAME", 64);
define("SET_LEN_ENTRY_AUTHOR", 64);
define("SET_LEN_ENTRY_FILENAME", 128);
define("SET_LEN_ENTRY_INFO", 40*3);
define("SET_LEN_ENTRY_NOTES", 1024);
define("SET_LEN_ENTRY_PREVIEW_FILE", 128);

define("SET_LEN_DISP_SLIDE_TITLE", 64);
define("SET_LEN_DISP_SLIDE_TEXT", 4096);
define("SET_LEN_ROT_LIST_NAME", 128);

define("SET_LEN_VOTEKEY", 64);


//
// Entry preview type (value)
//
define("EPREV_NONE",  0);           // No preview
define("EPREV_IMAGE", 1);           // Preview is image (PNG, JPEG)
define("EPREV_AUDIO", 2);           // Preview is audio (Vorbis, MP3)

$previewTypeList = array(
  EPREV_NONE         => array("No previews" , "Default"),
  EPREV_IMAGE        => array("Image file"  , "Image"),
  EPREV_AUDIO        => array("Audio file"  , "Audio"),
);

//
// File format classes
//
define("EFILE_UNKNOWN", 0);
define("EFILE_IMAGE", 1);
define("EFILE_AUDIO", 2);
define("EFILE_VIDEO", 3);
define("EFILE_TEXT", 4);
define("EFILE_BINARY", 5);
define("EFILE_ARCHIVE", 6);

//
// Entry flags (bitfield)
//
define("EFLAG_DISQUALIFIED", 1);    // Entry is disqualified
define("EFLAG_PROBLEMS", 2);        // Has some problems

$entryFlagsList = array(
  EFLAG_DISQUALIFIED => array("Disqualified", "img/disqualified.png"),
  EFLAG_PROBLEMS     => array("Has problems", "img/problems.png"),
);


//
// Results output flags
//
define("RFLAG_NORMAL", 0);
define("RFLAG_DISQUALIFIED", 1);
define("RFLAG_HIDDEN_COMPOS", 2);

//
// Competition types
//
define("COMPO_NORMAL", 0);          // Normal voting compo, points determine placement
define("COMPO_POINTS", 1);          // Assigned points, points determines placement (no voting)
define("COMPO_ASSIGN", 2);          // Assigned places (no voting)


$compoModeData = array(
  COMPO_NORMAL => array("Normal",
    "Normal voting compo.",
  ),
  COMPO_POINTS => array("Points",
    "Assigned points (no voting).",
    "Points",
  ),
  COMPO_ASSIGN => array("Assigned",
    "Assigned places (no points, no voting).",
    "Place",
  ),
);


//
// Different voting modes
//
define("VOTE_FREELY", 0);
define("VOTE_ACTIVATE", 1);
define("VOTE_ASSIGN", 2);

$voteModeData = array(
  VOTE_FREELY => array("Freeform voting",
    "Vote keys are not tied to attendees, and do not need to be activated. ".
    "Take one printed key slip, give it to attendee."
    ),
  VOTE_ACTIVATE => array("Key activation",
    "Vote keys are not tied to attendees, but require manual activation. ".
    "Take one printed key slip, find it by the index number in the list below, set to activated. ".
    "Give key slip to attendee."
    ),
  VOTE_ASSIGN => array("Assigned keys",
    "Votekeys are tied to attendees, activated by assigning the key to attendee. ".
    "Take one printed key slip, find attendee in the list below, enter key ID number, assign, check. ".
    "Give key slip to attendee."
    ),
);


//
// Data about the file types we use
//
$fileTypeData = array(
  "PNG"  => array(
    "class" => EFILE_IMAGE,
    "type" => EPREV_IMAGE,
    "mime" => "image/png",
    "fext" => ".png",
    "test" => "^PNG image data",
  ),
  "JPEG" => array(
    "class" => EFILE_IMAGE,
    "type" => EPREV_IMAGE,
    "mime" => "image/jpeg",
    "fext" => ".jpg",
    "test" => "^JPEG image data",
  ),
  "GIF"  => array(
    "class" => EFILE_IMAGE,
    "type" => EPREV_IMAGE,
    "mime" => "image/gif",
    "fext" => ".gif",
    "test" => "^GIF image data",
  ),

  "MP3" => array(
    "class" => EFILE_AUDIO,
    "type" => EPREV_AUDIO,
    "mime" => "audio/mpeg",
    "fext" => ".mp3",
    "test" => "MPEG ADTS, layer III",
  ),
  "OggVorbis" => array(
    "class" => EFILE_AUDIO,
    "type" => EPREV_AUDIO,
    "mime" => "audio/ogg; codecs=vorbis",
    "fext" => ".ogg",
    "test" => "Ogg data, Vorbis audio",
  ),
  "FLAC" => array(
    "class" => EFILE_AUDIO,
    "type" => EPREV_AUDIO,
    "mime" => "audio/x-flac",
    "fext" => ".flac",
  ),
  "WAV" => array(
    "class" => EFILE_AUDIO,
    "type" => EPREV_AUDIO,
    "mime" => "audio/x-wav",
    "fext" => ".wav",
  ),

  // Special cases
  "ILBM" => array(
    "class" => EFILE_IMAGE,
    "mime" => "gfx", // Special cases to be converted through gfxconv ..
    "fext" => ".lbm",
    "test" => "^IFF data",
  ),
  "PCX" => array(
    "class" => EFILE_IMAGE,
    "mime" => "image/x-pcx",
    "fext" => ".pcx",
    "test" => "^PCX ver\. 3\.0",
  ),

  "PTMOD" => array(
    "class" => EFILE_AUDIO,
    "mime" => "audio/x-mod",
    "fext" => ".mod",
    "test" => "^\d+-channel Protracker module",
  ),
  "PTMOD" => array(
    "class" => EFILE_AUDIO,
    "mime" => "audio/x-mod",
    "fext" => ".mod",
    "test" => "^\d+-channel Fasttracker module",
  ),
  "S3M" => array(
    "class" => EFILE_AUDIO,
    "mime" => "audio/x-mod",
    "fext" => ".s3m",
    "test" => "^ScreamTracker III Module",
  ),
  "XM" => array(
    "class" => EFILE_AUDIO,
    "mime" => "audio/x-mod",
    "fext" => ".xm",
    "test" => "^Fasttracker II module",
  ),
  "IT" => array(
    "class" => EFILE_AUDIO,
    "mime" => "audio/x-mod",
    "fext" => ".it",
    "test" => "^Impulse Tracker module",
  ),
  "PTM" => array(
    "class" => EFILE_AUDIO,
    "mime" => "audio/x-mod",
    "fext" => ".ptm",
    "test" => "^Poly Tracker PTM Module",
  ),

  "AVI" => array(
    "class" => EFILE_VIDEO,
    "mime" => "video/x-msvideo",
    "fext" => ".avi",
  ),
  "WMV" => array(
    "class" => EFILE_VIDEO,
    "mime" => "video/x-ms-asf",
    "fext" => ".wmv",
  ),
  "MP4" => array(
    "class" => EFILE_VIDEO,
    "mime" => "video/mp4",
    "fext" => ".mp4",
  ),
  "MOV" => array(
    "class" => EFILE_VIDEO,
    "mime" => "video/quicktime",
    "fext" => ".mov",
  ),
  "MKV" => array(
    "class" => EFILE_VIDEO,
    "mime" => "video/x-matroska",
    "fext" => ".mkv",
  ),

  // Archives
  "LHA" => array(
    "class" => EFILE_ARCHIVE,
    "mime" => "application/x-lha",
    "fext" => ".lha",
  ),
  "ZIP" => array(
    "class" => EFILE_ARCHIVE,
    "mime" => "application/zip",
    "fext" => ".zip",
  ),
  "7ZIP" => array(
    "class" => EFILE_ARCHIVE,
    "mime" => "application/x-7z-compressed",
    "fext" => ".7z",
  ),
  "RAR" => array(
    "class" => EFILE_ARCHIVE,
    "mime" => "application/x-rar",
    "fext" => ".rar",
  ),
  "ARJ" => array(
    "class" => EFILE_ARCHIVE,
    "mime" => "application/x-arj",
    "fext" => ".arj",
  ),

  // Final fallback
  "MISC" => array(
    "class" => EFILE_BINARY,
    "mime" => "application/octet-stream",
    "fext" => FALSE,
  ),

  "TEXT" => array(
    "class" => EFILE_TEXT,
    "mime" => "text/plain",
    "fext" => FALSE,
  ),
);


//
// Party infromation system data/variables handling
//
function stReloadDisplayVars()
{
  global $displayVars, $displayVarsChanged;

  $displayVars = array();
  $displayVarsChanged = array();

  if (($res = stExecSQL("SELECT * FROM display_vars")) !== FALSE)
  {
    foreach ($res as $row)
      $displayVars[$row["key"]] = stGetSQLSettingData($row);
  }
}


function stSaveDisplayVars()
{
  global $db, $displayVars, $displayVarsChanged;

  foreach (stExecSQL("SELECT * FROM display_vars") as $item)
  if (isset($displayVarsChanged[$item["key"]]))
  {
    $val = $displayVars[$item["key"]];
    stExecSQL(
      "UPDATE display_vars SET ".stGetSettingSQL($item, $val).
      " WHERE key=".$db->quote($item["key"]));
  }
}


function stDisplayUpdated()
{
  stSetDisplayVar("lastUpdate", time());
}


function stSetDisplayVarUpd($name, $value)
{
  if (stGetDisplayVar($name) != $value)
  {
    stSetDisplayVar($name, $value);
    stDisplayUpdated();
    return TRUE;
  }
  else
    return FALSE;
}


function stGetDisplayVar($name)
{
  global $displayVars;
  if (isset($displayVars[$name]))
    return $displayVars[$name];
  else
    die("No display var for '".$name."'.\n");
}


function stSetDisplayVar($name, $value)
{
  global $displayVars, $displayVarsChanged;
  if (isset($displayVars[$name]))
  {
    $displayVars[$name] = $value;
    $displayVarsChanged[$name] = true;
  }
  else
    die("No display var for '".$name."'.\n");
}


//
// Like stExecSQL(), but throws error messages to "userspace".
//
function stExecSQLCond($sql, $msg = FALSE)
{
  global $db;
  if (($res = stDBExecSQL($db, $sql)) !== FALSE)
  {
    if ($msg !== FALSE)
      stSetStatus(200, $msg);
    return $res;
  }
  else
  {
    stSetStatus(902, "Error in SQL execution.");
    return FALSE;
  }
}


function stPrintAttendee($item, $row, $tr, $full, $edit, $eclass = "")
{
  $id = $item["id"];
  $prefix = "at";

  if ($tr)
  {
    echo
      "  <tr class=\"".($row % 2 == 1 ? "rodd" : "reven").$eclass.
      "\" id=\"attendee".$id."\" ".($full ? "onClick=\"activateAttendee(".$id.")\"" : "").">";
  }

  echo
    stGetTDFormTextInput($edit, 20, SET_LEN_USERNAME, "name", $id, $prefix, $item["name"]).
    stGetTDFormTextInput($edit, 20, SET_LEN_GROUPS, "groups", $id, $prefix, $item["groups"]).
    "<td class=\"regtime\">".date("d.m. H:i", $item["regtime"])."</td>".
    stGetTDFormTextInput($edit, 30, SET_LEN_ONELINER, "oneliner", $id, $prefix, $item["oneliner"], "autocomplete=\"off\"");

  if ($full)
  {
    echo
      stGetTDFormTextInput($edit, 15, SET_LEN_EMAIL, "email", $id, $prefix, $item["email"], "autocomplete=\"off\"").
      stGetTDFormTextInput($edit, 15, SET_LEN_REGHOST, "reghost", $id, $prefix, $item["reghost"], "autocomplete=\"off\"");

    if ($edit)
    {
      echo
        "<td>".
        stGetFormButtonElement($prefix."upd".$id, "","", "Upd", "updateAttendee(".$id.")").
        stGetFormButtonElement($prefix."del".$id, "","", "Del", "deleteAttendee(".$id.")").
        "</td>";
    }
    else
      echo "<td></td>";
  }
  
  if ($tr)
    echo "</tr>\n";
}


function stPrintNewsItem($item)
{
  echo
  "<div class=\"newsItem\" id=\"news".$item["id"]."\">\n".
  "  <h2>".chentities($item["title"])."</h2>\n".
  "  <div class=\"newsText\">".dhentities($item["text"])."</div>\n".
  "  <div class=\"newsAuthor\"><span class=\"newsSig\">-- ".chentities($item["author"])."</span>".
  "<span class=\"newsDate\">".date("d M Y / H:i", $item["utime"])."</span></div>\n".
  "</div>\n";
}


function stGetTDFormTextInput($edit, $size, $len, $name, $id, $prefix, $value, $extra = "")
{
  return
    "<td class=\"".$name."\">".
    ($edit ? stGetFormTextInput($size, $len, $name, $id, $prefix, $value, $extra) : chentities($value)).
    "</td>";
}


function stGetEditFormTextInput($mode, $title, $size, $len, $name, $id, $prefix, $value, $extra = "")
{
  return
    "<div class=\"editControl\"><span class=\"editControlTitle\">".chentities($title)."</span>".
    ($mode ? stGetFormTextInput($size, $len, $name, $id, $prefix, $value, $extra) : chentities($value)).
    "</div>";
}


function stGetEditFormTextArea($mode, $title, $rows, $cols, $name, $id, $prefix, $value, $extra = "")
{
  return
    "<div class=\"editControl\"><span class=\"editControlTitle\">".chentities($title)."</span>".
    stGetFormTextArea($rows, $cols, $name, $id, $prefix, $value, ($mode ? "" : " disabled=\"disabled\" ").$extra).
    "</div>";
}


function stConvSwitchMode(&$str, &$mode, $newMode)
{
  if ($newMode != $mode)
  {
    if ($mode != "")
      $str .= "\n</".$mode.">\n";

    $mode = $newMode;

    if ($mode != "")
      $str .= "<".$mode.">\n";
  }
}


function stConvertCommonDesc($desc, $chent)
{
  $str = "";
  $mode = "";

  foreach (explode("\n", $desc) as $line)
  {
    if (preg_match("/^\s*\s*\*(.+)$/", $line, $m))
    {
      stConvSwitchMode($str, $mode, "ol");
      $str .= "<li>".($chent ? chentities($m[1]) : $m[1])."</li>\n";
    }
    else
    if (preg_match("/^\s*-\s*(.+)$/", $line, $m))
    {
      stConvSwitchMode($str, $mode, "ul");
      $str .= "<li>".($chent ? chentities($m[1]) : $m[1])."</li>\n";
    }
    else
    {
      stConvSwitchMode($str, $mode, "p");
      $str .= ($chent ? chentities($line) : $line);
    }
  }

  stConvSwitchMode($str, $mode, "");

  return $str;
}


function stGetNumberSuffix($val)
{
  switch ($val)
  {
    case  1: return "st";
    case  2: return "nd";
    case  3: return "rd";
    case  4: case 5: case 6:
    case  7: case 8: case 9: return "th";
    default: return "th";
  }
}


function stGenerateUserKey()
{
  global $db;
  $keyChars = "abdefghjkmnpqrstwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  
  while (TRUE)
  {
    // Generate one randomized keycode
    $key = "";
    for ($n = 0; $n < stGetSetting("userKeyLength"); $n++)
      $key .= $keyChars[rand() % strlen($keyChars)];

    // Check if it already exists, to avoid duplicates
    // We need custom query code here, because stFetchSQLColumn()
    // won't work due to it returning FALSE in error cases.
    $sql = stPrepareSQL("SELECT * FROM votekeys WHERE key=%s", $key);
    if (($res = @$db->query($sql)) !== FALSE)
    {
      // Did we get results?
      if ($res->fetchColumn() === FALSE)
      {
        // Nope, return key
        return $key;
      }
    }
    else
    {
      stLogSQLError($sql);
      return FALSE;
    }
  }
}


function stCheckRegistrationAvailable()
{
  global $maxAttendeesHard, $maxAttendeesSoft, $numAttendees;

  $maxAttendeesHard = stGetSetting("maxAttendeesHard");
  $maxAttendeesSoft = stGetSetting("maxAttendeesSoft");
  if (($numAttendees = stFetchSQLColumn("SELECT COUNT(*) FROM attendees")) === FALSE)
    $numAttendees = 0;

  return stChkSetting("allowRegister") && ($maxAttendeesHard <= 0 || $numAttendees < $maxAttendeesHard);
}


function stValidateRequestUserData($admin, $id = FALSE)
{
  $res = TRUE;
  $chk = 0;

  if (stChkRequestItem("name", $name,
      array(CHK_ISGT, VT_STR, 0, "Handle / name not given."),
      array(CHK_LTEQ, VT_STR, SET_LEN_USERNAME, "Handle / name is too long, should be less than ".SET_LEN_USERNAME." characters.")))
    $chk++;
  else
    $res = FALSE;

  if (stChkRequestItem("groups", $groups,
      array(CHK_LTEQ, VT_STR, SET_LEN_GROUPS, "Groups are too long, should be less than ".SET_LEN_GROUPS." characters.")))
    $chk++;
  else
    $res = FALSE;

  if (!stChkRequestItem("oneliner", $oneliner,
      array(CHK_LTEQ, VT_STR, SET_LEN_ONELINER, "Oneliner is too long, should be less than ".SET_LEN_ONELINER." characters.")))
    $res = FALSE;

  $email = stGetRequestItem("email");
  if (!$admin && stGetSetting("requireEMail") && strlen($email) < 4)
  {
    stError("E-mail address not given, or it is too short.");
    $res = FALSE;
  }

  if (strlen($email) > 0 && preg_match("/^[a-z0-9][a-z0-9\+\-\.\%_]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", $email) != 1)
  {
    stError("E-mail address not in proper format.");
    $res = FALSE;
  }

  if (strlen($email) > SET_LEN_EMAIL)
  {
    stError("E-mail address too long, max ".SET_LEN_EMAIL." characters.");
    $res = FALSE;
  }

  // Check if another user already exists
  if ($chk >= 2)
  {
    if ($id !== false)
      // By another ID, if we are updating an entry
      $sql = stPrepareSQL("SELECT * FROM attendees WHERE id<>%d AND name=%s AND groups=%s", $id, $name, $groups);
    else
      // Or just exists, if adding
      $sql = stPrepareSQL("SELECT * FROM attendees WHERE name=%s AND groups=%s", $name, $groups);

    if (($data = stFetchSQL($sql)) !== false)
    {
      stError("Someone with the same name and groups is already registered.");
      $res = FALSE;
    }
  }
  return $res;

}


function stGetCompoResultsSQL($mode, $compo, $flags)
{
  //
  // Act based on competition type
  //
  switch ($compo["ctype"])
  {
    case COMPO_NORMAL:
      //
      // "Normal" competition, where results are somehow
      // based on points / voting.
      //
      switch ($mode)
      {
        case VOTE_FREELY:
          $sql =
            "SELECT entries.*,SUM(votes.value) AS votesum ".
            "FROM entries ".
            "LEFT JOIN votes ON votes.entry_id=entries.id";
          break;

        case VOTE_ACTIVATE:
          $sql =
            "SELECT entries.*, ".
              "(SELECT SUM(votes.value) FROM votes ".
              "LEFT JOIN votekeys ON votes.key_id=votekeys.id ".
              "WHERE votes.entry_id=entries.id AND votekeys.active<>0) ".
              "AS votesum ".
            "FROM entries";
          break;

        case VOTE_ASSIGN:
          $sql =
            "SELECT entries.*, ".
              "(SELECT SUM(votes.value) FROM votes ".
              "LEFT JOIN votekeys ON votes.key_id=votekeys.id ".
              "LEFT JOIN attendees ON votekeys.id=attendees.key_id ".
              "WHERE votes.entry_id=entries.id AND attendees.key_id<>0) ".
              "AS votesum ".
            "FROM entries";
          break;
      }

      $extra = 
        "GROUP BY entries.id ".
        "ORDER BY votesum DESC";
      break;

    case COMPO_POINTS:
      //
      // Points ..
      //
      $sql = "SELECT entries.*,entries.evalue AS votesum FROM entries";
      $extra = "ORDER BY entries.evalue DESC";
      break;

    case COMPO_ASSIGN:
      //
      // Ascending
      //
      $sql = "SELECT entries.*,entries.evalue AS votesum FROM entries";
      $extra = "ORDER BY entries.evalue ASC";
      break;
  }

  return $sql." ".
    "WHERE entries.compo_id=".$compo["id"]." ".
    (($flags & RFLAG_DISQUALIFIED) ? "" : "AND (entries.flags & ".EFLAG_DISQUALIFIED.")=0 ").
    $extra;
}


function stGetCompoResults($flags)
{
  $voteKeyMode = stGetSetting("voteKeyMode");
  $out = array();
  $sql = "SELECT * FROM compos ".(($flags & RFLAG_HIDDEN_COMPOS) ? "" : "WHERE visible<>0 ")."ORDER BY name DESC";
  if (($res = stExecSQL($sql)) === false)
    return $out;

  // For each compo that has been set visible
  foreach ($res as $compo)
  {
    // Check if there are any entries for it
    $sql =
      "SELECT COUNT(*) FROM entries ".
      "WHERE compo_id=".$compo["id"].
      (($flags & RFLAG_DISQUALIFIED) ? "" : " AND (entries.flags & ".EFLAG_DISQUALIFIED.")=0");

    if (($nentries = stFetchSQLColumn($sql)) !== FALSE &&
        ($nentries > 0 || ($flags & RFLAG_HIDDEN_COMPOS)))
    {
      // Get voting results by mode
      $sql = stGetCompoResultsSQL($voteKeyMode, $compo, $flags);

      $out[$compo["id"]] = $compo;
      $out[$compo["id"]]["results"] = array();
      $prev = FALSE;
      $index = 0;

      foreach (stExecSQL($sql) as $entry)
      {
        if ($entry["votesum"] !== $prev)
          $index++;

        $entry["position"] = $index;
        $out[$compo["id"]]["results"][] = $entry;

        $prev = $entry["votesum"];
      }
    }
  }
  
  return $out;
}


function stGetCompoResultLine($html, $entry, $points, $showAuthor)
{
  $name = stStrChopPad($entry["name"], 30);
  $author = stStrChopPad($entry["author"], 30);

  $out = sprintf("  %s", $html ? chentities($name) : $name);

  // Author?
  if ($showAuthor)
    $out .= sprintf("  by  %s", $html ? chentities($author) : $author);

  // Points?
  if ($points !== FALSE)
    $out .= sprintf(" (%d pts)", $points);

  // Add disqualified flag etc.
  if ($entry["flags"] & EFLAG_DISQUALIFIED)
    $out .= " [DISQ]";

  return $out."\n";
}


function stGetCompoResultsASCIIStr($html, $flags)
{
  $out = "";
  foreach (stGetCompoResults($flags) as $compo)
  {
    // Output compo title / header
    if ($html)
    {
      $out .=
        "<pre>\n".
        "<b> ".chentities($compo["name"])." </b>\n".
        str_repeat("=", strlen($compo["name"]) + 2)."-- - .\n\n";
    }
    else
    {
      $out .=
        " ".$compo["name"]."\n".
        str_repeat("=", strlen($compo["name"]) + 2)."-- - .\n\n";
    }

    // List results for this compo
    $prev = FALSE;
    foreach ($compo["results"] as $entry)
    {
      if ($entry["position"] !== $prev)
        $out .= sprintf("%3d%s.", $entry["position"], stGetNumberSuffix($entry["position"]));
      else
        $out .= "  -''-";

      $out .= stGetCompoResultLine($html, $entry,
        ($compo["ctype"] != COMPO_ASSIGN) ? $entry["votesum"] : FALSE,
        ($compo["ctype"] != COMPO_NORMAL) ? $compo["show_authors"] : TRUE);

      $prev = $entry["position"];
    }
    $out .= "\n\n".($html ? "</pre>\n" : "");
  }

  return $out;
}


function stGetAttendeeRegistrationSQL()
{
  return stPrepareSQL(
    "INSERT INTO attendees (regtime,name,groups,oneliner,email,reghost) VALUES (%d,%S,%S,%S,%S,%s)",
    time(), "name", "groups", "oneliner", "email", $_SERVER["REMOTE_ADDR"]);
}


//
// Create a path, or URL from specified components
//
function stMakePath($isURL, $repExt, $components)
{
  $res = array();

  // If this is URL, the first component is passed as is
  if ($isURL)
  {
    $res[] = array_shift($components);
    $first = FALSE;
  }
  else
    $first = TRUE;

  // Handle each path component
  foreach ($components as $subComponent)
  {
    foreach (explode("/", $subComponent) as $item)
    {
      if ($item == "..")
        array_pop($res);
      else
      if ($item != "." && ($item != "" || $first))
        $res[] = preg_replace("/[^a-zA-Z0-9\,\.\/_-]/", "_", $item);

      $first = FALSE;
    }
  }

  // Optionally, replace the file extension with given string
  if ($repExt !== FALSE && ($tmp = array_pop($res)) !== false)
  {
    if (($spos = strrpos($tmp, ".")) !== FALSE)
      $tmp = substr($tmp, 0, $spos).$repExt;
    else
      $tmp .= $repExt;

    $res[] = $tmp;
  }

  return implode("/", $res);
}


function stGetEntryPreviewData($compo, $entry, $probePreview, $fullData)
{
  $res = array();
  $entryPath = stGetSetting("entryPath");
  $previewPath = stGetSetting("previewPath");
  $previewURL = stGetSetting("previewURL");
  $thumbDir = stGetSetting("thumbnailSubDir");

  $filename = $entry["filename"];

  // Data for the actual entry file
  $res["previewType"] = ($entry["preview_type"] != EPREV_NONE) ? $entry["preview_type"] : $compo["preview_type"];
  $res["entryFile"] = stMakePath(FALSE, FALSE, array($entryPath, $compo["cpath"], $filename));
  if ($fullData)
  {
    $res["entrySize"] = @filesize($res["entryFile"]);
  }

  // Based on preview type, set some basics
  switch ($res["previewType"])
  {
    case EPREV_IMAGE:
      $res["fileBase"] = stMakePath(FALSE, "_sshot", array($filename));
      $res["preferType"] = "PNG";
      $fileTypeList = array(
        "PNG"  => array(".png", ".PNG"),
        "GIF"  => array(".gif", ".GIF"),
        "JPEG" => array(".jpg", ".JPG"),
      );
      break;
    
    case EPREV_AUDIO:
      $res["fileBase"] = stMakePath(FALSE, "_sample", array($filename));
      $res["preferType"] = "PNG";
      $fileTypeList = array(
        "audio/mpeg" => array(".mp3", ".MP3"),
        "audio/ogg; codecs=vorbis" => array(".ogg", ".OGG", ".oga", ".OGA"),
      );
      break;
    
    default:
      return FALSE;
  }

  // Find the preview file(s)
  foreach ($fileTypeList as $fileType => $fileExts)
  {
    foreach ($fileExts as $fext)
    {
      $filename = stMakePath(FALSE, $fext, array($previewPath, $compo["cpath"], $res["fileBase"]));
      if ($probePreview == FALSE || file_exists($filename))
      {
        $res["previewFileType"]  = $fileType;
        $res["previewPath"]  = $filename;
        $res["previewURL"]   = stMakePath(TRUE, $fext, array($previewURL, $compo["cpath"], $res["fileBase"]));

        if ($res["previewType"] == EPREV_IMAGE)
        {
          $res["thumbPath"] = stMakePath(FALSE, $fext, array($previewPath, $compo["cpath"], $thumbDir, $res["fileBase"]));
          $res["thumbURL"]  = stMakePath(TRUE, $fext, array($previewURL, $compo["cpath"], $thumbDir, $res["fileBase"]));
        }

        if ($fullData)
        {
          $res["previewSize"]  = @filesize($res["previewPath"]);
          $res["thumbSize"] = @filesize($res["thumbPath"]);
        }

        return $res;
      }
    }
  }

  return FALSE;
}


function stPrintPreviewElements($compo, $entry)
{
  if (($pdata = stGetEntryPreviewData($compo, $entry, FALSE, TRUE)) === FALSE)
    return FALSE;

  switch ($pdata["previewType"])
  {
    case EPREV_IMAGE:
      if ($pdata["previewSize"] === FALSE || $pdata["thumbSize"] === FALSE)
      {
        echo
          "<img class=\"imagePreview\" src=\"img/nopreview_tn.png\" alt=\"Preview\" />";
      }
      else
      {
        echo
          "<a href=\"".ihentities($pdata["previewURL"]).
          "\" onClick=\"return jsShowPreviewImage('".ihentities($pdata["previewURL"])."');\">".
          "<img class=\"imagePreview\" src=\"".ihentities($pdata["thumbURL"]).
          "\" alt=\"Preview\" /></a>";
      }
      break;

    case EPREV_AUDIO:
      if ($pdata["previewSize"] !== FALSE)
      {
        echo
          "<audio controls preload=\"none\" class=\"audioPreview\">".
          "<source src=\"".ihentities($pdata["previewURL"])."\" type=\"".$pdata["previewFileType"]."\">".
          "</audio>";
      }
      break;
  }

  return TRUE;
}


//
// Probe file type information
//
function stProbeFileInfo($filename)
{
  global $fileTypeData;

  // Get file magic info
  if (($finfo = finfo_open()) === false)
  {
    error_log("Internal error. Failed to initialize finfo().");
    return stError("Internal error, failed to probe file.");
  }

  $sdata = @finfo_file($finfo, $filename, FILEINFO_NONE);
  $smime = @finfo_file($finfo, $filename, FILEINFO_MIME_TYPE);
  finfo_close($finfo);

  // Did we get anything?
  if ($sdata === FALSE || $smime === FALSE)
  {
    error_log("Failed to probe file '".$filename."'.");
    return stError("Internal error, failed to probe file.");
  }

  // Match through our supported types ..
  foreach ($fileTypeData as $fid => $fdata)
  {
    $fdata["id"] = $fid;

    if (isset($fdata["test"]))
    {
      if (preg_match("/".$fdata["test"]."/", $sdata))
        return $fdata;
    }
    else
    if ($fdata["mime"] == $smime)
      return $fdata;
  }

  error_log("File '".$filename."' (".$smime.") did not match any allowed file types.");
  return stError("No matching allowed file type found for '".$smime."'.");
}


//
// File table entry adding
//
function stAddFileEntry($filename, $size, $uploaderID, $type, $entryID, &$fileID)
{
  // Create new file entry
  $sql = stPrepareSQL(
    "INSERT INTO files (orig_filename,filesize,entry_id,uploader_id,utime) VALUES (%s,%d,%d,%d,%d)",
    $filename, $size, $entryID, $uploaderID, time());

  if (($fileID = stExecSQLInsert($sql)) === false)
    return stError("Failed to add new ".$type." for entry #".$entryID." '".$filename."'.");

  // Update entry's data
  $sql = stPrepareSQL("UPDATE entries SET ".$type."_id=%d WHERE id=%d",
    $fileID, $entryID);

  if (stExecSQL($sql) === false)
    return stError("Failed to update entry #".$entryID." ".$type." ID ... :S");

  return TRUE;
}


function stSetFileEntryFilename($fileID, $type, $entry, $fext, $ftype, &$fname)
{
  switch ($type)
  {
    case "preview":
      $fname = sprintf("%03d-%s--%s_%s_(%03d).%s",
	$entry["id"],
	$entry["author"], $entry["name"],
	$type, $fileID, $fext);
      break;

    case "entry":
      $fname = sprintf("%03d-%s--%s_(%03d).%s",
	$entry["id"],
	$entry["author"], $entry["name"],
	$fileID, $fext);
      break;

    default:
      return FALSE;
  }

  $sql = stPrepareSQL("UPDATE files SET filename=%s,filetype=%s WHERE id=%d",
    $fname, $ftype, $fileID);

  return stExecSQL($sql) !== false;
}


//
// File upload handling
//
function stHandleGenericFileUpload($userID)
{
  global $errorSet;

  // Check basics
  if (!stChkRequestItem("type", $uploadType,
        array(CHK_TYPE, VT_STR, "Invalid upload type."),
        array(CHK_ARRAY, VT_STR, array("entry", "preview"), "Invalid upload type."))
      ||
      !stChkRequestItem("entry_id", $entryID,
        array(CHK_TYPE, VT_INT, "Invalid entry ID.")))
    return FALSE;

  // Check entry existence
  if (($entry = stFetchSQL("SELECT * FROM entries WHERE id=".$entryID)) === false)
    return stError("Entry ID #".$entryID." does not exist??");

  if (($compo = stFetchSQL("SELECT * FROM compos WHERE id=".$entry["compo_id"])) === false)
    return stError("Compo ID does not exist??");

  // Check permissions for non-admins
  if ($userID != 0)
  {
    // Check if the user even exists, just in case
    if (($user = stFetchSQL("SELECT * FROM attendees WHERE id=".$userID)) === false)
      return stError("User ID #".$userID." does not exist??");

    if ($entry["owner_id"] != $userID)
      return stError("Attempted to upload file to entry not owned by user.");
  }

  // Check file status data
  $fileEntry = $uploadType."ToUpload".$entryID;
  $maxFileSize = stGetSetting($uploadType."MaxSize");
  $fileSize = $_FILES[$fileEntry]["size"];
  if ($fileSize > $maxFileSize)
    stError("File size ".$fileSize." exceeds FAPWeb's size of ".$maxFileSize." bytes for ".$uploadType." uploads.");

  if ($fileSize < 128)
    stError("File size ".$fileSize." is less than 128 bytes. This can't be right.");

  switch ($_FILES[$fileEntry]["error"])
  {
    case UPLOAD_ERR_INI_SIZE:
      stError("File size exceeds PHP's max upload size.");
      break;

    case UPLOAD_ERR_PARTIAL:
      stError("File only partially uploaded.");
      break;

    case UPLOAD_ERR_NO_FILE:
      stError("No file data received!");
      break;

    case UPLOAD_ERR_NO_TMP_DIR:
      stError("Internal error: Temporary file directory not available!");
      break;

    case UPLOAD_ERR_CANT_WRITE:
      stError("Internal error: PHP could not write the file to disk.");
      break;

    case UPLOAD_ERR_OK:
      break;

    default:
      stError("Unknown PHP file error occured.");
      break;
  }

  if ($errorSet)
    return FALSE;


  // Check file properties ..
  $tmpFilename = $_FILES[$fileEntry]["tmp_name"];
  if (($fileInfo = stProbeFileInfo($tmpFilename)) === false)
    return FALSE;

  if ($uploadType == "preview" && !isset($fileInfo["type"]))
    return stError("Preview file upload is not one of the supported preview file types.");

  // Add file entry
  if (!stAddFileEntry($_FILES[$fileEntry]["name"], $fileSize, $userID, $uploadType, $entry, $fileID))
    return FALSE;

  // Set rest of the data ..
  if (!stSetFileEntryFilename($fileID, $uploadType, $entry, $fileInfo["fext"], $fileInfo["id"], $filename))
    return FALSE;

  // Set permissions before moving the file
  if (chmod($tmpFilename, stGetSetting($uploadType."PathPerms")) === false)
  {
    error_log("Could not set permissions for uploaded file '".$tmpFilename."'.");
    return stError("Could not set permissions for uploaded file.");
  }

  // Move file to its destination
  $fullFile = stMakePath(FALSE, FALSE, array(stGetSetting("entryPath"), $compo["cpath"], $filename));
  if (@move_uploaded_file($tmpFilename, $fullFile) === false)
  {
    error_log("Could not move uploaded file '".$tmpFilename."' to '".$fullFile."'.");
    return stError("Deploying uploaded file failed.");
  }

  return TRUE;
}


// Get link helper function
function stGetMainPageLink($id, $name, $show = TRUE)
{
  global $pageName;
  if ($show)
    return "    <a class=\"".($id == $pageName ? "active" : "inactive")."\" href=\"".$id."\">".$name."</a>\n";
  else
    return "";
}


function stNormalizeListSlideOrder($list_id)
{
}


?>