legacy data

This commit is contained in:
torsten 2026-10-04 20:34:42 +02:00
parent 0b5b35e396
commit f00770f73f
210 changed files with 113175 additions and 0 deletions

View file

@ -0,0 +1,3 @@
{
"directory": "public/bower"
}

View file

@ -0,0 +1,33 @@
APP_NAME="Hoschis Tippspiel"
APP_ENV=local
APP_KEY=base64:6wMJO8U4QnPitLpymT0gkymX1kBQOB5/1U/iyuvewa8=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=pfosten
DB_USERNAME=pf_user
DB_PASSWORD=pf_password
BROADCAST_DRIVER=smtp
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=log
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

View file

@ -0,0 +1,33 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

View file

@ -0,0 +1,33 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:kDZstIrXoxXzGa2reMEbvFjDhcaoJ4eKupyPnPL7euE=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=DB
DB_PORT=3306
DB_DATABASE=pfosten
DB_USERNAME=pf_user
DB_PASSWORD=pf_password
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

View file

@ -0,0 +1,35 @@
APP_NAME="Hoschis Tippspiel"
APP_ENV=local
APP_KEY=base64:1+1OyIuQj0id5SH2kBWdQoCDdmEqwGGHxkqtfJPLA00=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://hoschis-tippspiel.de
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=d0274241
DB_USERNAME=d0274241
DB_PASSWORD=superpfosten!
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=sendmail
MAIL_HOST=w0172dd3.kasserver.com
MAIL_PORT=25
MAIL_USERNAME=info@hoschis-tippspiel.de
MAIL_PASSWORD=lassunstippen!1
MAIL_FROM_NAME="Tippspiel Info"
MAIL_FROM_ADDRESS=info@hoschis-tippspiel.de
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

View file

@ -0,0 +1,5 @@
* text=auto
*.css linguist-vendored
*.scss linguist-vendored
*.js linguist-vendored
CHANGELOG.md export-ignore

View file

@ -0,0 +1,13 @@
/node_modules
/public/hot
/public/storage
/storage/*.key
/vendor/*
/.idea
/.vagrant
Homestead.json
Homestead.yaml
npm-debug.log
.DS_Store
package-lock.json
composer.lock

View file

@ -0,0 +1,36 @@
FROM php:7.4-fpm
# Arguments defined in docker-compose.yml
ARG user
ARG uid
# Install system dependencies
RUN apt-get update && apt-get install -y \
git \
curl \
libpng-dev \
libonig-dev \
libxml2-dev \
zip \
unzip \
libzip-dev \
-y mariadb-client
# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*
# Install PHP extensions
RUN docker-php-ext-install zip mysqli pdo_mysql mbstring exif pcntl bcmath gd && docker-php-ext-enable mysqli
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# Create system user to run Composer and Artisan Commands
RUN useradd -G www-data,root -u $uid -d /home/$user $user
RUN mkdir -p /home/$user/.composer && \
chown -R $user:$user /home/$user
# Set working directory
WORKDIR /var/www
USER $user

View file

@ -0,0 +1,40 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}

View file

@ -0,0 +1,65 @@
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
\Illuminate\Auth\AuthenticationException::class,
\Illuminate\Auth\Access\AuthorizationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Session\TokenMismatchException::class,
\Illuminate\Validation\ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
/**
* Convert an authentication exception into an unauthenticated response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Illuminate\Http\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest(route('login'));
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Log;
use Carbon;
class Game extends Model
{
protected $fillable = [
'id','round_id','team1','team2','score1','score2','kickoff'
];
// true, wenn Anstoss - 1hr > now()
public static function locked($game_id)
{
$game = Game::find($game_id);
$now = Carbon\Carbon::now();
$tipp_input_end = $game->getLocktime($game);
return ($tipp_input_end <= $now);
}
public function hasResult() {
$game = $this;
return $game->score1 > -1;
}
public static function has_result($game_id) {
$game = Game::where('id',$game_id)->first();
$hasIt = $game->score1 > -1;
if ($hasIt==false) {
return false;
}
return true;
}
public static function resultString($game_id) {
$game = Game::where('id',$game_id)->first();
$now=Carbon\Carbon::now();
if (!$game->hasResult()) {
if ($game->kickoff > $now) return "-";
$start=Carbon\Carbon::parse($game->kickoff);
$end=$start->addHours(2);
if ($end<$now && $start>$now) return "Läuft";
return "(Eingeben)";
}
return $game->score1. " : " . $game->score2;
}
public function getLocktime() {
//return Carbon\Carbon::parse($this->kickoff)->addHour(-1);
return Carbon\Carbon::parse($this->kickoff)->addMinute(-1); // 2020-09-11 changed Lock from Hour to Minute
}
}

View file

@ -0,0 +1,3 @@
{
"directory": "public/bower"
}

View file

@ -0,0 +1,32 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
class ForgotPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset emails and
| includes a trait which assists in sending these notifications from
| your application to your users. Feel free to explore this trait.
|
*/
use SendsPasswordResetEmails;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}

View file

@ -0,0 +1,77 @@
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
if (preg_match_all('/[A-Z]/', $data['name']) > 4) {
// The string contains more than 4 uppercase characters
// echo "More than 4 uppercase letters found.";
return;
}
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* @var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

View file

@ -0,0 +1,72 @@
<?php
namespace App\Http\Controllers;
//use Illuminate\Http\Request;
use Request;
use App\Game;
use Carbon\Carbon;
use Auth;
use App\User;
use Log;
use App\MyClasses\TimeLogger;
class GamesController extends Controller
{
public function edit($game_id) {
if (Auth::guest()) { return redirect("/login"); }
$game=Game::where('id',$game_id)->first();
$kickoff_german = User::toGermanDate($game->kickoff);
return view('games.edit',compact('game','kickoff_german'));
}
public function store() {
if (Auth::guest()) { return redirect("/login"); }
$a=new TimeLogger("GamesController::store");
Log::info($a->getStartMessage());
// Validate form
Log::info("Starting validation");
$this->validate(request(), [
'id' => 'required',
'team1' => 'required',
'team2' => 'required',
'kickoff' => 'required'
]);
Log::info("Passed form validation.");
$score1=-1;
$score2=-1;
Log::info("Checking score");
if (is_null("score1")) Log::info("score1 is missing.");
if (is_null("score2")) Log::info("score2 is missing.");
if (!is_null(request("score1")) && !is_null(request("score2")) ) {
Log::info("Setting values");
$score1=request("score1");
$score2=request("score2");
}
// Fetch, modify, save game
$game = Game::where('id', request('id'))->first(); // Only for editing existing. New games get created in RoundsController.
$game->team1 = request('team1');
$game->team2 = request('team2');
$game->score1= $score1;
$game->score2= $score2;
$game->kickoff=User::toDBDate(request('kickoff'));
$game->save();
Log::info($a->getEndMessage());
// Redirect to the Rounds Index
return redirect('/rounds#'.$game->round_id);
}
}

View file

@ -0,0 +1,28 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('home');
}
}

View file

