<?php
  include("include.php");
  // Handle logins... must do it early in case we have to change headers
  // Login entry vectors are:
  // (1) extrasticks.php?login=&username=xxx&password=xxx (user clicked login button)
  //         -> set session, and redirect to extrasticks.php?sess=xxx, so that back button will work
  // (2) extrasticks.php?login=&username=xxx&password=wrong (user clicked login button)
  //         -> redirect to extrasticks.php?login=failed, to display the error message
  // (3) extrasticks.php?login=failed (for redirection after failed login)
  $login_failed=false;
  if (isset($REQ["login"]))
  { if ($REQ["login"]=="failed") $login_failed=true;
    else
    { $username = $REQ["username"];
      $password = $REQ["password"];
      $r = load_array("users/{$username}.txt");
      // nb. testing username might seem redundant, but it's not, because it also tests for succesfull loading of r
      $viewkey=""; $viewval="";
      if (isset($REQ["cat"])) {$viewkey="cat"; $viewval=$REQ["cat"];}
      if (isset($REQ["author"])) {$viewkey="author"; $viewval=$REQ["author"];}
      if (isset($r["username"]) && $r["username"]==$username && isset($r["password"]) && $r["password"]==crypt($password,"stk"))
      { $_SESSION["ssuser"]=$username;
        $urlarg = http_build_query4(array($viewkey=>$viewval, $ssname=>$ssid));
        header("Location: http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/extrasticks.php?{$urlarg}");
        exit;
      } 
      else
      { $urlarg = http_build_query4(array($viewkey=>$viewval, "login"=>"failed", "username"=>$username));
        header("Location: http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/extrasticks.php?{$urlarg}#login");
        exit;
      }      
    }  
  }
