added addStarter function to Event

This commit is contained in:
marko
2022-10-28 12:54:44 +02:00
parent 3e60b97050
commit c332fcdcd8
7 changed files with 483 additions and 1761 deletions

View File

@@ -1,3 +0,0 @@
<?php
?>

File diff suppressed because it is too large Load Diff

View File

@@ -1,223 +0,0 @@
<?php
require_once('./local/wkParticipoConf.php.inc');
require_once('./auth.php');
require_once('./local/db.php.inc');
require_once('./lib/wkParticipoLib.php.inc');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Wettkampfplanung der Judoka des CWSV</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php echo $login_status; ?>
<h1>Wettkampfplanung - Übersicht</h1>
<h2>Springe zu den ...</h2>
<a class="touchLink" href="#meldungen"><div>abge&shy;gebenen Meldungen.</div></a>
<a class="touchLink" href="#mitfahrgelegenheiten"><div>angemel&shy;deten Mitfahr&shy;gelegen&shy;heiten.</div></a>
<a class="touchLink" href="#wettkaempfen"><div>kommenden Wett&shy;kämpfen.</div></a>
<hr />
<?php
$mysqli = @new mysqli($db_server, $db_user, $db_password, $db_name);
if ($mysqli->connect_error) {
$message['error'] = 'Datenbankverbindung fehlgeschlagen: ' . $mysqli->connect_error;
echo $message['error']; die();
}
?>
<h2 id="meldungen">Meldungen zu kommenden Wettkämpfen</h2>
<?php
foreach( explode( ',', getUserData($mysqli, $_SESSION['user']['userId'])['kinder']) as $kindId){
$kindDaten = getUserData($mysqli, $kindId);
?>
<h3><?php echo $kindDaten['name'].", ".$kindDaten['vorname'].": ";?></h3>
<?php
// $wkEventData = getUsersCommingWkEvents($mysqli, $kindId);
$wkEventData = getUsersWkEvents($mysqli, $kindId);
if(empty($wkEventData)){
?>
<?php echo mb_convert_encoding($kindDaten['name'].", ".$kindDaten['vorname'], 'UTF-8');?> ist derzeit bei keinem Wettkampf eingeschrieben!
<?php
}
else{
foreach($wkEventData as $wkEvent){
?>
<h4><?php echo mb_convert_encoding($wkEvent['Veranstaltung'], 'UTF-8', 'ISO-8859-1');?></h4>
<?php print_r($wkEvent);?>
<ul>
<li>Datum: <?php echo mb_convert_encoding($wkEvent['Datum'], 'UTF-8', 'ISO-8859-1');?></li>
<li>Altersklassen: <?php echo mb_convert_encoding($wkEvent['Altersklassen'], 'UTF-8', 'ISO-8859-1');?></li>
</ul>
<a class="touchLink" href ="/ressourcen/phpLib/calendar.php?wkID=<?php echo $wkEvent['lfdeNr']?>"><div>Termin in Kalender übernehmen</div></a>
<form action="./showWkEvent.php" method="post">
<input type="hidden" name="f[eventId]" value="<?php echo (isset( $wkEvent['eventId'] ) ? $wkEvent['eventId'] : "");?>" />
<button type="submit">Detailansicht</button>
</form>
<?php
}
echo "</ul>";
}
}
?>
<h2 id="mitfahrgelegenheiten">Angemeldete Mitfahrgelegenheiten</h2>
<?php
$fahrten = array();
$fahrten = getUsersCommingFahrten($mysqli, $_SESSION['user']['userId']);
if( empty($fahrten) ){
?>
Keine Mitfahrangebote gefunden
<?php
}
else{
foreach($fahrten as $fahrt){
$mitfahrerData = getMitfahrer($mysqli, $fahrt['id']);
?>
<div class="wkBox">
<h3><?php echo (isset($fahrt['Veranstaltung']) ? mb_convert_encoding($fahrt['Veranstaltung'], 'UTF-8', 'ISO-8859-1') : "<fehlender Wettkampfname>" );?></h3>
<ul>
<li>Datum: <?php echo (isset($fahrt['Datum']) ? mb_convert_encoding($fahrt['Datum'], 'UTF-8', 'ISO-8859-1') : "<fehlendes Datum>" );?></li>
<li>Meldefrist: <?php echo (isset($fahrt['meldefrist']) ? mb_convert_encoding($fahrt['meldefrist'], 'UTF-8', 'ISO-8859-1') : "<fehlende Meldefrist>" );?></li>
<li>Altersklassen: <?php echo (isset($fahrt['Altersklassen']) ? mb_convert_encoding($fahrt['Altersklassen'], 'UTF-8', 'ISO-8859-1') : "<fehlende Altersklassen>" );?></li>
<li>Ort: <a href="<?php echo (isset($fahrt['Routenplaner']) ? mb_convert_encoding($fahrt['Routenplaner'], 'UTF-8', 'ISO-8859-1') : "" );?>"><?php echo (isset($fahrt['Ort']) ? mb_convert_encoding($fahrt['Ort'], 'UTF-8', 'ISO-8859-1') : "<fehlender Ort>" );?></a></li>
<li>Anzahl Plätze: <?php echo count($mitfahrerData)."/".$fahrt['plaetze'];?><ul><?php foreach($mitfahrerData as $mitfahrer){echo "<li>".$mitfahrer['name'].", ".$mitfahrer['vorname']."</li>";};?></ul></li>
</ul>
<a class="touchLink" href ="/ressourcen/phpLib/calendar.php?wkID=<?php echo $fahrt['lfdeNr']?>"><div>Termin in Kalender übernehmen</div></a>
<form action="./showWkEvent.php" method="post">
<input type="hidden" name="f[eventId]" value="<?php echo (isset( $fahrt['eventId'] ) ? $fahrt['eventId'] : "");?>" />
<button type="submit">Detailansicht</button>
</form>
</div>
<hr />
<?php
}
}
?>
<h2 id="wettkaempfen">Anstehende Wettkämpfe</h2>
<?php
$wkEvents = getCommingWkEvents($mysqli);
if( empty($wkEvents) ){
?>
<p>Momentan befinden sich anscheinend keine Wettkämpfe in Planung!</p>
<?php
}
else{
foreach( $wkEvents as $wk){
//print_r($wk);
?>
<div class="wkBox"><ul>
<li>Datum: <?php echo mb_convert_encoding($wk['Datum'], 'UTF-8', 'ISO-8859-1')?></li>
<li>Wettkampf: <?php echo mb_convert_encoding($wk['Veranstaltung'], 'UTF-8', 'ISO-8859-1')?></li>
<li>Altersklassen: <?php echo mb_convert_encoding($wk['Altersklassen'], 'UTF-8', 'ISO-8859-1')?></li>
<li>Meldefrist: <?php echo mb_convert_encoding($wk['meldefrist'], 'UTF-8', 'ISO-8859-1')?></li>
<li>angemeldete Starter:
<?php
$starters = getStarterForEvent($mysqli, $wk['id']);
if( empty($starters) ){
?>
Noch hat sich niemand für diesen Wettkampf gemeldet!
<?php
}
else{
echo count($starters);
}
?>
</li>
<?php
$fahrten = getFahrtenForEvent($mysqli, $wk['id']);
$anzPlätze = 0;
foreach($fahrten as $fahrt)
$anzPlätze += $fahrt['plaetze'];
echo "<li".( ($anzPlätze<count($starters)) ? " style=\"color: red\"" : "" ).">Anzahl Plätze: ".$anzPlätze."</li>";
?>
</ul>
<form action="./showWkEvent.php" method="post">
<input type="hidden" name="f[eventId]" value="<?php echo (isset( $wk['id'] ) ? $wk['id'] : "");?>" />
<button type="submit">Detailansicht</button>
</form>
<hr />
Für diesen Wettkampf ...
<form action="./addStarter.php" method="post">
<input type="hidden" name="f[eventId]" value=<?php echo ( isset( $wk['id'] ) ? $wk['id'] : "");?> />
<?php
if( date("Y-m-d") > $wk['meldefrist'] ){
?>
<button type="submit" disabled>ist die Meldefrist bereits abgelaufen!</button>
<?php
}
else{
?>
<button type="submit">einen Starter melden</button>
<?php
}
?>
</form>
<form action="./addFahrt.php" method="post">
<input type="hidden" name="f[eventId]" value="<?php echo ( isset( $wk['id'] ) ? $wk['id'] : "" );?>" />
<?php
// print_r($wk);
// echo $wk['id'];
if($wk['Datum'] > date("Y-m-d")){
?>
<button type="submit">eine Mitfahrgelegenheiten melden.</button>
<?php
}
else{
?>
<button type="submit" disabled>ist es leider zu spät, noch Mitfahrgelegenheiten hinzuzufügen.</button>
<?php
}
?>
</form>
</div>
<hr />
<?php
}
}
?>
<h2 id="ergebnisse">Letzte Ergebnisse</h2>
<ul>
<?php
foreach( explode( ',', getUserData($mysqli, $_SESSION['user']['userId'])['kinder']) as $kindId){
$kindDaten = getUserData($mysqli, $kindId);
echo "<li>".$kindDaten['name'].", ".$kindDaten['vorname'].":<ul>";
$ergebnisse = getUsersErgebnisse($mysqli, $kindId);
foreach( $ergebnisse as $ergebnis ){
?>
<li><?php echo mb_convert_encoding($ergebnis['Datum'], 'UTF-8', 'ISO-8859-1')?></li>
<li><?php echo mb_convert_encoding($ergebnis['Veranstaltung'], 'UTF-8', 'ISO-8859-1');?></li>
<li>Platz: <?php echo mb_convert_encoding($ergebnis['platz'], 'UTF-8', 'ISO-8859-1'); ?></li>
<?php
}
?>
</ul></li>
<?php
}
?>
</ul>
<?php
$mysqli->close();
?>
<!--Beginn der Einbindung des Counters-->
<?php
$chCounter_page_title = "Wettkampfplaner -- Übersicht";
$chCounter_page_url = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . "?user=".$_SESSION['user']['username'];
$chCounter_visible=0;
// include( $_SERVER['DOCUMENT_ROOT'].'/expCounter/counter.php');
?>
</body>
</html>