@ -0,0 +1,295 @@
<?php
namespace App\Http\Controllers\Leagues;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Leagues;
use Auth;
use App\Season;
use App\Round;
use App\User;
use App\Leagues\League;
use App\Leagues\LeagueMember;
use App\Leagues\Match;
use Illuminate\Support\Facades\Input;
use Log;
use DB;
use App\MyClasses\TimeLogger;
class LeaguesController extends Controller
{
public function index() {
$a=new TimeLogger("LeaguesController.index");
Log::info($a->getStartMessage());
$season=Season::getCurrent();
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
$season = Season::where('id','=',$season->id)->first();
if (!$season) return redirect("/seasons");
$start_round_name="Einstellen";
$rounds = Round::where('season_id','=',$season->id)->orderBy('id')->get();
if (!$rounds) return redirect("/seasons");
$round_count = 18;
$start_round_name="Einstellen";
$start_round_id=$rounds[0]->id;
$league_mode="Einstellen";
$league = League::where('season_id','=',$season->id)->first();
if ($league) {
$startround = Round::where('season_id', '=', $season->id)->orderBy('id')->first();
$start_round_id = $startround->id;
$startRound = Round::where('id','=',$league->start_round_id)->first();
$start_round_name = $startRound->name;
$start_round_id = $startRound->id;
$round_count = $league->round_count;
if($league->is_qualification) { $league_mode="Qualifikation"; } else { $league_mode="Liga-Spiel"; }
}
// Fetch existing leagues
// No leagues: Create Qualification League or Standard League System (including matches)
// necessary input: start_round(_id), round_count
// Delete all leagues & matches
//
Log::info($a->getEndMessage());
return view('leagues.index', compact('season','rounds','start_round_id','start_round_name','league_mode','round_count'));
}
public function createLeagues($start_round_id, $round_count) {
Log::info("CREATE_LEAGUES");
$a=new TimeLogger("LeaguesController::createLeagues()");
Log::info($a->getStartMessage());
$users=User::getActives();
if (sizeof($users)==0){
Log::info($a->getEndMessage());
return view("leagues.no_users");
}
League::createLeagues($start_round_id, $round_count);
Log::info("LeaguesController::createLeagues completed.");
Match::createMatchups();
Log::info($a->getEndMessage());
return redirect("/seasons");
}
public function showLeagueRounds() {
if (Auth::guest()) { return redirect("/"); }
$a=new TimeLogger("LeaguesController::showLeagueRounds()");
Log::info($a->getStartMessage());
$season=Season::getCurrent();
$roundNames = Round::getNames();
$leagueNames = League::getNames();
$leagues = League::where('season_id','=',$season->id)->where('rank','<=', 4)->orderBy('id')->get();
$matchesTotal = array();
foreach ($leagues as $league) {
$matches = Match::getMatchResults($league->id, -1);
foreach ($matches as $match) {
if (!key_exists($match->round_id, $matchesTotal)) {
$matchesTotal[$match->round_id]=array();
}
if (!key_exists($league->id, $matchesTotal[$match->round_id] )) {
$matchesTotal[$match->round_id][$league->id]=array();
}
$lg = $matchesTotal[$match->round_id][$league->id];
array_push($lg, $match);
$matchesTotal[$match->round_id][$league->id] = $lg;
}
}
Log::info($a->getEndMessage());
return view ('leagues.matches', compact('season', 'matchesTotal','leagues','leagueNames','roundNames'));
}
public static function showLeagueRanking() {
$a=new TimeLogger("LeaguesController::showLeagueRanking()");
Log::info($a->getStartMessage());
$season = Season::getCurrent();
//$leagues = array_reverse(League::getRanking($rank));
$leagueNames = League::getNames();
$userNames = User::getNames();
$leagues = League::where('season_id','=',$season->id)->where('rank','<=', 4)->orderBy('id')->get();
if (!sizeof($leagues)) {
Log::info($a->getEndMessage());
return redirect("/");
}
$totalRanking = League::getTotalRankingOverall(); // Nur für Auf/Abstiegsinfo benötigt.
$rankInfo=array();
foreach($totalRanking as $index => $entry) {
$userId=$entry[0];
$rankInfo[$userId]=$totalRanking[$index][4];
}
$cols=array();
$cols[1]="greenyellow";
$cols[2]="orange";
$cols[3]="lightgrey";
$cols[4]="";
$leagueScores=array();
foreach([1,2,3,4] as $rank) {
$leagueScores[$rank] = League::getRanking($rank);
}
Log::info($a->getEndMessage());
//error_log($a->getEndMessage());
return view ('leagues.chart',compact('season', 'leagueNames', 'userNames','leagueScores','rankInfo','rank','cols'));
}
// Originall copied over from showLeagueRanking
public static function showLeagueSwapForm() {
$a=new TimeLogger("LeaguesController::showLeagueSwapForm()");
Log::info($a->getStartMessage());
$season = Season::getCurrent();
//$leagues = array_reverse(League::getRanking($rank));
$leagueNames = League::getNames();
$userNames = User::getNames();
$leagues = League::where('season_id','=',$season->id)->where('rank','<=', 4)->orderBy('id')->get();
if (!sizeof($leagues)) {
Log::info($a->getEndMessage());
return redirect("/");
}
$totalRanking = League::getTotalRankingOverall(); // Nur für Auf/Abstiegsinfo benötigt.
$rankInfo=array();
foreach($totalRanking as $index => $entry) {
$userId=$entry[0];
$rankInfo[$userId]=$totalRanking[$index][4];
}
$cols=array();
$cols[1]="greenyellow";
$cols[2]="orange";
$cols[3]="lightgrey";
$cols[4]="";
$leagueScores=array();
foreach([1,2,3,4] as $rank) {
$leagueScores[$rank] = League::getRanking($rank);
}
Log::info($a->getEndMessage());
//error_log($a->getEndMessage());
return view ('leagues.chart_swapform',compact('season', 'leagueNames', 'userNames','leagueScores','rankInfo','rank','cols'));
}
public static function swapLeagueMembers(Request $request) {
Log::info("Start: LeaguesController::swapLeagueMembers");
Log::info("Method triggered successfully.");
Log::info($request->method()); // Klappt
$input=$request->input();
Log::info("Params:".sizeof($input));
foreach ($input as $key => $value) {
Log::info( $key."=>".$value );
}
$leagueIds = League::getIds();
$strLeagueIds = join(",", $leagueIds);
Log::info("League Ids: ".$strLeagueIds);
$user1_id=$request->input('user1_id');
$user2_id=$request->input('user2_id');
Log::info($user1_id);
Log::info($user2_id);
$sql=str_replace("#USER1_ID",$user1_id, "update leagues_matches set user1_id=999 where user1_id=#USER1_ID and league_id in (#LEAGUES);");
$sql=str_replace("#LEAGUES", $strLeagueIds,$sql);
Log::info($sql);
DB::update($sql);
$sql=str_replace("#USER1_ID",$user1_id, "update leagues_matches set user1_id=#USER1_ID where user1_id=#USER2_ID and league_id in (#LEAGUES);");
$sql=str_replace("#USER2_ID", $user2_id,$sql);
$sql=str_replace("#LEAGUES", $strLeagueIds,$sql);
Log::info($sql);
DB::update($sql);
$sql=str_replace("#USER2_ID",$user2_id, "update leagues_matches set user1_id=#USER2_ID where user1_id=999 and league_id in (#LEAGUES);");
$sql=str_replace("#LEAGUES", $strLeagueIds,$sql);
Log::info($sql);
DB::update($sql);
$sql=str_replace("#USER1_ID",$user1_id, "update leagues_matches set user2_id=999 where user2_id=#USER1_ID and league_id in (#LEAGUES);");
$sql=str_replace("#LEAGUES", $strLeagueIds,$sql);
Log::info($sql);
DB::update($sql);
$sql=str_replace("#USER1_ID",$user1_id, "update leagues_matches set user2_id=#USER1_ID where user2_id=#USER2_ID and league_id in (#LEAGUES);");
$sql=str_replace("#USER2_ID", $user2_id,$sql);
$sql=str_replace("#LEAGUES", $strLeagueIds,$sql);
Log::info($sql);
DB::update($sql);
$sql=str_replace("#USER2_ID",$user2_id, "update leagues_matches set user2_id=#USER2_ID where user2_id=999 and league_id in (#LEAGUES);");
$sql=str_replace("#LEAGUES", $strLeagueIds,$sql);
Log::info($sql);
DB::update($sql);
$sql=str_replace("#USER1_ID",$user1_id, "update leagues_members set user_id=999 where user_id=#USER1_ID and league_id in (#LEAGUES);");
$sql=str_replace("#LEAGUES", $strLeagueIds,$sql);
Log::info($sql);
DB::update($sql);
$sql=str_replace("#USER1_ID",$user1_id, "update leagues_members set user_id=#USER1_ID where user_id=#USER2_ID and league_id in (#LEAGUES);");
$sql=str_replace("#USER2_ID", $user2_id,$sql);
$sql=str_replace("#LEAGUES", $strLeagueIds,$sql);
Log::info($sql);
DB::update($sql);
$sql=str_replace("#USER2_ID",$user2_id, "update leagues_members set user_id=#USER2_ID where user_id=999 and league_id in (#LEAGUES);");
$sql=str_replace("#LEAGUES", $strLeagueIds,$sql);
Log::info($sql);
DB::update($sql);
}
public static function showSingleUserMatches($userId) {
$season = Season::getCurrent();
$leagueNames = League::getNames();
$roundNames = Round::getNames();
$matches = Match::getMatchResultsForUser($userId);
$user = User::where('id','=', $userId)->first();
$userName = $user->name;
return view ('leagues.playermatches',compact('season','leagueNames','roundNames','matches','userName'));
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace App\Http\Controllers\Leagues;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Leagues;
use Auth;
use App\Season;
class MatchController extends Controller
{
//
}

View file

@ -0,0 +1,10 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PaymentController extends Controller
{
//
}

View file

@ -0,0 +1,71 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Season;
use Log;
class RegistrationController extends Controller
{
public function create() {
$season=Season::getCurrent();
if ($season) {
if ( Season::hasStandardLeague() || Season::hasQualifications() ) {
// Redirect to the home page
return redirect()->home();
}
}
return view('registration.create');
}
public function store()
{
// Validate form
$this->validate(request(), [
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
]);
$name =request('firstname')." ".request('lastname');
if (User::where('name', '=', $name)->first() != null) {
\Session::flash('message', 'Name existiert bereits');
return redirect("/register");
}
if (User::where('email', '=', request('email'))->first() != null) {
\Session::flash('message', 'Email-Adresse wird bereits von einem anderen Spieler verwendet');
return redirect("/register");
}
// Create and save the user
//$user = User::create(request(['name','email','password']));
$user = User::create([
'name' => $name,
'firstname' => request('firstname'),
'lastname' => request('lastname'),
'email'=> request('email'),
'password' => bcrypt(request('password'))]);
// Sign them in
// First user is made admin automatically
Log::info("User count:" . User::all()->count());
if (User::all()->count()==1) {
$user->admin = true;
}
$user->save();
auth()->login($user);
\App\Tipp::createAllTips();
// Redirect to the home page
return redirect()->home();
}
}

View file

@ -0,0 +1,304 @@
<?php
namespace App\Http\Controllers;
use App\Roundmail;
use App\User;
use App\Round;
use App\Season;
use Illuminate\Http\Request;
use App\Mail\RoundmailMailer;
use Auth;
use DB;
use Log;
use Carbon;
use App\MyClasses\TimeLogger;
class RoundmailController extends Controller
{
public function index()
{
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
$a=new TimeLogger("RoundmailController::index()");
Log::info($a->getStartMessage());
$mails_db = Roundmail::all()->sortBy("send_date");
$mails=array();
foreach($mails_db as $mail_db) {
$fields=array();
$fields['id'] = $mail_db->id;
$fields['send_date'] = $mail_db->send_date;
$fields['topic'] = $mail_db->topic;
$sender = User::where('id','=',$mail_db->user_id)->first();
$sender_name="Automailer";
if ($sender) { $sender_name=$sender->name; }
$fields['sender'] = $sender_name;
array_push($mails,$fields);
}
$mails=array_reverse($mails);
Log::info($a->getEndMessage());
return view('roundmails.index',compact('mails'));
}
public function show($mail_id) {
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
$a=new TimeLogger("RoundmailController::show start");
Log::info($a->getStartMessage());
$user_id=Auth::user()->id;
$users = DB::table('users')->orderBy('lastname')->get();
$active_users=array();
$activeMailList=array();
$inactive_users=array();
$inactiveMailList=array();
$missingTippMailList=array();
$missingJokerMailList=array();
$adminMailList=array();
$topic="";
$send_date = date("d.m.Y h:i:s", time());
Log::info("Users to check for missing tipps:" . sizeof($users));
foreach($users as $user) {
Log::info("Season paytest user_id=".$user->id);
if (User::is_season_paid($user->id)=="Ja") {
Log::info("Season is paid.");
array_push($active_users,$user);
array_push($activeMailList,$user->email);
} else {
Log::info("Season is NOT paid.");
if (!$user->deleted) {
array_push($inactive_users, $user);
array_push($inactiveMailList, $user->email);
}
}
//Log::info("user-id=".$user->id.", ".$user->name);
//Log::info("Tipp: ".User::hasMissingTipp($user->id));
if (!$user->deleted) {
if (User::hasMissingTipp($user->id)) {
array_push($missingTippMailList, $user->email);
}
if (User::hasMissingJoker($user->id)) {
array_push($missingJokerMailList, $user->email);
}
if ($user->admin == true) {
array_push($adminMailList, $user->email);
}
}
}
Log::info("Size of missingMailist=".sizeof($missingTippMailList));
$activeMailList = implode(",",$activeMailList);
$inactiveMailList = implode(",",$inactiveMailList);
$missingTippMailList = implode(",",$missingTippMailList);
$missingJokerMailList = implode(",",$missingJokerMailList);
$adminMailList = implode(",",$adminMailList);
$tippSpielLink = Round::getTippSpielLink();
$topic="";
$mail_message="";
$sender_name="Automailer";
$recipients="";
$viewmode=false;
if ($mail_id>-1) {
$viewmode=true;
$mail = Roundmail::where('id','=',$mail_id)->first();
$send_date = $mail->send_date;
$topic = $mail->topic;
Log::info("Before:");
Log::info($mail->message);
//$mail_message = str_replace('<br/>','\n', $mail->message);
$mail_message = $mail->message;
Log::info("After:");
Log::info($mail_message);
$recipients = $mail->recipients;
$sender = User::where('id','=',$mail->user_id)->first();
if ($sender) {$sender_name = $sender->name;}
}
Log::info("!!! inactiveMailList content=". $inactiveMailList);
Log::info($a->getEndMessage());
return view('roundmails.show',compact('mail_id','activeMailList','inactiveMailList','missingTippMailList','missingJokerMailList','adminMailList','send_date','user_id','topic', 'mail_message', 'recipients', 'sender_name','viewmode','tippSpielLink'));
}
public function send() {
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
// Validate form
$this->validate(request(), [
'user_id' => 'required',
'send_date' => 'required',
'topic' => 'required',
'message' => 'required',
'recipients'=> 'required'
]);
Log::info("Preparing to send from user_id ".request('user_id'));
/*
foreach($users as $user) {
Log::info("Sending RoundmailMailer to: ".$user->name);
\Mail::to($user)->send(new RoundmailMailer);
}
*/
$r = new RoundmailMailer();
$r->user_id = Auth::user()->id;
$r->sender_email = Auth::user()->email;
$r->sender_name = Auth::user()->name;
$r->send_date = Carbon\Carbon::now();
$r->recipients = request('recipients');
Log::info("Topic:" . request('topic'));
Log::info("Recipients: '".$r->recipients."'");
$r->topic = request('topic');
$r->mail_message = str_replace("\r","",str_replace("\n","<br/>", request('message')));
try {
\Mail::to(explode(",",$r->recipients))->send($r);
} catch (\Exception $e) {
Log::error('Mail sending failed: ' . $e->getMessage());
}
// Die hier ist nur für die DB
$rm = new RoundMail();
$rm->send_date=$r->send_date;
$rm->recipients=$r->recipients;
$rm->user_id=$r->user_id;
$rm->topic=$r->topic;
$rm->message=$r->mail_message;
$rm->save();
return redirect('/roundmails');
}
public function checkReminder() {
Log::info("RoundmailController::checkReminder was triggered");
Log::info("piggyback function: delete users with > 4 uppercase letters");
DB::delete("delete from users where id in (
SELECT id
FROM users
WHERE (LENGTH(name) - LENGTH(REPLACE(name, 'A', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'B', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'C', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'D', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'E', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'F', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'G', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'H', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'I', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'J', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'K', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'L', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'M', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'N', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'O', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'P', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'Q', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'R', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'S', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'T', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'U', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'V', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'W', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'X', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'Y', ''))
+ LENGTH(name) - LENGTH(REPLACE(name, 'Z', ''))
) > 4
AND
name <> 'TONI Düsseldorf'
)"
);
$currentSeason = Season::getCurrent();
$users = User::whereNull('deleted')->get();
Log::info("Usercount: ".sizeof($users));
$emailsOfUsersWithIncompleteTipps=array();
foreach($users as $user) {
// 2.Versuch nur aktiven Spielern reminder mails zu schicken
if (User::is_season_paid($user->id)=="Ja") {
if (User::hasMissingTipp($user->id) || User::hasMissingJoker($user->id)) {
if ($user->gets_reminders) {
array_push($emailsOfUsersWithIncompleteTipps, $user->email);
}
}
}
}
$firstTippableRound = Round::getFirstTippableRound();
if (!$firstTippableRound) {
Log::info("RoundmailController::checkReminder: No tippable round detected, automailing aborted");
return;
}
$WARNING_HOURS_OFFSET=48;
if (!$firstTippableRound->isInLockWarningTime($WARNING_HOURS_OFFSET)) {
Log::info("RoundmailController->checkRemninder: skipping Reminder Mail because Lock is further away than ".$WARNING_HOURS_OFFSET." hours.");
return;
}
$roundLockTime = $firstTippableRound->getLockTime();
$r = new RoundmailMailer();
$r->user_id = 0;
$r->sender_email="hoschis.tippspiel.info@gmail.com";
$r->sender_name="Hoschis Tippspiel";
$r->send_date = Carbon\Carbon::now();
$r->recipients = implode(",", $emailsOfUsersWithIncompleteTipps);
$r->topic = "Fehlende Tipps/Joker";
$r->mail_message = 'Es fehlen noch Tipps/Joker für: ' . $firstTippableRound->name . '<br/>Die Runde sperrt sich: ' . $roundLockTime . '<br/><br/>Link zum Spiel: <a href="' . Round::getTippSpielLink(). '">( Hier klicken )</a>';
Log::info("Sending Reminder Mails");
try {
\Mail::to($emailsOfUsersWithIncompleteTipps)->send($r);
} catch (\Exception $e) {
Log::error('Mail sending failed: ' . $e->getMessage());
}
// Die hier ist nur für die DB
$rm = new RoundMail();
$rm->send_date=$r->send_date;
$rm->recipients=$r->recipients;
$rm->user_id=$r->user_id;
$rm->topic=$r->topic;
$rm->message=$r->mail_message;
$rm->save();
}
}

View file

@ -0,0 +1,185 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Season;
use App\Round;
use App\Game;
use App\User;
use App\Tipp;
use App\Quota;
use DB;
use Auth;
use Log;
use App\MyClasses\TimeLogger;
class RoundsController extends Controller
{
public function index() {
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
$a=new TimeLogger("RoundsController::index()");
Log::info($a->getStartMessage());
$activeSeason=Season::getCurrent();
$rounds =null;
if ($activeSeason) {
$activeSeasonId = Season::getCurrent()->id;
$rounds = Round::all()->where('season_id', '=', $activeSeasonId);
}
$quotas = Quota::getQuotas();
$round_count = Round::getCount();
Log::info($a->getEndMessage());
return view('rounds.index', compact('rounds','activeSeason', 'round_count'));
}
public function create() {
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
$currentSeason = Season::getCurrent();
if ($currentSeason) {
return view('rounds.create', compact('currentSeason'));
}
redirect()->home()->withErrors('Es muss zuerst eine Saison angelegt werden');
}
public function store() {
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
$a=new TimeLogger("RoundsController::store() start");
Log::info($a->getStartMessage());
// Validate form
$this->validate(request(), [
'name' => 'required',
'game1_team1' => 'required',
'game1_team2' => 'required',
'game1_kickoff' => 'required',
'game2_team1' => 'required',
'game2_team2' => 'required',
'game2_kickoff' => 'required',
'game3_team1' => 'required',
'game3_team2' => 'required',
'game3_kickoff' => 'required',
'game4_team1' => 'required',
'game4_team2' => 'required',
'game4_kickoff' => 'required'
]);
$seasonId = Season::getCurrent()->id;
$round = Round::create([
'name' => request('name'),
'season_id' => $seasonId
]);
$round->save();
$round_id = $round->id;
$game1 = Game::create([
'round_id' => $round_id,
'team1' => request('game1_team1'),
'team2' => request('game1_team2'),
'kickoff' => User::toDBDate(request('game1_kickoff'))
]);
$game2 = Game::create([
'round_id' => $round_id,
'team1' => request('game2_team1'),
'team2' => request('game2_team2'),
'kickoff' => User::toDBDate(request('game2_kickoff'))
]);
$game3 = Game::create([
'round_id' => $round_id,
'team1' => request('game3_team1'),
'team2' => request('game3_team2'),
'kickoff' => User::toDBDate(request('game3_kickoff'))
]);
$game4 = Game::create([
'round_id' => $round_id,
'team1' => request('game4_team1'),
'team2' => request('game4_team2'),
'kickoff' => User::toDBDate(request('game4_kickoff'))
]);
// Sign them in
Tipp::createAllTips();
Log::info($a->getEndMessage());
// Redirect to the home page
return redirect('/rounds');
}
public function store_report() {
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
$a=new TimeLogger("RoundsController::store_report()");
Log::info($a->getStartMessage());
// Validate form
$this->validate(request(), [
'round_id' => 'required'
]);
$seasonId = Season::getCurrent()->id;
$round = Round::where('id','=',request('round_id'))->first();
//Log::info("Report = ".request("report"));
$round->report="";
if (request("report")){
$round->report = str_replace("\n","<br/>", request("report"));
}
$round->save();
Log::info($a->getEndMessage());
// Redirect to the home page
return redirect('/rounds');
}
public function editname($round_id)
{
$round = Round::where('id', $round_id)->first();
return view('rounds.editname', compact('round'));
}
public function storename()
{
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
$a=new TimeLogger("RoundsController::storename()");
Log::info($a->getStartMessage());
// Validate form
$this->validate(request(), [
'round_id' => 'required',
'name' => 'required'
]);
$round = Round::where('id', request('round_id'))->first();
$round->name = request('name');
$round->save();
Log::info($a->getEndMessage());
return redirect('/rounds');
}
}

View file

@ -0,0 +1,207 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Season;
use App\Round;
use App\Quota;
use App\User;
use App\Game;
use App\Tipp;
use App\ManualPayout;
use Carbon;
use DB;
use Auth;
use Log;
class SeasonsController extends Controller
{
public function index() {
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
$seasons = DB::table('seasons')->get();
$currentSeason=Season::getCurrent();
$users = User::getActivesSortedByName();
$active_user_count = sizeof( $users );
$currentSeasonId=-1;
if ($currentSeason) {
$quotas = Quota::getQuotasForDisplay();
$payouts = Quota::getPayouts();
}
$winnerNames=array();
/*
$manualPayoutTypes=array('liga_platz1','liga_platz2','liga_platz3', 'liga_platz2_1', 'liga_platz3_1', 'pokal');
foreach($manualPayoutTypes as $payoutType) {
$user = ManualPayout::getWinner($payoutType);
$name="Festlegen";
if ($user) $name = $user->name;
$winnerNames[$payoutType] = $name;
}
*/
return view('seasons.index', compact('seasons','currentSeason','active_user_count','quotas','payouts', 'users', 'winnerNames'));
}
public function create() {
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
return view('seasons.create');
}
public function store() {
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
// Validate form
$this->validate(request(), [
'name' => 'required',
'roundcount' => 'required'
]);
// Create and save the season
$season = Season::create([
'name' => request('name'),
'rounds' => request('roundcount')
]);
$season->save();
Season::setCurrent($season->id);
Log::info('Setting season id=' .$season->id);
Quota::createDefaultQuota();
$nr=1;
$roundcount=request('roundcount');
$seasonId = Season::getCurrent()->id;
$endOfSeason = Carbon\Carbon::now()->addMonth(7);
while($nr<=$roundcount) {
$roundname="Runde ".$nr;
Log::info("Creating: ".$roundname);
$round = Round::create([
'name' => $roundname,
'season_id' => $seasonId
]);
$round->save();
$round_id = $round->id;
$game1 = Game::create([
'round_id' => $round_id,
'team1' => "Mannschaft 1",
'team2' => "Mannschaft 2",
//'kickoff' => User::toDBDate(request('game1_kickoff'))
'kickoff' => $endOfSeason
]);
$game1->save();
$game2 = Game::create([
'round_id' => $round_id,
'team1' => "Mannschaft 3",
'team2' => "Mannschaft 4",
'kickoff' => $endOfSeason
]);
$game2->save();
$game3 = Game::create([
'round_id' => $round_id,
'team1' => "Mannschaft 5",
'team2' => "Mannschaft 6",
'kickoff' => $endOfSeason
]);
$game3->save();
$game4 = Game::create([
'round_id' => $round_id,
'team1' => "Mannschaft 7",
'team2' => "Mannschaft 8",
'kickoff' => $endOfSeason
]);
$game4->save();
// Sign them in
$nr+=1;
}
Log::info("Round creation completed, now setting Tipps");
Tipp::createAllTips();
// Redirect to the home page
return redirect('/seasons');
}
public function store_quota() {
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
Log::info("--store_quota--");
Log::info(request());
$currentSeason=Season::getCurrent();
// Validate form
$this->validate(request(), [
'round_count' => 'required',
'season_id' => 'required',
'einsatz' => 'required',
'tagessieg' => 'required',
'platzierung' => 'required',
'platz1' => 'required',
'platz2' => 'required',
'platz3' => 'required',
'platz4' => 'required',
'platz5' => 'required',
'platz6' => 'required',
'platz7' => 'required',
'platz8' => 'required',
'platz9' => 'required',
'platz10' => 'required'
]);
Log::info("request validated");
// Create and save the season
Quota::setQuota('runden', request('round_count'));
Quota::setQuota('einsatz', request('einsatz'));
Quota::setQuota('tagessieg', str_replace(",",".",request('tagessieg')));
Quota::setQuota('platzierung', str_replace(",",".",request('platzierung')));
Quota::setQuota('platz1', str_replace(",",".",request('platz1')));
Quota::setQuota('platz2', str_replace(",",".",request('platz2')));
Quota::setQuota('platz3', str_replace(",",".",request('platz3')));
Quota::setQuota('platz4', str_replace(",",".",request('platz4')));
Quota::setQuota('platz5', str_replace(",",".",request('platz5')));
Quota::setQuota('platz6', str_replace(",",".",request('platz6')));
Quota::setQuota('platz7', str_replace(",",".",request('platz7')));
Quota::setQuota('platz8', str_replace(",",".",request('platz8')));
Quota::setQuota('platz9', str_replace(",",".",request('platz9')));
Quota::setQuota('platz10', str_replace(",",".",request('platz10')));
// Redirect to the home page
return redirect('/seasons');
}
public function setcurrent($new_season_id)
{
if (Auth::guest()) {
return redirect("/");
}
if (!Auth::user()->admin) {
return redirect("/");
}
Season::setCurrent($new_season_id);
return redirect("/seasons");
}
public function set_winner( $userId, $quotaName) {
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
ManualPayout::setWinner( $userId, $quotaName);
return redirect('/seasons');
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SessionsController extends Controller
{
function __construct() {
$this->middleware('guest', ['except' => 'destroy']); // Filter: Only guests = not logged in users are allowed. Everybody else is redirected away.
}
public function create() {
return view('sessions.create');
}
public function store() {
// Attempt to authenticate the user
$name=request('firstname')." ".request('lastname');
$password=request('password');
if (!auth()->attempt(['name'=>$name, 'password'=>$password])) {
return back()->withErrors(['message'=>'Bitte Logindaten prüfen und nochmal versuchen.']);
}
// And redirect to home page
return redirect()->home();
}
public function destroy() {
auth()->logout();
return redirect()->home();
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SettingController extends Controller
{
//
}

View file

@ -0,0 +1,362 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Season;
use App\Round;
use App\Game;
use App\Tipp;
use App\User;
use Auth;
use Log;
use DB;
use App\MyClasses\TimeLogger;
class TippsController extends Controller
{
//Duplicate from Tipps model
//TODO: Refactor usage to use only the Tipps version
public static function createTipps($user_id) {
$a=new TimeLogger("TippsController::createTipps()");
Log::info($a->getStartMessage());
$activeSeason = Season::getCurrent();
$rounds = Round::all()->where('season_id', '=', $activeSeason->id);
foreach($rounds as $round) {
$games=Game::all()->where('round_id','=',$round->id);
foreach($games as $game) {
// Tipp erzeugen wenn noch nicht vorhanden
$tipp = DB::table('tipps')->where([
['game_id','=',$game->id],
['user_id','=',$user_id]]
)->first();
if (! $tipp) {
//Log::info('Creating missing tip: game_id=' . $game->id . ", user_id=" . $user->id);
$tipp=Tipp::create([
'user_id' => $user_id,
'game_id'=> $game->id,
'score1'=> -1,
'score2'=> -1,
'joker'=> false
]);
$tipp->save();
}
}
}
Log::info($a->getEndMessage());
}
//Duplicate from Tipps model
//TODO: Refactor usage to use only the Tipps version
public static function createAllTips(){
$a=new TimeLogger("TippsController::createAllTipps()");
Log::info($a->getStartMessage());
$users = DB::table('users')->where('deleted',null)->get();
foreach($users as $user) {
TippsController::createTipps($user->id);
}
Log::info($a->getEndMessage());
}
public function index()
{
if (Auth::guest()) { return redirect("/"); }
$user = Auth::user();
$activeSeason = Season::getCurrent();
if (!$activeSeason) {
return redirect('/');
}
if (! User::payment_date($user->id, $activeSeason->id)) {
return view('users.no_payment');
}
$rounds = null;
TippsController::createTipps($user->id); // ggfs. fehlende Tipp Eintraege einfügen
$lastLockedRoundId=Round::getLastLockedRoundId();
$rounds = Round::where('season_id', '=', $activeSeason->id)->get();
$max_identical_jokertipps=$activeSeason->maxIdenticalJokertipps();
return view('tipps.index', compact('rounds', 'activeSeason', 'user', 'max_identical_jokertipps'));
}
public function edit($tipp_id) {
$tipp = Tipp::where('id','=',$tipp_id)->first();
$game = Game::where('id','=',$tipp->game_id)->first();
return view('tipps.edit',compact('tipp','game'));
}
public function edit4($round_id) {
$user=Auth::user();
Log::info("TippsController::edit4 for user-id ".$user->id);
Log::info("Multi fetch result for tipps");
$round=Round::where('id','=', $round_id)->first();
$games=Game::where('round_id', '=', $round_id)->get();
$tipps=Tipp::whereIn('game_id', [$games[0]->id, $games[1]->id, $games[2]->id, $games[3]->id])->where('user_id',$user->id)->get();
$tipp1=$tipps[0];
$game1=Game::where('id','=',$tipp1->game_id)->first();
$tipp2=$tipps[1];
$game2=Game::where('id','=',$tipp2->game_id)->first();
$tipp3=$tipps[2];
$game3=Game::where('id','=',$tipp3->game_id)->first();
$tipp4=$tipps[3];
$game4=Game::where('id','=',$tipp4->game_id)->first();
return view('tipps.edit4',compact('round','tipp1','tipp2','tipp3','tipp4', 'game1', 'game2', 'game3', 'game4'));
}
public function store() {
// Validate form
$this->validate(request(), [
'id' => 'required',
'score1' => 'required',
'score2' => 'required',
'round_id' => 'required'
]);
$user=Auth::user();
if ( is_null($user) ) {
Log::info("TippsController.store: No authenticated user detected. Aborting storage command.");
$tippLink="/tipps#";
$r=\App\Round::getFirstTippableRound();
if($r) $tippLink=$tippLink.$r->id;
// Redirect to the Rounds Index
return redirect($tippLink);
}
Log::info("TippsController::store for user-id ".$user->id);
// Fetch, modify, save Tipp
$tipp = Tipp::where('id', request('id'))->first();
$game = Game::where('id', $tipp->game_id)->first();
$round= Round::where('id',$game->round_id)->first();
//if (Round::hasLockedGame($round->id)) { return redirect('/tipps'); } // Für Schlauberger, die die Tippmaske auflassen.
$tipp->score1= request('score1');
$tipp->score2= request('score2');
if (request()->has('joker')) {
$tipp->joker=true;
Log::info("Request has joker");
} else {
$tipp->joker = false;
Log::info("Request has NO joker");
}
// Neuerung 2020-01-09: Joker nur speichern, wenn Ergebnis nicht schon zu oft "gejokert" wurde.
Log::info("Checking for joker");
if ($tipp->joker) {
Log::info("Joker found.");
$jokertipps=Tipp::getJokerUsageArray($user->id,$game->round_id);
$key=$tipp->score1.":".$tipp->score2;
Log::info("Key(Gamescore):".$key);
if (array_key_exists($key,$jokertipps)) {
Log::info("Key found in jokertipps array");
$value=$jokertipps[$key];
Log::info("Stored value:".$value);
$limit=Season::getCurrent()->maxIdenticalJokertipps();
if (intval($value)>=intval($limit)) {
Log::info("**JOKERLIMIT REACHED FOR GAMESCORE:".$key);
return redirect('/tipps/joker_impossible');
}
}
}
$tipp->save();
// Joker gesetzt ? Dann Jokerflag für alle Tipps der selben Runde entfernen
if ($tipp->joker){
//Log::info("Checking for joker strip");
$game=Game::where('id','=',$tipp->game_id)->first();
$round_id=$game->round_id;
$games = DB::table('games')->where('round_id', '=', request('round_id'))->get();
foreach ($games as $game) {
$tipp = Tipp::where('user_id', $user->id)->where('game_id', $game->id)->first();
//Log::info("Testing game_id " . $game->id);
if ($tipp->id != request('id')) {
//Log::info("Resetting game_id " . $game->id);
$tipp->joker = false;
$tipp->save();
}
}
}
$tippLink="/tipps#";
$r=\App\Round::getFirstTippableRound();
if($r) $tippLink=$tippLink.$r->id;
// Redirect to the Rounds Index
return redirect($tippLink);
}
// Try to store all 4 tipps of the round one by one.
// If one fails, previous saves are kept, but user
// is redirected to edit4 page again.
public function store4() {
Log::debug("### Store4 ###");
error_log("--- Store4 ---");
// Validate form
//dd(request());
$this->validate(request(), [
'round_id' => 'required',
'game_id_1' => 'required',
'game_id_2' => 'required',
'game_id_3' => 'required',
'game_id_4' => 'required',
'tipp_id_1' => 'required',
'tipp_id_2' => 'required',
'tipp_id_3' => 'required',
'tipp_id_4' => 'required',
'score1_1' => 'required',
'score1_2' => 'required',
'score1_3' => 'required',
'score1_4' => 'required',
'score2_1' => 'required',
'score2_2' => 'required',
'score2_3' => 'required',
'score2_4' => 'required'
]);
error_log("Validation passed.");
$round_id= request('round_id');
$game_id_1=request('game_id_1');
$game_id_2=request('game_id_2');
$game_id_3=request('game_id_3');
$game_id_4=request('game_id_4');
$tipp_id_1=request('tipp_id_1');
$tipp_id_2=request('tipp_id_2');
$tipp_id_3=request('tipp_id_3');
$tipp_id_4=request('tipp_id_4');
$score1_1=request('score1_1');
$score1_2=request('score1_2');
$score1_3=request('score1_3');
$score1_4=request('score1_4');
$score2_1=request('score2_1');
$score2_2=request('score2_2');
$score2_3=request('score2_3');
$score2_4=request('score2_4');
$joker_1=false;
$joker_2=false;
$joker_3=false;
$joker_4=false;
if (request()->has('joker_1')) {
$joker_1=true;
} elseif (request()->has('joker_2')) {
$joker_2=true;
} elseif (request()->has('joker_3')) {
$joker_3=true;
} elseif (request()->has('joker_4')) {
$joker_4=true;
}
// If store fails, the jokerlimit has been reached. Redirect to edit4 page
if (self::tryStore($tipp_id_1, $game_id_1, $round_id, $score1_1, $score2_1, $joker_1 ) == false) {
//return redirect('/tipps/edit4/'.$round_id);
return redirect('/tipps/joker_impossible');
}
// If store fails, the jokerlimit has been reached. Redirect to edit4 page
if (self::tryStore($tipp_id_2, $game_id_2, $round_id, $score1_2, $score2_2, $joker_2) == false) {
return redirect('/tipps/joker_impossible');
}
// If store fails, the jokerlimit has been reached. Redirect to edit4 page
if (self::tryStore($tipp_id_3, $game_id_3, $round_id, $score1_3, $score2_3, $joker_3 ) == false) {
return redirect('/tipps/joker_impossible');
}
// If store fails, the jokerlimit has been reached. Redirect to edit4 page
if (self::tryStore($tipp_id_4, $game_id_4, $round_id, $score1_4, $score2_4, $joker_4 ) == false) {
return redirect('/tipps/joker_impossible');
}
$tippLink="/tipps#";
$r=\App\Round::getFirstTippableRound();
if($r) $tippLink=$tippLink.$r->id;
// Redirect to the Rounds Index
return redirect($tippLink);
}
// Store tipp if valid.
public function tryStore($tipp_id, $game_id, $round_id, $score1, $score2, $has_joker ) {
Log::info("Starting tryStore");
$user=Auth::user();
$tipp = Tipp::where('id', $tipp_id)->first();
Log::info("tipp_id=".$tipp->id);
$game = Game::where('id', $game_id)->first();
$round= Round::where('id',$round_id)->first();
$tipp->joker=$has_joker;
// Neuerung 2020-01-09: Joker nur speichern, wenn Ergebnis nicht schon zu oft "gejokert" wurde.
if ($tipp->joker) {
$jokertipps=Tipp::getJokerUsageArray($user->id,$round_id);
$key=$score1.":".$score2;
Log::info("Key(Gamescore):".$key);
if (array_key_exists($key,$jokertipps)) {
//Log::info("Key found in jokertipps array");
$value=$jokertipps[$key];
Log::info("Stored value:".$value);
$limit=Season::getCurrent()->maxIdenticalJokertipps();
if (intval($value)>=intval($limit)) {
Log::info("**JOKERLIMIT REACHED FOR GAMESCORE:".$key);
Log::info("Returning false");
return false; // Returning false should make store4 method return to edit4 page.
}
}
}
Log::info("tryStore: Saving score ".$score1.":".$score2." for user-id ".$user->id);
$tipp->score1=$score1;
$tipp->score2=$score2;
$tipp->joker=$has_joker;
$tipp->save();
Log::info("Returning true");
return true; // Returning true should make store4 method return to general tipps (index) page.
}
// belongs to old single tipp functionality.
public static function joker_impossible() {
return view('tipps.joker_impossible');
}
}

View file

@ -0,0 +1,896 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Season;
use App\Payment;
use App\Round;
use App\Game;
use App\Tipp;
use App\Quota;
use App\Mail\RoundmailMailer;
use Password;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Auth\Passwords\PasswordBroker;
use DB;
use Auth;
use Log;
use Carbon;
use App\MyClasses\TimeLogger;
class UsersController extends Controller
{
public function main() {
//$a=new TimeLogger("UsersController::main()");
//Log::info($a->getStartMessage());
$currentSeason=Season::getCurrent();
$roundname="";
$report="";
// display_rounds berechnen für Nav und Rundenberichte
$display_rounds=array();
if ($currentSeason) {
$round_id = Round::getLastCompleteRoundId();
if ($round_id > -1) {
$rounds = Round::where("id", "<=", $round_id)->where('season_id','=',$currentSeason->id)->get();
foreach($rounds as $round) {
$dpr =array();
$dpr["name"]=$round->name;
$dpr["report"]=$round->report;
array_push($display_rounds, $dpr);
}
$display_rounds = array_reverse($display_rounds);
Log::info("Loaded report:".$report." round-id=".$round_id);
$roundname = $round->name;
} else { Log::info("No round identified. Last Locked=".$round_id); $report="";}
} else {Log::info("No current season");}
$nextRoundName="";
$nextRound = Round::getFirstTippableRound();
$nextRoundName = "";
$nextRoundLockTime = "";
$diffToLock ="";
$hourDiffToLock = 999;
if ($nextRound) {
$nextRoundName = $nextRound->name;
$nextRoundLockTime = $nextRound->getLockTime();
$hourDiffToLock=$nextRoundLockTime->diffInHours(Carbon\Carbon::now());
if ($hourDiffToLock==0) {
$diffMin=$nextRoundLockTime->diffInMinutes(Carbon\Carbon::now());
if ($diffMin==0) { $diffMin=1;}
if ($diffMin==1) {
$hourDiffToLock = $nextRoundLockTime->diffInMinutes(Carbon\Carbon::now())." Minute";
} else {
$hourDiffToLock = $nextRoundLockTime->diffInMinutes(Carbon\Carbon::now())." Minuten";
}
} else {
if ($hourDiffToLock==1) {
$hourDiffToLock = $hourDiffToLock." Stunde";
} else{
$hourDiffToLock = $hourDiffToLock." Stunden";
}
}
}
$user=Auth::user();
$message_text_tipps="";
$message_text_joker="";
if ($user && $currentSeason) {
if (User::hasMissingTipp($user->id)) {
$message_text_tipps="Fehlende Tipps für ".$nextRoundName;
}
if (User::hasMissingJoker($user->id)) {
$message_text_joker="Fehlender Joker für ".$nextRoundName;
}
}
//Log::info($a->getEndMessage());
return view('main',compact('roundname','display_rounds','message_text_joker','message_text_tipps','nextRoundName','nextRoundLockTime', 'hourDiffToLock'));
}
public function index() {
error_log("Starting Controller: UsersController.index");
$a=new TimeLogger("UserController::index()");
Log::info($a->getStartMessage());
error_log($a->getStartMessage());
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
$activeUsers = User::getActives();
$b=new TimeLogger("UsersController::index-db_subqueries");
Log::info($b->getStartMessage());
$currentSeason=Season::getCurrent();
if (!$currentSeason) { return redirect('/'); }
$active_user_count = sizeof( $activeUsers );
//$total_user_count = sizeof( DB::table('payments')->where('season_id',$currentSeason->id)->get() );
$users = DB::table('users')->where('deleted',null)->orderBy('lastname')->get();
$total_user_count = sizeof($users);
Log::info($b->getEndMessage());
Log::info($a->getStartMessage());
$missingTipps = User::getMissingTippsAndJokers($activeUsers);
Log::info("Missing tipps id overview:");
foreach($missingTipps["MISSING_TIPP"] as $uid => $val) {
Log::info($uid);
}
$c=new TimeLogger("UsersController::index-missingTipp Loop");
Log::info($c->getStartMessage());
$actIds=array();
foreach ($activeUsers as $aUser) {
Log::info("Active user: ".$aUser->id." ".$aUser->name);
$actIds[$aUser->id]=$aUser->id;
}
foreach($users as $index => $user) {
Log::info("Filling in data for user_id ".$user->id);
if (!array_key_exists($user->id, $actIds)) {
Log::info("Inactive id: " . $user->id);
$users[$index]->missingTippText = "inaktiv";
$users[$index]->tippStyling = "grey";
$users[$index]->missingJokerText = "inaktiv";
$users[$index]->jokerStyling = "grey";
} else {
if (array_key_exists($user->id, $missingTipps["MISSING_TIPP"])) {
Log::info("..adding missing tipp");
$users[$index]->missingTippText = "Tipps fehlen";
$users[$index]->tippStyling = "red";
} else {
Log::info("..adding existing tipp");
$users[$index]->missingTippText = "Runde getippt";
$users[$index]->tippStyling = "green";
}
Log::info("UsersController.index: Joker Display Check for UserId=".$user->id);
if (array_key_exists($user->id, $missingTipps["MISSING_JOKER"])) {
Log::info("UsersController.index: MISSING JOKER DETECTED -> ".$user->id);
$users[$index]->missingJokerText = "Joker fehlt";
$users[$index]->jokerStyling = "red";
} else {
Log::info("UsersController.index: JOKER EXISTS -> ".$user->id);
$users[$index]->missingJokerText = "Joker gesetzt";
$users[$index]->jokerStyling = "green";
}
}
}
Log::info($c->getEndMessage());
$round = Round::getFirstTippableRound();
$firstTippableRound=new Round();
$firstTippableRound->name="-";
if ($round) { $firstTippableRound = $round; }
Log::info($a->getEndMessage());
error_log($a->getEndMessage());
error_log($users);
return view('users.index', compact('users','active_user_count','total_user_count', 'firstTippableRound'));
}
public function index_deleted() {
$a=new TimeLogger("UserController::index_deleted()");
Log::info($a->getStartMessage());
//error_log($a->getStartMessage());
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
$users = User::whereNotNull('deleted')->orderBy('deleted','DESC')->get();
$currentSeason=Season::getCurrent();
if (!$currentSeason) { return redirect('/'); }
return view('users.index_deleted', compact('users'));
}
/*
public function showUsers() {
$users = DB::table('users')->orderBy('lastname')->get();
return view('users.list', compact('users'));
}
*/
// Route-Model binding, because parameter in web.php route has same name as functionparameter
public function showUser(User $userObject) {
//return $userObject; // If you want it as a JSON object
//$user = DB::table('users')->find($id);
return view('users.show', compact('userObject'));
}
public function edit($user_id) {
if (Auth::guest()) { return redirect("/"); }
if (!Auth::user()->admin) { return redirect("/"); }
$user = User::where('id',$user_id)->first();
$season_id = Season::getCurrent()->id;
$paid_date_str="";
$val=User::payment_date($user_id, $season_id);
if ($val) { $paid_date_str=User::toGermanDate($val);}
return view ('users.edit', compact('user','paid_date_str'));
}
public function store() {
if (Auth::guest()) { return redirect("/"); }
$a=new TimeLogger("UsersController::store()");
Log::info($a->getStartMessage());
//error_log($a->getStartMessage());
Log::info("## Fetching current id");
$season_id = Season::getCurrent()->id;
Log::info("## id = ".$season_id);
Log::info("## Validating form");
// Validate form
$this->validate(request(), [
'id' => 'required',
'firstname' => 'required',
'lastname' => 'required',
'email'=> 'required'
]);
Log::info("## Validation successful");
Log::info("## Fetching user");
$user=User::where('id', request('id'))->first();
Log::info("## Setting user fields");
$user->name=request('firstname')." ".request('lastname');
$user->firstname=request('firstname');
$user->lastname=request('lastname');
$user->email=request('email');
Log::info("## Request sanity checking");
if (request()->has('iban')) { $user->iban = request('iban'); }
if (request()->has('bankname')) { $user->bankname = request('bankname'); }
if (request()->has('blz')) { $user->blz = request('blz'); }
if (request()->has('kontonr')) { $user->kontonr = request('kontonr'); }
if (request()->has('mobile')) { $user->mobile = request('mobile'); }
if (request()->has('admin')) {
$user->admin = true;
Log::info("## user IS admin");
} else {
$user->admin=false;
Log::info("## user is NO admin");
}
Log::info("## Storing user");
$user->save();
Log::info("## Storing user completed");
Log::info("## Setting payment request date started");
Payment::set_payment_date(request('id'), $season_id, request('paid'));
Log::info("## Setting payment request date done");
//Tipp::createAllTips();
Log::info($a->getEndMessage());
//error_log($a->getEndMessage());
return redirect('/users');
}
public function ranking($max_round_id, $seasonId=-1) {
if (!Auth::user()) { return redirect("/"); }
$startTime = microtime(true);
$season = Season::getCurrent();
if ( $seasonId !=-1 ) {
$season=Season::where('id','=',$seasonId)->first();
$seasonId = $season->id;
} else {
$seasonId = $season->id;
}
// Check ob mindestens eine Runde der Saison gelockt ist, die angezeigt werden kann
if($max_round_id==-1) {
$max_round_id = Round::getLastLockedRoundId();
if ($max_round_id==-1) {
$sql="SELECT DATE_FORMAT(date_sub(games.kickoff, INTERVAL 1 MINUTE),'%d.%m.%Y %H:%i') as start_date from rounds,games where rounds.season_id=".$seasonId." and games.round_id=rounds.id order by games.id limit 1;";
//dd($sql);
$entries = DB::select(DB::raw($sql));
if (count($entries)>0) {
$start_date = $entries[0]->start_date;
return view('users.no_ranking', compact('start_date'));
} else {
return redirect("/");
}
}
}
$max_round_id=min($max_round_id, Round::getLastLockedRoundId());
// Payment made ?
if (! User::payment_date(Auth::user()->id, $season->id) && Auth::user()->name!="Torsten Schneider") {
return view('users.no_payment');
}
$response = Tipp::getRoundTipps($max_round_id);
$roundtipps = $response['roundtipps'];
$roundData = $response['roundData'];
$user_ids = $response['user_ids'];
$round_ids = $response['round_ids'];
///////////////////////////// DISPLAY AUFBAU /////////////////////////////
///
// AUFBAU RANKINGLISTE A.K.A. RANKINGDISPLAY AB HIER NUR NOCH ANZEIGE-SPEZIFIKA !
// Aufbau der Rankingliste in rankingDisplay, sowie aufaddieren der jeweiligen Punkte.
// Loop through games and users (again)
$rankingDisplay=array();
$isFinalRound=false;
foreach ($user_ids as $user_id) {
$round_id = $max_round_id;
$key = $round_id . "_" . $user_id;
if ($roundtipps[$key]["ranking_payout"]>0) {
$isFinalRound=true;
}
}
$payoutList = Quota::getPayoutList($response);
Log::info("Starting Display Loop");
foreach ($user_ids as $user_id) {
$rankscore_total= 0;
$payout_sum = 0;
$round_id = $max_round_id;
$key = $round_id . "_" . $user_id;
if (!array_key_exists($user_id, $rankingDisplay)) {
$rankingDisplay[$user_id] = array();
$rankingDisplay[$user_id]["user_id"] = $user_id;
$rankingDisplay[$user_id]["round_id"] = $round_id;
$rankingDisplay[$user_id]["rank"] = $roundtipps[$key]["rank"];
$rankingDisplay[$user_id]["payout"] = $roundtipps[$key]["payout"];
$rankingDisplay[$user_id]["user_name"] = $roundtipps[$key]["user_name"];
$rankingDisplay[$user_id]["is_dayscorewinner"] = $roundtipps[$key]["is_dayscorewinner"];
$rankingDisplay[$user_id]["grank"] = $roundtipps[$key]["grank"];
$rankingDisplay[$user_id]["gshirt_score"] = $roundtipps[$key]["gshirt_score"];
$rankingDisplay[$user_id]["gshirt_totalscore"] = $roundtipps[$key]["gshirt_totalscore"];
$rankingDisplay[$user_id]["gshirt_foulcount"] = $roundtipps[$key]["gshirt_foulcount"];
$rankingDisplay[$user_id]["gshirt_leader"] = $roundtipps[$key]["gshirt_leader"];
$rankingDisplay[$user_id]["ranking_payout"] = $roundtipps[$key]["ranking_payout"];
$rankingDisplay[$user_id]["rankscore"] = $roundtipps[$key]["rankscore"]; // Summe Rangwertung alle 4 Spiele/Tipps der letzten durchlaufenen Runde, NICHT in init stellen !!
$rankingDisplay[$user_id]["dayscore"] = $roundtipps[$key]["dayscore"]; // Dayscore der letzten durchlaufenen Runde, NICHT in init stellen !!
$rankingDisplay[$user_id]["dayScoreWithRankScore"] = $roundtipps[$key]["dayScoreWithRankScore"]; // Dayscore der letzten durchlaufenen Runde, NICHT in init stellen !!
}
$rankingDisplay[$user_id]["totalRankScore"] = $roundtipps[$key]['totalRankScore'];
$rankingDisplay[$user_id]["tipp_score1"] = $roundtipps[$key]["tipps"][0];
$rankingDisplay[$user_id]["tipp_score2"] = $roundtipps[$key]["tipps"][1];
$rankingDisplay[$user_id]["joker1"] = $roundtipps[$key]["joker"][0];
$rankingDisplay[$user_id]["result_score1"] = $roundtipps[$key]["results"][0];
$rankingDisplay[$user_id]["result_score2"] = $roundtipps[$key]["results"][1];
// Determine coloration for Game1
$rankingDisplay[$user_id]["trendCol1"] = Tipp::trendCol($roundtipps[$key]["results"][0],$roundtipps[$key]["results"][1],
$roundtipps[$key]["tipps"][0],$roundtipps[$key]["tipps"][1],
$roundtipps[$key]["joker"][0]);
$rankingDisplay[$user_id]["tipp_score3"] = $roundtipps[$key]["tipps"][2];
$rankingDisplay[$user_id]["tipp_score4"] = $roundtipps[$key]["tipps"][3];
$rankingDisplay[$user_id]["joker2"] = $roundtipps[$key]["joker"][1];
$rankingDisplay[$user_id]["result_score3"] = $roundtipps[$key]["results"][2];
$rankingDisplay[$user_id]["result_score4"] = $roundtipps[$key]["results"][3];
// Determine coloration for Game2
$rankingDisplay[$user_id]["trendCol2"] = Tipp::trendCol($roundtipps[$key]["results"][2],$roundtipps[$key]["results"][3],
$roundtipps[$key]["tipps"][2],$roundtipps[$key]["tipps"][3],
$roundtipps[$key]["joker"][1]);
$rankingDisplay[$user_id]["tipp_score5"] = $roundtipps[$key]["tipps"][4];
$rankingDisplay[$user_id]["tipp_score6"] = $roundtipps[$key]["tipps"][5];
$rankingDisplay[$user_id]["joker3"] = $roundtipps[$key]["joker"][2];
$rankingDisplay[$user_id]["result_score5"] = $roundtipps[$key]["results"][4];
$rankingDisplay[$user_id]["result_score6"] = $roundtipps[$key]["results"][5];
// Determine coloration for Game3
$rankingDisplay[$user_id]["trendCol3"] = Tipp::trendCol($roundtipps[$key]["results"][4],$roundtipps[$key]["results"][5],
$roundtipps[$key]["tipps"][4],$roundtipps[$key]["tipps"][5],
$roundtipps[$key]["joker"][2]);
$rankingDisplay[$user_id]["tipp_score7"] = $roundtipps[$key]["tipps"][6];
$rankingDisplay[$user_id]["tipp_score8"] = $roundtipps[$key]["tipps"][7];
$rankingDisplay[$user_id]["joker4"] = $roundtipps[$key]["joker"][3];
$rankingDisplay[$user_id]["result_score7"] = $roundtipps[$key]["results"][6];
$rankingDisplay[$user_id]["result_score8"] = $roundtipps[$key]["results"][7];
// Determine coloration for Game4
$rankingDisplay[$user_id]["trendCol4"] = Tipp::trendCol($roundtipps[$key]["results"][6],$roundtipps[$key]["results"][7],
$roundtipps[$key]["tipps"][6],$roundtipps[$key]["tipps"][7],
$roundtipps[$key]["joker"][3]);
if ($isFinalRound==true) {
// Add GShirt, Playoff, Pokal payout
Log::info("!> ".$user_id);
$rankingDisplay[$user_id]['gshirt_payout'] = 0;
$rankingDisplay[$user_id]['pokal'] = 0;
$rankingDisplay[$user_id]['playoff'] = 0;
$userPayouts = $payoutList[$user_id];
$hasGreenShirtGame=Season::hasGreenShirtGame();
foreach ($userPayouts as $payoutItem) {
Log::info($user_id." - ".$payoutItem['roundname']);
if ($hasGreenShirtGame) {
if ($payoutItem['roundname'] == "Grünes Trikot") {
$rankingDisplay[$user_id]["gshirt_payout"] = $payoutItem['payout'];
Log::info("GreenShirt goes to: ".$user_id);
}
}
if ($payoutItem['roundname'] == 'Pokal') {
$rankingDisplay[$user_id]["pokal"] = $payoutItem['payout'];
Log::info("Pokal goes to: ".$user_id);
}
if (strpos($payoutItem['roundname'], 'Liga') !== false) {
$rankingDisplay[$user_id]["playoff"] = $payoutItem['payout'];
Log::info($payoutItem['roundname']." goes to: ".$user_id);
}
}
}
}
$userids = array_keys($rankingDisplay);
$round=Round::where('id','=',$max_round_id)->first();
$games=Game::where('round_id','=',$max_round_id)->get();
$all_rounds=Round::where('season_id','=',$season->id)->get();
// Sortieren nach Rankscore
$entries = array();
usort($rankingDisplay, array($this,"cmp"));
foreach($rankingDisplay as $entry) {
array_push($entries, $entry);
}
$rankingDisplay = $entries;
// Store game results as separate array. Wir nutzen aus, dass die Ergebnisse in jeder Zeile
// von Rankingdisplay abgespeichert sind.
$game_results=array(); // 4 Spielergebnisse der angezeigten Runde
array_push($game_results,$rankingDisplay[0]["result_score1"],$rankingDisplay[0]["result_score2"],$rankingDisplay[0]["result_score3"],$rankingDisplay[0]["result_score4"],$rankingDisplay[0]["result_score5"],$rankingDisplay[0]["result_score6"],$rankingDisplay[0]["result_score7"],$rankingDisplay[0]["result_score8"]);
Log::info("UserController::ranking: ExecutionTime: " . number_format(( microtime(true) - $startTime), 4) . " Seconds\n");
//dd($rankingDisplay);
return view('users.ranking', compact('all_rounds','rankingDisplay','userids','round','games','game_results','isFinalRound'));
}
public function cmp($user1, $user2) {
return ($user1['totalRankScore'] < $user2['totalRankScore']);
}
public function cmpDayWin($user1, $user2) {
return ($user1[1] < $user2[1]); // Feld0: user_id, Feld1: dayScoreWithRankScore
}
public function cmpRank($rank1, $rank2) {
return ($rank1[1] < $rank2[1]);
}
public function show_payouts() {
$currentSeason = Season::getCurrent();
$active_user_count = sizeof(User::getActives());
$quotas = Quota::getQuotas();
$payouts = Quota::getPayouts();
return view('users.show_payouts', compact('payouts','active_user_count','quotas','currentSeason'));
}
public function mailtest() {
// Works:
// $user = User::where('id','=',1)->first();
// \Mail::to($user)->send(new RoundmailMailer);
$users = User::whereIn('id',array(1))->get();
foreach($users as $user) {
Log::info("Sending RoundmailMailer to: ".$user->name);
\Mail::to($user)->send(new RoundmailMailer);
}
}
public function test() {
//Password::sendResetLink(['email','magus@zauberturm.de']);
$request = new Request();
$request->merge(['email'=>'magus@zauberturm.de']);
$broker = $this->getBroker();
$response = Password::broker($broker)->sendResetLink($request->only('email'), function (Message $message) {
$message->subject($this->getEmailSubject());
});
}
// App\Http\Controllers\Auth\ForgotPasswordController@sendResetLinkEmail
public function reset() {
return view('auth.passwords.email');
}
public function processReset(Request $request) {
$response = $this->broker()->sendResetLink(
$request->only('email')
);
}
//route: useredit => useredit view
public function useredit($user_id) {
if (Auth::guest()) { return redirect("/"); }
$user=Auth::user();
$paid_date_str="";
$val=User::payment_date($user_id, Season::getCurrent()->id);
if ($val) { $paid_date_str=User::toGermanDate($val);}
return view ('users.useredit', compact('user','paid_date_str'));
}
public function send_reset_links_from_settings() {
if (Auth::guest()) { return redirect("/"); }
$this->sendResetLink(Auth::user());
}
public function storeUserEdit() {
Log::info("storeUserEdit");
if (Auth::guest()) { return redirect("/"); }
Log::info("Auth ok");
Log::info("Request:");
Log::info(request());
$season_id = Season::getCurrent()->id;
// Validate form
$this->validate(request(), [
'email'=> 'required'
]);
$user=Auth::user();
$user->email=request('email');
if (request()->has('gets_reminders')) {
Log::info("No reminder");
$user->gets_reminders = true;
} else {
Log::info("Set reminder");
$user->gets_reminders=false;
}
if (request()->has('iban')) {
$user->iban = request('iban');
}
if (request()->has('blz')) {
$user->blz=request('blz');
}
if (request()->has('bankname')) {
$user->bankname=request('bankname');
}
if (request()->has('kontonr')) {
$user->kontonr=request('kontonr');
}
if (request()->has('mobile')) {
$user->mobile=request('mobile');
}
Log::info("Setting gets_reminders to: " . request('gets_reminders'));
$user->save();
return redirect('/');
}
public function delete($user_id) {
if (!Auth::user()->admin) redirect("/users");
User::softDelete($user_id);
return redirect("/users");
}
public function restore($user_id) {
if (!Auth::user()->admin) redirect("/users");
$user=User::where('id','=',$user_id)->first();
$user->deleted = null;
$user->save();
return redirect("/users");
}
public function money_ranking() {
if (Auth::guest()) { return redirect("/"); }
$currentSeason = Season::getCurrent();
if (!$currentSeason) {
return view('users.no_ranking', compact('start_date'));
}
// Payment made ?
if (! User::payment_date(Auth::user()->id, $currentSeason->id) && Auth::user()->name!="Torsten Schneider") {
return view('users.no_payment');
}
// Check ob mindestens eine Runde der Saison gelockt ist angezeigt werden kann
$seasonId=$currentSeason->id;
$max_round_id = Round::getLastCompleteRoundId();
if ($max_round_id==-1) {
$sql="select DATE_FORMAT(date_sub(min(games.kickoff), interval 1 hour),'%d.%m.%Y %H:%i') as start_date from rounds,games where rounds.season_id=".$seasonId." and games.round_id=rounds.id order by rounds.id;";
//dd($sql);
$entries = DB::select($sql);
if (count($entries)>0) {
$start_date = $entries[0]->start_date;
return view('users.no_ranking', compact('start_date'));
} else {
return redirect("/");
}
}
$sortedPayout = Quota::getPayoutPerUser();
return view ('users.payout_ranking_index',compact('sortedPayout'));
}
public function money_ranking_with_iban() {
if (Auth::guest()) { return redirect("/"); }
$currentSeason = Season::getCurrent();
// Payment made ?
if (! User::payment_date(Auth::user()->id, $currentSeason->id) && Auth::user()->name!="Torsten Schneider") {
return view('users.no_payment');
}
$response = Tipp::getRoundTipps();
if (sizeof($response)==0) {
return redirect("/");
}
$roundtipps = $response['roundtipps'];
$roundData = $response['roundData'];
$user_ids = $response['user_ids'];
$round_ids = $response['round_ids'];
$payoutTotal = array();
$cnt=0;
foreach($round_ids as $round_id) {
foreach($user_ids as $user_id) {
$key=$round_id."_".$user_id;
$payout = str_replace(",",".",$roundtipps[$key]['payout']);
if (strlen($payout)==0) { $payout=0; }
if (!array_key_exists($user_id, $payoutTotal)) {
$payoutTotal[$user_id]['amount']=0;
$payoutTotal[$user_id]['name']=$roundtipps[$key]['user_name'];
$payoutTotal[$user_id]['user_id']=$roundtipps[$key]['user_id'];
}
$payoutTotal[$user_id]['amount'] += $payout;
$payout_ranking = $roundtipps[$key]['ranking_payout'];
$payoutTotal[$user_id]['amount'] += $payout_ranking;
}
}
$sortedPayout=array();
foreach($payoutTotal as $payout) {
$payment=array();
$payment['user_id']=$payout['user_id'];
$payment['name']=$payout['name'];
$payment['amount']=$payout['amount'];
$user=User::where('id','=',$payout['user_id'])->first();
$payment['iban']=$user->iban;
$payment['blz']=$user->blz;
$payment['bankname']=$user->bankname;
$payment['kontonr']=$user->kontonr;
array_push($sortedPayout,$payment);
}
usort($sortedPayout,array($this,'cmpPayment'));
$users=User::getActives();
return view ('users.payout_ranking_index_with_iban',compact('sortedPayout','users'));
}
public function cmpPayment($payment1, $payment2) {
return ($payment1['amount'] < $payment2['amount']);
}
public function money_ranking_detail($user_id) {
$currentSeason = Season::getCurrent();
// Payment made ?
if (! User::payment_date(Auth::user()->id, $currentSeason->id) && Auth::user()->name!="Torsten Schneider") {
return view('users.no_payment');
}
$payouts = Quota::getPayoutPerUserDetails($user_id);
$user = User::where('id','=',$user_id)->first();
return view ('users.payout_ranking_detail',compact('payouts','user'));
}
public function gshirt_ranking() {
if (Auth::guest()) { return redirect("/"); }
// Check ob mindestens eine Runde der Saison gelockt ist und angezeigt werden kann
$season=Season::getCurrent();
$seasonId=$season->id;
$max_round_id = Round::getLastCompleteRoundId();
if ($max_round_id==-1) {
$sql="select DATE_FORMAT(date_sub(min(games.kickoff), interval 1 hour),'%d.%m.%Y %H:%i') as start_date from rounds,games where rounds.season_id=".$seasonId." and games.round_id=rounds.id order by rounds.id;";
//dd($sql);
$entries = DB::select($sql);
if (count($entries)>0) {
$start_date = $entries[0]->start_date;
return view('users.no_ranking', compact('start_date'));
} else {
return redirect("/");
}
}
$rankingDisplay = Tipp::gshirt_table();
$usernames = User::getNames();
$roundnames = array();
foreach ($rankingDisplay[0] as $user_round) {
array_push($roundnames, $user_round['round_name']);
}
return view ('users.gshirt_ranking', compact('rankingDisplay','usernames', 'roundnames'));
}
public function no_payment() {
return view ('users.no_payment');
}
public function playoff_report() {
if (Auth::guest()) { return redirect("/"); }
$season=Season::getCurrent();
$seasonId=$season->id;
$sql="select playoff_report from seasons where id=$seasonId";
$result = DB::select($sql);
$playoff_report = $result[0]->playoff_report ?? 'Playoff Daten: Noch keine.';
return view ('users.playoff_report', compact('playoff_report'));
}
public function playoff_report_edit() {
if (!Auth::user()->admin) { return redirect("/"); }
$season=Season::getCurrent();
$seasonId=$season->id;
$sql="select playoff_report from seasons where id=$seasonId";
$result = DB::select($sql);
$playoff_report = $result[0]->playoff_report ?? 'Playoff Daten: Noch keine.';
return view ('users.playoff_report_edit', compact('playoff_report'));
}
public function store_playoff() {
$playoff_report = str_replace("'", "", request('playoff'));
$season=Season::getCurrent();
$seasonId=$season->id;
DB::update("UPDATE seasons SET playoff_report='$playoff_report' WHERE id=$seasonId;");
return redirect("/users/playoff");
}
public function pokal_report() {
if (Auth::guest()) { return redirect("/"); }
$season=Season::getCurrent();
$seasonId=$season->id;
$sql="select pokal_report from seasons where id=$seasonId";
$result = DB::select($sql);
$pokal_report = $result[0]->pokal_report ?? 'Pokal Daten: Noch keine.';
return view ('users.pokal_report', compact('pokal_report'));
}
public function pokal_report_edit() {
if (!Auth::user()->admin) { return redirect("/"); }
$season=Season::getCurrent();
$seasonId=$season->id;
$sql="select pokal_report from seasons where id=$seasonId";
$result = DB::select($sql);
$pokal_report = $result[0]->pokal_report ?? 'Pokal Daten: Noch keine.';
return view ('users.pokal_report_edit', compact('pokal_report'));
}
public function store_pokal() {
$pokal_report = str_replace("'", "", request('pokal'));
$season=Season::getCurrent();
$seasonId=$season->id;
DB::update("UPDATE seasons SET pokal_report='$pokal_report' WHERE id=$seasonId;");
//return view('users.pokal_report', compact('pokal_report'));
return redirect("/users/pokal");
}
}

View file

@ -0,0 +1,60 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}

View file

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as BaseEncrypter;
class EncryptCookies extends BaseEncrypter
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}

View file

@ -0,0 +1,26 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}

View file

@ -0,0 +1,18 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as BaseTrimmer;
class TrimStrings extends BaseTrimmer
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
'password',
'password_confirmation',
];
}

