Files
cwsvJudo/homepage/participo/lib/participoLib/starter.php
marko f28fa7b51b WIP: bring participo back - consistent use of bootstrap - formatting -
phpstan level 0 error free - fixes for kyu subpage - move mams into
participo framework - remove legacy `lib/db.php` usage - add attributer
admin function - add newsposter - fixing apiKey creation
2025-11-19 12:24:38 +01:00

571 lines
18 KiB
PHP

<?php
/** Types of starting */
abstract class StartingType
{
public const __default = null;
public const Fighter = 1;
public const Audience = 2;
public 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): mixed
{
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",
];
}
/** Frame for a start to a shiai */
class Starter
{
/** Constructor
*
* @todo Document
*/
public function __construct(
$id,
$eventId,
$typeId,
$userId,
$rideId = null,
$mass = null,
$result = null,
) {
$this->id = filter_var($id, FILTER_VALIDATE_INT, [
"options" => ["default" => null, "min_range" => 1],
]);
$this->eventId = filter_var($eventId, FILTER_VALIDATE_INT, [
"options" => ["default" => null, "min_range" => 1],
]);
$this->typeId = StartingType::toStartingType($typeId);
$this->userId = filter_var($userId, FILTER_VALIDATE_INT, [
"options" => ["default" => null, "min_range" => 1],
]);
$this->rideId = filter_var($rideId, 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($this->result, FILTER_VALIDATE_INT, [
"options" => ["default" => null, "min_range" => 0],
]);
}
}
////
// dbInterface
////
/** Load a Start from the db via an id
*
* @param int $startId
* @return loaded start or null (if sth. wrong)
*/
public static function loadFromDb(?int $startId)
{
$startId = filterId($startId);
if (!isset($startId)) {
return null;
}
return self::loadFromDbBy("id", $startId);
}
/** Retrieve the linked Event from the database
*
* @param bool $force By default, if there already is an event in the buffer it is reused. Set this parameter to true to enforce the loading.
* @return Event the event in the db identified via the eventId
*/
public function loadEvent(bool $force = false)
{
if ($force || !isset($this->event)) {
if (isset($this->eventId)) {
$this->event = Event::loadFromDb($this->eventId);
}
}
return $this->event;
}
/** Retrieve the linked User from the database
*
* @param bool $force By default, if there already is an user in the buffer it is reused. Set this parameter to true to enforce the loading.
* @return User the user in the db identified via the userId
*/
public function loadStarter(bool $force = false): ?User
{
if ($force || !isset($this->user)) {
if (isset($this->userId)) {
$this->user = User::loadFromDb($this->userId);
}
}
return $this->user;
}
/** Add the shiai to the database
*
* - before adding to the db it is checked wether the currently logged in user has sufficient rights
* - all starts of the same user to the same event get deleted before adding the start (again)
*
* @todo an admin should also be allowed
* @todo the deadline of the event should be checked as well
*
* @return int id under which the
*/
public function addToDb()
{
// - if the id is already set it *has* to be already in the DB hence we don't add it
// - the logged in user must have wardship over the starter
if (isset($this->id) || !participo::isWardOf($this->userId)) {
return null;
}
// You can only start once to an event so delete *all* other starts of this user to this event
self::dbDelete($this->eventId, $this->userId);
$this->id = self::dbInsert(
$this->eventId,
$this->typeId,
$this->userId,
);
return $this->id;
}
/** Remove the start from the db
*
* - check if the currently logged in user is allowed to remove the start first
*
* @todo an admin should also be allowed
* @todo the deadline of the event should be checked as well
*
* @return void
*/
public function removeFromDb(): void
{
// - the logged in user must have wardship over the starter
if (!participo::isWardOf($this->userId)) {
return;
}
self::dbDelete($this->eventId, $this->userId);
return;
}
// Getter for the member
public function getId(): int
{
return $this->id;
}
public function getEventId(): int
{
return $this->eventId;
}
public function getTypeId(): int
{
return $this->typeId;
}
public function getUserId(): int
{
return $this->userId;
}
public function getRideId(): int
{
return $this->rideId;
}
public function getMass(): string
{
return $this->mass;
}
public function getResult(): string
{
return $this->result;
}
public function getUser(): ?User
{
return User::loadFromDb($this->userId);
}
public function getEvent(): Event
{
return $this->event;
}
public function getHtmlFormRemove($class = null)
{
$today = new DateTime();
$event = $this->loadEvent();
$eventDeadline = $event->getDeadline();
if ($today > $eventDeadline) {
return self::getHtmlModalToLate($this->id);
}
return self::getHtmlFormRemoveStarterFromEvent($this->getId(), $class);
}
// inject html code of table with coming starts for the session user
public static function htmlTableComingStarts(): void
{
$userId = participo::getSessionUserId();
echo self::getHtmlTableComingStarts($userId);
}
// member variables
// - static member
/** Name of the table with all the starts
*
* @var string
*/
private static $tableName = "wkParticipo_Starter";
/** Names of the columns in the table (in the database) with their type
*
* @var array
*/
private static $dbColumns = [
"id" => PDO::PARAM_INT,
"eventId" => PDO::PARAM_INT,
"type" => PDO::PARAM_INT,
"userId" => PDO::PARAM_INT,
"fahrtId" => PDO::PARAM_INT,
"masse" => PDO::PARAM_STR,
"platz" => PDO::PARAM_STR,
];
// - non-static member
// data that's stored in the start table
/** unique database id for the start
*
* @var int/null
*/
private $id = null;
/** unique database id of the event one is starting
*
* @var int/null
*/
private $eventId = null;
/** type(id) of the starter
*
* @var int/null
*/
private $typeId = null;
/** unique database id of the starting user
*
* @var int/null
*/
private $userId = null;
/** unique database id of the ride where the starter can car pool
*
* @var int/null
*/
private $rideId = null;
/** the mass(-class) the starter had at the event, comma separated list if multiple
*
* @var string
*/
private $mass = null;
/** place result of the starter at the event, comma separated list if multiple
*
* @var string
*/
private $result = null;
/** Create a Starter from an assoziative array like it is returned from db requests
*
* @param array $member associative array with the UserData from the dbRequest
* @param $columnMappings renaming of columnNames, e.g., if the id isn't under id in the array, add 'id'=>'starterId' to the mappings
* @return User initialized user
*/
private static function fromDbArray($member, $columnMappings = []): Starter
{
// if it isn't remapped, take default column name
foreach (self::$dbColumns as $columnName => $columnDataType) {
if (!array_key_exists($columnName, $columnMappings)) {
$columnMappings[$columnName] = $columnName;
}
}
return new Starter(
$member[$columnMappings["id"]] ?? null,
$member[$columnMappings["eventId"]] ?? null,
$member[$columnMappings["type"]] ?? null,
$member[$columnMappings["userId"]] ?? null,
$member[$columnMappings["fahrtId"]] ?? null,
$member[$columnMappings["masse"]] ?? null,
$member[$columnMappings["platz"]] ?? null,
);
}
/** Load a starter from the db by a column
*
* @param string $name name of the column
* @param mixed $value value to look for
* @param bool $unique if the value is unique (true->return single value) or not (false->return array)
* @return Starter loaded starter or null (if sth. wrong)
*/
private static function loadFromDbBy($name, $value): ?Starter
{
if (!array_key_exists($name, self::$dbColumns)) {
return null;
}
$response = dbConnector::query(
"SELECT * FROM `wkParticipo_Starter` WHERE `{$name}` = :{$name}",
[
$name => [
"value" => $value,
"data_type" => self::$dbColumns[$name],
],
],
);
if (count($response) != 1) {
return null;
}
return self::fromDbArray($response[0]);
}
/** Add a Start to the db
*
* - backend function no input validation/sanitation is done
*
* @param [int] $eventId eventId for the start
* @param [int] $typeId type(Id) for the start
* @param [int] $userId id of the starting user
* @return [int] lastInserted id of the Start
*/
private static function dbInsert($eventId, $typeId, $userId)
{
$query =
"INSERT INTO `cwsvjudo_main`.`wkParticipo_Starter` (eventId, type, userId) values (:eventId, :typeId, :userId);";
$params = [
":eventId" => ["value" => $eventId, "data_type" => PDO::PARAM_INT],
":typeId" => ["value" => $typeId, "data_type" => PDO::PARAM_INT],
":userId" => ["value" => $userId, "data_type" => PDO::PARAM_INT],
];
// @todo remove ignoreErrors again
// @todo Inserting-Starter-Statement returns false on execution: Why? It seems to succeed!
$response = dbConnector::query($query, $params, [
"ignoreErrors" => true,
]);
return dbConnector::getLastInsertId();
}
private static function dbDelete($eventId, $userId): void
{
$query =
"DELETE FROM `cwsvjudo_main`.`wkParticipo_Starter` WHERE eventId = :eventId AND userId = :userId;";
$params = [
":eventId" => ["value" => $eventId, "data_type" => PDO::PARAM_INT],
":userId" => ["value" => $userId, "data_type" => PDO::PARAM_INT],
];
$response = dbConnector::query($query, $params);
return;
}
// request coming starts of a user from the db
private static function getComingStarts(
$userId = null,
$sinceDate = null,
): array {
// if no user is given, take it from the session data
$userId = $userId ?? participo::getSessionUserId();
// If no data is given, we take today
if (!$sinceDate) {
$sinceDate = "CURDATE()";
} else {
$sinceDate = 'DATE("' . $sinceDate . '")';
}
// Query all interesting starts
$query =
"SELECT " .
"`wkParticipo_Starter`.`id` as startId, " .
"`wkParticipo_Starter`.`userId` as starterId, " .
"`wkParticipo_Starter`.`eventId` as eventId, " .
"`wkParticipo_Events`.`wkId` as shiaiId " .
"FROM `wkParticipo_Starter` " .
// link to the event (to get the date)
"LEFT JOIN `wkParticipo_Events` ON `wkParticipo_Starter`.`eventId` = `wkParticipo_Events`.`id` " .
// link to all wardships for the starter
"LEFT JOIN `vormundschaft` ON `wkParticipo_Starter`.`userId` = `vormundschaft`.`kidId` " .
// link to the shiai of the event
"LEFT JOIN `wettkampfkalender` on `wettkampfkalender`.`lfdeNr` = `wkParticipo_Events`.`wkId` " .
"WHERE " .
// only events after
"`wkParticipo_Events`.`date` >= " .
$sinceDate .
" AND " .
// only if the current user is warden of the starte
"`vormundschaft`.`userId` = :userId " .
"ORDER BY `wkParticipo_Events`.`date` ASC;";
$params = [
":userId" => ["value" => $userId, "data_type" => PDO::PARAM_INT],
];
$response = dbConnector::query($query, $params);
$comingStarts = [];
foreach ($response as $r) {
$start = Starter::loadFromDb($r["startId"]);
$comingStarts[] = $start;
}
return $comingStarts;
}
// get html code of a list of starts
private static function getHtmlTable($starts)
{
$html =
'<table class="responsive-table">' .
"<thead><tr><th>Datum</th><th>Veranstaltung</th><th>Starter</th><th></th><th></th></tr></thead>" .
"<tbody>";
foreach ($starts as $start) {
$today = new DateTime();
$startingUser = User::loadFromDb($start->getUserId());
$event = Event::loadFromDb($start->getEventId());
$shiai = Shiai::loadFromDb($event->getShiaiId());
$eventDeadline = $event->getDeadline();
$eventDate = $event->getDate();
$html .=
"<tr>" .
"<td>" .
getHtmlSquareDate($eventDate) .
"</td>" .
"<td>" .
$shiai->getHtmlName() .
"</td>" .
"<td>" .
$startingUser->getName() .
", " .
$startingUser->getFirstName() .
"</td>" .
"<td>" .
StartingType::$AsString[$start->getTypeId()] .
"</td>" .
"<td>" .
$start->getHtmlFormRemove() .
"</td>" .
"</tr>";
}
$html .= "</tbody></table>";
return $html;
}
private static function getHtmlModalToLate($startId, $caption = "Austragen")
{
$modal =
'<a class="btn grey waves-effect waves-light modal-trigger" href="#modal-remove-starter-' .
$startId .
'">' .
$caption .
"</a>" .
'<div id="modal-remove-starter-' .
$startId .
'" class="modal" popover>' .
'<div class="modal-content">' .
"<p>Das Fenster zum Ein- und Austragen ist bereits geschlossen.</p>" .
"</div>" .
'<div class="modal-footer">' .
'<a href="#!" class="modal-close waves-effect waves-green btn-flat">OK</a>' .
"</div>" .
"</div>";
return $modal;
}
private static function getHtmlFormRemoveStarterFromEvent(
$starterId,
$class = null,
) {
$returnToUrl = urlencode(getCurPagesUrl());
$form =
"<form " .
(isset($class) ? 'class="' . $class . '"' : "") .
' action="api.starter.remove.php" method="post">' .
'<input type="hidden" name="returnToUrl" id="returnToUrl" value="' .
$returnToUrl .
'" >' .
'<input type="hidden" name="starterId" id="starterId" value="' .
$starterId .
'">' .
'<button class="btn red" type="submit" name="submit">austragen</button>' .
"</form>";
return $form;
}
/** Generate a html table of comming starts of an user
*
* If no user is given, the logged in user is used.
*
* @param ?int userId User to get the table of upcomming starts for
*/
private static function getHtmlTableComingStarts(
?int $userId = null,
): string {
$userId ??= participo::getSessionUserId();
$starts = self::getComingStarts($userId);
if (!(count($starts) > 0)) {
return "<div>Keine Meldungen zu bevorstehenden Events<div>";
}
return self::getHtmlTable($starts);
}
// buffers to reduce db access
/** Event of the start
*
* @var Event/null
*/
private $event = null;
/** Starting user of the start
*
* @var User/null
*/
private $user = null;
}