Code-Modernisierungen für PHP-8-Kompatibilität.

Zusätzlich Charsets, Linebreaks und Kommentar-Blöcke korrigiert.
This commit is contained in:
Kai Blaschke 2023-01-24 15:12:37 +01:00
parent 4afbdaf52b
commit 7b28fea35c
No known key found for this signature in database
GPG Key ID: B014B6811527389F
13 changed files with 1934 additions and 1810 deletions

View File

@ -8,7 +8,7 @@
* of the * of the
* *
* Bundesanstalt Technisches Hilfswerk * Bundesanstalt Technisches Hilfswerk
* Provinzialstra<EFBFBD>e 93 * Provinzialstraße 93
* D-53127 Bonn * D-53127 Bonn
* Germany * Germany
* E-Mail: redaktion@thw.de * E-Mail: redaktion@thw.de
@ -30,12 +30,12 @@
/* /*
Aufl<EFBFBD>sungen zu allen Fragen Auflösungen zu allen Fragen
*/ */
$tpl->addVars('navAntworten', 'current'); $GLOBALS['tpl']->addVars('navAntworten', 'current');
$katalog = -1; $katalog = -1;
if (isset($_REQUEST['katalog'])) { if (isset($_REQUEST['katalog'])) {
@ -44,13 +44,13 @@ if (isset($_REQUEST['katalog'])) {
$abschnitte = getTopics(); $abschnitte = getTopics();
foreach ($abschnitte as $nr => $description) { foreach ($abschnitte as $nr => $description) {
$tpl->addVars(Array( $GLOBALS['tpl']->addVars(array(
'abschnittNr' => $nr, 'abschnittNr' => $nr,
'abschnittName' => htmlspecialchars($description), 'abschnittName' => htmlspecialchars($description),
'navAntwortenAbschnitt' => ($katalog == $nr) ? 'current':'' 'navAntwortenAbschnitt' => ($katalog == $nr) ? 'current' : ''
)); ));
$tpl->parseBlock('page-body', 'NavAntworten', 'Sublinks', TRUE); $GLOBALS['tpl']->parseBlock('page-body', 'NavAntworten', 'Sublinks', TRUE);
} }
if (isset($_SESSION['zufallsfragen']) || isset($_SESSION['bogen'])) { if (isset($_SESSION['zufallsfragen']) || isset($_SESSION['bogen'])) {
@ -61,9 +61,8 @@ if (isset($_SESSION['zufallsfragen']) || isset($_SESSION['bogen'])) {
unset($_SESSION['fragen_cnt']); unset($_SESSION['fragen_cnt']);
unset($_SESSION['zufallstats']); unset($_SESSION['zufallstats']);
unset($_SESSION['bogen']); unset($_SESSION['bogen']);
} } else {
else { $GLOBALS['tpl']->addTemplates(array('content' => 'aufloesung-error'));
$tpl->addTemplates(Array('content' => 'aufloesung-error'));
return; return;
} }
} }
@ -78,20 +77,20 @@ if ($katalog > 0) {
$stmt->bind_result($selectedNr, $selectedDescription); $stmt->bind_result($selectedNr, $selectedDescription);
$stmt->fetch(); $stmt->fetch();
addBreadcrumb($_REQUEST['show'].'&katalog=' . $selectedNr, $selectedDescription); addBreadcrumb($_REQUEST['show'] . '&katalog=' . $selectedNr, $selectedDescription);
$tpl->addTemplates(Array( $GLOBALS['tpl']->addTemplates(array(
'content' => 'aufloesung-antworten' 'content' => 'aufloesung-antworten'
)); ));
$tpl->addVars(Array( $GLOBALS['tpl']->addVars(array(
'abschnittNr' => $selectedNr, 'abschnittNr' => $selectedNr,
'abschnittName' => htmlspecialchars($selectedDescription) 'abschnittName' => htmlspecialchars($selectedDescription)
)); ));
$stmt->close(); $stmt->close();
$stmt = $GLOBALS['db']->prepare('SELECT * FROM `fragen` WHERE `Abschnitt` = ? AND `Jahr` = ? ORDER BY Abschnitt,Nr ASC'); $stmt = $GLOBALS['db']->prepare('SELECT * FROM `fragen` WHERE `Abschnitt` = ? AND `Jahr` = ? ORDER BY Abschnitt,Nr');
$stmt->bind_param('ii', $katalog, $_SESSION['jahr']); $stmt->bind_param('ii', $katalog, $_SESSION['jahr']);
$stmt->execute(); $stmt->execute();
$questions = $stmt->get_result(); $questions = $stmt->get_result();
@ -100,32 +99,34 @@ if ($katalog > 0) {
while ($question = $questions->fetch_array(MYSQLI_ASSOC)) { while ($question = $questions->fetch_array(MYSQLI_ASSOC)) {
ShowAnswer($question); ShowAnswer($question);
$tpl->parseBlock('content', 'Antworten', 'Row', TRUE, TRUE); $GLOBALS['tpl']->parseBlock('content', 'Antworten', 'Row', TRUE, TRUE);
if ($I%10==0) { if ($I % 10 == 0) {
$tpl->parseBlock('content', 'Antworten', 'Topline', TRUE); $GLOBALS['tpl']->parseBlock('content', 'Antworten', 'Topline', TRUE);
} }
$I++; $I++;
} }
$questions->close(); $questions->close();
$stmt->close(); $stmt->close();
} } else {
else {
$tpl->addTemplates('content', 'aufloesung-abschnitte'); $GLOBALS['tpl']->addTemplates('content', 'aufloesung-abschnitte');
$stmt = $GLOBALS['db']->prepare('SELECT `Nr`,`Beschreibung` FROM `abschnitte` WHERE `Jahr` = ? ORDER BY Nr ASC'); $nr = 0;
$description = '';
$stmt = $GLOBALS['db']->prepare('SELECT `Nr`,`Beschreibung` FROM `abschnitte` WHERE `Jahr` = ? ORDER BY Nr');
$stmt->bind_param('i', $_SESSION['jahr']); $stmt->bind_param('i', $_SESSION['jahr']);
$stmt->execute(); $stmt->execute();
$stmt->bind_result($nr, $description); $stmt->bind_result($nr, $description);
while ($stmt->fetch()) { while ($stmt->fetch()) {
$tpl->addVars(Array( $GLOBALS['tpl']->addVars(array(
'abschnittNr' => $nr, 'abschnittNr' => $nr,
'abschnittName' => $description 'abschnittName' => $description
)); ));
$tpl->parseBlock('content', 'Abschnitte', 'Row', TRUE); $GLOBALS['tpl']->parseBlock('content', 'Abschnitte', 'Row', TRUE);
} }
} }
?>

View File

@ -1,15 +1,12 @@
<?php <?php
if (isset($_POST['normal'])) { if (isset($_POST['normal'])) {
setcookie("stylesheet", "normal", time()+60*60*24*365); setcookie("stylesheet", "normal", time()+60*60*24*365);
$tpl->addVars('extraStyleSheet', ''); $GLOBALS['tpl']->addVars('extraStyleSheet', '');
} }
if (isset($_POST['barrierefrei'])) { if (isset($_POST['barrierefrei'])) {
setcookie("stylesheet", "barrierefrei", time()+60*60*24*365); setcookie("stylesheet", "barrierefrei", time()+60*60*24*365);
} }
$tpl->addTemplates(Array("content" => "barrierefreiheit")); $GLOBALS['tpl']->addTemplates(Array("content" => "barrierefreiheit"));
?>

View File

@ -8,7 +8,7 @@
* of the * of the
* *
* Bundesanstalt Technisches Hilfswerk * Bundesanstalt Technisches Hilfswerk
* Provinzialstraße 93 * Provinzialstraße 93
* D-53127 Bonn * D-53127 Bonn
* Germany * Germany
* E-Mail: redaktion@thw.de * E-Mail: redaktion@thw.de
@ -29,523 +29,633 @@
*/ */
/************************************************************ /************************************************************
* Template class * Template class
* *
* This class is capable of replacing variables with text, * This class is capable of replacing variables with text,
* including other templates, and it can parse dynamic blocks * including other templates, and it can parse dynamic blocks
* which can be nested inside other blocks. * which can be nested inside other blocks.
* *
* Predefined variables: * Predefined template variables:
* *
* {templatePath} Contains the template path * - {templatePath} Contains the template path
* {templateLang} Contains the country code, if set * - {templateLang} Contains the country code, if set
* *
* If you don't need them, remove them immediately after * If you don't need them, remove them immediately after
* creating the class instance or setting a new template path. * creating the class instance or setting a new template path.
* *
* $id: class Template v1.0 / Kai Blaschke $ **************************************************************/
* class Template
**************************************************************/ {
/**
* @var array Contains all template filenames
*/
private array $templateFiles = array();
/**
* @var array Contains all template data
*/
private array $templateData = array();
class Template { /**
* @var array Already loaded templates.
*/
private array $loadedTemplates = array();
// ************************************************************ /**
// Member variables * @var array Array of variable/value pairs stored as $LOADED[HANDLE]=>true
*/
private array $parserVariables = array();
var $TPLFILES = array(); // Contains all template filenames /**
var $TPLDATA = array(); // Contains all template data * @var array Handles which contain parsed templates to be replaced in templates
var $LOADED = array(); // Already loaded templates are */
// stored as $LOADED[HANDLE]=>TRUE private array $templateHandles = array();
var $PARSEVARS = array(); // Array of variable/value pairs
// to be replaced in templates
var $HANDLES = array(); // Handles which contain parsed templates
var $BLOCKS = array(); // Array with dynamic block data /**
var $H_BLOCKS = array(); // Parsed block data * @var array Array with dynamic block data
*/
private array $templateBlocks = array();
// Filename: $TPLDIR/filename[.$LANG].tpl /**
var $TPLDIR; // Path to template files * @var array Parsed block data
var $LANG; // Country code (en, de, fr, ...) */
var $TPLEXT; // Filename extension (default is .tpl) private array $parsedBlocks = array();
/**
* @var string Path to template files. Filename: $templateDirectory/filename[.$languageCode].tpl
*/
private string $templateDirectory;
// ************************************************************ /**
// Global settings * @var string Country code (en, de, fr, ...)
*/
private string $languageCode;
var $RPLBRACES = TRUE; // Safely replaces curly braces with HTML /**
// entities in variable values if * @var string Filename extension (default is .tpl)
// set to TRUE. */
var $WIN32 = FALSE; // Set to "TRUE" on Win32 systems, if private string $templateExtension;
// you encounter problems with paths.
var $DIEONERR = TRUE; // If set to TRUE, die() is called in error
/**
* @var bool Safely replaces curly braces with HTML entities in variable values if set to true.
*/
public bool $replaceBraces = true;
/**
* @var bool Set to "true" on Windows systems, if you encounter problems with paths.
*/
public bool $useWindowsPathSeparator = false;
/**
* @var bool If set to true, die() is called in error
*/
public bool $dieOnError = true;
// ************************************************************ /**
// Constructor * constructor.
* @param string $tpldir The template base directory.
function Template($tpldir, $lang = "", $tplext = "tpl") * @param string $lang The browser language code.
* @param string $tplext Optional. The template file extension.
*/
function __construct(string $tpldir,
string $lang = "",
string $tplext = "tpl")
{ {
$this->setPath($tpldir); $this->setPath($tpldir);
$this->LANG = strtolower($lang); $this->languageCode = strtolower($lang);
$this->TPLEXT = $tplext; $this->templateExtension = $tplext;
$this->addVars("templateLang", $this->LANG); $this->addVars("templateLang", $this->languageCode);
} }
// ************************************************************ /**
// Sets or changes the template search path * Sets or changes the template search path
* @param string $path New template base directory.
function setPath($path) * @return bool true if the path was set correctly, false if an error occurred.
*/
function setPath(string $path): bool
{ {
if ($this->WIN32) { if ($this->useWindowsPathSeparator) {
if (ord(substr($path, -1)) != 92) $path .= chr(92); if (ord(substr($path, -1)) != 92) {
$path .= chr(92);
}
} else { } else {
if (ord(substr($path, -1)) != 47) $path .= chr(47); if (ord(substr($path, -1)) != 47) {
$path .= chr(47);
}
} }
if (is_dir($path)) { if (is_dir($path)) {
$this->TPLDIR = $path; $this->templateDirectory = $path;
// Add a path variable for use in templates // Add a path variable for use in templates
$this->addVars("templatePath", $path); $this->addVars("templatePath", $path);
return TRUE; return true;
} else { } else {
echo "[TEMPLATE ENGINE] The specified template path " echo "[TEMPLATE ENGINE] The specified template path "
."'<b>".$path."</b>' is invalid!<br />"; . "'<b>" . $path . "</b>' is invalid!<br />";
$this->TPLDIR = ""; $this->templateDirectory = "";
if ($this->DIEONERR == TRUE) die(); if ($this->dieOnError) {
return FALSE; die();
}
return false;
} }
} }
// ************************************************************ /**
// Get dynamic blocks recursively to enable nested blocks * Get dynamic blocks recursively to enable nested blocks.
* @param string $tplFilename Template base filename.
function getDynamicBlocks($tplFilename, $contents) * @param string $contents Content to search for dynamic blocks.
* @return void
*/
function getDynamicBlocks(string $tplFilename,
string $contents): void
{ {
preg_match_all("/(\{\|([a-zA-Z0-9]+)\})(.*?)\\1/s", preg_match_all("/(\{\|([a-zA-Z0-9]+)})(.*?)\\1/s", $contents, $blocks);
$contents, $blocks);
if (empty($blocks[0])) return; if (empty($blocks[0])) {
return;
}
// Go through all blocks and save them in $this->BLOCKS // Go through all blocks and save them in $this->BLOCKS
for ($I=0; $I<count($blocks[0]); $I++) { for ($I = 0; $I < count($blocks[0]); $I++) {
$blockparts = array(); $blockparts = array();
preg_match_all("/(\{\|" . $blocks[2][$I] .
"\*([a-zA-Z0-9]+)\})(.*?)\\1/s",
$blocks[3][$I], $blockparts);
for ($J=0; $J<count($blockparts[0]); $J++) { preg_match_all("/(\{\|" . $blocks[2][$I] . "\*([a-zA-Z0-9]+)})(.*?)\\1/s", $blocks[3][$I], $blockparts);
for ($J = 0; $J < count($blockparts[0]); $J++) {
// Get nested blocks // Get nested blocks
$this->getDynamicBlocks($tplFilename, $blockparts[3][$J]); $this->getDynamicBlocks($tplFilename, $blockparts[3][$J]);
// Replace block data with placeholders // Replace block data with placeholders
$blockparts[3][$J] = $blockparts[3][$J] = preg_replace("/(\{\|([a-zA-Z0-9]+)})(.*?)\\1/s", "\\1", $blockparts[3][$J]);
preg_replace("/(\{\|([a-zA-Z0-9]+)\})(.*?)\\1/s",
"\\1", $blockparts[3][$J]);
// Save block data // Save block data
$this->BLOCKS[$tplFilename][$blocks[2][$I]][$blockparts[2][$J]] $this->templateBlocks[$tplFilename][$blocks[2][$I]][$blockparts[2][$J]] = $blockparts[3][$J];
= $blockparts[3][$J];
} }
} }
} }
// ************************************************************ /**
// Loads a template, runs some checks and extracts dynamic blocks * Loads a template, runs some checks and extracts dynamic blocks.
* @param string $tplFilename Template base filename.
function loadTemplate($tplFilename) * @return bool true if the template is loaded, false if an error occurred.
*/
function loadTemplate(string $tplFilename): bool
{ {
// Template already loaded? // Template already loaded?
if (isset($this->LOADED[$tplFilename])) return TRUE; if (isset($this->loadedTemplates[$tplFilename])) {
return true;
}
// Has the path been set? // Has the path been set?
if (empty($this->TPLDIR)) { if (empty($this->templateDirectory)) {
echo "[TEMPLATE ENGINE] Template path not set or invalid!<br />"; echo "[TEMPLATE ENGINE] Template path not set or invalid!<br />";
if ($this->DIEONERR == TRUE) die(); if ($this->dieOnError) {
return FALSE; die();
}
return false;
} }
// Is a user-defined county code set? // Is a user-defined county code set?
if (!empty($this->LANG)) { if (!empty($this->languageCode)) {
// Yes. Try to find template with the specified CC // Yes. Try to find template with the specified CC
if (file_exists($this->TPLDIR.$this->TPLFILES[$tplFilename]."." if (file_exists($this->templateDirectory . $this->templateFiles[$tplFilename] . "." . $this->languageCode . "." . $this->templateExtension)) {
.$this->LANG.".".$this->TPLEXT)) { $filename = $this->templateDirectory . $this->templateFiles[$tplFilename] . "." . $this->languageCode . "." . $this->templateExtension;
$filename = $this->TPLDIR.$this->TPLFILES[$tplFilename].".".
$this->LANG.".".$this->TPLEXT;
} else { } else {
// Otherwise, use template filename without CC // Otherwise, use template filename without CC
if (file_exists($this->TPLDIR.$this->TPLFILES[$tplFilename]."." if (file_exists($this->templateDirectory . $this->templateFiles[$tplFilename] . "." . $this->templateExtension)) {
.$this->TPLEXT)) { $filename = $this->templateDirectory . $this->templateFiles[$tplFilename] . "."
$filename = $this->TPLDIR.$this->TPLFILES[$tplFilename]."." . $this->templateExtension;
.$this->TPLEXT;
} else { } else {
echo "[TEMPLATE ENGINE] Can't find template " echo "[TEMPLATE ENGINE] Can't find template " . "'" . $tplFilename . "'!<br />";
."'".$tplFilename."'!<br />";
if ($this->DIEONERR == TRUE) die(); if ($this->dieOnError) {
return FALSE; die();
}
return false;
} }
} }
} else { } else {
// No. Use template filename without CC // No. Use template filename without CC
if (file_exists($this->TPLDIR.$this->TPLFILES[$tplFilename]."." if (file_exists($this->templateDirectory . $this->templateFiles[$tplFilename] . "." . $this->templateExtension)) {
.$this->TPLEXT)) { $filename = $this->templateDirectory . $this->templateFiles[$tplFilename] . "." . $this->templateExtension;
$filename = $this->TPLDIR.$this->TPLFILES[$tplFilename]."."
.$this->TPLEXT;
} else { } else {
echo "[TEMPLATE ENGINE] Can't find template " echo "[TEMPLATE ENGINE] Can't find template " . "'" . $tplFilename . "'!<br />";
."'".$tplFilename."'!<br />";
if ($this->DIEONERR == TRUE) die(); if ($this->dieOnError) {
return FALSE; die();
}
return false;
} }
} }
// Load template file // Load template file
$contents = implode("", (@file($filename))); $contents = implode("", (@file($filename)));
if (!$contents || empty($contents)) { if (empty($contents)) {
echo "[TEMPLATE ENGINE] Can't load template '" echo "[TEMPLATE ENGINE] Can't load template '" . $tplFilename . "'!<br />";
.$tplFilename."'!<br />";
if ($this->DIEONERR == TRUE) die(); if ($this->dieOnError) {
return FALSE; die();
}
return false;
} }
// Parse dynamic blocks recursively // Parse dynamic blocks recursively
$this->getDynamicBlocks($tplFilename, $contents); $this->getDynamicBlocks($tplFilename, $contents);
// Replace all block data with placeholders // Replace all block data with placeholders
$contents = preg_replace("/(\{\|([a-zA-Z0-9]+)\})(.*?)\\1/s", "\\1", $contents = preg_replace("/(\{\|([a-zA-Z0-9]+)})(.*?)\\1/s", "\\1", $contents);
$contents);
$this->TPLDATA[$tplFilename] = $contents; $this->templateData[$tplFilename] = $contents;
$this->LOADED[$tplFilename] = 1; $this->loadedTemplates[$tplFilename] = 1;
return TRUE; return true;
} }
// ************************************************************ /**
// Parses a template and loads it if neccessary. * Parses a template and loads it if necessary.
// The result is assigned or concatenated to the specified handle. * The result is assigned or concatenated to the specified handle.
* @param string $handle Result handle to store the parsed template in.
function parse($handle = "", * @param string $file Template file to parse.
$file = "", * @param bool $append true to append the parsed template to the given handle, false replaces the contents.
$append = FALSE, * @param bool $delunused true to delete unused variable placeholders, false to keep them for later processing.
$delunused = FALSE) * @return bool true if the file was parsed correctly, false if an error occurred.
*/
function parse(string $handle = "",
string $file = "",
bool $append = false,
bool $delunused = false): bool
{ {
// Check if all prerequisites are met // Check if all prerequisites are met
if (empty($handle) || empty($file)) if (empty($handle) || empty($file)) {
return FALSE; return false;
}
if (!isset($this->TPLFILES[$file])) if (!isset($this->templateFiles[$file])) {
return FALSE; return false;
}
if (!isset($this->LOADED[$file])&&!$this->loadTemplate($file)) if (!isset($this->loadedTemplates[$file]) && !$this->loadTemplate($file)) {
return FALSE; return false;
}
$templateCopy = $this->TPLDATA[$file]; $templateCopy = $this->templateData[$file];
// Reset array pointers // Reset array pointers
reset($this->HANDLES); reset($this->templateHandles);
reset($this->PARSEVARS); reset($this->parserVariables);
// Replace blocks // Replace blocks
if (isset($this->H_BLOCKS[$file])) { if (isset($this->parsedBlocks[$file])) {
reset($this->H_BLOCKS[$file]); reset($this->parsedBlocks[$file]);
while (list($varname, $value) = each($this->H_BLOCKS[$file])) foreach ($this->parsedBlocks[$file] as $varname => $value) {
$templateCopy = preg_replace("/\{\|".$varname."\}/i", $templateCopy = preg_replace("/\{\|" . $varname . "}/i",
$value, $templateCopy); $value, $templateCopy);
} }
}
// Replace variables // Replace variables
while (list($varname, $value) = each($this->PARSEVARS)) foreach ($this->parserVariables as $varname => $value) {
$templateCopy = preg_replace("/\{".$varname."\}/i", $templateCopy = preg_replace("/\{" . $varname . "}/i",
$value, $templateCopy); $value, $templateCopy);
}
// Replace {~name} placeholders with already parsed handle of // Replace {~name} placeholders with already parsed handle of
// the same name // the same name
while (list($varname, $value) = each($this->HANDLES)) foreach ($this->templateHandles as $varname => $value) {
$templateCopy = preg_replace("/\{\~".$varname."\}/i", $templateCopy = preg_replace("/\{~" . $varname . "}/i",
$value, $templateCopy); $value, $templateCopy);
}
// Delete unused variables and placeholders // Delete unused variables and placeholders
if ($delunused) if ($delunused) {
$templateCopy = preg_replace("/\{[~|\|]?(\w*?)\}/", "", $templateCopy = preg_replace("/\{[~|]?(\w*?)}/", "", $templateCopy);
$templateCopy); }
// Assign to handle // Assign to handle
if ($append && isset($this->HANDLES[$handle])) { if ($append && isset($this->templateHandles[$handle])) {
$this->HANDLES[$handle] .= $templateCopy; $this->templateHandles[$handle] .= $templateCopy;
} else { } else {
$this->HANDLES[$handle] = $templateCopy; $this->templateHandles[$handle] = $templateCopy;
} }
return TRUE; return true;
} }
// ************************************************************
// Parses multiple templates.
// $list is an associative array of the type "handle"=>"template".
// Note that concatenation is not possible. Use the parse() method instead.
function multiParse($list) /**
* Parses multiple templates.
*
* $list is an associative array of the type "handle"=>"template".
* Note that concatenation is not possible. Use the parse() method instead.
* @param array $list Associative array with handles as key and files as values.
* @return bool true if all templates were parsed correctly, false if an error occurred.
*/
function multiParse(array $list): bool
{ {
if (!is_array($list)) return FALSE; foreach ($list as $handle => $file) {
if (!$this->parse($handle, $file)) return false;
while (list($handle, $file) = each($list))
if (!$this->parse($handle, $file)) return FALSE;
return TRUE;
} }
// ************************************************************ return true;
// Parses a template and prints the result. }
function printParse($handle = "", $file = "", $append = FALSE) /**
* Parses a template and prints the result.
* @param string $handle Result handle to store the parsed template in.
* @param string $file Template base filename to parse.
* @param bool $append true to append the parsed template to the given handle, false replaces the contents.
* @return bool true if the template was parsed correctly, false if an error occurred.
*/
function printParse(string $handle = "",
string $file = "",
bool $append = false): bool
{ {
if ($this->parse($handle, $file, $append)) { if ($this->parse($handle, $file, $append)) {
$this->printHandle($handle); $this->printHandle($handle);
return TRUE; return true;
} }
return FALSE; return false;
} }
// ************************************************************ /**
// Parses a block and replaces or appends the result to the block handle. * Parses a block and replaces or appends the result to the block handle.
// *
// Note: First argument is the template file name containing the blocks, * Note: First argument is the template file name containing the blocks,
// not a handle name! * not a handle name!
// *
// Note: This function has no effect on any template handle. * Note: This function has no effect on any template handle.
// Parsed block data is inserted into the template handle in the * Parsed block data is inserted into the template handle in the
// parse() method. * parse() method.
* @param string $file Template base filename to parse.
function parseBlock($file = "", * @param string $block Block name to parse.
$block = "", * @param string $blockpart Block part to parse.
$blockpart = "", * @param bool $append true appends the parsed data to the block contents, false replaces it.
$append = FALSE, * @param bool $delunused true removes unused variable placeholders, false keeps them for later processing.
$delunused = FALSE) * @return bool true if the bock was parsed successfully, false if an error occurred.
*/
function parseBlock(string $file = "",
string $block = "",
string $blockpart = "",
bool $append = false,
bool $delunused = false): bool
{ {
if (empty($file) || empty($block) || empty($blockpart)) if (empty($file) || empty($block) || empty($blockpart))
return FALSE; return false;
if (!isset($this->TPLFILES[$file])) if (!isset($this->templateFiles[$file]))
return FALSE; return false;
if (!isset($this->LOADED[$file])&&!$this->loadTemplate($file)) if (!isset($this->loadedTemplates[$file]) && !$this->loadTemplate($file))
return FALSE; return false;
$blockCopy = $this->BLOCKS[$file][$block][$blockpart]; $blockCopy = $this->templateBlocks[$file][$block][$blockpart];
// Reset array pointers // Reset array pointers
reset($this->H_BLOCKS); reset($this->parsedBlocks);
reset($this->PARSEVARS); reset($this->parserVariables);
// Replace blocks // Replace blocks
if (isset($this->H_BLOCKS[$file])) { if (isset($this->parsedBlocks[$file])) {
reset($this->H_BLOCKS[$file]); reset($this->parsedBlocks[$file]);
while (list($varname, $value) = each($this->H_BLOCKS[$file])) foreach ($this->parsedBlocks[$file] as $varname => $value) {
$blockCopy = preg_replace("/\{\|".$varname."\}/i", $blockCopy = preg_replace("/\{\|" . $varname . "}/i",
$value, $blockCopy); $value, $blockCopy);
} }
}
// Replace variables // Replace variables
while (list($varname, $value) = each($this->PARSEVARS)) foreach ($this->parserVariables as $varname => $value) {
$blockCopy = preg_replace("/\{".$varname."\}/i", $blockCopy = preg_replace("/\{" . $varname . "}/i",
$value, $blockCopy); $value, $blockCopy);
}
// Replace {~name} placeholders with already parsed handle of // Replace {~name} placeholders with already parsed handle of
// the same name // the same name
while (list($varname, $value) = each($this->HANDLES)) foreach ($this->templateHandles as $varname => $value) {
$blockCopy = preg_replace("/\{\~".$varname."\}/i", $blockCopy = preg_replace("/\{~" . $varname . "}/i",
$value, $blockCopy); $value, $blockCopy);
}
// Delete unused variables and placeholders // Delete unused variables and placeholders
if ($delunused) if ($delunused) {
$blockCopy = preg_replace("/\{[~|]?(\w*?)\}/", "", $blockCopy); $blockCopy = preg_replace("/\{[~|]?(\w*?)}/", "", $blockCopy);
}
// Assign to handle // Assign to handle
if ($append && isset($this->H_BLOCKS[$file][$block])) { if ($append && isset($this->parsedBlocks[$file][$block])) {
$this->H_BLOCKS[$file][$block] .= $blockCopy; $this->parsedBlocks[$file][$block] .= $blockCopy;
} else { } else {
$this->H_BLOCKS[$file][$block] = $blockCopy; $this->parsedBlocks[$file][$block] = $blockCopy;
} }
return TRUE; return true;
} }
// ************************************************************ /**
// Deletes all block handles * Deletes all block handles.
* @return void
function clearBlockHandles() */
function clearBlockHandles(): void
{ {
if (!empty($this->H_BLOCKS)) { if (!empty($this->parsedBlocks)) {
reset($this->H_BLOCKS); reset($this->parsedBlocks);
while (list($ref, $val) = each($this->H_BLOCKS)) foreach ($this->parsedBlocks as $ref => $val) {
unset($this->H_BLOCKS[$ref]); unset($this->parsedBlocks[$ref]);
}
} }
} }
// ************************************************************ /**
// Deletes the specified block handle * Deletes the specified block handle
* @param string $file The template base file the block is found ion.
function delBlockHandle($file, $block) * @param string $block The block name to delete.
* @return void
*/
function delBlockHandle(string $file,
string $block): void
{ {
if (!empty($file) && !empty($block)) if (!empty($file) && !empty($block)) {
if (isset($this->H_BLOCKS[$file][$block])) if (isset($this->parsedBlocks[$file][$block])) {
unset($this->H_BLOCKS[$file][$block]); unset($this->parsedBlocks[$file][$block]);
}
}
} }
// ************************************************************ /**
// Adds one or more templates * Adds one or more templates
// You can pass one associative array with $handle=>$filename pairs, * You can pass one associative array with $handle=>$filename pairs,
// or two strings ($handle, $filename) to this function. * or two strings ($handle, $filename) to this function.
* @param mixed $tplList A template handle or an associative array with template handles as keys and filenames as values.
function addTemplates($tplList, $tplFilename = "") * @param string $tplFilename A template base filename. Only used if $tplList is a single string.
* @return void
*/
function addTemplates(mixed $tplList,
string $tplFilename = ""): void
{ {
if (is_array($tplList)) { if (is_array($tplList)) {
reset($tplList); reset($tplList);
while (list($handle, $filename) = each($tplList)) { foreach ($tplList as $handle => $filename) {
// Add handle to list // Add handle to list
$this->TPLFILES[$handle] = $filename; $this->templateFiles[$handle] = $filename;
// Delete loaded flag if set // Delete loaded flag if set
unset($this->LOADED[$handle]); unset($this->loadedTemplates[$handle]);
} }
} else { } else {
$this->TPLFILES[$tplList] = $tplFilename; $this->templateFiles[$tplList] = $tplFilename;
unset($this->LOADED[$tplList]); unset($this->loadedTemplates[$tplList]);
} }
} }
// ************************************************************ /**
// Deletes all template handles * Deletes all template handles
* @return void
function clearHandles() */
function clearHandles(): void
{ {
if (!empty($this->HANDLES)) { if (!empty($this->templateHandles)) {
reset($this->HANDLES); reset($this->templateHandles);
while (list($ref, $val) = each($this->HANDLES)) foreach ($this->templateHandles as $ref => $val) {
unset($this->HANDLES[$ref]); unset($this->templateHandles[$ref]);
}
} }
} }
// ************************************************************ /**
// Deletes the specified template handle * Deletes the specified template handle
* @param string $handleName Template handle to delete.
function delHandle($handleName = "") * @return void
*/
function delHandle(string $handleName = ""): void
{ {
if (!empty($handleName)) if (!empty($handleName)) {
if (isset($this->HANDLES[$handleName])) if (isset($this->templateHandles[$handleName])) {
unset($this->HANDLES[$handleName]); unset($this->templateHandles[$handleName]);
}
}
} }
// ************************************************************ /**
// Returns the contents of the specified template handle * Returns the contents of the specified template handle.
* @param string $handleName The handle to return the contents for.
function getHandle($handleName = "") * @return bool|string false if the handle doesn't exist, or a string with the contents.
*/
function getHandle(string $handleName = ""): bool|string
{ {
if (empty($handleName)) if (empty($handleName))
return FALSE; return false;
if (isset($this->HANDLES[$handleName])) if (isset($this->templateHandles[$handleName]))
return $this->HANDLES[$handleName]; return $this->templateHandles[$handleName];
return FALSE; return false;
} }
// ************************************************************ /**
// Prints a parsed template handle * Prints a parsed template handle to the output stream.
* @param string $handleName The handle to print.
function printHandle($handleName = "") * @return bool false if the handle doesn't exist, true if the handle was printed.
*/
function printHandle(string $handleName = ""): bool
{ {
if (empty($handleName)) return FALSE; if (empty($handleName)) return false;
// Remove all remaining placeholders // Remove all remaining placeholders
$this->HANDLES[$handleName] = preg_replace("/\{[~|\|]?(\w*?)\}/", $this->templateHandles[$handleName] = preg_replace("/\{[~|]?(\w*?)}/",
"", $this->HANDLES[$handleName]); "", $this->templateHandles[$handleName]);
if (isset($this->HANDLES[$handleName])) { if (isset($this->templateHandles[$handleName])) {
echo $this->HANDLES[$handleName]; echo $this->templateHandles[$handleName];
return TRUE; return true;
} }
return FALSE; return false;
} }
// ************************************************************ /**
// Deletes all variables set with the addVars() method * Deletes all variables set with the addVars() method.
* @return void
function clearVars() */
function clearVars(): void
{ {
if (!empty($this->PARSEVARS)) { if (!empty($this->parserVariables)) {
reset($this->PARSEVARS); reset($this->parserVariables);
while (list($ref, $val) = each ($this->PARSEVARS)) foreach ($this->parserVariables as $ref => $val) {
unset($this->PARSEVARS[$ref]); unset($this->parserVariables[$ref]);
}
} }
} }
// ************************************************************ /**
// Adds one or more variables. * Adds one or more variables.
// You can pass one associative array with $varname=>$value pairs * You can pass one associative array with $varname=>$value pairs
// or two strings ($varname, $value) to this function. * or two strings ($varname, $value) to this function.
* @param mixed $varList Either an associative array with variable names as keys and values as values, or a string with the variable name.
function addVars($varList, $varValue = "") * @param string $varValue the value to insert for this variable. Only used if $varList is a string with the name of the variable.
* @return void
*/
function addVars(mixed $varList,
string $varValue = ""): void
{ {
if (is_array($varList)) { if (is_array($varList)) {
reset($varList); reset($varList);
while (list($varname, $value) = each($varList)) { foreach ($varList as $varname => $value) {
// Replace curly braces // Replace curly braces
if ($this->RPLBRACES == TRUE) { if ($this->replaceBraces == true) {
$value = preg_replace(Array("/(\{)/", "/(\})/"), $value = preg_replace(array("/(\{)/", "/(})/"),
Array("&#123;", "&#125;"), array("&#123;", "&#125;"),
$value); $value);
} }
// Add/replace variable // Add/replace variable
if (!preg_match("/[^0-9a-z\-\_]/i", $varname)) if (!preg_match("/[^0-9a-z\-_]/i", $varname))
$this->PARSEVARS[$varname] = $value; $this->parserVariables[$varname] = $value;
} }
} else { } else {
// Replace curly braces // Replace curly braces
if ($this->RPLBRACES == TRUE) { if ($this->replaceBraces == true) {
$varValue = preg_replace(Array("/(\{)/", "/(\})/"), $varValue = preg_replace(array("/(\{)/", "/(})/"),
Array("&#123;", "&#125;"), array("&#123;", "&#125;"),
$varValue); $varValue);
} }
// Add/replace variable // Add/replace variable
if (!preg_match("/[^0-9a-z\-\_]/i", $varList)) if (!preg_match("/[^0-9a-z\-_]/i", $varList))
$this->PARSEVARS[$varList] = $varValue; $this->parserVariables[$varList] = $varValue;
} }
} }
// ************************************************************ /**
// Returns a value set by the addVars() method * Returns a value set by the addVars() method.
* @param string $varName The variable to return the value of.
function getVar($varName = "") * @return bool|string false, if the variable didn't exist, or a string with the contents.
*/
function getVar(string $varName = ""): bool|string
{ {
if (empty($varName)) return FALSE; if (empty($varName)) {
if (isset($this->PARSEVARS[$varName])) return false;
return $this->PARSEVARS[$varName];
return FALSE;
} }
// ************************************************************ if (isset($this->parserVariables[$varName])) {
return $this->parserVariables[$varName];
}
} // End of class 'Template' return false;
}
?> }

2
db.php
View File

@ -50,6 +50,8 @@ function callBindParamArray($stmt, $bindArguments = null) {
} }
function getSingleResult($query, $bindArguments = null) { function getSingleResult($query, $bindArguments = null) {
$retVal = '';
$stmt = $GLOBALS['db']->prepare($query); $stmt = $GLOBALS['db']->prepare($query);
callBindParamArray($stmt, $bindArguments); callBindParamArray($stmt, $bindArguments);
$stmt->execute(); $stmt->execute();

View File

@ -8,7 +8,7 @@
* of the * of the
* *
* Bundesanstalt Technisches Hilfswerk * Bundesanstalt Technisches Hilfswerk
* Provinzialstraße 93 * Provinzialstraße 93
* D-53127 Bonn * D-53127 Bonn
* Germany * Germany
* E-Mail: redaktion@thw.de * E-Mail: redaktion@thw.de
@ -29,13 +29,12 @@
*/ */
/** /**
* Holt eine Einzelne Frage aus der DB * Holt eine einzelne Frage aus der Datenbank.
* * @param int $id Die Frage-ID
* @param $id Die Frage-ID * @return array Die Fragen-Inhalte als assoziatives Array.
*
* @return array Die Frage
*/ */
function getQuestionById($id) { function getQuestionById(int $id): array
{
$stmt = $GLOBALS['db']->prepare('SELECT * FROM fragen WHERE ID=?'); $stmt = $GLOBALS['db']->prepare('SELECT * FROM fragen WHERE ID=?');
$stmt->bind_param('i', $id); $stmt->bind_param('i', $id);
$stmt->execute(); $stmt->execute();
@ -48,11 +47,14 @@ function getQuestionById($id) {
/** /**
* Holt eine Liste aller Abschnitte im aktuellen Jahr * Holt eine Liste aller Abschnitte im aktuellen Jahr
* * @return array Liste der Themenbereiche.
* @return array
*/ */
function getTopics() { function getTopics(): array
$stmt = $GLOBALS['db']->prepare('SELECT `Nr`,`Beschreibung` FROM `abschnitte` WHERE `Jahr` = ? ORDER BY `Nr` ASC'); {
$nr = 0;
$description = '';
$stmt = $GLOBALS['db']->prepare('SELECT `Nr`,`Beschreibung` FROM `abschnitte` WHERE `Jahr` = ? ORDER BY `Nr`');
$stmt->bind_param('i', $_SESSION['jahr']); $stmt->bind_param('i', $_SESSION['jahr']);
$stmt->execute(); $stmt->execute();
$stmt->bind_result($nr, $description); $stmt->bind_result($nr, $description);
@ -66,13 +68,14 @@ function getTopics() {
return $topics; return $topics;
} }
/****************************************************************************** /**
* * Kopfzeile mit Informationen über Fragen-Nummer und Lernabschnitt.
* Kopfzeile mit Informationen über Fragennummer und Lernabschnitt * @param int $id Frage-ID
* * @param int $nr Frage-Nummer
/******************************************************************************/ * @param int $questionCount Anzahl Fragen
* @return void
function questionHeader($id, $nr, $questionCount) */
function questionHeader(int $id, int $nr, int $questionCount): void
{ {
$section = getSingleResult('SELECT Abschnitt FROM fragen WHERE ID=? AND Jahr=?', $section = getSingleResult('SELECT Abschnitt FROM fragen WHERE ID=? AND Jahr=?',
array('ii', $id, $_SESSION['jahr'])); array('ii', $id, $_SESSION['jahr']));
@ -90,27 +93,28 @@ function questionHeader($id, $nr, $questionCount)
$GLOBALS['tpl']->parseBlock('content', 'Kopf', 'Content'); $GLOBALS['tpl']->parseBlock('content', 'Kopf', 'Content');
} }
/****************************************************************************** /**
* * Eine einzelne Frage mit Kopfzeile ausgeben.
* Eine einzelne Frage mit Kopfzeile ausgeben * @param int $id Frage-ID
* * @param int $nr Frage-Nummer
/******************************************************************************/ * @param int $questionCount Anzahl Fragen
* @return void
function SingleQuestion($id, $Nr, $questionCount) */
function SingleQuestion(int $id, int $nr, int $questionCount): void
{ {
questionHeader($id, $Nr, $questionCount); questionHeader($id, $nr, $questionCount);
showQuestion($id); showQuestion($id);
} }
/****************************************************************************** /**
*
* Fragengenerator * Fragengenerator
* Erzeugt eine Tabelle mit Frage, Antworten und Formularinformationen
* zur übergebenen Fragen-ID
* *
/******************************************************************************/ * Erzeugt eine Tabelle mit Frage, Antworten und Formularinformationen
* zur übergebenen Fragen-ID
function showQuestion($id) * @param int $id Fragen-ID
* @return void
*/
function showQuestion(int $id): void
{ {
// Frage aus DB holen // Frage aus DB holen
$stmt = $GLOBALS['db']->prepare('SELECT * FROM fragen WHERE ID=?'); $stmt = $GLOBALS['db']->prepare('SELECT * FROM fragen WHERE ID=?');
@ -143,15 +147,17 @@ function showQuestion($id)
$stmt->close(); $stmt->close();
} }
/****************************************************************************** /**
*
* Auswertung * Auswertung
* Erzeugt eine Tabelle mit Frage, Antworten und Markiert richtige/falsche
* Antworten farblich (grün=richtig, rot=falsch)
* *
/******************************************************************************/ * Erzeugt eine Tabelle mit Frage, Antworten und Markiert richtige/falsche
* Antworten farblich (grün=richtig, rot=falsch)
function Answer($id, $answer, $showStatus = TRUE) * @param int $id Frage-ID
* @param array $answer Antwort-Array
* @param bool $showStatus Status anzeigen
* @return bool true, falls korrekt beantwortet, sonst false.
*/
function Answer(int $id, array $answer, bool $showStatus = true): bool
{ {
// Frage aus DB holen // Frage aus DB holen
$question = getQuestionById($id); $question = getQuestionById($id);
@ -165,7 +171,7 @@ function Answer($id, $answer, $showStatus = TRUE)
&& ($solution[2] == (isset($answer[$id][2]) ? $answer[$id][2] : 0)) && ($solution[2] == (isset($answer[$id][2]) ? $answer[$id][2] : 0))
&& ($solution[3] == (isset($answer[$id][3]) ? $answer[$id][3] : 0))); && ($solution[3] == (isset($answer[$id][3]) ? $answer[$id][3] : 0)));
// Aufräumen // Aufräumen
$GLOBALS['tpl']->delHandle('antwortStatus'); $GLOBALS['tpl']->delHandle('antwortStatus');
$GLOBALS['tpl']->delHandle('antwort1Loesung'); $GLOBALS['tpl']->delHandle('antwort1Loesung');
$GLOBALS['tpl']->delHandle('antwort2Loesung'); $GLOBALS['tpl']->delHandle('antwort2Loesung');
@ -212,31 +218,36 @@ function Answer($id, $answer, $showStatus = TRUE)
if (isset($answer[$id][2]) && $answer[$id][2] === '1') $GLOBALS['tpl']->parseBlock('content', 'A2L', 'Haken'); if (isset($answer[$id][2]) && $answer[$id][2] === '1') $GLOBALS['tpl']->parseBlock('content', 'A2L', 'Haken');
if (isset($answer[$id][3]) && $answer[$id][3] === '1') $GLOBALS['tpl']->parseBlock('content', 'A3L', 'Haken'); if (isset($answer[$id][3]) && $answer[$id][3] === '1') $GLOBALS['tpl']->parseBlock('content', 'A3L', 'Haken');
// Anhängen per default // Anhängen per default
$GLOBALS['tpl']->parse('content', 'antwort', TRUE, TRUE); $GLOBALS['tpl']->parse('content', 'antwort', TRUE, TRUE);
return $correct; return $correct;
} }
/****************************************************************************** /**
* Brotkrumen-Navigation.
* *
* Antwort * Fügt einen Link zur Brotkrumen-Navigation hinzu.
* Zeigt die Frage und die zugehörigen korrekten Antworten an * @param string $page Seiten-Link
* Antworten sind farblich gekennzeichnet (grün=richtig, rot=falsch) * @param string $title Seiten-Titel
* * @return void
/******************************************************************************/ */
function addBreadcrumb(string $page, string $title): void
function addBreadcrumb($params, $title)
{ {
$GLOBALS['tpl']->addVars(Array( $GLOBALS['tpl']->addVars(Array(
'page' => htmlspecialchars($params), 'page' => htmlspecialchars($page),
'pageTitle' => htmlspecialchars($title) 'pageTitle' => htmlspecialchars($title)
)); ));
$GLOBALS['tpl']->parseBlock('page-body', 'Breadcrumb', 'Link', TRUE); $GLOBALS['tpl']->parseBlock('page-body', 'Breadcrumb', 'Link', TRUE);
} }
function ShowAnswer(&$frage) /**
* Zeigt die Auflösung an.
* @param array $frage Referenz auf das assoziative Fragen-Array
* @return void
*/
function ShowAnswer(array &$frage): void
{ {
@ -245,7 +256,7 @@ function ShowAnswer(&$frage)
2 => (($frage['Loesung'] & 0x2) >> 1), 2 => (($frage['Loesung'] & 0x2) >> 1),
3 => (($frage['Loesung'] & 0x4) >> 2)); 3 => (($frage['Loesung'] & 0x4) >> 2));
// Aufräumen // Aufräumen
$GLOBALS['tpl']->delHandle('antwortStatus'); $GLOBALS['tpl']->delHandle('antwortStatus');
$GLOBALS['tpl']->delHandle('antwort1Loesung'); $GLOBALS['tpl']->delHandle('antwort1Loesung');
$GLOBALS['tpl']->delHandle('antwort2Loesung'); $GLOBALS['tpl']->delHandle('antwort2Loesung');
@ -280,5 +291,3 @@ function ShowAnswer(&$frage)
$GLOBALS['tpl']->parseBlock('content', 'ThreeRows', 'Row'); $GLOBALS['tpl']->parseBlock('content', 'ThreeRows', 'Row');
} }
} }
?>

View File

@ -8,7 +8,7 @@
* of the * of the
* *
* Bundesanstalt Technisches Hilfswerk * Bundesanstalt Technisches Hilfswerk
* Provinzialstraße 93 * Provinzialstraße 93
* D-53127 Bonn * D-53127 Bonn
* Germany * Germany
* E-Mail: redaktion@thw.de * E-Mail: redaktion@thw.de
@ -28,7 +28,19 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ */
function getStats() { /**
* Holt die Gesamt-Statistiken aus der Datenbank und füllt das Template.
* @return void
*/
function getStats(): void
{
$fragen = 0;
$richtig = 0;
$falsch = 0;
$boegen = 0;
$bestanden = 0;
$durchgefallen = 0;
$stmt = $GLOBALS['db']->prepare('SELECT fragen,richtig,falsch,boegen,bestanden,durchgefallen FROM statistik'); $stmt = $GLOBALS['db']->prepare('SELECT fragen,richtig,falsch,boegen,bestanden,durchgefallen FROM statistik');
$stmt->execute(); $stmt->execute();
$stmt->bind_result( $stmt->bind_result(
@ -42,7 +54,7 @@ function getStats() {
$stmt->fetch(); $stmt->fetch();
$GLOBALS['tpl']->addVars(Array( $GLOBALS['tpl']->addVars(array(
'statsFragen' => sprintf('%0.d', $fragen), 'statsFragen' => sprintf('%0.d', $fragen),
'statsFragenRichtig' => sprintf('%0.d (%0.2f %%)', $richtig, ($fragen > 0 ? $richtig / $fragen * 100 : 0)), 'statsFragenRichtig' => sprintf('%0.d (%0.2f %%)', $richtig, ($fragen > 0 ? $richtig / $fragen * 100 : 0)),
'statsFragenFalsch' => sprintf('%0.d (%0.2f %%)', $falsch, ($fragen > 0 ? $falsch / $fragen * 100 : 0)), 'statsFragenFalsch' => sprintf('%0.d (%0.2f %%)', $falsch, ($fragen > 0 ? $falsch / $fragen * 100 : 0)),
@ -55,7 +67,7 @@ function getStats() {
} }
getStats(); getStats();
$GLOBALS['tpl']->addTemplates(Array(
$GLOBALS['tpl']->addTemplates(array(
'content' => 'home' 'content' => 'home'
)); ));
?>

View File

@ -8,7 +8,7 @@
* of the * of the
* *
* Bundesanstalt Technisches Hilfswerk * Bundesanstalt Technisches Hilfswerk
* Provinzialstraße 93 * Provinzialstraße 93
* D-53127 Bonn * D-53127 Bonn
* Germany * Germany
* E-Mail: redaktion@thw.de * E-Mail: redaktion@thw.de
@ -28,54 +28,54 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ */
require_once 'db.php'; require_once 'db.php';
require_once 'class.template.inc.php'; require_once 'class.template.inc.php';
require_once 'functions.inc.php'; require_once 'functions.inc.php';
require_once 'init.inc.php'; require_once 'init.inc.php';
if (!isset($_REQUEST['show'])) { if (!isset($_REQUEST['show'])) {
$_REQUEST['show'] = 'home'; $_REQUEST['show'] = 'home';
} }
switch ($_REQUEST['show']) { switch ($_REQUEST['show']) {
case 'fragen': case 'fragen':
addBreadcrumb($_REQUEST['show'], 'Zufallsfragen beantworten'); addBreadcrumb($_REQUEST['show'], 'Zufallsfragen beantworten');
include ('zufallsfragen.inc.php'); include('zufallsfragen.inc.php');
break; break;
case 'bogen': case 'bogen':
addBreadcrumb($_REQUEST['show'], 'Prüfungsbogen üben'); addBreadcrumb($_REQUEST['show'], 'Prüfungsbogen üben');
include ('pruefbogen.inc.php'); include('pruefbogen.inc.php');
break; break;
case 'loesung': case 'loesung':
addBreadcrumb($_REQUEST['show'], 'Antworten anzeigen'); addBreadcrumb($_REQUEST['show'], 'Antworten anzeigen');
include ('antworten.inc.php'); include('antworten.inc.php');
break; break;
case 'ordnung': case 'ordnung':
addBreadcrumb($_REQUEST['show'], 'Prüfungsordnung'); addBreadcrumb($_REQUEST['show'], 'Prüfungsordnung');
$tpl->addVars('navOrdnung', 'current'); $GLOBALS['tpl']->addVars('navOrdnung', 'current');
$tpl->addTemplates(Array('content' => 'ordnung')); $GLOBALS['tpl']->addTemplates(array('content' => 'ordnung'));
break; break;
case 'stats': case 'stats':
$tpl->addVars(Array( $GLOBALS['tpl']->addVars(array(
// Statistik Zufallsfragen // Statistik Zufallsfragen
'fragenBisher' => $_SESSION['stats']['Fragen_Bisher'], 'fragenBisher' => $_SESSION['stats']['Fragen_Bisher'],
'fragenRichtig' => $_SESSION['stats']['Fragen_Richtig'], 'fragenRichtig' => $_SESSION['stats']['Fragen_Richtig'],
'fragenFalsch' => $_SESSION['stats']['Fragen_Falsch'], 'fragenFalsch' => $_SESSION['stats']['Fragen_Falsch'],
'fragenQuote' => (($_SESSION['stats']['Fragen_Bisher']>0)?(preg_replace('/\./is', ',', number_format($_SESSION['stats']['Fragen_Richtig']/$_SESSION['stats']['Fragen_Bisher']*100,2))):('0')) . '%', 'fragenQuote' => (($_SESSION['stats']['Fragen_Bisher'] > 0) ? (preg_replace('/\./is', ',', number_format($_SESSION['stats']['Fragen_Richtig'] / $_SESSION['stats']['Fragen_Bisher'] * 100, 2))) : ('0')) . '%',
// Statistik Prüfungsbögen // Statistik Prüfungsbögen
'boegenBisher' => $_SESSION['stats']['Boegen_Bisher'], 'boegenBisher' => $_SESSION['stats']['Boegen_Bisher'],
'boegenRichtig' => $_SESSION['stats']['Boegen_Bestanden'], 'boegenRichtig' => $_SESSION['stats']['Boegen_Bestanden'],
'boegenFalsch' => $_SESSION['stats']['Boegen_Durchgefallen'], 'boegenFalsch' => $_SESSION['stats']['Boegen_Durchgefallen'],
'boegenQuote' => (($_SESSION['stats']['Boegen_Bisher']>0)?(preg_replace('/\./is', ',', number_format($_SESSION['stats']['Boegen_Bestanden']/$_SESSION['stats']['Boegen_Bisher']*100,2))):('0')) . '%' 'boegenQuote' => (($_SESSION['stats']['Boegen_Bisher'] > 0) ? (preg_replace('/\./is', ',', number_format($_SESSION['stats']['Boegen_Bestanden'] / $_SESSION['stats']['Boegen_Bisher'] * 100, 2))) : ('0')) . '%'
)); ));
addBreadcrumb($_REQUEST['show'], 'Statistiken'); addBreadcrumb($_REQUEST['show'], 'Statistiken');
$tpl->addVars('navStats', 'current'); $GLOBALS['tpl']->addVars('navStats', 'current');
$tpl->addTemplates(Array('content' => 'stats')); $GLOBALS['tpl']->addTemplates(array('content' => 'stats'));
break; break;
case "barrierefreiheit": case "barrierefreiheit":
@ -85,26 +85,24 @@
case 'impressum': case 'impressum':
addBreadcrumb($_REQUEST['show'], 'Impressum'); addBreadcrumb($_REQUEST['show'], 'Impressum');
$tpl->addTemplates(Array('content' => 'impressum')); $GLOBALS['tpl']->addTemplates(array('content' => 'impressum'));
break; break;
case 'datenschutz': case 'datenschutz':
addBreadcrumb($_REQUEST['show'], 'Datenschutzhinweis'); addBreadcrumb($_REQUEST['show'], 'Datenschutzhinweis');
$tpl->addTemplates(Array('content' => 'datenschutz')); $GLOBALS['tpl']->addTemplates(array('content' => 'datenschutz'));
break; break;
case "downloads": case "downloads":
addBreadcrumb($_REQUEST["show"], "Offline-Version"); addBreadcrumb($_REQUEST["show"], "Offline-Version");
$tpl->addVars("navOffline", "current"); $GLOBALS['tpl']->addVars("navOffline", "current");
$tpl->addTemplates(Array("content" => "offline")); $GLOBALS['tpl']->addTemplates(array("content" => "offline"));
break; break;
default: default:
$title = ''; $title = '';
include('home.inc.php'); include('home.inc.php');
} }
$tpl->parse('pageContent', 'content'); $GLOBALS['tpl']->parse('pageContent', 'content');
$tpl->printParse('pageMain', 'page-body'); $GLOBALS['tpl']->printParse('pageMain', 'page-body');
?>

View File

@ -30,10 +30,9 @@
header('Content-Type: text/html; charset=utf-8'); header('Content-Type: text/html; charset=utf-8');
$GLOBALS['tpl'] = new Template('./templates/'); $GLOBALS['tpl'] = new Template(__DIR__ . '/templates/');
$tpl =& $GLOBALS['tpl'];
$tpl->addTemplates(Array( $GLOBALS['tpl']->addTemplates(Array(
'page-body' => 'page-body', 'page-body' => 'page-body',
'top-line' => 'top-line' 'top-line' => 'top-line'
)); ));
@ -60,14 +59,12 @@ if (isset($_REQUEST['jahr'])) {
$_SESSION['jahr'] = 2020; $_SESSION['jahr'] = 2020;
} }
srand(microtime()*(double)10000); mt_srand(intval(microtime()) * 10000);
if ((isset($_COOKIE['stylesheet']) && $_COOKIE['stylesheet'] == 'barrierefrei') if ((isset($_COOKIE['stylesheet']) && $_COOKIE['stylesheet'] == 'barrierefrei')
|| isset($_POST['barrierefrei']) || isset($_POST['barrierefrei'])
|| (isset($_GET['style']) && $_GET['style'] == 'rg')) { || (isset($_GET['style']) && $_GET['style'] == 'rg')) {
$tpl->addVars('extraStyleSheet', '<link href="rg-styles.css" rel="stylesheet" type="text/css" />'); $GLOBALS['tpl']->addVars('extraStyleSheet', '<link href="rg-styles.css" rel="stylesheet" type="text/css" />');
} else {
} }
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') { if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
@ -78,14 +75,12 @@ if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$protocol = 'http'; $protocol = 'http';
} }
$tpl->addVars(Array( $GLOBALS['tpl']->addVars(Array(
// Globale Variablen // Globale Variablen
'scriptName' => $_SERVER['SCRIPT_NAME'], 'scriptName' => $_SERVER['SCRIPT_NAME'],
'catalogYear' => $_SESSION['jahr'], 'catalogYear' => $_SESSION['jahr'],
'baseUrl' => $protocol . '://thw-theorie.de/' 'baseUrl' => $protocol . '://' . $_SERVER['HTTP_HOST'] . '/'
)); ));
$tpl->parse('topLine', 'top-line'); $GLOBALS['tpl']->parse('topLine', 'top-line');
?>

View File

@ -8,7 +8,7 @@
* of the * of the
* *
* Bundesanstalt Technisches Hilfswerk * Bundesanstalt Technisches Hilfswerk
* Provinzialstraße 93 * Provinzialstraße 93
* D-53127 Bonn * D-53127 Bonn
* Germany * Germany
* E-Mail: redaktion@thw.de * E-Mail: redaktion@thw.de
@ -30,12 +30,12 @@
/* /*
* *
* Vollständiger Prüfungsbogen mit zufälligen Fragen * Vollständiger Prüfungsbogen mit zufälligen Fragen
* *
*/ */
$tpl->parseBlock('page-body', 'NavBogen', 'Sublinks'); $GLOBALS['tpl']->parseBlock('page-body', 'NavBogen', 'Sublinks');
$tpl->addVars('navBogen', 'current'); $GLOBALS['tpl']->addVars('navBogen', 'current');
if (isset($_REQUEST['create']) && $_REQUEST['create'] == '1') { if (isset($_REQUEST['create']) && $_REQUEST['create'] == '1') {
// Neuen Bogen erstellen // Neuen Bogen erstellen
@ -43,17 +43,20 @@ if (isset($_REQUEST['create']) && $_REQUEST['create'] == '1') {
// Werte initialisieren // Werte initialisieren
$_SESSION['bogen']['StartTime'] = time(); $_SESSION['bogen']['StartTime'] = time();
$_SESSION['bogen']['Fragen'] = Array(); $_SESSION['bogen']['Fragen'] = array();
// Anz. Abschnitte und Fragen aus der DB holen // Anz. Abschnitte und Fragen aus der DB holen
$sectionCount = getSingleResult('SELECT COUNT(*) FROM abschnitte WHERE Jahr = ?', array('i', $_SESSION['jahr'])); $sectionCount = getSingleResult('SELECT COUNT(*) FROM abschnitte WHERE Jahr = ?', array('i', $_SESSION['jahr']));
$stmt = $GLOBALS['db']->prepare('SELECT ID, Abschnitt FROM fragen WHERE Jahr = ? ORDER BY Abschnitt, Nr ASC'); $questionId = 0;
$questionSection = 0;
$stmt = $GLOBALS['db']->prepare('SELECT ID, Abschnitt FROM fragen WHERE Jahr = ? ORDER BY Abschnitt, Nr');
$stmt->bind_param('i', $_SESSION['jahr']); $stmt->bind_param('i', $_SESSION['jahr']);
$stmt->execute(); $stmt->execute();
$stmt->bind_result($questionId, $questionSection); $stmt->bind_result($questionId, $questionSection);
// Fragen in Array übertragen // Fragen in Array übertragen
while ($stmt->fetch()) { while ($stmt->fetch()) {
$fragen[$questionId] = $questionSection; $fragen[$questionId] = $questionSection;
} }
@ -74,13 +77,14 @@ if (isset($_REQUEST['create']) && $_REQUEST['create'] == '1') {
unset($fragen[$id]); unset($fragen[$id]);
} }
// Restliche Fragen zufällig auffüllen // Restliche Fragen zufällig auffüllen.
// Dazu verbliebene Keys von $fragen als Values in neues Array $fragen2 kopieren, // Dazu verbliebene Keys von $fragen als Values in neues Array $fragen2 kopieren,
// da shuffle() die Keys verwirft! // da shuffle() die Keys verwirft!
$fragen2 = Array(); $fragen2 = array();
foreach ($fragen As $key => $value) { foreach ($fragen as $key => $value) {
array_push($fragen2, $key); array_push($fragen2, $key);
} }
shuffle($fragen2); shuffle($fragen2);
for ($i = 0; $i < 40 - $sectionCount; $i++) { for ($i = 0; $i < 40 - $sectionCount; $i++) {
array_push($_SESSION['bogen']['Fragen'], array_shift($fragen2)); array_push($_SESSION['bogen']['Fragen'], array_shift($fragen2));
@ -97,14 +101,14 @@ if (isset($_SESSION['bogen'])) {
$richtig = 0; $richtig = 0;
$falsch = 0; $falsch = 0;
$fragen_cnt = count($_SESSION['bogen']['Fragen']); $fragen_cnt = count($_SESSION['bogen']['Fragen']);
$zeit = time()-$_SESSION['bogen']['StartTime']; $zeit = time() - $_SESSION['bogen']['StartTime'];
for ($i = 0; $i < $fragen_cnt; $i++) { for ($i = 0; $i < $fragen_cnt; $i++) {
$id = $_SESSION['bogen']['Fragen'][$i]; $id = $_SESSION['bogen']['Fragen'][$i];
$solutionBitmask = getSingleResult('SELECT `Loesung` FROM `fragen` WHERE `ID` = ?', $solutionBitmask = getSingleResult('SELECT `Loesung` FROM `fragen` WHERE `ID` = ?',
array('i', $id)); array('i', $id));
$loesung = array( 1 => ( $solutionBitmask & 0x1), $loesung = array(1 => ($solutionBitmask & 0x1),
2 => (($solutionBitmask & 0x2) >> 1), 2 => (($solutionBitmask & 0x2) >> 1),
3 => (($solutionBitmask & 0x4) >> 2)); 3 => (($solutionBitmask & 0x4) >> 2));
@ -112,7 +116,7 @@ if (isset($_SESSION['bogen'])) {
$korrekt = (($loesung[1] == (isset($_POST['antwort'][$id][1]) ? $_POST['antwort'][$id][1] : 0)) $korrekt = (($loesung[1] == (isset($_POST['antwort'][$id][1]) ? $_POST['antwort'][$id][1] : 0))
&& ($loesung[2] == (isset($_POST['antwort'][$id][2]) ? $_POST['antwort'][$id][2] : 0)) && ($loesung[2] == (isset($_POST['antwort'][$id][2]) ? $_POST['antwort'][$id][2] : 0))
&& ($loesung[3] == (isset($_POST['antwort'][$id][3]) ? $_POST['antwort'][$id][3] : 0))); && ($loesung[3] == (isset($_POST['antwort'][$id][3]) ? $_POST['antwort'][$id][3] : 0)));
} else{ } else {
$korrekt = false; $korrekt = false;
} }
@ -134,58 +138,59 @@ if (isset($_SESSION['bogen'])) {
$_SESSION["stats"]['Boegen_Durchgefallen']++; $_SESSION["stats"]['Boegen_Durchgefallen']++;
$GLOBALS['db']->query('UPDATE statistik SET fragen=fragen+' . $fragen_cnt $GLOBALS['db']->query('UPDATE statistik SET fragen=fragen+' . $fragen_cnt
.',richtig=richtig+' . $richtig . ',richtig=richtig+' . $richtig
.',falsch=falsch+' . $falsch . ',falsch=falsch+' . $falsch
.',boegen=boegen+1' . ',boegen=boegen+1'
.',bestanden=bestanden+' . (($richtig / $fragen_cnt) >= 0.8?1:0) . ',bestanden=bestanden+' . (($richtig / $fragen_cnt) >= 0.8 ? 1 : 0)
.',durchgefallen=durchgefallen+' . (($richtig / $fragen_cnt) < 0.8?1:0)); . ',durchgefallen=durchgefallen+' . (($richtig / $fragen_cnt) < 0.8 ? 1 : 0));
$tpl->addTemplates('content', 'bogen-ende'); $GLOBALS['tpl']->addTemplates('content', 'bogen-ende');
$tpl->addVars(Array( $GLOBALS['tpl']->addVars(array(
'anzFragen' => count($_SESSION['bogen']['Fragen']), 'anzFragen' => count($_SESSION['bogen']['Fragen']),
'zeit' => sprintf('%02d:%02d\'%02d', $zeit / 3600, ($zeit/60)%60, $zeit%60), 'zeit' => sprintf('%02d:%02d\'%02d', $zeit / 3600, ($zeit / 60) % 60, $zeit % 60),
'fragenRichtig' => $richtig, 'fragenRichtig' => $richtig,
'fragenRichtigQuote' => sprintf('%.2f %%', $richtig / $fragen_cnt * 100), 'fragenRichtigQuote' => sprintf('%.2f %%', $richtig / $fragen_cnt * 100),
'fragenFalsch' => $falsch, 'fragenFalsch' => $falsch,
'fragenFalschQuote' => sprintf('%.2f %%', $falsch / $fragen_cnt * 100) 'fragenFalschQuote' => sprintf('%.2f %%', $falsch / $fragen_cnt * 100)
)); ));
if (($richtig / $fragen_cnt) >= 0.8) if (($richtig / $fragen_cnt) >= 0.8) {
$tpl->parseBlock('content', 'Bestanden', 'Ja'); $GLOBALS['tpl']->parseBlock('content', 'Bestanden', 'Ja');
else }
$tpl->parseBlock('content', 'Bestanden', 'Nein'); else {
$GLOBALS['tpl']->parseBlock('content', 'Bestanden', 'Nein');
}
for ($i=0; $i<count($_SESSION['bogen']['Fragen']); $i++) { for ($i = 0; $i < count($_SESSION['bogen']['Fragen']); $i++) {
if ($i>0 && $i%10==0) { if ($i > 0 && $i % 10 == 0) {
// 'Nach oben'-Zeile an Handle anhängen // 'Nach oben'-Zeile an Handle anhängen
$tpl->parseBlock('content', 'Aufloesung', 'Topline', TRUE); $GLOBALS['tpl']->parseBlock('content', 'Aufloesung', 'Topline', TRUE);
} }
Answer($_SESSION['bogen']['Fragen'][$i], $_POST['antwort'], FALSE); Answer($_SESSION['bogen']['Fragen'][$i], $_POST['antwort'], FALSE);
$tpl->parseBlock('content', 'Aufloesung', 'Antwort', TRUE, TRUE); $GLOBALS['tpl']->parseBlock('content', 'Aufloesung', 'Antwort', TRUE, TRUE);
} }
unset($_SESSION['bogen']); unset($_SESSION['bogen']);
} } else {
else {
// Fragen anzeigen // Fragen anzeigen
$tpl->addTemplates(Array( $GLOBALS['tpl']->addTemplates(array(
'content' => 'bogen-fragen' 'content' => 'bogen-fragen'
)); ));
$tpl->addVars(Array( $GLOBALS['tpl']->addVars(array(
'zeit' => date('G:i', $_SESSION['bogen']['StartTime']) 'zeit' => date('G:i', $_SESSION['bogen']['StartTime'])
)); ));
for ($i=0; $i<count($_SESSION['bogen']['Fragen']); $i++) { for ($i = 0; $i < count($_SESSION['bogen']['Fragen']); $i++) {
if ($i>0 && $i%10==0) { if ($i > 0 && $i % 10 == 0) {
$tpl->parseBlock('content', 'Bogen', 'Topline', TRUE); $GLOBALS['tpl']->parseBlock('content', 'Bogen', 'Topline', TRUE);
} }
// Frage aus DB holen // Frage aus DB holen
$question = getQuestionById($_SESSION['bogen']['Fragen'][$i]); $question = getQuestionById($_SESSION['bogen']['Fragen'][$i]);
$tpl->addVars(Array( $GLOBALS['tpl']->addVars(array(
'frageIndex' => $i + 1, 'frageIndex' => $i + 1,
'frageID' => $question['ID'], 'frageID' => $question['ID'],
'frageNr' => $question['Nr'], 'frageNr' => $question['Nr'],
@ -197,20 +202,18 @@ if (isset($_SESSION['bogen'])) {
)); ));
if ($question['Antwort3'] == '') { if ($question['Antwort3'] == '') {
$tpl->addVars('rowCnt', '2'); $GLOBALS['tpl']->addVars('rowCnt', '2');
$tpl->delBlockHandle('content', 'ThreeRows'); $GLOBALS['tpl']->delBlockHandle('content', 'ThreeRows');
} } else {
else { $GLOBALS['tpl']->addVars('rowCnt', '3');
$tpl->addVars('rowCnt', '3'); $GLOBALS['tpl']->parseBlock('content', 'ThreeRows', 'Row');
$tpl->parseBlock('content', 'ThreeRows', 'Row');
} }
$tpl->parseBlock('content', 'Bogen', 'Frage', TRUE, TRUE); $GLOBALS['tpl']->parseBlock('content', 'Bogen', 'Frage', TRUE, TRUE);
} }
} }
} } else {
else { $GLOBALS['tpl']->addVars('navBogenNeu', 'current');
$tpl->addVars('navBogenNeu', 'current'); $GLOBALS['tpl']->addTemplates(array('content' => 'bogen-start'));
$tpl->addTemplates(Array('content' => 'bogen-start'));
} }

View File

@ -6,7 +6,7 @@
* of the * of the
* *
* Bundesanstalt Technisches Hilfswerk * Bundesanstalt Technisches Hilfswerk
* Provinzialstraße 93 * Provinzialstraße 93
* D-53127 Bonn * D-53127 Bonn
* Germany * Germany
* E-Mail: redaktion@thw.de * E-Mail: redaktion@thw.de

View File

@ -6,7 +6,7 @@
* of the * of the
* *
* Bundesanstalt Technisches Hilfswerk * Bundesanstalt Technisches Hilfswerk
* Provinzialstraße 93 * Provinzialstraße 93
* D-53127 Bonn * D-53127 Bonn
* Germany * Germany
* E-Mail: redaktion@thw.de * E-Mail: redaktion@thw.de

View File

@ -8,7 +8,7 @@
* of the * of the
* *
* Bundesanstalt Technisches Hilfswerk * Bundesanstalt Technisches Hilfswerk
* Provinzialstraße 93 * Provinzialstraße 93
* D-53127 Bonn * D-53127 Bonn
* Germany * Germany
* E-Mail: redaktion@thw.de * E-Mail: redaktion@thw.de
@ -30,27 +30,27 @@
/* /*
* *
* Fragen in zufälliger Reihenfolge üben * Fragen in zufälliger Reihenfolge üben
* *
*/ */
$tpl->parseBlock('page-body', 'NavZufall', 'Sublinks'); $GLOBALS['tpl']->parseBlock('page-body', 'NavZufall', 'Sublinks');
$tpl->addVars('navZufall', 'current'); $GLOBALS['tpl']->addVars('navZufall', 'current');
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'neu') { if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'neu') {
// Fragenkatalog löschen // Fragenkatalog löschen
unset($_SESSION['zufallsfragen']); unset($_SESSION['zufallsfragen']);
} }
if (isset($_SESSION['zufallsfragen'])) { if (isset($_SESSION['zufallsfragen'])) {
// Fragenkatalog schon vorhanden. Zu nächster unbeantworteter Frage // Fragenkatalog schon vorhanden. Zu nächster unbeantworteter Frage
// bzw. Antwort der letzten Frage springen // bzw. Antwort der letzten Frage springen.
// Wenn keine Fragen mehr im Katalog vorhanden sind, // Wenn keine Fragen mehr im Katalog vorhanden sind,
// Statistik anzeigen. // Statistik anzeigen.
if (count($_SESSION['zufallsfragen'])==0) { if (count($_SESSION['zufallsfragen']) == 0) {
// Alle Fragen beantwortet, Ergebnis zeigen // Alle Fragen beantwortet, Ergebnis zeigen
$tpl->addVars(Array( $GLOBALS['tpl']->addVars(array(
'anzFragen' => $_SESSION['fragen_cnt'], 'anzFragen' => $_SESSION['fragen_cnt'],
'fragenRichtig' => $_SESSION['zufallstats']['Richtig'], 'fragenRichtig' => $_SESSION['zufallstats']['Richtig'],
'fragenRichtigQuote' => sprintf('%.2f %%', $_SESSION['zufallstats']['Richtig'] / $_SESSION['fragen_cnt'] * 100), 'fragenRichtigQuote' => sprintf('%.2f %%', $_SESSION['zufallstats']['Richtig'] / $_SESSION['fragen_cnt'] * 100),
@ -58,17 +58,16 @@ if (isset($_SESSION['zufallsfragen'])) {
'fragenFalschQuote' => sprintf('%.2f %%', $_SESSION['zufallstats']['Falsch'] / $_SESSION['fragen_cnt'] * 100), 'fragenFalschQuote' => sprintf('%.2f %%', $_SESSION['zufallstats']['Falsch'] / $_SESSION['fragen_cnt'] * 100),
)); ));
$tpl->addTemplates('content', 'zufallsfragen-ende'); $GLOBALS['tpl']->addTemplates('content', 'zufallsfragen-ende');
if (($_SESSION['zufallstats']['Richtig'] / $_SESSION['fragen_cnt']) >= 0.8) { if (($_SESSION['zufallstats']['Richtig'] / $_SESSION['fragen_cnt']) >= 0.8) {
$tpl->parseBlock('content', 'Bestanden', 'Ja'); $GLOBALS['tpl']->parseBlock('content', 'Bestanden', 'Ja');
} else { } else {
$tpl->parseBlock('content', 'Bestanden', 'Nein'); $GLOBALS['tpl']->parseBlock('content', 'Bestanden', 'Nein');
} }
// Sessiondaten löschen // Sessiondaten löschen
unset($_SESSION['zufallsfragen']); unset($_SESSION['zufallsfragen']);
unset($_SESSION['frage_nr']); unset($_SESSION['frage_nr']);
unset($_SESSION['fragen_cnt']); unset($_SESSION['fragen_cnt']);
@ -76,12 +75,11 @@ if (isset($_SESSION['zufallsfragen'])) {
unset($_SESSION['bogen']); unset($_SESSION['bogen']);
return; return;
} }
if (!isset($_REQUEST['frage_id']) || $_REQUEST['frage_id'][0] <> $_SESSION['zufallsfragen'][0]) { if (!isset($_REQUEST['frage_id']) || $_REQUEST['frage_id'][0] <> $_SESSION['zufallsfragen'][0]) {
$tpl->addTemplates(Array('content' => 'zufallsfragen-frage')); $GLOBALS['tpl']->addTemplates(array('content' => 'zufallsfragen-frage'));
// Frage stellen // Frage stellen
SingleQuestion($_SESSION['zufallsfragen'][0], $_SESSION['frage_nr'], $_SESSION['fragen_cnt']); SingleQuestion($_SESSION['zufallsfragen'][0], $_SESSION['frage_nr'], $_SESSION['fragen_cnt']);
@ -89,11 +87,11 @@ if (isset($_SESSION['zufallsfragen'])) {
return; return;
} }
$tpl->addTemplates(Array('content' => 'zufallsfragen-aufloesung')); $GLOBALS['tpl']->addTemplates(array('content' => 'zufallsfragen-aufloesung'));
// Antwort auswerten // Antwort auswerten
questionHeader($_REQUEST['frage_id'][0], $_SESSION['frage_nr'], $_SESSION['fragen_cnt'], $_SESSION['jahr']); questionHeader($_REQUEST['frage_id'][0], $_SESSION['frage_nr'], $_SESSION['fragen_cnt']);
$korrekt = Answer($_REQUEST['frage_id'][0], $_REQUEST['antwort']); $korrekt = Answer($_REQUEST['frage_id'][0], $_REQUEST['antwort']);
// Statistik anpassen // Statistik anpassen
@ -101,20 +99,19 @@ if (isset($_SESSION['zufallsfragen'])) {
$_SESSION['zufallstats']['Richtig']++; $_SESSION['zufallstats']['Richtig']++;
$_SESSION['stats']['Fragen_Richtig']++; $_SESSION['stats']['Fragen_Richtig']++;
$stmt = $GLOBALS['db']->prepare('UPDATE statistik SET fragen=fragen+1,richtig=richtig+1'); $stmt = $GLOBALS['db']->prepare('UPDATE statistik SET fragen=fragen+1,richtig=richtig+1');
$stmt->execute();
} else { } else {
$_SESSION['zufallstats']['Falsch']++; $_SESSION['zufallstats']['Falsch']++;
$_SESSION['stats']['Fragen_Falsch']++; $_SESSION['stats']['Fragen_Falsch']++;
$stmt = $GLOBALS['db']->prepare('UPDATE statistik SET fragen=fragen+1,falsch=falsch+1'); $stmt = $GLOBALS['db']->prepare('UPDATE statistik SET fragen=fragen+1,falsch=falsch+1');
$stmt->execute();
} }
$stmt->execute();
$tpl->addVars(Array( $GLOBALS['tpl']->addVars(array(
'submitText' => ($_SESSION['frage_nr']==$_SESSION['fragen_cnt'])?'Gesamtstatistik':'N&auml;chste Frage', 'submitText' => ($_SESSION['frage_nr'] == $_SESSION['fragen_cnt']) ? 'Gesamtstatistik' : 'N&auml;chste Frage',
'aktuelleFrage' => $_SESSION['frage_nr'], 'aktuelleFrage' => $_SESSION['frage_nr'],
'fragenRichtig' => $_SESSION['zufallstats']['Richtig'], 'fragenRichtig' => $_SESSION['zufallstats']['Richtig'],
'fragenFalsch' => $_SESSION['zufallstats']['Falsch'], 'fragenFalsch' => $_SESSION['zufallstats']['Falsch'],
'fragenQuote' => sprintf('%0.2f', $_SESSION['zufallstats']['Falsch']/$_SESSION['frage_nr']*100) . '%' 'fragenQuote' => sprintf('%0.2f', $_SESSION['zufallstats']['Falsch'] / $_SESSION['frage_nr'] * 100) . '%'
)); ));
// Frage entfernen // Frage entfernen
@ -129,26 +126,24 @@ if (isset($_SESSION['zufallsfragen'])) {
// Neuen Fragenkatalog erstellen // Neuen Fragenkatalog erstellen
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'start') { if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'start') {
$topicCount = getSingleResult('SELECT COUNT(*) AS Cnt FROM abschnitte WHERE Jahr = ?', $topicCount = getSingleResult('SELECT COUNT(*) AS Cnt FROM abschnitte WHERE Jahr = ?', array('i', $_SESSION['jahr']));
array('i', $_SESSION['jahr']));
// Gewählte Abschnitte in Query einsetzen // Gewählte Abschnitte in Query einsetzen
$selectedTopics = array(); $selectedTopics = array();
for ($topic = 1; $topic <= $topicCount; $topic++){ for ($topic = 1; $topic <= $topicCount; $topic++) {
if (isset($_REQUEST['abschnitt'][$topic]) && $_REQUEST['abschnitt'][$topic] == '1') { if (isset($_REQUEST['abschnitt'][$topic]) && $_REQUEST['abschnitt'][$topic] == '1') {
array_push($selectedTopics, $topic); $selectedTopics[] = $topic;
} }
} }
if (count($selectedTopics) == 0) if (count($selectedTopics) == 0) {
{ // Kein Themenabschnitt gewählt
// Kein Themenabschnitt gewählt $GLOBALS['tpl']->addTemplates(array('content' => 'zufallsfragen-error'));
$tpl->addTemplates(Array('content' => 'zufallsfragen-error'));
return; return;
} }
// Sessiondaten löschen // Sessiondaten löschen
unset($_SESSION['zufallsfragen']); unset($_SESSION['zufallsfragen']);
unset($_SESSION['frage_nr']); unset($_SESSION['frage_nr']);
unset($_SESSION['fragen_cnt']); unset($_SESSION['fragen_cnt']);
@ -160,28 +155,30 @@ if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'start') {
$_SESSION['frage_nr'] = 1; $_SESSION['frage_nr'] = 1;
$_SESSION['zufallstats'] = array('Richtig' => '0', 'Falsch' => '0'); $_SESSION['zufallstats'] = array('Richtig' => '0', 'Falsch' => '0');
$tpl->addTemplates(Array('content' => 'zufallsfragen-frage')); $GLOBALS['tpl']->addTemplates(array('content' => 'zufallsfragen-frage'));
// Fragen holen // Fragen holen
$inClauseParams = implode(',', array_fill(0, count($selectedTopics), '?')); $inClauseParams = implode(',', array_fill(0, count($selectedTopics), '?'));
$inClauseTypes = str_repeat('i', count($selectedTopics)); $inClauseTypes = str_repeat('i', count($selectedTopics));
$params = array_merge(array('i'.$inClauseTypes, $_SESSION['jahr']), $selectedTopics); $params = array_merge(array('i' . $inClauseTypes, $_SESSION['jahr']), $selectedTopics);
$id = 0;
$stmt = $GLOBALS['db']->prepare('SELECT ID FROM fragen WHERE Jahr = ? AND Abschnitt IN (' . $inClauseParams . ')'); $stmt = $GLOBALS['db']->prepare('SELECT ID FROM fragen WHERE Jahr = ? AND Abschnitt IN (' . $inClauseParams . ')');
callBindParamArray($stmt, $params); callBindParamArray($stmt, $params);
$stmt->execute(); $stmt->execute();
$stmt->bind_result($id); $stmt->bind_result($id);
// Fragen in Array übertragen // Fragen in Array übertragen
while ($stmt->fetch()) { while ($stmt->fetch()) {
array_push($_SESSION['zufallsfragen'], $id); $_SESSION['zufallsfragen'][] = $id;
} }
$stmt->close(); $stmt->close();
// Fragen zufällig mischen // Fragen zufällig mischen
shuffle($_SESSION['zufallsfragen']); shuffle($_SESSION['zufallsfragen']);
// Nur gewählte Anzahl Fragen zulassen // Nur gewählte Anzahl Fragen zulassen
if ($_REQUEST['fragen'] > 0 && $_REQUEST['fragen'] < count($_SESSION['zufallsfragen'])) { if ($_REQUEST['fragen'] > 0 && $_REQUEST['fragen'] < count($_SESSION['zufallsfragen'])) {
$_SESSION['zufallsfragen'] = array_slice($_SESSION['zufallsfragen'], 0, $_REQUEST['fragen']); $_SESSION['zufallsfragen'] = array_slice($_SESSION['zufallsfragen'], 0, $_REQUEST['fragen']);
} }
@ -197,25 +194,25 @@ if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'start') {
} }
// Startseite mit Abschnittsauswahl // Startseite mit Abschnittsauswahl
$tpl->addVars('navZufallNeu', 'current'); $GLOBALS['tpl']->addVars('navZufallNeu', 'current');
$abschnitte = getTopics(); $abschnitte = getTopics();
$topicCount = getSingleResult('SELECT COUNT(*) AS Cnt FROM abschnitte WHERE Jahr = ?', $topicCount = getSingleResult('SELECT COUNT(*) AS Cnt FROM abschnitte WHERE Jahr = ?',
array('i', $_SESSION['jahr'])); array('i', $_SESSION['jahr']));
$maxFragen = getSingleResult('SELECT COUNT(*) AS Cnt FROM fragen WHERE Jahr = ?', $maxFragen = getSingleResult('SELECT COUNT(*) AS Cnt FROM fragen WHERE Jahr = ?',
array('i', $_SESSION['jahr'])); array('i', $_SESSION['jahr']));
$tpl->addVars(Array( $GLOBALS['tpl']->addVars(array(
'abschnitteAnz' => $topicCount, 'abschnitteAnz' => $topicCount,
'maxFragen' => $maxFragen 'maxFragen' => $maxFragen
)); ));
$tpl->addTemplates('content', 'zufallsfragen-start'); $GLOBALS['tpl']->addTemplates('content', 'zufallsfragen-start');
foreach ($abschnitte as $nr => $description) { foreach ($abschnitte as $nr => $description) {
$tpl->addVars(Array( $GLOBALS['tpl']->addVars(array(
'abschnittNr' => $nr, 'abschnittNr' => $nr,
'abschnittDesc' => htmlspecialchars($description) 'abschnittDesc' => htmlspecialchars($description)
)); ));
$tpl->parseBlock('content', 'Abschnitte', 'Row', TRUE); $GLOBALS['tpl']->parseBlock('content', 'Abschnitte', 'Row', TRUE);
} }