View file

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
}

View file

@ -0,0 +1,835 @@
<?php
namespace App\Leagues;
use Illuminate\Database\Eloquent\Model;
use App\Season;
use App\Round;
use App\User;
use App\Leagues\LeagueMember;
use DB;
use Log;
use App\MyClasses;
class League extends Model
{
const RANK_LEAGUE1 = 1;
const RANK_LEAGUE2 = 2;
const RANK_LEAGUE3 = 3;
const RANK_QUALIFICATION = 4;
protected $table ='leagues';
protected $fillable = [
'id','season_id','is_qualification','rank','subrank','start_round_id','round_count','name'
];
//
public static function neededLeagues($member_count, $round_count) {
$max_members_per_league=22;
if ($member_count<=$max_members_per_league) return 1;
$neededLeagues = intdiv($member_count, $max_members_per_league);
if ( $member_count - $max_members_per_league * $neededLeagues ) {
$neededLeagues+=1;
}
return $neededLeagues;
}
public static function getMemberCount($league_id) {
$members = DB::table('leagues_members')->where('league_id','=',$league_id)->get();
return sizeof($members);
}
public static function getNames() {
$season = Season::getCurrent();
$leagues = League::where('season_id','=',$season->id)->orderBy('rank')->orderBy('name')->get();
$leagueNames = array();
foreach($leagues as $league) {
$leagueNames[$league->id] = $league->name;
}
return $leagueNames;
}
public static function getIds() {
$season = Season::getCurrent();
$leagues = League::where('season_id','=',$season->id)->get();
$leagueIds = array();
foreach($leagues as $league) {
$leagueIds[]=$league->id; // push id onto array
}
return $leagueIds;
}
public static function getStartRoundId($leagueId)
{
$league = League::where('id','=',$leagueId)->first();
return $league->start_round_id;
}
public static function cmpScore($score1, $score2) {
// [0] = user-id
// [1] = league_score
// [4] = rank
$_score1 = $score1[1];
$goals1 = $score1[2];
$cGoals1 = $score1[3];
$rank1 = -1;
if (array_key_exists(4, $score1 )) { $rank1 = $score1[4]; }
$_score2 = $score2[1];
$goals2 = $score2[2];
$cGoals2 = $score2[3];
$rank2 = -1;
if (array_key_exists(4, $score2 )) {$rank2 = $score2[4]; }
$diff1 = $goals1-$cGoals1;
$diff2 = $goals2-$cGoals2;
if ($rank1 > $rank2) return true;
if ($rank1 < $rank2) return false;
if ($_score1 == $_score2) {
if ($diff1==$diff2) {
if ($goals1 == $goals2) {
return $cGoals1 > $cGoals2;
}
return ( $goals1 < $goals2 );
}
return ($diff1<$diff2);
}
return ($_score1 < $_score2);
}
// Funktioniert nur auf bereits sortierter Liste, nur für Selektion Gruppe 3 Auf & Abstieg
public static function cmpScoreForPos($score1, $score2) {
// [0] = user-id
// [4] = rank
$_score1 = $score1[1];
$goals1 = $score1[2];
$cGoals1 = $score1[3];
$rank1 = $score1[4];
$pos1 = $score1[5];
$_score2 = $score2[1];
$goals2 = $score2[2];
$cGoals2 = $score2[3];
$rank2 = $score2[4];
$pos2 = $score2[5];
$diff1 = $goals1-$cGoals1;
$diff2 = $goals2-$cGoals2;
if ($rank1 > $rank2) return true;
if ($rank1 < $rank2) return false;
if ($pos1 > $pos2) return true;
if ($pos1 < $pos2) return false;
if ($_score1 == $_score2) {
if ($diff1==$diff2) {
if ($goals1 == $goals2) {
return $cGoals1 > $cGoals2;
}
return ( $goals1 < $goals2 );
}
return ($diff1<$diff2);
}
return ($_score1 < $_score2);
}
public static function getRanking($rank, $seasonId=-1) {
$season = Season::getCurrent();
if ($seasonId > -1) { $season=Season::where('id','=',$seasonId)->first(); };
$leagues = League::where('rank','=',$rank)->where('season_id','=', $season->id)->orderBy('id')->get();
$leagueScores=array();
foreach($leagues as $league) {
$memberIds = LeagueMember::getMembers($league->id);
$memberScores =array();
foreach($memberIds as $memberId) {
$tpl=array();
$tpl[0]=$memberId;
$tpl[1]=0; // league_score
$tpl[2]=0; // goals
$tpl[3]=0; // countergoals
$memberScores[$memberId] = $tpl;
}
$lastLockedRoundId=Round::getLastLockedRoundId();
//Log::info("LASTLOCKKEDROUNDID=".$lastLockedRoundId);
$matches=Match::getMatchResults($league->id,-1);
foreach ($matches as $match) {
if (Round::isCompleted($match->round_id) || $match->round_id==$lastLockedRoundId ) {
$memberScores[$match->user1_id][1] += $match->user1_league_score;
//error_log("+++ ".$match->user1_id." +".$match->user1_league_score);
$memberScores[$match->user1_id][2] += $match->user1_rankscore; // goals
$memberScores[$match->user1_id][3] += $match->user2_rankscore; // countergoals
$memberScores[$match->user2_id][1] += $match->user2_league_score;
//error_log("+++ ".$match->user2_id." +".$match->user2_league_score);
$memberScores[$match->user2_id][2] += $match->user2_rankscore; // goals
$memberScores[$match->user2_id][3] += $match->user1_rankscore; // countergoals
}
}
usort($memberScores, array('App\Leagues\League','cmpScore'));
$leagueScores[$league->id]=$memberScores;
//error_log("League::getRanking leagueid / userid / score");
foreach ($memberScores as $entry) {
//error_log($league->id." / ".$entry[0]." / ".$entry[1]);
}
//error_log("---");
}
return $leagueScores;
}
// Für Auf/Abstiegsberechnung - wird auf previous Season angewendet.
// getUnifiedRanking bezieht sich (nur) auf Gruppen-Übergreifende Listung (also alle Untergruppen)
// Rank = -1 bedeutet über alle Ranks (benötigt für Auf- und Abstieg über alle Ligen)
public static function getUnifiedRanking($rank, $seasonId=-1) {
//Log::info("getUnified Ranking [last season], rank=".$rank." seasonId=".$seasonId);
$leagueScores = League::getRanking($rank, $seasonId);
$unifiedScores = array();
foreach($leagueScores as $leagueId => $singleLeagueScores) {
foreach ($singleLeagueScores as $placeNr => $singleLeagueScore) {
$userId=$singleLeagueScores[$placeNr][0];
$scoreWithPos=$singleLeagueScores[$placeNr];
$scoreWithPos[4]=$placeNr+1;
$unifiedScores[$userId]=$scoreWithPos;
}
}
usort($unifiedScores,array('App\Leagues\League','cmpScore'));
//Log::info("getUnifiedRanking result, $rank=".$rank.", SeasonId=".$seasonId);
//Log::info($unifiedScores);
return $unifiedScores;
}
// Nur für Auf und Abstiegsberechnung.
// Schreibt den zukünftigen Rank auf Index4
public static function getTotalRankingOverall($seasonId=-1) {
$a=new MyClasses\TimeLogger("League::getTotalRankingOverall (seasonId=".$seasonId.")");
Log::info($a->getStartMessage());
$userNames = User::getNames();
$totalRanking=array();
$hasRank4 = false;
foreach([1,2,3,4] as $rank) {
foreach (League::getUnifiedRanking($rank, $seasonId) as $rankEntry) {
// Tuple: [0] = userId, [1] = league_score [2] = goals, [3] = counter_goals [4] = LigaPos
$tpl = array();
$tpl[0] = $rankEntry[0]; // userId
$tpl[1] = $rankEntry[1]; // league_score
$tpl[2] = $rankEntry[2]; // goals
$tpl[3] = $rankEntry[3]; // countergoals
$tpl[4] = $rank; // league_rank (1,2,3, 4=quali)
$tpl[5] = $rankEntry[4]; // league_pos (for multiple leagues per rank, usually ranks 3 and 4)
if ($rank==4) { $hasRank4=true;}
// only add to list if user has paid for season
if (User::is_season_paid($tpl[0])=="Ja") {
array_push($totalRanking, $tpl);
}
}
}
usort($totalRanking, array('App\Leagues\League','cmpScore'));
usort($totalRanking, array('App\Leagues\League','cmpScoreForPos')); // Dieser Sort funktioniert nur auf bereits sortierter Liste !! Nur für GruppenRank=3
// Neuen Rang auf Index 4 schreiben
foreach ($totalRanking as $index => $entry) {
$rank=3;
if ($index<44) { $rank=2; }
if ($index<22) { $rank=1; }
$totalRanking[$index][4]=$rank;
}
// kein Rank4 ==> Ligaspiel ==> Auf & Abstieg wird angewendet.
if ($hasRank4) {
Log::info("Rank4 gesetzt, Quali, keine Vorsaison, Auf/Abstieg wird übersprungen");
}else {
Log::info("Rank4 nicht gesetzt, keine Quali, Auf/Abstieg wird berechnet");
// Liga 1/2: Swap rank 17-22 <> 23-28 ==> index 16-21 to rank=2, index 22-27 to rank=1
// Liga 2/3: Swap rank 39-44 <> 45-50 ==> index 38-43 to rank=3, index 44-49 to rank=2
$totalRanking[16][4]=2;
$uid=$totalRanking[16][0];
Log::info("Abstieg in Liga 2: [".$uid."] ".$userNames[$uid]);
$totalRanking[17][4]=2;
$uid=$totalRanking[17][0];
Log::info("Abstieg in Liga 2: [".$uid."] ".$userNames[$uid]);
$totalRanking[18][4]=2;
$uid=$totalRanking[18][0];
Log::info("Abstieg in Liga 2: [".$uid."] ".$userNames[$uid]);
$totalRanking[19][4]=2;
$uid=$totalRanking[19][0];
//Log::info("Abstieg in Liga 2: ["+$uid+"] ".$userNames[$uid]);
$totalRanking[20][4]=2;
$uid=$totalRanking[20][0];
Log::info("Abstieg in Liga 2: [".$uid."] ".$userNames[$uid]);
$totalRanking[21][4]=2;
$uid=$totalRanking[21][0];
Log::info("Abstieg in Liga 2: [".$uid."] ".$userNames[$uid]);
$totalRanking[22][4]=1;
$uid=$totalRanking[22][0];
Log::info("Aufstieg in Liga 1: [".$uid."] ".$userNames[$uid]);
$totalRanking[23][4]=1;
$uid=$totalRanking[23][0];
Log::info("Aufstieg in Liga 1: [".$uid."] ".$userNames[$uid]);
$totalRanking[24][4]=1;
$uid=$totalRanking[24][0];
Log::info("Aufstieg in Liga 1: [".$uid."] ".$userNames[$uid]);
$totalRanking[25][4]=1;
$uid=$totalRanking[25][0];
Log::info("Aufstieg in Liga 1: [".$uid."] ".$userNames[$uid]);
$totalRanking[26][4]=1;
$uid=$totalRanking[26][0];
Log::info("Aufstieg in Liga 1: [".$uid."] ".$userNames[$uid]);
$totalRanking[27][4]=1;
$uid=$totalRanking[27][0];
Log::info("Aufstieg in Liga 1: [".$uid."] ".$userNames[$uid]);
$totalRanking[38][4]=3;
$uid=$totalRanking[38][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[39][4]=3;
$uid=$totalRanking[39][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[40][4]=3;
$uid=$totalRanking[40][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[41][4]=3;
$uid=$totalRanking[41][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[42][4]=3;
$uid=$totalRanking[42][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[43][4]=3;
$uid=$totalRanking[43][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[44][4]=2;
$uid=$totalRanking[44][0];
Log::info("Aufstieg in Liga 2: [".$uid."] ".$userNames[$uid]);
$totalRanking[45][4]=2;
$uid=$totalRanking[45][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[46][4]=2;
$uid=$totalRanking[46][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[47][4]=2;
$uid=$totalRanking[47][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[48][4]=2;
$uid=$totalRanking[48][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
$totalRanking[49][4]=2;
$uid=$totalRanking[49][0];
Log::info("Abstieg in Liga 3: [".$uid."] ".$userNames[$uid]);
usort($totalRanking, array('App\Leagues\League','cmpScore'));
}
Log::info($a->getEndMessage());
//error_log($a->getEndMessage());
return $totalRanking;
}
public static function getNewUsers($seasonId=-1) {
$users=User::getActives($seasonId);
$previousSeason=Season::getPrevious($seasonId);
$old_users=User::getActives($previousSeason->id);
// Structure of unified list entry
/*
$tpl = array();
$tpl[0] = $rankEntry[0]; // userId
$tpl[1] = $rankEntry[1]; // league_score
$tpl[2] = $rankEntry[2]; // goals
$tpl[3] = $rankEntry[3]; // countergoals
$tpl[4] = $rank; // league_rank (1,2,3, 4=quali)
$tpl[5] = $rankEntry[4]; // league_pos (for multiple leagues per rank, usually ranks 3 and 4)
*/
$new_users=array();
foreach($users as $user) {
$exists=0;
foreach($old_users as $old_user) {
if ($old_user->id == $user->id) { $exists=1;}
}
if (!$exists) {
if (User::payment_date($user->id, $seasonId)) {
$entry = [$user->id,0,0,0,3,0];
array_push($new_users, $entry);
}
}
}
return $new_users;
}
// ausfaktoriert aus LeaguesController::createLeagues()
// TODO: $round_count ist nur im Quali-Modus relevant und steuert, wieviele Quali-Gruppen benötigt werden.
// TODO: Sobald es Liga1 und Liga2 gibt, wird der round_count immer 21 sein, da Liga1 und Liga2 auf
// TODO: 22 Mitspieler festgelegt sind.
public static function createLeagues($start_round_id, $round_count) {
Log::info("Leagues\League::createLeagues, start_round_id=".$start_round_id.", round_count=".$round_count);
$currentSeason=Season::getCurrent();
$previousSeason=Season::getPrevious();
$userNames = User::getNames();
// Eventuell vorhandene Ligen loeschen
$leagues=League::where('season_id','=',$currentSeason->id)->get();
if ($leagues) {
foreach ($leagues as $league) {
DB::table('leagues_matches')->where('league_id', '=', $league->id)->delete();
DB::table('leagues_members')->where('league_id', '=', $league->id)->delete();
DB::table('leagues')->where('id', '=', $league->id)->delete();
}
}
$active_member_count=sizeof(User::getActives());
Log::info("Aktive Spieler: ".$active_member_count);
$neededLeagues3 = League::neededLeagues($active_member_count, $round_count);
Log::info("Benötigte Liga-Gruppen: ".$neededLeagues3);
$league_ids=array();
//TODO: Wenn es keine Vorsaison gibt -> Qualifikation
//TODO: Ansonsten: Standard-Ligen (1,2,3) erzeugen. Liga 1 und 2 sind auf 22 Spieler festgelegt.
if (!$previousSeason) {
// Alle Spieler werden gleichmässig auf Qualifikationsgruppen aufgeteilt
// Dieser Modus wird gewählt, wenn es keine Vorsaison gibt, es also
// die erste Saison im System ist.
Log::info("League::createLeagues => No previous season detected.");
for ($league_nr=1; $league_nr<=$neededLeagues3; $league_nr+=1) {
$league = League::create([
'is_qualification' => true,
'name' => 'Qualifikationsgruppe '.$league_nr,
'rank' => '4',
'subrank' => $league_nr,
'round_count' => $round_count,
'season_id' => $currentSeason->id,
'start_round_id' => $start_round_id
]);
$league->save();
$league_ids[$league_nr-1] = $league->id;
}
// Distribute members
$users = User::getActives();
shuffle($users);
$league_index=0;
Log::info("Distributing Members between groups");
while(sizeof($users)>0) {
$user = array_pop($users);
$leagueMember = LeagueMember::create([
'user_id' => $user->id,
'league_id' => $league_ids[$league_index]
]);
$leagueMember->save();
Log::info("Saving user_id ".$user->id);
$league_index+=1;
if (sizeof($league_ids)==$league_index) { $league_index=0; }
}
} else {
// Es gibt eine Vorsaison.
// - 1.) Ligen erzeugen
// - 2.) unified Liste bauen
// - 3.) Wenn Vorsaison keine Quali war, dann Auf & Abstieg umsetzen ( unfified Liste als Basis )
// - 4.) Member den Ligen zuordnen
Log::info("League::createLeagues => Previous season detected. Creating Leagues 1, 2 and 3");
// Erzeugung der Ligen
$createdLeagues=array();
$neededLeagues3=0;
$league_size1= min(22,$active_member_count);
Log::info("Creating League 'Spielerliga 1'");
$league1 = League::create([
'is_qualification' => false,
'name' => 'Spielerliga 1',
'rank' => '1',
'subrank' => '1',
'round_count' => $round_count,
'season_id' => $currentSeason->id,
'start_round_id' => $start_round_id
]);
array_push($createdLeagues, $league1);
$league_size2=min(22,$active_member_count - $league_size1);
if ($league_size2>0) {
Log::info("Creating League 'Spielerliga 2'");
$league2 = League::create([
'is_qualification' => false,
'name' => 'Spielerliga 2',
'rank' => '2',
'subrank' => '1',
'round_count' => $round_count,
'season_id' => $currentSeason->id,
'start_round_id' => $start_round_id
]);
array_push($createdLeagues, $league2);
$league_size3 = $active_member_count - $league_size1 - $league_size2;
Log::info("Size of league 3 = ". $league_size3);
// Make neededLeagues3 visible outside of scope
$neededLeagues3=-1;
if ($league_size3>0) {
$neededLeagues3 = League::neededLeagues($league_size3, $round_count);
Log::info("Needed 3-Leagues for league_size=".$league_size3." and round_count=".$round_count." is: ".$neededLeagues3);
for ($league_nr=1; $league_nr<=$neededLeagues3; $league_nr+=1) {
$league = League::create([
'is_qualification' => false,
'name' => 'Spielerliga 3, Gruppe '.$league_nr,
'rank' => '3',
'subrank' => $league_nr,
'round_count' => $round_count,
'season_id' => $currentSeason->id,
'start_round_id' => $start_round_id
]);
$league->save();
array_push($createdLeagues,$league);
}
}
Log::info("League::createLeagues Creating unified List from previous season (i call League::getTotalRankingOverall)");
$unifiedList = League::getTotalRankingOverall($previousSeason->id); // WICHTIG !! getTotalRankingOverall implentiert Auf- und Abstieg !!
Log:info("League::createLeagues Unified List:");
$userNames = User::getNames();
$unifiedList2=array(); // We will only transfer users over to here that have paid the current season and are not deleted.
$count=0;
foreach($unifiedList as $listEntry) {
$userId = $listEntry[0];
$leagueScore=$listEntry[1];
if (User::is_season_paid($userId) && !User::isDeleted($userId)) {
$count+=1;
array_push($unifiedList2, $listEntry);
Log::info($count.".) [".$userId."] ".$userNames[$userId]." ".$leagueScore." Punkte");
} else {
Log::info($count.".) [".$userId."] ".$userNames[$userId]." [DELETED]");
}
}
$unifiedList = $unifiedList2;
// Jetzt neue Spieler hinzufügen, die letzte Saison noch nicht dabei waren, und deshalb in getTotalRankingOverall nicht enthalten sind.
Log::info("League::createLeagues Adding new users not within previous season");
foreach( League::getNewUsers() as $entry) {
array_push($unifiedList, $entry);
$userId=$entry[0];
Log::info("adding new user not in previous season: ( [".$userId."] ".$userNames[$userId]." )");
}
// Wenn es für Liga 3 mehr als eine Gruppe gibt, dann die Reihenfolge der Members randomisieren.
if ($neededLeagues3>1) {
$numberOfSwaps=50;
// Structure of unified list entry
/*
$tpl = array();
$tpl[0] = $rankEntry[0]; // userId
$tpl[1] = $rankEntry[1]; // league_score
$tpl[2] = $rankEntry[2]; // goals
$tpl[3] = $rankEntry[3]; // countergoals
$tpl[4] = $rank; // league_rank (1,2,3, 4=quali)
$tpl[5] = $rankEntry[4]; // league_pos (for multiple leagues per rank, usually ranks 3 and 4)
*/
Log::info("League 3 entries before shuffling:");
foreach($unifiedList as $entry) {
if ($entry[4]==3) {
Log::info ("(".$entry[0].") ".$userNames[$entry[0]]);
}
}
$league3entries=array();
foreach($unifiedList as $pos => $entry) {
if ($entry[4]==3) {
array_push($league3entries, $entry);
}
}
shuffle($league3entries);
$pos=0;
foreach ( $unifiedList as $key => $entry) {
if ($entry[4]==3) {
$unifiedList[$key] = $league3entries[$pos];
$pos += 1;
}
}
Log::info("League 3 entries after shuffling:");
foreach($unifiedList as $entry) {
if ($entry[4]==3) { Log::info ("(".$entry[0].") ".$userNames[$entry[0]]); }
}
}
$currentCount = 1;
$nr=1;
$leagueNr=1;
$neededSize3=0;
$subLeague=1; // for rank 3 leagues only
$leagueCount=1;
$leagueIndex=0;
Log::info("League::createLeagues unified list size= ".sizeof($unifiedList));
foreach($unifiedList as $entry) {
if ($nr==23) { $leagueNr=2; $leagueCount=1; $leagueIndex=1; }
if ($nr==45) {
$leagueNr=3; $leagueCount=1; $leagueIndex=2;
$neededSize3=intdiv(($active_member_count-44),$neededLeagues3); // $neededLeagues = needed Groups for rank 3 leagues
if ( ($active_member_count-44) % 2) {
$neededSize3+=1;
}
Log::info("League::createLeagues Needed min/switch size for rank 3 leagues: ".$neededSize3);
}
if ($nr>45 && $leagueCount > $neededSize3) {
$subLeague+=1;
$leagueCount=1;
$leagueIndex+=1;
}
Log::info("League::createLeagues "."#".$leagueCount." Liga ".$leagueNr."-".$subLeague.") ".$nr." ".$entry[0]." (".$userNames[$entry[0]].")");
$league=$createdLeagues[$leagueIndex];
$leagueMember = LeagueMember::create([
'user_id' => $entry[0],
'league_id' => $league->id
]);
Log::info("(".$entry[0].") ".$userNames[$entry[0]]." => leagueIndex=".$leagueIndex);
$leagueMember->save();
$leagueCount+=1;
$nr++;
}
}
}
}
// Aktuelle Liga-Zuordnung auf Basis des Rangs in der letzten Liga
// Oder des Rangs in der Qualifikation
// oder erstellung des Quali Rangs wenn es keine previous Season gibt.
// Liga-Zugehörigkeit festlegen. Setzt voraus, dass die Ligen bereits erzeugt wurden.
public static function setLeagueForPlayers()
/*
* setLeagueForPlayers__NEW_QUALIFICATION case1
* setLeagueForPlayers__FROM_QUALIFICATION case2
* setLeagueForPlayers__FROM_LEAGUES case3
*/
{
$previousSeason = Season::getPrevious();
$currentSeason = Season::getCurrent();
$users = User::getActives();
if (!$previousSeason) {
// case 1: first season ever, no previous season exists, qualification (league-rank=4)
} elseif (Season::hasQualification($previousSeason->id)){
// case 2: previous season was qualification season (rank 4)
} else { /*case 3 - default: determine league-ranks 1,2,3 from previous Season rank verwenden*/
}
// 2 Möglichkeiten:
// 1.) previousSeason hat rank=4 => Qualification Round
// 2.) sonst aus .
$usersLastSeason = User::getActives($previousSeason->id);
$league1 = League::getUnifiedRanking(1, $previousSeason->id);
$league2 = League::getUnifiedRanking( 2, $previousSeason->id);
$league3 = League::getUnifiedRanking( 3, $previousSeason->id);
//$lastLeagues = League::where('season_id','=',$previousSeason->id)->get();
// WAS MACHT DIESER CODE ?!
/*
foreach ($users as $index => $user) {
$found = false;
foreach ($usersLastSeason as $userLastSeason) {
if ($userLastSeason->id == $user->id) $found = true;
}
if (!$found) {
$users[$index]['rank']=League::RANK_LEAGUE3; // In der letzten Season unter den Actives nicht gefunden
$leagueMember = LeagueMember::create([
'user_id' => $user->id,
'league_id' => $league3->id
]);
$leagueMember->save();
} else {
// League1, 1-16: RANK_LEAGUE1
// League1, 17-22: RANK_LEAGUE2
// League2, 1-6: RANK_LEAGUE1
// League2, 7-16: RANK_LEAGUE2
// League2, 17-22: RANK_LEAGUE3
// League3, best6: RANK_LEAGUE2
// League3, 7-end: RANK_LEAGUE3
//
//alte Ligen durchsuchen und entsprechend einordnen
foreach($league1 as $index => $entry) {
$userId = $entry[0];
$score = $entry[1];
$goals = $entry[2];
$cGoals = $entry[3];
$leagueId = -1;
if ($user->id == $userId) {
$rank=-1;
if ($index<16) {
$rank=1;
$leagueId=$league1->id;
} else {
$rank=2;
$leagueId=$league2->id;
}
$leagueMember = LeagueMember::create([
'user_id' => $userId,
'league_id' => $leagueId
]);
$leagueMember->save();
}
}
foreach($league2 as $index => $entry) {
$userId = $entry[0];
$score = $entry[1];
$goals = $entry[2];
$cGoals = $entry[3];
$leagueId = -1;
if ($user->id == $userId) {
$rank=-1;
$leagueId=$league1->id;
if ($index<6) {
$rank=1;
} elseif ($index<16) {
$rank=2;
$leagueId=$league2->id;
} else {
$rank=3;
$leagueId=$league3->id;
}
$leagueMember = LeagueMember::create([
'user_id' => $userId,
'league_id' => $leagueId
]);
$leagueMember->save();
}
}
foreach($league3 as $index => $entry) {
$userId = $entry[0];
$score = $entry[1];
$goals = $entry[2];
$cGoals = $entry[3];
if ($user->id == $userId) {
$rank=-1;
if ($index<6) {
$rank=2;
$leagueId=$league2->id;
} else {
$rank=3;
$leagueId=$league3->id;
}
$leagueMember = LeagueMember::create([
'user_id' => $userId,
'league_id' => $leagueId
]);
$leagueMember->save();
}
}
}
}
*/
// WAS MACHT DIESER CODE? --ENDE
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace App\Leagues;
use Illuminate\Database\Eloquent\Model;
use App\User;
class LeagueMember extends Model
{
protected $table ='leagues_members';
protected $fillable = [
'id','user_id','league_id'
];
//
public static function getMembers($league_id) {
$members =LeagueMember::where('league_id','=',$league_id)->orderBy('id')->get();
$userList=array();
foreach($members as $member) {
array_push($userList,$member->user_id);
}
return $userList;
}
public static function playsInRound($userId, $roundId, $leagueId) {
$matches1 = Match::where('user1_id','=',$userId)->where('round_id','=',$roundId)->where('league_id','=',$leagueId)->get();
if (sizeof($matches1)>0) return true;
$matches2 = Match::where('user2_id','=',$userId)->where('round_id','=',$roundId)->where('league_id','=',$leagueId)->get();
return sizeof($matches2)>0;
}
}

View file

@ -0,0 +1,332 @@
<?php
namespace App\Leagues;
use Illuminate\Database\Eloquent\Model;
use App\Leagues\League;
use App\Leagues\LeagueMember;
use App\User;
use App\Round;
use App\Season;
use App\Tipp;
use Log;
use DB;
class Match extends Model
{
protected $table ='leagues_matches';
protected $fillable = [
'id','league_id','round_id','user1_id','user2_id'
];
// https://en.wikipedia.org/wiki/Round-robin_tournament
public static function createMatchups()
{ // should be restricted to league ranks 1,2,3 and 4. All other leagues will have to use some
// incremental matchmaking system.
Log::info("Match::Creating matchups()");
$currentSeason = Season::getCurrent();
$leagues = League::where('season_id', '=', $currentSeason->id)->get();
foreach ($leagues as $league) {
error_log("Match::createMatchups league_id=".$league->id);
Log::info("Match::createMatchups: Creating matchups for league_id=".$league->id);
// Wenn es keine previous League gibt, dann ist $league->rank immer RANK_QUALIFICATION,
// ansonsten ist es einer von RANK_LEAGUE1, RANK_LEAGUE2, RANK_LEAGUE3
Log::info("rank_id of league_id ".$league->id." = ".$league->rank);
if ($league->rank <= League::RANK_QUALIFICATION) {
$rounds = Round::where('id','>=',$league->start_round_id)->get();
error_log("Match::createMatchups. start_round_id = ".$league->start_round_id);
$roundNr=1;
$neededRoundCount = Match::getNumberOfNeededRounds($league->id);
Log::info("Match::createMatchups( league_id=".$league->id.", numberOfrounds=".sizeof($rounds));
$allPairings=Match::getAllPairings($league->id);
Log::info("Match::createMatchups: Rounds:");
$counter=1;
foreach($rounds as $round) {
Log::info($counter);
Log::info($round."\n");
$counter+=1;
}
Log::info("Match::createMatchups: League-id=".$league->id.", Size of allPairings:".sizeof($allPairings));
foreach ($rounds as $round) {
Log::info("Match::createMatchups: Fetching roundNr/index=".$roundNr);
$pairings = $allPairings[$roundNr];
// Save pairings
foreach($pairings as $pair) {
Log::info("Match::createMatchups: Saving match. " . $pair[0] . " vs " . $pair[1] . " roundid=" . $round->id);
$newMatch = Match::create([
'league_id' => $league->id,
'round_id' => $round->id,
'user1_id' => $pair[0],
'user2_id' => $pair[1]
]);
$newMatch->save();
//Log::info("Saving match: league_id=".$league->id.", round_id=".$round->id.", ".$pair[0]." vs ".$pair[2]);
}
$roundNr += 1;
if ($roundNr > $neededRoundCount) break;
}
} else {Log::info("Match::createMatchups: Skipped match creation because of unfitting rank=".$league->rank);}
}
}
public static function hasMatched($user1_id, $user2_id, $league_id)
{
$matches = DB::table('leagues_matches')
->where('league_id', '=', $league_id)
->where('user1_id', '=', $user1_id)
->where('user2_id', '=', $user2_id)
->get();
if (sizeof($matches)) {
return true;
}
$matches = DB::table('leagues_matches')
->where('league_id', '=', $league_id)
->where('user1_id', '=', $user2_id)
->where('user2_id', '=', $user1_id)
->get();
if (sizeof($matches)) {
return true;
}
return false;
}
// Selektiert nur die "Heimspiele"
public static function getMatches($user_id, $league_id) {
$matches = DB::table('leagues_matches')->where('league_id', '=', $league_id)->where('user1_id','=',$user_id)->get();
return $matches;
}
public static function getLeagueMatches($leagueId) {
error_log("App\Match::getLeagueMatches(leagueId=".$leagueId.")");
$matches = DB::table('leagues_matches')->where('league_id','=',$leagueId)->orderBy('round_id')->get();
$league=League::where('id','=',$leagueId)->first();
$season = Season::where('id','=',$league->season_id)->first();
$roundnames = Round::getNames($season->id);
$usernames = User::getNames();
foreach($matches as $match) {
//error_log("Needed round_id: ".$match->round_id);
//error_log(" User1: ".$match->user1_id);
//error_log(" User2: ".$match->user2_id);
$match->round_name = $roundnames[$match->round_id];
$match->user1_name = $usernames[$match->user1_id];
$match->user2_name = $usernames[$match->user2_id];
// Punktauswertung in Match::getMatchResults($leagueId, $maxRoundId);
}
return $matches;
}
// Hier findet RoundRobin statt.
public static function getAllPairings($leagueId) {
Log::info("GetAllPairings for LeagueId=".$leagueId);
$members = LeagueMember::getMembers($leagueId);
$roundCount=Match::getNumberOfNeededRounds($leagueId);
if (sizeof($members) % 2 == 1) { // ungerade memberzahl => freilos einfügen
error_log("Adding -1 free entry");
Log::info("Adding -1 free entry");
array_push($members,-1);
}
shuffle($members);
error_log("Number of members:".sizeof($members));
Log::info("Number of members.".sizeof($members));
$pairingCount = Match::getNumberOfPairingsPerRound($leagueId);
error_log("pairingCount=".$pairingCount);
Log::info("pairingCount=".$pairingCount);
$all = array();
for ($currentRoundNr=1; $currentRoundNr<= $roundCount; $currentRoundNr++) {
$roundRobin = array();
foreach ($members as $userId) {
array_push($roundRobin, $userId);
}
//error_log("RoundNr ".$currentRoundNr." Array start:");
//error_log(implode(",",$roundRobin));
Log::info("RoundNr ".$currentRoundNr." Array start:");
Log::info(implode(",",$roundRobin));
$_roundNr = $currentRoundNr;
while ($_roundNr >= 1) {
// Round-Robin shift: First element stays, rest rotates
$first = array_shift($roundRobin); // Erstes Element sichern & entfernen
$last = array_pop($roundRobin); // Letztes Element sichern & entfernen
array_unshift($roundRobin, $last); // Vorne einfügen
array_unshift($roundRobin, $first); // Vorne einfügen
$_roundNr--;
}
//error_log("RoundNr ".$currentRoundNr." Array end:");
//error_log(implode(",",$roundRobin));
Log::info("RoundNr ".$currentRoundNr." Array end:");
Log::info(implode(",",$roundRobin));
$idx = 0;
$slot = 0;
$pairings = array();
foreach ($roundRobin as $index => $userId) {
$idx = $index;
if ($index >= $pairingCount) {
$idx = 2 * $pairingCount - $index - 1;
$slot = 1;
}
$pairings[$idx][$slot] = $userId;
//error_log($idx.",".$slot." => ".$userId);
Log::info($idx.",".$slot." => ".$userId);
}
// Matches die nur einen Teilnehmer haben entfernen. Passiert bei ungerader Teilnehmerzahl.
// Der nicht im Pairing befindliche Spieler hat einen spielfreien Tag.
//error_log(" Cleaning up Round pairings");
Log::info("Cleaning up Round pairings");
$pairings_clean=array();
//error_log(":".$pairings[0]);
foreach($pairings as $idx => $pairing) {
if ($pairing[0] == -1 || $pairing[1] == -1) {
//error_log("DONT ADD");
Log::info("DONT ADD");
} else {
//error_log("adding...");
Log::info("adding...");
$pairings_clean[$idx] = $pairing;
}
}
$all[$currentRoundNr]=$pairings_clean;
//$all[$currentRoundNr]=$pairings;
}
foreach ($all as $roundNr => $pairings) {
foreach ($pairings as $slotIdx => $pairing) {
error_log($pairing[0]." vs ".$pairing[1]);
Log::info($pairing[0]." vs ".$pairing[1]);
}
}
return $all; // $all[$roundnr]= Array of Tuples ( UserId1, UserId2 )
//return null;
}
public static function getNumberOfPairingsPerRound($leagueId) {
$members = LeagueMember::getMembers($leagueId);
$pairingsPerRound = intdiv(sizeof($members),2);
if (sizeof($members)-$pairingsPerRound*2) {
$pairingsPerRound+=1;
}
return $pairingsPerRound;
}
public static function getNumberOfNeededRounds($leagueId) {
$members = LeagueMember::getMembers($leagueId);
$memberCount = sizeof($members);
if ($memberCount % 2 == 1) { return $memberCount; } // 1 Runde mehr wg. Freilos für 1 Spieler
return $memberCount-1;
}
public static function getMatchResults($leagueId, $maxRoundId=-1) {
$league=League::where('id','=',$leagueId)->first();
$season=Season::where('id','=',$league->season_id)->first();
$roundtipps = Tipp::getRoundTipps($maxRoundId, $season->id);
$roundtipps = $roundtipps["roundtipps"];
$matches = Match::getLeagueMatches($leagueId, $maxRoundId);
if ($maxRoundId==-1) {
//$maxRoundId = Round::getLastRoundId($season->id);
$maxRoundId = Round::getLastLockedRoundId($season->id);
Log::info("LASTLOCKEDROUND_ID=".$maxRoundId);
}
foreach($matches as $key => $match) {
$user1_key = $match->round_id."_".$match->user1_id;
$user2_key = $match->round_id."_".$match->user2_id;
if (array_key_exists($user1_key,$roundtipps ) && array_key_exists($user2_key,$roundtipps) ) {
$user1_score = $roundtipps[$user1_key]["rankscore"];
$user2_score = $roundtipps[$user2_key]["rankscore"];
$matches[$key]->user1_rankscore = $user1_score;
$matches[$key]->user2_rankscore = $user2_score;
//$matches[$key]->user1_hits = $roundtipps[$user1_key][]
if ($user1_score > $user2_score) {
$matches[$key]->user1_league_score = 3;
$matches[$key]->user2_league_score = 0;
}
else if ($user1_score < $user2_score){
$matches[$key]->user1_league_score = 0;
$matches[$key]->user2_league_score = 3;
} else {
$matches[$key]->user1_league_score = 1;
$matches[$key]->user2_league_score = 1;
}
} else { // Untipped/future round
$matches[$key]->user1_league_score = 0;
$matches[$key]->user2_league_score = 0;
$matches[$key]->user1_rankscore = -1;
$matches[$key]->user2_rankscore = -1;
}
}
return $matches;
}
public static function getMatchResultsForUser($userId, $maxRoundId=-1) {
$season = Season::getCurrent();
$leagues = League::where('season_id','=',$season->id)->get();
$matchList=array();
foreach($leagues as $league) {
$member=LeagueMember::where('league_id','=',$league->id)->where('user_id','=',$userId)->first();
if ($member) {
// $userId ist member dieser League
$matchResults = Match::getMatchResults($league->id,$maxRoundId);
foreach($matchResults as $result) {
if ($result->user1_id == $userId || $result->user2_id==$userId) {
array_push($matchList, $result);
}
}
}
}
return $matchList;
}
}

View file

@ -0,0 +1,44 @@
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class RoundmailMailer extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct()
{
}
public $user_id;
public $send_date;
public $sender_name;
public $sender_email;
public $recipients;
public $topic;
public $mail_message;
/**
* Build the message.
*
* @return $this
*/
public function build()
{
//return $this->subject($this->topic)->view('emails.roundmail')->from($this->sender_email, $this->sender_name);
return $this->subject($this->topic)->view('emails.roundmail')->from("hoschis.tippspiel.info@gmail.com", $this->sender_name);
}
}

View file

@ -0,0 +1,59 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Season;
use App\User;
use Log;
class ManualPayout extends Model
{
protected $fillable = [
'season_id','name','user_id'
];
public static function getManualQuotaNames() {
$manualQuotas=array('liga_platz1','liga_platz2','liga_platz3','liga_platz2_1','liga_platz3_1','pokal');
return $manualQuotas;
}
public static function getWinners() {
$winners=array();
$manualQuotas=ManualPayout::getManualQuotaNames();
foreach ($manualQuotas as $quota) {
$userId=0;
$winner=ManualPayout::getWinner($quota);
if ($winner) { $userId=$winner->id; }
$winners[$quota]=$userId;
}
return $winners;
}
public static function getWinner($quotaName) {
$season = Season::getCurrent();
$entry = ManualPayout::where('season_id','=', $season->id)->where('quota_name','=',$quotaName)->first();
if (!$entry) return null;
$user = User::where('id','=',$entry->user_id);
return $user->first();
}
public static function setWinner( $userId, $quotaName) {
$season = Season::getCurrent();
Log::info("setWinner, season_id=".$season->id.", quota_name='".$quotaName."'");
$entry = ManualPayout::where('season_id','=',$season->id)->where('quota_name','=',$quotaName)->first();
if (!$entry) {
$entry = new ManualPayout;
$entry->user_id = $userId;
$entry->season_id = $season->id;
$entry->quota_name = $quotaName;
}
$entry->user_id = $userId;
$entry->save();
}
}

View file

@ -0,0 +1,44 @@
<?php
namespace App\MyClasses;
/* USAGE IN CLASS
--START OF FILE
use App\MyClasses\TimeLogger;
--START OF METHOD
$a=new TimeLogger("method XXX start");
Log::info($a->getStartMessage());
--END OF METHOD
Log::info($a->getEndMessage());
*/
class TimeLogger
{
public $startTime;
public $pkey;
public $functionName;
public function __construct($_functionName) {
$this->startTime = microtime(true);
$this->functionName =$_functionName;
$this->pkey="".rand(1000,9999);
}
public function getStartMessage() {
return "[CLOCK] [".$this->pkey."-".$this->functionName."] [started]";
}
public function getEndMessage() {
$time= ( microtime(true) - $this->startTime);
$timestr=number_format( $time, 4);
$retval="[CLOCK] [".$this->pkey."-". $this->functionName."] [ended] [elapsed: ".$timestr."]";
if ($time > 1.5) {
$retval=$retval." [PERFORMANCE_WARNING]";
}
return $retval;
}
}

View file

@ -0,0 +1,44 @@
<?php
namespace App\MyClasses;
/* USAGE IN CLASS
--START OF FILE
use App\MyClasses\TimeLogger;
--START OF METHOD
$a=new TimeLogger("method XXX start");
Log::info($a->getStartMessage());
--END OF METHOD
Log::info($a->getEndMessage());
*/
class TimeLogger
{
public $startTime;
public $pkey;
public $functionName;
public function __construct($_functionName) {
$this->startTime = microtime(true);
$this->functionName =$_functionName;
$this->pkey="".rand(1000,9999);
}
public function getStartMessage() {
return "[CLOCK] [".$this->pkey."-".$this->functionName."] [started]";
}
public function getEndMessage() {
$time= ( microtime(true) - $this->startTime);
$timestr=number_format( $time, 4);
$retval="[CLOCK] [".$this->pkey."-". $this->functionName."] [ended] [elapsed: ".$timestr."]";
if ($time > 1.5) {
$retval=$retval." [PERFORMANCE_WARNING]";
}
return $retval;
}
}

View file

@ -0,0 +1,37 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Payment extends Model
{
protected $fillable = [
'season_id', 'user_id', 'paid_date'
];
public static function set_payment_date($user_id,$season_id,$paid_date) {
$payment = Payment::where([
['user_id', '=', $user_id],
['season_id', '=', $season_id]
])->first();
if (!$payment) {
$payment= Payment::create([
'user_id' => $user_id,
'season_id'=> $season_id,
'paid_date'=> $paid_date ? User::toDBDate($paid_date):null
]);
} else {
$payment->user_id = $user_id;
$payment->season_id = $season_id;
$payment->paid_date = $paid_date ? User::toDBDate($paid_date):null;
}
$payment->save();
}
}

View file

@ -0,0 +1,28 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}

View file

@ -0,0 +1,21 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Broadcast;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\Event' => [
'App\Listeners\EventListener',
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
parent::boot();
//
}
}

View file

@ -0,0 +1,73 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
}

View file

@ -0,0 +1,455 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Log;
use DB;
use App\ManualPayout;
class Quota extends Model
{
/*
* "tagessieg"
"platz1" =>
"platz2" =>
"platz3" =>
"platz4" =>
"platz5" =>
"platz6" =>
"platz7" =>
"platz8" =>
"platz9" =>
"platz10" =
"liga_platz
"liga_platz
"liga_platz
"liga_platz
"liga_platz
"gshirt" =>
"pokal" =>
*/
public static function getPayouts() {
$season_id = Season::getCurrent()->id;
$quotas = Quota::getQuotas();
$roundCount=Round::getCount();
//Quotas fuer Season wegwerfen falls vorhanden und default Wert reinschreiben
if (sizeof($quotas)==0) {
Quota::createDefaultQuota();
$quotas = Quota::getQuotas();
}
$active_user_count = sizeof(User::getActives());
$euro_pott = $active_user_count * $quotas["einsatz"];
$euro_tagessieg_sum = intval ($euro_pott * ( $quotas["tagessieg"] / 100 ) );
$euro_tagessieg = Quota::get6Divisor( intval($euro_tagessieg_sum / $roundCount));
$euro_gruenes_trikot = intval($euro_pott * (($quotas["gshirt"] / 100)));
$euro_gruenes_trikot = Quota::get6Divisor($euro_gruenes_trikot);
$euro_pokal= intval ($euro_pott * (($quotas["pokal"] / 100)));
$euro_pokal= Quota::get6Divisor($euro_pokal);
$euro_platzierung = intval ( $euro_pott * (($quotas["platzierung"] / 100)));
$tagessieg_rest = $euro_tagessieg_sum - ($euro_tagessieg * $roundCount);
//Log::info("Tagessieg Rest=".$tagessieg_rest." €");
$euro_platzierung += $tagessieg_rest;
$euro_platz1 = Quota::get6Divisor(intval( $euro_platzierung * (( $quotas["platz1"] / 100))));
//Log::info("Platz 1=".$euro_platz1);
$euro_platz2 = Quota::get6Divisor(intval( $euro_platzierung * (( $quotas["platz2"] / 100))));
$euro_platz3 = Quota::get6Divisor(intval( $euro_platzierung * (( $quotas["platz3"] / 100))));
$euro_platz4 = Quota::get6Divisor(intval( $euro_platzierung * (( $quotas["platz4"] / 100))));
$euro_platz5 = Quota::get6Divisor(intval( $euro_platzierung * (( $quotas["platz5"] / 100))));
$euro_platz6 = Quota::get6Divisor(intval( $euro_platzierung * (( $quotas["platz6"] / 100))));
$euro_platz7 = Quota::get6Divisor(intval( $euro_platzierung * (( $quotas["platz7"] / 100))));
$euro_platz8 = Quota::get6Divisor(intval( $euro_platzierung * (( $quotas["platz8"] / 100))));
$euro_platz9 = Quota::get6Divisor(intval( $euro_platzierung * (( $quotas["platz9"] / 100))));
$euro_platz10= Quota::get6Divisor(intval( $euro_platzierung * (( $quotas["platz10"] / 100))));
$euro_liga=intval($euro_pott *(($quotas["liga"] / 100)));
$euro_liga_platz1 = Quota::get6Divisor(intval($euro_liga*(($quotas["liga_platz1"] / 100))));
$euro_liga_platz2 = Quota::get6Divisor(intval($euro_liga*(($quotas["liga_platz2"] / 100))));
$euro_liga_platz3 = Quota::get6Divisor(intval($euro_liga*(($quotas["liga_platz3"] / 100))));
$euro_liga_platz2_1 = Quota::get6Divisor(intval($euro_liga*(($quotas["liga_platz2_1"] / 100))));
$euro_liga_platz3_1 = Quota::get6Divisor(intval($euro_liga*(($quotas["liga_platz3_1"] / 100))));
$finaler_rest = $euro_pott - ( $roundCount*$euro_tagessieg + $euro_gruenes_trikot + $euro_pokal + $euro_platz1
+ $euro_platz2 + $euro_platz3+ $euro_platz4 + $euro_platz5
+ $euro_platz6 + $euro_platz7 + $euro_platz8 + $euro_platz9 + $euro_platz10
+ $euro_liga_platz1 + $euro_liga_platz2 + $euro_liga_platz3 + $euro_liga_platz2_1
+ $euro_liga_platz3_1);
$euro_platz1 = $euro_platz1 + $finaler_rest;
//Log::info("PLatz 1 mit Rest(".$finaler_rest.") = ".$euro_platz1);
$payouts=array();
$payouts['tagessieg'] = $euro_tagessieg;
$payouts['platz1'] = $euro_platz1;
$payouts['platz2'] = $euro_platz2;
$payouts['platz3'] = $euro_platz3;
$payouts['platz4'] = $euro_platz4;
$payouts['platz5'] = $euro_platz5;
$payouts['platz6'] = $euro_platz6;
$payouts['platz7'] = $euro_platz7;
$payouts['platz8'] = $euro_platz8;
$payouts['platz9'] = $euro_platz9;
$payouts['platz10'] = $euro_platz10;
$payouts['liga_platz1'] = $euro_liga_platz1;
$payouts['liga_platz2'] = $euro_liga_platz2;
$payouts['liga_platz3'] = $euro_liga_platz3;
$payouts['liga_platz2_1'] = $euro_liga_platz2_1;
$payouts['liga_platz3_1'] = $euro_liga_platz3_1;
$payouts['gshirt'] = $euro_gruenes_trikot;
$payouts['pokal'] = $euro_pokal;
return $payouts;
}
// Subfunction of setQuotas
public static function setQuota($name, $value) {
$season_id = Season::getCurrent()->id;
$quota = Quota::all()->where('season_id','=',$season_id)->where('name','=',$name)->first();
if (!$quota) {
$quota = new Quota();
}
$quota->season_id = $season_id;
$quota->name = $name;
$quota->prc = $value;
$quota->save();
}
public static function getQuota($quota_name) {
$season_id=Season::getCurrent()->id;
$quota=Quota::all()->where('season_id','=', $season_id)->where('name','=', $quota_name)->first();
return $quota['prc'];
}
public static function getQuotas() {
$season_id = Season::getCurrent()->id;
$quotas=Quota::all()->where('season_id','=', $season_id);
$arr=array();
foreach($quotas as $quota) {
$arr[$quota['name']]=$quota['prc'];
}
return $arr;
}
public static function getQuotasForDisplay() {
$quotas=Quota::getQuotas();
foreach($quotas as $key => $val) {
$quotas[$key]=str_replace(".",",", $val);
}
return $quotas;
}
public static function setQuotas($quotas) {
$season_id = Season::getCurrent()->id;
foreach ($quotas as $key => $quota) {
setQuota($key, $quota, $season_id);
}
}
public static function createDefaultQuota()
{
$season_id = Season::getCurrent()->id;
Log::info('Creating default quotas');
DB::table('quotas')->where('season_id', '=', $season_id)->delete();
$roundCount=Season::getCurrent()->rounds;
Log::info("Creating new Quota");
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "einsatz";
$quota->prc = 40;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "tagessieg";
$quota->prc = 40;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "platzierung";
$quota->prc = 40;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "gshirt";
$quota->prc = 3;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "pokal";
$quota->prc = 3;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "liga";
$quota->prc = 14;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "platz1";
$quota->order = 1;
$quota->prc = 21;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "platz2";
$quota->order = 2;
$quota->prc = 17;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "platz3";
$quota->order = 3;
$quota->prc = 13;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "platz4";
$quota->order = 4;
$quota->prc = 10;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "platz5";
$quota->order = 5;
$quota->prc = 9;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "platz6";
$quota->order = 6;
$quota->prc = 8;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "platz7";
$quota->order = 7;
$quota->prc = 7;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "platz8";
$quota->order = 8;
$quota->prc = 6;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "platz9";
$quota->order = 9;
$quota->prc = 5;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "platz10";
$quota->order = 10;
$quota->prc = 4;
$quota->save();
///////////////////////////////////
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "liga_platz1";
$quota->order = 10;
$quota->prc = 50;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "liga_platz2";
$quota->order = 10;
$quota->prc = 20;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "liga_platz3";
$quota->order = 10;
$quota->prc = 17;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "liga_platz2_1";
$quota->order = 10;
$quota->prc = 8;
$quota->save();
$quota = new Quota;
$quota->season_id = $season_id;
$quota->name = "liga_platz3_1";
$quota->order = 10;
$quota->prc = 5;
$quota->save();
}
// Senkt die Zahl solange, bis sie durch 6 teilbar ist,
// Abrundungsvorgabe für Ausschüttungs-Grundbeträge.
public static function get6Divisor($number) {
// Eine Zahl ist durch 6 teilbar, wenn sie durch 2 und 3 teilbar ist.
while ($number % 2 or $number %3 ) { $number--; }
return $number;
}
// Beinhaltet Liste der Payouts für alle User.
// User ohne Payout sind mit leerer Liste ebenfalls enthalten.
public static function getPayoutList($response=null) {
if (!$response) {
$response = Tipp::getRoundTipps();
}
$roundtipps = $response['roundtipps'];
$round_ids = $response['round_ids'];
$user_ids = $response['user_ids'];
$payoutList=array();
foreach($user_ids as $userId) {
$payoutList[$userId]=array();
}
$payouts = array();
foreach($round_ids as $roundId) {
foreach($user_ids as $userId) {
$key = $roundId . "_" . $userId;
$payout = $roundtipps[$key]['payout'];
if (strlen($payout) > 0) {
$round = Round::where('id', '=', $roundId)->first();
$item = array();
$item['roundname'] = $round->name . " (Tagessieg)";
$item['payout'] = str_replace(",",".",$payout);
array_push($payoutList[$userId], $item);
}
if ($roundtipps[$key]['ranking_payout'] > 0) {
$item = array();
$item['roundname'] = "Platzierungssieg Rang " . $roundtipps[$key]['rank'];
$item['payout'] = str_replace(",",".",$roundtipps[$key]['ranking_payout']);
array_push($payoutList[$userId], $item);
}
}
}
// Gshirt START
if (Season::hasGreenShirtGame() ) {
$gshirtTotalPayout = Quota::getPayouts()['gshirt'];
$leaderCount = 0;
$leaderIds = array();
foreach ($user_ids as $uid) {
$key = Round::getLastRoundId() . "_" . $uid; // $key could be nonexistenen if we are not in the last round
if (!array_key_exists($key, $roundtipps)) continue;
if ($roundtipps[$key]['gshirt_leader'] == 1) {
$leaderCount += 1;
array_push($leaderIds,$uid);
}
}
if ($leaderCount) {
$payoutPerLeader = round($gshirtTotalPayout / $leaderCount, 2);
foreach ($leaderIds as $leaderId) {
$item = array();
$item['roundname'] = "Grünes Trikot";
$item['payout'] = $payoutPerLeader;
array_push($payoutList[$leaderId], $item);
}
}
}
// GSHirt End
// Manuelle Payouts hinzufügen
$names = ["pokal" => "Pokal", "liga_platz1"=>"Liga 1, Platz 1",
"liga_platz2"=>"Liga 1, Platz 2 ", "liga_platz3" => "Liga 1, Platz 3",
"liga_platz2_1" =>"Liga 2, Platz 1", "liga_platz3_1"=>"Liga 3, Platz 1"
];
$_payouts = Quota::getPayouts();
$winners = ManualPayout::getWinners();
foreach ($winners as $quota => $uId) {
if ($uId==0) continue; // No winner
$item = array();
$item['roundname']=$names[$quota];
$item['payout']=$_payouts[$quota];
array_push($payoutList[$uId],$item);
}
return $payoutList;
}
public static function getPayoutPerUserDetails($userId, $response=null) {
$allPayouts = Quota::getPayoutList($response);
return $allPayouts[$userId];
}
public static function getPayoutPerUser($seasonId=-1)
{
$payoutList = Quota::getPayoutList();
$usernames = User::getNames();
// Details pro UserId addieren
$payoutPerUser=array();
foreach ( $payoutList as $userId => $payoutItems) {
$payoutPerUser[$userId]=0;
foreach ($payoutItems as $payoutItem) {
$payoutPerUser[$userId] += $payoutItem['payout'];
}
}
// Nach Payout-Betrag absteigend sortieren
$sortedPayout = array();
foreach ($payoutPerUser as $userId => $amount) {
$payment = array();
$payment['user_id'] = $userId;
$payment['name'] = $usernames[$userId];
$payment['amount'] = $amount;
array_push($sortedPayout, $payment);
}
usort($sortedPayout,array('App\Quota','cmpPayment'));
return $sortedPayout;
}
public static function cmpPayment($payment1, $payment2) {
return ($payment1['amount'] < $payment2['amount']);
}
}

View file

@ -0,0 +1,247 @@
<?php
namespace App;
use App\Season;
use Illuminate\Database\Eloquent\Model;
use App\Game;
use Log;
use DB;
use Carbon;
use App\MyClasses\TimeLogger;
class Round extends Model
{
protected $fillable = [
'name', 'season_id'
];
public function games()
{
return $this->hasMany('App\Game');
}
// true, wenn irgend ein Game locked ist.
public static function hasLockedGame($round_id)
{
//Log::info("Check Round::HasLockedGame => ".$round_id);
$games = Game::where('round_id', $round_id)->get();
foreach ($games as $game) {
if (Game::locked($game->id)==true) {
return true;
}
}
return false;
}
public static function isCompleted($round_id) {
$round = Round::where('id','=',$round_id)->first();
$games = Game::where('round_id','=',$round->id)->get();
$completed = true;
foreach($games as $game) {
if ($game->score1==-1 || $game->score2==-1) {
$completed=false;
}
}
return $completed;
}
public static function getLastCompleteRoundId($seasonId=-1) {
$season = Season::getCurrent();
if ($seasonId!=-1) {
$season=Season::where('id','=',$seasonId)->first();
}
if (!$season) return -1;
$seasonId=$season->id;
$rounds=Round::where('season_id','=',$season->id)->orderBy('id')->get();
$lastCompleteRound=-1;
foreach ($rounds as $round) {
if (Round::isCompleted($round->id) == true) {
$lastCompleteRound = $round->id;
}
}
return $lastCompleteRound;
}
public static function getFirstIncompleteRound($seasonId=-1) {
$season=null;
if ($seasonId==-1) {
$season = Season::getCurrent();
} else {
$season = Season::where('id','=',$seasonId)->first();
}
if (!$season) return -1;
$seasonId=$season->id;
$rounds = Round::where('season_id','=',$seasonId)->orderBy('id')->get();
foreach($rounds as $round) {
if (!Round::isCompleted($round->id)) return $round->id;
}
return -1;
}
public static function getNextRoundId($roundId, $seasonId=-1) {
$season=null;
if ($seasonId==-1) {
$currentSeason=Season::getCurrent();
} else {
$currentSeason=Season::where('id','=', $seasonId)->first();
}
if (!$currentSeason) return -1;
$seasonId = $currentSeason->id;
$rounds = Round::where('season_id','=',$seasonId)->where('id','>=',$roundId)->get();
foreach($rounds as $round) {
if ($round->id == $roundId) { continue; }
return $round->id;
}
return -1;
}
public static function getLastLockedRoundId($seasonId=-1) {
$season=null;
if ($seasonId==-1) {
$season=Season::getCurrent();
} else {
$season=Season::where('id','=', $seasonId)->first();
}
if (!$season) return -1;
$rounds=Round::where('season_id','=',$season->id)->orderBy('id')->get();
$lastLockedRoundId=-1;
foreach ($rounds as $round) {
if (Round::hasLockedGame($round->id) == true) {
$lastLockedRoundId = $round->id;
}
}
return $lastLockedRoundId;
}
public static function getFirstTippableRoundId($seasonId=-1) {
$round = Round::getFirstTippableRound();
if (!$round) return -1;
return $round->id;
}
public static function getFirstTippableRound($seasonId=-1) {
$season=null;
if ($seasonId==-1) {
$season=Season::getCurrent();
} else {
$season=Season::where('id','=', $seasonId)->first();
}
if (!$season) {
return null;
}
$rounds=Round::where('season_id','=',$season->id)->orderBy('id')->get();
$locked = false;
foreach ($rounds as $round) {
if (!Round::hasLockedGame($round->id)) {
return $round;
}
}
return null;
}
public static function getCount($seasonId=-1) {
$season=null;
if ($seasonId==-1) {
$season=Season::getCurrent();
} else {
$season=Season::where('id','=', $seasonId)->first();
}
if (!$season) return 0;
$rounds=Round::where('season_id','=',$season->id)->get();
return sizeof($rounds);
}
// TODO: CHeck : Unused ??
public static function getClosestRoundToNow() {
$sql="select round_id,DATEDIFF(NOW(),kickoff) from games order by 2 desc limit 1;";
$result=DB::select($sql);
if (count($result)==0) return 0;
return $result[0]->round_id;
}
public static function getTippSpielLink() // Mit Verweis auf den aktuellen Tipp
{
$firstTippableRound=Round::getFirstTippableRound();
if (!$firstTippableRound) return "";
$firstTippableRoundId=$firstTippableRound->id;
$tippSpielLink="http://hoschis-tippspiel.de/tipps#".$firstTippableRoundId;
return $tippSpielLink;
}
// Ab sofort Verzicht auf statische Methoden, soweit möglich.
public function getLockTime() {
$games = Game::where('round_id','=',$this->id)->get();
$earliestKickoff = Carbon\Carbon::now();
$earliestKickoff->addWeeks(100);
foreach($games as $game) {
$kickoff = Carbon\Carbon::parse($game->kickoff);
if ($kickoff < $earliestKickoff) { $earliestKickoff = $kickoff; }
}
//$earliestKickoff->subHour();
$earliestKickoff->subMinute(); // 2020-09-11 changed from SubHour()
return $earliestKickoff;
}
public function isInLockWarningTime($hours) {
$hourDiffToLock=$this->getLockTime()->diffInHours(Carbon\Carbon::now());
if ($hourDiffToLock<=$hours) return true;
return false;
}
public function getRemainingHoursBeforeLock() {
$hourDiffToLock=$this->getLockTime()->diffInHours(Carbon\Carbon::now());
return $hourDiffToLock;
}
public static function getNames($seasonId=-1) {
Log::info("Round::getNames for seasonId=".$seasonId);
$season= Season::getCurrent();
if ($seasonId!=-1) { $season = Season::where('id','=',$seasonId)->first(); }
$rounds = Round::where('season_id','=',$season->id)->get();
//Log::info("Number of rounds:".sizeof($rounds));
//Log::info("START");
$roundnames = array();
foreach($rounds as $round) {
$roundnames[$round->id] = $round->name;
}
return $roundnames;
}
public static function getLastRoundId($seasonId=-1) {
$season= Season::getCurrent();
if ($seasonId!=-1) { $season = Season::where('id','=',$seasonId)->first(); }
$round = Round::where('season_id', '=', $season->id)->orderBy('id','desc')->first(); // get last entry
return $round->id;
}
public static function getSeasonId($round_id) {
$round=Round::where('id',$round_id)->first();
return $round->season_id;
}
}

View file

@ -0,0 +1,12 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Roundmail extends Model
{
protected $fillable = [
'send_date', 'recipients','topic','message','user_id'
];
}

View file

@ -0,0 +1,120 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use \App\Setting;
use Log;
use \App\Leagues\League;
class Season extends Model
{
protected $fillable = [
'name','rounds',"max_identical_jokertipps"
];
/*
public function isActive() {
return $this->hasOne('App\Setting','season_id');
}
*/
public static function getCurrent() {
$setting = Setting::all()->first();
if (!$setting) {
//Log::info('Season.getCurrent(): No current season set');
error_log('Season.getCurrent(): No current season set');
return null;
}
//Log::info("current_season_id=" . $setting->current_season_id);
$currentSeason = Season::where('id',$setting->current_season_id)->first();
return $currentSeason;
}
public static function setCurrent($season_id) {
$setting = Setting::all()->first();
if (!$setting) {
$setting = Setting::create([
'current_season_id' => $season_id
]);
}
$setting->current_season_id=$season_id;
$setting->save();
}
public static function getPrevious() {
$seasons=Season::where('id','>',0)->orderBy('id','DESC')->get();
if (sizeof($seasons)<2) { return null; }
return $seasons[1];
}
public static function get($seasonId) {
if ($seasonId==-1) return Season::getCurrent();
$season=Season::where('id','=',$seasonId)->first();
return $season;
}
public static function hasQualifications($seasonId=-1) {
return Season::hasLeagueType($seasonId,League::RANK_QUALIFICATION);
}
public static function hasStandardLeague($seasonId=-1) {
return Season::hasLeagueType($seasonId,League::RANK_LEAGUE1);
}
public static function hasLeagueType($seasonId=-1, $ltype) {
$season=null;
if ($seasonId==-1) {
$season = Season::getCurrent();
if (!$season) return false;
$seasonId=$season->id;
}
$leagues = League::where('season_id', '=', $seasonId)->get();
foreach ($leagues as $league) {
if ($league->rank == $ltype) return true;
}
return false;
}
public static function hasGreenShirtGame($seasonId=-1) {
$season=null;
if ($seasonId==-1) {
$season = Season::getCurrent();
if (!$season) return false;
$seasonId=$season->id;
}
$quota=Quota::getQuota("gshirt");
return $quota>0;
}
// implemented 2020-01-08 because of needed first round_id of the season
public static function getFirstRoundId($seasonId=-1) {
$season=null;
if ($seasonId==-1) {
$season = Season::getCurrent();
} else {
$season = Season::where('id','=',$seasonId)->first();
}
if (!$season) return -1;
$seasonId=$season->id;
$firstRound = Round::where('season_id','=',$seasonId)->orderBy('id')->first();
return $firstRound->id;
}
public static function maxIdenticalJokertipps($seasonId=-1) {
$season=null;
if ($seasonId==-1) {
$season = Season::getCurrent();
} else {
$season = Season::where('id','=',$seasonId)->first();
}
return $season->max_identical_jokertipps;
}
}

View file

@ -0,0 +1,12 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $fillable = [
'current_season_id'
];
}

View file

@ -0,0 +1,78 @@
<?php
namespace App;
use Carbon;
use Illuminate\Database\Eloquent\Model;
class Test extends Model
{
// In order for testing seasons to work, we need a way to set all the users to 'paid'
// this method is used by fillSeason method
public static function paySeason($seasonId=-1)
{
if ($seasonId==-1) {
$season = Season::getCurrent();
$seasonId = $season->id;
}
$users = User::all();
$cnt=0;
foreach ($users as $user) {
if (!$user->deleted && $user->id !=1)
{ Payment::set_payment_date($user->id, $seasonId, '01.01.2017'); $cnt+=1;}
}
return $cnt." Users in season_id ".$seasonId." set to paid";
}
public static function fillSeason($seasonId=-1) {
if ($seasonId==-1) {
$season = Season::getCurrent();
$seasonId = $season->id;
}
error_log("creating all tipps started");
Tipp::createAllTips();
error_log("creating all tipps completed");
$users = User::all();
error_log("setting payment started");
Test::paySeason($seasonId);
error_log("setting payment completed");
error_log("Users: ".sizeof($users));
// Spielergebnisse faken
$rounds=Round::where('season_id','=',$seasonId)->get();
error_log("Rounds: ".sizeof($rounds));
foreach ($rounds as $round) {
$games=Game::where('round_id','=',$round->id)->get();
$jokerSet=false;
error_log("Faking Tipps and game results for all users for: ".$round->name);
foreach ($games as $game) {
$game->score1=random_int(0,3);
$game->score2=random_int(0,3);
$game->kickoff= Carbon\Carbon::now();
$game->save();
foreach ($users as $user) {
// Tipps faken
$tipp=Tipp::where('game_id','=',$game->id)->where('user_id','=',$user->id)->first();
$tipp->score1 = random_int(0,3);
$tipp->score2 = random_int(0,3);
if (!$jokerSet) {
$tipp->joker=true;
}
$tipp->save();
}
$jokerSet=true;
}
}
}
}

View file

@ -0,0 +1,916 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
use Carbon;
use Log;
use App\MyClasses\TimeLogger;
use Symfony\Component\CssSelector\Tests\Node\SelectorNodeTest;
class Tipp extends Model
{
protected $fillable = [
'id', 'user_id', 'game_id','score1','score2','joker'
];
public static function trendCol($score1, $score2, $tipp1, $tipp2, $joker) {
$tippTendenz = $tipp1 - $tipp2;
if ($tippTendenz > 0) {$tippTendenz=1;}
if ($tippTendenz < 0) {$tippTendenz=-1;}
$gameTendenz = $score1 - $score2;
if ($gameTendenz<0) {$gameTendenz=-1;}
if ($gameTendenz>0) {$gameTendenz=1;}
if ($tippTendenz!=$gameTendenz || $score1 ==-1 || $score2==-1 || $tipp1 == -1 || $tipp2==-1) {
return "";
}
$styling='background-color:grey;';
if ( ($tipp1 == $score1) && ($tipp2 == $score2) ) {
$styling='background-color:orange;';
if ($joker) {
$styling='background-color:red';
}
}
return $styling;
}
// get tendency Color
public static function getCol($user_id,$game_id) {
$tipp = Tipp::getTipp($user_id,$game_id);
$game = Game::where('id',$tipp->game_id)->first();
$tippTendenz = $tipp->score1 - $tipp->score2;
if ($tippTendenz > 0) {$tippTendenz=1;}
if ($tippTendenz < 0) {$tippTendenz=-1;}
$gameTendenz = $game->score1 - $game->score2;
if ($gameTendenz<0) {$gameTendenz=-1;}
if ($gameTendenz>0) {$gameTendenz=1;}
if ($tippTendenz!=$gameTendenz || $game->score1 ==-1 || $game->score2==-1 || $tipp->score1 == -1 || $tipp->score2==-1) {
return "";
}
$styling='background-color:grey;';
if ( ($tipp->score1 == $game->score1) && ($tipp->score2 == $game->score2) ) {
$styling='background-color:orange;';
if ($tipp->joker==true) {
$styling='background-color:red';
}
}
return $styling;
}
public static function getTipp( $user_id,$game_id) {
//Log::info("getTipp for game_id, user_id = ".$game_id.",".$user_id);
return DB::table('tipps')->where([
['user_id','=',$user_id],
['game_id','=',$game_id]
])->first();
}
public static function getScoreLocal($goals1, $goals2, $tipp1, $tipp2, $joker) {
$score=0;
$tippTendenz = $tipp1 - $tipp2;
if ($tippTendenz > 0) {$tippTendenz=1;}
if ($tippTendenz < 0) {$tippTendenz=-1;}
$gameTendenz = $goals1 - $goals2;
if ($gameTendenz<0) {$gameTendenz=-1;}
if ($gameTendenz>0) {$gameTendenz=1;}
if ($tippTendenz==$gameTendenz) { $score=1; }
if ( ($tipp1 == $goals1) && ($tipp2 == $goals2) ) {
$bonus = max(0,$goals1 + $goals2 - 3);
$score= 2 + $bonus;
}
if ($joker==true) {
$score = $score * 2;
}
if ($tipp1==-1||$tipp2==-1||$goals1==-1||$goals2==-1) { $score=0; }
return $score;
}
// Bei Tagessieg gilt nur wer am meisten genau richtig getippt hat,
// Bei Gleichstand wer den höchsten Jokersieg hat ( Jokersieg mit mehr Toren zählt mehr)
// Bei Gleichstand gilt die Summe aller Rankscores, deshalb wird sie auch im Ergebnis gespeichert
// Fürs Dayscore-Bewerten ist rankscore allerdings irrelevant. Mit Rank nur fürs Sortieren, um die Auswahl einzugrenzen.
public static function getDayScoreLocal($goals1, $goals2, $tipp1, $tipp2, $joker, $rankScore=0) {
if ($tipp1==-1||$tipp2==-1||$goals1==-1||$goals2==-1) { return 0; } // Ungetippt oder Spiel hat noch kein Ergebnis
if ( ($tipp1 != $goals1) || ($tipp2 != $goals2) ) return 0;
$jokerValue=0;
if ($joker) {
$jokerValue = max(0, $goals1 + $goals2 - 3) + 1;
}
return 1000 + $jokerValue * 100 + $rankScore;
}
public static function getTippScore($user_id,$game_id, $team=0) {
//Log::info("Getting tippstring for game_id=". $game_id .", user_id=" . $user_id.", $team=".$team);
$tipp=Tipp::getTipp($user_id,$game_id);
if (!$tipp) {
//Log::info("not found !");
return "x";
}
$tippScore="";
if ($team==0) { $tippScore= $tipp->score1;}
else { $tippScore=$tipp->score2; }
if ($tippScore==-1) { /*Log::info("untipped!");*/$tippScore="x";}
//Log::info("Returning: ". $tippScore);
return $tippScore;
}
public static function getScore($tipp_id) {
$tipp = Tipp::where('id',$tipp_id)->first();
$game = Game::where('id',$tipp->game_id)->first();
$bonus = max(0,$game->score1 + $game->score2 - 3);
$tippTendenz = $tipp->score1 - $tipp->score2;
if ($tippTendenz > 0) {$tippTendenz=1;}
if ($tippTendenz < 0) {$tippTendenz=-1;}
$gameTendenz = $game->score1 - $game->score2;
if ($gameTendenz<0) {$gameTendenz=-1;}
if ($gameTendenz>0) {$gameTendenz=1;}
$score=0;
if ($tippTendenz == $gameTendenz) { $score=1; }
if ( ($tipp->score1 == $game->score1) && ($tipp->score2 == $game->score2) ) {
$score=2 + $bonus;
}
if ($tipp->joker==true) {
$score = $score *2;
}
if ($game->score1 == -1) { $score=0; }
if ($tipp->score1==-1 || $tipp->score2==-1) {$score=0;}
return $score;
}
public static function resultString($tipp_id) {
$tipp = Tipp::where('id',$tipp_id)->first();
$rStr="Ungetippt";
if ($tipp->score1 > -1) $rStr= $tipp->score1 . " : " . $tipp->score2;
return $rStr;
}
public static function createTipps($user_id) {
$a=new TimeLogger("Tipp::createTipps()");
Log::info($a->getStartMessage());
$activeSeason = Season::getCurrent();
$rounds = Round::all()->where('season_id', '=', $activeSeason->id);
foreach($rounds as $round) {
$games=Game::all()->where('round_id','=',$round->id);
foreach($games as $game) {
// Tipp erzeugen wenn noch nicht vorhanden
$tipp = DB::table('tipps')->where([
['game_id','=',$game->id],
['user_id','=',$user_id]]
)->first();
if (! $tipp) {
$tipp=Tipp::create([
'user_id' => $user_id,
'game_id'=> $game->id,
'score1'=> -1,
'score2'=> -1,
'joker'=> false
]);
$tipp->save();
}
}
}
Log::info($a->getEndMessage());
}
public static function createAllTips() {
$a=new TimeLogger("Tipp::createAllTipps()");
Log::info($a->getStartMessage());
$users = DB::table('users')->where('deleted',null)->get();
foreach($users as $user) {
Log::info("Creating tipps for userid ".$user->id);
Tipp::createTipps($user->id);
}
Log::info($a->getEndMessage());
}
// Struktur: gameval * 1000 + jokerValue * 100 + rankscore
public static function addDayScoreValues($val1, $val2) {
$gameVal1 = intdiv($val1 , 1000);
$gameVal2 = intdiv( $val2, 1000);
$jokerVal1 = intdiv(($val1 - $gameVal1*1000),100);
$jokerVal2 = intdiv(($val2 - $gameVal2*1000),100);
if ( $gameVal1 ==0 ) { $jokerVal1=0; $rankVal1=0; }
if ( $gameVal2 ==0 ) { $jokerVal2=0; $rankVal2=0; }
$rankVal1 = $val1 - $gameVal1*1000 - $jokerVal1*100;
$rankVal2 = $val2 - $gameVal2*1000 - $jokerVal2*100;
// Minimaler Brainfuck, da $rankVal1 und $rankVal2 immer gleich sein sollten
$result = ($gameVal1 + $gameVal2) * 1000 + max($jokerVal1, $jokerVal2) * 100 + max ($rankVal1, $rankVal2);
return $result;
}
public static function getDayScoreWithoutRankScore($val) {
$gameVal = intdiv($val , 1000);
$jokerVal = intdiv(($val - $gameVal*1000),100);
if ($gameVal==0) return 0;
return $gameVal * 1000 + $jokerVal * 100;
}
// TODO: Implement partial caching
public static function getRoundTipps($max_round_id=-1, $seasonId=-1)
{
$a=new TimeLogger("getRoundTipps max_round_id=".$max_round_id.", seasonId=".$seasonId);
Log::info($a->getStartMessage());
$startTime = microtime(true);
$currentSeason = Season::getCurrent();
if ($seasonId != -1) {
$currentSeason = Season::where('id', '=', $seasonId)->first();
};
if (Round::getLastLockedRoundId($seasonId)==-1) {
error_log("Tipp::getRoundTipps returns null, because there is no LastLockedRoundId");
return null;
}
// Hier werden _alle_ Tipps der aktuellen Saison ausgerechnet, die $round_id Begrenzung wird erst später ausgewertet.
// TODO: Nur die Runden durchrechnen, die aktuell sind, oder round_incomplete, alle anderen Runden (bis zur ersten unvollständigen) sollen in eine Cachetabelle gespeichert werden.
$sql = "select users.id as user_id, users.name as user_name, ";
$sql = $sql . "rounds.id as round_id, rounds.name as round_name, ";
$sql = $sql . "games.id as game_id, games.team1, games.team2, games.score1 as game_score1, games.score2 as game_score2, games.kickoff as game_kickoff, ";
$sql = $sql . "tipps.id as tipp_id, tipps.score1 as tipp_score1, tipps.score2 as tipp_score2, tipps.joker ";
$sql = $sql . "from users,rounds,games,tipps,payments ";
$sql = $sql . "where rounds.season_id=" . $currentSeason->id . " ";
$sql = $sql . "and games.round_id=rounds.id and tipps.game_id=games.id and users.id = tipps.user_id ";
$sql = $sql . "and payments.season_id=" . $currentSeason->id . " and payments.user_id = users.id ";
$sql = $sql . "and payments.paid_date is not null ";
$sql = $sql . "order by rounds.id, games.id, users.id;";
$result = DB::select($sql);
$roundtipps = array();
$roundData = array();
$user_ids = array();
$round_ids = array();
// Write sql result to roundtipps (score per round & user)
if ($max_round_id == -1) {
$max_round_id = Round::getLastLockedRoundId($currentSeason->id);
}
foreach ($result as $entry) {
$round_id = $entry->round_id;
if ($max_round_id > -1 && $round_id > $max_round_id) break;
if (!in_array($entry->user_id, $user_ids)) {
array_push($user_ids, $entry->user_id);
}
if (!in_array($entry->round_id, $round_ids)) {
array_push($round_ids, $entry->round_id);
}
if (!in_array($round_id, $roundData)) {
$roundData[$round_id] = array();
}
$user_id = $entry->user_id;
$key = $round_id . "_" . $user_id;
if (!array_key_exists($key, $roundtipps)) {
$roundtipps[$key] = array();
$roundtipps[$key]['tipps'] = array();
$roundtipps[$key]['results'] = array();
$roundtipps[$key]['joker'] = array();
$roundtipps[$key]['round_completed'] = true;
$roundtipps[$key]['user_name'] = $entry->user_name;
$roundtipps[$key]['user_id'] = $entry->user_id;
$roundtipps[$key]['rankscore'] = 0;
$roundtipps[$key]['payout'] = 0;
$roundtipps[$key]['earliest_kickoff'] = $entry->game_kickoff;
$roundtipps[$key]['hits'] = 0; // Wenigstens Tendenz getroffen. Wenn 4, dann 2 Punkte Bonus auf rankscore
$roundtipps[$key]['is_dayscorewinner'] = 0;
$roundtipps[$key]["ranking_payout"] = 0; // Existiert nur in der letzten Runde
}
if (!array_key_exists('is_completed', $roundData[$round_id])) {
$roundData[$round_id]['is_completed'] = true;
}
$game_value = Tipp::getScoreLocal($entry->game_score1, $entry->game_score2, $entry->tipp_score1, $entry->tipp_score2, $entry->joker); // Für alle 4 Spiele
$roundtipps[$key]['rankscore'] += $game_value;
if ($game_value > 0) {
$roundtipps[$key]['hits'] += 1;
}
if ($roundtipps[$key]['hits'] == 4) {
$roundtipps[$key]['rankscore'] += 2;
} // Wenn alle 4 Spiele mind. Tendenz, dann 2 Punkte Bonus
if ($entry->game_score1 == -1 || $entry->game_score2 == -1) {
$roundtipps[$key]['round_completed'] = false; // TODO: Remove it, its succeeded by roundData['is_completed']
$rounds[$round_id]['is_completed'] = false;
}
array_push($roundtipps[$key]['tipps'], $entry->tipp_score1);
array_push($roundtipps[$key]['tipps'], $entry->tipp_score2);
array_push($roundtipps[$key]['results'], $entry->game_score1);
array_push($roundtipps[$key]['results'], $entry->game_score2);
array_push($roundtipps[$key]['joker'], $entry->joker);
if ($entry->game_kickoff < $roundtipps[$key]['earliest_kickoff']) {
$roundtipps[$key]['earliest_kickoff'] = $entry->game_kickoff;
}
}
// NOW ALL KEYS FOR ROUNDTIPPS (ROUND & USER) EXIST
/////////////////////////////////////////////////////////////////////
// CALCULATION OF SCORES, RANKS, ETC. (COMPUTE AGGREGATED VALUES) EXCEPT GREENSHIRT, ARGH !!
/////////////////////////////////////////////////////////////////////
$highestDayscores = array();
foreach ($user_ids as $user_id) {
$totalRankScore = 0;
foreach ($round_ids as $round_id) {
$key = $round_id . "_" . $user_id;
// Compute Dayscore values
$dayScore1WithRankScore = Tipp::getDayScoreLocal($roundtipps[$key]['results'][0], $roundtipps[$key]['results'][1], $roundtipps[$key]['tipps'][0], $roundtipps[$key]['tipps'][1], $roundtipps[$key]['joker'][0], $roundtipps[$key]['rankscore']);
$dayScore2WithRankScore = Tipp::getDayScoreLocal($roundtipps[$key]['results'][2], $roundtipps[$key]['results'][3], $roundtipps[$key]['tipps'][2], $roundtipps[$key]['tipps'][3], $roundtipps[$key]['joker'][1], $roundtipps[$key]['rankscore']);
$dayScore3WithRankScore = Tipp::getDayScoreLocal($roundtipps[$key]['results'][4], $roundtipps[$key]['results'][5], $roundtipps[$key]['tipps'][4], $roundtipps[$key]['tipps'][5], $roundtipps[$key]['joker'][2], $roundtipps[$key]['rankscore']);
$dayScore4WithRankScore = Tipp::getDayScoreLocal($roundtipps[$key]['results'][6], $roundtipps[$key]['results'][7], $roundtipps[$key]['tipps'][6], $roundtipps[$key]['tipps'][7], $roundtipps[$key]['joker'][3], $roundtipps[$key]['rankscore']);
$totalDayScoreWithRankScore = Tipp::addDayScoreValues($dayScore1WithRankScore, $dayScore2WithRankScore);
$totalDayScoreWithRankScore = Tipp::addDayScoreValues($totalDayScoreWithRankScore, $dayScore3WithRankScore);
$totalDayScoreWithRankScore = Tipp::addDayScoreValues($totalDayScoreWithRankScore, $dayScore4WithRankScore);
if ($round_id==921 && $user_id==125) {
Log::info("DayScore Alexander in Runde 19: ". $totalDayScoreWithRankScore);
}
if ($round_id==921 && $user_id==71) {
Log::info("DayScore Karl in Runde 19: ". $totalDayScoreWithRankScore);
}
$roundtipps[$key]['dayScoreWithRankScore'] = $totalDayScoreWithRankScore;
$roundtipps[$key]['dayscore'] = Tipp::getDayScoreWithoutRankScore($totalDayScoreWithRankScore);
if (!array_key_exists($round_id, $highestDayscores)) {
$highestDayscores[$round_id] = 0;
}
if ($highestDayscores[$round_id] < $roundtipps[$key]['dayscore']) {
$highestDayscores[$round_id] = $roundtipps[$key]['dayscore'];
}
$totalRankScore += $roundtipps[$key]["rankscore"];
$roundtipps[$key]['totalRankScore'] = $totalRankScore;
// Corona Update for season_id=6
// round_id 252 ==> Runde 22
if ( $user_id == 54 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 4; }
if ( $user_id == 82 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 2; }
if ( $user_id == 117 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 2; }
if ( $user_id == 20 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 2; }
if ( $user_id == 25 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 2; }
if ( $user_id == 56 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 120 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 19 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 106 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 112 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 114 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 23 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 21 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 7 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 61 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 69 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 75 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 22 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 111 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 81 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 98 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 34 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 107 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 6 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 68 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 40 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 13 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 91 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 94 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 30 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 116 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 99 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 121 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
if ( $user_id == 62 && $round_id == 252) { $roundtipps[$key]['totalRankScore'] += 1; }
}
}
////////////////////////////////////////////////////////
// Sortier-Array nach Rang (nur für max_round_id)
$userRankings = array();
foreach ($user_ids as $user_id) {
$key = $max_round_id . "_" . $user_id;
array_push($userRankings, [$user_id, $roundtipps[$key]['totalRankScore']]);
}
usort($userRankings, array('App\Tipp', 'cmpRank'));
// Ranknr identifizieren, inkl, geteilter Rankplatzierungen
$lastScore = -1;
$lastrank = 0;
$current_list_position = 0;
foreach ($userRankings as $userRank) {
$user_id = $userRank[0];
$totalRankScore = $userRank[1];
$key = $max_round_id . "_" . $user_id;
$current_list_position += 1;
if ($roundtipps[$key]["totalRankScore"] == $lastScore) {
$roundtipps[$key]["rank"] = $lastrank;
} else {
$lastrank = $current_list_position;
$roundtipps[$key]["rank"] = $current_list_position;
$lastScore = $totalRankScore;
}
}
////////////////////////////////////////////////////////
// Sortier-Array für GShirt nach rankscore des Tages (für jede round_id)
foreach ($round_ids as $round_id) {
$userRankings = array();
foreach ($user_ids as $user_id) {
$key = $round_id . "_" . $user_id;
array_push($userRankings, [$user_id, $roundtipps[$key]['rankscore']]);
}
usort($userRankings, array('App\Tipp', 'cmpRank'));
// Ranknr identifizieren, inkl, geteilter Rankplatzierungen
$lastScore = -1;
$lastGrank = 0;
$current_list_position = 0;
foreach ($userRankings as $userRank) {
$user_id = $userRank[0];
$totalRankScore = $userRank[1];
$key = $round_id . "_" . $user_id;
$current_list_position += 1;
if ($roundtipps[$key]["rankscore"] == $lastScore) {
$roundtipps[$key]["grank"] = $lastGrank;
} else {
$lastGrank = $current_list_position;
$roundtipps[$key]["grank"] = $current_list_position;
$lastScore = $totalRankScore;
}
}
}
////////////////////////////////////////////////////////
// Greenshirt Score Determination
// Loop again over roundtipps, sort each round, give/write forth greenshirt score
$userList=array(); // Only to detect ranks 1-5; score results will get written to roundtipps[$key]['...']
// (A) SET GSCORE EVERY ROUND
// 1.) Loop over roundtipps and : a.) add user + rankscore + foulcount to $userList
// b.) Sort $userList by rankscore
// c.) Determine ranks 1-5 and number of points to distribute
// d.) Mark Rank1 as is_gshirt_owner
// e.) Distribute points, set roundtipps[$key]['gshirt_score'], every other to zero
// (B) SET GSCORE_TOTAL EVERY ROUND
// 2.) Loop over roundtipps and: a.) add gshirt_score to gshirt_score_total --OR-- zero gshirt_score_total if foulCount==3
// A) SET GSCORE EVERY ROUND
foreach($round_ids as $round_id) {
// A-1 fill members with numbers of users per rank
$members=array();
foreach($user_ids as $user_id) {
$key=$round_id."_".$user_id;
$grank=$roundtipps[$key]["grank"];
if(!array_key_exists($grank, $members)) {
$members[$grank]=0;
}
$members[$grank]+=1;
}
// A-2 compute gain
$scoreGain=[0,10,5,3,2,1]; // Rank 0 existiert nicht
// Move gain out of empty ranks into the upper ones.
foreach ([5,4,3,2,1] as $grank) {
if (!array_key_exists($grank,$members)) {
$scoreGain[$grank-1]+= $scoreGain[$grank];
$scoreGain[$grank]=0; // Shouldnt be needed, but makes movement of gain explicit
} else {
}
}
//dd($log."Rank gain: ".$scoreGain[1].", ".$scoreGain[2].", ".$scoreGain[3].", ",$scoreGain[4].", ".$scoreGain[5]);
// Distribute gain
foreach($user_ids as $user_id) {
$key = $round_id . "_" . $user_id;
$grank= $roundtipps[$key]["grank"];
if ($grank<=5) {
$gain = round($scoreGain[$grank] / $members[$grank], 2);
if ($gain>0) {
$gain+=$roundtipps[$key]["rankscore"]; // Gemachte Punkte draufrechnen
}
$roundtipps[$key]["gshirt_score"] = $gain;
} else {
$roundtipps[$key]["gshirt_score"]=0;
}
}
}
// B) SET GSCORE TOTAL EVERY ROUND ( and take fouls into consideration )
$maxScorePerRound=array();
foreach($user_ids as $user_id) {
$foulCount=0;
$totalScore=0;
foreach ($round_ids as $round_id) {
$key = $round_id . "_" . $user_id;
if (!array_key_exists($round_id, $maxScorePerRound)) { $maxScorePerRound[$round_id]=0; }
$score = $roundtipps[$key]['gshirt_score'];
$isFoul = ( $roundtipps[$key]['rankscore'] == 0 && $totalScore > 0 );
if ($isFoul) {
//Log::info("Foul => round_id _ user_id=".$key." / totalRankScore=".$roundtipps[$key]["totalRankScore"]);
$foulCount+=1;
if ($foulCount==3) {
$foulCount=0;
$totalScore=0;
$roundtipps[$key]['gshirt_foul_reset']=1;
} else {
$roundtipps[$key]['gshirt_foul_reset']=0;
}
}
$lastTotalRankScore=
$totalScore += $score;
if ($totalScore > $maxScorePerRound[$round_id]) { $maxScorePerRound[$round_id]=$totalScore; }
$roundtipps[$key]['gshirt_totalscore']=$totalScore;
$roundtipps[$key]['gshirt_foulcount']=$foulCount;
//error_log("Test: key=".$key.", ".$roundtipps[$key]['gshirt_score']);
//Log::info("Test: key=".$key.", ".$roundtipps[$key]['gshirt_score']);
}
}
// C) Set gscore_leader for each round
foreach ($round_ids as $round_id) {
foreach($user_ids as $user_id) {
$key = $round_id . "_" . $user_id;
if ($roundtipps[$key]['gshirt_totalscore'] == $maxScorePerRound[$round_id] && $maxScorePerRound[$round_id]>0 ) {
$roundtipps[$key]['gshirt_leader'] =1;
} else {
$roundtipps[$key]['gshirt_leader'] =0;
}
}
}
//dd("User 11 Round 1 gshirt_score =".$roundtipps['1_11']['gshirt_score'].", totalscore=".$roundtipps['1_11']['gshirt_totalscore']);
//////////////////////////////
// START OF HURTFUL 6 PLACE RESTRICTION IF DAYSCORE WIN (exception: completely even scores)
// If more than 6 DayScoreWinners: Restrict by dayscore (rank)
// Compute highest dayscore
// Addition: no dayscorewinner && round_completed: Payout goes to next round
$payouts = Quota::getPayouts();
$totalDayWinPayout = 0;
$round_count=0;
//error_log("Round ids: ".implode(",",$round_ids));
foreach ($round_ids as $round_id) {
$round_count += 1;
$totalDayWinPayout += $payouts["tagessieg"];
$highestDayScore = $highestDayscores[$round_id];
$usersWithHighestDayScore = array();
$round_completed = false;
foreach ($user_ids as $user_id) {
$key = $round_id . "_" . $user_id;
if ($roundtipps[$key]['dayscore'] == $highestDayScore && $roundtipps[$key]['round_completed'] && $highestDayScore > 0) {
array_push($usersWithHighestDayScore, [$user_id, $roundtipps[$key]['dayScoreWithRankScore']]);
}
if($round_id==921 and $user_id==125) {
Log::info("High-Eval: Alexander Runde 19 => " . $roundtipps[$key]['dayScoreWithRankScore']);
}
if($round_id==921 and $user_id==71) {
Log::info("High-Eval: Karl Runde 19 => " . $roundtipps[$key]['dayScoreWithRankScore']);
}
}
$dayScoreWinnersIds = array();
// Bei >6 Tagessiegern über rankscore reduzieren
if (sizeof($usersWithHighestDayScore) > 6) {
Log::info("Special: >6 Tagessieger in round_id=".$round_id);
usort($usersWithHighestDayScore, array('App\Tipp', 'cmpDayWin'));
$count = 0;
$cutOffScore = 0;
foreach ($usersWithHighestDayScore as $user) { // Feld0: user_id, dayScoreWithRankScore
$key = $max_round_id . "_" . $user[0]; // Hier: $user[0] = user_id, $user[1] = dayScore WithRankScore
$rankscore = $user[1];
$count += 1;
if ($count == 1) {
$cutOffScore = $rankscore;
}
if ($rankscore < $cutOffScore) {
break;
}
array_push($dayScoreWinnersIds, $user[0]);
$key = $round_id . "_" . $user[0];
$roundtipps[$key]['is_dayscorewinner'] = true;
}
}
// Bei bis zu 6 Gewinnern normal als Sieger klassifizieren
else {
foreach ($usersWithHighestDayScore as $user) {
array_push($dayScoreWinnersIds, $user[0]);
$key = $round_id . "_" . $user[0];
$roundtipps[$key]['is_dayscorewinner'] = true;
if ($round_id==921) {
Log::info("Klassifiziere User ". $user[0] . " als Tagessieger für Runde 19");
}
}
}
// Compute Dayscorewin payout (Tagessieg)
$winnerCount = sizeof($dayScoreWinnersIds);
$single_payout=0;
if ($winnerCount > 0) {
$single_payout = $totalDayWinPayout / $winnerCount;
$single_payout = number_format((float)$single_payout, 2, '.', '');
$single_payout = str_replace(".", ",", $single_payout);
$totalDayWinPayout=0;
}
foreach ($user_ids as $user_id) {
$key = $round_id . "_" . $user_id;
if ($roundtipps[$key]['is_dayscorewinner']) {
$roundtipps[$key]['payout'] = $single_payout;
} else {
$roundtipps[$key]['payout'] = '';
}
}
}
///// END OF HURTFUL 6 PLACE RESTRICTION
/// CALCULATE RANK AND PAYOUT QUOTAS
$quotas=Quota::getQuotas();
Log::debug("Round-Count=".$round_count);
if ($round_count==Round::getCount()) {
// Ranking Payout ausschütten
$payout_groups =array();
$lastRoundId= array_values(array_slice($round_ids,-1))[0];
foreach($user_ids as $user_id) {
$key = $lastRoundId."_".$user_id;
$rank = $roundtipps[$key]["rank"];
//Log::info("Setting ranking_payout for user_id ".$user_id);
//TODO: Do it for any number of rank payouts
if ($rank<11) {
if (!array_key_exists($rank,$payout_groups)) {
$payout_groups[$rank]=array();
}
array_push($payout_groups[$rank],$user_id);
}
}
// platz0= unsused, just for getting place equal to rank position.
$rank_names=['platz0','platz1','platz2','platz3','platz4','platz5','platz6','platz7','platz8','platz9','platz10'];
// Ausschüttungsgruppen für Platzierung bilden
foreach([1,2,3,4,5,6,7,8,9,10] as $rank) { // Jedes Payout, das verteilt werden muss
$current_rank = $rank;
$rankPayout=$payouts[$rank_names[$rank]];
while($current_rank) {
while (!array_key_exists($current_rank, $payout_groups)) { $current_rank -=1; }
$groupsize = sizeof($payout_groups[$current_rank]);
$single_payout = $rankPayout / $groupsize;
foreach($payout_groups[$current_rank] as $user_id) {
$key = $lastRoundId."_".$user_id;
$roundtipps[$key]["ranking_payout"] += $single_payout;
}
$current_rank=0;
}
}
}
//////////////////// END OF ROUNDTIPPS CREATION ///////////////////
$response = array();
$response['roundtipps'] = $roundtipps;
$response['roundData'] = $roundData;
$response['user_ids'] = $user_ids;
$response['round_ids'] = $round_ids;
Log::info("Tipp::getRoundTipps: ExecutionTime: " . number_format(( microtime(true) - $startTime), 4) . " Seconds\n");
Log::info($a->getEndMessage());
return $response;
}
// Used by getRoundTipps method
public static function cmpRank($rank1, $rank2) {
return ($rank1[1] < $rank2[1]); //Feld0: user_id, Feld1: rank
}
// Used by getRoundTipps method
public static function cmpDayWin($user1, $user2) {
return ($user1[1] < $user2[1]); // Feld0: user_id, Feld1: dayScoreWithRankScore
}
// Used by getRoundTipps
public static function cmpGShirt($rank1, $rank2) {
return ($rank1[1] < $rank2[1]); //Feld0: user_id, Feld1: rank
}
//Used by gshirt_table: sort by gshirt_totalscore
public static function cmpGShirtTotal($ranktippEntry1, $ranktippEntry2) {
return ($ranktippEntry1['gshirt_totalscore'] < $ranktippEntry2['gshirt_totalscore']); //Feld0: user_id, Feld1: rank
}
public static function gshirt_table() {
$a=new TimeLogger("Tipp::gshirt_table()");
Log::info($a->getStartMessage());
$rt = Tipp::getRoundTipps();
$roundtipps = $rt['roundtipps'];
$round_ids = $rt['round_ids'];
$last_round_id = end($round_ids);
$users=User::getActives();
$roundNames = Round::getNames();
$lastroundentries=array();
foreach ($users as $user) {
$key=$last_round_id."_".$user->id;
array_push($lastroundentries, $roundtipps[$key]);
}
usort($lastroundentries, array('App\Tipp', 'cmpGShirtTotal'));
$rankingDisplay=array();
foreach($lastroundentries as $entry) {
$user_id = $entry['user_id'];
foreach ($round_ids as $round_id) {
$key = $round_id."_".$user_id;
if (!array_key_exists($user_id,$rankingDisplay)) {
$rankingDisplay[$user_id]=array();
}
$roundtipps[$key]["round_name"]=$roundNames[$round_id];
array_push($rankingDisplay[$user_id],$roundtipps[$key]);
}
}
//Rundenreihenfolge umkehren: Neuste zuerst
$rankingDisplay2=array();
foreach($lastroundentries as $entry){
$user_id = $entry['user_id'];
$rankingDisplay[$user_id]=array_reverse($rankingDisplay[$user_id]);
array_push($rankingDisplay2,$rankingDisplay[$user_id]);
}
Log::info($a->getEndMessage());
return $rankingDisplay2;
}
// Creates array of countings of all joker usages
public static function getJokerUsageArray($user_id,$round_id) {
$seasonId=Round::getSeasonId($round_id);
$firstRoundId=Season::getFirstRoundId($seasonId);
if ($firstRoundId==-1) return 0; // No first round detected.
$sql= <<<EOD
SELECT
count(*) as cnt,
concat(tipps.score1,':',tipps.score2) as game_result
FROM
tipps,games,rounds
WHERE
tipps.user_id=$user_id
AND
tipps.game_id = games.id
AND
games.round_id = rounds.id
AND
joker = true
AND
rounds.id >= $firstRoundId
AND
rounds.id <= $round_id
GROUP BY 2
ORDER BY 1 DESC
;
EOD;
$result = DB::select($sql);
$joker_usage_array=array();
foreach ($result as $line) {
$key = $line->game_result;
$value = $line->cnt;
$joker_usage_array[$key]=$value;
}
return $joker_usage_array;
}
// Creates string from array of countings of all joker usages
public static function getJokerUsageString($user_id, $round_id) {
$joker_usage_array=Tipp::getJokerUsageArray($user_id,$round_id);
//Log::info("RoundId: ".$round_id.", Joker usage array size:".sizeof($joker_usage_array));
$str_result="";
foreach ($joker_usage_array as $key => $value) {
if (strlen($str_result)>0) {
$str_result=$str_result.", ";
}
$str_result=$str_result.$value."x".$key;
}
return $str_result;
}
}

View file

@ -0,0 +1,340 @@
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable; // already implements CanResetPassword
use App\Season;
use App\Payment;
use App\Round;
use App\Game;
use Carbon;
use Log;
use DB;
use App\MyClasses\TimeLogger;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'firstname', 'lastname', 'email', 'password', 'gets_reminders', 'iban', 'bankname' , 'blz', 'kontonr', 'mobile'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
// Only the current season.
public static function is_season_paid($user_id,$seasonId=-1) {
$season=Season::getCurrent();
if ($seasonId!=-1) { $season=Season::where('id','=',$seasonId)->first();}
$retval="Ja";
if (User::payment_date($user_id, $season->id)==null) { $retval="Nein"; }
return $retval;
}
public static function payment_date($user_id,$season_id) {
$season = Season::getCurrent();
if ($season) {
$payment = Payment::where([
['user_id', '=', $user_id],
['season_id', '=', $season->id]
])->first();
if ($payment) {
if ($payment->paid_date) {
return $payment->paid_date;
}
} else {
$payment= Payment::create([
'user_id' => $user_id,
'season_id'=> $season->id,
'paid_date'=> null
]);
$payment->save();
}
}
return null;
}
// Aufgerechnete Summe. wird $maxround_id mit übergeben, dann wird nur
// bis zur entsprechenden Runde aufsummiert. Das setzt voraus, dass die
// Runden in Reihenfolge eingegeben wurden...
public static function getTotalScore($user_id,$maxround_id=1000000) {
$season = Season::getCurrent();
$rounds = Round::where('season_id','=',$season->id)->get();
$totalScore=0;
foreach($rounds as $round) {
if ($round->id <= $maxround_id) {
$totalScore += User::getRoundScore($user_id, $round->id);
}
}
return $totalScore;
}
public static function getRoundScore($user_id, $round_id) {
$games = Game::where('round_id','=',$round_id)->get();
$totalScore=0;
foreach ($games as $game) {
$tipp = Tipp::getTipp($user_id,$game->id);
$score = Tipp::getScore($tipp->id);
$totalScore+=$score;
}
return $totalScore;
}
// This totally does not belong here. But i am too afraid to put it into
// a separate php file that gets smashed by autoregenerate.
public static function toGermanDate($engDate)
{
$values = explode("-", $engDate);
$year = $values[0];
$month = $values[1];
$day = explode(" ", $values[2])[0];
$timeval = explode(" ", $engDate)[1];
$hour = explode(":", $timeval)[0];
$minute = explode(":", $timeval)[1];
return $day.".".$month.".".$year." ".$hour.":".$minute;
}
public static function toDBDate($deDate)
{
if (!$deDate) return "";
$values = explode(" ", $deDate);
$year = explode(".",$values[0])[2];
$month = explode(".",$values[0])[1];
$day = explode(".", $values[0])[0];
Log::info("values[0]=".$values[0]." day=".$day."count=". count($values));
$hour="00";
$minute="00";
if (count($values)>1) {
$hour = explode(":", $values[1])[0];
$minute = explode(":", $values[1])[1];
}
$dbDate=$year . "-" . $month . "-" . $day . " " . $hour . ":" . $minute . ":00";
//Log::info("deDate=".$deDate." converted to:".$dbDate);
return $dbDate;
}
// TODO: implement hasMissingTipps($user_array)
// OPTIMIZED VERSION FOR hasMissingTipp
public static function getMissingTippsAndJokers($users) {
$round = Round::getFirstTippableRound();
if (!$round) {
Log::info("User::getMissingTippsandJokers(users) => no tippable round exists");
$result=array();
$result["MISSING_TIPP"]=array();
$result["MISSING_JOKER"]=array();
return $result;
}
Log::info("User::getMissingTippsandJokers(users) => first tippable round= [".$round->id."] ".$round->name);
$tippClock=new TimeLogger("User::getMissingTippsAndJokers()");
Log::info($tippClock->getStartMessage());
// expecting collection of user db objects like: $users = DB::table('users')->where('deleted',null)->orderBy('lastname')->get();
$usersWithoutJoker=array();
foreach($users as $key => $user) {
//array_push($usersWithoutJoker,$user->id);
$usersWithoutJoker[$user->id]="";
}
$games = Game::where('round_id','=',$round->id)->get();
$gameIds=array();
foreach ($games as $key => $game) { // Vorsicht: $key ist nur der Array index, nicht die game id
array_push($gameIds,$game->id);
Log::info("GAME_ID:".$game->id);
}
$tipps = Tipp::whereIn('game_id', $gameIds)->get();
Log::info("Fetched advanced tipps, checking now for missing tipps and jokers");
$usersWithoutTipps=array();
foreach($tipps as $tipp) {
if ($tipp->score1 == -1 || $tipp->score2 == -1) {
$usersWithoutTipps[$tipp->user_id]="no_tipp";
//Log::info("UserId ".$tipp->user_id." is missing a tipp!");
}
if ($tipp->joker == true) {
Log::info("Removing from usersWithoutJokerlist: ".$tipp->user_id);
unset($usersWithoutJoker[$tipp->user_id]);
}
}
foreach ($usersWithoutJoker as $key => $id) {
Log::info("Jokerless:".$key);
}
$result=array();
$result["MISSING_TIPP"]=$usersWithoutTipps;
$result["MISSING_JOKER"]=$usersWithoutJoker;
foreach(array_keys($result) as $key => $value) {
Log::info("Main key: ".$key.", value=".$value);
}
$mtipps=$result["MISSING_TIPP"];
foreach($mtipps as $key => $value) {
Log::info("MTipp: ".$key." => ".$value);
}
return $result;
}
public static function hasMissingTipp($user_id) {
$round = Round::getFirstTippableRound();
if (!$round) return false;
//$a=new TimeLogger("User::hasMissingTipp()");
//Log::info($a->getStartMessage());
$round_id = $round->id;
$games = Game::where('round_id','=',$round_id)->get();
foreach ($games as $game) {
$tipp = Tipp::where([['game_id','=',$game->id],['user_id','=',$user_id]])->first();
if(!$tipp) {
Log::info("Tipp doesnt exist: game_id=".$game->id.", user_id=".$user_id);
//Log::info($a->getEndMessage());
return 1;
}
if ($tipp->score1 == -1 || $tipp->score2 == -1) {
//Log::info($a->getEndMessage());
return 1;
}
}
//Log::info($a->getEndMessage());
return 0;
}
public static function hasMissingJoker($user_id) {
$round=Round::getFirstTippableRound();
if (!$round) return false;
$round_id = $round->id;
$games = Game::where('round_id','=',$round_id." user_id=".$user_id)->get();
$joker=0;
foreach ($games as $game) {
$tipp = Tipp::where([['game_id','=',$game->id],['user_id','=',$user_id]])->first();
if(!$tipp) {
Log::info("tipp is null! OMG! // Infos: user_id=".$user_id.", game_id=".$game->id.", round_id=".$round_id);
return true;
}
if ($tipp->joker == true) { $joker=1; }
//Log::info("!!! Joker for user_id ".$user_id.", round_id=".$round_id.", game_id=".$game->id." was found.");
}
if ($joker==1) {
return false;
}
//Log::info("!!! Joker is missing for user_id=".$user_id." round_id=".$round_id);
return true;
}
// aktiv = hat die Saison bezahlt.
public static function getActives($seasonId=-1) {
$season=Season::getCurrent();
if (!$season) return array();
if ($seasonId != -1) { $season = Season::where('id','=',$seasonId)->first(); }
$seasonId = $season->id;
$users = User::all();
$payments = Payment::where('season_id','=',$seasonId)->get();
$payref = array();
foreach($payments as $payment) {
if ($payment->paid_date) {
//Log::info("(".$payment->user_id.") PAID DATE: ".$payment->paid_date);
$payref[$payment->user_id] = 'ok';
}
}
$userlist=array();
foreach($users as $user) {
if (array_key_exists($user->id,$payref)) {
if($payref[$user->id]) {
array_push($userlist,$user);
}
}
}
return $userlist;
}
public static function getActivesSortedByName($seasonId=-1) {
$users = User::getActives($seasonId);
usort($users, array("App\User","cmpName"));
return $users;
}
public static function cmpName($user1, $user2) {
return ($user1['lastname']." ".$user1['firstname'] > $user2['lastname']." ".$user2['firstname']);
}
public static function isDeleted($user_id) {
$user=User::where('id','=',$user_id)->first();
if (!$user) return true;
if ($user->deleted) return true;
return false;
}
public static function softDelete($user_id) {
$user = User::where('id','=',$user_id)->first();
if ($user) { $user->deleted = Carbon\Carbon::now();}
$user->save();
$season = Season::getCurrent();
Payment::set_payment_date($user_id,$season->id,null);
}
public static function getNames() {
$users=User::all();
$usernames = array();
foreach($users as $user) {
$usernames[$user->id] = $user->name;
}
return $usernames;
}
}

View file

@ -0,0 +1,51 @@
#!/usr/bin/env php
<?php
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);

View file

@ -0,0 +1,55 @@
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
realpath(__DIR__.'/../')
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;

View file

@ -0,0 +1,17 @@
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Composer Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so we do not have to manually load any of
| our application's PHP classes. It just feels great to relax.
|
*/
require __DIR__.'/../vendor/autoload.php';

View file

@ -0,0 +1,2 @@
*
!.gitignore

View file

@ -0,0 +1,57 @@
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": [
"framework",
"laravel"
],
"license": "MIT",
"type": "project",
"require": {
"php": ">=5.6.4",
"laravel/framework": "^5.8.0",
"laravel/tinker": "~1.0",
"laravelcollective/html": "^5.4"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"mockery/mockery": "0.9.*",
"phpunit/phpunit": "~5.7"
},
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"post-root-package-install": [
"php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"php artisan key:generate"
],
"post-install-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postInstall",
"php artisan optimize"
],
"post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"php artisan optimize"
]
},
"config": {
"platform-check": false,
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": false,
"secure-http": false
}
}