View File

@@ -1,5 +1,5 @@
<?php <?php
include_once("events.inc.php"); include_once 'events.inc.php';
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
@@ -9,7 +9,7 @@ include_once("events.inc.php");
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- shared imports (common css, MaterializeCss) --> <!-- shared imports (common css, MaterializeCss) -->
<?php readfile("./shared/imports.php");?> <?php readfile('./shared/imports.php'); ?>
<!-- inits for the materializeCss --> <!-- inits for the materializeCss -->
<script> <script>
@@ -52,8 +52,8 @@ include_once("events.inc.php");
}); });
</script> </script>
<title><?php echo($meta['title']);?></title> <title><?php echo($meta['title']); ?></title>
<meta name="description" content="<?php echo($meta['description']);?>" /> <meta name="description" content="<?php echo($meta['description']); ?>" />
<link rel="icon" href="<?echo($config['ressourceUrl']);?>/graphiken/icons/cwsv.ico" /> <link rel="icon" href="<?echo($config['ressourceUrl']);?>/graphiken/icons/cwsv.ico" />
<link rel="apple-touch-icon" href="<?echo($config['baseUrl']);?>/apple-touch-icon.png"> <link rel="apple-touch-icon" href="<?echo($config['baseUrl']);?>/apple-touch-icon.png">
@@ -63,17 +63,36 @@ include_once("events.inc.php");
<body> <body>
<header> <header>
<!-- The sidenav --> <!-- The sidenav -->
<?php require("./events.sidenav.inc.php");?> <?php require './events.sidenav.inc.php'; ?>
</header> </header>
<?php if($_SESSION['login']){ ?> <?php if ($_SESSION['login']) { ?>
<main> <main>
<?php
$eventList = participo::getEventStarter();
$htmlTable = null;
if ($eventList) {
$htmlTable = '<table>'
. '<thead><tr><th>Datum</th><th>Veranstaltung</th><th>Starter</th></tr></thead>'
. '<tbody>';
foreach ($eventList as $event) {
$htmlTable .= '<tr><td>' . $event['eventDate'] . '</td><td>' . $event['eventName'] . '</td><td>' . $event['userName'] . ', ' . $event['userFirstname'] . '</td></tr>';
}
$htmlTable .= '</tbody></table>';
echo('<h2 id="commingStarts">Aktuelle Einschreibungen</h2>');
echo($htmlTable);
} else {
echo($eventList ? $htmlTable : '<div>Keine Meldungen zu bevorstehenden Events');
}
?>
<h2 id="eventList">Übersicht anstehender Events</h2> <h2 id="eventList">Übersicht anstehender Events</h2>
<!-- Table with events--> <!-- Table with events-->
<?php echo( eventPlaner::getHtmlEventTable(eventPlaner::getCommingWkEvents()) );?> <?php echo(eventPlaner::getHtmlEventTable(eventPlaner::getCommingWkEvents())); ?>
<h2 id="detailedEventList">Detailansicht kommender Wettkämpfe</h2> <h2 id="detailedEventList">Detailansicht kommender Wettkämpfe</h2>
<?php foreach( eventPlaner::getCommingWkEvents() as $event ) echo($event->asHtmlCard());?> <?php foreach (eventPlaner::getCommingWkEvents() as $event) {
echo($event->asHtmlCard());
}?>
</main> </main>
<?php } ?> <?php } ?>
</body> </body>

View File