?>
<html>
<head>
<title>Extra Stick Figures</title>
<link rel=stylesheet href="extra.css" TYPE="text/css" title="Extra">
</head>
<body>


 <div style="text-align: center;">
 <div style="width: 620px; text-align: center;">
  

 <h1>Extra Stick Figures</h1>

 
 <?php


   // This page is for displaying either the "new" list of stick figures, or a category.
   // (1) ?cat=Abstract%2FAmp tells us to display that category. Cat is eg. "Abstract/Amp" for sticks/Abstract/Amp/*.stk
   // (2) ?author=xxx tells us to display sticks by that user
   // (2) ?login&username=u&password=fred tells us to log in (disregarding the one in username).
   // (x) &{$ssname}=xxx is a session-id, which might provide a username
   $viewby = "new"; // new/cat/author
   $viewcat=""; $viewauthor=""; 
   //
   // We build a list of sticks and a list of categories.
   // $categories = array([0]=>"Abstract", [1]=>"Abstract/Amp", ...)
   // $sticks = array(  [0]=>array(["fn"]=>"Hello (lu)", ["stickname"]=>"Hello", ["author"]=>"lu", ["cat"]=>cat, ["time"]=>timestamp) ... )
   $categories = array();

   //
   $viewby="new";
   if (isset($REQ["cat"])) {$viewby="cat"; $viewcat=$REQ["cat"]; if ($viewcat=="") $viewby="new";}
   if (isset($REQ["author"])) {$viewby="author"; $viewauthor=$REQ["author"]; if ($viewauthor=="") $viewby="new";}
   $viewkey=$viewby; $viewval=""; if ($viewby=="cat") $viewval=$viewcat; if ($viewby=="author") $viewval=$viewauthor;
     

   $filterauthor_s = "";
   function filterauthor($stick) {global $filterauthor_s; return ($filterauthor_s==$stick["author"]);}      
   //
   $buildok=true;
   if (!file_exists("sticks/categories.txt")) $buildok=$buildok && build_cache($username);
   $buf = file_get_string("sticks/categories.txt");
   $categories=array(); if ($buf!="") $categories=unserialize($buf);


   // print the categories   
   echo "<p style=\"font-size: smaller;\">\n";
   echo "<a href=\"extrasticks.php?{$ssname}=${ssid}\">Home</a>";
   $prefix="_";
   foreach($categories as $catstruct)
   { if ($catstruct["isempty"]) continue;
     if ($catstruct["silent"]) continue;
     $cat = $catstruct["fn"];
     $i=strpos($cat,"/"); $path=($i==0)?$cat:substr($cat,0,$i); $name=($i==0)?$cat:substr($cat,$i+1);
     $samecat = ($prefix==$path); 
     $rcat = $cat; if ($samecat) $rcat=$name;
     if ($samecat) echo ", "; else echo " -- ";
     $urlarg = http_build_query4(array("cat"=>$cat, $ssname=>$ssid));
     echo "\n<a href=\"extrasticks.php?{$urlarg}\">".str_replace(" ","&nbsp;",$rcat)."</a>";
     $prefix=$path;
   }

  
  if (!$buildok) echo "<p>[The stick database is momentarily undergoing maintenance. If things look odd, please refresh.]</p>\n";

  
  // Now the tables of sticks, and the login box below.

  // Hopefully we can connect to the database to print votes
  $db=@mysql_connect($sql["server"],$sql["username"],$sql["password"]);
  if ($db) mysql_select_db("wischik_sticky");

  // A "cat" page shows just one table of sticks -- for the category
  // The "new" page shows an optional "new" table of sticks, then the editor's picks, then an optional "top-vote" table.
  // The "author" page shows just one table, of sticks by that author
  $tables = array();
  if ($viewby=="new")
  { $sticks=array();
    $fn="sticks/new.txt"; if (!file_exists($fn)) $buildok=$buildok && build_cache($username);
    $buf=file_get_string($fn); if ($buf!="") $sticks=unserialize($buf);
    if (count($sticks)>0) $tables["Recent sticks"]=$sticks;
    //
    $sticks=array();
    $fn="sticks/picks.txt"; if (!file_exists($fn)) $buildok=$buildok && build_cache($username);
    $buf=file_get_string($fn); if ($buf!="") $sticks=unserialize($buf);
    if (count($sticks)>0) $tables["Editor's picks"]=$sticks;
    //
    $sticks=array(); $allsticks=array();
    $fn="sticks/all.txt"; if (!file_exists($fn)) $buildok=$buildok && build_cache($username);
    $buf=file_get_string($fn); if ($buf!="") $allsticks=unserialize($buf);
    if (count($sticks)>0) $tables["Editor's picks"]=$sticks;
    if ($db)
    { $q=mysql_query("SELECT * FROM sticks ORDER BY vote DESC LIMIT 8"); $numtops=mysql_num_rows($q);
      for ($i=0; $i<$numtops; $i++)
      { $r=mysql_fetch_assoc($q);
        if (!isset($r["vote"]) || $r["vote"]==0) continue;
        $fn = $r["fn"];
        if (isset($allsticks[$fn])) {$stick=$allsticks[$fn]; $sticks[]=$stick;}
      } 
    }
    if (count($sticks)>0) $tables["Top votes"]=$sticks;      
  }
  else if ($viewby=="cat")
  { $fn="sticks/{$viewcat}/index.txt"; if (!file_exists($fn)) $buildok=$buildok && build_cache($username);
    $buf=file_get_string($fn); if ($buf!="") $sticks=unserialize($buf);
    if (count($sticks)>0) $tables[$viewcat]=$sticks;
  }
  else if ($viewby=="author")
  { $fn="sticks/all.txt"; if (!file_exists($fn)) $buildok=$buildok && build_cache($username);
    $buf=file_get_string($fn); if ($buf!="") $sticks=unserialize($buf);
    global $filterauthor_s; $filterauthor_s=$viewauthor;
    $sticks=array_filter($sticks,"filterauthor");
    if (count($sticks)>0) $tables["Sticks by {$viewauthor}"]=$sticks;
  }
  
  // The topmost table might display the "[admin] [logout] [submit]" panel; other tables won't.
  $panel="";
  if ($username!="" && is_admin($username)) $panel .="<a href=\"admin.php?".http_build_query4(array($ssname=>$ssid))."\">[@]</a> &nbsp; ";
  $panel .="<a href=\"vote.php?".http_build_query4(array($viewkey=>$viewval, "recent"=>"recent", $ssname=>$ssid))."\">[forum]</a> &nbsp; ";
  if ($username!="") $panel .="<a href=\"extrasticks.php?".http_build_query4(array($viewkey=>$viewval))."\">[logout]</a> &nbsp; ";
  $urlarg=""; if ($viewby=="cat") $urlarg=http_build_query4(array("cat"=>$viewcat, "new"=>"new", $ssname=>$ssid));
  else $urlarg=http_build_query4(array("new"=>"new", $ssname=>$ssid));
  if ($username!="") $panel .="<a href=\"submit.php?{$urlarg}\">[submit]</a> ";
  
  foreach($tables as $tname=>$sticks)
  { echo "<table>\n";
    echo "<tr><td style=\"padding-top: 3ex;\">&nbsp;</td></tr>\n";      
    echo "<tr><td colspan=".($panel==""?"4":"2")." class=\"download\">".htmlspecialchars($tname)."</td>\n";
    if ($panel!="") echo "<td colspan=2 class=\"download\" style=\"text-align: right\">\n{$panel}\n</td>\n";
    echo "<tr>\n";
    $panel="";
      
    // the first few icons are for sub-categories.
    $rowcount = 0;
    if ($viewby=="cat")
    { foreach($categories as $catstruct)
      { if (!$catstruct["silent"]) continue;
        $cat = $catstruct["fn"];
        $parent = ExtractFilePath($cat);
        if ($parent!=$viewcat) continue;
        if ($rowcount==4) {echo "\n\n</tr><tr>\n\n"; $rowcount=0;}
        echo "<td class=\"thumb\"><a href=\"extrasticks.php?".http_build_query4(array("cat"=>$cat, $ssname=>$ssid))."\">";
        echo "<img width=128 height=128 src=\"".urlfix("sticks/{$cat}/index.gif")."\"><br>";
        echo ExtractFileName($cat)."</a></td>\n\n";
        $rowcount = $rowcount+1;
      }
    }
   
    foreach($sticks as $stick)
    { if ($rowcount==4) {echo "\n\n</tr><tr>\n\n"; $rowcount=0;}
      $cat = $stick["cat"];
      $fn = $stick["fn"];
      $stickname = $stick["stickname"];
      $author = $stick["author"];
      $edit = ($author!=$username && !is_admin($username)) ? "" : "<a style=\"text-decoration: none;\" href=\"submit.php?".http_build_query4(array("cat"=>$cat, "edit"=>$fn, $ssname=>$ssid))."\">*</a>";
      // 
      $vote=""; $stkid="";
      if (isset($stick["stkid"]))
      { $stkid = $stick["stkid"];
        if ($db && isset($stkid) && $stkid!=-1 && $stkid!="")
        { $q = mysql_query("SELECT * FROM sticks WHERE stkid={$stkid}");
          $r = mysql_fetch_array($q, MYSQL_ASSOC); if (isset($r["vote"])) $vote=(int)($r["vote"]+0.5);
          mysql_free_result($q);
        }
      }
      if ($username!="" && $stkid!="" && $vote=="") $vote="[vote]";
      if ($vote!="" && $vote!="[vote]") $vote=$vote."/5";
      if ($stkid!="") $vote="<a style=\"text-decoration: none;\" href=\"vote.php?".http_build_query4(array("stk"=>$stkid, $viewkey=>$viewval, $ssname=>$ssid))."\">".$vote."</a>";
      if (!$db) $vote="";
      //
      $urlarg = http_build_query4(array("author"=>$author, $ssname=>$ssid));
      $attrib = ($author=="") ? "" : "by <a style=\"text-decoration: none;\" href=\"extrasticks.php?{$urlarg}\">{$author}</a>.{$edit}<br>{$vote}";
      echo "<td class=\"thumb\"><a href=\"".urlfix("sticks/{$cat}/{$fn}.stk")."\">";
      echo "<img ".nearest_colorclass($stick["bg"])." width=128 height=128 src=\"".urlfix("sticks/{$cat}/{$fn}.gif")."\"><br>";
      echo "{$stickname}</a><br>";
      echo "{$attrib}</td>\n\n";
      $rowcount = $rowcount+1;
    }
    echo "</tr>"; // that ends this table
  } // ends the "foreach table"
  // but if no tables were displayed, we still need the panel...
  if ($panel!="")
  { echo "<tr><td style=\"padding-top: 3ex;\">&nbsp;</td></tr>\n";      
    echo "<td colspan=4 class=\"download\" style=\"text-align: right\">\n{$panel}\n</td>\n";
    echo "<tr>\n";
    echo "</table>\n";
    $panel="";
  }
     
  
   
  if ($db) mysql_close($db);



   if ($username=="")
   { $urlarg=http_build_query4(array($viewkey=>$viewval, $ssname=>$ssid)); 
     echo "<table>\n".
          "<tr><td colspan=4 style=\"padding-top: 12ex;\">&nbsp;</td></tr>\n".
          "<tr><td colspan=4 style=\"text-align: left; background-color: rgb(40,40,40); padding: 2ex;\">\n" .
          "<form name=\"subForm\" id=subForm action=\"extrasticks.php?{$urlarg}\" method=post>\n";
     echo "<p style=\"font-size: smaller;\">Instructions: click on a stick, and choose \"Open\". Or save it to your computer and then double-click.<br>\n".
          "If you don't know what these things are, go to the main page: <a href=\"index.html\">Dancing Stick Figures</a>.</p>\n".
          "<p style=\"font-size: smaller;\"><b>Security note:</b> these sticks are guaranteed safe to download.<br>\n".
          "Upon submission, each stick is broken down by the website into its\n".
          "constituent text and images, checked for anomalies, then zipped up\n".
          "by the website and renamed from .zip to .stk. It's technically\n".
          "impossible for any of these sticks to contain malicious content.</p>\n".
          "</td></tr><tr><td colspan=4 style=\"font-size: xx-small\">&nbsp;</td></tr><tr>\n".
          "<a name=\"login\"></a><td colspan=4 style=\"text-align: left; background-color: rgb(40,40,40); padding: 2ex;\">\n";
     $us=""; if (isset($REQ["username"])) $us=$REQ["username"];
     $pa=""; if (isset($REQ["password"])) $pa=$REQ["password"];
     if ($login_failed) echo "<p class=\"error\">Login failed.</p>\n";
     echo "Username: <input type=\"text\" name=\"username\" id=\"username\" style=\"width: 6em;\" value=\"{$us}\"/>\n" .
          "Password: <input type=\"password\" name=\"password\" id=\"password\" style=\"width: 6em;\" value=\"{$pa}\"/>\n" .
          "<input type=\"submit\" name=\"login\" id=\"login\" value=\"login\"/>\n".
          "<p>Registered users can upload their own sticks, and vote and post comments. <a href=\"register.php\">Register</a>.</p>\n".
          "</form></td></tr>\n</table>\n\n";
          
   }


   ?>
   
   


 </div>
 </div>
 

</body>
</html> 
