view beta.php @ 10:6272ca0cacea

Make editing of custom timetable easier.
author Matti Hamalainen <ccr@tnsp.org>
date Tue, 11 Jan 2011 22:30:59 +0200
parents fe5b563eaae5
children 03c393c347c7
line wrap: on
line source

<?
$pageCSS = array("http://tnsp.org/docs1.css", "luk.css");
$pageCharset = "iso-8859-15";
$luokkaDefault = "TTE9SNO";
$dataDir = "cache/";
$classFile = "luokat.txt";
$mapFile = "kartta.png";
$roomFile = "luokkatilat.txt";
$cacheFile = "coursecache.txt";
$baseURI = "http://tnsp.org/luk/beta.php";
$infoURI = "http://www.oamk.fi/opiskelijalle/rakenne/opinto-opas/koulutusohjelmat/?sivu=oj&kieli=FI&opas=2010-2011&vuosi=10S11K&koodi1=";
$dayNames = array("Maanantai", "Tiistai", "Keskiviikko", "Torstai", "Perjantai", "Lauantai", "Sunnuntai");

// Include framework
require "mcommon.inc.php";
require "merrors.inc.php";


// Helper functions
function checkClassID(&$id)
{
  global $luokkaDefault;
  if (!preg_match("#^[A-Z]{3}\d\S+|ccr#", $id)) {
    errorMsg("Virhe! Luokan täytyy olla muotoa <b>XXXnXXX</b>, käytetään vakioavoa <b>".$luokkaDefault."</b>.");
    $id = $luokkaDefault;
    return FALSE;
  } else
    return TRUE;
}


// Check given parameters
if (isset($_GET["luokka"])) {
  $luokka = $_GET["luokka"];
  if (checkClassID($luokka)) {
    setcookie("lukluokka", $luokka, time() + 365*24*60*60); // expire in a year
  }
} else
if (isset($_COOKIE["lukluokka"])) {
  $luokka = $_COOKIE["lukluokka"];
  checkClassID($luokka);
} else {
  errorMsg("Luokkaa ei asetettu, käytetään vakioarvoa <b>".$luokkaDefault."</b>.");
  $luokka = $luokkaDefault;
}


if (isset($_GET["tila"])) {
  $tila = $_GET["tila"];
  echo "Luokkatilan n&auml;ytt&ouml;moodi ei viel&auml; tuettu.<br />\n";
  exit;

  $fp = @fopen($roomFile, "rb");
  if ($fp) {
    fclose($fp);
  }
}

  
function getHour($hour)
{
  return "<br />".($hour + 8).":15 - ".($hour + 9).":00<br /><br />";
}


function matchCourse($id)
{
  global $cache, $infoURI, $cacheDirty;

  // Check if course exists in cache
  if (!isset($cache[$id])) {
    $cacheDirty = TRUE;
    // Not cached, try to fetch data
    $data = @file_get_contents($infoURI.$id);
    if ($data !== FALSE) {
      if (preg_match("#<td class=\"smallheadercell\"><strong>(.+?)\s+(\d+)\s*op\s*</strong></td>#", $data, $m)) {
        // Add data to cache
        $cache[$id] = array("desc" => $m[1], "op" => intval($m[2]));
      }
    }
  }
  
  if (isset($cache[$id]))
    return "<a target=\"_blank\" title=\"".htmlentities($id." - ".$cache[$id]["op"]." op").
    "\" href=\"".htmlentities($infoURI.$id)."\">".htmlentities($cache[$id]["desc"])."</a>";
  else
    return htmlentities($id);
}


function matchClass($matches)
{
  global $baseURI;
  return "<b><a href=\"".$baseURI."?tila=".$matches[1]."\">".$matches[1]."</a></b> ".$matches[2];
}


// Global cache for course data
$cache = array();
$cacheDirty = FALSE;


// Try to read cachefile, if we can get file lock on it
$fp = @fopen($cacheFile, "rb");
if ($fp) {
  if (flock($fp, LOCK_SH)) { 
    require($cacheFile);
    flock($fp, LOCK_UN);
  }
  fclose($fp);
}

$fp = @fopen($classFile, "rb");
$classes = array();
if ($fp) {
  if (flock($fp, LOCK_SH)) { 
    while (!feof($fp)) {
      $str = trim(fgets($fp, 128));
      if ($str[0] != "#" && strlen($str) > 2)
        $classes[] = $str;
    }
    flock($fp, LOCK_UN);
  }
  fclose($fp);
}


if (!file_exists($dataDir.$luokka.".data")) {
  errorMsg("Luokan ".htmlentities($luokka)." datatiedostoa ei löytynyt!");
  $haveData = FALSE;
} else {
  require($dataDir.$luokka.".data");
  $haveData = isset($classDefs);
}


function printHourInfo($dayHours, $showDays)
{
  $out = " <tr>\n  <td>Tunteja (<b>ryhmä</b>)</td>\n";
  for ($day = 0; $day < $showDays; $day++) {
    $out .=  "  <td>".$dayHours[$day]["total"]."h (<b>".$dayHours[$day]["grouped"]."h</b>)</td>\n";
  }
  return $out." </tr>\n";
}