Binary file not shown.

View file

@ -0,0 +1,237 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
*/
'name' => env('APP_NAME', 'Hoschis Tippspiel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services your application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => env('APP_DEBUG', true),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
/*'timezone' => 'UTC',*/
'timezone' => 'Europe/Berlin',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
//'locale' => 'en',
'locale' => 'de',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Logging Configuration
|--------------------------------------------------------------------------
|
| Here you may configure the log settings for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Settings: "single", "daily", "syslog", "errorlog"
|
*/
'log' => env('APP_LOG', 'daily'),
'log_level' => env('APP_LOG_LEVEL', 'debug'),
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
Laravel\Tinker\TinkerServiceProvider::class,
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
Collective\Html\HtmlServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Form' => Collective\Html\FormFacade::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Html' => Collective\Html\HtmlFacade::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
],
];

View file

@ -0,0 +1,102 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];

View file

@ -0,0 +1,58 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
| Supported: "pusher", "redis", "log", "null"
|
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
//
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];

View file

@ -0,0 +1,91 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
| Supported: "apc", "array", "database", "file", "memcached", "redis"
|
*/
'default' => env('CACHE_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing a RAM based store such as APC or Memcached, there might
| be other applications utilizing the same cache. So, we'll specify a
| value to get prefixed to all our keys so we can avoid collisions.
|
*/
'prefix' => 'laravel',
];

