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
*
* Bundesanstalt Technisches Hilfswerk
* Provinzialstra<EFBFBD>e 93
* Provinzialstraße 93
* D-53127 Bonn
* Germany
* 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;
if (isset($_REQUEST['katalog'])) {
@ -44,13 +44,13 @@ if (isset($_REQUEST['katalog'])) {
$abschnitte = getTopics();
foreach ($abschnitte as $nr => $description) {
$tpl->addVars(Array(
$GLOBALS['tpl']->addVars(array(
'abschnittNr' => $nr,
'abschnittName' => htmlspecialchars($description),
'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'])) {
@ -61,9 +61,8 @@ if (isset($_SESSION['zufallsfragen']) || isset($_SESSION['bogen'])) {
unset($_SESSION['fragen_cnt']);
unset($_SESSION['zufallstats']);
unset($_SESSION['bogen']);
}
else {
$tpl->addTemplates(Array('content' => 'aufloesung-error'));
} else {
$GLOBALS['tpl']->addTemplates(array('content' => 'aufloesung-error'));
return;
}
}
@ -80,18 +79,18 @@ if ($katalog > 0) {
addBreadcrumb($_REQUEST['show'] . '&katalog=' . $selectedNr, $selectedDescription);
$tpl->addTemplates(Array(
$GLOBALS['tpl']->addTemplates(array(
'content' => 'aufloesung-antworten'
));
$tpl->addVars(Array(
$GLOBALS['tpl']->addVars(array(
'abschnittNr' => $selectedNr,
'abschnittName' => htmlspecialchars($selectedDescription)
));
$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->execute();
$questions = $stmt->get_result();
@ -100,32 +99,34 @@ if ($katalog > 0) {
while ($question = $questions->fetch_array(MYSQLI_ASSOC)) {
ShowAnswer($question);
$tpl->parseBlock('content', 'Antworten', 'Row', TRUE, TRUE);
$GLOBALS['tpl']->parseBlock('content', 'Antworten', 'Row', TRUE, TRUE);
if ($I % 10 == 0) {
$tpl->parseBlock('content', 'Antworten', 'Topline', TRUE);
$GLOBALS['tpl']->parseBlock('content', 'Antworten', 'Topline', TRUE);
}
$I++;
}
$questions->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->execute();
$stmt->bind_result($nr, $description);
while ($stmt->fetch()) {
$tpl->addVars(Array(
$GLOBALS['tpl']->addVars(array(
'abschnittNr' => $nr,
'abschnittName' => $description
));
$tpl->parseBlock('content', 'Abschnitte', 'Row', TRUE);
$GLOBALS['tpl']->parseBlock('content', 'Abschnitte', 'Row', TRUE);
}
}
?>

View File

@ -1,15 +1,12 @@
<?php
if (isset($_POST['normal'])) {
setcookie("stylesheet", "normal", time()+60*60*24*365);
$tpl->addVars('extraStyleSheet', '');
$GLOBALS['tpl']->addVars('extraStyleSheet', '');
}
if (isset($_POST['barrierefrei'])) {
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
*
* Bundesanstalt Technisches Hilfswerk
* Provinzialstraße 93
* Provinzialstraße 93
* D-53127 Bonn
* Germany
* E-Mail: redaktion@thw.de
@ -35,517 +35,627 @@
* including other templates, and it can parse dynamic blocks
* which can be nested inside other blocks.
*
* Predefined variables:
* Predefined template variables:
*
* {templatePath} Contains the template path
* {templateLang} Contains the country code, if set
* - {templatePath} Contains the template path
* - {templateLang} Contains the country code, if set
*
* If you don't need them, remove them immediately after
* 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 $LOADED = array(); // Already loaded templates are
// stored as $LOADED[HANDLE]=>TRUE
var $PARSEVARS = array(); // Array of variable/value pairs
// to be replaced in templates
var $HANDLES = array(); // Handles which contain parsed templates
/**
* @var array Handles which contain parsed templates to be replaced in templates
*/
private array $templateHandles = array();
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 $LANG; // Country code (en, de, fr, ...)
var $TPLEXT; // Filename extension (default is .tpl)
/**
* @var array Parsed block data
*/
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
// set to TRUE.
var $WIN32 = FALSE; // Set to "TRUE" on Win32 systems, if
// you encounter problems with paths.
var $DIEONERR = TRUE; // If set to TRUE, die() is called in error
/**
* @var string Filename extension (default is .tpl)
*/
private string $templateExtension;
/**
* @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
function Template($tpldir, $lang = "", $tplext = "tpl")
/**
* constructor.
* @param string $tpldir The template base directory.
* @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->LANG = strtolower($lang);
$this->TPLEXT = $tplext;
$this->languageCode = strtolower($lang);
$this->templateExtension = $tplext;
$this->addVars("templateLang", $this->LANG);
$this->addVars("templateLang", $this->languageCode);
}
// ************************************************************
// Sets or changes the template search path
function setPath($path)
/**
* Sets or changes the template search path
* @param string $path New template base directory.
* @return bool true if the path was set correctly, false if an error occurred.
*/
function setPath(string $path): bool
{
if ($this->WIN32) {
if (ord(substr($path, -1)) != 92) $path .= chr(92);
if ($this->useWindowsPathSeparator) {
if (ord(substr($path, -1)) != 92) {
$path .= chr(92);
}
} else {
if (ord(substr($path, -1)) != 47) $path .= chr(47);
if (ord(substr($path, -1)) != 47) {
$path .= chr(47);
}
}
if (is_dir($path)) {
$this->TPLDIR = $path;
$this->templateDirectory = $path;
// Add a path variable for use in templates
$this->addVars("templatePath", $path);
return TRUE;
return true;
} else {
echo "[TEMPLATE ENGINE] The specified template path "
. "'<b>" . $path . "</b>' is invalid!<br />";
$this->TPLDIR = "";
$this->templateDirectory = "";
if ($this->DIEONERR == TRUE) die();
return FALSE;
if ($this->dieOnError) {
die();
}
return false;
}
}
// ************************************************************
// Get dynamic blocks recursively to enable nested blocks
function getDynamicBlocks($tplFilename, $contents)
/**
* Get dynamic blocks recursively to enable nested blocks.
* @param string $tplFilename Template base filename.
* @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",
$contents, $blocks);
preg_match_all("/(\{\|([a-zA-Z0-9]+)})(.*?)\\1/s", $contents, $blocks);
if (empty($blocks[0])) return;
if (empty($blocks[0])) {
return;
}
// Go through all blocks and save them in $this->BLOCKS
for ($I = 0; $I < count($blocks[0]); $I++) {
$blockparts = array();
preg_match_all("/(\{\|" . $blocks[2][$I] .
"\*([a-zA-Z0-9]+)\})(.*?)\\1/s",
$blocks[3][$I], $blockparts);
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
$this->getDynamicBlocks($tplFilename, $blockparts[3][$J]);
// Replace block data with placeholders
$blockparts[3][$J] =
preg_replace("/(\{\|([a-zA-Z0-9]+)\})(.*?)\\1/s",
"\\1", $blockparts[3][$J]);
$blockparts[3][$J] = preg_replace("/(\{\|([a-zA-Z0-9]+)})(.*?)\\1/s", "\\1", $blockparts[3][$J]);
// Save block data
$this->BLOCKS[$tplFilename][$blocks[2][$I]][$blockparts[2][$J]]
= $blockparts[3][$J];
$this->templateBlocks[$tplFilename][$blocks[2][$I]][$blockparts[2][$J]] = $blockparts[3][$J];
}
}
}
// ************************************************************
// Loads a template, runs some checks and extracts dynamic blocks
function loadTemplate($tplFilename)
/**
* Loads a template, runs some checks and extracts dynamic blocks.
* @param string $tplFilename Template base filename.
* @return bool true if the template is loaded, false if an error occurred.
*/
function loadTemplate(string $tplFilename): bool
{
// Template already loaded?
if (isset($this->LOADED[$tplFilename])) return TRUE;
if (isset($this->loadedTemplates[$tplFilename])) {
return true;
}
// Has the path been set?
if (empty($this->TPLDIR)) {
if (empty($this->templateDirectory)) {
echo "[TEMPLATE ENGINE] Template path not set or invalid!<br />";
if ($this->DIEONERR == TRUE) die();
return FALSE;
if ($this->dieOnError) {
die();
}
return false;
}
// Is a user-defined county code set?
if (!empty($this->LANG)) {
if (!empty($this->languageCode)) {
// Yes. Try to find template with the specified CC
if (file_exists($this->TPLDIR.$this->TPLFILES[$tplFilename]."."
.$this->LANG.".".$this->TPLEXT)) {
$filename = $this->TPLDIR.$this->TPLFILES[$tplFilename].".".
$this->LANG.".".$this->TPLEXT;
if (file_exists($this->templateDirectory . $this->templateFiles[$tplFilename] . "." . $this->languageCode . "." . $this->templateExtension)) {
$filename = $this->templateDirectory . $this->templateFiles[$tplFilename] . "." . $this->languageCode . "." . $this->templateExtension;
} else {
// Otherwise, use template filename without CC
if (file_exists($this->TPLDIR.$this->TPLFILES[$tplFilename]."."
.$this->TPLEXT)) {
$filename = $this->TPLDIR.$this->TPLFILES[$tplFilename]."."
.$this->TPLEXT;
if (file_exists($this->templateDirectory . $this->templateFiles[$tplFilename] . "." . $this->templateExtension)) {
$filename = $this->templateDirectory . $this->templateFiles[$tplFilename] . "."
. $this->templateExtension;
} else {
echo "[TEMPLATE ENGINE] Can't find template "
."'".$tplFilename."'!<br />";
echo "[TEMPLATE ENGINE] Can't find template " . "'" . $tplFilename . "'!<br />";
if ($this->DIEONERR == TRUE) die();
return FALSE;
if ($this->dieOnError) {
die();
}
return false;
}
}
} else {
// No. Use template filename without CC
if (file_exists($this->TPLDIR.$this->TPLFILES[$tplFilename]."."
.$this->TPLEXT)) {
$filename = $this->TPLDIR.$this->TPLFILES[$tplFilename]."."
.$this->TPLEXT;
if (file_exists($this->templateDirectory . $this->templateFiles[$tplFilename] . "." . $this->templateExtension)) {
$filename = $this->templateDirectory . $this->templateFiles[$tplFilename] . "." . $this->templateExtension;
} else {
echo "[TEMPLATE ENGINE] Can't find template "
."'".$tplFilename."'!<br />";
echo "[TEMPLATE ENGINE] Can't find template " . "'" . $tplFilename . "'!<br />";
if ($this->DIEONERR == TRUE) die();
return FALSE;
if ($this->dieOnError) {
die();
}
return false;
}
}
// Load template file
$contents = implode("", (@file($filename)));
if (!$contents || empty($contents)) {
echo "[TEMPLATE ENGINE] Can't load template '"
.$tplFilename."'!<br />";
if (empty($contents)) {
echo "[TEMPLATE ENGINE] Can't load template '" . $tplFilename . "'!<br />";
if ($this->DIEONERR == TRUE) die();
return FALSE;
if ($this->dieOnError) {
die();
}
return false;
}
// Parse dynamic blocks recursively
$this->getDynamicBlocks($tplFilename, $contents);
// Replace all block data with placeholders
$contents = preg_replace("/(\{\|([a-zA-Z0-9]+)\})(.*?)\\1/s", "\\1",
$contents);
$contents = preg_replace("/(\{\|([a-zA-Z0-9]+)})(.*?)\\1/s", "\\1", $contents);
$this->TPLDATA[$tplFilename] = $contents;
$this->LOADED[$tplFilename] = 1;
$this->templateData[$tplFilename] = $contents;
$this->loadedTemplates[$tplFilename] = 1;
return TRUE;
return true;
}
// ************************************************************
// Parses a template and loads it if neccessary.
// The result is assigned or concatenated to the specified handle.
function parse($handle = "",
$file = "",
$append = FALSE,
$delunused = FALSE)
/**
* Parses a template and loads it if necessary.
* The result is assigned or concatenated to the specified handle.
* @param string $handle Result handle to store the parsed template in.
* @param string $file Template file to parse.
* @param bool $append true to append the parsed template to the given handle, false replaces the contents.
* @param bool $delunused true to delete unused variable placeholders, false to keep them for later processing.
* @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
if (empty($handle) || empty($file))
return FALSE;
if (empty($handle) || empty($file)) {
return false;
}
if (!isset($this->TPLFILES[$file]))
return FALSE;
if (!isset($this->templateFiles[$file])) {
return false;
}
if (!isset($this->LOADED[$file])&&!$this->loadTemplate($file))
return FALSE;
if (!isset($this->loadedTemplates[$file]) && !$this->loadTemplate($file)) {
return false;
}
$templateCopy = $this->TPLDATA[$file];
$templateCopy = $this->templateData[$file];
// Reset array pointers
reset($this->HANDLES);
reset($this->PARSEVARS);
reset($this->templateHandles);
reset($this->parserVariables);
// Replace blocks
if (isset($this->H_BLOCKS[$file])) {
reset($this->H_BLOCKS[$file]);
if (isset($this->parsedBlocks[$file])) {
reset($this->parsedBlocks[$file]);
while (list($varname, $value) = each($this->H_BLOCKS[$file]))
$templateCopy = preg_replace("/\{\|".$varname."\}/i",
foreach ($this->parsedBlocks[$file] as $varname => $value) {
$templateCopy = preg_replace("/\{\|" . $varname . "}/i",
$value, $templateCopy);
}
}
// Replace variables
while (list($varname, $value) = each($this->PARSEVARS))
$templateCopy = preg_replace("/\{".$varname."\}/i",
foreach ($this->parserVariables as $varname => $value) {
$templateCopy = preg_replace("/\{" . $varname . "}/i",
$value, $templateCopy);
}
// Replace {~name} placeholders with already parsed handle of
// the same name
while (list($varname, $value) = each($this->HANDLES))
$templateCopy = preg_replace("/\{\~".$varname."\}/i",
foreach ($this->templateHandles as $varname => $value) {
$templateCopy = preg_replace("/\{~" . $varname . "}/i",
$value, $templateCopy);
}
// Delete unused variables and placeholders
if ($delunused)
$templateCopy = preg_replace("/\{[~|\|]?(\w*?)\}/", "",
$templateCopy);
if ($delunused) {
$templateCopy = preg_replace("/\{[~|]?(\w*?)}/", "", $templateCopy);
}
// Assign to handle
if ($append && isset($this->HANDLES[$handle])) {
$this->HANDLES[$handle] .= $templateCopy;
if ($append && isset($this->templateHandles[$handle])) {
$this->templateHandles[$handle] .= $templateCopy;
} 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;
while (list($handle, $file) = each($list))
if (!$this->parse($handle, $file)) return FALSE;
return TRUE;
foreach ($list as $handle => $file) {
if (!$this->parse($handle, $file)) return false;
}
// ************************************************************
// Parses a template and prints the result.
return true;
}
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)) {
$this->printHandle($handle);
return TRUE;
return true;
}
return FALSE;
return false;
}
// ************************************************************
// Parses a block and replaces or appends the result to the block handle.
//
// Note: First argument is the template file name containing the blocks,
// not a handle name!
//
// Note: This function has no effect on any template handle.
// Parsed block data is inserted into the template handle in the
// parse() method.
function parseBlock($file = "",
$block = "",
$blockpart = "",
$append = FALSE,
$delunused = FALSE)
/**
* Parses a block and replaces or appends the result to the block handle.
*
* Note: First argument is the template file name containing the blocks,
* not a handle name!
*
* Note: This function has no effect on any template handle.
* Parsed block data is inserted into the template handle in the
* parse() method.
* @param string $file Template base filename to parse.
* @param string $block Block name to parse.
* @param string $blockpart Block part to parse.
* @param bool $append true appends the parsed data to the block contents, false replaces it.
* @param bool $delunused true removes unused variable placeholders, false keeps them for later processing.
* @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))
return FALSE;
return false;
if (!isset($this->TPLFILES[$file]))
return FALSE;
if (!isset($this->templateFiles[$file]))
return false;
if (!isset($this->LOADED[$file])&&!$this->loadTemplate($file))
return FALSE;
if (!isset($this->loadedTemplates[$file]) && !$this->loadTemplate($file))
return false;
$blockCopy = $this->BLOCKS[$file][$block][$blockpart];
$blockCopy = $this->templateBlocks[$file][$block][$blockpart];
// Reset array pointers
reset($this->H_BLOCKS);
reset($this->PARSEVARS);
reset($this->parsedBlocks);
reset($this->parserVariables);
// Replace blocks
if (isset($this->H_BLOCKS[$file])) {
reset($this->H_BLOCKS[$file]);
if (isset($this->parsedBlocks[$file])) {
reset($this->parsedBlocks[$file]);
while (list($varname, $value) = each($this->H_BLOCKS[$file]))
$blockCopy = preg_replace("/\{\|".$varname."\}/i",
foreach ($this->parsedBlocks[$file] as $varname => $value) {
$blockCopy = preg_replace("/\{\|" . $varname . "}/i",
$value, $blockCopy);
}
}
// Replace variables
while (list($varname, $value) = each($this->PARSEVARS))
$blockCopy = preg_replace("/\{".$varname."\}/i",
foreach ($this->parserVariables as $varname => $value) {
$blockCopy = preg_replace("/\{" . $varname . "}/i",
$value, $blockCopy);
}
// Replace {~name} placeholders with already parsed handle of
// the same name
while (list($varname, $value) = each($this->HANDLES))
$blockCopy = preg_replace("/\{\~".$varname."\}/i",
foreach ($this->templateHandles as $varname => $value) {
$blockCopy = preg_replace("/\{~" . $varname . "}/i",
$value, $blockCopy);
}
// Delete unused variables and placeholders
if ($delunused)
$blockCopy = preg_replace("/\{[~|]?(\w*?)\}/", "", $blockCopy);
if ($delunused) {
$blockCopy = preg_replace("/\{[~|]?(\w*?)}/", "", $blockCopy);
}
// Assign to handle
if ($append && isset($this->H_BLOCKS[$file][$block])) {
$this->H_BLOCKS[$file][$block] .= $blockCopy;
if ($append && isset($this->parsedBlocks[$file][$block])) {
$this->parsedBlocks[$file][$block] .= $blockCopy;
} else {
$this->H_BLOCKS[$file][$block] = $blockCopy;
$this->parsedBlocks[$file][$block] = $blockCopy;
}
return TRUE;
return true;
}
// ************************************************************
// Deletes all block handles
function clearBlockHandles()
/**
* Deletes all block handles.
* @return void
*/
function clearBlockHandles(): void
{
if (!empty($this->H_BLOCKS)) {
reset($this->H_BLOCKS);
while (list($ref, $val) = each($this->H_BLOCKS))
unset($this->H_BLOCKS[$ref]);
if (!empty($this->parsedBlocks)) {
reset($this->parsedBlocks);
foreach ($this->parsedBlocks as $ref => $val) {
unset($this->parsedBlocks[$ref]);
}
}
}
// ************************************************************
// Deletes the specified block handle
function delBlockHandle($file, $block)
/**
* Deletes the specified block handle
* @param string $file The template base file the block is found ion.
* @param string $block The block name to delete.
* @return void
*/
function delBlockHandle(string $file,
string $block): void
{
if (!empty($file) && !empty($block))
if (isset($this->H_BLOCKS[$file][$block]))
unset($this->H_BLOCKS[$file][$block]);
if (!empty($file) && !empty($block)) {
if (isset($this->parsedBlocks[$file][$block])) {
unset($this->parsedBlocks[$file][$block]);
}
}
}
// ************************************************************
// Adds one or more templates
// You can pass one associative array with $handle=>$filename pairs,
// or two strings ($handle, $filename) to this function.
function addTemplates($tplList, $tplFilename = "")
/**
* Adds one or more templates
* You can pass one associative array with $handle=>$filename pairs,
* 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.
* @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)) {
reset($tplList);
while (list($handle, $filename) = each($tplList)) {
foreach ($tplList as $handle => $filename) {
// Add handle to list
$this->TPLFILES[$handle] = $filename;
$this->templateFiles[$handle] = $filename;
// Delete loaded flag if set
unset($this->LOADED[$handle]);
unset($this->loadedTemplates[$handle]);
}
} else {
$this->TPLFILES[$tplList] = $tplFilename;
unset($this->LOADED[$tplList]);
$this->templateFiles[$tplList] = $tplFilename;
unset($this->loadedTemplates[$tplList]);
}
}
// ************************************************************
// Deletes all template handles
function clearHandles()
/**
* Deletes all template handles
* @return void
*/
function clearHandles(): void
{
if (!empty($this->HANDLES)) {
reset($this->HANDLES);
while (list($ref, $val) = each($this->HANDLES))
unset($this->HANDLES[$ref]);
if (!empty($this->templateHandles)) {
reset($this->templateHandles);
foreach ($this->templateHandles as $ref => $val) {
unset($this->templateHandles[$ref]);
}
}
}
// ************************************************************
// Deletes the specified template handle
function delHandle($handleName = "")
/**
* Deletes the specified template handle
* @param string $handleName Template handle to delete.
* @return void
*/
function delHandle(string $handleName = ""): void
{
if (!empty($handleName))
if (isset($this->HANDLES[$handleName]))
unset($this->HANDLES[$handleName]);
if (!empty($handleName)) {
if (isset($this->templateHandles[$handleName])) {
unset($this->templateHandles[$handleName]);
}
}
}
// ************************************************************
// Returns the contents of the specified template handle
function getHandle($handleName = "")
/**
* Returns the contents of the specified template handle.
* @param string $handleName The handle to return the contents for.
* @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))
return FALSE;
return false;
if (isset($this->HANDLES[$handleName]))
return $this->HANDLES[$handleName];
if (isset($this->templateHandles[$handleName]))
return $this->templateHandles[$handleName];
return FALSE;
return false;
}
// ************************************************************
// Prints a parsed template handle
function printHandle($handleName = "")
/**
* Prints a parsed template handle to the output stream.
* @param string $handleName The handle to print.
* @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
$this->HANDLES[$handleName] = preg_replace("/\{[~|\|]?(\w*?)\}/",
"", $this->HANDLES[$handleName]);
$this->templateHandles[$handleName] = preg_replace("/\{[~|]?(\w*?)}/",
"", $this->templateHandles[$handleName]);
if (isset($this->HANDLES[$handleName])) {
echo $this->HANDLES[$handleName];
return TRUE;
if (isset($this->templateHandles[$handleName])) {
echo $this->templateHandles[$handleName];
return true;
}
return FALSE;
return false;
}
// ************************************************************
// Deletes all variables set with the addVars() method
function clearVars()
/**
* Deletes all variables set with the addVars() method.
* @return void
*/
function clearVars(): void
{
if (!empty($this->PARSEVARS)) {
reset($this->PARSEVARS);
while (list($ref, $val) = each ($this->PARSEVARS))
unset($this->PARSEVARS[$ref]);
if (!empty($this->parserVariables)) {
reset($this->parserVariables);
foreach ($this->parserVariables as $ref => $val) {
unset($this->parserVariables[$ref]);
}
}
}
// ************************************************************
// Adds one or more variables.
// You can pass one associative array with $varname=>$value pairs
// or two strings ($varname, $value) to this function.
function addVars($varList, $varValue = "")
/**
* Adds one or more variables.
* You can pass one associative array with $varname=>$value pairs
* 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.
* @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)) {
reset($varList);
while (list($varname, $value) = each($varList)) {
foreach ($varList as $varname => $value) {
// Replace curly braces
if ($this->RPLBRACES == TRUE) {
$value = preg_replace(Array("/(\{)/", "/(\})/"),
Array("&#123;", "&#125;"),
if ($this->replaceBraces == true) {
$value = preg_replace(array("/(\{)/", "/(})/"),
array("&#123;", "&#125;"),
$value);
}
// Add/replace variable
if (!preg_match("/[^0-9a-z\-\_]/i", $varname))
$this->PARSEVARS[$varname] = $value;
if (!preg_match("/[^0-9a-z\-_]/i", $varname))
$this->parserVariables[$varname] = $value;
}
} else {
// Replace curly braces
if ($this->RPLBRACES == TRUE) {
$varValue = preg_replace(Array("/(\{)/", "/(\})/"),
Array("&#123;", "&#125;"),
if ($this->replaceBraces == true) {
$varValue = preg_replace(array("/(\{)/", "/(})/"),
array("&#123;", "&#125;"),
$varValue);
}
// Add/replace variable
if (!preg_match("/[^0-9a-z\-\_]/i", $varList))
$this->PARSEVARS[$varList] = $varValue;
if (!preg_match("/[^0-9a-z\-_]/i", $varList))
$this->parserVariables[$varList] = $varValue;
}
}
// ************************************************************
// Returns a value set by the addVars() method
function getVar($varName = "")
/**
* Returns a value set by the addVars() method.
* @param string $varName The variable to return the value of.
* @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 (isset($this->PARSEVARS[$varName]))
return $this->PARSEVARS[$varName];
return FALSE;
if (empty($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) {
$retVal = '';
$stmt = $GLOBALS['db']->prepare($query);
callBindParamArray($stmt, $bindArguments);
$stmt->execute();

View File

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

View File

@ -8,7 +8,7 @@
* of the
*
* Bundesanstalt Technisches Hilfswerk
* Provinzialstraße 93
* Provinzialstraße 93
* D-53127 Bonn
* Germany
* E-Mail: redaktion@thw.de
@ -28,7 +28,19 @@
* 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->execute();
$stmt->bind_result(
@ -42,7 +54,7 @@ function getStats() {
$stmt->fetch();
$GLOBALS['tpl']->addVars(Array(
$GLOBALS['tpl']->addVars(array(
'statsFragen' => sprintf('%0.d', $fragen),
'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)),
@ -55,7 +67,7 @@ function getStats() {
}
getStats();
$GLOBALS['tpl']->addTemplates(Array(
$GLOBALS['tpl']->addTemplates(array(
'content' => 'home'
));
?>

View File

@ -8,7 +8,7 @@
* of the
*
* Bundesanstalt Technisches Hilfswerk
* Provinzialstraße 93
* Provinzialstraße 93
* D-53127 Bonn
* Germany
* E-Mail: redaktion@thw.de
@ -44,7 +44,7 @@
break;
case 'bogen':
addBreadcrumb($_REQUEST['show'], 'Prüfungsbogen üben');
addBreadcrumb($_REQUEST['show'], 'Prüfungsbogen üben');
include('pruefbogen.inc.php');
break;
@ -54,28 +54,28 @@
break;
case 'ordnung':
addBreadcrumb($_REQUEST['show'], 'Prüfungsordnung');
$tpl->addVars('navOrdnung', 'current');
$tpl->addTemplates(Array('content' => 'ordnung'));
addBreadcrumb($_REQUEST['show'], 'Prüfungsordnung');
$GLOBALS['tpl']->addVars('navOrdnung', 'current');
$GLOBALS['tpl']->addTemplates(array('content' => 'ordnung'));
break;
case 'stats':
$tpl->addVars(Array(
$GLOBALS['tpl']->addVars(array(
// Statistik Zufallsfragen
'fragenBisher' => $_SESSION['stats']['Fragen_Bisher'],
'fragenRichtig' => $_SESSION['stats']['Fragen_Richtig'],
'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')) . '%',
// Statistik Prüfungsbögen
// Statistik Prüfungsbögen
'boegenBisher' => $_SESSION['stats']['Boegen_Bisher'],
'boegenRichtig' => $_SESSION['stats']['Boegen_Bestanden'],
'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')) . '%'
));
addBreadcrumb($_REQUEST['show'], 'Statistiken');
$tpl->addVars('navStats', 'current');
$tpl->addTemplates(Array('content' => 'stats'));
$GLOBALS['tpl']->addVars('navStats', 'current');
$GLOBALS['tpl']->addTemplates(array('content' => 'stats'));
break;
case "barrierefreiheit":
@ -85,18 +85,18 @@
case 'impressum':
addBreadcrumb($_REQUEST['show'], 'Impressum');
$tpl->addTemplates(Array('content' => 'impressum'));
$GLOBALS['tpl']->addTemplates(array('content' => 'impressum'));
break;
case 'datenschutz':
addBreadcrumb($_REQUEST['show'], 'Datenschutzhinweis');
$tpl->addTemplates(Array('content' => 'datenschutz'));
$GLOBALS['tpl']->addTemplates(array('content' => 'datenschutz'));
break;
case "downloads":
addBreadcrumb($_REQUEST["show"], "Offline-Version");
$tpl->addVars("navOffline", "current");
$tpl->addTemplates(Array("content" => "offline"));
$GLOBALS['tpl']->addVars("navOffline", "current");
$GLOBALS['tpl']->addTemplates(array("content" => "offline"));
break;
default:
@ -104,7 +104,5 @@
include('home.inc.php');
}
$tpl->parse('pageContent', 'content');
$tpl->printParse('pageMain', 'page-body');
?>
$GLOBALS['tpl']->parse('pageContent', 'content');
$GLOBALS['tpl']->printParse('pageMain', 'page-body');

View File

@ -30,10 +30,9 @@
header('Content-Type: text/html; charset=utf-8');
$GLOBALS['tpl'] = new Template('./templates/');
$tpl =& $GLOBALS['tpl'];
$GLOBALS['tpl'] = new Template(__DIR__ . '/templates/');
$tpl->addTemplates(Array(
$GLOBALS['tpl']->addTemplates(Array(
'page-body' => 'page-body',
'top-line' => 'top-line'
));
@ -60,14 +59,12 @@ if (isset($_REQUEST['jahr'])) {
$_SESSION['jahr'] = 2020;
}
srand(microtime()*(double)10000);
mt_srand(intval(microtime()) * 10000);
if ((isset($_COOKIE['stylesheet']) && $_COOKIE['stylesheet'] == 'barrierefrei')
|| isset($_POST['barrierefrei'])
|| (isset($_GET['style']) && $_GET['style'] == 'rg')) {
$tpl->addVars('extraStyleSheet', '<link href="rg-styles.css" rel="stylesheet" type="text/css" />');
} else {
$GLOBALS['tpl']->addVars('extraStyleSheet', '<link href="rg-styles.css" rel="stylesheet" type="text/css" />');
}
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
@ -78,14 +75,12 @@ if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$protocol = 'http';
}
$tpl->addVars(Array(
$GLOBALS['tpl']->addVars(Array(
// Globale Variablen
'scriptName' => $_SERVER['SCRIPT_NAME'],
'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
*
* Bundesanstalt Technisches Hilfswerk
* Provinzialstraße 93
* Provinzialstraße 93
* D-53127 Bonn
* Germany
* 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');
$tpl->addVars('navBogen', 'current');
$GLOBALS['tpl']->parseBlock('page-body', 'NavBogen', 'Sublinks');
$GLOBALS['tpl']->addVars('navBogen', 'current');
if (isset($_REQUEST['create']) && $_REQUEST['create'] == '1') {
// Neuen Bogen erstellen
@ -43,17 +43,20 @@ if (isset($_REQUEST['create']) && $_REQUEST['create'] == '1') {
// Werte initialisieren
$_SESSION['bogen']['StartTime'] = time();
$_SESSION['bogen']['Fragen'] = Array();
$_SESSION['bogen']['Fragen'] = array();
// Anz. Abschnitte und Fragen aus der DB holen
$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->execute();
$stmt->bind_result($questionId, $questionSection);
// Fragen in Array übertragen
// Fragen in Array übertragen
while ($stmt->fetch()) {
$fragen[$questionId] = $questionSection;
}
@ -74,13 +77,14 @@ if (isset($_REQUEST['create']) && $_REQUEST['create'] == '1') {
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,
// da shuffle() die Keys verwirft!
$fragen2 = Array();
foreach ($fragen As $key => $value) {
$fragen2 = array();
foreach ($fragen as $key => $value) {
array_push($fragen2, $key);
}
shuffle($fragen2);
for ($i = 0; $i < 40 - $sectionCount; $i++) {
array_push($_SESSION['bogen']['Fragen'], array_shift($fragen2));
@ -140,9 +144,9 @@ if (isset($_SESSION['bogen'])) {
. ',bestanden=bestanden+' . (($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']),
'zeit' => sprintf('%02d:%02d\'%02d', $zeit / 3600, ($zeit / 60) % 60, $zeit % 60),
'fragenRichtig' => $richtig,
@ -151,41 +155,42 @@ if (isset($_SESSION['bogen'])) {
'fragenFalschQuote' => sprintf('%.2f %%', $falsch / $fragen_cnt * 100)
));
if (($richtig / $fragen_cnt) >= 0.8)
$tpl->parseBlock('content', 'Bestanden', 'Ja');
else
$tpl->parseBlock('content', 'Bestanden', 'Nein');
if (($richtig / $fragen_cnt) >= 0.8) {
$GLOBALS['tpl']->parseBlock('content', 'Bestanden', 'Ja');
}
else {
$GLOBALS['tpl']->parseBlock('content', 'Bestanden', 'Nein');
}
for ($i = 0; $i < count($_SESSION['bogen']['Fragen']); $i++) {
if ($i > 0 && $i % 10 == 0) {
// 'Nach oben'-Zeile an Handle anhängen
$tpl->parseBlock('content', 'Aufloesung', 'Topline', TRUE);
// 'Nach oben'-Zeile an Handle anhängen
$GLOBALS['tpl']->parseBlock('content', 'Aufloesung', 'Topline', TRUE);
}
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']);
}
else {
} else {
// Fragen anzeigen
$tpl->addTemplates(Array(
$GLOBALS['tpl']->addTemplates(array(
'content' => 'bogen-fragen'
));
$tpl->addVars(Array(
$GLOBALS['tpl']->addVars(array(
'zeit' => date('G:i', $_SESSION['bogen']['StartTime'])
));
for ($i = 0; $i < count($_SESSION['bogen']['Fragen']); $i++) {
if ($i > 0 && $i % 10 == 0) {
$tpl->parseBlock('content', 'Bogen', 'Topline', TRUE);
$GLOBALS['tpl']->parseBlock('content', 'Bogen', 'Topline', TRUE);
}
// Frage aus DB holen
$question = getQuestionById($_SESSION['bogen']['Fragen'][$i]);
$tpl->addVars(Array(
$GLOBALS['tpl']->addVars(array(
'frageIndex' => $i + 1,
'frageID' => $question['ID'],
'frageNr' => $question['Nr'],
@ -197,20 +202,18 @@ if (isset($_SESSION['bogen'])) {
));
if ($question['Antwort3'] == '') {
$tpl->addVars('rowCnt', '2');
$tpl->delBlockHandle('content', 'ThreeRows');
}
else {
$tpl->addVars('rowCnt', '3');
$tpl->parseBlock('content', 'ThreeRows', 'Row');
$GLOBALS['tpl']->addVars('rowCnt', '2');
$GLOBALS['tpl']->delBlockHandle('content', 'ThreeRows');
} else {
$GLOBALS['tpl']->addVars('rowCnt', '3');
$GLOBALS['tpl']->parseBlock('content', 'ThreeRows', 'Row');
}
$tpl->parseBlock('content', 'Bogen', 'Frage', TRUE, TRUE);
$GLOBALS['tpl']->parseBlock('content', 'Bogen', 'Frage', TRUE, TRUE);
}
}
}
else {
$tpl->addVars('navBogenNeu', 'current');
$tpl->addTemplates(Array('content' => 'bogen-start'));
} else {
$GLOBALS['tpl']->addVars('navBogenNeu', 'current');
$GLOBALS['tpl']->addTemplates(array('content' => 'bogen-start'));
}

View File

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

View File

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

View File

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