repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
vemcogroup/laravel-translation
https://github.com/vemcogroup/laravel-translation/blob/6bec99ffd1a5da6c1e53e3732203dd2c701b4aaa/src/Commands/AddTerms.php
src/Commands/AddTerms.php
<?php namespace Vemcogroup\Translation\Commands; use Exception; use Illuminate\Console\Command; use Vemcogroup\Translation\Translation; class AddTerms extends Command { protected $signature = 'translation:add-terms {--scan : Whether the job should scan before uploading} '; protected $description = 'Upload all terms to POEditor'; public function handle(): void { try { $this->info('⬆️ Preparing to upload terms'); if ($this->option('scan')) { $this->call('translation:scan'); } app(Translation::class)->addTerms(); $this->info('⬆️ Finished uploading all terms'); } catch (Exception $e) { $this->error($e->getMessage()); } } }
php
MIT
6bec99ffd1a5da6c1e53e3732203dd2c701b4aaa
2026-01-05T05:03:46.176465Z
false
vemcogroup/laravel-translation
https://github.com/vemcogroup/laravel-translation/blob/6bec99ffd1a5da6c1e53e3732203dd2c701b4aaa/src/Commands/Scan.php
src/Commands/Scan.php
<?php namespace Vemcogroup\Translation\Commands; use Exception; use Illuminate\Console\Command; use Vemcogroup\Translation\Translation; class Scan extends Command { protected $signature = 'translation:scan {--merge : Whether the job should overwrite or new translations keys}'; protected $description = 'Scan code base for translation variables'; public function handle(): void { try { $this->info('Preparing to scan code base'); $this->info('Finding all translation variables'); $this->info($this->option('merge') ? 'Merging keys' : 'Overwriting keys'); $variables = app(Translation::class)->scan($this->option('merge')); $this->info('Finished scanning code base, found: ' . $variables . ' variables'); } catch (Exception $e) { $this->error($e->getMessage()); } } }
php
MIT
6bec99ffd1a5da6c1e53e3732203dd2c701b4aaa
2026-01-05T05:03:46.176465Z
false
vemcogroup/laravel-translation
https://github.com/vemcogroup/laravel-translation/blob/6bec99ffd1a5da6c1e53e3732203dd2c701b4aaa/src/Commands/Upload.php
src/Commands/Upload.php
<?php namespace Vemcogroup\Translation\Commands; use Exception; use Illuminate\Console\Command; use Vemcogroup\Translation\Translation; class Upload extends Command { protected $signature = 'translation:upload {--scan : Whether the job should scan before uploading} {--translations=all : Upload translations for language sv,da,...} '; protected $description = 'Upload all translations to POEditor'; public function handle(): void { try { $this->info('⬆️ Preparing to upload translations'); if ($this->option('scan')) { $this->call('translation:scan'); } app(Translation::class)->syncTerms(); if ($this->hasOption('translations')) { $language = in_array($this->option('translations'), [null, 'all'], true) ? null : explode(',', $this->option('translations')); app(Translation::class)->syncTranslations($language); } $this->info('⬆️ Finished uploading all translations'); } catch (Exception $e) { $this->error($e->getMessage()); } } }
php
MIT
6bec99ffd1a5da6c1e53e3732203dd2c701b4aaa
2026-01-05T05:03:46.176465Z
false
vemcogroup/laravel-translation
https://github.com/vemcogroup/laravel-translation/blob/6bec99ffd1a5da6c1e53e3732203dd2c701b4aaa/src/Commands/Download.php
src/Commands/Download.php
<?php namespace Vemcogroup\Translation\Commands; use Exception; use Illuminate\Console\Command; use Vemcogroup\Translation\Translation; class Download extends Command { protected $signature = 'translation:download {--skip-trimming : Whether translation trimming should be skipped}'; protected $description = 'Download all languages from POEditor'; public function handle(): void { try { $this->info('⬇️ Preparing to download languages'); $languages = app(Translation::class)->download($this->option('skip-trimming')); $this->info('⬇️ Finished downloading languages: ' . $languages->implode(', ')); } catch (Exception $e) { $this->error($e->getMessage()); } } }
php
MIT
6bec99ffd1a5da6c1e53e3732203dd2c701b4aaa
2026-01-05T05:03:46.176465Z
false
vemcogroup/laravel-translation
https://github.com/vemcogroup/laravel-translation/blob/6bec99ffd1a5da6c1e53e3732203dd2c701b4aaa/src/Commands/CreateJs.php
src/Commands/CreateJs.php
<?php namespace Vemcogroup\Translation\Commands; use Exception; use Illuminate\Console\Command; use Vemcogroup\Translation\Translation; class CreateJs extends Command { protected $signature = 'translation:create-js {--download : Download language files before creating js}'; protected $description = 'Create js files based on json language files'; public function handle(): void { try { $this->info('Preparing create js files'); if ($this->option('download')) { $this->call('translation:download'); } $files = app(Translation::class)->createJs(); $this->info('Finished creating js files, created: ' . $files . ' files'); } catch (Exception $e) { $this->error($e->getMessage()); } } }
php
MIT
6bec99ffd1a5da6c1e53e3732203dd2c701b4aaa
2026-01-05T05:03:46.176465Z
false
vemcogroup/laravel-translation
https://github.com/vemcogroup/laravel-translation/blob/6bec99ffd1a5da6c1e53e3732203dd2c701b4aaa/config/translation.php
config/translation.php
<?php return [ /* |-------------------------------------------------------------------------- | Base Language |-------------------------------------------------------------------------- | | Here you may specify which of language is your base language. | The base language select will be created as json file when scanning. | It will also be the file it reads and uploads to POEditor. | */ 'base_language' => 'en', /* |-------------------------------------------------------------------------- | Functions |-------------------------------------------------------------------------- | | Here you define an array describing all the function names to scan files for. | */ 'functions' => ['__'], /* |-------------------------------------------------------------------------- | Excluded directories |-------------------------------------------------------------------------- | | Here you define which directories are excluded from scan. | */ 'excluded_directories' => ['vendor', 'storage', 'public', 'node_modules'], /* |-------------------------------------------------------------------------- | Output directory |-------------------------------------------------------------------------- | | Here you define which directory to write the created JSON files into. | */ 'output_directory' => public_path(env('TRANSLATION_OUTPUT_DIRECTORY', 'build/lang')), /* |-------------------------------------------------------------------------- | Extensions |-------------------------------------------------------------------------- | | Here you define an array describing all the file extensions to scan through. | */ 'extensions' => ['*.php', '*.vue'], /* |-------------------------------------------------------------------------- | API Key |-------------------------------------------------------------------------- | | Here you define your API Key for POEditor. | | More info: https://poeditor.com/account/api | */ 'api_key' => env('POEDITOR_API_KEY'), /* |-------------------------------------------------------------------------- | Project Id |-------------------------------------------------------------------------- | | Here you define the project Id to upload / download from. | */ 'project_id' => env('POEDITOR_PROJECT_ID'), ];
php
MIT
6bec99ffd1a5da6c1e53e3732203dd2c701b4aaa
2026-01-05T05:03:46.176465Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/src/HejServiceProvider.php
src/HejServiceProvider.php
<?php namespace RenokiCo\Hej; use Illuminate\Support\ServiceProvider; class HejServiceProvider extends ServiceProvider { /** * Boot the service provider. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/../database/migrations/2020_07_24_000000_create_socials_table.php' => database_path('migrations/2020_07_24_000000_create_socials_table.php'), ], 'migrations'); $this->publishes([ __DIR__.'/../config/hej.php' => config_path('hej.php'), ], 'config'); $this->mergeConfigFrom( __DIR__.'/../config/hej.php', 'hej' ); } /** * Register the service provider. * * @return void */ public function register() { // } }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/src/Social.php
src/Social.php
<?php namespace RenokiCo\Hej; use Illuminate\Database\Eloquent\Model; class Social extends Model { /** * {@inheritdoc} */ protected $guarded = []; /** * Get the model that uses this Social instance. * * @return mixed */ public function model() { return $this->morphTo(); } }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/src/Http/Controllers/SocialController.php
src/Http/Controllers/SocialController.php
<?php namespace RenokiCo\Hej\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\Session; use Illuminate\Support\Str; use Laravel\Socialite\Contracts\Factory as Socialite; use RenokiCo\Hej\Concerns\HandlesSocialRequests; class SocialController extends Controller { use HandlesSocialRequests; /** * The Socialite factory instance. * * @var \Laravel\Socialite\Contracts\Factory */ protected $socialite; /** * Initialize the controller. * * @param \Laravel\Socialite\Contracts\Factory $socialite * @return void */ public function __construct(Socialite $socialite) { $this->socialite = $socialite; if ($allowedProviders = config('hej.allowed_providers')) { static::$allowedSocialiteProviders = $allowedProviders; } } /** * Get the Socialite direct instance that will redirect * the user to the right provider OAuth page. * * @param \Illuminate\Http\Request $request * @param string $provider * @return mixed */ protected function getSocialiteRedirect(Request $request, string $provider) { return $this->socialite ->driver($provider) ->redirect(); } /** * Get the Socialite User instance that will be * given after the OAuth authorization passes. * * @param \Illuminate\Http\Request $request * @param string $provider * @return \Laravel\Socialite\AbstractUser */ protected function getSocialiteUser(Request $request, string $provider) { return $this->socialite ->driver($provider) ->user(); } /** * Get the model to login (or register). * * @param \Illuminate\Http\Request $request * @param string $provider * @return string */ public function getAuthenticatable(Request $request, string $provider) { return config('hej.default_authenticatable'); } /** * Get the key to store into session the authenticatable * primary key to be checked on returning from OAuth. * * @param \Illuminate\Http\Request $request * @param string $provider * @param \Illuminate\Database\Eloquent\Model|null $model * @return string */ public function getLinkSessionKey(Request $request, string $provider, $model): string { return $model ? "hej_{$provider}_{$model->getKey()}" : ''; } /** * Get the Authenticatable model data to fill on register. * When the user gets created, it will receive these parameters * in the `::create()` method. * * @param \Illuminate\Http\Request $request * @param string $provider * @param \Laravel\Socialite\AbstractUser $providerUser * @return array */ protected function getRegisterData(Request $request, string $provider, $providerUser): array { return [ 'name' => $providerUser->getName(), 'email' => $providerUser->getEmail(), 'password' => Hash::make(Str::random(64)), ]; } /** * Get the Social model data to fill on register or login. * * @param \Illuminate\Http\Request $request * @param string $provider * @param \Illuminate\Database\Eloquent\Model $model * @param \Laravel\Socialite\AbstractUser $providerUser * @return array */ protected function getSocialData(Request $request, string $provider, $model, $providerUser): array { return [ 'provider_nickname' => $providerUser->getNickname(), 'provider_name' => $providerUser->getName(), 'provider_email' => $providerUser->getEmail(), 'provider_avatar' => $providerUser->getAvatar(), ]; } /** * Handle the user login and redirection. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Http\RedirectResponse */ protected function authenticateModel($model) { Auth::login($model); Session::flash('social', 'Welcome back in your account!'); return $this->redirectToAfterAuthentication($model); } /** * Handle the callback when a provider gets rejected. * * @param \Illuminate\Http\Request $request * @param string $provider * @return \Illuminate\Http\RedirectResponse */ protected function providerRejected(Request $request, $provider) { $provider = ucfirst($provider); Session::flash('social', "The authentication with {$provider} failed!"); return $this->redirectToAfterProviderIsRejected($request, $provider); } /** * Handle the callback when the user's social account * E-Mail address is already used. * * @param \Illuminate\Http\Request $request * @param string $provider * @param \Laravel\Socialite\AbstractUser $providerUser * @return \Illuminate\Http\RedirectResponse */ protected function duplicateEmail(Request $request, $provider, $providerUser) { $provider = ucfirst($provider); Session::flash( 'social', "The E-Mail address associated with your {$provider} account is already used." ); return $this->redirectToAfterDuplicateEmail($request, $provider, $providerUser); } /** * Handle the callback when the user tries * to link a social account when it * already has one, with the same provider. * * @param \Illuminate\Http\Request $request * @param string $provider * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Http\RedirectResponse */ protected function providerAlreadyLinked(Request $request, $provider, $model) { $provider = ucfirst($provider); Session::flash( 'social', "You already have a {$provider} account linked." ); return $this->redirectToAfterProviderIsAlreadyLinked($request, $provider, $model); } /** * Handle the callback when the user tries * to link a social account that is already existent. * * @param \Illuminate\Http\Request $request * @param string $provider * @param \Illuminate\Database\Eloquent\Model $model * @param \Laravel\Socialite\AbstractUser $providerUser * @return \Illuminate\Http\RedirectResponse */ protected function providerAlreadyLinkedByAnotherAuthenticatable(Request $request, $provider, $model, $providerUser) { $provider = ucfirst($provider); Session::flash( 'social', "Your {$provider} account is already linked to another account." ); return $this->redirectToAfterProviderAlreadyLinkedByAnotherAuthenticatable( $request, $provider, $model, $providerUser ); } /** * Handle the user redirect after linking. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Model $model * @param \Illuminate\Database\Eloquent\Model $social * @param \Laravel\Socialite\AbstractUser $providerUser * @return \Illuminate\Http\RedirectResponse */ protected function redirectAfterLink(Request $request, $model, $social, $providerUser) { $provider = ucfirst($social->provider); Session::flash('social', "The {$provider} account has been linked to your account."); return $this->redirectToAfterLink($request, $model, $social, $providerUser); } /** * Handle the user redirect after unlinking. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Model $model * @param string $provider * @return \Illuminate\Http\RedirectResponse */ protected function redirectAfterUnlink(Request $request, $model, string $provider) { $provider = ucfirst($provider); Session::flash('social', "The {$provider} account has been unlinked."); return $this->redirectToAfterUnlink($request, $model, $provider); } /** * Handle the callback after the registration process. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Model $model * @param \Illuminate\Database\Eloquent\Model $social * @param \Laravel\Socialite\AbstractUser $providerUser * @return void */ protected function registered(Request $request, $model, $social, $providerUser) { // } /** * Handle the callback after the login process. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Model $model * @param \Illuminate\Database\Eloquent\Model $social * @param \Laravel\Socialite\AbstractUser $providerUser * @return void */ protected function authenticated(Request $request, $model, $social, $providerUser) { // } /** * Handle the callback after the linking process. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Model $model * @param \Illuminate\Database\Eloquent\Model $social * @param \Laravel\Socialite\AbstractUser $providerUser * @return void */ protected function linked(Request $request, $model, $social, $providerUser) { // } /** * Handle the callback after the unlink process. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Model $model * @param string $provider * @return void */ protected function unlinked(Request $request, $model, string $provider) { // } /** * Specify the redirection route after successful authentication. * * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Http\RedirectResponse */ protected function redirectToAfterAuthentication($model) { return Redirect::route(config('hej.redirects.authenticated', 'home')); } /** * Specify the redirection route to let the users know * the authentication using the selected provider was rejected. * * @param \Illuminate\Http\Request $request * @param string $provider * @return \Illuminate\Http\RedirectResponse */ protected function redirectToAfterProviderIsRejected(Request $request, $provider) { return Redirect::route(config('hej.redirects.provider_rejected', 'home')); } /** * Specify the redirection route to let the users know * the E-Mail address used with this social account is * already existent as another account. This is most often * occuring during registrations with Social accounts. * * @param \Illuminate\Http\Request $request * @param string $provider * @param \Laravel\Socialite\AbstractUser $providerUser * @return \Illuminate\Http\RedirectResponse */ protected function redirectToAfterDuplicateEmail(Request $request, $provider, $providerUser) { return Redirect::route(config('hej.redirects.duplicate_email', 'home')); } /** * Specify the redirection route to let the users know * the social account is already associated with their account. * * @param \Illuminate\Http\Request $request * @param string $provider * @param \Illuminate\Database\Eloquent\Model $model * @return \Illuminate\Http\RedirectResponse */ protected function redirectToAfterProviderIsAlreadyLinked(Request $request, $provider, $model) { return Redirect::route(config('hej.redirects.provider_already_linked', 'home')); } /** * Specify the redirection route to let the users know * the social account is associated with another account. * * @param \Illuminate\Http\Request $request * @param string $provider * @param \Illuminate\Database\Eloquent\Model $model * @param \Laravel\Socialite\AbstractUser $providerUser * @return \Illuminate\Http\RedirectResponse */ protected function redirectToAfterProviderAlreadyLinkedByAnotherAuthenticatable( Request $request, $provider, $model, $providerUser ) { return Redirect::route(config('hej.redirects.provider_linked_to_another', 'home')); } /** * Specify the redirection route to let the users know * they linked the social account. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Model $model * @param \Illuminate\Database\Eloquent\Model $social * @param \Laravel\Socialite\AbstractUser $providerUser * @return \Illuminate\Http\RedirectResponse */ protected function redirectToAfterLink(Request $request, $model, $social, $providerUser) { return Redirect::route(config('hej.redirects.link', 'home')); } /** * Specify the redirection route to let the users * they have unlinked the social account. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Database\Eloquent\Model $model * @param string $provider * @return \Illuminate\Http\RedirectResponse */ protected function redirectToAfterUnlink(Request $request, $model, string $provider) { return Redirect::route(config('hej.redirects.unlink', 'home')); } }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/src/Contracts/Sociable.php
src/Contracts/Sociable.php
<?php namespace RenokiCo\Hej\Contracts; interface Sociable { // }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/src/Concerns/HasSocialAccounts.php
src/Concerns/HasSocialAccounts.php
<?php namespace RenokiCo\Hej\Concerns; trait HasSocialAccounts { /** * Get the social accounts for this model. * * @return mixed */ public function socials() { return $this->morphMany(config('hej.models.social'), 'model'); } /** * Check if the authenticatable instance * has a Social account. * * @param string $provider * @return bool */ public function hasSocial(string $provider): bool { return $this->socials() ->whereProvider($provider) ->exists(); } /** * Get the social account for a specific provider. * * @param string $provider * @return \Illuminate\Database\Eloquent\Model|null */ public function getSocial(string $provider) { return $this->socials() ->whereProvider($provider) ->first(); } }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/src/Concerns/HandlesSocialRequests.php
src/Concerns/HandlesSocialRequests.php
<?php namespace RenokiCo\Hej\Concerns; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; use RenokiCo\Hej\Social; trait HandlesSocialRequests { /** * Whitelist social providers to be used. * * @var array */ protected static $allowedSocialiteProviders = [ // ]; /** * Redirect the user to the OAuth portal. * * @param \Illuminate\Http\Request $request * @param string $provider * @return \Illuminate\Http\RedirectResponse */ public function redirect(Request $request, string $provider) { if ($this->rejectProvider($provider)) { return $this->providerRejected($request, $provider); } return $this->getSocialiteRedirect($request, $provider); } /** * Redirect to link a social account * for the current authenticated user. * * @param \Illuminate\Http\Request $request * @param string $provider * @return \Illuminate\Http\RedirectResponse */ public function link(Request $request, string $provider) { if ($this->rejectProvider($provider)) { return $this->providerRejected($request, $provider); } $model = $request->user(); if ($model->hasSocial($provider)) { return $this->providerAlreadyLinked( $request, $provider, $model ); } $sessionKey = $this->getLinkSessionKey($request, $provider, $model); Session::put($sessionKey, $model->getKey()); return $this->getSocialiteRedirect($request, $provider); } /** * Try to unlink a social account * for the current authenticated user. * * @param \Illuminate\Http\Request $request * @param string $provider * @return \Illuminate\Http\RedirectResponse */ public function unlink(Request $request, string $provider) { if ($this->rejectProvider($provider)) { return $this->providerRejected($request, $provider); } $model = $request->user(); if ($social = $model->getSocial($provider)) { $social->delete(); } $this->unlinked($request, $model, $provider); return $this->redirectAfterUnlink($request, $model, $provider); } /** * Process the user callback. * * @param \Illuminate\Http\Request $request * @param string $provider * @return \Illuminate\Http\RedirectResponse */ public function callback(Request $request, string $provider) { if ($this->rejectProvider($provider)) { return $this->providerRejected($request, $provider); } $providerUser = $this->getSocialiteUser($request, $provider); // If the user tried to link the account, handle different logic. $sessionKey = $this->getLinkSessionKey($request, $provider, $request->user()); if ($authenticatableKey = Session::pull($sessionKey)) { return $this->linkCallback($request, $provider, $authenticatableKey, $providerUser); } // If the Social is attached to any authenticatable model, // then jump off and login. if ($model = $this->getModelBySocialId($request, $provider, $providerUser->getId())) { $social = $this->updateSocialInstance($request, $provider, $model, $providerUser); $this->authenticated( $request, $model, $social, $providerUser ); return $this->authenticateModel($model); } // Otherwise, create a new Authenticatable model // and attach a Social instance to it. $authenticatable = $this->getAuthenticatable($request, $provider); if ($this->emailAlreadyExists($provider, $authenticatable, $providerUser)) { return $this->duplicateEmail($request, $provider, $providerUser); } $model = $authenticatable::create( $this->getRegisterData( $request, $provider, $providerUser ) ); $social = $model->socials()->create([ 'provider' => $provider, 'provider_id' => $providerUser->getId(), ]); $social = $this->updateSocialInstance($request, $social, $model, $providerUser); $this->registered($request, $model, $social, $providerUser); return $this->authenticateModel($model); } /** * Handle the link callback to attach to an authenticatable ID. * * @param \Illuminate\Http\Request $request * @param string $provider * @param string $authenticatableId * @param \Laravel\Socialite\AbstractUser $providerUser * @return \Illuminate\Http\RedirectResponse */ protected function linkCallback(Request $request, string $provider, string $authenticatableId, $providerUser) { $authenticatableModel = $this->getAuthenticatable($request, $provider); $model = $authenticatableModel::find($authenticatableId); // Check if user has already a Social account with the provider. if ($model->hasSocial($provider)) { return $this->providerAlreadyLinked( $request, $provider, $model ); } // Make sure that there are not two same authenticatables // that are linked to same social account. if ($this->getSocialById($request, $provider, $providerUser->getId())) { return $this->providerAlreadyLinkedByAnotherAuthenticatable( $request, $provider, $model, $providerUser ); } $social = $model->socials()->create([ 'provider' => $provider, 'provider_id' => $providerUser->getId(), ]); $social = $this->updateSocialInstance( $request, $social, $model, $providerUser ); $this->linked($request, $model, $social, $providerUser); return $this->redirectAfterLink( $request, $model, $social, $providerUser ); } /** * Get the user by using a social provider's ID. * * @param \Illuminate\Http\Request $request * @param string $provider * @param mixed $id * @return null|\Illuminate\Eloquent\Database\Model */ protected function getModelBySocialId(Request $request, string $provider, $id) { $social = $this->getSocialById($request, $provider, $id); return $social ? $social->model : null; } /** * Get a Social instance by Social and ID. * * @param \Illuminate\Http\Request $request * @param string $provider * @param mixed $id * @return \Illuminate\Database\Eloquent\Model|null */ protected function getSocialById(Request $request, string $provider, $id) { $socialModel = config('hej.models.social'); return $socialModel::whereProvider($provider) ->whereProviderId($id) ->whereModelType($this->getAuthenticatable($request, $provider)) ->first(); } /** * Check if the E-Mail address already exists. * * @param string $provider * @param \Illuminate\Database\Eloquent\Model $model * @param \Laravel\Socialite\AbstractUser $providerUser * @return bool */ protected function emailAlreadyExists(string $provider, $model, $providerUser): bool { if (! $model = $model::whereEmail($providerUser->getEmail())->first()) { return false; } return ! $model->socials() ->whereProvider($provider) ->whereProviderId($providerUser->getId()) ->exists(); } /** * Update a social account using a Socialite * authentication instance. * * @param \Illuminate\Http\Request $request * @param string|\Illuminate\Database\Eloquent\Model $provider * @param \Illuminate\Database\Eloquent\Model $model * @param \Laravel\Socialite\AbstractUser $providerUser * @return \Illuminate\Database\Eloquent\Model */ protected function updateSocialInstance(Request $request, $provider, $model, $providerUser) { $social = $provider instanceof Social ? $provider : $this->getSocialById($request, $provider, $providerUser->getId()); if (! $social) { return false; } $social->update( $this->getSocialData( $request, $provider, $model, $providerUser ) ); return $social; } /** * Wether the provider is rejected by the current * whitelist status. * * @param string $provider * @return bool */ protected function rejectProvider(string $provider): bool { if (static::$allowedSocialiteProviders === ['*']) { return true; } return ! in_array($provider, static::$allowedSocialiteProviders); } }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/tests/TestCase.php
tests/TestCase.php
<?php namespace RenokiCo\Hej\Test; use Laravel\Socialite\Contracts\Factory as Socialite; use Orchestra\Testbench\BrowserKit\TestCase as Orchestra; abstract class TestCase extends Orchestra { /** * {@inheritdoc} */ protected function setUp(): void { parent::setUp(); $this->resetDatabase(); $this->loadLaravelMigrations(['--database' => 'sqlite']); $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); $this->withFactories(__DIR__.'/database/factories'); } /** * {@inheritdoc} */ protected function getPackageProviders($app) { return [ \Laravel\Socialite\SocialiteServiceProvider::class, \RenokiCo\Hej\HejServiceProvider::class, TestServiceProvider::class, ]; } /** * {@inheritdoc} */ public function getEnvironmentSetUp($app) { $app['config']->set('database.default', 'sqlite'); $app['config']->set('database.connections.sqlite', [ 'driver' => 'sqlite', 'database' => __DIR__.'/database.sqlite', 'prefix' => '', ]); $app['config']->set('auth.providers.users.model', Models\User::class); $app['config']->set('app.key', 'wslxrEFGWY6GfGhvN9L3wH3KSRJQQpBD'); $app['config']->set('hej.default_authenticatable', Models\User::class); $app['config']->set('services.github', [ 'client_id' => 'client_id', 'client_secret' => 'client_secret', 'redirect' => 'redirect', ]); } /** * Reset the database. * * @return void */ protected function resetDatabase() { file_put_contents(__DIR__.'/database.sqlite', null); } /** * Mock the Socialite Factory with a specific provider. * * @param string $provider * @return void */ public function mockSocialiteFacade(string $provider) { $socialiteUser = $this->createMock(\Laravel\Socialite\Two\User::class); $methodCallers = [ 'getId' => 1234, 'getNickname' => 'rennokki', 'getName' => 'rennokki', 'getEmail' => 'test@test.com', 'getAvatar' => 'https://avatars2.githubusercontent.com/u/21983456?v=4', ]; foreach ($methodCallers as $method => $return) { $socialiteUser->expects($this->any()) ->method($method) ->willReturn($return); } $socialiteUser->expects($this->any()) ->method('getRaw') ->willReturn([ 'login' => 'rennokki', 'id' => 1234, 'avatar_url' => 'https://avatars2.githubusercontent.com/u/21983456?v=4', 'url' => 'https://api.github.com/users/rennokki', 'email' => 'test@test.com', 'name' => 'rennokki', ]); $socialiteUser->token = 'token_123'; $socialiteUser->refreshToken = null; $socialiteUser->expiresIn = null; $provider = $this->createMock($provider); $provider->expects($this->any()) ->method('user') ->willReturn($socialiteUser); $stub = $this->createMock(Socialite::class); $stub->expects($this->any()) ->method('driver') ->willReturn($provider); $this->app->instance(Socialite::class, $stub); } }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/tests/TestServiceProvider.php
tests/TestServiceProvider.php
<?php namespace RenokiCo\Hej\Test; use Illuminate\Support\ServiceProvider; class TestServiceProvider extends ServiceProvider { /** * Boot the service provider. * * @return void */ public function boot() { $this->loadRoutesFrom(__DIR__.'/routes/web.php'); } /** * Register the service provider. * * @return void */ public function register() { // } }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/tests/ProviderTest.php
tests/ProviderTest.php
<?php namespace RenokiCo\Hej\Test; use RenokiCo\Hej\Test\Models\User; class ProviderTest extends TestCase { public function test_redirect_should_redirect_to_provider_website() { $this->call('GET', route('redirect', ['provider' => 'github'])) ->assertStatus(302); } public function test_should_not_redirect_or_callback_for_unwhitelisted_providers() { $this->call('GET', route('redirect', ['provider' => 'facebook'])) ->assertRedirectedToRoute('home'); $this->call('GET', route('callback', ['provider' => 'facebook'])) ->assertRedirectedToRoute('home'); $this->call('GET', route('unlink', ['provider' => 'facebook'])) ->assertRedirectedToRoute('home'); } public function test_register_if_not_registered() { $this->mockSocialiteFacade( \Laravel\Socialite\Two\GithubProvider::class ); $this->call('GET', route('callback', ['provider' => 'github'])) ->assertStatus(302); $this->assertNotNull( $user = User::whereEmail('test@test.com')->first() ); $this->assertCount(1, $user->socials()->get()); $social = $user->socials()->first(); $expected = [ 'id' => 1, 'model_type' => "RenokiCo\Hej\Test\Models\User", 'model_id' => '1', 'provider' => 'github', 'provider_id' => '1234', 'provider_nickname' => 'rennokki', 'provider_name' => 'rennokki', 'provider_email' => 'test@test.com', 'provider_avatar' => 'https://avatars2.githubusercontent.com/u/21983456?v=4', ]; $existingData = $social->setHidden([])->toArray(); foreach ($expected as $key => $value) { $this->assertEquals( $existingData[$key], $value ); } } public function test_login_if_already_registered() { $this->mockSocialiteFacade( \Laravel\Socialite\Two\GithubProvider::class ); $this->call('GET', route('callback', ['provider' => 'github'])) ->assertStatus(302); $this->call('GET', route('callback', ['provider' => 'github'])) ->assertStatus(302); $this->assertNotNull( $user = User::whereEmail('test@test.com')->first() ); $this->assertCount(1, $user->socials()->get()); $social = $user->socials()->first(); $expected = [ 'id' => 1, 'model_type' => "RenokiCo\Hej\Test\Models\User", 'model_id' => '1', 'provider' => 'github', 'provider_id' => '1234', 'provider_nickname' => 'rennokki', 'provider_name' => 'rennokki', 'provider_email' => 'test@test.com', 'provider_avatar' => 'https://avatars2.githubusercontent.com/u/21983456?v=4', ]; $existingData = $social->setHidden([])->toArray(); foreach ($expected as $key => $value) { $this->assertEquals( $existingData[$key], $value ); } } public function test_register_with_existent_email() { $this->mockSocialiteFacade( \Laravel\Socialite\Two\GithubProvider::class ); $socialModel = config('hej.models.social'); $user = factory(User::class)->create(['email' => 'test@test.com']); $this->assertCount(0, $user->socials()->get()); $this->call('GET', route('callback', ['provider' => 'github'])) ->assertRedirectedToRoute('home'); $this->assertCount(0, $user->socials()->get()); $this->assertEquals(0, $socialModel::count()); } public function test_link_unused_social_account() { $user = factory(User::class)->create(['email' => 'test@test.com']); $this->actingAs($user) ->call('GET', route('link', ['provider' => 'github'])) ->assertStatus(302); $this->assertEquals(1, session('hej_github_1')); $this->mockSocialiteFacade( \Laravel\Socialite\Two\GithubProvider::class ); $this->assertCount( 0, $user->socials()->get() ); $this->call('GET', route('callback', ['provider' => 'github'])) ->assertStatus(302); $this->assertNull(session('hej_github_1')); $this->assertCount(1, $user->socials()->get()); $this->assertCount(1, User::all()); $social = $user->socials()->first(); $expected = [ 'id' => 1, 'model_type' => "RenokiCo\Hej\Test\Models\User", 'model_id' => '1', 'provider' => 'github', 'provider_id' => '1234', 'provider_nickname' => 'rennokki', 'provider_name' => 'rennokki', 'provider_email' => 'test@test.com', 'provider_avatar' => 'https://avatars2.githubusercontent.com/u/21983456?v=4', ]; $existingData = $social->setHidden([])->toArray(); foreach ($expected as $key => $value) { $this->assertEquals( $existingData[$key], $value ); } } public function test_link_already_linked_social_account() { $user = factory(User::class)->create(['email' => 'test@test.com']); $user2 = factory(User::class)->create(['email' => 'test2@test.com']); $this->actingAs($user) ->call('GET', route('link', ['provider' => 'github'])) ->assertStatus(302); $this->actingAs($user2) ->call('GET', route('link', ['provider' => 'github'])) ->assertStatus(302); $this->mockSocialiteFacade( \Laravel\Socialite\Two\GithubProvider::class ); $this->actingAs($user) ->call('GET', route('callback', ['provider' => 'github'])) ->assertStatus(302); $response = $this->actingAs($user2) ->call('GET', route('callback', ['provider' => 'github'])) ->assertRedirectedToRoute('home'); $session = $response->getSession(); $this->assertEquals( 'Your Github account is already linked to another account.', $session->get('social') ); } public function test_unlink_account() { $user = factory(User::class)->create(['email' => 'test@test.com']); $this->actingAs($user) ->call('GET', route('link', ['provider' => 'github'])) ->assertStatus(302); $this->mockSocialiteFacade( \Laravel\Socialite\Two\GithubProvider::class ); $this->actingAs($user) ->call('GET', route('callback', ['provider' => 'github'])) ->assertStatus(302); $this->assertCount(1, $user->socials()->get()); $this->actingAs($user) ->call('GET', route('unlink', ['provider' => 'github'])) ->assertStatus(302); $this->assertCount(0, $user->socials()->get()); } public function test_link_already_linked_social_account_by_same_user() { $user = factory(User::class)->create(['email' => 'test@test.com']); $this->actingAs($user) ->call('GET', route('link', ['provider' => 'github'])) ->assertStatus(302); $this->assertEquals(1, session('hej_github_1')); $this->mockSocialiteFacade( \Laravel\Socialite\Two\GithubProvider::class ); $this->assertCount( 0, $user->socials()->get() ); $user->socials()->create([ 'provider' => 'github', 'provider_id' => '123', ]); // Calling it again wont link it. $response = $this->call('GET', route('callback', ['provider' => 'github'])) ->assertRedirectedToRoute('home'); $session = $response->getSession(); $this->assertEquals( 'You already have a Github account linked.', $session->get('social') ); } }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/tests/Controllers/SocialController.php
tests/Controllers/SocialController.php
<?php namespace RenokiCo\Hej\Test\Controllers; use Illuminate\Http\Request; use RenokiCo\Hej\Http\Controllers\SocialController as BaseSocialController; class SocialController extends BaseSocialController { /** * Whitelist social providers to be used. * * @var array */ protected static $allowedSocialiteProviders = [ 'github', ]; /** * Get the Authenticatable model data to fill on register. * When the user gets created, it will receive these parameters * in the `::create()` method. * * @param \Illuminate\Http\Request $request * @param string $provider * @param \Laravel\Socialite\AbstractUser $providerUser * @return array */ protected function getAuthenticatableFillableDataOnRegister(Request $request, string $provider, $providerUser): array { return [ 'name' => $providerUser->getName(), 'email' => $providerUser->getEmail(), 'email_verified_at' => now(), 'password' => mt_rand(1, 3), ]; } /** * Get the Socialite direct instance that will redirect * the user to the right provider OAuth page. * * @param \Illuminate\Http\Request $request * @param string $provider * @return mixed */ protected function getSocialiteRedirect(Request $request, string $provider) { return $this->socialite ->driver($provider) ->scopes(['admin:repo_hook', 'gist']) ->redirect(); } /** * Get the Socialite User instance that will be * given after the OAuth authorization passes. * * @param \Illuminate\Http\Request $request * @param string $provider * @return mixed */ protected function getSocialiteUser(Request $request, string $provider) { return $this->socialite ->driver($provider) ->user(); } }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/tests/routes/web.php
tests/routes/web.php
<?php use Illuminate\Support\Facades\Route; Route::get('/home', function () { return 'Home'; })->name('home'); Route::get('/register', function () { return 'Register'; })->name('register'); Route::group(['middleware' => [\Illuminate\Session\Middleware\StartSession::class]], function () { Route::group(['middleware' => [\RenokiCo\Hej\Test\Middleware\Authenticate::class]], function () { Route::get('/{provider}/link', 'RenokiCo\Hej\Test\Controllers\SocialController@link') ->name('link'); Route::get('/{provider}/unlink', 'RenokiCo\Hej\Test\Controllers\SocialController@unlink') ->name('unlink'); }); Route::get('/{provider}/redirect', 'RenokiCo\Hej\Test\Controllers\SocialController@redirect') ->name('redirect'); Route::get('/{provider}/callback', 'RenokiCo\Hej\Test\Controllers\SocialController@callback') ->name('callback'); });
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/tests/Middleware/Authenticate.php
tests/Middleware/Authenticate.php
<?php namespace RenokiCo\Hej\Test\Middleware; use Illuminate\Auth\Middleware\Authenticate as Middleware; class Authenticate extends Middleware { /** * Get the path the user should be redirected to when they are not authenticated. * * @param \Illuminate\Http\Request $request * @return string|null */ protected function redirectTo($request) { if (! $request->expectsJson()) { return route('home'); } } }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/tests/Models/User.php
tests/Models/User.php
<?php namespace RenokiCo\Hej\Test\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use RenokiCo\Hej\Concerns\HasSocialAccounts; use RenokiCo\Hej\Contracts\Sociable; class User extends Authenticatable implements Sociable { use HasSocialAccounts; protected $fillable = [ 'name', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/tests/database/factories/UserFactory.php
tests/database/factories/UserFactory.php
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | This directory should contain each of the model factory definitions for | your application. Factories provide a convenient way to generate new | model instances for testing / seeding your application's database. | */ use Illuminate\Support\Str; $factory->define(\RenokiCo\Hej\Test\Models\User::class, function () { return [ 'name' => 'Name'.Str::random(5), 'email' => Str::random(5).'@gmail.com', 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret 'remember_token' => Str::random(10), ]; });
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/config/hej.php
config/hej.php
<?php return [ /* |-------------------------------------------------------------------------- | Models |-------------------------------------------------------------------------- | | Here you can configure the model classes to be used by the package. | If you wish to extend certain functionalities, you can extend the models | and replace the full class name here. | */ 'models' => [ 'social' => \RenokiCo\Hej\Social::class, ], /* |-------------------------------------------------------------------------- | Default Authenticatable |-------------------------------------------------------------------------- | | When logging in or registering with Hej!, it will assume the | authenticatable it needs to register or login with is the default | User class. However, you can change it here if you have a different | Authenticatable model or you can also specify it in the controller | when you extend it. | */ 'default_authenticatable' => \App\Models\User::class, /* |-------------------------------------------------------------------------- | Redirects |-------------------------------------------------------------------------- | | Specify the route names to use as redirects after different actions. | These can be also overwritten if you extend the controller class. | */ 'redirects' => [ 'authenticated' => 'home', 'provider_rejected' => 'home', 'duplicate_email' => 'home', 'provider_already_linked' => 'home', 'provider_linked_to_another' => 'home', 'link' => 'home', 'unlink' => 'home', ], /* |-------------------------------------------------------------------------- | Allowed Providers |-------------------------------------------------------------------------- | | This will overwrite the list of allowed providers within the controller. | */ 'allowed_providers' => [ // 'facebook', // 'twitter', // 'github', ], ];
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
renoki-co/hej
https://github.com/renoki-co/hej/blob/6b5e2784ccdbf81be6f42d68d296136a98d73430/database/migrations/2020_07_24_000000_create_socials_table.php
database/migrations/2020_07_24_000000_create_socials_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateSocialsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('socials', function (Blueprint $table) { $table->bigIncrements('id'); $table->morphs('model'); $table->string('provider'); $table->string('provider_id'); $table->string('provider_nickname')->nullable(); $table->string('provider_name')->nullable(); $table->string('provider_email')->nullable(); $table->string('provider_avatar')->nullable(); $table->timestamps(); $table->index(['model_id', 'model_type']); $table->index(['provider', 'provider_id']); $table->index(['provider', 'provider_id', 'model_id', 'model_type'], 'mix'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('socials'); } }
php
Apache-2.0
6b5e2784ccdbf81be6f42d68d296136a98d73430
2026-01-05T05:03:58.089582Z
false
skoerfgen/ACMECert
https://github.com/skoerfgen/ACMECert/blob/1fd77938de821d6113f65b6621d7de77c5bba2ed/ACMECert.php
ACMECert.php
<?php require __DIR__.'/src/ACME_Exception.php'; require __DIR__.'/src/ACMEv2.php'; require __DIR__.'/src/ACMECert.php';
php
MIT
1fd77938de821d6113f65b6621d7de77c5bba2ed
2026-01-05T05:04:08.403775Z
false
skoerfgen/ACMECert
https://github.com/skoerfgen/ACMECert/blob/1fd77938de821d6113f65b6621d7de77c5bba2ed/src/ACMEv2.php
src/ACMEv2.php
<?php /* MIT License Copyright (c) 2018 Stefan Körfgen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // https://github.com/skoerfgen/ACMECert namespace skoerfgen\ACMECert; use Exception; use skoerfgen\ACMECert\ACME_Exception; class ACMEv2 { // Communication with Let's Encrypt via ACME v2 protocol protected $directories=array( 'live'=>'https://acme-v02.api.letsencrypt.org/directory', 'staging'=>'https://acme-staging-v02.api.letsencrypt.org/directory' ),$ch=null,$logger=true,$bits,$sha_bits,$directory,$resources,$jwk_header,$kid_header,$account_key,$thumbprint,$nonce=null,$delay_until=null; public function __construct($live=true){ if (is_bool($live)){ // backwards compatibility to ACMECert v3.1.2 or older $this->directory=$this->directories[$live?'live':'staging']; }else{ $this->directory=$live; } } public function __destruct(){ if (PHP_MAJOR_VERSION<8 && $this->account_key) openssl_pkey_free($this->account_key); if ($this->ch) curl_close($this->ch); } public function loadAccountKey($account_key_pem){ if (PHP_MAJOR_VERSION<8 && $this->account_key) openssl_pkey_free($this->account_key); if (false===($this->account_key=openssl_pkey_get_private($account_key_pem))){ throw new Exception('Could not load account key: '.$account_key_pem.' ('.$this->get_openssl_error().')'); } if (false===($details=openssl_pkey_get_details($this->account_key))){ throw new Exception('Could not get account key details: '.$account_key_pem.' ('.$this->get_openssl_error().')'); } $this->bits=$details['bits']; switch($details['type']){ case OPENSSL_KEYTYPE_EC: if (version_compare(PHP_VERSION,'7.1.0')<0) throw new Exception('PHP >= 7.1.0 required for EC keys !'); $this->sha_bits=($this->bits==521?512:$this->bits); $this->jwk_header=array( // JOSE Header - RFC7515 'alg'=>'ES'.$this->sha_bits, 'jwk'=>array( // JSON Web Key 'crv'=>'P-'.$details['bits'], 'kty'=>'EC', 'x'=>$this->base64url(str_pad($details['ec']['x'],ceil($this->bits/8),"\x00",STR_PAD_LEFT)), 'y'=>$this->base64url(str_pad($details['ec']['y'],ceil($this->bits/8),"\x00",STR_PAD_LEFT)) ) ); break; case OPENSSL_KEYTYPE_RSA: $this->sha_bits=256; $this->jwk_header=array( // JOSE Header - RFC7515 'alg'=>'RS256', 'jwk'=>array( // JSON Web Key 'e'=>$this->base64url($details['rsa']['e']), // public exponent 'kty'=>'RSA', 'n'=>$this->base64url($details['rsa']['n']) // public modulus ) ); break; default: throw new Exception('Unsupported key type! Must be RSA or EC key.'); break; } $this->kid_header=array( 'alg'=>$this->jwk_header['alg'], 'kid'=>null ); $this->thumbprint=$this->base64url( // JSON Web Key (JWK) Thumbprint - RFC7638 hash( 'sha256', json_encode($this->jwk_header['jwk']), true ) ); } public function getAccountID(){ if (!$this->kid_header['kid']) self::getAccount(); return $this->kid_header['kid']; } public function setLogger($value=true){ switch(true){ case is_bool($value): break; case is_callable($value): break; default: throw new Exception('setLogger: invalid value provided'); break; } $this->logger=$value; } public function log($txt){ switch(true){ case $this->logger===true: error_log($txt); break; case $this->logger===false: break; default: $fn=$this->logger; $fn($txt); break; } } protected function create_ACME_Exception($type,$detail,$subproblems=array()){ $this->log('ACME_Exception: '.$detail.' ('.$type.')'); return new ACME_Exception($type,$detail,$subproblems); } protected function get_openssl_error(){ $out=array(); $arr=error_get_last(); if (is_array($arr)){ $out[]=$arr['message']; } $out[]=openssl_error_string(); return implode(' | ',$out); } protected function getAccount(){ $this->log('Getting account info'); $ret=$this->request('newAccount',array('onlyReturnExisting'=>true)); $this->log('Account info retrieved'); return $ret; } protected function keyAuthorization($token){ return $token.'.'.$this->thumbprint; } protected function readDirectory(){ $this->log('Initializing ACME v2 environment: '.$this->directory); $ret=$this->http_request($this->directory); // Read ACME Directory if ( !is_array($ret['body']) || !empty( array_diff_key( array_flip(array('newNonce','newAccount','newOrder')), $ret['body'] ) ) ){ throw new Exception('Failed to read directory: '.$this->directory); } $this->resources=$ret['body']; // store resources for later use $this->log('Initialized'); } protected function request($type,$payload='',$retry=false){ if (!$this->jwk_header) { throw new Exception('use loadAccountKey to load an account key'); } if (!$this->resources) $this->readDirectory(); if (0===stripos($type,'http')) { $this->resources['_tmp']=$type; $type='_tmp'; } try { $ret=$this->http_request($this->resources[$type],json_encode( $this->jws_encapsulate($type,$payload) )); }catch(ACME_Exception $e){ // retry previous request once, if replay-nonce expired/failed if (!$retry && $e->getType()==='urn:ietf:params:acme:error:badNonce') { $this->log('Replay-Nonce expired, retrying previous request'); return $this->request($type,$payload,true); } if (!$retry && $e->getType()==='urn:ietf:params:acme:error:rateLimited' && $this->delay_until!==null) { return $this->request($type,$payload,true); } throw $e; // rethrow all other exceptions } if (!$this->kid_header['kid'] && $type==='newAccount'){ $this->kid_header['kid']=$ret['headers']['location']; $this->log('AccountID: '.$this->kid_header['kid']); } return $ret; } protected function jws_encapsulate($type,$payload,$is_inner_jws=false){ // RFC7515 if ($type==='newAccount' || $is_inner_jws) { $protected=$this->jwk_header; }else{ $this->getAccountID(); $protected=$this->kid_header; } if (!$is_inner_jws) { if (!$this->nonce) { $ret=$this->http_request($this->resources['newNonce'],false); } $protected['nonce']=$this->nonce; $this->nonce=null; } if (!isset($this->resources[$type])){ throw new Exception('Resource "'.$type.'" not available.'); } $protected['url']=$this->resources[$type]; $protected64=$this->base64url(json_encode($protected,JSON_UNESCAPED_SLASHES)); $payload64=$this->base64url(is_string($payload)?$payload:json_encode($payload,JSON_UNESCAPED_SLASHES)); if (false===openssl_sign( $protected64.'.'.$payload64, $signature, $this->account_key, 'SHA'.$this->sha_bits )){ throw new Exception('Failed to sign payload !'.' ('.$this->get_openssl_error().')'); } return array( 'protected'=>$protected64, 'payload'=>$payload64, 'signature'=>$this->base64url($this->jwk_header['alg'][0]=='R'?$signature:$this->asn2signature($signature,ceil($this->bits/8))) ); } private function asn2signature($asn,$pad_len){ if ($asn[0]!=="\x30") throw new Exception('ASN.1 SEQUENCE not found !'); $asn=substr($asn,$asn[1]==="\x81"?3:2); if ($asn[0]!=="\x02") throw new Exception('ASN.1 INTEGER 1 not found !'); $R=ltrim(substr($asn,2,ord($asn[1])),"\x00"); $asn=substr($asn,ord($asn[1])+2); if ($asn[0]!=="\x02") throw new Exception('ASN.1 INTEGER 2 not found !'); $S=ltrim(substr($asn,2,ord($asn[1])),"\x00"); return str_pad($R,$pad_len,"\x00",STR_PAD_LEFT).str_pad($S,$pad_len,"\x00",STR_PAD_LEFT); } protected function base64url($data){ // RFC7515 - Appendix C return rtrim(strtr(base64_encode($data),'+/','-_'),'='); } protected function base64url_decode($data){ return base64_decode(strtr($data,'-_','+/')); } private function json_decode($str){ $ret=json_decode($str,true); if ($ret===null) { throw new Exception('Could not parse JSON: '.$str); } return $ret; } protected function http_request($url,$data=null){ if ($this->ch===null) { if (extension_loaded('curl') && $this->ch=curl_init()) { $this->log('Using cURL'); }elseif(ini_get('allow_url_fopen')){ $this->ch=false; $this->log('Using fopen wrappers'); }else{ throw new Exception('Can not connect, no cURL or fopen wrappers enabled !'); } } if ($this->delay_until!==null){ $delta=$this->delay_until-time(); if ($delta>0 && $delta<300){ // ignore delay if not in range 1s..5min $this->log('Delaying '.$delta.'s (rate limit)'); sleep($delta); } $this->delay_until=null; } $method=$data===false?'HEAD':($data===null?'GET':'POST'); $user_agent='ACMECert v3.7.1 (+https://github.com/skoerfgen/ACMECert)'; $header=($data===null||$data===false)?array():array('Content-Type: application/jose+json'); if ($this->ch) { $headers=array(); curl_setopt_array($this->ch,array( CURLOPT_URL=>$url, CURLOPT_FOLLOWLOCATION=>true, CURLOPT_RETURNTRANSFER=>true, CURLOPT_TCP_NODELAY=>true, CURLOPT_NOBODY=>$data===false, CURLOPT_USERAGENT=>$user_agent, CURLOPT_CUSTOMREQUEST=>$method, CURLOPT_HTTPHEADER=>$header, CURLOPT_POSTFIELDS=>$data, CURLOPT_HEADERFUNCTION=>static function($ch,$header)use(&$headers){ $headers[]=$header; return strlen($header); } )); $took=microtime(true); $body=curl_exec($this->ch); $took=round(microtime(true)-$took,2).'s'; if ($body===false) throw new Exception('HTTP Request Error: '.curl_error($this->ch)); }else{ $opts=array( 'http'=>array( 'header'=>$header, 'method'=>$method, 'user_agent'=>$user_agent, 'ignore_errors'=>true, 'timeout'=>60, 'content'=>$data ) ); $took=microtime(true); $body=file_get_contents($url,false,stream_context_create($opts)); $took=round(microtime(true)-$took,2).'s'; if ($body===false) throw new Exception('HTTP Request Error: '.$this->get_openssl_error()); $headers=$http_response_header; } $headers=array_reduce( // parse http response headers into array array_filter($headers,function($item){ return trim($item)!=''; }), function($carry,$item)use(&$code){ $parts=explode(':',$item,2); if (count($parts)===1){ list(,$code)=explode(' ',trim($item),3); $carry=array(); }else{ list($k,$v)=$parts; $k=strtolower(trim($k)); switch($k){ case 'link': if (preg_match('/<(.*)>\s*;\s*rel=\"(.*)\"/',$v,$matches)){ $carry[$k][$matches[2]][]=trim($matches[1]); } break; case 'content-type': list($v)=explode(';',$v,2); default: $carry[$k]=trim($v); break; } } return $carry; }, array() ); $this->log(' '.$url.' ['.$code.'] ('.$took.')'); if (!empty($headers['replay-nonce'])) $this->nonce=$headers['replay-nonce']; if (isset($headers['retry-after'])){ $this->delay_until=$this->parseRetryAfterHeader($headers['retry-after'])+time(); } if (!empty($headers['content-type'])){ switch($headers['content-type']){ case 'application/json': if ($code[0]=='2'){ // on non 2xx response: fall through to problem+json case $body=$this->json_decode($body); if (isset($body['error']) && !(isset($body['status']) && $body['status']==='valid')) { $this->handleError($body['error']); } break; } case 'application/problem+json': $body=$this->json_decode($body); $this->handleError($body); break; } } if ($code[0]!='2') { throw new Exception('Invalid HTTP-Status-Code received: '.$code.': '.print_r($body,true)); } $ret=array( 'code'=>$code, 'headers'=>$headers, 'body'=>$body ); return $ret; } protected function parseRetryAfterHeader($h){ if (is_numeric($h)){ return (int)$h; }else{ $ts=strtotime($h); return $ts===false?0:max(0,$ts-time()); } } private function handleError($error){ throw $this->create_ACME_Exception($error['type'],$error['detail'], array_map(function($subproblem){ return $this->create_ACME_Exception( $subproblem['type'], (isset($subproblem['identifier']['value'])? '"'.$subproblem['identifier']['value'].'": ': '' ).$subproblem['detail'] ); },isset($error['subproblems'])?$error['subproblems']:array()) ); } }
php
MIT
1fd77938de821d6113f65b6621d7de77c5bba2ed
2026-01-05T05:04:08.403775Z
false
skoerfgen/ACMECert
https://github.com/skoerfgen/ACMECert/blob/1fd77938de821d6113f65b6621d7de77c5bba2ed/src/ACMECert.php
src/ACMECert.php
<?php /* MIT License Copyright (c) 2018 Stefan Körfgen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // https://github.com/skoerfgen/ACMECert namespace skoerfgen\ACMECert; use skoerfgen\ACMECert\ACMEv2; use skoerfgen\ACMECert\ACME_Exception; use Exception; use stdClass; class ACMECert extends ACMEv2 { private $alternate_chains=array(); public function register($termsOfServiceAgreed=false,$contacts=array()){ return $this->_register($termsOfServiceAgreed,$contacts); } public function registerEAB($termsOfServiceAgreed,$eab_kid,$eab_hmac,$contacts=array()){ if (!$this->resources) $this->readDirectory(); $protected=array( 'alg'=>'HS256', 'kid'=>$eab_kid, 'url'=>$this->resources['newAccount'] ); $payload=$this->jwk_header['jwk']; $protected64=$this->base64url(json_encode($protected,JSON_UNESCAPED_SLASHES)); $payload64=$this->base64url(json_encode($payload,JSON_UNESCAPED_SLASHES)); $signature=hash_hmac('sha256',$protected64.'.'.$payload64,$this->base64url_decode($eab_hmac),true); return $this->_register($termsOfServiceAgreed,$contacts,array( 'externalAccountBinding'=>array( 'protected'=>$protected64, 'payload'=>$payload64, 'signature'=>$this->base64url($signature) ) )); } private function _register($termsOfServiceAgreed=false,$contacts=array(),$extra=array()){ $this->log('Registering account'); $ret=$this->request('newAccount',array( 'termsOfServiceAgreed'=>(bool)$termsOfServiceAgreed, 'contact'=>$this->make_contacts_array($contacts) )+$extra); $this->log($ret['code']==201?'Account registered':'Account already registered'); return $ret['body']; } public function update($contacts=array()){ $this->log('Updating account'); $ret=$this->request($this->getAccountID(),array( 'contact'=>$this->make_contacts_array($contacts) )); $this->log('Account updated'); return $ret['body']; } public function getAccount(){ $ret=parent::getAccount(); return $ret['body']; } public function deactivateAccount(){ $this->log('Deactivating account'); $ret=$this->deactivate($this->getAccountID()); $this->log('Account deactivated'); return $ret; } public function deactivate($url){ $this->log('Deactivating resource: '.$url); $ret=$this->request($url,array('status'=>'deactivated')); $this->log('Resource deactivated'); return $ret['body']; } public function getTermsURL(){ if (!$this->resources) $this->readDirectory(); if (!isset($this->resources['meta']['termsOfService'])){ throw new Exception('Failed to get Terms Of Service URL'); } return $this->resources['meta']['termsOfService']; } public function getCAAIdentities(){ if (!$this->resources) $this->readDirectory(); if (!isset($this->resources['meta']['caaIdentities'])){ throw new Exception('Failed to get CAA Identities'); } return $this->resources['meta']['caaIdentities']; } public function keyChange($new_account_key_pem){ // account key roll-over $ac2=new ACMEv2(); $ac2->loadAccountKey($new_account_key_pem); $account=$this->getAccountID(); $ac2->resources=$this->resources; $this->log('Account Key Roll-Over'); $ret=$this->request('keyChange', $ac2->jws_encapsulate('keyChange',array( 'account'=>$account, 'oldKey'=>$this->jwk_header['jwk'] ),true) ); $this->log('Account Key Roll-Over successful'); $this->loadAccountKey($new_account_key_pem); return $ret['body']; } public function revoke($pem){ if (false===($res=openssl_x509_read($pem))){ throw new Exception('Could not load certificate: '.$pem.' ('.$this->get_openssl_error().')'); } if (false===(openssl_x509_export($res,$certificate))){ throw new Exception('Could not export certificate: '.$pem.' ('.$this->get_openssl_error().')'); } $this->log('Revoking certificate'); $this->request('revokeCert',array( 'certificate'=>$this->base64url($this->pem2der($certificate)) )); $this->log('Certificate revoked'); } public function getCertificateChain($pem,$domain_config,$callback,$settings=array()){ $settings=$this->parseSettings($settings); $domain_config=array_change_key_case($domain_config,CASE_LOWER); $domains=array_keys($domain_config); $authz_deactivated=false; $this->getAccountID(); // get account info upfront to avoid mixed up logging order // === Order === $this->log('Creating Order'); $ret=$this->request('newOrder',$this->makeOrder($domains,$settings)); $order=$ret['body']; $order_location=$ret['headers']['location']; $this->log('Order created: '.$order_location); // === Authorization === if ($order['status']==='ready' && $settings['authz_reuse']) { $this->log('All authorizations already valid, skipping validation altogether'); }else{ $groups=array(); $auth_count=count($order['authorizations']); foreach($order['authorizations'] as $idx=>$auth_url){ $this->log('Fetching authorization '.($idx+1).' of '.$auth_count); $ret=$this->request($auth_url,''); $authorization=$ret['body']; // wildcard authorization identifiers have no leading *. $domain=( // get domain and add leading *. if wildcard is used isset($authorization['wildcard']) && $authorization['wildcard'] ? '*.':'' ).$authorization['identifier']['value']; if ($authorization['status']==='valid') { if ($settings['authz_reuse']) { $this->log('Authorization of '.$domain.' already valid, skipping validation'); }else{ $this->log('Authorization of '.$domain.' already valid, deactivating authorization'); $this->deactivate($auth_url); $authz_deactivated=true; } continue; } // groups are used to be able to set more than one TXT Record for one subdomain // when using dns-01 before firing the validation to avoid DNS caching problem $groups[ $domain_config[$domain]['challenge']. '|'. (($settings['group'])?ltrim($domain,'*.'):$domain) ][$domain]=array($auth_url,$authorization); } if ($authz_deactivated){ $this->log('Restarting Order after deactivating already valid authorizations'); $settings['authz_reuse']=true; return $this->getCertificateChain($pem,$domain_config,$callback,$settings); } // make sure dns-01 comes last to avoid DNS problems for other challenges krsort($groups); foreach($groups as $group){ $pending_challenges=array(); try { // make sure that pending challenges are cleaned up in case of failure foreach($group as $domain=>$arr){ list($auth_url,$authorization)=$arr; $config=$domain_config[$domain]; $type=$config['challenge']; $challenge=$this->parse_challenges($authorization,$type,$challenge_url); $opts=array( 'domain'=>$domain, 'config'=>$config ); list($opts['key'],$opts['value'])=$challenge; $this->log('Triggering challenge callback for '.$domain.' using '.$type); $remove_cb=$callback($opts); $pending_challenges[]=array($remove_cb,$opts,$challenge_url,$auth_url); } foreach($pending_challenges as $arr){ list($remove_cb,$opts,$challenge_url,$auth_url)=$arr; $this->log('Notifying server for validation of '.$opts['domain']); $this->request($challenge_url,new stdClass); $this->log('Waiting for server challenge validation'); sleep(1); if (!$this->poll('pending',$auth_url,$body)) { $this->log('Validation failed: '.$opts['domain']); $error=$body['challenges'][0]['error']; throw $this->create_ACME_Exception( $error['type'], 'Challenge validation failed: '.$error['detail'] ); }else{ $this->log('Validation successful: '.$opts['domain']); } } }finally{ // cleanup pending challenges foreach($pending_challenges as $arr){ list($remove_cb,$opts)=$arr; if ($remove_cb) { $this->log('Triggering remove callback for '.$opts['domain']); $remove_cb($opts); } } } } } // autodetect if Private Key or CSR is used if ($key=openssl_pkey_get_private($pem)){ // Private Key detected if (PHP_MAJOR_VERSION<8) openssl_free_key($key); $this->log('Generating CSR'); $csr=$this->generateCSR($pem,$domains); }elseif(openssl_csr_get_subject($pem)){ // CSR detected $this->log('Using provided CSR'); if (0===strpos($pem,'file://')) { $csr=file_get_contents(substr($pem,7)); if (false===$csr) { throw new Exception('Failed to read CSR from '.$pem.' ('.$this->get_openssl_error().')'); } }else{ $csr=$pem; } }else{ throw new Exception('Could not load Private Key or CSR ('.$this->get_openssl_error().'): '.$pem); } $this->log('Finalizing Order'); $ret=$this->request($order['finalize'],array( 'csr'=>$this->base64url($this->pem2der($csr)) )); $ret=$ret['body']; if (isset($ret['certificate'])) { return $this->request_certificate($ret); } if ($this->poll('processing',$order_location,$ret)) { return $this->request_certificate($ret); } throw new Exception('Order failed'); } public function getCertificateChains($pem,$domain_config,$callback,$settings=array()){ $default_chain=$this->getCertificateChain($pem,$domain_config,$callback,$settings); $out=array(); $out[$this->getTopIssuerCN($default_chain)]=$default_chain; foreach($this->alternate_chains as $link){ $chain=$this->request_certificate(array('certificate'=>$link),true); $out[$this->getTopIssuerCN($chain)]=$chain; } $this->log('Received '.count($out).' chain(s): '.implode(', ',array_keys($out))); return $out; } public function generateCSR($domain_key_pem,$domains){ if (false===($domain_key=openssl_pkey_get_private($domain_key_pem))){ throw new Exception('Could not load domain key: '.$domain_key_pem.' ('.$this->get_openssl_error().')'); } $fn=$this->tmp_ssl_cnf($domains); $cn=reset($domains); $dn=array(); if (!filter_var($cn,FILTER_VALIDATE_IP) && strlen($cn)<=64){ $dn['commonName']=$cn; } $csr=openssl_csr_new($dn,$domain_key,array( 'config'=>$fn, 'req_extensions'=>'SAN', 'digest_alg'=>'sha512' )); unlink($fn); if (PHP_MAJOR_VERSION<8) openssl_free_key($domain_key); if (false===$csr) { throw new Exception('Could not generate CSR ! ('.$this->get_openssl_error().')'); } if (false===openssl_csr_export($csr,$out)){ throw new Exception('Could not export CSR ! ('.$this->get_openssl_error().')'); } return $out; } private function generateKey($opts){ $fn=$this->tmp_ssl_cnf(); $config=array('config'=>$fn)+$opts; if (false===($key=openssl_pkey_new($config))){ throw new Exception('Could not generate new private key ! ('.$this->get_openssl_error().')'); } if (false===openssl_pkey_export($key,$pem,null,$config)){ throw new Exception('Could not export private key ! ('.$this->get_openssl_error().')'); } unlink($fn); if (PHP_MAJOR_VERSION<8) openssl_free_key($key); return $pem; } public function generateRSAKey($bits=2048){ return $this->generateKey(array( 'private_key_bits'=>(int)$bits, 'private_key_type'=>OPENSSL_KEYTYPE_RSA )); } public function generateECKey($curve_name='P-384'){ if (version_compare(PHP_VERSION,'7.1.0')<0) throw new Exception('PHP >= 7.1.0 required for EC keys !'); $map=array('P-256'=>'prime256v1','P-384'=>'secp384r1','P-521'=>'secp521r1'); if (isset($map[$curve_name])) $curve_name=$map[$curve_name]; return $this->generateKey(array( 'curve_name'=>$curve_name, 'private_key_type'=>OPENSSL_KEYTYPE_EC )); } public function parseCertificate($cert_pem){ if (false===($ret=openssl_x509_read($cert_pem))) { throw new Exception('Could not load certificate: '.$cert_pem.' ('.$this->get_openssl_error().')'); } if (!is_array($ret=openssl_x509_parse($ret,true))) { throw new Exception('Could not parse certificate ('.$this->get_openssl_error().')'); } return $ret; } public function getSAN($pem){ $ret=$this->parseCertificate($pem); if (!isset($ret['extensions']['subjectAltName'])){ throw new Exception('No Subject Alternative Name (SAN) found in certificate'); } $out=array(); foreach(explode(',',$ret['extensions']['subjectAltName']) as $line){ list($type,$name)=array_map('trim',explode(':',$line,2)); if ($type==='DNS' || $type==='IP Address'){ $out[]=$name; } } return $out; } public function getRemainingDays($cert_pem){ $ret=$this->parseCertificate($cert_pem); return ($ret['validTo_time_t']-time())/86400; } public function getRemainingPercent($cert_pem){ $ret=$this->parseCertificate($cert_pem); $total=$ret['validTo_time_t']-$ret['validFrom_time_t']; $used=time()-$ret['validFrom_time_t']; return (1-max(0,min(1,$used/$total)))*100; } public function generateALPNCertificate($domain_key_pem,$domain,$token){ $domains=array($domain); $csr=$this->generateCSR($domain_key_pem,$domains); $fn=$this->tmp_ssl_cnf($domains,'1.3.6.1.5.5.7.1.31=critical,DER:0420'.$token."\n"); $config=array( 'config'=>$fn, 'x509_extensions'=>'SAN', 'digest_alg'=>'sha512' ); $cert=openssl_csr_sign($csr,null,$domain_key_pem,1,$config); unlink($fn); if (false===$cert) { throw new Exception('Could not generate self signed certificate ! ('.$this->get_openssl_error().')'); } if (false===openssl_x509_export($cert,$out)){ throw new Exception('Could not export self signed certificate ! ('.$this->get_openssl_error().')'); } return $out; } public function getProfiles(){ if (!$this->resources) $this->readDirectory(); if ( !isset($this->resources['meta']['profiles']) || !is_array($this->resources['meta']['profiles'])) { throw new Exception('certificate profiles not supported by CA'); } return $this->resources['meta']['profiles']; } private function requireARI(){ if (!$this->resources) $this->readDirectory(); if (!isset($this->resources['renewalInfo'])) throw new Exception('ARI not supported by CA'); } public function getARI($pem,&$ari_cert_id=null){ $ari_cert_id=null; $id=$this->getARICertID($pem); $this->requireARI(); $this->log('Requesting ACME Renewal Information'); $ret=$this->http_request($this->resources['renewalInfo'].'/'.$id); $this->delay_until=null; if (!is_array($ret['body']['suggestedWindow'])) throw new Exception('ARI suggestedWindow not present'); $sw=&$ret['body']['suggestedWindow']; if (!isset($sw['start'])) throw new Exception('ARI suggestedWindow start not present'); if (!isset($sw['end'])) throw new Exception('ARI suggestedWindow end not present'); $sw=array_map(array($this,'parseDate'),$sw); $out=$ret['body']; if (isset($out['explanationURL'])){ if (trim($out['explanationURL'])===''){ unset($out['explanationURL']); } } if (isset($ret['headers']['retry-after'])){ $tmp=$this->parseRetryAfterHeader($ret['headers']['retry-after']); if ($tmp>0){ $out['retry_after']=$tmp; } } $out['ari_cert_id']=$id; $ari_cert_id=$id; return $out; } private function getARICertID($pem){ if (version_compare(PHP_VERSION,'7.1.2','<')){ throw new Exception('PHP Version >= 7.1.2 required for ARI'); // serialNumberHex - https://github.com/php/php-src/pull/1755 } $ret=$this->parseCertificate($pem); if (!isset($ret['extensions']['authorityKeyIdentifier'])) { throw new Exception('authorityKeyIdentifier missing'); } $aki=trim($ret['extensions']['authorityKeyIdentifier']); if (stripos($aki,'keyid')===0) $aki=substr($aki,5); $aki=hex2bin(str_replace(':','',$aki)); if (!$aki) throw new Exception('Failed to parse authorityKeyIdentifier'); if (!isset($ret['serialNumberHex'])) { throw new Exception('serialNumberHex missing'); } $ser=hex2bin(trim($ret['serialNumberHex'])); if (!$ser) throw new Exception('Failed to parse serialNumberHex'); if (ord($ser[0]) & 0x80) $ser="\x00".$ser; return $this->base64url($aki).'.'.$this->base64url($ser); } private function parseDate($str){ $ret=strtotime(preg_replace('/(\.\d\d)\d+/','$1',$str)); if ($ret===false) throw new Exception('Failed to parse date: '.$str); return $ret; } private function parseSettings($opts){ // authz_reuse: backwards compatibility to ACMECert v3.1.2 or older if (!is_array($opts)) $opts=array('authz_reuse'=>(bool)$opts); if (!isset($opts['authz_reuse'])) $opts['authz_reuse']=true; if (!isset($opts['group'])) $opts['group']=true; $diff=array_diff_key( $opts, array_flip(array('authz_reuse','notAfter','notBefore','replaces','profile','group')) ); if (!empty($diff)){ throw new Exception('getCertificateChain(s): Invalid option "'.key($diff).'"'); } return $opts; } private function setRFC3339Date(&$out,$key,$opts){ if (isset($opts[$key])){ $out[$key]=is_string($opts[$key])? $opts[$key]: date(DATE_RFC3339,$opts[$key]); } } private function makeOrder($domains,$opts){ $order=array( 'identifiers'=>array_map( function($domain){ if (filter_var($domain,FILTER_VALIDATE_IP)){ return array('type'=>'ip','value'=>$domain); }else{ return array('type'=>'dns','value'=>$domain); } }, $domains ) ); $this->setRFC3339Date($order,'notAfter',$opts); $this->setRFC3339Date($order,'notBefore',$opts); if (isset($opts['replaces'])) { // ARI $this->requireARI(); $order['replaces']=$opts['replaces']; $this->log('Replacing Certificate: '.$opts['replaces']); } if (isset($opts['profile'])) { // certificate profiles $profiles=$this->getProfiles(); if (!isset($profiles[$opts['profile']])) { throw new Exception('certificate profile "'.$opts['profile'].'" not supported by CA'); } $order['profile']=$opts['profile']; $this->log('Selected certificate profile: '.$opts['profile']); } return $order; } private function parse_challenges($authorization,$type,&$url){ foreach($authorization['challenges'] as $challenge){ if ($challenge['type']!=$type) continue; $url=$challenge['url']; switch($challenge['type']){ case 'dns-01': return array( '_acme-challenge.'.$authorization['identifier']['value'], $this->base64url(hash('sha256',$this->keyAuthorization($challenge['token']),true)) ); break; case 'http-01': return array( '/.well-known/acme-challenge/'.$challenge['token'], $this->keyAuthorization($challenge['token']) ); break; case 'tls-alpn-01': return array(null,hash('sha256',$this->keyAuthorization($challenge['token']))); break; } } throw new Exception( 'Challenge type: "'.$type.'" not available, for this challenge use '. implode(' or ',array_map( function($a){ return '"'.$a['type'].'"'; }, $authorization['challenges'] )) ); } private function poll($initial,$type,&$ret){ $max_tries=10; // ~ 5 minutes for($i=0;$i<$max_tries;$i++){ $ret=$this->request($type); $ret=$ret['body']; if ($ret['status']!==$initial) return $ret['status']==='valid'; $s=pow(2,min($i,6)); if ($i!==$max_tries-1){ $this->log('Retrying in '.($s).'s'); sleep($s); } } throw new Exception('Aborted after '.$max_tries.' tries'); } private function request_certificate($ret,$alternate=false){ $this->log('Requesting '.($alternate?'alternate':'default').' certificate-chain'); $ret=$this->request($ret['certificate'],''); if ($ret['headers']['content-type']!=='application/pem-certificate-chain'){ throw new Exception('Unexpected content-type: '.$ret['headers']['content-type']); } $chain=array(); foreach($this->splitChain($ret['body']) as $cert){ $info=$this->parseCertificate($cert); $chain[]='['.$info['issuer']['CN'].']'; } if (!$alternate) { if (isset($ret['headers']['link']['alternate'])){ $this->alternate_chains=$ret['headers']['link']['alternate']; }else{ $this->alternate_chains=array(); } } $this->log(($alternate?'Alternate':'Default').' certificate-chain retrieved: '.implode(' -> ',array_reverse($chain,true))); return $ret['body']; } private function tmp_ssl_cnf($domains=null,$extension=''){ if (false===($fn=tempnam(sys_get_temp_dir(), "CNF_"))){ throw new Exception('Failed to create temp file !'); } if (false===@file_put_contents($fn, 'HOME = .'."\n". 'RANDFILE=$ENV::HOME/.rnd'."\n". '[v3_ca]'."\n". '[req]'."\n". 'default_bits=2048'."\n". ($domains? 'distinguished_name=req_distinguished_name'."\n". '[req_distinguished_name]'."\n". '[v3_req]'."\n". '[SAN]'."\n". 'subjectAltName='. implode(',',array_map(function($domain){ if (filter_var($domain,FILTER_VALIDATE_IP)){ return 'IP:'.$domain; }else{ return 'DNS:'.$domain; } },$domains))."\n" : '' ).$extension )){ throw new Exception('Failed to write tmp file: '.$fn); } return $fn; } private function pem2der($pem) { return base64_decode(implode('',array_slice( array_map('trim',explode("\n",trim($pem))),1,-1 ))); } private function make_contacts_array($contacts){ if (!is_array($contacts)) { $contacts=$contacts?array($contacts):array(); } return array_map(function($contact){ return 'mailto:'.$contact; },$contacts); } private function getTopIssuerCN($chain){ $tmp=$this->splitChain($chain); $ret=$this->parseCertificate(end($tmp)); return $ret['issuer']['CN']; } public function splitChain($chain){ $delim='-----END CERTIFICATE-----'; return array_map(function($item)use($delim){ return trim($item.$delim); },array_filter(explode($delim,$chain),function($item){ return strpos($item,'-----BEGIN CERTIFICATE-----')!==false; })); } }
php
MIT
1fd77938de821d6113f65b6621d7de77c5bba2ed
2026-01-05T05:04:08.403775Z
false
skoerfgen/ACMECert
https://github.com/skoerfgen/ACMECert/blob/1fd77938de821d6113f65b6621d7de77c5bba2ed/src/ACME_Exception.php
src/ACME_Exception.php
<?php /* MIT License Copyright (c) 2018 Stefan Körfgen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // https://github.com/skoerfgen/ACMECert namespace skoerfgen\ACMECert; use Exception; class ACME_Exception extends Exception { private $type,$subproblems; function __construct($type,$detail,$subproblems=array()){ $this->type=$type; $this->subproblems=$subproblems; parent::__construct($detail.' ('.$type.')'); } function getType(){ return $this->type; } function getSubproblems(){ return $this->subproblems; } }
php
MIT
1fd77938de821d6113f65b6621d7de77c5bba2ed
2026-01-05T05:04:08.403775Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/DoucheWeb/app.php
src/DoucheWeb/app.php
<?php namespace DoucheWeb; use Douche\Interactor\AuctionListResponse; use Douche\Interactor\AuctionViewRequest; use Douche\Interactor\UserLoginRequest; use Douche\Interactor\UserLoginResponse; use Douche\Interactor\AuctionViewResponse; use Douche\Interactor\BidRequest; use Douche\Exception\Exception as DoucheException; use Mustache\Silex\Provider\MustacheServiceProvider; use Silex\Application; use Silex\Provider\DoctrineServiceProvider; use Silex\Provider\MonologServiceProvider; use Silex\Provider\ServiceControllerServiceProvider; use Silex\Provider\SessionServiceProvider; use Silex\ExceptionListenerWrapper; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\KernelEvents; use Money\Money; use Money\Currency; $app = new Application(); $app->register(new MonologServiceProvider()); $app->register(new DoctrineServiceProvider()); $app->register(new MustacheServiceProvider(), [ 'mustache.options' => [ 'helpers' => [ 'format_money' => function ($money) { return $money->getCurrency().' '.($money->getAmount() / 100); }, 'format_date' => function (\DateTime $date) { return $date->format("Y-m-d H:i:s"); }, ], ], ]); $app->register(new ServiceControllerServiceProvider()); $app->register(new SessionServiceProvider()); $app->register(new ServiceProvider()); $app->get('/', 'interactor.auction_list') ->value('controller', 'auction_list'); $app->get('/auction/{id}', 'interactor.auction_view') ->value('controller', 'auction_view') ->convert('request', function ($request) { return new AuctionViewRequest($request->attributes->get('id')); }); $app->post('/auction/{id}/bids', 'interactor.bid') ->before(function (Request $request, Application $app) { if (!$request->getSession()->has('current_user')) { return $app->abort(401, 'Authentication Required'); } }) ->value('controller', 'bid') ->value('success_handler', function ($view, $request) { return new RedirectResponse("/auction/" . $request->attributes->get('id')); }) ->value('error_handlers', [ "Douche\Exception\BidTooLowException" => function ($e, $code, $request) { $request->getSession()->getFlashBag()->set('errors', [ 'The provided bid was too low.', ]); return new RedirectResponse("/auction/" . $request->attributes->get('id')); }, ]) ->convert('request', function ($request) { return new BidRequest( $request->attributes->get('id'), $request->getSession()->get('current_user')->id, new Money((int) $request->request->get('amount') * 100, new Currency($request->request->get('currency'))) ); }); $app->post('/login', 'interactor.user_login') ->value('controller', 'login') ->value('success_handler', function ($view, $request) { $request->getSession()->set('current_user', $view->user); return new RedirectResponse("/"); }) ->value('error_handlers', [ "Douche\Exception\UserNotFoundException" => function ($e) { return [ 'errors' => ['Incorrect email provided.'], 'email' => $e->email, ]; }, "Douche\Exception\IncorrectPasswordException" => function ($e) { return [ 'errors' => ['Invalid credentials provided.'], 'email' => $e->email, ]; }, ]) ->convert('request', function ($request) { return new UserLoginRequest($request->request->all()); }); $app->get('/login', function (Request $request, Application $app) { $view = [ 'errors' => [], ]; return $app['mustache']->render('login.html.mustache', $view); }); $app->get('/logout', function (Request $request, Application $app) { $request->getSession()->start(); $request->getSession()->invalidate(); return $app->redirect("/"); }); $app['resolver'] = $app->share($app->extend('resolver', function ($resolver, $app) { $resolver = new ControllerResolver($resolver, $app); return $resolver; })); $app->before(function (Request $request) { $request->attributes->set('request', $request); }); $app->error(function (DoucheException $e, $code) use ($app) { $app['request']->attributes->set('failed', true); $errorHandlers = $app['request']->attributes->get('error_handlers', []); foreach ($errorHandlers as $type => $handler) { if ($e instanceof $type) { return $handler($e, $code, $app['request']); } } }); $app->on(KernelEvents::VIEW, function ($event) use ($app) { $view = $event->getControllerResult(); if (is_null($view) || is_string($view)) { return; } $request = $event->getRequest(); if (!$request->attributes->get('failed') && $request->attributes->has('success_handler')) { $handler = $request->attributes->get('success_handler'); $view = $handler($view, $request); if ($view instanceof Response) { $event->setResponse($view); return; } } $controller = $request->attributes->get('controller'); $template = "$controller.html"; $view = (object) $view; $view->current_user = $request->getSession()->get('current_user'); $view->form_errors = $request->getSession()->getFlashBag()->get('errors'); $body = $app['mustache']->render($template, $view); $response = new Response($body); $event->setResponse($response); }); $app->after(function () use ($app) { $app['douche.auction_repo']->save(); }); return $app;
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/DoucheWeb/ServiceProvider.php
src/DoucheWeb/ServiceProvider.php
<?php namespace DoucheWeb; use Douche\Storage\Sql\AuctionRepository; use Douche\Storage\File\UserRepository; use Douche\Interactor\AuctionList; use Douche\Interactor\AuctionView; use Douche\Interactor\UserLogin; use Douche\Interactor\Bid; use Douche\Service\PairCurrencyConverter; use Douche\Service\UppercasePasswordEncoder; use Silex\Application; use Silex\ServiceProviderInterface; use Money\Currency; use Money\CurrencyPair; /** * External dependencies * * Services: * - db (DoctrineServiceProvider) * * Parameters: * - douche.user_repo.file: string filename for json storage */ class ServiceProvider implements ServiceProviderInterface { public function register(Application $app) { $app['douche.user_repo'] = $app->share(function ($app) { return new UserRepository($app['douche.user_repo.file']); }); $app['douche.auction_repo'] = $app->share(function ($app) { return new AuctionRepository($app['db'], $app['douche.user_repo']); }); $app['douche.password_encoder'] = $app->share(function ($app) { return new UppercasePasswordEncoder; }); $app['douche.currency_converter'] = $app->share(function ($app) { return new PairCurrencyConverter([ CurrencyPair::createFromIso('USD/GBP 0.5'), CurrencyPair::createFromIso('GBP/USD 2.0'), ]); }); $app['interactor.auction_list'] = $app->share(function ($app) { return new AuctionList($app['douche.auction_repo']); }); $app['interactor.auction_view'] = $app->share(function ($app) { return new AuctionView($app['douche.auction_repo']); }); $app['interactor.user_login'] = $app->share(function ($app) { return new UserLogin($app['douche.user_repo'], $app['douche.password_encoder']); }); $app['interactor.bid'] = $app->share(function ($app) { return new Bid($app['douche.auction_repo'], $app['douche.user_repo'], $app['douche.currency_converter']); }); } public function boot(Application $app) { } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/DoucheWeb/console.php
src/DoucheWeb/console.php
<?php namespace DoucheWeb; use Douche\Storage\Sql\Util; use Douche\Entity\User; use Igorw\Silex\ConfigServiceProvider; use Symfony\Component\Console\Application; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; require __DIR__.'/../../vendor/autoload.php'; $app = require __DIR__.'/app.php'; $app->register(new ConfigServiceProvider(__DIR__."/../../config/dev.json", [ 'storage_path' => __DIR__.'/../../storage', 'template_path' => __DIR__.'/../../src/DoucheWeb/views', ])); $console = new Application(); $console ->register('init') ->setDescription('Initialize doucheswag') ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { Util::createAuctionSchema($app['db']); }); $console ->register('sql') ->setDefinition([ new InputArgument('query', InputArgument::REQUIRED), ]) ->setDescription('Query the database') ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { $sql = $input->getArgument('query'); $rows = $app['db']->executeQuery($sql); var_dump(iterator_to_array($rows)); }); $console ->register('create-auction') ->setDefinition([ new InputArgument('name', InputArgument::REQUIRED), new InputArgument('ends-at', InputArgument::REQUIRED), ]) ->setDescription('Create an auction') ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { $name = $input->getArgument('name'); $endsAt = new \DateTime($input->getArgument('ends-at')); // $app['douche.auction_repo']->createAuction($name, $endsAt); throw new \RuntimeException('Not implemented yet'); }); $console ->register('create-user') ->setDefinition([ new InputArgument('id', InputArgument::REQUIRED), new InputArgument('name', InputArgument::REQUIRED), new InputArgument('email', InputArgument::REQUIRED), new InputArgument('passwordHash', InputArgument::REQUIRED), ]) ->setDescription('Create a user') ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) { $user = new User( $input->getArgument('id'), $input->getArgument('name'), $input->getArgument('email'), $input->getArgument('passwordHash') ); $app['douche.user_repo']->add($user); $app['douche.user_repo']->save(); }); $console->run();
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/DoucheWeb/ControllerResolver.php
src/DoucheWeb/ControllerResolver.php
<?php namespace DoucheWeb; use Pimple; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; class ControllerResolver implements ControllerResolverInterface { protected $resolver; protected $container; public function __construct(ControllerResolverInterface $resolver, Pimple $container) { $this->resolver = $resolver; $this->container = $container; } public function getController(Request $request) { $controller = $request->attributes->get('_controller', null); if (!is_string($controller) || !isset($this->container[$controller])) { return $this->resolver->getController($request); } if (!is_callable($this->container[$controller])) { throw new \InvalidArgumentException(sprintf('Service "%s" is not callable.', $controller)); } return $this->container[$controller]; } public function getArguments(Request $request, $controller) { return $this->resolver->getArguments($request, $controller); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Entity/User.php
src/Douche/Entity/User.php
<?php namespace Douche\Entity; class User { private $id; private $name; private $email; private $passwordHash; public function __construct($id, $name, $email, $passwordHash) { $this->id = $id; $this->name = $name; $this->email = $email; $this->passwordHash = $passwordHash; } public function getId() { return $this->id; } public function getName() { return $this->name; } public function getEmail() { return $this->email; } public function getPasswordHash() { return $this->passwordHash; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Entity/Auction.php
src/Douche/Entity/Auction.php
<?php namespace Douche\Entity; use Douche\Value\Bid; use Douche\Exception\BidTooLowException; use Douche\Exception\AuctionClosedException; use DateTime; use Money\Currency; class Auction { private $id; private $name; private $endingAt; private $currency; protected $bids = []; public function __construct($id, $name, DateTime $endingAt, Currency $currency) { $this->id = $id; $this->name = $name; $this->endingAt = $endingAt; $this->currency = $currency; } public function getId() { return $this->id; } public function getName() { return $this->name; } public function getCurrency() { return $this->currency; } public function getEndingAt() { return $this->endingAt; } public function bid(User $bidder, Bid $bid, \DateTime $now = null) { if (!$this->isRunning($now)) { throw new AuctionClosedException(); } $highestBid = $this->getHighestBid(); if ($highestBid && $bid->getAmount() <= $highestBid->getAmount()) { throw new BidTooLowException(); } $this->bids[] = [$bidder, $bid]; } public function getHighestBid() { list($bidder, $bid) = $this->getHighestBidTuple(); return $bid; } public function getHighestBidder() { list($bidder, $bid) = $this->getHighestBidTuple(); return $bidder; } public function isRunning(\DateTime $now = null) { $now = $now ?: new DateTime(); return $this->endingAt > $now; } private function getHighestBidTuple() { return end($this->bids); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Entity/UserRepository.php
src/Douche/Entity/UserRepository.php
<?php namespace Douche\Entity; interface UserRepository { function find($id); function findOneByEmail($email); function add(User $user); }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Entity/AuctionRepository.php
src/Douche/Entity/AuctionRepository.php
<?php namespace Douche\Entity; interface AuctionRepository { function findAll(); function find($id); }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Storage/File/UserRepository.php
src/Douche/Storage/File/UserRepository.php
<?php namespace Douche\Storage\File; use Douche\Entity\User; use Douche\Entity\UserRepository as UserRepositoryInterface; use Douche\Exception\UserNotFoundException; class UserRepository implements UserRepositoryInterface { private $file; private $users = []; public function __construct($file) { $this->file = $file; $this->users = $this->loadUsers(); } public function find($id) { return $this->findOneByField('id', $id); } public function findOneByEmail($email) { return $this->findOneByField('email', $email); } public function add(User $user) { $this->users[] = $user; } public function save() { $rawUsers = $this->serializeUsers(); $json = json_encode($rawUsers, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); file_put_contents($this->file, $json."\n"); } private function findOneByField($field, $value) { foreach ($this->users as $user) { $getter = 'get'.$field; if ($value === $user->$getter()) { return $user; } } return null; } private function loadUsers() { if (!file_exists($this->file)) { return []; } $rawUsers = json_decode(file_get_contents($this->file), true) ?: []; return array_map( function ($rawUser) { return new User( $rawUser['id'], $rawUser['name'], $rawUser['email'], $rawUser['passwordHash'] ); }, $rawUsers ); } private function serializeUsers() { return array_map( function ($user) { return [ 'id' => $user->getId(), 'name' => $user->getName(), 'email' => $user->getEmail(), 'passwordHash' => $user->getPasswordHash(), ]; }, $this->users ); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Storage/Sql/Util.php
src/Douche/Storage/Sql/Util.php
<?php namespace Douche\Storage\Sql; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Schema\Schema; class Util { public static function createAuctionSchema(Connection $conn) { $sm = $conn->getSchemaManager(); $schema = static::getAuctionSchema(); foreach ($schema->getTables() as $table) { $sm->createTable($table); } } public static function getAuctionSchema() { $schema = new Schema; $auctions = $schema->createTable('auctions'); $auctions->addColumn('id', 'integer'); $auctions->setPrimaryKey(array("id")); $auctions->addColumn('name', 'string'); $auctions->addColumn('ending_at', 'datetime'); $auctions->addColumn('currency', 'string'); $auctionBids = $schema->createTable('auction_bids'); $auctionBids->addColumn('id', 'integer'); $auctionBids->setPrimaryKey(array("id")); $auctionBids->addColumn('auction_id', 'integer'); $auctionBids->addColumn('user_id', 'string'); $auctionBids->addColumn('amount', 'integer'); $auctionBids->addColumn('currency', 'string'); $auctionBids->addColumn('original_amount', 'integer'); $auctionBids->addColumn('original_currency', 'string'); return $schema; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Storage/Sql/AuctionRepository.php
src/Douche/Storage/Sql/AuctionRepository.php
<?php namespace Douche\Storage\Sql; use Doctrine\Dbal\Connection; use Douche\Entity\UserRepository; use Douche\Entity\AuctionRepository as AuctionRepositoryInterface; use Douche\Value\Bid; use Money\Money; use Money\Currency; class AuctionRepository implements AuctionRepositoryInterface { const SELECT_SQL = " SELECT a.id as id, a.name as name, a.ending_at as ending_at, a.currency as currency, ab.id as bid_id, ab.user_id as bid_user_id, ab.amount as bid_amount, ab.currency as bid_currency, ab.original_amount as bid_original_amount, ab.original_currency as bid_original_currency FROM auctions a LEFT JOIN auction_bids ab ON a.id = ab.auction_id "; protected $conn; protected $userRepo; protected $identityMap = []; protected $originalData = []; public function __construct(Connection $conn, UserRepository $userRepo) { $this->conn = $conn; $this->userRepo = $userRepo; } public function findAll() { $rows = $this->conn->fetchAll(static::SELECT_SQL); if (empty($rows)) { return []; } return $this->rowsToAuctions($rows); } public function find($id) { if (isset($this->identityMap[$id])) { return $this->identityMap[$id]; } $rows = $this->conn->fetchAll(static::SELECT_SQL . " WHERE a.id = ?", [$id]); if (empty($rows)) { return null; } $auctions = $this->rowsToAuctions($rows); $first = reset($auctions); return $first; } public function save() { foreach ($this->identityMap as $id => $auction) { if (count($this->originalData[$id]['bids']) === count($auction->getBids())) { continue; } $this->conn->transactional(function () use ($auction) { $this->conn->delete('auction_bids', ['auction_id' => $auction->getId()]); foreach ($auction->getBids() as $tuple) { list($bidder, $bid) = $tuple; $this->conn->insert('auction_bids', [ 'auction_id' => $auction->getId(), 'user_id' => $bidder->getId(), 'amount' => $bid->getAmount()->getAmount(), 'currency' => $bid->getAmount()->getCurrency(), 'original_amount' => $bid->getOriginalAmount()->getAmount(), 'original_currency' => $bid->getOriginalAmount()->getCurrency(), ]); } }); } } protected function rowsToAuctions($rows) { $groupedRows = []; $auctions = []; foreach ($rows as $row) { if (!isset($groupedRows[$row['id']])) { $groupedRows[$row['id']] = []; } $groupedRows[$row['id']][] = $row; } foreach ($groupedRows as $id => $rows) { if (isset($this->identityMap[$id])) { $auctions[] = $this->identityMap[$id]; continue; } $row = reset($rows); $auction = new Entity\Auction( $id, $row['name'], new \DateTime($row['ending_at']), new Currency($row['currency']) ); $this->identityMap[$id] = $auction; $this->originalData[$id] = array( 'auction' => $rows ); $auctions[] = $auction; foreach ($rows as $row) { if (!empty($row['bid_id'])) { $amount = new Money((int) $row['bid_amount'], new Currency($row['bid_currency'])); $originalAmount = new Money((int) $row['bid_original_amount'], new Currency($row['bid_original_currency'])); $bid = new Bid($amount, $originalAmount); /* could look to proxy this */ $bidder = $this->userRepo->find($row['bid_user_id']); $auction->addBid($bidder, $bid); } } $this->originalData[$id]['bids'] = $auction->getBids(); } return $auctions; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Storage/Sql/Entity/Auction.php
src/Douche/Storage/Sql/Entity/Auction.php
<?php namespace Douche\Storage\Sql\Entity; use Douche\Value\Bid; use Douche\Entity\User; use Douche\Entity\Auction as BaseAuction; class Auction extends BaseAuction { public function addBid(User $bidder, Bid $bid) { $this->bids[] = [$bidder, $bid]; } public function getBids() { return $this->bids; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/UserLoginResponse.php
src/Douche/Interactor/UserLoginResponse.php
<?php namespace Douche\Interactor; use Douche\View\UserView; class UserLoginResponse { public $user; public function __construct(UserView $user) { $this->user = $user; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/BidResponse.php
src/Douche/Interactor/BidResponse.php
<?php namespace Douche\Interactor; use Douche\Value\Bid as BidValue; use Douche\Exception\Exception; class BidResponse { public $bid; public function __construct(BidValue $bid) { $this->bid = $bid; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/BidRequest.php
src/Douche/Interactor/BidRequest.php
<?php namespace Douche\Interactor; use Money\Money; class BidRequest { public $auctionId; public $userId; public $amount; public function __construct($auctionId, $userId, Money $amount) { $this->auctionId = $auctionId; $this->userId = $userId; $this->amount = $amount; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/AuctionViewRequest.php
src/Douche/Interactor/AuctionViewRequest.php
<?php namespace Douche\Interactor; class AuctionViewRequest { public $id; public function __construct($id) { $this->id = $id; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/PasswordEncoder.php
src/Douche/Interactor/PasswordEncoder.php
<?php namespace Douche\Interactor; interface PasswordEncoder { function encodePassword($password); function isPasswordValid($encoded, $raw); }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/RegisterUserResponse.php
src/Douche/Interactor/RegisterUserResponse.php
<?php namespace Douche\Interactor; class RegisterUserResponse { public $id; public function __construct($id) { $this->id = $id; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/AuctionList.php
src/Douche/Interactor/AuctionList.php
<?php namespace Douche\Interactor; use Douche\Entity\Auction; use Douche\Entity\AuctionRepository; use Douche\View\AuctionView; class AuctionList { private $repo; public function __construct(AuctionRepository $repo) { $this->repo = $repo; } public function __invoke() { $auctions = $this->repo->findAll(); $auctionViews = array_map("Douche\View\AuctionView::fromEntity", $auctions); return new AuctionListResponse($auctionViews); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/CurrencyConverter.php
src/Douche/Interactor/CurrencyConverter.php
<?php namespace Douche\Interactor; use Money\Currency; use Money\Money; interface CurrencyConverter { /** @return Money */ public function convert(Money $money, Currency $currency); }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/AuctionViewResponse.php
src/Douche/Interactor/AuctionViewResponse.php
<?php namespace Douche\Interactor; use Douche\View\AuctionView as AuctionViewDto; class AuctionViewResponse { public $auction; public function __construct(AuctionViewDto $auction) { $this->auction = $auction; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/RegisterUserRequest.php
src/Douche/Interactor/RegisterUserRequest.php
<?php namespace Douche\Interactor; class RegisterUserRequest { public $id; public $name; public $email; public $password; public function __construct(array $properties) { foreach ($properties as $name => $value) { $this->$name = $value; } } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/AuctionListResponse.php
src/Douche/Interactor/AuctionListResponse.php
<?php namespace Douche\Interactor; class AuctionListResponse { public $auctions; public function __construct(array $auctions) { $this->auctions = $auctions; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/UserLogin.php
src/Douche/Interactor/UserLogin.php
<?php namespace Douche\Interactor; use Douche\View\UserView; use Douche\Entity\UserRepository; use Douche\Exception\IncorrectPasswordException; use Douche\Exception\UserNotFoundException; class UserLogin { private $userRepo; private $passwordEncoder; public function __construct(UserRepository $userRepo, PasswordEncoder $passwordEncoder) { $this->userRepo = $userRepo; $this->passwordEncoder = $passwordEncoder; } public function __invoke(UserLoginRequest $request) { $user = $this->userRepo->findOneByEmail($request->email); if (!$user) { throw new UserNotFoundException($request->email); } if (!$this->passwordEncoder->isPasswordValid($user->getPasswordHash(), $request->password)) { throw new IncorrectPasswordException($request->email); } return new UserLoginResponse(UserView::fromUser($user)); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/Bid.php
src/Douche/Interactor/Bid.php
<?php namespace Douche\Interactor; use Douche\Entity\AuctionRepository; use Douche\Entity\UserRepository; use Douche\Value\Bid as BidValue; use Douche\View\AuctionView as AuctionViewDto; use Douche\Exception\AuctionClosedException; class Bid { private $auctionRepo; private $userRepo; private $converter; public function __construct(AuctionRepository $auctionRepo, UserRepository $userRepo, CurrencyConverter $converter) { $this->auctionRepo = $auctionRepo; $this->userRepo = $userRepo; $this->converter = $converter; } public function __invoke(BidRequest $request) { $auction = $this->auctionRepo->find($request->auctionId); $user = $this->userRepo->find($request->userId); $converted = $this->converter->convert($request->amount, $auction->getCurrency()); $bid = new BidValue($converted, $request->amount); $auction->bid($user, $bid); return new BidResponse($bid); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/UserLoginRequest.php
src/Douche/Interactor/UserLoginRequest.php
<?php namespace Douche\Interactor; class UserLoginRequest { public $email; public $password; public function __construct(array $data) { foreach ($data as $key => $value) { $this->$key = $value; } } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/RegisterUser.php
src/Douche/Interactor/RegisterUser.php
<?php namespace Douche\Interactor; use Douche\Entity\User; use Douche\Entity\UserRepository; class RegisterUser { private $userRepo; public function __construct(UserRepository $userRepo, PasswordEncoder $passwordEncoder) { $this->userRepo = $userRepo; $this->passwordEncoder = $passwordEncoder; } public function __invoke(RegisterUserRequest $request) { $passwordHash = $this->passwordEncoder->encodePassword($request->password); $user = new User($request->id, $request->name, $request->email, $passwordHash); $this->userRepo->add($user); return new RegisterUserResponse($user->getId()); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Interactor/AuctionView.php
src/Douche/Interactor/AuctionView.php
<?php namespace Douche\Interactor; use Douche\Entity\AuctionRepository; use Douche\View\AuctionView as AuctionViewDto; class AuctionView { private $repo; public function __construct(AuctionRepository $repo) { $this->repo = $repo; } public function __invoke(AuctionViewRequest $request) { $auction = $this->repo->find($request->id); $view = AuctionViewDto::fromEntity($auction); return new AuctionViewResponse($view); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Value/Bid.php
src/Douche/Value/Bid.php
<?php namespace Douche\Value; use Money\Money; class Bid { private $amount; private $originalAmount; public function __construct(Money $amount, Money $originalAmount) { $this->amount = $amount; $this->originalAmount = $originalAmount; } public function getAmount() { return $this->amount; } public function getOriginalAmount() { return $this->originalAmount; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Exception/AuctionClosedException.php
src/Douche/Exception/AuctionClosedException.php
<?php namespace Douche\Exception; class AuctionClosedException extends BidRejectedException { }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Exception/BidTooLowException.php
src/Douche/Exception/BidTooLowException.php
<?php namespace Douche\Exception; class BidTooLowException extends BidRejectedException { }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Exception/UserNotFoundException.php
src/Douche/Exception/UserNotFoundException.php
<?php namespace Douche\Exception; class UserNotFoundException extends Exception { public $email; public function __construct($email) { parent::__construct(); $this->email = $email; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Exception/IncorrectPasswordException.php
src/Douche/Exception/IncorrectPasswordException.php
<?php namespace Douche\Exception; class IncorrectPasswordException extends Exception { public $email; public function __construct($email) { parent::__construct(); $this->email = $email; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Exception/Exception.php
src/Douche/Exception/Exception.php
<?php namespace Douche\Exception; use Exception as BaseException; class Exception extends BaseException { }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Exception/BidRejectedException.php
src/Douche/Exception/BidRejectedException.php
<?php namespace Douche\Exception; class BidRejectedException extends Exception { }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Repository/AuctionArrayRepository.php
src/Douche/Repository/AuctionArrayRepository.php
<?php namespace Douche\Repository; use Douche\Entity\AuctionRepository; class AuctionArrayRepository implements AuctionRepository { private $auctions; public function __construct(array $auctions) { $this->auctions = $auctions; } public function findAll() { return $this->auctions; } public function find($id) { foreach($this->auctions as $auction) { if ($auction->getId() === $id) { return $auction; } } return null; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Repository/UserArrayRepository.php
src/Douche/Repository/UserArrayRepository.php
<?php namespace Douche\Repository; use Douche\Entity\User; use Douche\Entity\UserRepository; class UserArrayRepository implements UserRepository { private $users; public function __construct(array $users) { $this->users = $users; } public function find($id) { foreach ($this->users as $user) { if ($user->getId() === $id) { return $user; } } return null; } public function findOneByEmail($email) { foreach ($this->users as $user) { if ($user->getEmail() === $email) { return $user; } } return null; } public function add(User $user) { if (null !== $this->find($user->getId())) { throw new \InvalidArgumentException('User already exists'); } $this->users[] = $user; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Service/UppercasePasswordEncoder.php
src/Douche/Service/UppercasePasswordEncoder.php
<?php namespace Douche\Service; use Douche\Interactor\PasswordEncoder; class UppercasePasswordEncoder implements PasswordEncoder { public function encodePassword($password) { return strtoupper($password); } public function isPasswordValid($encoded, $raw) { return $encoded === $this->encodePassword($raw); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Service/PairCurrencyConverter.php
src/Douche/Service/PairCurrencyConverter.php
<?php namespace Douche\Service; use Douche\Interactor\CurrencyConverter; use Money\Money; use Money\Currency; use Money\CurrencyPair; class PairCurrencyConverter implements CurrencyConverter { private $pairs; public function __construct(array $pairs) { $this->pairs = $pairs; } public function convert(Money $money, Currency $currency) { $pair = $this->findPair($money->getCurrency(), $currency); return $pair->convert($money); } private function findPair(Currency $counterCurrency, Currency $baseCurrency) { if ($counterCurrency->equals($baseCurrency)) { return new CurrencyPair($baseCurrency, $counterCurrency, 1.0); } foreach ($this->pairs as $pair) { if ($counterCurrency == $pair->getCounterCurrency() && $baseCurrency == $pair->getBaseCurrency()) { return $pair; } } throw new \RuntimeException( sprintf('No pair found for currencies %s and %s.', $counterCurrency, $baseCurrency)); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/Service/DumbCurrencyConverter.php
src/Douche/Service/DumbCurrencyConverter.php
<?php namespace Douche\Service; use Douche\Interactor\CurrencyConverter; use Money\Money; use Money\Currency; class DumbCurrencyConverter implements CurrencyConverter { public function convert(Money $money, Currency $currency) { return new Money($money->getAmount(), $currency); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/View/UserView.php
src/Douche/View/UserView.php
<?php namespace Douche\View; use Douche\Entity\User; class UserView { public $id; public $name; public $email; public function __construct(array $attributes = array()) { foreach ($attributes as $name => $value) { $this->$name = $value; } } public static function fromUser(User $user) { return new static([ 'id' => $user->getId(), 'email' => $user->getEmail(), 'name' => $user->getName(), ]); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/src/Douche/View/AuctionView.php
src/Douche/View/AuctionView.php
<?php namespace Douche\View; use Douche\Entity\Auction; class AuctionView { public $id; public $name; public $highestBid; public $highestBidder; public $isRunning; public $endingAt; public function __construct(array $attributes = array()) { foreach ($attributes as $name => $value) { $this->$name = $value; } } public static function fromEntity(Auction $auction) { return new static([ 'id' => $auction->getId(), 'name' => $auction->getName(), 'highestBid' => $auction->getHighestBid(), 'highestBidder' => $auction->getHighestBidder() ? $auction->getHighestBidder()->getId() : null, 'isRunning' => $auction->isRunning(), 'endingAt' => $auction->getEndingAt(), ]); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/tests/integration/Douche/Storage/Sql/SqlTestCase.php
tests/integration/Douche/Storage/Sql/SqlTestCase.php
<?php namespace tests\integration\Douche\Storage\Sql; use Doctrine\DBAL\Schema\Table; use Douche\Storage\Sql\Util; class SqlTestCase extends \PHPUnit_Framework_TestCase { protected $conn; public function setup() { $params = [ 'driver' => 'pdo_sqlite', 'memory' => true, ]; $this->conn = \Doctrine\DBAL\DriverManager::getConnection($params); Util::createAuctionSchema($this->conn); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/tests/integration/Douche/Storage/Sql/AuctionRepositoryTest.php
tests/integration/Douche/Storage/Sql/AuctionRepositoryTest.php
<?php namespace tests\integration\Douche\Storage\Sql; use Douche\Storage\Sql\AuctionRepository; use Douche\Repository\UserArrayRepository; use Douche\Entity\User; use Douche\Value\Bid; use Money\Money; use Money\Currency; class AuctionRepositoryTest extends SqlTestCase { public function setUp() { parent::setUp(); $this->repo = new AuctionRepository( $this->conn, $this->userRepo = new UserArrayRepository([]) ); } /** @test */ public function findShouldReturnAnExistingAuction() { $this->createAuction(); $this->createAuction(); $id = $this->createAuction([ 'name' => 'Dave', 'ending_at' => '2011-10-10 10:10:10', 'currency' => 'GBP', ]); $auction = $this->repo->find($id); $this->assertInstanceOf("Douche\Entity\Auction", $auction); $this->assertEquals($id, $auction->getId()); $this->assertEquals('Dave', $auction->getName()); $this->assertEquals(new Currency('GBP'), $auction->getCurrency()); } /** @test */ public function findShouldJoinBids() { $this->createAuction(); $this->createAuction(); $userId = $this->createUser(); $id = $this->createAuction([ 'name' => 'Dave', 'ending_at' => '2011-10-10 10:10:10', 'currency' => 'GBP', 'bids' => [ [ 'amount' => 200, 'currency' => 'GBP', 'original_amount' => 600, 'original_currency' => 'USD', ], [ 'amount' => 300, 'currency' => 'GBP', 'original_amount' => 900, 'original_currency' => 'USD', 'user_id' => $userId, ], ] ]); $auction = $this->repo->find($id); $bid = $auction->getHighestBid(); $this->assertInstanceOf("Douche\Value\Bid", $bid); $this->assertEquals(300, $bid->getAmount()->getAmount()); $this->assertEquals(new Currency('GBP'), $bid->getAmount()->getCurrency()); $bidder = $auction->getHighestBidder(); $this->assertInstanceOf("Douche\Entity\User", $bidder); $this->assertEquals($userId, $bidder->getId()); } /** @test */ public function saveShouldInsertTheFirstBid() { $id = $this->createAuction(["bids" => []]); $auction = $this->repo->find($id); $userId = $this->createUser(); $user = $this->userRepo->find($userId); $auction->bid($user, new Bid( new Money(300, new Currency('GBP')), new Money(900, new Currency('USD')) )); $this->repo->save(); $expected = [ 'user_id' => $userId, 'amount' => '300', 'currency' => 'GBP', 'original_amount' => '900', 'original_currency' => 'USD', ]; $bids = $this->conn->fetchAll("SELECT user_id, amount, currency, original_amount, original_currency FROM auction_bids WHERE auction_id = ? ORDER BY amount ASC", [$id]); $this->assertEquals(1, count($bids)); $this->assertEquals($expected, $bids[0]); } /** @test */ public function saveShouldInsertAnyNewBids() { $id = $this->createAuction([ 'bids' => [ [ 'amount' => 200, 'currency' => 'GBP', 'original_amount' => 600, 'original_currency' => 'USD', ], ] ]); $auction = $this->repo->find($id); $userId = $this->createUser(); $user = $this->userRepo->find($userId); $auction->bid($user, new Bid( new Money(300, new Currency('GBP')), new Money(900, new Currency('USD')) )); $this->repo->save(); $expected = [ 'user_id' => $userId, 'amount' => '300', 'currency' => 'GBP', 'original_amount' => '900', 'original_currency' => 'USD', ]; $bids = $this->conn->fetchAll("SELECT user_id, amount, currency, original_amount, original_currency FROM auction_bids WHERE auction_id = ? ORDER BY amount ASC", [$id]); $this->assertEquals(2, count($bids)); $this->assertEquals($expected, $bids[1]); } /** @test */ public function findShouldReturnNullOnEmptyRepo() { $this->assertNull($this->repo->find(123)); } /** @test */ public function findShouldReturnNullForUnkownId() { $id = $this->createAuction(); $this->assertNull($this->repo->find($id + 123)); } /** @test */ public function findAllShouldReturnAnEmptyArrayForAnEmptyRepo() { $this->assertEquals([], $this->repo->findAll()); } /** @test */ public function findAllShouldReturnArrayOfAuctionsIfExistingAuctions() { $this->createAuction(); $this->createAuction(); $auctions = $this->repo->findAll(); $this->assertInternalType("array", $auctions); foreach ($auctions as $auction) { $this->assertInstanceOf("Douche\Entity\Auction", $auction); } } protected function createAuction(array $data = []) { $data = array_merge([ 'name' => uniqid(), 'ending_at' => (new \DateTime("+3 days"))->format("Y-m-d H:i:s"), 'currency' => 'USD', 'bids' => [ [ 'amount' => 2000, 'currency' => 'GBP', 'original_amount' => 6000000, 'original_currency' => 'USD', ], ] ], $data); $bids = $data['bids']; unset($data['bids']); $this->conn->insert('auctions', $data); $id = $this->conn->lastInsertId(); foreach ($bids as $bid) { if (!isset($bid['user_id'])) { $bid['user_id'] = $this->createUser(); } $bid['auction_id'] = $id; $this->conn->insert('auction_bids', $bid); } return $id; } protected function createUser(array $data = array()) { $name = isset($data['name']) ? $data['name'] : uniqid(); $email = isset($data['email']) ? $data['email'] : uniqid(); $passwordHash = isset($data['passwordHash']) ? $data['passwordHash'] : uniqid(); $id = isset($data['id']) ? $data['id'] : uniqid(); $user = new User($id, $name, $email, $passwordHash); $this->userRepo->add($user); return $id; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/tests/unit/DoucheWeb/ControllerResolverTest.php
tests/unit/DoucheWeb/ControllerResolverTest.php
<?php namespace tests\unit\DoucheWeb; use Phake; use DoucheWeb\ControllerResolver; use Pimple; use Symfony\Component\HttpFoundation\Request; class ControllerResolverTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->decoratedResolver = Phake::mock("Symfony\Component\HttpKernel\Controller\ControllerResolverInterface"); $this->container = new Pimple(); $this->resolver = new ControllerResolver($this->decoratedResolver, $this->container); } /** @test */ public function getControllerShouldReturnService() { $this->container['my_callable_controller'] = $this->container->protect(function () {}); $request = Request::create("/"); $request->attributes->set('_controller', "my_callable_controller"); $controller = $this->resolver->getController($request); $this->assertSame($this->container['my_callable_controller'], $controller); } /** @test */ public function getControllerShouldDeferIfControllerNotAString() { $request = Request::create("/"); $request->attributes->set('_controller', function () {}); $this->resolver->getController($request); Phake::verify($this->decoratedResolver)->getController($request); } /** @test */ public function getControllerShouldDeferIfControllerIsStringButNotInApp() { $request = Request::create("/"); $request->attributes->set('_controller', "non_existant_service"); $this->resolver->getController($request); Phake::verify($this->decoratedResolver)->getController($request); } /** * @test * @expectedException InvalidArgumentException * @expectedExceptionMessage Service "my_string" is not callable. */ public function getControllerShouldThrowIfServiceNotCallable() { $this->container['my_string'] = "dave"; $request = Request::create("/"); $request->attributes->set('_controller', "my_string"); $this->resolver->getController($request); } /** @test */ public function getArgumentsShouldDeferToDecoratedResolver() { $request = Request::create("/"); $this->resolver->getArguments($request, $controller = function () {}); Phake::verify($this->decoratedResolver)->getArguments($request, $controller); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/tests/unit/Douche/Entity/AuctionTest.php
tests/unit/Douche/Entity/AuctionTest.php
<?php namespace Douche\Entity; use Money\Money; use Money\Currency; use Douche\Value\Bid; class AuctionTest extends \PHPUnit_Framework_TestCase { private $now; public function setUp() { $this->now = new \DateTime('2012-03-02'); } /** @test */ public function bidShouldAddBidToAuction() { $auction = new Auction(1, 'YOLO Glasses', new \DateTime('2012-03-04'), new Currency('GBP')); $bidder = new User(42, 'John Doe', 'john.doe@example.com', 'foo'); $bid = new Bid(Money::GBP(200), Money::GBP(200)); $auction->bid($bidder, $bid, $this->now); $this->assertEquals($bid, $auction->getHighestBid()); $this->assertEquals($bidder, $auction->getHighestBidder()); return $auction; } /** * @test * @depends bidShouldAddBidToAuction */ public function higherBidShouldOverrideOldOne(Auction $auction) { $bidder = new User(43, 'Jane Doe', 'jane.doe@example.com', 'bar'); $bid = new Bid(Money::GBP(205), Money::GBP(205)); $auction->bid($bidder, $bid, $this->now); $this->assertEquals($bid, $auction->getHighestBid()); $this->assertEquals($bidder, $auction->getHighestBidder()); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/tests/unit/Douche/Storage/File/UserRepositoryTest.php
tests/unit/Douche/Storage/File/UserRepositoryTest.php
<?php namespace Douche\Storage\File; use Douche\Entity\User; class UserRepositoryTest extends \PHPUnit_Framework_TestCase { /** @test */ public function findOnEmptyRepoShouldReturnNull() { $repo = new UserRepository(__DIR__.'/Fixtures/non_existent.json'); $user = $repo->find('missing'); $this->assertNull($user); } /** @test */ public function findShouldReturnNullOnMissingUser() { $repo = new UserRepository(__DIR__.'/Fixtures/users.json'); $user = $repo->find('missing'); $this->assertNull($user); } /** @test */ public function findShouldReturnExistingUser() { $repo = new UserRepository(__DIR__.'/Fixtures/users.json'); $user = $repo->find('igorw'); $expectedUser = new User('igorw', 'Igor Wiedler', 'igor@wiedler.ch', 'FOOBAR'); $this->assertEquals($expectedUser, $user); } /** @test */ public function findOneByEmailShouldReturnNullOnMissingUser() { $repo = new UserRepository(__DIR__.'/Fixtures/users.json'); $user = $repo->findOneByEmail('john.doe@example.com'); $this->assertNull($user); } /** @test */ public function findOneByEmailShouldReturnExistingUser() { $repo = new UserRepository(__DIR__.'/Fixtures/users.json'); $user = $repo->findOneByEmail('igor@wiedler.ch'); $expectedUser = new User('igorw', 'Igor Wiedler', 'igor@wiedler.ch', 'FOOBAR'); $this->assertEquals($expectedUser, $user); } /** @test */ public function addShouldAddUserInMemory() { $repo = new UserRepository(__DIR__.'/Fixtures/users.json'); $john = new User('johndoe', 'John Doe', 'john.doe@example.com', 'BARFOO'); $repo->add($john); $this->assertEquals($john, $repo->find('johndoe')); } /** @test */ public function saveShouldStoreChangesInFile() { $file = tempnam(sys_get_temp_dir(), 'doucheswag_test_'); $repo = new UserRepository($file); $john = new User('johndoe', 'John Doe', 'john.doe@example.com', 'BARFOO'); $repo->add($john); $repo->save(); $repo = new UserRepository($file); $this->assertEquals($john, $repo->find('johndoe')); unlink($file); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/tests/unit/Douche/Interactor/UserLoginTest.php
tests/unit/Douche/Interactor/UserLoginTest.php
<?php namespace Douche\Interactor; use Douche\Interactor\UserLogin; use Douche\Interactor\UserLoginRequest; use Douche\Interactor\UserLoginResponse; use Douche\Entity\User; use Phake; class UserLoginTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->userRepo = Phake::mock('Douche\Entity\UserRepository'); $this->passwordEncoder = Phake::mock('Douche\Interactor\PasswordEncoder'); $this->interactor = new UserLogin($this->userRepo, $this->passwordEncoder); Phake::when($this->userRepo)->findOneByEmail('dave@example.com')->thenReturn( $this->sampleUser = new User('dave', 'Dave', 'dave@example.com', 'encoded password') ); Phake::when($this->passwordEncoder)->isPasswordValid( $this->sampleUser->getPasswordHash(), $this->correctPassword = 'password' )->thenReturn(true); } /** @test */ public function shouldReturnUserLoginResponse() { $request = new UserLoginRequest([ 'email' => $this->sampleUser->getEmail(), 'password' => $this->correctPassword, ]); $response = call_user_func($this->interactor, $request); $this->assertInstanceOf("Douche\Interactor\UserLoginResponse", $response); } /** @test */ public function shouldIncludeUserInUserLoginResponse() { $request = new UserLoginRequest([ 'email' => $this->sampleUser->getEmail(), 'password' => $this->correctPassword, ]); $response = call_user_func($this->interactor, $request); $this->assertInstanceOf("Douche\View\UserView", $response->user); } /** * @test * @expectedException Douche\Exception\IncorrectPasswordException */ public function shouldThrowOnIncorrectPassword() { $request = new UserLoginRequest([ 'email' => $this->sampleUser->getEmail(), 'password' => "Some wrong password", ]); $response = call_user_func($this->interactor, $request); } /** * @test * @expectedException Douche\Exception\UserNotFoundException */ public function shouldThrowIfUserNotFound() { $request = new UserLoginRequest([ 'email' => 'unknown@example.com', 'password' => $this->correctPassword, ]); $response = call_user_func($this->interactor, $request); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/tests/unit/Douche/Service/UppercasePasswordEncoderTest.php
tests/unit/Douche/Service/UppercasePasswordEncoderTest.php
<?php namespace Douche\Service; class UppercasePasswordEncoderTest extends \PHPUnit_Framework_TestCase { /** @test */ public function shouldValidateRawPasswordAgainstEncodedPassword() { $encoder = new UppercasePasswordEncoder(); $this->assertTrue($encoder->isPasswordValid('DAVE', 'dave')); $this->assertFalse($encoder->isPasswordValid('DAVasE', 'dave')); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/tests/unit/Douche/Service/DumbCurrencyConverterTest.php
tests/unit/Douche/Service/DumbCurrencyConverterTest.php
<?php namespace Douche\Service; use Money\Money; use Money\Currency; class DumbCurrencyConverterTest extends \PHPUnit_Framework_TestCase { /** @test */ public function convertShouldLeaveAmountUntouched() { $converter = new DumbCurrencyConverter(); $chf = Money::CHF(100); $gbp = $converter->convert($chf, new Currency('GBP')); $this->assertEquals(Money::GBP(100), $gbp); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/tests/unit/Douche/Service/PairCurrencyConverterTest.php
tests/unit/Douche/Service/PairCurrencyConverterTest.php
<?php namespace Douche\Service; use Money\Money; use Money\Currency; use Money\CurrencyPair; class PairCurrencyConverterTest extends \PHPUnit_Framework_TestCase { /** * @test * @expectedException RuntimeException */ public function convertWithoutCurrenciesShouldFail() { $converter = new PairCurrencyConverter([]); $eur = Money::EUR(100); $converter->convert($eur, new Currency('USD')); } /** * @test * @expectedException RuntimeException */ public function convertWithWrongCurrencyShouldFail() { $converter = new PairCurrencyConverter([ CurrencyPair::createFromIso('EUR/CHF 1.2500'), ]); $eur = Money::EUR(100); $converter->convert($eur, new Currency('USD')); } /** @test */ public function convertShouldUseSuppliedCurrencyPair() { $converter = new PairCurrencyConverter([ CurrencyPair::createFromIso('EUR/USD 1.2500'), ]); $eur = Money::EUR(100); $usd = $converter->convert($eur, new Currency('USD')); $this->assertEquals(Money::USD(125), $usd); } /** @test */ public function convertShouldConvertToSameCurrency() { $converter = new PairCurrencyConverter([]); $eur = Money::EUR(100); $converted = $converter->convert($eur, new Currency('EUR')); $this->assertEquals(Money::EUR(100), $converted); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/features/bootstrap/AuctionHelper.php
features/bootstrap/AuctionHelper.php
<?php use Douche\Entity\Auction; use Douche\Entity\User; use Douche\Entity\UserRepository; use Douche\Interactor\AuctionList; use Douche\Interactor\AuctionView as AuctionViewInteractor; use Douche\Interactor\AuctionViewRequest; use Douche\Interactor\Bid as BidInteractor; use Douche\Interactor\BidRequest; use Douche\Repository\AuctionArrayRepository; use Douche\Value\Bid as BidValue; use Douche\View\AuctionView; use Douche\Exception\Exception as DoucheException; use Douche\Service\DumbCurrencyConverter; use Money\Money; use Money\Currency; require_once 'vendor/phpunit/phpunit/PHPUnit/Framework/Assert/Functions.php'; class AuctionHelper { protected $auctionRepo; protected $userHelper; protected $auctions = array(); protected $auction; protected $response; public function __construct(UserHelper $userHelper) { $this->userHelper = $userHelper; } public function createAuction($name, $endingAt = null) { $endingAt = $endingAt ?: new \DateTime("+10 days"); $this->auctions[] = $auction = new Auction(count($this->auctions) + 1, $name, $endingAt, new Currency("USD")); $this->auction = $auction; } public function truncateAuctions() { $this->auctions = array(); $this->auctionRepo = null; } public function listAuctions() { $interactor = new AuctionList($this->getAuctionRepository()); $this->response = $interactor(); } public function viewAuction() { $interactor = new AuctionViewInteractor($this->getAuctionRepository()); $request = new AuctionViewRequest($this->auction->getId()); $this->response = $interactor($request); } public function placeBidWithAlternateCurrency($amount, $userId = null) { return $this->placeBid($amount, $userId, new Currency("GBP")); } public function placeBid($amount, Currency $currency = null) { $userId = $this->getUserHelper()->getCurrentUserId(); if ($userId == null) { $userId = $this->getUserHelper()->createUser(); } $interactor = new BidInteractor( $this->getAuctionRepository(), $this->getUserHelper()->getUserRepository(), new DumbCurrencyConverter() ); $amount = new Money(intval($amount * 100), $currency ?: $this->auction->getCurrency()); $request = new BidRequest($this->auction->getId(), $userId, $amount); try { $this->response = $interactor($request); } catch (DoucheException $e) { $this->response = $e; } } public function assertAuctionPresent() { assertInstanceOf("Douche\View\AuctionView", $this->response->auction); } public function assertNoRunningAuctions() { assertEquals(0, count($this->response->auctions)); } public function assertSomeRunningAuctions() { assertGreaterThan(0, count($this->response->auctions)); } public function assertBidAccepted() { assertInstanceOf("Douche\Interactor\BidResponse", $this->response); } public function assertBidAcceptedWithCurrencyConversion() { assertInstanceOf("Douche\Interactor\BidResponse", $this->response); assertNotSame( $this->response->bid->getAmount(), $this->response->bid->getOriginalAmount() ); } public function assertBidRejected() { assertInstanceOf("Douche\Exception\BidRejectedException", $this->response); } public function assertBiddingNotOffered() { assertFalse($this->response->auction->isRunning); } protected function getUserHelper() { return $this->userHelper; } protected function getAuctionRepository() { $this->auctionRepo = $this->auctionRepo ?: new AuctionArrayRepository($this->auctions); return $this->auctionRepo; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/features/bootstrap/EndToEndUserHelper.php
features/bootstrap/EndToEndUserHelper.php
<?php use Behat\Mink\Mink; use Douche\Entity\UserRepository; require_once __DIR__.'/UserHelper.php'; class EndToEndUserHelper extends UserHelper { public function __construct(UserRepository $userRepo, Mink $mink) { parent::__construct($userRepo); $this->mink = $mink; } public function login() { $this->mink->getSession()->visit("/login"); $page = $this->mink->getSession()->getPage(); $page->fillField('email', $this->getUser()->getEmail()); $page->fillField('password', $this->userPassword); $page->pressButton("Login"); } public function assertSuccessfulLogin() { $this->mink->assertSession()->statusCodeEquals(200); $this->mink->assertSession()->pageTextContains("Logged in as: " . $this->getUser()->getId()); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/features/bootstrap/UserHelper.php
features/bootstrap/UserHelper.php
<?php use Douche\Entity\UserRepository; use Douche\Entity\User; use Douche\Interactor\RegisterUser; use Douche\Interactor\RegisterUserRequest; use Douche\Interactor\UserLogin; use Douche\Interactor\UserLoginRequest; use Douche\Service\UppercasePasswordEncoder; require_once 'vendor/phpunit/phpunit/PHPUnit/Framework/Assert/Functions.php'; class UserHelper { private $userRepo; private $passwordEncoder; private $response; private $user; public function __construct(UserRepository $userRepo) { $this->userRepo = $userRepo; } public function registerUserAccount(array $userData) { $interactor = new RegisterUser($this->getUserRepository(), $this->getPasswordEncoder()); $request = new RegisterUserRequest($userData); $this->response = $interactor($request); } public function assertUserCreated($userId) { assertInstanceOf("Douche\Interactor\RegisterUserResponse", $this->response); assertSame($userId, $this->response->id); assertNotNull($this->userRepo->find($userId)); } public function createUser() { $this->userPassword = 'password'; $user = new User(uniqid(), uniqid(), uniqid().'@'.uniqid().'.com', $this->getPasswordEncoder()->encodePassword($this->userPassword)); $this->user = $user; $this->getUserRepository()->add($user); return $user->getId(); } public function getCurrentUserId() { return isset($this->user) ? $this->user->getId() : null; } public function iAmAnonymous() { $this->user = null; } public function getUserRepository() { return $this->userRepo; } public function login() { $request = new UserLoginRequest([ 'email' => $this->user->getEmail(), 'password' => $this->userPassword, ]); $interactor = new UserLogin($this->getUserRepository(), $this->getPasswordEncoder()); $this->response = $interactor($request); } public function assertSuccessfulLogin() { assertInstanceOf("Douche\Interactor\UserLoginResponse", $this->response); assertSame($this->user->getId(), $this->response->user->id); } protected function getUser() { return $this->user; } private function getPasswordEncoder() { $this->passwordEncoder = $this->passwordEncoder ?: new UppercasePasswordEncoder(); return $this->passwordEncoder; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/features/bootstrap/EndToEndAuctionHelper.php
features/bootstrap/EndToEndAuctionHelper.php
<?php use Doctrine\DBAL\Connection; use Behat\Mink\Mink; require_once 'vendor/phpunit/phpunit/PHPUnit/Framework/Assert/Functions.php'; class EndToEndAuctionHelper { protected $userHelper; protected $conn; protected $mink; protected $auctionId; public function __construct(UserHelper $userHelper, Connection $conn, Mink $mink) { $this->userHelper = $userHelper; $this->conn = $conn; $this->mink = $mink; } public function createAuction($name, $endingAt = null) { $endingAt = $endingAt ?: new \DateTime("+10 days"); $this->conn->insert('auctions', [ 'name' => $name, 'ending_at' => $endingAt->format("Y-m-d H:i:s"), 'currency' => 'USD', ]); $this->auctionId = $this->conn->lastInsertId(); $this->auctionName = $name; } public function truncateAuctions() { $this->conn->query("TRUNCATE auctions"); } public function viewAuction() { $this->mink->getSession()->visit("/auction/" . $this->auctionId); } public function assertAuctionPresent() { $this->mink->assertSession()->statusCodeEquals(200); $this->mink->assertSession()->pageTextContains($this->auctionName); } public function placeBid($amount, Currency $currency = null) { $page = $this->mink->getSession()->getPage(); $page->fillField('amount', $amount); if ($currency) { $page->selectOption('currency', $currency->getName()); } $page->pressButton("Place Bid"); } public function assertBidAccepted() { $this->assertAuctionPresent(); $this->mink->assertSession()->pageTextContains( "Highest Bidder: " . $this->getUserHelper()->getCurrentUserId() ); } public function assertBiddingNotOffered() { $this->assertAuctionPresent(); $this->mink->assertSession()->elementNotExists('css', 'form#place_bid'); } protected function getUserHelper() { return $this->userHelper; } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/features/bootstrap/FeatureContext.php
features/bootstrap/FeatureContext.php
<?php use Behat\Behat\Context\ClosuredContextInterface, Behat\Behat\Context\TranslatedContextInterface, Behat\Behat\Context\BehatContext, Behat\Behat\Exception\PendingException; use Behat\Gherkin\Node\PyStringNode, Behat\Gherkin\Node\TableNode; use Symfony\Component\HttpKernel\Client; use Behat\Mink\Mink; use Behat\Mink\Session; use Behat\Mink\Driver\BrowserKitDriver; use Douche\Entity\Auction; use Douche\Entity\User; use Douche\Interactor\AuctionList; use Douche\Interactor\AuctionListResponse; use Douche\Repository\AuctionArrayRepository; use Douche\Repository\UserArrayRepository; use Douche\View\AuctionView; require_once 'vendor/phpunit/phpunit/PHPUnit/Framework/Assert/Functions.php'; class FeatureContext extends BehatContext { protected $parameters; public function __construct(array $parameters) { $this->parameters = $parameters; } /** * @BeforeScenario */ public function bootstrapHelpers($event) { $node = $event instanceof OutlineEvent ? $event->getOutline() : $event->getScenario(); if ($this->parameters['boundary'] == 'http' && $node->hasTag('end-to-end-available')) { $this->bootstrapEndToEndHelpers(); return; } $this->users = [ 'igorw' => new User('igorw', 'Igor Wiedler', 'igor@wiedler.ch', 'BAR'), ]; $this->rawUsers = [ 'davedevelopment' => [ 'id' => 'davedevelopment', 'name' => 'Dave Marshall', 'email' => 'dave.marshall@atstsolutions.co.uk', 'password' => 'foo', ], ]; $this->userRepository = new UserArrayRepository(array_values($this->users)); $this->userHelper = new UserHelper($this->userRepository); $this->auctionHelper = new AuctionHelper($this->userHelper); } protected function bootstrapEndToEndHelpers() { $app = require __DIR__."/../../src/DoucheWeb/app.php"; $app->register(new Igorw\Silex\ConfigServiceProvider(__DIR__."/../../config/test.json", [ 'storage_path' => __DIR__.'/../../storage', 'template_path' => __DIR__.'/../../src/DoucheWeb/views', ])); $mink = new Mink(array( 'browserkit' => new Session(new BrowserKitDriver(new Client($app))), )); $mink->setDefaultSessionName('browserkit'); if (isset($app['db']->getParams()['memory'])) { \Douche\Storage\Sql\Util::createAuctionSchema($app['db']); } $this->userHelper = new EndToEndUserHelper($app['douche.user_repo'], $mink); $this->auctionHelper = new EndToEndAuctionHelper($this->userHelper, $app['db'], $mink); } /** * @Given /^there are no running auctions$/ */ public function thereAreNoRunningAuctions() { $this->auctionHelper->truncateAuctions(); } /** * @When /^I list the running auctions$/ */ public function iListTheRunningAuctions() { $this->auctionHelper->listAuctions(); } /** * @Then /^I should see no running auctions$/ */ public function iShouldSeeNoRunningAuctions() { $this->auctionHelper->assertNoRunningAuctions(); } /** * @Given /^there are some running auctions$/ */ public function thereAreSomeRunningAuctions() { $this->auctionHelper->createAuction("Swag Hat"); } /** * @Then /^I should see some running auctions$/ */ public function iShouldSeeSomeRunningAuctions() { $this->auctionHelper->assertSomeRunningAuctions(); } /** * @Given /^there is a (closed|running) auction$/ */ public function thereIsAAuction($status) { $endingAt = $status == 'closed' ? new \DateTime("-1 days") : null; $this->auctionHelper->createAuction("Swag Scarf", $endingAt); } /** * @When /^I view the running auction$/ */ public function iViewTheRunningAuction() { $this->auctionHelper->viewAuction(); } /** * @Then /^I should see the running auction$/ */ public function iShouldSeeTheRunningAuction() { $this->auctionHelper->assertAuctionPresent(); } /** * @Given /^I am a registered user$/ */ public function iAmARegisteredUser() { $this->userHelper->createUser(); } /** * @Given /^I am viewing the auction$/ */ public function iAmViewingTheAuction() { $this->auctionHelper->viewAuction(); } /** * @When /^I place a bid on the(?:| running) auction$/ */ public function iPlaceABidOnTheRunningAuction() { $this->auctionHelper->placeBid(1.0); } /** * @When /^I place a bid on the running auction in a different currency$/ */ public function iPlaceABidOnTheRunningAuctionInADifferentCurrency() { $this->auctionHelper->placeBidWithAlternateCurrency(1.0); } /** * @When /^I place a bid of "([^"]+)" on the auction$/ */ public function iPlaceABidOfXXXOnTheRunningAuction($amount) { $this->auctionHelper->placeBid($amount); } /** * @Then /^I should see my bid is accepted$/ */ public function iShouldSeeMyBidIsAccepted() { $this->auctionHelper->assertBidAccepted(); } /** * @Then /^I should see my bid is rejected$/ */ public function iShouldSeeMyBidIsRejected() { $this->auctionHelper->assertBidRejected(); } /** * @Given /^the auction has a high bid of "([^"]*)"$/ */ public function theAuctionHasAHighBidOf($amount) { $this->auctionHelper->placeBid($amount); } /** * @Given /^I should see the amount placed in the auction currency$/ */ public function iShouldSeeTheAmountPlacedInTheAuctionCurrency() { $this->auctionHelper->assertBidAcceptedWithCurrencyConversion(); } /** * @Given /^I am an anonymous user$/ */ public function iAmAnAnonymousUser() { $this->userHelper->iAmAnonymous(); } /** * @When /^I register a new user account as "([^"]*)"$/ */ public function iRegisterANewUserAccount($userId) { $userData = $this->rawUsers[$userId]; $this->userHelper->registerUserAccount($userData); } /** * @Then /^I should see my account "([^"]*)" was created$/ */ public function iShouldSeeMyAccountWasCreated($userId) { $this->userHelper->assertUserCreated($userId); } /** * @When /^I (am logged in|login)$/ */ public function iLogin() { $this->userHelper->login(); } /** * @Then /^I should be logged in$/ */ public function iShouldBeLoggedIn() { $this->userHelper->assertSuccessfulLogin(); } /** * @Then /^I should not be offered a chance to bid$/ */ public function iShouldNotBeOfferedAChanceToBid() { $this->auctionHelper->assertBiddingNotOffered(); } }
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/web/prod.php
web/prod.php
<?php $env = 'prod'; return require __DIR__.'/front.php';
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/web/dev.php
web/dev.php
<?php $env = 'dev'; return require __DIR__.'/front.php';
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
igorw/doucheswag
https://github.com/igorw/doucheswag/blob/cd4f07034569bf5e70f316dfdc22e604db3eef63/web/front.php
web/front.php
<?php $filename = __DIR__.preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']); if (php_sapi_name() === 'cli-server' && is_file($filename)) { return false; } if (!isset($env)) { http_response_code(503); echo 'Front controller must have environment configured.'; exit; } require __DIR__.'/../vendor/autoload.php'; $app = require __DIR__.'/../src/DoucheWeb/app.php'; $app->register(new Igorw\Silex\ConfigServiceProvider(__DIR__."/../config/$env.json", [ 'storage_path' => __DIR__.'/../storage', 'template_path' => __DIR__.'/../src/DoucheWeb/views', ])); $app->run();
php
MIT
cd4f07034569bf5e70f316dfdc22e604db3eef63
2026-01-05T05:04:15.010015Z
false
SkinsRestorer/SkinSystem
https://github.com/SkinsRestorer/SkinSystem/blob/68101b9efdcad6213a4468be289b59c4910828ff/index.php
index.php
<?php define('VER', '1.7.2'); if (!file_exists('config.nogit.php')) { session_start(); session_destroy(); die(header('Location: installation/?v=' . VER)); } require_once('resources/server/libraries.php'); if ($config['version'] != VER) { require_once('installation/installation.php'); confupdater($config, VER); die(header("Refresh:0")); } session_start(); /* Set username session for non-authme system */ if (empty($_SESSION['username']) && $config['am']['enabled'] == false) { $_SESSION['username'] = 'SkinSystemUser'; } ?> <!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title><?php echo L::mn_title; ?></title> <!-- Libraries --> <link rel="shortcut icon" href="favicon.ico"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous"> <?php if (isset($_COOKIE['theme']) and is_file('resources/themes/' . $_COOKIE['theme'] . '.css')) { $theme = $_COOKIE['theme']; } else { $theme = $config['def_theme']; } echo '<link id="stylesheetSelector" rel="stylesheet" name="' . $theme . '" href="resources/themes/' . $theme . '.css">'; // pick theme from cookie; if cookie invalid, pick default theme from config ?> <script type="text/javascript"> function setCookie(cname, cvalue) { const d = new Date(); d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000)); // cookies will last a year document.cookie = cname + "=" + cvalue + ";expires=" + d.toUTCString() + ";path=/"; } const theme = document.getElementById("stylesheetSelector").getAttribute("name"); setCookie("theme", theme); // swap that stale cookie for a new one! function rotateTheme() { // move a metaphorical carousel by one item $.getJSON("resources/themes/", {}, function (lst) { setCookie("theme", lst[((lst.indexOf(theme + ".css") + 1) % lst.length)].slice(0, -4)); location.reload(); }); } const l = {}; l.uplty1_lbl = "<?php echo L::upl_uplty1_lbl; ?>"; </script> <?php foreach ([ 'https://code.jquery.com/jquery-3.3.1.min.js' => 'f8da8f95b6ed33542a88af19028e18ae3d9ce25350a06bfc3fbf433ed2b38fefa5e639cddfdac703fc6caa7f3313d974b92a3168276b3a016ceb28f27db0714a', 'https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js' => 'f43dfd388488b509a66879608c35d7c1155f93dcec33ca875082f59f35552740d65e9a344a044d7ec534f0278a6bb6f0ed81047f73dcf615f7dcd76e0a482009', 'https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js' => '64681777a4c1e6a8edbd353a439a3f2c9338a702cdcbc53c5d7261faf2590d7a76c02f004ab97858e7a2bdaab67e961cdd39d308bcf20ef56363c621bcd61a5e', 'https://raw.githubusercontent.com/InventivetalentDev/MineRender/v1.1.0/dist/skin.min.js' => '5acd05d47d28928779a88a13126a396fc1a57cda55fb82180db9e69dba009ad466156e1ca75562026c2ebcdf195adcfc178c78602468eafe3303b726706447b0', 'https://cdn.jsdelivr.net/npm/sweetalert2@8.8.5' => '2d90ae300e9e37ef219afa3c50f2261e220f83424a83d30286d53492becce0ea6f1dc1749b0cd47eec37c6a008f877b79e40ab48638efd1462f4aeff2a288c96' ] as $url => $sha512) { $expl = explode('/', $url); echo '<script src="' . cacheGrab($url, end($expl), './', false, ['sha512', $sha512]) . '"></script>'; } ?> </head> <body class="bg-light"> <!-- Main Container --> <section class="bg-light h-100"> <div class="container h-100"> <div class="row h-100"> <div class="col-lg-<?php echo(!empty($_SESSION['username']) ? 8 : 6); ?> m-auto"> <div class="card border-0 shadow"> <div class="card-header bg-primary text-white"> <div class="row mx-2 align-items-center"> <h5 class="mb-0"><?php echo L::ssys; ?> <?php echo '<small style="font-size: 60%;"><a id="versionDisplay" title="' . str_replace("%v%", $config['version'], L::mn_rlhov) . '" href="https://github.com/SkinsRestorer/SkinSystem/releases/tag/' . $config['version'] . '">v.' . $config['version'] . '</a>'; if ($config['version'] !== getLatestVersion()) { echo ' <a title="' . L::mn_nwrel_hov . '" href="https://github.com/SkinsRestorer/SkinSystem/releases/latest">(' . L::mn_nwrel . ')</a>'; } echo '</small>' ?> </h5> <h6 class="mb-0 ml-auto"> <?php if ($config['am']['enabled'] == true && !empty($_SESSION['username'])){ $SkullURL = 'resources/server/skinRender.php?vr=0&hr=0&headOnly=true&ratio=4&user=' . $_SESSION['username']; echo '<a class="skinDownload" id="skinDownloadUrl" title="' . L::mn_dlhov . '" name="' . $_SESSION['username'] . '" href="resources/server/skinRender.php?format=raw&dl=true&user=' . $_SESSION['username'] . '"><img class="skinDownload" style="max-height:29px!important;" src="' . $SkullURL . '"> ' . htmlspecialchars($_SESSION['username'], ENT_QUOTES) . '</a>'; ?> <a class="btn btn-sm btn-light ml-2 rounded-circle" title="<?php echo L::mn_lgout; ?>" href="resources/server/authenCore.php?logout"><i class="fas fa-sign-out-alt"></i></a> <?php } ?> </h6> <a class="btn btn-sm btn-light ml-2 rounded-circle" title="<?php echo L::mn_swthm; ?>" onclick="rotateTheme();"><i class="fas fa-adjust"></i></a> </div> </div> <div class="card-body"> <?php if (!empty($_SESSION['username'])) { ?> <script src="resources/js/skinCore.js"></script> <div class="row"> <!-- Uploader --> <div class="col-lg-8 pr-lg-2 mb-lg-0 mb-3"> <div class="card border-0 shadow"> <h6 class="card-header bg-info text-white"><i class="fas fa-file-upload text-dark"></i> <?php echo L::upl_title; ?> </h6> <div class="card-body"> <form id="uploadSkinForm"> <?php if ($config['am']['enabled'] == false) { ?> <div class="form-group row"> <h5 class="col-lg-3"><span class="badge badge-success"><?php echo L::upl_usrnm; ?></span> </h5> <div class="col-lg-9"> <input id="input-username" class="form-control form-control-sm" name="username" type="text" required> </div> </div> <?php } ?> <div class="form-group"> <h5 class="mb-0 mr-3 custom-control-inline"><span class="badge badge-info"><?php echo L::upl_sknty; ?></span> </h5> <div class="custom-control custom-radio custom-control-inline"> <input id="skintype-steve" class="custom-control-input" name="isSlim" value="false" type="radio"> <label class="custom-control-label" for="skintype-steve"><?php echo L::upl_sknty1; ?></label> </div> <div class="custom-control custom-radio custom-control-inline"> <input id="skintype-alex" class="custom-control-input" name="isSlim" value="true" type="radio"> <label class="custom-control-label" for="skintype-alex"><?php echo L::upl_sknty2; ?></label> </div> </div> <div class="form-group mb-4"> <h5 class="mb-0 mr-3 custom-control-inline"><span class="badge badge-info"><?php echo L::upl_uplty; ?></span> </h5> <div class="custom-control custom-radio custom-control-inline"> <input id="uploadtype-file" class="custom-control-input" name="uploadtype" value="file" type="radio" checked> <label class="custom-control-label" for="uploadtype-file"><?php echo L::upl_uplty1; ?></label> </div> <div class="custom-control custom-radio custom-control-inline"> <input id="uploadtype-url" class="custom-control-input" name="uploadtype" value="url" type="radio"> <label class="custom-control-label" for="uploadtype-url"><?php echo L::upl_uplty2; ?></label> </div> </div> <div id="form-input-file" class="form-group"> <div class="custom-file"> <input id="input-file" class="custom-file-input" name="file" type="file" accept="image/*" required> <label class="custom-file-label text-truncate"><?php echo L::upl_uplty1_lbl; ?></label> </div> </div> <div id="form-input-url" class="form-group row" style="display: none;"> <div class="col-lg-12"> <input id="input-url" class="form-control form-control-sm" name="url" type="text" placeholder="<?php echo L::upl_uplty2_lbl; ?>"> </div> </div> <button class="btn btn-primary w-100"> <strong><?php echo L::upl_buttn; ?></strong></button> <small class="form-text text-muted" id="uploadDisclaimer"<?php if ($config['data_warn'] === 'no' or ($config['data_warn'] === 'eu' and file_get_contents(cacheGrab('https://ipapi.co/' . IP . '/in_eu', 'in_eu-' . IP)) !== 'True')) { echo ' style="display: none;"'; } ?>><?php echo str_replace("%h%", $_SERVER['HTTP_HOST'], L::mn_discl); ?></small> </form> </div> </div> </div> <!-- Skin Viewer --> <div class="col-lg-4"> <div class="card border-0 shadow"> <h6 class="card-header bg-info text-white"><i class="fas fa-eye text-dark"></i> Preview</h6> <div class="card-body"> <div id="skinViewerContainer"></div> <script type="text/javascript"> window.onresize = function () { // skinViewer height shall match uploadSkin document.getElementById('skinViewerContainer').style.height = document.getElementById('uploadSkinForm').clientHeight + 'px'; } window.onresize(); </script> </div> </div> </div> <?php if (false) { ?> <!-- Skin History --> <div class="col-lg-12 mt-3"> <div class="card border-0 shadow"> <h6 class="card-header bg-info text-white"><i class="fas fa-history text-dark"></i> <?php echo L::mn_hstry; ?> </h6> <div class="card-body"> <a id="mineskin-recent" href="<?php echo cacheGrab('https://api.mineskin.org/get/list/0?size=6', 'mineskin-recent', './', (10 * 60)); ?>" style="display:none;"></a> <div class="row" id="skinlist"></div> <script type="text/javascript"> setCookie('skinHistoryType', 'mineskin'); function getCookie(cname) { const value = "; " + document.cookie; const parts = value.split("; " + cname + "="); if (parts.length === 2) return parts.pop().split(";").shift(); } const historytype = getCookie('skinHistoryType'); if (historytype === 'personal') { } else if (historytype === 'server') { } else if (historytype === 'mineskin') { $.getJSON($('#mineskin-recent')[0].href, {}, function (lst) { $.each(lst.skins.slice(0, 6), function (key, val) { skinid = val.url.match(/\w+$/); $('#skinlist').append('<div class="col-2 skinlist-mineskin"><img class="skinlistitem" style="max-width:75px;width:inherit;cursor:pointer;" title="' + ('Select skin ' + val.name).trim() + '" onclick="skinURL(\'resources/server/skinRender.php?format=raw&mojang=' + skinid + '\');" src="resources/server/skinRender.php?mojang=' + skinid + '"></div>'); }); }); } function skinURL(url) { $('#uploadtype-url').prop('checked', true).change(); $('#input-url').val(url); } </script> </div> </div> </div> <?php } ?> </div> <?php } else { ?> <script src="resources/js/authenCore.js"></script> <div class="row"> <div class="col-lg-12"> <div class="card border-0 shadow"> <h6 class="card-header bg-info text-white"><i class="fas fa-sign-in-alt"></i> <?php echo L::auth_title; ?></h6> <div class="card-body"> <form id="loginForm"> <div class="input-group mb-3"> <div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-user"></i></span></div> <input id="login-username" class="form-control" name="username" type="text" placeholder="<?php echo L::auth_usrnm; ?>" required> </div> <div class="input-group mb-3"> <div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-lock"></i></span></div> <input id="login-password" class="form-control" name="password" type="password" placeholder="<?php echo L::auth_psswd; ?>" required> </div> <button class="btn btn-success w-100"><?php echo L::auth_login; ?></button> </form> </div> </div> </div> </div> <?php } ?> </div> </div> </div> </div> </div> </section> </body> </html>
php
MIT
68101b9efdcad6213a4468be289b59c4910828ff
2026-01-05T05:04:25.960579Z
false
SkinsRestorer/SkinSystem
https://github.com/SkinsRestorer/SkinSystem/blob/68101b9efdcad6213a4468be289b59c4910828ff/installation/installation.php
installation/installation.php
<?php if (file_exists(__DIR__ . '/../config.nogit.php')) { die(header('Location: ../')); } require_once '../resources/server/i18n.class.php'; $i18n = new i18n(); $i18n->setCachePath('../resources/lang/cache'); $i18n->setFilePath('../resources/lang/{LANGUAGE}.ini'); // language file path $i18n->setFallbackLang('en'); $i18n->setMergeFallback(true); // make keys available from the fallback language $i18n->init(); function printDataAndDie($data = []) { if (!isset($data['success'])) { $data['success'] = empty($data['error']); } die(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); } function printErrorAndDie($error) { printDataAndDie(['error' => $error]); } /* Update config file */ function confupdater($config, $version) { $config['version'] = $version; $renames = [ 'playretable' => 'playertable' ]; // default config file layout, with default values preg_match('/([^\/]*)\.css$/', glob(__DIR__ . '/../resources/themes/*.css')[0], $thm); $defaults = [ 'version' => false, 'def_theme' => $thm[1], 'data_warn' => 'no', 'am' => [ 'enabled' => false, 'host' => '', 'port' => '', 'database' => '', 'username' => '', 'password' => '', 'table' => 'authme', 'hash' => [ 'method' => 'sha256' ], 'authsec' => [ 'enabled' => true, 'failed_attempts' => 3, 'threshold_hours' => 24 ] ], 'sr' => [ 'host' => '', 'port' => '', 'database' => '', 'skintable' => '', 'playertable' => '', 'username' => '', 'password' => '' ], 'cache_for_days' => 7, 'cache_dir' => 'resources/cache/' ]; foreach ($renames as $from => $to) { if (isset($config[$from])) { $config[$to] = $config[$from]; unset($config[$from]); } } /* Write and return config file */ $repl = [ '/\s*array \(/' => ' [', '/,(\s*)\)/' => '${1}]', '/(\s+)\'am\' => \[/' => '$1/* ' . L::config_am . ' */$0', '/(\s+)\'sr\' => \[/' => '$1/* ' . L::config_sr . ' */$0', '/(\s+)\'cache_for_days\' => /' => '$1/* ' . L::config_cache_for_days . ' */$0', '/(\s+)\'def_theme\' => /' => '$1/* ' . L::config_def_theme . ' */$0', '/(\s+)\'data_warn\' => /' => '$1/* ' . L::config_data_warn . ' */$0' ]; $confarr = preg_replace(array_keys($repl), $repl, var_export(array_replace_recursive($defaults, $config), true)); $byteswritten = file_put_contents(__DIR__ . '/../config.nogit.php', "<?php return" . $confarr . ";?>"); if (!$byteswritten) { printErrorAndDie(L::instl_noconf); } } if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (empty($_POST['release-version'])) { printErrorAndDie(str_replace("%rsn%", L::instl_invreq_verusp, L::instl_invreq)); } if (empty($_POST['thm-selection'])) { printErrorAndDie(str_replace("%rsn%", L::instl_invreq_thmusp, L::instl_invreq)); } $config['def_theme'] = $_POST['thm-selection']; /* Get Data from SkinsRestorer's config.yml */ if (empty($_FILES['sr-config']['tmp_name'])) { printErrorAndDie(str_replace("%rsn%", L::instl_invreq_srfile, L::instl_invreq)); } $is_srconfig = preg_match('/MySQL:((\s+.*)*)/', file_get_contents($_FILES['sr-config']['tmp_name']), $re); if (!$is_srconfig) { printErrorAndDie(L::instl_srivfl); } preg_match_all('/\n\s*(\w+):\s*[\'"]?([\'"]{2}|[^\s\'"]+)/', $re[0], $re); $kitms = ['enabled', 'host', 'port', 'database', 'skintable', 'playertable', 'username', 'password']; foreach ($re[1] as $k => $v) { $v = strtolower($v); if (in_array($v, $kitms)) { $config['sr'][$v] = $re[2][$k]; }; } if (!isset($config['sr']) || $config['sr']['enabled'] == false) { printErrorAndDie(L::instl_srendb); } if (!isset($config['sr']) || $config['sr']['password'] == "''") { $config['sr']['password'] = ''; } unset($config['sr']['enabled']); /* Get Data from AuthMe's config.yml */ if (!empty($_POST['am-activation'])) { $config['am']['enabled'] = true; if (empty($_FILES['am-config']['tmp_name'])) { printErrorAndDie(str_replace("%rsn%", L::instl_invreq_amfile, L::instl_invreq)); } $raw_amconfig = file_get_contents($_FILES['am-config']['tmp_name']); $is_srconfig = preg_match('/DataSource:((?:\n\s+.*)*)/', $raw_amconfig, $re); if (!$is_srconfig) { printErrorAndDie(L::instl_amivfl); } preg_match_all('/\n\s*(?:mySQL)?([^#\/:]+):\s*[\'"]?([\'"]{2}|[^\s\'"]+)/', $re[0], $re); $kitms = ['backend', 'enabled', 'host', 'port', 'database', 'username', 'password', 'table']; foreach ($re[1] as $k => $v) { $v = strtolower($v); if (in_array($v, $kitms)) { $config['am'][$v] = $re[2][$k]; }; } if ($config['am']['backend'] !== 'MYSQL') { printErrorAndDie(L::instl_amendb); } if (preg_match('/\n\s*passwordHash:\s*[\'"]?([\'"]{2}|[^\s\'"]+)/', $raw_amconfig, $re)) { $config['am']['hash']['method'] = strtolower($re[1]); if ($config['am']['hash']['method'] === 'pbkdf2') { if (preg_match('/\n\s*pbkdf2Rounds:\s*[\'"]?([\'"]{2}|[^\s\'"]+)/', $raw_amconfig, $re)) { $config['am']['hash']['pbkdf2rounds'] = $re[1]; } } } } unset($config['am']['backend']); /* Get non-default value for Authsecurity */ if (empty($_POST['as-activation'])) { $config['am']['authsec']['enabled'] = false; } /* Set default properties, write file */ confupdater($config, $_POST['release-version']); printDataAndDie(); }
php
MIT
68101b9efdcad6213a4468be289b59c4910828ff
2026-01-05T05:04:25.960579Z
false
SkinsRestorer/SkinSystem
https://github.com/SkinsRestorer/SkinSystem/blob/68101b9efdcad6213a4468be289b59c4910828ff/installation/index.php
installation/index.php
<?php if (file_exists(__DIR__ . '/../config.nogit.php')) { header('Location: ../'); die(); } require_once '../resources/server/i18n.class.php'; $i18n = new i18n(); $i18n->setCachePath('../resources/lang/cache'); $i18n->setFilePath('../resources/lang/{LANGUAGE}.ini'); // language file path $i18n->setFallbackLang('en'); $i18n->setMergeFallback(true); // make keys available from the fallback language $i18n->init(); ?> <!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title><?php echo L::instl_title; ?></title> <!-- Libraries --> <link rel="shortcut icon" href="../favicon.ico"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css"> <?php $themelist = []; foreach (glob(__DIR__ . '/../resources/themes/*.css') as $thm) { preg_match('/([^\/]*)\.css$/', $thm, $vl); $themelist[] = $vl[1]; } echo '<link id="stylesheetSelector" rel="stylesheet" href="../resources/themes/' . $themelist[0] . '.css">'; ?> </head> <body class="bg-light"> <!-- Main Container --> <section class="bg-light h-100"> <div class="container h-100"> <div class="row h-100"> <div class="col-lg-8 m-auto"> <div class="card border-0 shadow"> <div class="card-header bg-primary text-white"> <div class="row mx-2 align-items-center"> <h5 class="mb-0"><i class="fas fa-wrench"></i> <?php echo L::instl_title; ?> <small style="font-size: 60%;">v.<?php echo $_GET['v']; ?></small></h5> </div> </div> <div class="card-body"> <form id="installation-form"> <input id="release-version" name="release-version" type="text" value="<?php echo $_GET['v']; ?>" style="display: none;"/> <div class="row"> <div class="col-lg-12 mb-lg-0"> <div id="alert" class="alert alert-danger" style="display: none;"><i class="fas fa-exclamation-circle"></i> <span><?php echo L::gnrl_error; ?></span></div> </div> <div class="col-lg-5 pr-lg-1 mb-lg-0 mb-3"> <div class="card border-0 shadow"> <h6 class="card-header bg-info text-white"><i class="fas fa-check"></i> <?php echo L::instl_optns; ?></h6> <div class="card-body"> <div class="form-group"> <div class="row"> <div class="col-sm" style="flex-grow:.1;padding-right:0;"> <h5 class="mb-0 mr-3 custom-control-inline" style="padding-top:5px;"> <span class="badge badge-info"><?php echo L::instl_dfthm; ?></span> </h5> </div> <div class="col-sm" style="padding-left:0;"> <select id="thm-selection" name="thm-selection" class="form-control" style="height: 35px;padding: 5px;" onchange="document.getElementById('stylesheetSelector').href='../resources/themes/'+this.value+'.css';"> <?php foreach ($themelist as $theme) { echo "<option>" . $theme . "</option>"; } ?> </select> </div> </div> </div> <div class="form-group"> <div class="custom-control custom-checkbox"> <input id="am-activation" class="custom-control-input" type="checkbox" name="am-activation"> <label class="custom-control-label" for="am-activation"><?php echo L::instl_am1; ?></label> <small class="form-text text-muted"><?php echo L::instl_am2; ?></small> </div> </div> <div id="as-activation-form" class="form-group" style="display: none;"> <div class="custom-control custom-checkbox"> <input id="as-activation" class="custom-control-input" type="checkbox" name="as-activation"> <label class="custom-control-label" for="as-activation"><?php echo L::instl_al1; ?></label> <small class="form-text text-muted"><?php echo L::instl_al2; ?></small> </div> </div> </div> </div> </div> <div class="col-lg-7"> <div class="card border-0 shadow"> <h6 class="card-header bg-info text-white"><i class="fas fa-file-upload"></i> <?php echo L::instl_ldcnf; ?></h6> <div class="card-body"> <div class="form-group"> <label><?php echo L::instl_srcnf; ?></label> <div class="custom-file"> <input id="sr-config-input" class="custom-file-input" type="file" accept=".yml" name="sr-config"> <label class="custom-file-label text-truncate"><?php echo L::instl_cnfch; ?></label> </div> </div> <div id="am-config-form" class="form-group" style="display: none;"> <label><?php echo L::instl_amcnf; ?></label> <div class="custom-file"> <input id="am-config-input" class="custom-file-input" type="file" accept=".yml" name="am-config"> <label class="custom-file-label text-truncate"><?php echo L::instl_cnfch; ?></label> </div> </div> <button class="btn btn-success w-100" type="submit"><i class="fas fa-cog"></i> <?php echo L::instl_finish; ?></button> </div> </div> </div> </div> </form> </div> </div> </div> </div> </section> <!-- Libraries --> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script> <script src="core.js"></script> </body> </html>
php
MIT
68101b9efdcad6213a4468be289b59c4910828ff
2026-01-05T05:04:25.960579Z
false
SkinsRestorer/SkinSystem
https://github.com/SkinsRestorer/SkinSystem/blob/68101b9efdcad6213a4468be289b59c4910828ff/resources/cache/index.php
resources/cache/index.php
<?php header("Location: https://vk.cc/7iPiB9"); die(); ?>
php
MIT
68101b9efdcad6213a4468be289b59c4910828ff
2026-01-05T05:04:25.960579Z
false
SkinsRestorer/SkinSystem
https://github.com/SkinsRestorer/SkinSystem/blob/68101b9efdcad6213a4468be289b59c4910828ff/resources/themes/index.php
resources/themes/index.php
<?php header('Content-Type: application/json'); echo json_encode(glob('*.css')); ?>
php
MIT
68101b9efdcad6213a4468be289b59c4910828ff
2026-01-05T05:04:25.960579Z
false
SkinsRestorer/SkinSystem
https://github.com/SkinsRestorer/SkinSystem/blob/68101b9efdcad6213a4468be289b59c4910828ff/resources/server/authenCore.php
resources/server/authenCore.php
<?php require_once(__DIR__ . '/libraries.php'); if ($config['am']['enabled'] == false) { printErrorAndDie(L::amcr_unusb); } session_start(); // https://github.com/AuthMe/AuthMeReloaded/tree/master/samples/website_integration function isValidPassword($password, $hash) { global $config; $method = strtolower($config['am']['hash']['method']); $parts = explode('$', $hash); if (in_array($method, hash_algos())) { // known hash methods by php (sha256) return (count($parts) === 4 && $parts[3] === hash($method, hash($method, $password) . $parts[2])); } elseif ($method === 'pbkdf2') { // pbkdf2 $iter = $config['am']['hash']['pbkdf2rounds']; $chash = 'pbkdf2_sha256$' . $iter . '$' . $parts[2] . '$' . hash_pbkdf2('sha256', $password, $parts[2], (int)$iter, 64, false); return (strtolower(substr($hash, 0, strlen($chash))) === strtolower($chash)); } else { // bcrypt/argon2 return (password_verify($password, $hash)); } } /* logout Request */ if (isset($_GET['logout'])) { session_destroy(); header('Location: ../../'); } /* If login request is valid */ if (!empty($_POST['username']) && !empty($_POST['password'])) { $username = strtolower($_POST['username']); $timeout = $config['am']['authsec']['threshold_hours'] * 60 * 60; $cdir = __DIR__ . '/../../' . $config['cache_dir']; if (!is_dir($cdir)) { mkdir($cdir, 0775, true); } // rate limit by publicly assigned ip (prefix v6, whole v4) $blk[0] = $cdir . '.loginratelimit-addr-' . IP; // rate limit by username they are trying to log into (limit+1, limit IP before username) $blk[1] = $cdir . '.loginratelimit-user-' . $username; $now = time(); if (!$config['am']['authsec']['enabled'] or !is_file($blk[0]) or !is_file($blk[1]) or (max([filemtime($blk[0]), filemtime($blk[1])]) < $now)) { $password = $_POST['password']; /* Get user's password from AuthMe Storage */ $authmeTable = $config['am']['table']; $pdo = query('am', "SELECT password FROM $authmeTable WHERE username = ?", [$username]); /* Analyse AuthMe Password Algorithm */ if (isValidPassword($password, $pdo->fetch(PDO::FETCH_ASSOC)['password'])) { $_SESSION['username'] = $username; foreach ($blk as $rlfl) { if (is_file($rlfl)) { unlink($rlfl); } } printDataAndDie(['title' => L::amcr_lgsc_title, 'text' => L::amcr_lgsc_text, 'refresh' => True]); } else { /* Login failed, they should stop soon! */ foreach ($blk as $index => $rlfl) { if (!is_file($rlfl) or filemtime($rlfl) < ($now - $timeout)) { $failvl = ($now - $timeout); } else { $failvl = filemtime($rlfl); } $failvl = ($failvl + ($timeout / ($config['am']['authsec']['failed_attempts'] + $index)) + 120); touch($rlfl, $failvl); } printErrorAndDie(['type' => 'warning', 'title' => L::amcr_cd401_title, 'text' => L::amcr_cd401_text]); } } else { printErrorAndDie(['title' => L::amcr_cd429_title, 'text' => L::amcr_cd429_text]); } } printErrorAndDie(L::amcr_invrq); ?>
php
MIT
68101b9efdcad6213a4468be289b59c4910828ff
2026-01-05T05:04:25.960579Z
false
SkinsRestorer/SkinSystem
https://github.com/SkinsRestorer/SkinSystem/blob/68101b9efdcad6213a4468be289b59c4910828ff/resources/server/skinRender.php
resources/server/skinRender.php
<?php require_once('libraries.php'); /****** MINECRAFT 3D Skin Generator ***** * The contents of this project were first developed by Pierre Gros on 17th April 2012. * It has once been modified by Carlos Ferreira (http://www.carlosferreira.me) on 31st May 2014. * Translations done by Carlos Ferreira. * Later adapted by Gijs "Gyzie" Oortgiese (http://www.gijsoortgiese.com/). Started on the 6st of July 2014. * Fixing various issues. * Later changed by ITZVGcGPmO (https://github.com/ITZVGcGPmO) April 2019. * Adapted for SkinSystem. * **** GET Parameters **** * user - A username for the skin to be rendered. (Required w/o "mojang") * mojang - A texture from https://textures.minecraft.net to render. (Required w/o "user") * vr - Vertical Rotation. (-25 by default) * hr - Horizontal Rotation. (35 by default) * * hrh - Horizontal Rotation of the Head. (0 by default) * * vrll - Vertical Rotation of the Left Leg. (0 by default) * vrrl - Vertical Rotation of the Right Leg. (0 by default) * vrla - Vertical Rotation of the Left Arm. (0 by default) * vrra - Vertical Rotation of the Right Arm. (0 by default) * * displayHair - Either or not to display hairs. Set to "false" to NOT display hairs. (true by default) * headOnly - Either or not to display the ONLY the head. Set to "true" to display ONLY the head. (false by default) * * format - The format in which the image is to be rendered. "png", "svg", "base64", "raw". (png by default) * * ratio - The size of the "png" image. The default and minimum value is 2. (12 by default) * * aa - Anti-aliasing (Not real AA, fake AA). When set to "true" the image will be smoother. (false by default). * * layers - Apply extra skin layers. (true by default) */ if (basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])) { // Don't adjust the error reporting if we are an include file error_reporting(E_ERROR); //error_reporting(E_ALL); //ini_set("display_errors", 1); // TODO not here - this is set in index.php } /* Start Global variabal * These variabals are shared over multiple classes */ $seconds_to_cache = $config['cache_for_days'] * 24 * 60 * 60; // Cache duration sent to the browser. // Cosine and Sine values $cos_alpha = null; $sin_alpha = null; $cos_omega = null; $sin_omega = null; $minX = null; $maxX = null; $minY = null; $maxY = null; /* End Global variabel */ /* Function converts the old _GET names to * the new names. This makes it still compatable * with scrips using the old names. * * Espects the English _GET name. * Returns the _GET value or the default value. * Return false if the _GET is not found. */ function grabGetValue($name) { $parameters = array('mojang' => array('old' => 'mojang', 'default' => false), 'user' => array('old' => 'login', 'default' => false), 'vr' => array('old' => 'a', 'default' => '-25'), 'hr' => array('old' => 'w', 'default' => '35'), 'hrh' => array('old' => 'wt', 'default' => '0'), 'vrll' => array('old' => 'ajg', 'default' => '0'), 'vrrl' => array('old' => 'ajd', 'default' => '0'), 'vrla' => array('old' => 'abg', 'default' => '0'), 'vrra' => array('old' => 'abd', 'default' => '0'), 'displayHair' => array('old' => 'displayHairs', 'default' => 'true'), 'headOnly' => array('old' => 'headOnly', 'default' => 'false'), 'format' => array('old' => 'format', 'default' => 'png'), 'ratio' => array('old' => 'ratio', 'default' => '12'), 'aa' => array('old' => 'aa', 'default' => 'false'), 'layers' => array('old' => 'layers', 'default' => 'true') ); if (array_key_exists($name, $parameters)) { if (isset($_GET[$name])) { return $_GET[$name]; } else if (isset($_GET[$parameters[$name]['old']])) { return $_GET[$parameters[$name]['old']]; } return $parameters[$name]['default']; } return false; } // Check if the player name value has been set, and that we are not running as an included/required file. else do nothing. if ((basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])) && ((grabGetValue('user') !== false) || (grabGetValue('mojang') !== false))) { // There is a player name so they want an image output via url $renderparams = array(grabGetValue('mojang'), grabGetValue('user'), grabGetValue('vr'), grabGetValue('hr'), grabGetValue('hrh'), grabGetValue('vrll'), grabGetValue('vrrl'), grabGetValue('vrla'), grabGetValue('vrra'), grabGetValue('displayHair'), grabGetValue('headOnly'), grabGetValue('format'), grabGetValue('ratio'), grabGetValue('aa'), grabGetValue('layers')); $player = new render3DPlayer(...$renderparams); $res = $player->getSkinFile(); $skinRaw = $res[0]; $skinHash = $res[1]; if ($_GET['dl'] == 'true') { header('Content-Disposition: attachment; filename=' . grabGetValue('user') . '-' . hash('adler32', serialize($renderparams) . $skinRaw) . '.png'); } $conttype = ['svg' => 'image/svg+xml', 'base64' => 'text/plain', 'png' => 'image/png', 'raw' => 'image/png']; header('Content-Type: ' . $conttype[grabGetValue('format')]); // send content-type for any format if (grabGetValue('format') == 'raw') { echo file_get_contents($skinRaw); } else { // cache system for "rendered" skins unset($renderparams[0]); unset($renderparams[1]); $cdir = __DIR__ . '/../../' . $config['cache_dir']; mkdir($cdir, 0775, true); $cfile = $cdir . $skinHash . '-' . hash("md5", serialize($renderparams)); if (!is_file($cfile) or file_get_contents($cfile) == '') { $player->get3DRender($skinRaw, $cfile); } echo file_get_contents($cfile); touch($cfile); cacheClean(__DIR__ . '/../../'); } } else { header('Content-Type: text/plain'); echo file_get_contents(__FILE__); } /* Render3DPlayer class * */ class render3DPlayer { // Use a fallback skin whenever something goes wrong. private $fallback_img = 'https://textures.minecraft.net/texture/dc1c77ce8e54925ab58125446ec53b0cdd3d0ca3db273eb908d5482787ef4016'; private $mojang = null; private $playerName = null; private $playerSkin = false; private $isNewSkinType = false; private $hd_ratio = 1; private $vR = null; private $hR = null; private $hrh = null; private $vrll = null; private $vrrl = null; private $vrla = null; private $vrra = null; private $head_only = null; private $display_hair = null; private $format = null; private $ratio = null; private $aa = null; private $layers = null; // Rotation variables in radians (3D Rendering) private $alpha = null; // Vertical rotation on the X axis. private $omega = null; // Horizontal rotation on the Y axis. private $members_angles = array(); // Head, Helmet, Torso, Arms, Legs private $visible_faces_format = null; private $visible_faces = null; private $all_faces = null; private $front_faces = null; private $back_faces = null; private $cube_points = null; private $polygons = null; private $times = null; public function __construct($mojang, $user, $vr, $hr, $hrh, $vrll, $vrrl, $vrla, $vrra, $displayHair, $headOnly, $format, $ratio, $aa, $layers) { $this->mojang = $mojang; $this->playerName = $user; $this->vR = $vr; $this->hR = $hr; $this->hrh = $hrh; $this->vrll = $vrll; $this->vrrl = $vrrl; $this->vrla = $vrla; $this->vrra = $vrra; $this->head_only = ($headOnly == 'true'); $this->display_hair = ($displayHair != 'false'); $this->format = $format; $this->ratio = $ratio; $this->aa = ($aa == 'true'); $this->layers = ($layers == 'true'); } /* Function can be used for tracking script duration * */ public function getSkinFile() { global $config; if ($this->mojang != null) { preg_match('/[^\/]+$/', $this->mojang, $mj256); $skinURL = 'https://textures.minecraft.net/texture/' . $mj256[0]; } else if ($this->playerName != null) { // get existing skin from skinsrestorer. $skinName = query('sr', 'SELECT Skin FROM ' . $config['sr']['playertable'] . ' WHERE Nick = ?', [$this->playerName])->fetch(PDO::FETCH_ASSOC)['Skin']; $skinLookup = query('sr', 'SELECT Value FROM ' . $config['sr']['skintable'] . ' WHERE Nick = ?', [$skinName])->fetch(PDO::FETCH_ASSOC)['Value']; $skinURL = json_decode(base64_decode($skinLookup), true)['textures']['SKIN']['url']; if (!is_string($skinURL)) { // if cannot get skin from skinsrestorer, get skin from mojang. $mjdfskfl = __DIR__ . '/../../' . $config['cache_dir'] . 'mojang_skin-' . strtolower($this->playerName); if (file_exists($mjdfskfl)) { // fetch cached mojang skin $skinURL = file_get_contents($mjdfskfl); } else { // fetch mojang version of skin $pf = json_decode(file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . strtolower($this->playerName)), true); if (is_array($pf) and array_key_exists("id", $pf)) { $ca = json_decode(file_get_contents('https://sessionserver.mojang.com/session/minecraft/profile/' . $pf["id"]), true); } // $ca = json_decode(file_get_contents(cacheGrab('https://sessionserver.mojang.com/session/minecraft/profile/ef5db304c36841089a352fd0a072b73d', 'test', __DIR__.'/../../'))); if (is_array($ca) and array_key_exists("properties", $ca)) { foreach ($ca["properties"] as $element) { if (array_key_exists("name", $element) && $element["name"] == "textures") { $content = base64_decode($element["value"]); $skinArray = json_decode($content, true); if (array_key_exists("textures", $skinArray) and array_key_exists("SKIN", $skinArray["textures"])) { file_put_contents($mjdfskfl, $skinArray["textures"]["SKIN"]["url"]); $skinURL = $skinArray["textures"]["SKIN"]["url"]; } } } } } } } if (strlen($skinURL) < 1) { $skinURL = $this->fallback_img; } // if can't get skin, use steve. if (!$mj256) { preg_match('/[^\/]+$/', $skinURL, $mj256); } return [cacheGrab($skinURL, $mj256[0], __DIR__ . '/../../', false, ['sha256', $mj256[0]]), $mj256[0]]; } /* Fetches skin URL from database using the given name * * Expects a name * returns a player skin file */ public function get3DRender($skinRaw, $cacheFile) { global $minX, $maxX, $minY, $maxY; // Download and check the player skin $this->playerSkin = @imageCreateFromPng($skinRaw); if ((!$this->playerSkin) || (imagesy($this->playerSkin) % 32 != 0)) { // Player skin does not exist or bad ratio created $this->playerSkin = imageCreateFromPng($this->fallback_img); } $this->hd_ratio = imagesx($this->playerSkin) / 64; // Set HD ratio to 2 if the skin is 128x64. Check via width, not height because of new skin type. // check if new skin type. If both sides are equaly long: new skin type if (imagesx($this->playerSkin) == imagesy($this->playerSkin)) { $this->isNewSkinType = true; } $this->playerSkin = img::convertToTrueColor($this->playerSkin); // Convert the image to true color if not a true color image $this->times[] = array('Convert-to-true-color-if-needed', $this->microtime_float()); $this->makeBackgroundTransparent(); // make background transparent (fix for weird rendering skins) $this->times[] = array('Made-Background-Transparent', $this->microtime_float()); // Quick fix for 1.8: // Copy the extra layers ontop of the base layers if ($this->layers) { $this->fixNewSkinTypeLayers(); } $this->calculateAngles(); $this->times[] = array('Angle-Calculations', $this->microtime_float()); $this->facesDetermination(); $this->times[] = array('Determination-of-faces', $this->microtime_float()); $this->generatePolygons(); $this->times[] = array('Polygon-generation', $this->microtime_float()); $this->memberRotation(); $this->times[] = array('Members-rotation', $this->microtime_float()); $this->createProjectionPlan(); $this->times[] = array('Projection-plan', $this->microtime_float()); $result = $this->displayImage($output); $this->times[] = array('Display-image', $this->microtime_float()); switch ($this->format) { case 'svg': file_put_contents($cacheFile, '<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' . $result . "\n"); break; case 'base64': echo file_put_contents($cacheFile, $result); break; case 'png': default: imagepng($result, $cacheFile); imagedestroy($result); break; } } /* Function renders the 3d image * */ private function microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } /* Function fixes issues with images that have a solid background * * Espects an tru color image. */ private function makeBackgroundTransparent() { // check if the corner box is one solid color $tempValue = null; $needRemove = true; for ($iH = 0; $iH < 8; $iH++) { for ($iV = 0; $iV < 8; $iV++) { $pixelColor = imagecolorat($this->playerSkin, $iH, $iV); $indexColor = imagecolorsforindex($this->playerSkin, $pixelColor); if ($indexColor['alpha'] > 120) { // the image contains transparancy, noting to do $needRemove = false; } if ($tempValue === null) { $tempValue = $pixelColor; } else if ($tempValue != $pixelColor) { // Cannot determine a background color, file is probably fine $needRemove = false; } } } $imgX = imagesx($this->playerSkin); $imgY = imagesy($this->playerSkin); $dst = img::createEmptyCanvas($imgX, $imgY); imagesavealpha($this->playerSkin, false); if ($needRemove) { // the entire block is one solid color. Use this color to clear the background. $r = ($tempValue >> 16) & 0xFF; $g = ($tempValue >> 8) & 0xFF; $b = $tempValue & 0xFF; //imagealphablending($dst, true); $transparant = imagecolorallocate($this->playerSkin, $r, $g, $b); imagecolortransparent($this->playerSkin, $transparant); // create fill $color = imagecolorallocate($dst, $r, $g, $b); } else { // create fill $color = imagecolorallocate($dst, 0, 0, 0); } // fill the areas that should not be transparant $positionMultiply = $imgX / 64; // head imagefilledrectangle($dst, 8 * $positionMultiply, 0 * $positionMultiply, 23 * $positionMultiply, 7 * $positionMultiply, $color); imagefilledrectangle($dst, 0 * $positionMultiply, 8 * $positionMultiply, 31 * $positionMultiply, 15 * $positionMultiply, $color); // right leg, body, right arm imagefilledrectangle($dst, 4 * $positionMultiply, 16 * $positionMultiply, 11 * $positionMultiply, 19 * $positionMultiply, $color); imagefilledrectangle($dst, 20 * $positionMultiply, 16 * $positionMultiply, 35 * $positionMultiply, 19 * $positionMultiply, $color); imagefilledrectangle($dst, 44 * $positionMultiply, 16 * $positionMultiply, 51 * $positionMultiply, 19 * $positionMultiply, $color); imagefilledrectangle($dst, 0 * $positionMultiply, 20 * $positionMultiply, 54 * $positionMultiply, 31 * $positionMultiply, $color); // left leg, left arm imagefilledrectangle($dst, 20 * $positionMultiply, 48 * $positionMultiply, 27 * $positionMultiply, 51 * $positionMultiply, $color); imagefilledrectangle($dst, 36 * $positionMultiply, 48 * $positionMultiply, 43 * $positionMultiply, 51 * $positionMultiply, $color); imagefilledrectangle($dst, 16 * $positionMultiply, 52 * $positionMultiply, 47 * $positionMultiply, 63 * $positionMultiply, $color); imagecopy($dst, $this->playerSkin, 0, 0, 0, 0, $imgX, $imgY); $this->playerSkin = $dst; return; } /* Function converts a 1.8 skin (which is not supported by * the script) to the old skin format. * * Espects an image. * Returns a croped image. */ private function fixNewSkinTypeLayers() { if (!$this->isNewSkinType) { return; } imagecopy($this->playerSkin, $this->playerSkin, 0, 16, 0, 32, 56, 16); // RL2, BODY2, RA2 imagecopy($this->playerSkin, $this->playerSkin, 16, 48, 0, 48, 16, 16); // LL2 imagecopy($this->playerSkin, $this->playerSkin, 32, 48, 48, 48, 16, 16); // LA2 } /* Function copys the extra layers of a 1.8 skin * onto the base layers so that it will still show. QUICK FIX, NEEDS BETTER FIX * * Espects an image. * Returns a croped image. */ private function calculateAngles() { global $cos_alpha, $sin_alpha, $cos_omega, $sin_omega; global $minX, $maxX, $minY, $maxY; // Rotation variables in radians (3D Rendering) $this->alpha = deg2rad($this->vR); // Vertical rotation on the X axis. $this->omega = deg2rad($this->hR); // Horizontal rotation on the Y axis. // Cosine and Sine values $cos_alpha = cos($this->alpha); $sin_alpha = sin($this->alpha); $cos_omega = cos($this->omega); $sin_omega = sin($this->omega); $this->members_angles['torso'] = array( 'cos_alpha' => cos(0), 'sin_alpha' => sin(0), 'cos_omega' => cos(0), 'sin_omega' => sin(0) ); $alpha_head = 0; $omega_head = deg2rad($this->hrh); $this->members_angles['head'] = $this->members_angles['helmet'] = array( // Head and helmet get the same calculations 'cos_alpha' => cos($alpha_head), 'sin_alpha' => sin($alpha_head), 'cos_omega' => cos($omega_head), 'sin_omega' => sin($omega_head) ); $alpha_right_arm = deg2rad($this->vrra); $omega_right_arm = 0; $this->members_angles['rightArm'] = array( 'cos_alpha' => cos($alpha_right_arm), 'sin_alpha' => sin($alpha_right_arm), 'cos_omega' => cos($omega_right_arm), 'sin_omega' => sin($omega_right_arm) ); $alpha_left_arm = deg2rad($this->vrla); $omega_left_arm = 0; $this->members_angles['leftArm'] = array( 'cos_alpha' => cos($alpha_left_arm), 'sin_alpha' => sin($alpha_left_arm), 'cos_omega' => cos($omega_left_arm), 'sin_omega' => sin($omega_left_arm) ); $alpha_right_leg = deg2rad($this->vrrl); $omega_right_leg = 0; $this->members_angles['rightLeg'] = array( 'cos_alpha' => cos($alpha_right_leg), 'sin_alpha' => sin($alpha_right_leg), 'cos_omega' => cos($omega_right_leg), 'sin_omega' => sin($omega_right_leg) ); $alpha_left_leg = deg2rad($this->vrll); $omega_left_leg = 0; $this->members_angles['leftLeg'] = array( 'cos_alpha' => cos($alpha_left_leg), 'sin_alpha' => sin($alpha_left_leg), 'cos_omega' => cos($omega_left_leg), 'sin_omega' => sin($omega_left_leg) ); $minX = 0; $maxX = 0; $minY = 0; $maxY = 0; } /* Function Calculates the angels * */ private function facesDetermination() { $this->visible_faces_format = array( 'front' => array(), 'back' => array() ); $this->visible_faces = array( 'head' => $this->visible_faces_format, 'torso' => $this->visible_faces_format, 'rightArm' => $this->visible_faces_format, 'leftArm' => $this->visible_faces_format, 'rightLeg' => $this->visible_faces_format, 'leftLeg' => $this->visible_faces_format ); $this->all_faces = array( 'back', 'right', 'top', 'front', 'left', 'bottom' ); // Loop each preProject and Project then calculate the visible faces for each - also display foreach ($this->visible_faces as $k => &$v) { unset($cube_max_depth_faces, $this->cube_points); $this->setCubePoints(); foreach ($this->cube_points as $cube_point) { $cube_point[0]->preProject(0, 0, 0, $this->members_angles[$k]['cos_alpha'], $this->members_angles[$k]['sin_alpha'], $this->members_angles[$k]['cos_omega'], $this->members_angles[$k]['sin_omega']); $cube_point[0]->project(); if (!isset($cube_max_depth_faces)) { $cube_max_depth_faces = $cube_point; } else if ($cube_max_depth_faces[0]->getDepth() > $cube_point[0]->getDepth()) { $cube_max_depth_faces = $cube_point; } } $v['back'] = $cube_max_depth_faces[1]; $v['front'] = array_diff($this->all_faces, $v['back']); } $this->setCubePoints(); unset($cube_max_depth_faces); foreach ($this->cube_points as $cube_point) { $cube_point[0]->project(); if (!isset($cube_max_depth_faces)) { $cube_max_depth_faces = $cube_point; } else if ($cube_max_depth_faces[0]->getDepth() > $cube_point[0]->getDepth()) { $cube_max_depth_faces = $cube_point; } $this->back_faces = $cube_max_depth_faces[1]; $this->front_faces = array_diff($this->all_faces, $this->back_faces); } } /* Function determinates faces * */ private function setCubePoints() { $this->cube_points = array(); $this->cube_points[] = array( new Point(array( 'x' => 0, 'y' => 0, 'z' => 0 )), array( 'back', 'right', 'top' )); // 0 $this->cube_points[] = array( new Point(array( 'x' => 0, 'y' => 0, 'z' => 1 )), array( 'front', 'right', 'top' )); // 1 $this->cube_points[] = array( new Point(array( 'x' => 0, 'y' => 1, 'z' => 0 )), array( 'back', 'right', 'bottom' )); // 2 $this->cube_points[] = array( new Point(array( 'x' => 0, 'y' => 1, 'z' => 1 )), array( 'front', 'right', 'bottom' )); // 3 $this->cube_points[] = array( new Point(array( 'x' => 1, 'y' => 0, 'z' => 0 )), array( 'back', 'left', 'top' )); // 4 $this->cube_points[] = array( new Point(array( 'x' => 1, 'y' => 0, 'z' => 1 )), array( 'front', 'left', 'top' )); // 5 $this->cube_points[] = array( new Point(array( 'x' => 1, 'y' => 1, 'z' => 0 )), array( 'back', 'left', 'bottom' )); // 6 $this->cube_points[] = array( new Point(array( 'x' => 1, 'y' => 1, 'z' => 1 )), array( 'front', 'left', 'bottom' )); // 7 } /* Function sets all cube points * */ private function generatePolygons() { $depths_of_face = array(); $this->polygons = array(); $cube_faces_array = array('front' => array(), 'back' => array(), 'top' => array(), 'bottom' => array(), 'right' => array(), 'left' => array() ); $this->polygons = array('helmet' => $cube_faces_array, 'head' => $cube_faces_array, 'torso' => $cube_faces_array, 'rightArm' => $cube_faces_array, 'leftArm' => $cube_faces_array, 'rightLeg' => $cube_faces_array, 'leftLeg' => $cube_faces_array ); $hd_ratio = $this->hd_ratio; $img_png = $this->playerSkin; // HEAD for ($i = 0; $i < 9 * $hd_ratio; $i++) { for ($j = 0; $j < 9 * $hd_ratio; $j++) { if (!isset($volume_points[$i][$j][-2 * $hd_ratio])) { $volume_points[$i][$j][-2 * $hd_ratio] = new Point(array( 'x' => $i, 'y' => $j, 'z' => -2 * $hd_ratio )); } if (!isset($volume_points[$i][$j][6 * $hd_ratio])) { $volume_points[$i][$j][6 * $hd_ratio] = new Point(array( 'x' => $i, 'y' => $j, 'z' => 6 * $hd_ratio )); } } } for ($j = 0; $j < 9 * $hd_ratio; $j++) { for ($k = -2 * $hd_ratio; $k < 7 * $hd_ratio; $k++) { if (!isset($volume_points[0][$j][$k])) { $volume_points[0][$j][$k] = new Point(array( 'x' => 0, 'y' => $j, 'z' => $k )); } if (!isset($volume_points[8 * $hd_ratio][$j][$k])) { $volume_points[8 * $hd_ratio][$j][$k] = new Point(array( 'x' => 8 * $hd_ratio, 'y' => $j, 'z' => $k )); } } } for ($i = 0; $i < 9 * $hd_ratio; $i++) { for ($k = -2 * $hd_ratio; $k < 7 * $hd_ratio; $k++) { if (!isset($volume_points[$i][0][$k])) { $volume_points[$i][0][$k] = new Point(array( 'x' => $i, 'y' => 0, 'z' => $k )); } if (!isset($volume_points[$i][8 * $hd_ratio][$k])) { $volume_points[$i][8 * $hd_ratio][$k] = new Point(array( 'x' => $i, 'y' => 8 * $hd_ratio, 'z' => $k )); } } } for ($i = 0; $i < 8 * $hd_ratio; $i++) { for ($j = 0; $j < 8 * $hd_ratio; $j++) { $this->polygons['head']['back'][] = new Polygon(array( $volume_points[$i][$j][-2 * $hd_ratio], $volume_points[$i + 1][$j][-2 * $hd_ratio], $volume_points[$i + 1][$j + 1][-2 * $hd_ratio], $volume_points[$i][$j + 1][-2 * $hd_ratio] ), imagecolorat($img_png, (32 * $hd_ratio - 1) - $i, 8 * $hd_ratio + $j)); $this->polygons['head']['front'][] = new Polygon(array( $volume_points[$i][$j][6 * $hd_ratio], $volume_points[$i + 1][$j][6 * $hd_ratio], $volume_points[$i + 1][$j + 1][6 * $hd_ratio], $volume_points[$i][$j + 1][6 * $hd_ratio] ), imagecolorat($img_png, 8 * $hd_ratio + $i, 8 * $hd_ratio + $j)); } } for ($j = 0; $j < 8 * $hd_ratio; $j++) { for ($k = -2 * $hd_ratio; $k < 6 * $hd_ratio; $k++) { $this->polygons['head']['right'][] = new Polygon(array( $volume_points[0][$j][$k], $volume_points[0][$j][$k + 1], $volume_points[0][$j + 1][$k + 1], $volume_points[0][$j + 1][$k] ), imagecolorat($img_png, $k + 2 * $hd_ratio, 8 * $hd_ratio + $j)); $this->polygons['head']['left'][] = new Polygon(array( $volume_points[8 * $hd_ratio][$j][$k], $volume_points[8 * $hd_ratio][$j][$k + 1], $volume_points[8 * $hd_ratio][$j + 1][$k + 1], $volume_points[8 * $hd_ratio][$j + 1][$k] ), imagecolorat($img_png, (24 * $hd_ratio - 1) - $k - 2 * $hd_ratio, 8 * $hd_ratio + $j)); } } for ($i = 0; $i < 8 * $hd_ratio; $i++) { for ($k = -2 * $hd_ratio; $k < 6 * $hd_ratio; $k++) { $this->polygons['head']['top'][] = new Polygon(array( $volume_points[$i][0][$k], $volume_points[$i + 1][0][$k], $volume_points[$i + 1][0][$k + 1], $volume_points[$i][0][$k + 1] ), imagecolorat($img_png, 8 * $hd_ratio + $i, $k + 2 * $hd_ratio)); $this->polygons['head']['bottom'][] = new Polygon(array( $volume_points[$i][8 * $hd_ratio][$k], $volume_points[$i + 1][8 * $hd_ratio][$k], $volume_points[$i + 1][8 * $hd_ratio][$k + 1], $volume_points[$i][8 * $hd_ratio][$k + 1] ), imagecolorat($img_png, 16 * $hd_ratio + $i, 2 * $hd_ratio + $k)); } } if ($this->display_hair) { // HELMET/HAIR $volume_points = array(); for ($i = 0; $i < 9 * $hd_ratio; $i++) { for ($j = 0; $j < 9 * $hd_ratio; $j++) { if (!isset($volume_points[$i][$j][-2 * $hd_ratio])) { $volume_points[$i][$j][-2 * $hd_ratio] = new Point(array( 'x' => $i * 9 / 8 - 0.5 * $hd_ratio, 'y' => $j * 9 / 8 - 0.5 * $hd_ratio, 'z' => -2.5 * $hd_ratio )); } if (!isset($volume_points[$i][$j][6 * $hd_ratio])) { $volume_points[$i][$j][6 * $hd_ratio] = new Point(array( 'x' => $i * 9 / 8 - 0.5 * $hd_ratio, 'y' => $j * 9 / 8 - 0.5 * $hd_ratio, 'z' => 6.5 * $hd_ratio )); } } } for ($j = 0; $j < 9 * $hd_ratio; $j++) { for ($k = -2 * $hd_ratio; $k < 7 * $hd_ratio; $k++) { if (!isset($volume_points[0][$j][$k])) { $volume_points[0][$j][$k] = new Point(array( 'x' => -0.5 * $hd_ratio, 'y' => $j * 9 / 8 - 0.5 * $hd_ratio,
php
MIT
68101b9efdcad6213a4468be289b59c4910828ff
2026-01-05T05:04:25.960579Z
true
SkinsRestorer/SkinSystem
https://github.com/SkinsRestorer/SkinSystem/blob/68101b9efdcad6213a4468be289b59c4910828ff/resources/server/i18n.class.php
resources/server/i18n.class.php
<?php /* * Fork this project on GitHub! * https://github.com/Philipp15b/php-i18n * * License: MIT */ class i18n { /** * Language file path * This is the path for the language files. You must use the '{LANGUAGE}' placeholder for the language or the script wont find any language files. * * @var string */ protected $filePath = './lang/lang_{LANGUAGE}.ini'; /** * Cache file path * This is the path for all the cache files. Best is an empty directory with no other files in it. * * @var string */ protected $cachePath = './langcache/'; /** * Fallback language * This is the language which is used when there is no language file for all other user languages. It has the lowest priority. * Remember to create a language file for the fallback!! * * @var string */ protected $fallbackLang = 'en'; /** * Merge in fallback language * Whether to merge current language's strings with the strings of the fallback language ($fallbackLang). * * @var bool */ protected $mergeFallback = false; /** * The class name of the compiled class that contains the translated texts. * @var string */ protected $prefix = 'L'; /** * Forced language * If you want to force a specific language define it here. * * @var string */ protected $forcedLang = NULL; /** * This is the separator used if you use sections in your ini-file. * For example, if you have a string 'greeting' in a section 'welcomepage' you will can access it via 'L::welcomepage_greeting'. * If you changed it to 'ABC' you could access your string via 'L::welcomepageABCgreeting' * * @var string */ protected $sectionSeparator = '_'; /* * The following properties are only available after calling init(). */ /** * User languages * These are the languages the user uses. * Normally, if you use the getUserLangs-method this array will be filled in like this: * 1. Forced language * 2. Language in $_GET['lang'] * 3. Language in $_SESSION['lang'] * 4. Fallback language * * @var array */ protected $userLangs = array(); protected $appliedLang = NULL; protected $langFilePath = NULL; protected $cacheFilePath = NULL; protected $isInitialized = false; /** * Constructor * The constructor sets all important settings. All params are optional, you can set the options via extra functions too. * * @param string [$filePath] This is the path for the language files. You must use the '{LANGUAGE}' placeholder for the language. * @param string [$cachePath] This is the path for all the cache files. Best is an empty directory with no other files in it. No placeholders. * @param string [$fallbackLang] This is the language which is used when there is no language file for all other user languages. It has the lowest priority. * @param string [$prefix] The class name of the compiled class that contains the translated texts. Defaults to 'L'. */ public function __construct($filePath = NULL, $cachePath = NULL, $fallbackLang = NULL, $prefix = NULL) { // Apply settings if ($filePath != NULL) { $this->filePath = $filePath; } if ($cachePath != NULL) { $this->cachePath = $cachePath; } if ($fallbackLang != NULL) { $this->fallbackLang = $fallbackLang; } if ($prefix != NULL) { $this->prefix = $prefix; } } public function init() { if ($this->isInitialized()) { throw new BadMethodCallException('This object from class ' . __CLASS__ . ' is already initialized. It is not possible to init one object twice!'); } $this->isInitialized = true; $this->userLangs = $this->getUserLangs(); // search for language file $this->appliedLang = NULL; foreach ($this->userLangs as $priority => $langcode) { $this->langFilePath = $this->getConfigFilename($langcode); if (file_exists($this->langFilePath)) { $this->appliedLang = $langcode; break; } } if ($this->appliedLang == NULL) { throw new RuntimeException('No language file was found.'); } // search for cache file $this->cacheFilePath = $this->cachePath . '/php_i18n_' . md5_file(__FILE__) . '_' . $this->prefix . '_' . $this->appliedLang . '.cache.php'; // whether we need to create a new cache file $outdated = !file_exists($this->cacheFilePath) || filemtime($this->cacheFilePath) < filemtime($this->langFilePath) || // the language config was updated ($this->mergeFallback && filemtime($this->cacheFilePath) < filemtime($this->getConfigFilename($this->fallbackLang))); // the fallback language config was updated if ($outdated) { $config = $this->load($this->langFilePath); if ($this->mergeFallback) $config = array_replace_recursive($this->load($this->getConfigFilename($this->fallbackLang)), $config); $compiled = "<?php class " . $this->prefix . " {\n" . $this->compile($config) . 'public static function __callStatic($string, $args) {' . "\n" . ' return vsprintf(constant("self::" . $string), $args);' . "\n}\n}\n" . "function " . $this->prefix . '($string, $args=NULL) {' . "\n" . ' $return = constant("' . $this->prefix . '::".$string);' . "\n" . ' return $args ? vsprintf($return,$args) : $return;' . "\n}"; if (!is_dir($this->cachePath)) mkdir($this->cachePath, 0755, true); if (file_put_contents($this->cacheFilePath, $compiled) === FALSE) { throw new Exception("Could not write cache file to path '" . $this->cacheFilePath . "'. Is it writable?"); } chmod($this->cacheFilePath, 0755); } require_once $this->cacheFilePath; } public function isInitialized() { return $this->isInitialized; } /** * getUserLangs() * Returns the user languages * Normally it returns an array like this: * 1. Forced language * 2. Language in $_GET['lang'] * 3. Language in $_SESSION['lang'] * 4. HTTP_ACCEPT_LANGUAGE * 5. Fallback language * Note: duplicate values are deleted. * * @return array with the user languages sorted by priority. */ public function getUserLangs() { $userLangs = array(); // Highest priority: forced language if ($this->forcedLang != NULL) { $userLangs[] = $this->forcedLang; } // 2nd highest priority: GET parameter 'lang' if (isset($_GET['lang']) && is_string($_GET['lang'])) { $userLangs[] = $_GET['lang']; } // 3rd highest priority: SESSION parameter 'lang' if (isset($_SESSION['lang']) && is_string($_SESSION['lang'])) { $userLangs[] = $_SESSION['lang']; } // 4th highest priority: HTTP_ACCEPT_LANGUAGE if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $part) { $userLangs[] = strtolower(substr($part, 0, 2)); } } // Lowest priority: fallback $userLangs[] = $this->fallbackLang; // remove duplicate elements $userLangs = array_unique($userLangs); // remove illegal userLangs $userLangs2 = array(); foreach ($userLangs as $key => $value) { // only allow a-z, A-Z and 0-9 and _ and - if (preg_match('/^[a-zA-Z0-9_-]*$/', $value) === 1) $userLangs2[$key] = $value; } return $userLangs2; } protected function getConfigFilename($langcode) { return str_replace('{LANGUAGE}', $langcode, $this->filePath); } protected function load($filename) { $ext = substr(strrchr($filename, '.'), 1); switch ($ext) { case 'properties': case 'ini': $config = parse_ini_file($filename, true); break; case 'yml': case 'yaml': $config = spyc_load_file($filename); break; case 'json': $config = json_decode(file_get_contents($filename), true); break; default: throw new InvalidArgumentException($ext . " is not a valid extension!"); } return $config; } /** * Recursively compile an associative array to PHP code. */ protected function compile($config, $prefix = '') { $code = ''; foreach ($config as $key => $value) { if (is_array($value)) { $code .= $this->compile($value, $prefix . $key . $this->sectionSeparator); } else { $fullName = $prefix . $key; if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $fullName)) { throw new InvalidArgumentException(__CLASS__ . ": Cannot compile translation key " . $fullName . " because it is not a valid PHP identifier."); } $code .= 'const ' . $fullName . ' = \'' . str_replace('\'', '\\\'', $value) . "';\n"; } } return $code; } public function getAppliedLang() { return $this->appliedLang; } public function getCachePath() { return $this->cachePath; } public function setCachePath($cachePath) { $this->fail_after_init(); $this->cachePath = $cachePath; } public function getFallbackLang() { return $this->fallbackLang; } public function setFallbackLang($fallbackLang) { $this->fail_after_init(); $this->fallbackLang = $fallbackLang; } public function setFilePath($filePath) { $this->fail_after_init(); $this->filePath = $filePath; } protected function fail_after_init() { if ($this->isInitialized()) { throw new BadMethodCallException('This ' . __CLASS__ . ' object is already initalized, so you can not change any settings.'); } } public function setMergeFallback($mergeFallback) { $this->fail_after_init(); $this->mergeFallback = $mergeFallback; } public function setPrefix($prefix) { $this->fail_after_init(); $this->prefix = $prefix; } public function setForcedLang($forcedLang) { $this->fail_after_init(); $this->forcedLang = $forcedLang; } /** * @deprecated Use setSectionSeparator. */ public function setSectionSeperator($sectionSeparator) { $this->setSectionSeparator($sectionSeparator); } public function setSectionSeparator($sectionSeparator) { $this->fail_after_init(); $this->sectionSeparator = $sectionSeparator; } }
php
MIT
68101b9efdcad6213a4468be289b59c4910828ff
2026-01-05T05:04:25.960579Z
false
SkinsRestorer/SkinSystem
https://github.com/SkinsRestorer/SkinSystem/blob/68101b9efdcad6213a4468be289b59c4910828ff/resources/server/libraries.php
resources/server/libraries.php
<?php require_once __DIR__ . '/i18n.class.php'; $i18n = new i18n(); $i18n->setCachePath(__DIR__ . '/../lang/cache'); $i18n->setFilePath(__DIR__ . '/../lang/{LANGUAGE}.ini'); // language file path $i18n->setFallbackLang('en'); $i18n->setMergeFallback(true); // make keys available from the fallback language $i18n->init(); global $i18n; $config = require_once(__DIR__ . '/../../config.nogit.php'); global $config; /* client remote address with ipv6 as (/64 block) prefix */ define('IP', preg_replace('/^(?:((?:[[:xdigit:]]+(:)){1,4})[[:xdigit:]:]*|((?:\d+\.){3}\d+))$/', '\1\2\3', $_SERVER['REMOTE_ADDR'])); /* Initialize PDO */ if ($config['am']['enabled'] == true) { $amPDOinstance = new PDO('mysql:host=' . $config['am']['host'] . '; port=' . $config['am']['port'] . '; dbname=' . $config['am']['database'] . ';', $config['am']['username'], $config['am']['password']); $amPDOinstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } $srPDOinstance = new PDO('mysql:host=' . $config['sr']['host'] . '; port=' . $config['sr']['port'] . '; dbname=' . $config['sr']['database'] . ';', $config['sr']['username'], $config['sr']['password']); $srPDOinstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /* When working with AuthMe or SkinsRestorer database */ function query($type, $mysqlcommand, $key = []) { if ($type == 'am') { global $amPDOinstance; $result = $amPDOinstance->prepare($mysqlcommand); $result->execute($key); } else if ($type == 'sr') { global $srPDOinstance; $result = $srPDOinstance->prepare($mysqlcommand); $result->execute($key); } return $result; } function printDataAndDie($data = []) { if (is_string($data)) { $data = ['title' => $data]; } $defaults = ['type' => 'success', 'title' => L::gnrl_sucsspop, 'heightAuto' => False, 'showConfirmButton' => False]; if (isset($data['refresh'])) { $data['refresh'] = 350; } // refresh in 350ms $data = array_replace($defaults, $data); if (!isset($data['success'])) { $data['success'] = empty($data['error']); } header('Content-Type: application/json'); die(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); } function printErrorAndDie($data = []) { if (is_string($data)) { $data = ['title' => $data]; } $defaults = ['type' => 'error', 'title' => L::gnrl_errorpop, 'showCloseButton' => True, 'footer' => '']; $data = array_replace($defaults, $data); $url = 'https://status.mineskin.org'; $dta = curl(cacheGrab($url, $url, __DIR__ . '/../../', (60 * 60))); preg_match('/https:\/\/status\.mineskin\.org\/api\/getMonitorList\/\w+/', $dta, $match); $ret = curl(cacheGrab($match[0], $match[0], __DIR__ . '/../../', 60)); foreach (json_decode($ret, true)['psp']['monitors'] as $value) { if ($value['name'] == 'Mineskin API' and $value['statusClass'] != 'success') { $expl = explode('/', $value['monitorId']); $msg = str_replace("%site%", $value['name'], L::gnrl_srvofl); $data['footer'] = $data['footer'] . "\n" . '<div class="col"><a href="https://status.mineskin.org"><i class="fas fa-exclamation-circle" style="padding-right: 5px;"></i>' . $msg . '</a></div>'; error_log($msg . ' (https://status.mineskin.org)'); } } if (isset($data['footer'])) { $data['footer'] = '<div class="container">' . $data['footer'] . '</div>'; } printDataAndDie($data); } /* GitHub getLastestVersion */ function getLatestVersion() { $nwVer = cacheGrab('https://api.github.com/repos/SkinsRestorer/SkinSystem/releases/latest', 'latest_version', __DIR__ . '/../../', (24 * 60 * 60)); return json_decode(curl($nwVer), true)['tag_name']; } function curl($url) { if (preg_match('/^https?:\/\//', $url)) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'The SkinSystem'); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 5); $response = curl_exec($ch); if ($response === false) { printErrorAndDie(str_replace("%err%", curl_error($ch), L::gnrl_crlerr)); } curl_close($ch); return ($response); } else { return (file_get_contents($url)); } } // downloads to cache if need be, removes unused cache files, return location of cache file. function cacheGrab($url, $nm, $dirhead = '', $max_cache = false, $hchk = false) { global $config; $cdir = $dirhead . $config['cache_dir']; if (!is_dir($cdir)) { mkdir($cdir, 0775, true); } $file = $cdir . preg_replace('/[^\w\.]/', '_', $nm); if (!$max_cache) { if (is_file($file)) { touch($file); } } // no max cache? touch so it's not caught by cleanup if (($max_cache && is_file($file) && (time() - filemtime($file) >= $max_cache)) || !is_file($file)) { $filecont = curl($url); if ($hchk) { for ($i = 0; $i < 10; $i++) { if (hash($hchk[0], $filecont) != $hchk[1]) { $filecont = curl($url); } else { break; } } } file_put_contents($file, $filecont); } cacheClean($dirhead); return $file; } function cacheClean($dirhead = '') { // initiate cleanup only every 15 mins or so global $config; $cdir = $dirhead . $config['cache_dir']; if (!is_dir($cdir)) { mkdir($cdir, 0775, true); } $now = time(); if ($now - filemtime($cdir . 'index.php') >= (15 * 60)) { touch($cdir . 'index.php'); foreach (glob($cdir . '*') as $cl) { if (is_file($cl) && ($now - filemtime($cl) >= $config['cache_for_days'] * 24 * 60 * 60)) { unlink($cl); } } } } ?>
php
MIT
68101b9efdcad6213a4468be289b59c4910828ff
2026-01-05T05:04:25.960579Z
false
SkinsRestorer/SkinSystem
https://github.com/SkinsRestorer/SkinSystem/blob/68101b9efdcad6213a4468be289b59c4910828ff/resources/server/skinCore.php
resources/server/skinCore.php
<?php require_once(__DIR__ . '/libraries.php'); session_start(); /* Initialize playername */ if ($config['am']['enabled'] == true && !empty($_SESSION['username'])) { $playername = $_SESSION['username']; } else if ($config['am']['enabled'] != true && !empty($_POST['username'])) { $playername = $_POST['username']; } if (empty($playername)) { printErrorAndDie(str_replace("%rsn%", L::skcr_error_plnm, L::skcr_error)); } /* Check a request from users, Does it valid? --> If it valid do the statment below */ if (!empty($_POST['isSlim']) && !empty($_POST['uploadtype']) && isset($_FILES['file']['tmp_name']) && isset($_POST['url'])) { /* Initialize Data for sending to MineSkin API */ $postparams = ['visibility' => 0]; if ($_POST['isSlim'] == 'true') { $postparams['model'] = 'slim'; } /* Send with URL */ if ($_POST['uploadtype'] == 'url' && !empty($_POST['url'])) { $postparams['url'] = $_POST['url']; $endpointURL = 'https://api.mineskin.org/generate/url'; /* Send with File */ } else { $file = $_FILES['file']; $validFileType = ['image/jpeg', 'image/png']; /* Check If the skin is a Minecraft's skin format */ if (!in_array($file['type'], $validFileType)) { printErrorAndDie(L::skcr_skfmt); } list($skinWidth, $skinHeight) = getimagesize($file['tmp_name']); if (($skinWidth != 64 && $skinHeight != 64) || ($skinWidth != 64 && $skinHeight != 32)) { printErrorAndDie(L::skcr_invsk); } $postparams['file'] = new CURLFile($file['tmp_name'], $file['type'], $file['name']); $endpointURL = 'https://api.mineskin.org/generate/upload'; } /* cURL to MineSkin API */ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpointURL); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postparams); $response = curl_exec($ch); curl_close($ch); if ($response == false) { /* cURL ERROR */ printErrorAndDie(str_replace("%rsn%", L::skcr_error_mscurl, L::skcr_error)); } $json = json_decode($response, true); /* Prevent from duplicated casual skin of SkinsRestorer */ $transformedName = ' ' . $playername; /* MineSkin API returned unusable data */ if (empty($json['data']['texture']['value']) || empty($json['data']['texture']['signature'])) { printErrorAndDie(str_replace("%rsn%", L::skcr_error_msinvl, L::skcr_error)); } /* Assign data for putting to SkinsRestorer Storage */ $value = $json['data']['texture']['value']; $signature = $json['data']['texture']['signature']; /* https://github.com/Th3Tr0LLeR/SkinsRestorer---Maro/blob/9358d5727cfc7a1dce4e2af9412679999be5b519/src/main/java/skinsrestorer/shared/storage/SkinStorage.java#L274 From condition in SkinRestorer source code, ``` if (timestamp + TimeUnit.MINUTES.toMillis(Config.SKIN_EXPIRES_AFTER) <= System.currentTimeMillis()) { ``` Variable "timestamp", toMillis(...), currentTimeMillis() are long, except SKIN_EXPIRES_AFTER which is integer. This mean the left side of operator is less than or equal to Long.MAX_VALUE (2^63 - 1). Since we want to get maximum timestamp, we substitute SKIN_EXPIRES_AFTER with Integer.MAX_VALUE (2^31 - 1), and we get (2^31 - 1) * 60 * 1000 where 60 is used for convert to second and 1000 to convert to millisecond. To get maximum timestamp, we substract Long.MAX_VALUE with value above with get us: (2^63 - 1) - ((2^31 - 1) * 60 * 1000) = 9223243187835955807 */ $timestamp = "9223243187835955807"; /* Storage Writing (Skins Table) */ query('sr', "INSERT INTO {$config['sr']['skintable']} (Nick, Value, Signature, timestamp) VALUES (?, ?, ?, ?) " . "ON DUPLICATE KEY UPDATE Nick=VALUES(Nick), Value=VALUES(Value), Signature=VALUES(Signature), " . "timestamp=VALUES(timestamp)", [$transformedName, $value, $signature, $timestamp] ); /* Storage Writing (Players Table) */ query('sr', "INSERT INTO {$config['sr']['playertable']} (Nick, Skin) VALUES (?, ?) " . "ON DUPLICATE KEY UPDATE Nick=VALUES(Nick), Skin=VALUES(Skin)", [$playername, $transformedName] ); printDataAndDie(['title' => L::skcr_upld_title, 'text' => L::skcr_upld_text, 'refresh' => True]); } printErrorAndDie(str_replace("%rsn%", L::skcr_error_endprg, L::skcr_error));
php
MIT
68101b9efdcad6213a4468be289b59c4910828ff
2026-01-05T05:04:25.960579Z
false
HurryBy/CloudDiskAnalysis
https://github.com/HurryBy/CloudDiskAnalysis/blob/28f7f8334fc5f49f446ae54b0e37fc26670da9cf/网页版/public/api/lanzou.php
网页版/public/api/lanzou.php
<?php error_reporting(0); $downloadLink = ""; $docname = ""; function rand_IP() { $ip2id = round(rand(600000, 2550000) / 10000); $ip3id = round(rand(600000, 2550000) / 10000); $ip4id = round(rand(600000, 2550000) / 10000); $arr_1 = array("218", "218", "66", "66", "218", "218", "60", "60", "202", "204", "66", "66", "66", "59", "61", "60", "222", "221", "66", "59", "60", "60", "66", "218", "218", "62", "63", "64", "66", "66", "122", "211"); $randarr = mt_rand(0, count($arr_1) - 1); $ip1id = $arr_1[$randarr]; return $ip1id . "." . $ip2id . "." . $ip3id . "." . $ip4id; } function get_file_info($data) { $info = []; $name = zhengze('/"md">(.*) <span/', $data); $info[0] = $name; $size = zhengze('/mtt">\( (.*) \)<\/span>/', $data); $info[1] = $size; $author = zhengze('/发布者:<\/span>(.*?) <span/', $data); $info[2] = $author; $time = zhengze('/时间:<\/span>(.*?) <span/', $data); $info[3] = $time; $description = zhengze('/mdo">[\s\S](.*?)<\/div>/m', $data); $info[4] = $description; return $info; } function get_file_info_vip($data) { $info = []; $name = zhengze('/<div class="appname">(.*?)</div>', $data); $info[0] = $name; $size = zhengze('/下载 \((.*?)\)/', $data); $info[1] = $size; $author = zhengze('/<div class="user-name">(.*?)<\/div>/', $data); $info[2] = $author; // $time = zhengze('/时间:<\/span>(.*?) <span/', $data); $info[3] = NULL; // $description = zhengze('/mdo">[\s\S](.*?)<\/div>/m', $data); $info[4] = NULL; return $info; } function get_redirect_url($url, $ua = 0) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $httpheader[] = "Accept:*/*"; $httpheader[] = "Accept-Encoding:gzip,deflate,sdch"; $httpheader[] = "Accept-Language:zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6"; curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader); curl_setopt($ch, CURLOPT_HEADER, true); if ($ua) { curl_setopt($ch, CURLOPT_USERAGENT, $ua); } else { curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Linux; U; Android 4.0.4; es-mx; HTC_One_X Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0"); } curl_setopt($ch, CURLOPT_NOBODY, 1); curl_setopt($ch, CURLOPT_ENCODING, "gzip"); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $ret = curl_exec($ch); curl_close($ch); preg_match("/Location: (.*?)\r\n/iU", $ret, $location); return $location[1]; } function c($url, $ua = 0) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_REFERER, $url); $headers = array( "accept-language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6" ); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); if ($ua) { curl_setopt($ch, CURLOPT_USERAGENT, $ua); } else { curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Android 4.4; Mobile; rv:70.0) Gecko/70.0 Firefox/70.0"); } $data = curl_exec($ch); curl_close($ch); return $data; } function zhengze($biaodashi, $link) { $soisMatched = preg_match($biaodashi, $link, $somatches); return $somatches[1]; } function start($link, $password) { $result = array( 'code' => 200, 'data' => array(), 'msg' => "解析成功" ); // 去除前缀 $link = str_replace("https://", "", $link); $link = str_replace("http://", "", $link); // 获取链接信息 $lanzou = zhengze('/.lanzou(.*).com/', $link); $lanzou_prefix = zhengze('/(.*).lanzou' . $lanzou . '.com/', $link); $length = strlen($link) - strrpos($link, "/") + 1; $lanzou_id = substr($link, strrpos($link, "/") + 1, $length); // 修正链接 $realLink = "https://" . $lanzou_prefix . ".lanzou" . $lanzou . ".com/" . $lanzou_id; $testData = c($realLink, ""); $accessiblePrefix = ['w', 'k', 'i', 'l']; if (stripos($testData, '谨防刷单兼职,网贷,金融,裸聊敲诈,赌博等诈骗,请立即举报') == FALSE) { for ($i = 0; $i <= count($accessiblePrefix) - 1; $i++) { $lanzou = $accessiblePrefix[$i]; $realLink = "https://" . $lanzou_prefix . ".lanzou" . $lanzou . ".com/" . $lanzou_id; $testData = c($realLink, ""); if (stripos($testData, '谨防刷单兼职,网贷,金融,裸聊敲诈,赌博等诈骗,请立即举报') != FALSE || stripos($testData, '文件受密码保护,请输入密码继续下载') != FALSE) { break; } if ($i == count($accessiblePrefix) - 1) { return array( "code" => 202, "msg" => '链接错误' ); } } } $curlData = $testData; $documentData = c($realLink, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"); if (stripos($documentData, '文件受密码保护,请输入密码继续下载')) { $curlData = $documentData; // 文件夹 preg_match_all('/var (.*)\';/m', $curlData, $somatches, PREG_SET_ORDER, 0); $docname = $somatches[0][1]; $t = $somatches[1][1]; $k = $somatches[2][1]; $docname = zhengze('/=\'(.*)/', $docname); $t = zhengze('/= \'(.*)/', $t); $k = zhengze('/= \'(.*)/', $k); $fid = zhengze('/\'fid\':(.*),/', $curlData); $uid = zhengze('/\'uid\':\'(.*)\'/', $curlData); $pgs = 1; $post_data = array('lx' => 2, 'fid' => intval($fid), 'uid' => $uid, 'pg' => intval($pgs), 'rep' => '0', 't' => $t, 'k' => $k, 'up' => 1, 'ls' => 1, 'pwd' => $password); $postdata = http_build_query($post_data); $options = array('http' => array( 'method' => 'POST', 'header' => 'Referer: ' . "https:" . $lanzou_prefix . ".lanzou" . $lanzou . ".com/" . '\\r\\n' . 'Accept-Language:zh-CN,zh;q=0.9\\r\\n', 'content' => $postdata, )); $context = stream_context_create($options); $data = file_get_contents('https://' . $lanzou_prefix . '.lanzou' . $lanzou . '.com/filemoreajax.php', false, $context); $dataa = json_decode($data, true); if ($dataa['zt'] != 1) { return array( 'code' => 201, 'msg' => '密码错误' ); } $i = 0; while (1) { if ($dataa['text'][$i]['id'] != NULL) { $file_id = $dataa['text'][$i]['id']; $curlData = c("https://" . $lanzou_prefix . ".lanzou" . $lanzou . ".com/tp/" . $file_id, ""); $pototo = zhengze('/var tedomain = \'(.*)\';/', $curlData); if (!$pototo) { $lanzou = "w"; $curlData = c("https://" . $lanzou_prefix . ".lanzou" . $lanzou . ".com/tp/" . $lanzou_id, ""); $pototo = zhengze('/var tedomain = (.*)/', $curlData); } $spototo = zhengze('/var domianload = \'(.*)\';/', $curlData); $resultabc = $pototo . $spototo; $resultabc = get_redirect_url($resultabc, "Mozilla/5.0 (Android 4.4; Mobile; rv:70.0) Gecko/70.0 Firefox/70.0"); $info = get_file_info($curlData); array_push($result['data'], array( 'id' => $dataa['text'][$i]['id'], "name" => $info[0], "size" => $info[1], "author" => $info[2], "time" => $info[3], "description" => $info[4], "DownloadURL" => $resultabc )); } else { break; } $i = $i + 1; } return $result; } // 有密码的 if ($password) { if (stripos($curlData, '分享者')) { // 普通用户 $realLink = "https://" . $lanzou_prefix . ".lanzou" . $lanzou . ".com/tp/" . $lanzou_id; $curlData = c($realLink, ""); $posign = zhengze('/var postsign = (.*)/', $curlData); $posign = str_replace("'", "", $posign); $posign = str_replace(";", "", $posign); $info = get_file_info($curlData); } else { // 会员用户 $posign = zhengze('/sign=([^&]*)/', $curlData); $info = get_file_info_vip($curlData); } // 有密码请求网址 $post_data = array('action' => 'downprocess', 'sign' => $posign, 'p' => $password); $postdata = http_build_query($post_data); $options = array('http' => array( 'method' => 'POST', 'header' => 'Referer: ' . "https:" . $lanzou_prefix . ".lanzou" . $lanzou . ".com/" . '\\r\\n' . 'Accept-Language:zh-CN,zh;q=0.9\\r\\n', 'content' => $postdata, )); $context = stream_context_create($options); $data = file_get_contents('https://' . $lanzou_prefix . '.lanzou' . $lanzou . '.com/ajaxm.php', false, $context); $data123 = json_decode($data, true); $dom = $data123['dom']; $url = $data123['url']; $zt = $data123['zt']; if ($zt != 1) { return array( 'code ' => 201, 'msg' => '密码错误' ); } $resultUrl = $dom . '/file/' . $url; $headers = array( 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding: gzip, deflate', 'Accept-Language: zh-CN,zh;q=0.9', 'Cache-Control: no-cache', 'Connection: keep-alive', 'Pragma: no-cache', 'Upgrade-Insecure-Requests: 1', 'X-Forwarded-For: ' . rand_IP() ); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $resultUrl); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLINFO_HEADER_OUT, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $data = curl_exec($curl); $url = curl_getinfo($curl); curl_close($curl); $downloadLink = $url["redirect_url"]; array_push($result['data'], array( "id" => $lanzou_id, "password" => $password, "name" => $info[0], "size" => $info[1], "author" => $info[2], "time" => $info[3], "description" => $info[4], "DownloadURL" => $downloadLink )); return $result; } // 无密码的 if (stripos($curlData, '分享者')) { // 普通用户 $realLink = "https://" . $lanzou_prefix . ".lanzou" . $lanzou . ".com/tp/" . $lanzou_id; $curlData = c($realLink, ""); $pototo = zhengze('/var tedomain = \'(.*)\';/', $curlData); if (!$pototo) { $lanzou = "w"; $curlData = c("https://" . $lanzou_prefix . ".lanzou" . $lanzou . ".com/tp/" . $lanzou_id, ""); $pototo = zhengze('/var tedomain = (.*)/', $curlData); } $spototo = zhengze('/var domianload = \'(.*)\';/', $curlData); $resultUrl = $pototo . $spototo; $resultUrl = get_redirect_url($resultUrl, "Mozilla/5.0 (Android 4.4; Mobile; rv:70.0) Gecko/70.0 Firefox/70.0"); $downloadLink = $resultUrl; $info = get_file_info($curlData); array_push($result['data'], array( "id" => $lanzou_id, "name" => $info[0], "size" => $info[1], "author" => $info[2], "time" => $info[3], "description" => $info[4], "DownloadURL" => $downloadLink )); } else { // 会员用户 $urlpt = zhengze('/var urlpt = \'(.*)\';/', $curlData); $downloadLink = zhengze('/var link = \'(.*)\';/', $curlData); $resultUrl = $urlpt . $downloadLink; $resultUrl = get_redirect_url($resultUrl, "Mozilla/5.0 (Android 4.4; Mobile; rv:70.0) Gecko/70.0 Firefox/70.0"); $info = get_file_info_vip($curlData); array_push($result['data'], array( "id" => $lanzou_id, "name" => $info[0], "size" => $info[1], "author" => $info[2], "time" => $info[3], "description" => $info[4], "DownloadURL" => $resultUrl )); } return $result; } $link = isset($_GET['link']) ? $_GET['link'] : NULL; $password = isset($_GET['pwd']) ? $_GET['pwd'] : NULL; $redirect = isset($_GET['red']) ? $_GET['red'] : NULL; $result = start($link, $password); if ($redirect == NULL) { header('Access-Control-Allow-Origin:*'); header('Content-Type:application/json'); if ($result['data'][0]['DownloadURL'] == NULL && $result['code'] != 201) { $result = array( "code" => 202, "msg" => '解析失败', ); } echo json_encode($result, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit(); } else { if ($result['data'][1] == NULL) { header("HTTP/1.1 301 Moved Permanently"); header('Location: ' . $result['data'][0]['DownloadURL']); } else { header('Access-Control-Allow-Origin:*'); header('Content-Type:application/json'); $json = array( "code" => 200, "msg" => '解析成功(多文件不支持直接跳转)', "data" => $result ); echo json_encode($json, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } }
php
Apache-2.0
28f7f8334fc5f49f446ae54b0e37fc26670da9cf
2026-01-05T05:04:21.446543Z
false
HurryBy/CloudDiskAnalysis
https://github.com/HurryBy/CloudDiskAnalysis/blob/28f7f8334fc5f49f446ae54b0e37fc26670da9cf/网页版/public/api/yidong.php
网页版/public/api/yidong.php
<?php function curlPost($url, $post_data = array(), $timeout = 5, $header = "", $data_type = "") { $header = empty($header) ? '' : $header; //支持json数据数据提交 if ($data_type == 'json') { $post_string = json_encode($post_data); } elseif ($data_type == 'array') { $post_string = $post_data; } elseif (is_array($post_data)) { $post_string = http_build_query($post_data, '', '&'); } $ch = curl_init(); // 启动一个CURL会话 curl_setopt($ch, CURLOPT_URL, $url); // 要访问的地址 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查 // https请求 不验证证书和hosts curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在 curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); // Post提交的数据包 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // 设置超时限制防止死循环 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回 $result = curl_exec($ch); curl_close($ch); return $result; } function get($link) { $options = array('http' => array( 'method' => 'GET', )); $context = stream_context_create($options); $data = file_get_contents($link, false, $context); return $data; } function start($link = 0, $password = '') { $result = array( 'code' => 200, 'data' => array(), 'msg' => "解析成功" ); // 分割 $re = '/data=([^&]*)/m'; preg_match_all($re, $link, $matches, PREG_SET_ORDER, 0); $data = $matches[0][1] ? $matches[0][1] : NULL; // 替换 str_replace("&data=$data", '', $link); str_replace("&isShare=1", '', $link); str_replace("&isShare=0", '', $link); str_replace("&pwd=$password", '', $link); // 编码 $link = urlencode($link); // 请求 $response = get("https://www.ecpan.cn/drive/fileextoverrid.do?chainUrlTemplate=$link&data=$data&parentId=-1"); $json = json_decode($response, true); // 获取数据 $fileName = $json["var"]["chainFileInfo"]["jsonFileList"][0]["fileName"]; $fileSize = $json["var"]["chainFileInfo"]["jsonFileList"][0]["fileSize"]; $cloudpFileList = $json["var"]["chainFileInfo"]["cloudpFileList"]; // 获取信息 $groupId = $cloudpFileList[0]["groupId"]; $shareId = $json["var"]["chainFileInfo"]["shareId"]; // 是否是文件夹 if ($cloudpFileList == NULL || $cloudpFileList == '') { //// 是文件夹 // 获取信息 $cloudpFile = $json["var"]["chainFileInfo"]['cloudpFile']; $appFileID = $cloudpFile['appFileId']; $groupId = $cloudpFile['groupId']; $rootUsn = $cloudpFile['rootUsn']; //构建GET请求 $response = get("https://www.ecpan.cn/drive/fileextoverrid.do?rootUsn=$rootUsn&data=$data&shareId=$shareId&parentId=$appFileID&extCodeFlag=0&chainUrlTemplate=$link"); $json = json_decode($response, true); } // 获取文件个数 $isFinish = FALSE; $Length = 0; while (!$isFinish) { if ($json['var']['chainFileInfo']['cloudpFileList'][$Length]['appFileId'] == NULL) { $isFinish = TRUE; } $Length++; } $Length = $Length - 2; $cloudpFileList = $json['var']['chainFileInfo']['cloudpFileList']; for ($i = 0; $i <= $Length; $i++) { // 构建cloudpFileList $tempCloudpFileList = $cloudpFileList[$i]; $tempCloudpFileList['downloadUrl'] = NULL; //// 请求下载链接 // 是否是加密链接 if ($password != NULL) { // 构建POST请求 $postdata = array( 'extCodeFlag' => 1, 'extractionCode' => $password, 'groupId' => $groupId, 'isIp' => 0, 'shareId' => $shareId, 'fileIdList' => array($tempCloudpFileList) ); $header = array("Content-Type:multipart/x-www-form-urlencoded"); $dlData = curlPost("https://www.ecpan.cn/drive/sharedownload.do", $postdata, 5, $header, 'json'); } else { // 构建POST请求 $postdata = array( 'extCodeFlag' => 0, 'groupId' => $groupId, 'isIp' => 0, 'shareId' => $shareId, 'fileIdList' => array($tempCloudpFileList) ); // print(json_encode($postdata)); $header = array("Content-Type:multipart/x-www-form-urlencoded"); $dlData = curlPost("https://www.ecpan.cn/drive/sharedownload.do", $postdata, 5, $header, 'json'); } $json1 = json_decode($dlData, true); $downloadLink = $json1["var"]["downloadUrl"]; // 输出 $fileName = $tempCloudpFileList["fileName"]; $fileSize = $tempCloudpFileList["fileSize"]; array_push($result['data'], array( "name" => $fileName, "size" => $fileSize, "DownloadURL" => $downloadLink )); } return $result; } $link = isset($_GET['link']) ? $_GET['link'] : NULL; $password = isset($_GET['pwd']) ? $_GET['pwd'] : NULL; $redirect = isset($_GET['red']) ? $_GET['red'] : NULL; $result = start($link, $password); if ($redirect == NULL) { header('Access-Control-Allow-Origin:*'); header('Content-Type:application/json'); echo json_encode($result, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit(); } else { if ($result['data'][1] == NULL) { header("HTTP/1.1 301 Moved Permanently"); header('Location: ' . $result['data'][0]['DownloadURL']); } else { header('Access-Control-Allow-Origin:*'); header('Content-Type:application/json'); $json = array( "code" => 200, "msg" => '解析成功(多文件不支持直接跳转)', "data" => $result ); echo json_encode($json, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } }
php
Apache-2.0
28f7f8334fc5f49f446ae54b0e37fc26670da9cf
2026-01-05T05:04:21.446543Z
false
HurryBy/CloudDiskAnalysis
https://github.com/HurryBy/CloudDiskAnalysis/blob/28f7f8334fc5f49f446ae54b0e37fc26670da9cf/网页版/public/api/123.php
网页版/public/api/123.php
<?php function post($link, $post_data) { $postdata = http_build_query($post_data); $options = array('http' => array( 'method' => 'POST', 'content' => $postdata, )); $context = stream_context_create($options); $data = file_get_contents($link, false, $context); return $data; } function get_redirect_url($url) { $re = '/\?params=(.*)&/m'; preg_match_all($re, $url, $matches, PREG_SET_ORDER, 0); return base64_decode($matches[0][1]); } function start($link = 0, $password = '') { $result = array( 'code' => 200, 'data' => array(), 'msg' => "解析成功" ); // Get Share_Key $re = '/s\/(.*).html/m'; preg_match_all($re, $link, $matches, PREG_SET_ORDER, 0); $share_key = $matches[0][1] ? $matches[0][1] : NULL; if ($share_key == NULL) { return array( "code" => 201, "message" => "分享地址错误" ); } $data = file_get_contents("https://www.123pan.com/b/api/share/get?limit=100&next=1&orderBy=share_id&orderDirection=desc&shareKey=$share_key&SharePwd=$password&ParentFileId=0&Page=1", false); $data = json_decode($data, true); if ($data['code'] == 5103) { return array( "code" => 201, "message" => $data['message'] ); } else { // 开始获取链接 // 1.获取Len if ($data['data']['InfoList'][0]['Type'] == 1) { // 文件夹 $ID = $data['data']['InfoList'][0]['FileId']; $result = array( 'code' => 200, 'data' => array(), 'msg' => "解析成功", 'docname' => $data['data']['InfoList'][0]['FileName'] ); $data = file_get_contents("https://www.123pan.com/b/api/share/get?limit=100&next=1&orderBy=share_id&orderDirection=desc&shareKey=$share_key&SharePwd=$password&ParentFileId=$ID&Page=1", false); $data = json_decode($data, true); if ($data['code'] == 5103) { return array( "code" => 201, "message" => $data['message'] ); } } $length = $data['data']['Len']; // 2. 循环Length遍 for ($i = 1; $i <= $length; $i++) { // 获取InfoList $infoList = $data['data']['InfoList'][$i - 1]; $FileID = $infoList['FileId']; $FileName = $infoList['FileName']; $Size = $infoList['Size']; $S3KeyFlag = $infoList['S3KeyFlag']; $Etag = $infoList['Etag']; $post_data = array( 'Etag' => $Etag, 'FileID' => $FileID, 'S3keyFlag' => $S3KeyFlag, 'ShareKey' => $share_key, 'Size' => $Size ); $dataA = post('https://www.123pan.com/b/api/share/download/info', $post_data); $dataA = json_decode($dataA, true); $DownloadURL = $dataA['data']['DownloadURL']; $DownloadURL1 = get_redirect_url($DownloadURL); array_push($result['data'], array( "name" => $FileName, "size" => $Size, "DownloadURL" => $DownloadURL1 )); } return $result; } } $link = isset($_GET['link']) ? $_GET['link'] : NULL; $password = isset($_GET['pwd']) ? $_GET['pwd'] : NULL; $redirect = isset($_GET['red']) ? $_GET['red'] : NULL; $result = start($link, $password); if ($redirect == NULL) { header('Access-Control-Allow-Origin:*'); header('Content-Type:application/json'); if ($result['data'][0]['DownloadURL'] == NULL && $result['code'] != 201) { $result = array( "code" => 202, "msg" => '链接错误/失效/解析失败', ); } echo json_encode($result, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit(); } else { if ($result['data'][1] == NULL) { header("HTTP/1.1 301 Moved Permanently"); header('Location: ' . $result['data'][0]['DownloadURL']); } else { header('Access-Control-Allow-Origin:*'); header('Content-Type:application/json'); $json = array( "code" => 200, "msg" => '解析成功(多文件不支持直接跳转)', "data" => $result ); echo json_encode($json, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } }
php
Apache-2.0
28f7f8334fc5f49f446ae54b0e37fc26670da9cf
2026-01-05T05:04:21.446543Z
false
mschwarzmueller/laravel-basics-youtube
https://github.com/mschwarzmueller/laravel-basics-youtube/blob/1295312ab4e0b26f839fb161e9aedf9044559422/server.php
server.php
<?php /** * Laravel - A PHP Framework For Web Artisans * * @package Laravel * @author Taylor Otwell <taylorotwell@gmail.com> */ $uri = urldecode( parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ); // This file allows us to emulate Apache's "mod_rewrite" functionality from the // built-in PHP web server. This provides a convenient way to test a Laravel // application without having installed a "real" web server software here. if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) { return false; } require_once __DIR__.'/public/index.php';
php
MIT
1295312ab4e0b26f839fb161e9aedf9044559422
2026-01-05T05:04:32.355687Z
false
mschwarzmueller/laravel-basics-youtube
https://github.com/mschwarzmueller/laravel-basics-youtube/blob/1295312ab4e0b26f839fb161e9aedf9044559422/app/User.php
app/User.php
<?php namespace App; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; class User extends Model implements Authenticatable { use \Illuminate\Auth\Authenticatable; public function posts() { return $this->hasMany('App\Post'); } public function likes() { return $this->hasMany('App\Like'); } }
php
MIT
1295312ab4e0b26f839fb161e9aedf9044559422
2026-01-05T05:04:32.355687Z
false