View file

@ -0,0 +1,120 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'pfosten'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'root'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => 'predis',
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
],
];

View file

@ -0,0 +1,68 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DRIVER', 'local'),
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => env('FILESYSTEM_CLOUD', 's3'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
| Supported Drivers: "local", "ftp", "s3", "rackspace"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_KEY'),
'secret' => env('AWS_SECRET'),
'region' => env('AWS_REGION'),
'bucket' => env('AWS_BUCKET'),
],
],
];

View file

@ -0,0 +1,94 @@
<?php
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 14,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => 'critical',
],
'papertrail' => [
'driver' => 'monolog',
'level' => 'debug',
'handler' => SyslogUdpHandler::class,
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
],
],
'stderr' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
],
'syslog' => [
'driver' => 'syslog',
'level' => 'debug',
],
'errorlog' => [
'driver' => 'errorlog',
'level' => 'debug',
],
],
];

View file

@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
| "sparkpost", "log", "array"
|
*/
'driver' => env('MAIL_DRIVER', 'smtp'),
//'driver' => env('MAIL_DRIVER', 'log'),
/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
|
*/
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
*/
'port' => env('MAIL_PORT', 587),
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'info@hoschis-tippspiel.de'),
'name' => env('MAIL_FROM_NAME', 'Hoschis Tippspiel'),
],
/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/
'sendmail' => '/usr/sbin/sendmail -bs',
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];