@@ -1,26 +1,26 @@
<?php <?php
require_once 'config/participo.php'; require_once 'config/participo.php';
require_once './local/cwsvJudo.php'; require_once './local/cwsvJudo.php';
require_once './lib/db.php'; // should be replaced require_once './lib/db.php'; // should be replaced
require_once './lib/api.php'; // should be replaced require_once './lib/api.php'; // should be replaced
require_once 'participoLib/participo.php'; require_once 'participoLib/participo.php';
require_once 'participoLib/planer.php'; require_once 'participoLib/planer.php';
require_once("config/phpcount.config.php"); require_once 'config/phpcount.config.php';
require_once("phpcount/phpcount.php"); require_once 'phpcount/phpcount.php';
PHPCount::AddHit("participo"); PHPCount::AddHit('participo');
dbConnector::connect( dbConnector::connect(
$cwsvJudoConfig['db']['host'], $cwsvJudoConfig['db']['host'],
$cwsvJudoConfig['db']['name'], $cwsvJudoConfig['db']['name'],
$cwsvJudoConfig['db']['user'], $cwsvJudoConfig['db']['user'],
$cwsvJudoConfig['db']['password'] $cwsvJudoConfig['db']['password']
); );
eventPlaner::setDbConnection(dbConnector::getDbConnection()); eventPlaner::setDbConnection(dbConnector::getDbConnection());
participo::authentificate(); participo::authentificate();
$userData = getUserData(dbConnector::getDbConnection(), $_SESSION['user']['userId']); $userData = getUserData(dbConnector::getDbConnection(), $_SESSION['user']['userId']);
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -123,13 +123,13 @@ echo(
], ],
])->htmlCode() ])->htmlCode()
) )
?> ?>
</div> <!-- mitmachApps --> </div> <!-- mitmachApps -->
<h2>Zur Information</h2> <h2>Zur Information</h2>
<div class="row" id="infoApps"> <div class="row" id="infoApps">
<?php <?php
echo( echo(
AppCard::fromArray([ AppCard::fromArray([
'link' => 'infoZettel', 'link' => 'infoZettel',
'title' => 'Infozettel', 'title' => 'Infozettel',
@@ -148,7 +148,7 @@ echo(
AppCardAction::fromArray(['caption' => 'Anwesenheit', 'link' => 'attendance']), AppCardAction::fromArray(['caption' => 'Anwesenheit', 'link' => 'attendance']),
], ],
])->htmlCode() ])->htmlCode()
); );
// @todo attendanceApp?> // @todo attendanceApp?>
</div> <!-- infoApps --> </div> <!-- infoApps -->
@@ -206,20 +206,6 @@ if (participo::isUserAdmin($userData['id'])) {
])->htmlCode() . ])->htmlCode() .
'</div>' '</div>'
); );
echo("<h2 id=\"commingStarts\">Aktuelle Einschreibungen</h2>");
$eventList = participo::getEventStarter("2022-01-01");
$htmlTable = null;
if($eventList){
$htmlTable = "<table>"
."<thead><tr><th>Datum</th><th>Veranstaltung</th><th>Starter</th></tr></thead>"
."<tbody>";
foreach($eventList as $event){
$htmlTable .= "<tr><td>".$event['eventDate']."</td><td>".$event['eventName']."</td><td>".$event['userName'].", ".$event['userFirstname']."</td></tr>";
}
$htmlTable .= "</tbody></table>";
}
echo($eventList?$htmlTable:"<div>Keine Meldungen zu bevorstehenden Events");
} ?> } ?>
</main> </main>
<?php <?php

View File