if ($haveData) {
  $totalHours = 0;
  $totalGrouped = 0;
  $dayHours = array();

  for ($day = 0; $day < $classInfo["maxdays"]; $day++) 
    $dayHours[$day]["total"] = $dayHours[$day]["grouped"] = 0;

  foreach ($classDefs as $id => $data) {
    $h = $data["hours"];
  
    $totalHours += $h;
    $dayHours[$data["day"]]["total"] += $h;

    if (!$data["grouped"]) {
      $totalGrouped += $h;
      $dayHours[$data["day"]]["grouped"] += $h;
    }
  }

  // Create the timetable table
  $out =
  "<p>".join("; ", $classInfo["general"])."</p>\n".
  "<table class=\"timetable\">".
  " <tr>\n  <th></th>\n";
  for ($day = 0; $day < $classInfo["maxdays"]; $day++) {
    $out .=  "  <th class=\"days\">".$dayNames[$day]."</th>\n";
  }
  $out .= " </tr>\n";

for ($hour = 0; $hour < $classInfo["maxhours"]; $hour++) {
  $out .= " <tr>\n".
  "  <th class=\"hours\">".getHour($hour)."</th>\n";
  for ($day = 0; $day < $classInfo["maxdays"]; $day++) {
    if (isset($classHourTable[$hour][$day])) {
      $h = $classHourTable[$hour][$day];
        
      if ($h < 1) {
        if ($h > -9999) {
          $n = 0;
          for ($i = $hour; $i < $classInfo["maxhours"]; $i++)
          if ($classHourTable[$i][$day] == $h) {
            $classHourTable[$i][$day] = -9999;
            $n++;
          } else
            break;
          $out .= "  <td rowspan=\"".$n."\" class=\"clnothing\"></td>\n";
        }
      } else
      if (isset($classDefs[$h])) {
        if (!isset($classDefs[$h]["done"])) {
          $classDefs[$h]["done"] = true;
          $i = $classDefs[$h];
          $d = $classDefs[$h]["data"];
          
          $isSplit = preg_match("/^[A-Z]\d{6}$/", $d[1]);
          
          $out .= "  <td rowspan=\"".$i["hours"].
          "\" class=\"".($isSplit || $i["grouped"] ? "clgrouped" : "clnormal")."\">";
          
          if ($isSplit) {
            $out .= "<table>".
            "<tr><td>".matchCourse($d[0])."</td><td>".matchCourse($d[1])."</td></tr>";
            for ($j = 2; $j < count($d); $j += 2)
              $out .= "<tr><td>".htmlentities($d[$j])."</td><td>".(isset($d[$j+1]) ? htmlentities($d[$j+1]) : "")."</td></tr>";
            $out .= "</table>";
          } else {
            $out .= matchCourse($d[0])."<br />";
            for ($j = 1; $j < count($d); $j++)
              $out .= htmlentities($d[$j])."<br />";
          }
          $out .= "<div class=\"nhours\"><span>".$i["hours"]."h</span></div></td>\n";
        }
      } else
        errorMsg("Internal error cell $hour / $day : hour id $h does not exist!");
    } else
      errorMsg("Internal error, cell $hour / $day does not exist.");
  }
  $out .= " </tr>\n";
}

  $out .= printHourInfo($dayHours, $classInfo["maxdays"]).
  "</table>";

} // haveData


$pageTitle = $haveData ? $luokka." / ".join("; ", $classInfo["info"]) : $luokka;
printPageHeader($pageTitle);
echo "<h1>".$pageTitle."</h1>\n";

echo "<form action=\"".$baseURI."\" method=\"get\">\n".
" <select name=\"luokka\">\n";

foreach ($classes as $class) {
  echo "  <option value=\"".$class."\">".htmlentities($class)."</option>\n";
}
echo " </select>\n <input type=\"submit\" value=\" Vaihda \" />\n</form>\n";

// Show error messages
if ($errorSet) {
  echo "<ul>\n";
  foreach ($errorMsgs as $msg)
    echo "<li>$msg</li>\n";
  echo "</ul>\n";
}

echo $out;

printPageFooter();


// Dump the course data cache, but only if it has changed
if ($cacheDirty) {
  // First try append mode
  $fp = @fopen($cacheFile, "rb+");

  // If file didn't exist, try write mode
  if (!$fp)
    $fp = @fopen($cacheFile, "wb");

  if ($fp) {
    // Use locking to prevent concurrent access and dump data
    if (flock($fp, LOCK_EX)) {
      ftruncate($fp, 0);
      fwrite($fp, "<?\n\$cache = array(\n");
      foreach ($cache as $id => $data) {
        fwrite($fp, "  \"".addslashes($id)."\" => array(\"desc\" => \"".
        addslashes($data["desc"])."\", \"op\" => ".$data["op"]."),\n");
      }
      fwrite($fp, ");\n?>");
    }
    fclose($fp);
  }
}

?>