View file

@ -0,0 +1,85 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Driver
|--------------------------------------------------------------------------
|
| Laravel's queue API supports an assortment of back-ends via a single
| API, giving you convenient access to each back-end using the same
| syntax for each one. Here you may set the default queue driver.
|
| Supported: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'default' => env('QUEUE_DRIVER', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
],
'sqs' => [
'driver' => 'sqs',
'key' => 'your-public-key',
'secret' => 'your-secret-key',
'prefix' => 'https://sqs.us-east-1.amazonaws.com/your-account-id',
'queue' => 'your-queue-name',
'region' => 'us-east-1',
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'retry_after' => 90,
],
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
];

View file

@ -0,0 +1,38 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, SparkPost and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => 'us-east-1',
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => App\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
];

View file

@ -0,0 +1,179 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => 120,
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => null,
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using the "apc" or "memcached" session drivers, you may specify a
| cache store that should be used for these sessions. This value must
| correspond with one of the application's configured cache stores.
|
*/
'store' => null,
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => 'laravel_session',
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN', null),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE', false),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
];

View file

@ -0,0 +1,33 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => [
resource_path('views'),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => realpath(storage_path('framework/views')),
];

View file

@ -0,0 +1 @@
*.sqlite

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,24 @@
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
];
});