@@ -1,9 +1,11 @@
<?php <?php
// require_once("spyc/Spyc.php"); // require_once("spyc/Spyc.php");
class participo{ class participo
{
private static $db = null; private static $db = null;
private static $message = ['error' => NULL, 'success' => NULL, 'notice' => NULL]; private static $message = ['error' => null, 'success' => null, 'notice' => null];
private static $userId = null;
/** /**
* Returns the current login status * Returns the current login status
@@ -12,7 +14,8 @@ class participo{
* *
* @return The login status or false if none is set so far * @return The login status or false if none is set so far
*/ */
static public function isLoginValid(){ public static function isLoginValid()
{
return ($_SESSION['login'] ?? false); return ($_SESSION['login'] ?? false);
} }
@@ -21,13 +24,14 @@ class participo{
* *
* @return string htmlEntity showing the login status * @return string htmlEntity showing the login status
*/ */
static public function htmlLoginStatus(){ public static function htmlLoginStatus()
{
return return
"<div style=\"border: 1px solid black\">". '<div style="border: 1px solid black">' .
"Datum: ".date("Y-m-d")."<br />". 'Datum: ' . date('Y-m-d') . '<br />' .
"Angemeldet als <strong>".htmlspecialchars($_SESSION['user']['username'])."</strong>.<br />". 'Angemeldet als <strong>' . htmlspecialchars($_SESSION['user']['username']) . '</strong>.<br />' .
"<a href=\"logout.php\">Sitzung beenden</a>". '<a href="logout.php">Sitzung beenden</a>' .
"</div>"; '</div>';
} }
/** /**
@@ -36,16 +40,25 @@ class participo{
* *
* @retval void * @retval void
*/ */
static public function authentificate(){ public static function authentificate()
{
session_start(); session_start();
if ( !self::isLoginValid() ) { if (!self::isLoginValid()) {
header("Location: login?returnToUrl=".urlencode($_SERVER['REQUEST_URI'].($_POST['fragment'] ?? "")), TRUE, 301); header('Location: login?returnToUrl=' . urlencode($_SERVER['REQUEST_URI'] . ($_POST['fragment'] ?? '')), true, 301);
exit(); // should'nt matter exit(); // should'nt matter
} }
participo::$userId = $_SESSION['user']['userId'];
} }
static public function getMessages(){return self::$message;} public static function getMessages()
static public function addMessage($type, $message){self::$message[$type] = (self::$message[$type] ?? "").$message;} {
return self::$message;
}
public static function addMessage($type, $message)
{
self::$message[$type] = (self::$message[$type] ?? '') . $message;
}
/** /**
* check password for user * check password for user
@@ -56,11 +69,12 @@ class participo{
* @retval true $password belongs to $loginName * @retval true $password belongs to $loginName
* @retval false otherwise * @retval false otherwise
*/ */
static public function checkCredentials($loginName, $password){ public static function checkCredentials($loginName, $password)
{
sleep(1); // just to discourage brute force attacks sleep(1); // just to discourage brute force attacks
// Check for dbConnection // Check for dbConnection
if(!dbConnector::getDbConnection()){ if (!dbConnector::getDbConnection()) {
self::addMessage('error', "<div>No DbConnection available</div>"); self::addMessage('error', '<div>No DbConnection available</div>');
return false; return false;
} }
@@ -68,33 +82,33 @@ class participo{
// @todo check for e.g., len(user)=1 // @todo check for e.g., len(user)=1
// @todo getUser? // @todo getUser?
$user = dbConnector::query( $user = dbConnector::query(
"SELECT `id`, `loginName`, `pwHash`, `config` FROM `wkParticipo_Users` WHERE `loginName` = :loginName", 'SELECT `id`, `loginName`, `pwHash`, `config` FROM `wkParticipo_Users` WHERE `loginName` = :loginName',
['loginName' => ['value'=>$loginName, 'data_type'=>PDO::PARAM_STR]] ['loginName' => ['value' => $loginName, 'data_type' => PDO::PARAM_STR]]
); );
$user = $user[0]; $user = $user[0];
// If there is no such user OR the password isn't valid the login fails // If there is no such user OR the password isn't valid the login fails
if( empty($user) || !password_verify( $password, $user['pwHash'])){ if (empty($user) || !password_verify($password, $user['pwHash'])) {
sleep(5); // discourage brute force attacks sleep(5); // discourage brute force attacks
self::addMessage('error', "<div>Falsches Passwort oder LoginName</div>"); self::addMessage('error', '<div>Falsches Passwort oder LoginName</div>');
return false; return false;
} }
session_start(); session_start();
// case valid login: Set the session data // case valid login: Set the session data
$_SESSION = array( $_SESSION = [
'login' => true, 'login' => true,
'user' => array( 'user' => [
'username' => $user['loginName'], 'username' => $user['loginName'],
'userId' => $user['id'], 'userId' => $user['id'],
'userConfig' => json_decode($user['config'], true) 'userConfig' => json_decode($user['config'], true)
) ]
); ];
// Logging Logins // Logging Logins
logLoginsToJsonFile($_SESSION['user']['username']); logLoginsToJsonFile($_SESSION['user']['username']);
self::addMessage('success', "<div>Anmeldung erfolgreich</div>"); self::addMessage('success', '<div>Anmeldung erfolgreich</div>');
return true; return true;
} }
@@ -105,8 +119,9 @@ class participo{
* @retval true user with id $userId has attribute "isAdmin" * @retval true user with id $userId has attribute "isAdmin"
* @retval false otherwise * @retval false otherwise
*/ */
static function isUserAdmin($userId){ public static function isUserAdmin($userId)
return self::hasUserAttribute( $userId, "isAdmin"); {
return self::hasUserAttribute($userId, 'isAdmin');
} }
/** /**
@@ -116,7 +131,8 @@ class participo{
* @param [type] $attributeName string name of the attribute to check * @param [type] $attributeName string name of the attribute to check
* @return boolean * @return boolean
*/ */
static public function hasUserAttribute($userId, $attributeName){ public static function hasUserAttribute($userId, $attributeName)
{
// sqlQuery: Select the user if it has the given attribute // sqlQuery: Select the user if it has the given attribute
$query = <<<SQL $query = <<<SQL
SELECT `wkParticipo_user<=>userAttributes`.userId, `wkParticipo_userAttributes`.name SELECT `wkParticipo_user<=>userAttributes`.userId, `wkParticipo_userAttributes`.name
@@ -124,37 +140,41 @@ FROM `wkParticipo_user<=>userAttributes` LEFT JOIN `wkParticipo_userAttributes`
ON `wkParticipo_user<=>userAttributes`.`attributeId` = `wkParticipo_userAttributes`.`id` ON `wkParticipo_user<=>userAttributes`.`attributeId` = `wkParticipo_userAttributes`.`id`
WHERE `wkParticipo_userAttributes`.name = :attributeName AND userId=:userId; WHERE `wkParticipo_userAttributes`.name = :attributeName AND userId=:userId;
SQL; SQL;
$params = array( $params = [
':userId' => array('value'=>$userId, 'data_type'=>PDO::PARAM_INT), ':userId' => ['value' => $userId, 'data_type' => PDO::PARAM_INT],
':attributeName' => array('value'=>$attributeName, 'data_type'=>PDO::PARAM_STR) ':attributeName' => ['value' => $attributeName, 'data_type' => PDO::PARAM_STR]
); ];
$attributedUsers = dbConnector::query($query, $params); $attributedUsers = dbConnector::query($query, $params);
// Since the id should be unique, there should only be one result this is just for dealing with empty arrays // Since the id should be unique, there should only be one result this is just for dealing with empty arrays
foreach($attributedUsers as $u) foreach ($attributedUsers as $u) {
if($u['userId']==$userId) if ($u['userId'] == $userId) {
return true; return true;
}
}
return false; return false;
} }
public static function getEventStarter($sinceDate = null)
static public function getEventStarter($sinceDate=null){ {
if(!$sinceDate) $userId = $_SESSION['user']['userId'];
$sinceDate = "CURDATE()"; if (!$sinceDate) {
else $sinceDate = 'CURDATE()';
$sinceDate = "DATE(\"".$sinceDate."\")"; } else {
$sinceDate = 'DATE("' . $sinceDate . '")';
}
$query = <<<SQL $query = <<<SQL
SELECT SELECT
`wkParticipo_Events`.`date` as eventDate `wkParticipo_Events`.`date` as eventDate
, `wkParticipo_Starter`.`id` as starterId , `wkParticipo_Starter`.`id` as starterId
, `wkParticipo_Users`.`name` as userName , `wkParticipo_Users`.`name` as userName
, `wkParticipo_Users`.`vorname` as userFirstname , `wkParticipo_Users`.`vorname` as userFirstname
, `wkParticipo_Events`.`date` as eventDate
, `wettkampfkalender`.`veranstaltung` as eventName , `wettkampfkalender`.`veranstaltung` as eventName
FROM `wkParticipo_Starter` FROM `wkParticipo_Starter`
LEFT JOIN `wkParticipo_Users` ON `wkParticipo_Starter`.`userId` = `wkParticipo_Users`.`id` LEFT JOIN `wkParticipo_Users` ON `wkParticipo_Starter`.`userId` = `wkParticipo_Users`.`id`
LEFT JOIN `wkParticipo_Events` ON `wkParticipo_Starter`.`eventId` = `wkParticipo_Events`.`id` LEFT JOIN `wkParticipo_Events` ON `wkParticipo_Starter`.`eventId` = `wkParticipo_Events`.`id`
LEFT JOIN `wettkampfkalender` ON `wkParticipo_Events`.`wkId` = `wettkampfkalender`.`lfdeNr` LEFT JOIN `wettkampfkalender` ON `wkParticipo_Events`.`wkId` = `wettkampfkalender`.`lfdeNr`
WHERE `wkParticipo_Events`.`date` >= $sinceDate LEFT JOIN `vormundschaft` ON `wkParticipo_Users`.`id` = `vormundschaft`.`kidId`
WHERE `wkParticipo_Events`.`date` >= $sinceDate AND `vormundschaft`.`userId` = $userId
ORDER BY `wkParticipo_Events`.`date` DESC; ORDER BY `wkParticipo_Events`.`date` DESC;
SQL; SQL;
$commingStarts = dbConnector::query($query); $commingStarts = dbConnector::query($query);
@@ -166,37 +186,44 @@ SQL;
/** /**
* Action element of an MaterializeCss (App-)card * Action element of an MaterializeCss (App-)card
*/ */
class AppCardAction{ class AppCardAction
{
private $caption = null; //< Caption for the action private $caption = null; //< Caption for the action
private $link = "."; //< link for the action private $link = '.'; //< link for the action
/** /**
* Constructor for the AppAction * Constructor for the AppAction
* *
* @param string $caption caption for the action * @param string $caption caption for the action
* @param string $link link to the action * @param string $link link to the action
*/ */
function __construct( $caption, $link = "." ){ public function __construct($caption, $link = '.')
{
//! @todo input sanitation //! @todo input sanitation
$this->link = $link; $this->link = $link;
$this->caption = $caption; $this->caption = $caption;
} }
/** /**
* Create htmlCode for the action * Create htmlCode for the action
* *
* @return string with htmlCode of the action * @return string with htmlCode of the action
*/ */
function htmlCode(){ public function htmlCode()
return "<a href=\"".$this->link."\">".$this->caption."</a>"; {
return '<a href="' . $this->link . '">' . $this->caption . '</a>';
} }
/** /**
* Create AppCardAction from assoziative array * Create AppCardAction from assoziative array
* *
* @param array $member array with the member values * @param array $member array with the member values
* @return AppCardAction * @return AppCardAction
*/ */
static public function fromArray($member){ public static function fromArray($member)
{
$caption = $member['caption'] ?? null; $caption = $member['caption'] ?? null;
$link = $member['link'] ?? "."; $link = $member['link'] ?? '.';
return new AppCardAction($caption, $link); return new AppCardAction($caption, $link);
} }
} }
@@ -204,12 +231,14 @@ class AppCardAction{
/** /**
* MaterializeCss card for an App * MaterializeCss card for an App
*/ */
class AppCard{ class AppCard
private $title = ""; //< title of the card {
private $description = ""; //< description of the App private $title = ''; //< title of the card
private $description = ''; //< description of the App
private $link = null; //< link for the card-content private $link = null; //< link for the card-content
private $imgUrl = null; //< url for an image right under the title private $imgUrl = null; //< url for an image right under the title
private $actionList = []; //< list of actions for the bottom of the card private $actionList = []; //< list of actions for the bottom of the card
/** /**
* Constructor for the AppCard * Constructor for the AppCard
* *
@@ -219,7 +248,8 @@ class AppCard{
* @param string $imgUrl url for an image right under the title * @param string $imgUrl url for an image right under the title
* @param array $actionList list of actions at the bottom of the card * @param array $actionList list of actions at the bottom of the card
*/ */
function __construct($title, $description, $link=null, $imgUrl=null, $actionList=[]){ public function __construct($title, $description, $link = null, $imgUrl = null, $actionList = [])
{
//! @todo input sanitation //! @todo input sanitation
$this->title = $title; $this->title = $title;
$this->description = $description; $this->description = $description;
@@ -227,38 +257,42 @@ class AppCard{
$this->imgUrl = $imgUrl; $this->imgUrl = $imgUrl;
$this->actionList = $actionList; $this->actionList = $actionList;
} }
/** /**
* Create htmlCode for the AppCard * Create htmlCode for the AppCard
* *
* @return string html code for the AppCard * @return string html code for the AppCard
*/ */
public function htmlCode($options=[]){ public function htmlCode($options = [])
$extraClass = $options['extraClass'] ?? ""; {
$actionListCode = ""; $extraClass = $options['extraClass'] ?? '';
foreach($this->actionList as $a){ $actionListCode = '';
foreach ($this->actionList as $a) {
$actionListCode .= $a->htmlCode(); $actionListCode .= $a->htmlCode();
} }
return return
"<div style=\"padding:1%;\" class=\"col s12 m6 ".$extraClass."\">". '<div style="padding:1%;" class="col s12 m6 ' . $extraClass . '">' .
"<div style=\"margin:1%;\" class=\"card blue-grey darken-1\">". '<div style="margin:1%;" class="card blue-grey darken-1">' .
"<div class=\"card-content white-text\">". '<div class="card-content white-text">' .
(($this->link!=null)?("<a href=\"".$this->link."\">"):(""))."<span class=\"card-title\">".$this->title."</span>".(($this->link!=null)?("</a>"):("")). (($this->link != null) ? ('<a href="' . $this->link . '">') : ('')) . '<span class="card-title">' . $this->title . '</span>' . (($this->link != null) ? ('</a>') : ('')) .
(($this->imgUrl!=null)?("<img alt=\"".$this->title."\" style=\"display:block;margin-left:auto;margin-right:auto;max-height:10vh;\" class=\"responsive-img\" src=\"".$this->imgUrl."\" />"):("")). (($this->imgUrl != null) ? ('<img alt="' . $this->title . '" style="display:block;margin-left:auto;margin-right:auto;max-height:10vh;" class="responsive-img" src="' . $this->imgUrl . '" />') : ('')) .
"<p>".$this->description."</p>". '<p>' . $this->description . '</p>' .
"</div>". '</div>' .
"<div class=\"card-action\">".$actionListCode."</div>". '<div class="card-action">' . $actionListCode . '</div>' .
"</div>". '</div>' .
"</div>"; '</div>';
} }
/** /**
* Create AppCard from an associative array * Create AppCard from an associative array
* *
* @param array $member array with member as keys and values as the member values * @param array $member array with member as keys and values as the member values
* @return AppCard from array values * @return AppCard from array values
*/ */
static public function fromArray($member){ public static function fromArray($member)
$title = $member['title'] ?? ""; {
$description = $member['description'] ?? ""; $title = $member['title'] ?? '';
$description = $member['description'] ?? '';
$link = $member['link'] ?? null; $link = $member['link'] ?? null;
$imgUrl = $member['imgUrl'] ?? null; $imgUrl = $member['imgUrl'] ?? null;
$actionList = $member['actions'] ?? []; $actionList = $member['actions'] ?? [];
@@ -273,52 +307,54 @@ class AppCard{
* @param string $jsonFileName path to the json file with the logged logins * @param string $jsonFileName path to the json file with the logged logins
* @return string Html table of users last logins * @return string Html table of users last logins
*/ */
function lastLoginTable($jsonFileName="lastLogins.json"){ function lastLoginTable($jsonFileName = 'lastLogins.json')
$lastLogins=json_decode( file_get_contents($jsonFileName), true); {
$lastLogins = json_decode(file_get_contents($jsonFileName), true);
$lastLoginsTable = $lastLoginsTable =
"<table>". '<table>' .
"<thead><tr><th>userName</th><th>lastLogins</th></tr></thead>". '<thead><tr><th>userName</th><th>lastLogins</th></tr></thead>' .
"<tbody>"; '<tbody>';
foreach( $lastLogins as $userName => $lastLogins ){ foreach ($lastLogins as $userName => $lastLogins) {
$lastLoginsTable .= $lastLoginsTable .=
"<tr><td>".$userName."</td><td>".$lastLogins['lastLogins'][0]."</td></tr>"; '<tr><td>' . $userName . '</td><td>' . $lastLogins['lastLogins'][0] . '</td></tr>';
} }
$lastLoginsTable .= "</tbody></table>"; $lastLoginsTable .= '</tbody></table>';
return $lastLoginsTable; return $lastLoginsTable;
} }
/// Eine Fehler/Warnung/Notiz/Erfolgsmeldung als divBox im String zurückgeben /// Eine Fehler/Warnung/Notiz/Erfolgsmeldung als divBox im String zurückgeben
function htmlRetMessage($anRetMessage){ function htmlRetMessage($anRetMessage)
$retHtmlString = ""; {
if( !empty($anRetMessage) ){ $retHtmlString = '';
$retHtmlString .= "<div style=\"border: 1px solid;\">"; if (!empty($anRetMessage)) {
if( !empty($anRetMessage['error']) ){ $retHtmlString .= '<div style="border: 1px solid;">';
$retHtmlString .= "<div style=\"border: 1px solid;\">"; if (!empty($anRetMessage['error'])) {
$retHtmlString .= "ERROR:<br />"; $retHtmlString .= '<div style="border: 1px solid;">';
$retHtmlString .= 'ERROR:<br />';
$retHtmlString .= $anRetMessage['error']; $retHtmlString .= $anRetMessage['error'];
$retHtmlString .= "</div>"; $retHtmlString .= '</div>';
} }
if( !empty($anRetMessage['warning']) ){ if (!empty($anRetMessage['warning'])) {
$retHtmlString .= "<div style=\"border: 1px solid;\">"; $retHtmlString .= '<div style="border: 1px solid;">';
$retHtmlString .= "WARNING:<br />"; $retHtmlString .= 'WARNING:<br />';
$retHtmlString .= $anRetMessage['warning']; $retHtmlString .= $anRetMessage['warning'];
$retHtmlString .= "</div>"; $retHtmlString .= '</div>';
} }
if( !empty($anRetMessage['notice']) ){ if (!empty($anRetMessage['notice'])) {
$retHtmlString .= "<div style=\"border: 1px solid;\">"; $retHtmlString .= '<div style="border: 1px solid;">';
$retHtmlString .= "Info:<br />"; $retHtmlString .= 'Info:<br />';
$retHtmlString .= $anRetMessage['notice']; $retHtmlString .= $anRetMessage['notice'];
$retHtmlString .= "</div>"; $retHtmlString .= '</div>';
} }
if( !empty($anRetMessage['success']) ){ if (!empty($anRetMessage['success'])) {
$retHtmlString .= "<div style=\"border: 1px solid;\">"; $retHtmlString .= '<div style="border: 1px solid;">';
$retHtmlString .= "SUCCESS:<br />"; $retHtmlString .= 'SUCCESS:<br />';
$retHtmlString .= $anRetMessage['success']; $retHtmlString .= $anRetMessage['success'];
$retHtmlString .= "</div>"; $retHtmlString .= '</div>';
} }
$retHtmlString .= "</div>"; $retHtmlString .= '</div>';
} }
return $retHtmlString; return $retHtmlString;
} }
/** /**
@@ -327,15 +363,16 @@ return $retHtmlString;
* @param string $fileName filename of the markdown file * @param string $fileName filename of the markdown file
* @return array assocative array('yaml'=>array(..), 'mdText'=>string) containing the yamlHeader as associative array and the markdown text as string * @return array assocative array('yaml'=>array(..), 'mdText'=>string) containing the yamlHeader as associative array and the markdown text as string
*/ */
function loadMarkdownFile($fileName){ function loadMarkdownFile($fileName)
{
// load the whole file // load the whole file
$fileText = file_get_contents($fileName); $fileText = file_get_contents($fileName);
// split at '---' to get ((),yamls,array) // split at '---' to get ((),yamls,array)
$fileParts = preg_split('/[\n]*[-]{3}[\n]/', $fileText, 3); $fileParts = preg_split('/[\n]*[-]{3}[\n]/', $fileText, 3);
// not all mdfiles have a yamlHeader, so the mdText can be at different indices // not all mdfiles have a yamlHeader, so the mdText can be at different indices
$yaml=[]; $yaml = [];
$mdText = ""; $mdText = '';
switch( count($fileParts) ){ switch(count($fileParts)) {
case 1:{ case 1:{
$mdText = $fileParts[0]; $mdText = $fileParts[0];
break; break;
@@ -348,25 +385,22 @@ function loadMarkdownFile($fileName){
default:{ default:{
$mdText = $fileText; $mdText = $fileText;
} }
} }
// get a title, if none is in the markdown // get a title, if none is in the markdown
if(!array_key_exists('title', $yaml)){ if (!array_key_exists('title', $yaml)) {
// find the first heading, set it as header and remove it from the markdown // find the first heading, set it as header and remove it from the markdown
if( preg_match("/^#(.*)$/m", $mdText, $matches) ){ if (preg_match('/^#(.*)$/m', $mdText, $matches)) {
$yaml['title'] = $matches[1]; $yaml['title'] = $matches[1];
$mdText = preg_replace("/^#(.*)$/m", "", $mdText, 1); $mdText = preg_replace('/^#(.*)$/m', '', $mdText, 1);
} } else {
else{
// fallback for the title, if not even one heading is found // fallback for the title, if not even one heading is found
$yaml['title'] = "<fehlender Titel>"; $yaml['title'] = '<fehlender Titel>';
} }
} }
return array( return [
'yaml' => $yaml 'yaml' => $yaml, 'mdText' => $mdText
, 'mdText' => $mdText ];
);
} }
/** /**
@@ -376,20 +410,22 @@ function loadMarkdownFile($fileName){
* @param string $fileName filename to log to * @param string $fileName filename to log to
* @return void * @return void
*/ */
function logLoginsToJsonFile($userName, $fileName="lastLogins.json"){ function logLoginsToJsonFile($userName, $fileName = 'lastLogins.json')
try{ {
try {
$lastLogins = json_decode(file_get_contents($fileName), true); $lastLogins = json_decode(file_get_contents($fileName), true);
if ($lastLogins == NULL){ if ($lastLogins == null) {
return; return;
} }
if(!array_key_exists($userName, $lastLogins)) if (!array_key_exists($userName, $lastLogins)) {
$lastLogins[$userName] = []; $lastLogins[$userName] = [];
if(!array_key_exists('lastLogins', $lastLogins[$userName]))
$lastLogins[$userName]['lastLogins'] = [];
$lastLogins[$userName]['lastLogins'] = array_merge( array( date('Y-m-d H:i:s') ), $lastLogins[$userName]['lastLogins'] );
file_put_contents($fileName, json_encode($lastLogins));
} }
catch (Exception $e){ if (!array_key_exists('lastLogins', $lastLogins[$userName])) {
$lastLogins[$userName]['lastLogins'] = [];
}
$lastLogins[$userName]['lastLogins'] = array_merge([date('Y-m-d H:i:s')], $lastLogins[$userName]['lastLogins']);
file_put_contents($fileName, json_encode($lastLogins));
} catch (Exception $e) {
// silently ignore errors // silently ignore errors
} }
} }
@@ -397,15 +433,20 @@ function logLoginsToJsonFile($userName, $fileName="lastLogins.json"){
/** /**
* interface for connecting and communicating with a database * interface for connecting and communicating with a database
*/ */
class dbConnector{ class dbConnector
static private $db = null; {
private static $db = null;
// connect to the database // connect to the database
public static function connect($hostname, $dbName, $user, $password){ public static function connect($hostname, $dbName, $user, $password)
return self::setDbConnection( self::connectToPdo($hostname, $dbName, $user, $password) ); {
return self::setDbConnection(self::connectToPdo($hostname, $dbName, $user, $password));
} }
public static function getDbConnection(){return self::$db;} public static function getDbConnection()
{
return self::$db;
}
/// perform a pdo-query /// perform a pdo-query
/// ///
@@ -414,11 +455,18 @@ class dbConnector{
/// ':userId' => array('value'=>$anUserId, 'data_type'=>PDO::PARAM_INT), /// ':userId' => array('value'=>$anUserId, 'data_type'=>PDO::PARAM_INT),
/// ':attributeId'=> array('value'=>$anAttributeId, 'data_type'=>PDO::PARAM_INT) ) /// ':attributeId'=> array('value'=>$anAttributeId, 'data_type'=>PDO::PARAM_INT) )
/// @param $someOption /// @param $someOption
public static function query($aQueryString, $aBindArray = array(), $someOptions = array()){ public static function query($aQueryString, $aBindArray = [], $someOptions = [])
{
// Standardbelegungen // Standardbelegungen
if( empty($someOptions['dbCharset' ]) ) $someOptions['dbCharset' ] = "ISO-8859-1"; if (empty($someOptions['dbCharset'])) {
if( empty($someOptions['outCharset']) ) $someOptions['outCharset'] = "UTF-8"; $someOptions['dbCharset'] = 'ISO-8859-1';
if( empty($someOptions['dontFetch' ]) ) $someOptions['dontFetch' ] = false; }
if (empty($someOptions['outCharset'])) {
$someOptions['outCharset'] = 'UTF-8';
}
if (empty($someOptions['dontFetch'])) {
$someOptions['dontFetch'] = false;
}
/// @toDo: Bisher wird nur die Rückgabe konvertiert. Eigentlich muss /// @toDo: Bisher wird nur die Rückgabe konvertiert. Eigentlich muss
/// doch auch die Eingabe konvertiert werden. Aber das jetzt /// doch auch die Eingabe konvertiert werden. Aber das jetzt
@@ -426,41 +474,41 @@ class dbConnector{
/// als UTF8 in latin1(?) gespeichert. /// als UTF8 in latin1(?) gespeichert.
/// @toDo: Die Standardwerte sollten vielleicht aus einer config /// @toDo: Die Standardwerte sollten vielleicht aus einer config
/// kommen, nicht hardcoded /// kommen, nicht hardcoded
try{ try {
$pdoStatement = self::$db->prepare( $aQueryString ); $pdoStatement = self::$db->prepare($aQueryString);
foreach( $aBindArray as $bindName => $bind ){ foreach ($aBindArray as $bindName => $bind) {
if( $bind['data_type'] == PDO::PARAM_STR) if ($bind['data_type'] == PDO::PARAM_STR) {
$bind['value'] = iconv( $bind['value'] = iconv(
$someOptions['outCharset'], $someOptions['outCharset'],
$someOptions['dbCharset'], $someOptions['dbCharset'],
$bind['value'] $bind['value']
); );
}
$pdoStatement->bindValue( $pdoStatement->bindValue(
$bindName, $bindName,
$bind['value'], $bind['value'],
(isset($bind['data_type'])?$bind['data_type']:PDO::PARAM_STR) (isset($bind['data_type']) ? $bind['data_type'] : PDO::PARAM_STR)
); );
} }
$pdoResult = $pdoStatement->execute(); $pdoResult = $pdoStatement->execute();
if(!$pdoResult){ if (!$pdoResult) {
echo("Error during dbQuery!\n"); echo("Error during dbQuery!\n");
echo("DB-Error:\n"); var_dump(self::$db->errorInfo()); echo("DB-Error:\n");
var_dump(self::$db->errorInfo());
} }
if($someOptions['dontFetch']){ if ($someOptions['dontFetch']) {
$ret = NULL; $ret = null;
} } else {
else{
$ret = $pdoStatement->fetchAll(PDO::FETCH_ASSOC); $ret = $pdoStatement->fetchAll(PDO::FETCH_ASSOC);
} }
} } catch(PDOException $db_error) {
catch(PDOException $db_error){ print 'Error!: ' . $db_error->getMessage() . '<br/>';
print "Error!: " . $db_error->getMessage() . "<br/>";
return null; return null;
} }
// Zeichensatzkonvertierung // Zeichensatzkonvertierung
if( is_array($ret) ){ if (is_array($ret)) {
foreach($ret as &$entry){ foreach ($ret as &$entry) {
array_walk( array_walk(
$entry, $entry,
function (&$value, $key, $someOptions) { function (&$value, $key, $someOptions) {
@@ -474,40 +522,39 @@ class dbConnector{
} }
// get a Connection to the database // get a Connection to the database
static private function connectToPdo($hostname, $dbName, $user, $password){ private static function connectToPdo($hostname, $dbName, $user, $password)
$dbConnection=null; {
try{ $dbConnection = null;
try {
$dbConnection = new PDO( $dbConnection = new PDO(
'mysql:host='.$hostname.';dbname='.$dbName, 'mysql:host=' . $hostname . ';dbname=' . $dbName,
$user, $user,
$password $password
); );
} } catch(PDOException $dbError) {
catch(PDOException $dbError){ echo('Error whilst getting a dbConnection!: ' . $dbError->getMessage());
echo( "Error whilst getting a dbConnection!: " . $dbError->getMessage() );
} }
return $dbConnection; return $dbConnection;
} }
// set the dbConnection (just setting, no establishing) // set the dbConnection (just setting, no establishing)
private static function setDbConnection($dbConnection){ private static function setDbConnection($dbConnection)
{
$success = false; $success = false;
if($dbConnection instanceof PDO){ if ($dbConnection instanceof PDO) {
self::$db = $dbConnection; self::$db = $dbConnection;
$success = true; $success = true;
} } else {
else{
self::$db = null; self::$db = null;
} }
} }
} }
/** /**
* User for the Participo system * User for the Participo system
*/ */
class User{ class User
{
private $id; private $id;
private $loginName; private $loginName;
private $name; private $name;
@@ -521,7 +568,7 @@ class User{
$this->loginName = $loginName; $this->loginName = $loginName;
$this->name = $name; $this->name = $name;
$this->firstName = $firstName; $this->firstName = $firstName;
$this->dateOfBirth = $dateOfBirth!=null?DateTime::createFromFormat('Y-m-d', $dateOfBirth):null; $this->dateOfBirth = $dateOfBirth != null ? DateTime::createFromFormat('Y-m-d', $dateOfBirth) : null;
$this->eMail = $eMail; $this->eMail = $eMail;
} }
@@ -531,35 +578,36 @@ class User{
* @param array $member associative array with the UserData from the dbRequest * @param array $member associative array with the UserData from the dbRequest
* @return User initialized user * @return User initialized user
*/ */
public static function fromDbArray($member){ public static function fromDbArray($member)
{
return new User( return new User(
$member['id']??null, $member['id'] ?? null,
$member['loginName']??null, $member['loginName'] ?? null,
$member['name']??null, $member['name'] ?? null,
$member['vorname']??null, $member['vorname'] ?? null,
$member['gebDatum']??null, $member['gebDatum'] ?? null,
array_key_exist('eMail', $member)?explode(',', $member['eMail']):null array_key_exist('eMail', $member) ? explode(',', $member['eMail']) : null
); );
} }
/** /**
* Export the User data into an associative array * Export the User data into an associative array
*/ */
function toAssoc(){ public function toAssoc()
return array( {
"id" => $this->id, return [
"loginName"=> $this->loginName, 'id' => $this->id,
"name" => $this->name, 'loginName' => $this->loginName,
"vorname" => $this->firstName, 'name' => $this->name,
"gebDatum" => $this->dateOfBirth, 'vorname' => $this->firstName,
"eMail" => $this->eMail); 'gebDatum' => $this->dateOfBirth,
'eMail' => $this->eMail];
} }
function loadFromDb($dbConn, $id){ public function loadFromDb($dbConn, $id)
{
$this->set( $this->set(
loadUserDataFromDb($dbConn, $id) loadUserDataFromDb($dbConn, $id)
); );
} }
} }
?>

View File

@@ -3,7 +3,7 @@
/** /**
* frame for a shiai * frame for a shiai
*/ */
class shiai class Shiai
{ {
private $id = null; //< unique id private $id = null; //< unique id
private $date = null; //< date of the shiai private $date = null; //< date of the shiai
@@ -90,7 +90,10 @@ class shiai
} }
} // end class shiai } // end class shiai
class event /**
* Framework for a event
*/
class Event
{ {
private $id = null; //< unique id of the event in the db private $id = null; //< unique id of the event in the db
private $date = null; //< date for the event (@todo ranges?) private $date = null; //< date for the event (@todo ranges?)
@@ -98,8 +101,18 @@ class event
private $deadline = null; //< until when one can register for the event private $deadline = null; //< until when one can register for the event
private $remarks = null; //< remarks to the event (special rules) or a json object for missing data (e.g. non-shiai events) private $remarks = null; //< remarks to the event (special rules) or a json object for missing data (e.g. non-shiai events)
private $shiai = null; private $shiai = null; //< a place to load the linked shiai to (if loaded)
/**
* constructor
*
* @param int $id id in the database
* @param string $date date of the event as string in the format "YYYY-MM-DD"
* @param int $shiaiId id of the linked shiai or null if not appropriate
* @param string $deadline deadline for sign ins in the format "YYYY-MM-DD"
* @param string $remarks (json formatted) string with meta information
* @param Shiai $shiai if the shiai is loaded anyway it can be placed here.
*/
public function __construct($id, $date, $shiaiId, $deadline, $remarks, $shiai) public function __construct($id, $date, $shiaiId, $deadline, $remarks, $shiai)
{ {
//! @todo InputValidation //! @todo InputValidation
@@ -112,6 +125,11 @@ class event
$this->shiai = $shiai; $this->shiai = $shiai;
} }
/**
* Representation of an event as (materializeCss) card
*
* @return string string with the html code of the event
*/
public function asHtmlCard() public function asHtmlCard()
{ {
return return
@@ -135,7 +153,8 @@ class event
'<tr>' . '<tr>' .
'<td>' . $this->date->format('Y-m-d') . '</td>' . '<td>' . $this->date->format('Y-m-d') . '</td>' .
'<td><a href="/pages/desktop/wkParticipo/showWkEvent.php?eventId=' . $this->id . '" >' . $this->shiai->getName() . '</a></td>' . '<td><a href="/pages/desktop/wkParticipo/showWkEvent.php?eventId=' . $this->id . '" >' . $this->shiai->getName() . '</a></td>' .
'<td><a class="waves-effect waves-light btn-floating modal-trigger" href="#event-modal-' . $this->id . '"><i class="material-icons">add</i></a></td>' . '<td><a class="waves-effect waves-light btn-floating modal-trigger" href="#event-modal-' . $this->id . '"><i class="material-icons">zoom_in
</i></a></td>' .
'</tr>'; '</tr>';
} }
@@ -166,8 +185,140 @@ class event
shiai::fromArray(($shiai != null) ? $shiai : $member) shiai::fromArray(($shiai != null) ? $shiai : $member)
); );
} }
/// Einen Starter per userId mit typeId zu einem Event per eventId hinzufügen
/// Es erfolgt keine Überprüfung der Meldeberechtigung!
public static function addStarter($dbConnection, $starter)
{
$retMessage = [];
$query = 'INSERT INTO `wkParticipo_Starter` (eventId, userId, type) values (:eventId, :userId, :typeId);';
$params = [
':eventId' => ['value' => $starter->getEventId(), 'data_type' => PDO::PARAM_INT],
':userId' => ['value' => $starter->getUserId(), 'data_type' => PDO::PARAM_INT],
':typeId' => ['value' => $starter->getTypeId(), 'data_type' => PDO::PARAM_INT]
];
return dbConnector::query($query, $params);
}
} // end class event } // end class event
abstract class StartingType
{
const __default = null;
const Fighter = 1;
const Audience = 2;
const NoParticipation = 3;
/**
* convert a variable into a StartingType
*
* @param [int] $type starting type candidate
* @return int representation of the StartingType if successful converted, otherwise null
*/
public static function toStartingType($type)
{
return filter_var($type, FILTER_VALIDATE_INT, ['options' => ['default' => null, 'min_range' => 1, 'max_range' => 3]]);
}
/**
* string representations of the starting type
*
* @var array array of StartingType=> its string representation
*/
public static $AsString = [1 => 'Kämpfer', 2 => 'Zuschauer', 3 => 'keine Teilnahme'];
}
class Starter
{
private $id = null; //< id of the event in the database
private $eventId = null; //< dbId of the event one is starting
private $typeId = null; //< type(id) of the starter
private $userId = null; //< id of the starting user
private $rideId = null; //< id of the ride where the starter can car pool
private $mass = null; //< mass in kg on the scale
private $result = null; //< result of the start (array of places if multi start)
// Getter for the member
public function getId()
{
return $this->id;
}
public function getEventId()
{
return $this->eventId;
}
public function getTypeId()
{
return $this->typeId;
}
public function getUserId()
{
return $this->userId;
}
public function getRideId()
{
return $this->rideId;
}
public function getMass()
{
return $this->mass;
}
public function getResult()
{
return $this->result;
}
/**
* Construtor
*
* @todo Document
* @todo Rethink validation: filter_var is supposed to return the converted value in case of success. But the reference didn't say anything about not success...
*/
public function __construct($id, $eventId, $typeId, $userId, $rideId, $mass, $result)
{
$this->id = filter_var($id, FILTER_VALIDATE_INT, ['options' => ['default' => null, 'min_range' => 1]]);
$this->eventId = filter_var($id, FILTER_VALIDATE_INT, ['options' => ['default' => null, 'min_range' => 1]]);
$this->typeId = StartingType::toStartingType($type);
$this->userId = filter_var($id, FILTER_VALIDATE_INT, ['options' => ['default' => null, 'min_range' => 1]]);
$this->rideId = filter_var($id, FILTER_VALIDATE_INT, ['options' => ['default' => null, 'min_range' => 1]]);
$this->mass = filter_var($mass, FILTER_VALIDATE_FLOAT, ['options' => ['default' => null, 'min_range' => 0.0]]);
if (is_iterable($result)) {
$this->result = [];
foreach ($result as $r) {
$r = filter_var($r, FILTER_VAR_INT, ['options' => ['default' => null, 'min_range' => 0]]);
if ($r) {
array_push($this->result, $r);
}
}
} else {
$this->$result = filter_var($r, FILTER_VAR_INT, ['options' => ['default' => null, 'min_range' => 0]]);
}
}
// create starter from assoc array
public static function create($parameter)
{
$id = $parameter['id'] ?? null; //< id of the event in the database
$eventId = $parameter['eventId'] ?? null; //< dbId of the event one is starting
$typeId = $parameter['typeId'] ?? null; //< type(id) of the starter
$userId = $parameter['userId'] ?? null; //< id of the starting user
$rideId = $parameter['rideId'] ?? null; //< id of the ride where the starter can car pool
$mass = $parameter['mass'] ?? null; //< mass in kg on the scale
$result = $parameter['result'] ?? null; //< result of the start (array of places if multi start)
return new Starter($id, $eventId, $typeId, $userId, $rideId, $mass, $result);
}
}
class eventPlaner class eventPlaner
{ {
private static $db = null; private static $db = null;