View file

@ -0,0 +1,46 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name',201);
$table->string('firstname', 100);
$table->string('lastname', 100);
$table->string('email',150)->unique();
$table->string('password',100);
$table->string('iban', 128);
$table->string('bankname', 64);
$table->string('blz', 20);
$table->string('kontonr', 64);
$table->timestamp('deleted')->nullable();
$table->boolean('admin')->default(false);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}

View file

@ -0,0 +1,32 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePasswordResetsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('password_resets', function (Blueprint $table) {
$table->string('email',150)->index();
$table->string('token',100);
$table->timestamp('created_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('password_resets');
}
}

View file

@ -0,0 +1,32 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSettingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('current_season_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('settings');
}
}

View file

@ -0,0 +1,36 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTippsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tipps', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->hasOne('App\User');
$table->integer('game_id')->hasOne('App\Game');
$table->integer('score1');
$table->integer('score2');
$table->boolean('joker')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tipps');
}
}

View file

@ -0,0 +1,34 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePaymentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('payments', function (Blueprint $table) {
$table->increments('id');
$table->integer('season_id');
$table->integer('user_id');
$table->dateTime('paid_date')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('payments');
}
}

View file

@ -0,0 +1,37 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateGamesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('games', function (Blueprint $table) {
$table->increments('id');
$table->integer('round_id');
$table->string('team1',100);
$table->string('team2',100);
$table->integer('score1')->default(-1);
$table->integer('score2')->default(-1);
$table->dateTime('kickoff');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('games');
}
}

View file

@ -0,0 +1,34 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRoundsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('rounds', function (Blueprint $table) {
$table->increments('id');
$table->string('name',64);
$table->integer('season_id');
$table->string('report',16000)->default('');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('rounds');
}
}

View file

@ -0,0 +1,34 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSeasonsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('seasons', function (Blueprint $table) {
$table->increments('id');
$table->string('name',100);
$table->integer('rounds')->default(36);
$table->boolean('active')->default(true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('seasons');
}
}

View file

@ -0,0 +1,38 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateQuotasTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::dropIfExists('quotas');
Schema::create('quotas', function (Blueprint $table) {
$table->increments('id');
$table->integer('season_id')->default(0);
$table->string('name',100);
$table->integer('order')->default(0);
$table->float('prc')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('quotas');
}
}

View file

@ -0,0 +1,42 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRoundmailsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::dropIfExists('roundmails');
Schema::create('roundmails', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->date('send_date');
$table->text('recipients',15000);
$table->string('topic',200);
$table->text('message',16000);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('roundmails');
}
}

View file

@ -0,0 +1,32 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddReminderfieldToUsers extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->boolean('gets_reminders')->default(true);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
//
});
}
}

View file

@ -0,0 +1,47 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLeaguesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('leagues', function (Blueprint $table) {
$table->increments('id');
$table->integer('season_id');
$table->integer('rank');
$table->integer('subrank');
$table->string('name');
$table->boolean('is_qualification');
$table->integer('start_round_id');
$table->integer('round_count')->default(18);
$table->timestamps();
});
Schema::create('leagues_members', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('league_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('leagues');
Schema::dropIfExists('leagues_members');
}
}

View file

@ -0,0 +1,35 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMatchesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('leagues_matches', function (Blueprint $table) {
$table->increments('id');
$table->integer('league_id');
$table->integer('round_id');
$table->integer('user1_id');
$table->integer('user2_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('leagues_matches');
}
}

View file

@ -0,0 +1,33 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateManualPayoutsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('manual_payouts', function (Blueprint $table) {
$table->increments('id');
$table->integer('season_id');
$table->integer('user_id');
$table->string('quota_name')->default("");
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('manual_payouts');
}
}

View file

@ -0,0 +1,30 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddMaxIdenticalJokertippsToSeasons extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('seasons', function (Blueprint $table) {
$table->integer('max_identical_jokertipps')->default(6);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}

View file

@ -0,0 +1,30 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddMobileFieldToUsers extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('mobile')->default('');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}

View file

@ -0,0 +1,33 @@
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddPlayoffPokalToSeason extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('seasons', function (Blueprint $table) {
$table->text('pokal_report',15000);
$table->text('playoff_report',15000);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('seasons', function (Blueprint $table) {
//
});
}
}

View file

@ -0,0 +1,16 @@
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
}
}

View file

@ -0,0 +1,33 @@
-- Liga Tausch user_id 74 <-> 81
-- Liga Tausch user_id 97 <-> 46
update leagues_members set user_id=1000 where league_id>28 and user_id=74;
update leagues_members set user_id=74 where league_id>28 and user_id=81;
update leagues_members set user_id=81 where league_id>28 and user_id=1000;
update leagues_members set user_id=1000 where league_id>28 and user_id=97;
update leagues_members set user_id=97 where league_id>28 and user_id=46;
update leagues_members set user_id=46 where league_id>28 and user_id=1000;
-- Match Tausch 74 <-> 81
-- Match Tausch 97 <-> 46
update leagues_matches set user1_id=1000 where league_id>28 and user1_id=74;
update leagues_matches set user1_id=74 where league_id>28 and user1_id=81;
update leagues_matches set user1_id=81 where league_id>28 and user1_id=1000;
update leagues_matches set user2_id=1000 where league_id>28 and user2_id=74;
update leagues_matches set user2_id=74 where league_id>28 and user2_id=81;
update leagues_matches set user2_id=81 where league_id>28 and user2_id=1000;
update leagues_matches set user1_id=1000 where league_id>28 and user1_id=97;
update leagues_matches set user1_id=97 where league_id>28 and user1_id=46;
update leagues_matches set user1_id=46 where league_id>28 and user1_id=1000;
update leagues_matches set user2_id=1000 where league_id>28 and user2_id=97;
update leagues_matches set user2_id=97 where league_id>28 and user2_id=46;
update leagues_matches set user2_id=46 where league_id>28 and user2_id=1000;

View file

@ -0,0 +1,57 @@
services:
app:
build:
args:
user: sammy
uid: 1000
context: ./
dockerfile: Dockerfile.dev
working_dir: /var/www/
environment:
- COMPOSER_MEMORY_LIMIT=-1
depends_on:
- db
volumes:
- ./:/var/www
networks:
- lahmi
db:
image: mysql:5.7
environment:
MYSQL_DATABASE: ${DB_DATABASE}
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
MYSQL_PASSWORD: ${DB_PASSWORD}
MYSQL_USER: ${DB_USERNAME}
SERVICE_TAGS: dev
SERVICE_NAME: mysql
volumes:
- dbdata_pfosten:/var/lib/mysql
- ./docker-compose/mysql/my.cnf:/etc/mysql/my.cnf
- ./docker-compose/mysql/init:/docker-entrypoint-initdb.d
ports:
- 3307:3306
networks:
- lahmi
nginx:
image: nginx:alpine
ports:
- 8005:80
depends_on:
- db
- app
volumes:
- ./:/var/www
- ./docker-compose/nginx:/etc/nginx/conf.d/
networks:
- lahmi
networks:
lahmi:
driver: bridge
volumes:
dbdata_pfosten:
driver: local

View file

@ -0,0 +1,7 @@
# create databases
CREATE DATABASE IF NOT EXISTS `local_laravel`;
# create local_developer user and grant rights
CREATE USER 'local_developer'@'db' IDENTIFIED BY 'secret';
GRANT ALL PRIVILEGES ON *.* TO 'local_developer'@'%';

View file

@ -0,0 +1,4 @@
[mysqld]
general_log = 1
general_log_file = /var/lib/mysql/general.log

View file

@ -0,0 +1,21 @@
server {
listen 80;
index index.php index.html;
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
root /var/www/public;
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass app:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
location / {
try_files $uri $uri/ /index.php?$query_string;
gzip_static on;
}
}

Some files were not shown because too many files have changed in this diff Show more