Add 'community_server/' from commit 'b6544b9e69fb85d4da100934675323c3e8c8ef67'

git-subtree-dir: community_server
git-subtree-mainline: ff11f6efe35bba180260fe84077bcd94298895c1
git-subtree-split: b6544b9e69fb85d4da100934675323c3e8c8ef67
This commit is contained in:
Ulf Gebhardt 2021-03-17 00:39:06 +01:00
commit 6fe5fd6d7e
467 changed files with 81698 additions and 0 deletions

11
community_server/.gitignore vendored Normal file
View File

@ -0,0 +1,11 @@
config/app.php
logs/
src/GPBMetadata/
tmp/
vendor/
composer.lock
websrc/node_modules/
websrc/package-lock.json
mithril_client/
websrc/src/less-files.css

6
community_server/.gitmodules vendored Normal file
View File

@ -0,0 +1,6 @@
[submodule "mithril_client"]
path = mithril_client
url = git@github.com:gradido/gradido_mithrilJS_client.git
[submodule "src/protobuf"]
path = src/protobuf
url = git@github.com:gradido/gradido_protocol.git

View File

@ -0,0 +1,13 @@
FROM phpdockerio/php74-fpm
# install php fpm
RUN apt-get update \
&& apt-get -y --no-install-recommends install curl unzip php7.4-curl php7.4-fpm php7.4-mbstring php7.4-intl php7.4-xml php7.4-pdo php7.4-mysql \
&& apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
WORKDIR /var/www/cakephp
RUN mkdir logs && mkdir tmp && chmod 777 logs && chmod 777 tmp
COPY ./community_server/ .
COPY ./configs/community_server/app.php ./config/
RUN composer update

View File

@ -0,0 +1,51 @@
# CakePHP Application Skeleton
[![Build Status](https://img.shields.io/travis/cakephp/app/master.svg?style=flat-square)](https://travis-ci.org/cakephp/app)
[![Total Downloads](https://img.shields.io/packagist/dt/cakephp/app.svg?style=flat-square)](https://packagist.org/packages/cakephp/app)
A skeleton for creating applications with [CakePHP](https://cakephp.org) 3.x.
The framework source code can be found here: [cakephp/cakephp](https://github.com/cakephp/cakephp).
## Installation
1. Download [Composer](https://getcomposer.org/doc/00-intro.md) or update `composer self-update`.
2. Run `php composer.phar create-project --prefer-dist cakephp/app [app_name]`.
If Composer is installed globally, run
```bash
composer create-project --prefer-dist cakephp/app
```
In case you want to use a custom app dir name (e.g. `/myapp/`):
```bash
composer create-project --prefer-dist cakephp/app myapp
```
You can now either use your machine's webserver to view the default home page, or start
up the built-in webserver with:
```bash
bin/cake server -p 8765
```
Then visit `http://localhost:8765` to see the welcome page.
## Update
Since this skeleton is a starting point for your application and various files
would have been modified as per your needs, there isn't a way to provide
automated upgrades, so you have to do any updates manually.
## Configuration
Read and edit `config/app.php` and setup the `'Datasources'` and any other
configuration relevant for your application.
## Layout
The app skeleton uses a subset of [Foundation](http://foundation.zurb.com/) (v5) CSS
framework by default. You can, however, replace it with any other library or
custom styles.

75
community_server/bin/cake Executable file
View File

@ -0,0 +1,75 @@
#!/usr/bin/env sh
################################################################################
#
# Cake is a shell script for invoking CakePHP shell commands
#
# CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
# Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
#
# Licensed under The MIT License
# For full copyright and license information, please see the LICENSE.txt
# Redistributions of files must retain the above copyright notice.
#
# @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
# @link https://cakephp.org CakePHP(tm) Project
# @since 1.2.0
# @license https://opensource.org/licenses/mit-license.php MIT License
#
################################################################################
# Canonicalize by following every symlink of the given name recursively
canonicalize() {
NAME="$1"
if [ -f "$NAME" ]
then
DIR=$(dirname -- "$NAME")
NAME=$(cd -P "$DIR" > /dev/null && pwd -P)/$(basename -- "$NAME")
fi
while [ -h "$NAME" ]; do
DIR=$(dirname -- "$NAME")
SYM=$(readlink "$NAME")
NAME=$(cd "$DIR" > /dev/null && cd "$(dirname -- "$SYM")" > /dev/null && pwd)/$(basename -- "$SYM")
done
echo "$NAME"
}
# Find a CLI version of PHP
findCliPhp() {
for TESTEXEC in php php-cli /usr/local/bin/php
do
SAPI=$(echo "<?= PHP_SAPI ?>" | $TESTEXEC 2>/dev/null)
if [ "$SAPI" = "cli" ]
then
echo $TESTEXEC
return
fi
done
echo "Failed to find a CLI version of PHP; falling back to system standard php executable" >&2
echo "php";
}
# If current path is a symlink, resolve to real path
realname="$0"
if [ -L "$realname" ]
then
realname=$(readlink -f "$0")
fi
CONSOLE=$(dirname -- "$(canonicalize "$realname")")
APP=$(dirname "$CONSOLE")
# If your CLI PHP is somewhere that this doesn't find, you can define a PHP environment
# variable with the correct path in it.
if [ -z "$PHP" ]
then
PHP=$(findCliPhp)
fi
if [ "$(basename "$realname")" != 'cake' ]
then
exec "$PHP" "$CONSOLE"/cake.php "$(basename "$realname")" "$@"
else
exec "$PHP" "$CONSOLE"/cake.php "$@"
fi
exit

View File

@ -0,0 +1,27 @@
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: Cake is a Windows batch script for invoking CakePHP shell commands
::
:: CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
:: Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
::
:: Licensed under The MIT License
:: Redistributions of files must retain the above copyright notice.
::
:: @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
:: @link https://cakephp.org CakePHP(tm) Project
:: @since 2.0.0
:: @license https://opensource.org/licenses/mit-license.php MIT License
::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
@echo off
SET app=%0
SET lib=%~dp0
php "%lib%cake.php" %*
echo.
exit /B %ERRORLEVEL%

View File

@ -0,0 +1,12 @@
#!/usr/bin/php -q
<?php
// Check platform requirements
require dirname(__DIR__) . '/config/requirements.php';
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Application;
use Cake\Console\CommandRunner;
// Build the runner with an application and root executable name.
$runner = new CommandRunner(new Application(dirname(__DIR__) . '/config'), 'cake');
exit($runner->run($argv));

View File

@ -0,0 +1,57 @@
{
"name": "cakephp/app",
"description": "CakePHP skeleton app",
"homepage": "https://cakephp.org",
"type": "project",
"license": "MIT",
"require": {
"php": ">=5.6",
"cakephp/cakephp": "3.8.*",
"cakephp/migrations": "^2.0.0",
"cakephp/plugin-installer": "^1.0",
"datto/json-rpc": "^6.0",
"google/protobuf": "v3.10.*",
"mobiledetect/mobiledetectlib": "2.*",
"paragonie/sodium_compat": "^1.11",
"tuupola/base58": "^2.0"
},
"require-dev": {
"cakephp/bake": "^1.9.0",
"cakephp/cakephp-codesniffer": "^3.0",
"cakephp/debug_kit": "^3.17.0",
"josegonzalez/dotenv": "3.*",
"phpunit/phpunit": "^5.7|^6.0",
"psy/psysh": "@stable"
},
"suggest": {
"markstory/asset_compress": "An asset compression plugin which provides file concatenation and a flexible filter system for preprocessing and minification.",
"dereuromark/cakephp-ide-helper": "After baking your code, this keeps your annotations in sync with the code evolving from there on for maximum IDE and PHPStan compatibility."
},
"autoload": {
"psr-4": {
"App\\": "src/",
"" : "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Test\\": "tests/",
"Cake\\Test\\": "vendor/cakephp/cakephp/tests/"
}
},
"scripts": {
"post-install-cmd": "App\\Console\\Installer::postInstall",
"post-create-project-cmd": "App\\Console\\Installer::postInstall",
"check": [
"@test",
"@cs-check"
],
"cs-check": "phpcs --colors -p --standard=vendor/cakephp/cakephp-codesniffer/CakePHP src/ tests/",
"cs-fix": "phpcbf --colors --standard=vendor/cakephp/cakephp-codesniffer/CakePHP src/ tests/",
"test": "phpunit --colors=always"
},
"prefer-stable": true,
"config": {
"sort-packages": true
}
}

View File

@ -0,0 +1,407 @@
<?php
use Cake\Cache\Engine\FileEngine;
use Cake\Database\Connection;
use Cake\Database\Driver\Mysql;
use Cake\Error\ExceptionRenderer;
use Cake\Log\Engine\FileLog;
use Cake\Mailer\Transport\MailTransport;
return [
/**
* Debug Level:
*
* Production Mode:
* false: No error messages, errors, or warnings shown.
*
* Development Mode:
* true: Errors and warnings shown.
*/
'debug' => filter_var(env('DEBUG', true), FILTER_VALIDATE_BOOLEAN),
/**
* Configure basic information about the application.
*
* - namespace - The namespace to find app classes under.
* - defaultLocale - The default locale for translation, formatting currencies and numbers, date and time.
* - encoding - The encoding used for HTML + database connections.
* - base - The base directory the app resides in. If false this
* will be auto detected.
* - dir - Name of app directory.
* - webroot - The webroot directory.
* - wwwRoot - The file path to webroot.
* - baseUrl - To configure CakePHP to *not* use mod_rewrite and to
* use CakePHP pretty URLs, remove these .htaccess
* files:
* /.htaccess
* /webroot/.htaccess
* And uncomment the baseUrl key below.
* - fullBaseUrl - A base URL to use for absolute links. When set to false (default)
* CakePHP generates required value based on `HTTP_HOST` environment variable.
* However, you can define it manually to optimize performance or if you
* are concerned about people manipulating the `Host` header.
* - imageBaseUrl - Web path to the public images directory under webroot.
* - cssBaseUrl - Web path to the public css directory under webroot.
* - jsBaseUrl - Web path to the public js directory under webroot.
* - paths - Configure paths for non class based resources. Supports the
* `plugins`, `templates`, `locales` subkeys, which allow the definition of
* paths for plugins, view templates and locale files respectively.
*/
'App' => [
'namespace' => 'App',
'encoding' => env('APP_ENCODING', 'UTF-8'),
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
'defaultTimezone' => env('APP_DEFAULT_TIMEZONE', 'UTC'),
'base' => false,
'dir' => 'src',
'webroot' => 'webroot',
'wwwRoot' => WWW_ROOT,
//'baseUrl' => env('SCRIPT_NAME'),
'fullBaseUrl' => false,
'imageBaseUrl' => 'img/',
'cssBaseUrl' => 'css/',
'jsBaseUrl' => 'js/',
'paths' => [
'plugins' => [ROOT . DS . 'plugins' . DS],
'templates' => [APP . 'Template' . DS],
'locales' => [APP . 'Locale' . DS],
],
],
/**
* Security and encryption configuration
*
* - salt - A random string used in security hashing methods.
* The salt value is also used as the encryption key.
* You should treat it as extremely sensitive data.
*/
'Security' => [
'salt' => env('SECURITY_SALT', '__SALT__'),
],
/**
* Apply timestamps with the last modified time to static assets (js, css, images).
* Will append a querystring parameter containing the time the file was modified.
* This is useful for busting browser caches.
*
* Set to true to apply timestamps when debug is true. Set to 'force' to always
* enable timestamping regardless of debug value.
*/
'Asset' => [
//'timestamp' => true,
// 'cacheTime' => '+1 year'
],
/**
* Configure the cache adapters.
*/
'Cache' => [
'default' => [
'className' => FileEngine::class,
'path' => CACHE,
'url' => env('CACHE_DEFAULT_URL', null),
],
/**
* Configure the cache used for general framework caching.
* Translation cache files are stored with this configuration.
* Duration will be set to '+2 minutes' in bootstrap.php when debug = true
* If you set 'className' => 'Null' core cache will be disabled.
*/
'_cake_core_' => [
'className' => FileEngine::class,
'prefix' => 'myapp_cake_core_',
'path' => CACHE . 'persistent/',
'serialize' => true,
'duration' => '+1 years',
'url' => env('CACHE_CAKECORE_URL', null),
],
/**
* Configure the cache for model and datasource caches. This cache
* configuration is used to store schema descriptions, and table listings
* in connections.
* Duration will be set to '+2 minutes' in bootstrap.php when debug = true
*/
'_cake_model_' => [
'className' => FileEngine::class,
'prefix' => 'myapp_cake_model_',
'path' => CACHE . 'models/',
'serialize' => true,
'duration' => '+1 years',
'url' => env('CACHE_CAKEMODEL_URL', null),
],
/**
* Configure the cache for routes. The cached routes collection is built the
* first time the routes are processed via `config/routes.php`.
* Duration will be set to '+2 seconds' in bootstrap.php when debug = true
*/
'_cake_routes_' => [
'className' => FileEngine::class,
'prefix' => 'myapp_cake_routes_',
'path' => CACHE,
'serialize' => true,
'duration' => '+1 years',
'url' => env('CACHE_CAKEROUTES_URL', null),
],
],
/**
* Configure the Error and Exception handlers used by your application.
*
* By default errors are displayed using Debugger, when debug is true and logged
* by Cake\Log\Log when debug is false.
*
* In CLI environments exceptions will be printed to stderr with a backtrace.
* In web environments an HTML page will be displayed for the exception.
* With debug true, framework errors like Missing Controller will be displayed.
* When debug is false, framework errors will be coerced into generic HTTP errors.
*
* Options:
*
* - `errorLevel` - int - The level of errors you are interested in capturing.
* - `trace` - boolean - Whether or not backtraces should be included in
* logged errors/exceptions.
* - `log` - boolean - Whether or not you want exceptions logged.
* - `exceptionRenderer` - string - The class responsible for rendering
* uncaught exceptions. If you choose a custom class you should place
* the file for that class in src/Error. This class needs to implement a
* render method.
* - `skipLog` - array - List of exceptions to skip for logging. Exceptions that
* extend one of the listed exceptions will also be skipped for logging.
* E.g.:
* `'skipLog' => ['Cake\Http\Exception\NotFoundException', 'Cake\Http\Exception\UnauthorizedException']`
* - `extraFatalErrorMemory` - int - The number of megabytes to increase
* the memory limit by when a fatal error is encountered. This allows
* breathing room to complete logging or error handling.
*/
'Error' => [
'errorLevel' => E_ALL,
'exceptionRenderer' => ExceptionRenderer::class,
'skipLog' => [],
'log' => true,
'trace' => true,
],
/**
* Email configuration.
*
* By defining transports separately from delivery profiles you can easily
* re-use transport configuration across multiple profiles.
*
* You can specify multiple configurations for production, development and
* testing.
*
* Each transport needs a `className`. Valid options are as follows:
*
* Mail - Send using PHP mail function
* Smtp - Send using SMTP
* Debug - Do not send the email, just return the result
*
* You can add custom transports (or override existing transports) by adding the
* appropriate file to src/Mailer/Transport. Transports should be named
* 'YourTransport.php', where 'Your' is the name of the transport.
*/
'EmailTransport' => [
'default' => [
'className' => MailTransport::class,
/*
* The following keys are used in SMTP transports:
*/
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => null,
'password' => null,
'client' => null,
'tls' => null,
'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),
],
],
/**
* Email delivery profiles
*
* Delivery profiles allow you to predefine various properties about email
* messages from your application and give the settings a name. This saves
* duplication across your application and makes maintenance and development
* easier. Each profile accepts a number of keys. See `Cake\Mailer\Email`
* for more information.
*/
'Email' => [
'default' => [
'transport' => 'default',
'from' => 'you@localhost',
//'charset' => 'utf-8',
//'headerCharset' => 'utf-8',
],
],
/**
* Connection information used by the ORM to connect
* to your application's datastores.
*
* ### Notes
* - Drivers include Mysql Postgres Sqlite Sqlserver
* See vendor\cakephp\cakephp\src\Database\Driver for complete list
* - Do not use periods in database name - it may lead to error.
* See https://github.com/cakephp/cakephp/issues/6471 for details.
* - 'encoding' is recommended to be set to full UTF-8 4-Byte support.
* E.g set it to 'utf8mb4' in MariaDB and MySQL and 'utf8' for any
* other RDBMS.
*/
'Datasources' => [
'default' => [
'className' => Connection::class,
'driver' => Mysql::class,
'persistent' => false,
'host' => 'localhost',
/*
* CakePHP will use the default DB port based on the driver selected
* MySQL on MAMP uses port 8889, MAMP users will want to uncomment
* the following line and set the port accordingly
*/
//'port' => 'non_standard_port_number',
'username' => 'my_app',
'password' => 'secret',
'database' => 'my_app',
/*
* You do not need to set this flag to use full utf-8 encoding (internal default since CakePHP 3.6).
*/
//'encoding' => 'utf8mb4',
'timezone' => 'UTC',
'flags' => [],
'cacheMetadata' => true,
'log' => false,
/**
* Set identifier quoting to true if you are using reserved words or
* special characters in your table or column names. Enabling this
* setting will result in queries built using the Query Builder having
* identifiers quoted when creating SQL. It should be noted that this
* decreases performance because each query needs to be traversed and
* manipulated before being executed.
*/
'quoteIdentifiers' => false,
/**
* During development, if using MySQL < 5.6, uncommenting the
* following line could boost the speed at which schema metadata is
* fetched from the database. It can also be set directly with the
* mysql configuration directive 'innodb_stats_on_metadata = 0'
* which is the recommended value in production environments
*/
//'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
'url' => env('DATABASE_URL', null),
],
/**
* The test connection is used during the test suite.
*/
'test' => [
'className' => Connection::class,
'driver' => Mysql::class,
'persistent' => false,
'host' => 'localhost',
//'port' => 'non_standard_port_number',
'username' => 'my_app',
'password' => 'secret',
'database' => 'test_myapp',
//'encoding' => 'utf8mb4',
'timezone' => 'UTC',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
'log' => false,
//'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
'url' => env('DATABASE_TEST_URL', null),
],
],
/**
* Configures logging options
*/
'Log' => [
'debug' => [
'className' => FileLog::class,
'path' => LOGS,
'file' => 'debug',
'url' => env('LOG_DEBUG_URL', null),
'scopes' => false,
'levels' => ['notice', 'info', 'debug'],
],
'error' => [
'className' => FileLog::class,
'path' => LOGS,
'file' => 'error',
'url' => env('LOG_ERROR_URL', null),
'scopes' => false,
'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'],
],
// To enable this dedicated query log, you need set your datasource's log flag to true
'queries' => [
'className' => FileLog::class,
'path' => LOGS,
'file' => 'queries',
'url' => env('LOG_QUERIES_URL', null),
'scopes' => ['queriesLog'],
],
],
/**
* Session configuration.
*
* Contains an array of settings to use for session configuration. The
* `defaults` key is used to define a default preset to use for sessions, any
* settings declared here will override the settings of the default config.
*
* ## Options
*
* - `cookie` - The name of the cookie to use. Defaults to 'CAKEPHP'. Avoid using `.` in cookie names,
* as PHP will drop sessions from cookies with `.` in the name.
* - `cookiePath` - The url path for which session cookie is set. Maps to the
* `session.cookie_path` php.ini config. Defaults to base path of app.
* - `timeout` - The time in minutes the session should be valid for.
* Pass 0 to disable checking timeout.
* Please note that php.ini's session.gc_maxlifetime must be equal to or greater
* than the largest Session['timeout'] in all served websites for it to have the
* desired effect.
* - `defaults` - The default configuration set to use as a basis for your session.
* There are four built-in options: php, cake, cache, database.
* - `handler` - Can be used to enable a custom session handler. Expects an
* array with at least the `engine` key, being the name of the Session engine
* class to use for managing the session. CakePHP bundles the `CacheSession`
* and `DatabaseSession` engines.
* - `ini` - An associative array of additional ini values to set.
*
* The built-in `defaults` options are:
*
* - 'php' - Uses settings defined in your php.ini.
* - 'cake' - Saves session files in CakePHP's /tmp directory.
* - 'database' - Uses CakePHP's database sessions.
* - 'cache' - Use the Cache class to save sessions.
*
* To define a custom session handler, save it at src/Network/Session/<name>.php.
* Make sure the class implements PHP's `SessionHandlerInterface` and set
* Session.handler to <name>
*
* To use database sessions, load the SQL file located at config/schema/sessions.sql
*/
'Session' => [
'defaults' => 'php',
],
// Gradido specific configuration
// Login Server ip and port
'LoginServer' => [
'host' => 'http://127.0.0.1',
'port' => 1201
],
'API' => [
'allowedCaller' => [''] // insert domains or ips from login-server and gdt if they not at localhost
],
'ServerAdminEmail' => 'info@gradido.net', // email 'from' field for transfer notification emails
'noReplyEmail' => 'no-replay@gradido.net', // email sender for creation notification emails to user
'GroupNode' => false
];

View File

@ -0,0 +1,205 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 0.10.8
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
/*
* Configure paths required to find CakePHP + general filepath constants
*/
require __DIR__ . '/paths.php';
/*
* Bootstrap CakePHP.
*
* Does the various bits of setup that CakePHP needs to do.
* This includes:
*
* - Registering the CakePHP autoloader.
* - Setting the default application paths.
*/
require CORE_PATH . 'config' . DS . 'bootstrap.php';
use Cake\Cache\Cache;
use Cake\Console\ConsoleErrorHandler;
use Cake\Core\Configure;
use Cake\Core\Configure\Engine\PhpConfig;
use Cake\Core\Plugin;
use Cake\Database\Type;
use Cake\Datasource\ConnectionManager;
use Cake\Error\ErrorHandler;
use Cake\Http\ServerRequest;
use Cake\Log\Log;
use Cake\Mailer\Email;
use Cake\Mailer\TransportFactory;
use Cake\Utility\Inflector;
use Cake\Utility\Security;
/**
* Uncomment block of code below if you want to use `.env` file during development.
* You should copy `config/.env.default to `config/.env` and set/modify the
* variables as required.
*
* It is HIGHLY discouraged to use a .env file in production, due to security risks
* and decreased performance on each request. The purpose of the .env file is to emulate
* the presence of the environment variables like they would be present in production.
*/
// if (!env('APP_NAME') && file_exists(CONFIG . '.env')) {
// $dotenv = new \josegonzalez\Dotenv\Loader([CONFIG . '.env']);
// $dotenv->parse()
// ->putenv()
// ->toEnv()
// ->toServer();
// }
/*
* Read configuration file and inject configuration into various
* CakePHP classes.
*
* By default there is only one configuration file. It is often a good
* idea to create multiple configuration files, and separate the configuration
* that changes from configuration that does not. This makes deployment simpler.
*/
try {
Configure::config('default', new PhpConfig());
Configure::load('app', 'default', false);
} catch (\Exception $e) {
exit($e->getMessage() . "\n");
}
/*
* Load an environment local configuration file.
* You can use a file like app_local.php to provide local overrides to your
* shared configuration.
*/
//Configure::load('app_local', 'default');
/*
* When debug = true the metadata cache should only last
* for a short time.
*/
if (Configure::read('debug')) {
Configure::write('Cache._cake_model_.duration', '+2 minutes');
Configure::write('Cache._cake_core_.duration', '+2 minutes');
// disable router cache during development
Configure::write('Cache._cake_routes_.duration', '+2 seconds');
}
/*
* Set the default server timezone. Using UTC makes time calculations / conversions easier.
* Check http://php.net/manual/en/timezones.php for list of valid timezone strings.
*/
date_default_timezone_set(Configure::read('App.defaultTimezone'));
/*
* Configure the mbstring extension to use the correct encoding.
*/
mb_internal_encoding(Configure::read('App.encoding'));
/*
* Set the default locale. This controls how dates, number and currency is
* formatted and sets the default language to use for translations.
*/
ini_set('intl.default_locale', Configure::read('App.defaultLocale'));
/*
* Register application error and exception handlers.
*/
$isCli = PHP_SAPI === 'cli';
if ($isCli) {
(new ConsoleErrorHandler(Configure::read('Error')))->register();
} else {
(new ErrorHandler(Configure::read('Error')))->register();
}
/*
* Include the CLI bootstrap overrides.
*/
if ($isCli) {
require __DIR__ . '/bootstrap_cli.php';
}
/*
* Set the full base URL.
* This URL is used as the base of all absolute links.
*
* If you define fullBaseUrl in your config file you can remove this.
*/
if (!Configure::read('App.fullBaseUrl')) {
$s = null;
if (env('HTTPS')) {
$s = 's';
}
$httpHost = env('HTTP_HOST');
if (isset($httpHost)) {
Configure::write('App.fullBaseUrl', 'http' . $s . '://' . $httpHost);
}
unset($httpHost, $s);
}
Cache::setConfig(Configure::consume('Cache'));
ConnectionManager::setConfig(Configure::consume('Datasources'));
TransportFactory::setConfig(Configure::consume('EmailTransport'));
Email::setConfig(Configure::consume('Email'));
Log::setConfig(Configure::consume('Log'));
Security::setSalt(Configure::consume('Security.salt'));
/*
* The default crypto extension in 3.0 is OpenSSL.
* If you are migrating from 2.x uncomment this code to
* use a more compatible Mcrypt based implementation
*/
//Security::engine(new \Cake\Utility\Crypto\Mcrypt());
/*
* Setup detectors for mobile and tablet.
*/
ServerRequest::addDetector('mobile', function ($request) {
$detector = new \Detection\MobileDetect();
return $detector->isMobile();
});
ServerRequest::addDetector('tablet', function ($request) {
$detector = new \Detection\MobileDetect();
return $detector->isTablet();
});
/*
* Enable immutable time objects in the ORM.
*
* You can enable default locale format parsing by adding calls
* to `useLocaleParser()`. This enables the automatic conversion of
* locale specific date formats. For details see
* @link https://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html#parsing-localized-datetime-data
*/
Type::build('time')
->useImmutable();
Type::build('date')
->useImmutable();
Type::build('datetime')
->useImmutable();
Type::build('timestamp')
->useImmutable();
/*
* Custom Inflector rules, can be set to correctly pluralize or singularize
* table, model, controller names or whatever other string is passed to the
* inflection functions.
*/
//Inflector::rules('plural', ['/^(inflect)or$/i' => '\1ables']);
//Inflector::rules('irregular', ['red' => 'redlings']);
//Inflector::rules('uninflected', ['dontinflectme']);
//Inflector::rules('transliteration', ['/å/' => 'aa']);

View File

@ -0,0 +1,28 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
use Cake\Core\Configure;
/**
* Additional bootstrapping and configuration for CLI environments should
* be put here.
*/
// Set the fullBaseUrl to allow URLs to be generated in shell tasks.
// This is useful when sending email from shells.
//Configure::write('App.fullBaseUrl', php_uname('n'));
// Set logs to different files so they don't have permission conflicts.
Configure::write('Log.debug.file', 'cli-debug');
Configure::write('Log.error.file', 'cli-error');

View File

@ -0,0 +1,46 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
return [
// Container element used by control().
'inputContainer' => '{{content}}',
// Container element used by control() when a field has an error.
'inputContainerError' => '<div class="{{type}}{{required}} is-invalid">{{content}}{{error}}</div>',
// Label element when inputs are not nested inside the label.
'label' => '<label{{attrs}} class="form-label">{{text}}</label>',
// Generic input element.
'input' => '<input type="{{type}}" class="form-control" name="{{name}}"{{attrs}}/>',
// Textarea input element,
'textarea' => '<textarea class="form-control" name="{{name}}"{{attrs}}>{{value}}</textarea>',
// Error message wrapper elements.
'error' => '<div class="invalid-feedback">'
. '{{content}}'
. '</div>',
// Container for error items.
'errorList' => '{{content}}',
// Error item wrapper.
'errorItem' => '<div>{{text}}</div>'
];
/*
<div class="form-group row showcase_row_area">
<div class="col-md-3 showcase_text_area">
<label for="inputAmount">Betrag in GDD</label>
</div>
<div class="col-md-9 showcase_content_area">
<input type="number" step="0.01" class="form-control" id="inputAmount" name="inputAmount" >
</div>
</div>
<div class="input number required">
<label for="amount">Amount</label>
<input type="number" name="amount" required="required" step="0.01" id="amount">
</div>
*/

View File

@ -0,0 +1,25 @@
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REQUEST_SCHEME $scheme;
fastcgi_param HTTPS $https if_not_empty;
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;

View File

@ -0,0 +1,88 @@
types {
text/html html htm shtml;
text/css css;
text/xml xml;
image/gif gif;
image/jpeg jpeg jpg;
application/javascript js;
application/atom+xml atom;
application/rss+xml rss;
text/mathml mml;
text/plain txt;
text/vnd.sun.j2me.app-descriptor jad;
text/vnd.wap.wml wml;
text/x-component htc;
image/png png;
image/tiff tif tiff;
image/vnd.wap.wbmp wbmp;
image/x-icon ico;
image/x-jng jng;
image/x-ms-bmp bmp;
image/svg+xml svg svgz;
image/webp webp;
application/font-woff woff;
application/java-archive jar war ear;
application/json json;
application/mac-binhex40 hqx;
application/msword doc;
application/pdf pdf;
application/postscript ps eps ai;
application/rtf rtf;
application/vnd.apple.mpegurl m3u8;
application/vnd.ms-excel xls;
application/vnd.ms-fontobject eot;
application/vnd.ms-powerpoint ppt;
application/vnd.wap.wmlc wmlc;
application/vnd.google-earth.kml+xml kml;
application/vnd.google-earth.kmz kmz;
application/x-7z-compressed 7z;
application/x-cocoa cco;
application/x-java-archive-diff jardiff;
application/x-java-jnlp-file jnlp;
application/x-makeself run;
application/x-perl pl pm;
application/x-pilot prc pdb;
application/x-rar-compressed rar;
application/x-redhat-package-manager rpm;
application/x-sea sea;
application/x-shockwave-flash swf;
application/x-stuffit sit;
application/x-tcl tcl tk;
application/x-x509-ca-cert der pem crt;
application/x-xpinstall xpi;
application/xhtml+xml xhtml;
application/xspf+xml xspf;
application/zip zip;
application/octet-stream bin exe dll;
application/octet-stream deb;
application/octet-stream dmg;
application/octet-stream iso img;
application/octet-stream msi msp msm;
application/vnd.openxmlformats-officedocument.wordprocessingml.document docx;
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx;
application/vnd.openxmlformats-officedocument.presentationml.presentation pptx;
audio/midi mid midi kar;
audio/mpeg mp3;
audio/ogg ogg;
audio/x-m4a m4a;
audio/x-realaudio ra;
video/3gpp 3gpp 3gp;
video/mp2t ts;
video/mp4 mp4;
video/mpeg mpeg mpg;
video/quicktime mov;
video/webm webm;
video/x-flv flv;
video/x-m4v m4v;
video/x-mng mng;
video/x-ms-asf asx asf;
video/x-ms-wmv wmv;
video/x-msvideo avi;
}

View File

@ -0,0 +1,86 @@
server {
listen 80 ;
listen [::]:80;
server_name 0.0.0.0;
#include /etc/nginx/common/protect.conf;
#include /etc/nginx/common/protect_add_header.conf;
#include /etc/nginx/common/ssl.conf;
root /usr/share/nginx/html/webroot;
index index.php;
location ~* \.(png|jpg|ico|webp)\$ {
expires 30d;
}
location ~* \.(js|css) {
# expires 1d;
expires 1d;
}
location ~ \.php\$ {
# regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;
# Bypass the fact that try_files resets $fastcgi_path_info
# see: http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;
fastcgi_index index.php;
include fastcgi.conf;
#fastcgi_pass unix:/run/php/php7.3-fpm.sock;
fastcgi_pass 127.0.0.1:9000;
}
location ~ /\.ht {
deny all;
}
location /account {
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_cache_bypass \$http_upgrade;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$remote_addr;
proxy_set_header Host \$host;
rewrite /account/(.*) /\$1 break;
#proxy_next_upstream error timeout invalid_header http_502 non_idempotent;
proxy_pass http://login-server:1200;
proxy_redirect off;
}
location /login_api {
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_cache_bypass \$http_upgrade;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$remote_addr;
proxy_set_header Host \$host;
rewrite /login_api/(.*) /\$1 break;
proxy_pass http://login-server:1201;
proxy_redirect off;
}
location / {
try_files \$uri \$uri/ /index.php?\$args;
}
# access_log /var/log/nginx/access.log main;
}

View File

@ -0,0 +1,89 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license MIT License (https://opensource.org/licenses/mit-license.php)
*/
/**
* Use the DS to separate the directories in other defines
*/
if (!defined('DS')) {
define('DS', DIRECTORY_SEPARATOR);
}
/**
* These defines should only be edited if you have cake installed in
* a directory layout other than the way it is distributed.
* When using custom settings be sure to use the DS and do not add a trailing DS.
*/
/**
* The full path to the directory which holds "src", WITHOUT a trailing DS.
*/
define('ROOT', dirname(__DIR__));
/**
* The actual directory name for the application directory. Normally
* named 'src'.
*/
define('APP_DIR', 'src');
/**
* Path to the application's directory.
*/
define('APP', ROOT . DS . APP_DIR . DS);
/**
* Path to the config directory.
*/
define('CONFIG', ROOT . DS . 'config' . DS);
/**
* File path to the webroot directory.
*
* To derive your webroot from your webserver change this to:
*
* `define('WWW_ROOT', rtrim($_SERVER['DOCUMENT_ROOT'], DS) . DS);`
*/
define('WWW_ROOT', ROOT . DS . 'webroot' . DS);
/**
* Path to the tests directory.
*/
define('TESTS', ROOT . DS . 'tests' . DS);
/**
* Path to the temporary files directory.
*/
define('TMP', ROOT . DS . 'tmp' . DS);
/**
* Path to the logs directory.
*/
define('LOGS', ROOT . DS . 'logs' . DS);
/**
* Path to the cache files directory. It can be shared between hosts in a multi-server setup.
*/
define('CACHE', TMP . 'cache' . DS);
/**
* The absolute path to the "cake" directory, WITHOUT a trailing DS.
*
* CakePHP should always be installed with composer, so look there.
*/
define('CAKE_CORE_INCLUDE_PATH', ROOT . DS . 'vendor' . DS . 'cakephp' . DS . 'cakephp');
/**
* Path to the cake directory.
*/
define('CORE_PATH', CAKE_CORE_INCLUDE_PATH . DS);
define('CAKE', CORE_PATH . 'src' . DS);

View File

@ -0,0 +1,2 @@
#upload_max_filesize = 100M
#post_max_size = 108M

View File

@ -0,0 +1,39 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.5.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
/*
* You can empty out this file, if you are certain that you match all requirements.
*/
/*
* You can remove this if you are confident that your PHP version is sufficient.
*/
if (version_compare(PHP_VERSION, '5.6.0') < 0) {
trigger_error('Your PHP version must be equal or higher than 5.6.0 to use CakePHP.' . PHP_EOL, E_USER_ERROR);
}
/*
* You can remove this if you are confident you have intl installed.
*/
if (!extension_loaded('intl')) {
trigger_error('You must enable the intl extension to use CakePHP.' . PHP_EOL, E_USER_ERROR);
}
/*
* You can remove this if you are confident you have mbstring installed.
*/
if (!extension_loaded('mbstring')) {
trigger_error('You must enable the mbstring extension to use CakePHP.' . PHP_EOL, E_USER_ERROR);
}

View File

@ -0,0 +1,25 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
return [
'inputContainer' => '{{content}}',
'input' => '<div class="input-group showcase_row_area">'
. '<input type="{{type}}" class="form-control" name="{{name}}"{{attrs}}/>'
. '</div>',
'error' => '<div class="input-group showcase_content_area invalid-feedback">'
. '{{content}}'
. '</div>',
// Container for error items.
//'errorList' => '<ul>{{content}}</ul>',
'errorList' => '{{content}}',
// Error item wrapper.
//'errorItem' => '<li>{{text}}</li>',
'errorItem' => '<div>{{text}}</div>'
];

View File

@ -0,0 +1,138 @@
<?php
/**
* Routes configuration
*
* In this file, you set up routes to your controllers and their actions.
* Routes are very important mechanism that allows you to freely connect
* different URLs to chosen controllers and their actions (functions).
*
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
use Cake\Routing\Route\DashedRoute;
use Cake\Core\Configure;
/**
* The default class to use for all routes
*
* The following route classes are supplied with CakePHP and are appropriate
* to set as the default:
*
* - Route
* - InflectedRoute
* - DashedRoute
*
* If no call is made to `Router::defaultRouteClass()`, the class used is
* `Route` (`Cake\Routing\Route\Route`)
*
* Note that `Route` does not do any inflections on URLs which will result in
* inconsistently cased URLs when used with `:plugin`, `:controller` and
* `:action` markers.
*
* Cache: Routes are cached to improve performance, check the RoutingMiddleware
* constructor in your `src/Application.php` file to change this behavior.
*
*/
Router::defaultRouteClass(DashedRoute::class);
Router::scope('/', function (RouteBuilder $routes) {
$csrf = new CsrfProtectionMiddleware([
'httpOnly' => true
]);
// Token check will be skipped when callback returns `true`.
$csrf->whitelistCallback(function ($request) {
// Skip token check for API URLs.
//die($request->getParam('controller'));
$whitelist = ['JsonRequestHandler', 'ElopageWebhook'];
foreach($whitelist as $entry) {
if($request->getParam('controller') === $entry) {
if($entry == 'ElopageWebhook') {
return true;
}
if($request->clientIp() == '127.0.0.1' || $request->clientIp() == 'localhost') {
return true;
}
$allowedCaller = Configure::read('API.allowedCaller');
if($allowedCaller && count($allowedCaller) > 0) {
$callerIp = $request->clientIp();
foreach($allowedCaller as $allowed) {
$ip = gethostbyname($allowed);
if($ip === $callerIp) return true;
}
}
}
}
});
// Register scoped middleware for in scopes.
$routes->registerMiddleware('csrf', $csrf);
/**
* Apply a middleware to the current route scope.
* Requires middleware to be registered via `Application::routes()` with `registerMiddleware()`
*/
$routes->applyMiddleware('csrf');
/**
* Here, we are connecting '/' (base path) to a controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, src/Template/Pages/home.ctp)...
*/
//$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
$routes->connect('/', ['controller' => 'Dashboard', 'action' => 'index']);
$routes->connect('/server', ['controller' => 'Dashboard', 'action' => 'serverIndex']);
//$routes->connect('/', 'https://gradido2.dario-rekowski.de/account', array('status' => 303));
/**
* ...and connect the rest of 'Pages' controller's URLs.
*/
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
/**
* Connect catchall routes for all controllers.
*
* Using the argument `DashedRoute`, the `fallbacks` method is a shortcut for
*
* ```
* $routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'DashedRoute']);
* $routes->connect('/:controller/:action/*', [], ['routeClass' => 'DashedRoute']);
* ```
*
* Any route class can be used with this method, such as:
* - DashedRoute
* - InflectedRoute
* - Route
* - Or your own route class
*
* You can remove these routes once you've connected the
* routes you want in your application.
*/
$routes->fallbacks(DashedRoute::class);
});
/**
* If you need a different set of middleware or none at all,
* open new scope and define routes there.
*
* ```
* Router::scope('/api', function (RouteBuilder $routes) {
* // No $routes->applyMiddleware() here.
* // Connect API actions here.
* });
* ```
*/

View File

@ -0,0 +1,18 @@
# Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
#
# Licensed under The MIT License
# For full copyright and license information, please see the LICENSE.txt
# Redistributions of files must retain the above copyright notice.
# MIT License (https://opensource.org/licenses/mit-license.php)
CREATE TABLE i18n (
id int NOT NULL auto_increment,
locale varchar(6) NOT NULL,
model varchar(255) NOT NULL,
foreign_key int(10) NOT NULL,
field varchar(255) NOT NULL,
content text,
PRIMARY KEY (id),
UNIQUE INDEX I18N_LOCALE_FIELD(locale, model, foreign_key, field),
INDEX I18N_FIELD(model, foreign_key, field)
);

View File

@ -0,0 +1,15 @@
# Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
#
# Licensed under The MIT License
# For full copyright and license information, please see the LICENSE.txt
# Redistributions of files must retain the above copyright notice.
# MIT License (https://opensource.org/licenses/mit-license.php)
CREATE TABLE `sessions` (
`id` char(40) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
`created` datetime DEFAULT CURRENT_TIMESTAMP, -- optional, requires MySQL 5.6.5+
`modified` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- optional, requires MySQL 5.6.5+
`data` blob DEFAULT NULL, -- for PostgreSQL use bytea instead of blob
`expires` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

View File

@ -0,0 +1,6 @@
CREATE TABLE `address_types` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(25) NOT NULL,
`text` VARCHAR(255) NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,7 @@
CREATE TABLE `operators` (
`id` INT NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(128) NOT NULL ,
`data_base64` VARCHAR(255) NOT NULL ,
PRIMARY KEY (`id`), UNIQUE (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,7 @@
CREATE TABLE `state_balances` (
`id` int(11) NOT NULL,
`state_user_id` int(11) NOT NULL,
`modified` datetime NOT NULL,
`amount` bigint(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,10 @@
CREATE TABLE `state_created` (
`id` int(11) NOT NULL,
`transaction_id` int(11) NOT NULL,
`month` tinyint(4) NOT NULL,
`year` smallint(6) NOT NULL,
`state_user_id` int(11) NOT NULL,
`created` datetime NOT NULL,
`short_ident_hash` int(11) NOT NULL,
PRIMARY KEY (`id`), INDEX(`short_ident_hash`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,7 @@
CREATE TABLE `state_group_addresses` (
`id` int(11) NOT NULL,
`state_group_id` int(11) NOT NULL,
`public_key` binary(32) NOT NULL,
`address_type_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,7 @@
CREATE TABLE `state_group_relationships` (
`id` int(11) NOT NULL,
`state_group1_id` int(11) NOT NULL,
`state_group2_id` int(11) NOT NULL,
`state_relationship_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,8 @@
CREATE TABLE `state_groups` (
`id` INT NOT NULL AUTO_INCREMENT,
`index_id` VARBINARY(64) NOT NULL,
`name` VARCHAR(50) NOT NULL,
`root_public_key` BINARY(32) NOT NULL,
`user_count` SMALLINT NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,6 @@
CREATE TABLE `state_relationship_types` (
`id` int(11) NOT NULL,
`name` varchar(25) COLLATE utf8_bin NOT NULL,
`text` varchar(255) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,7 @@
CREATE TABLE `state_users` (
`id` int(11) NOT NULL,
`index_id` smallint(6) NOT NULL,
`state_group_id` int(11) NOT NULL,
`public_key` binary(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,10 @@
CREATE TABLE `transaction_creations` (
`id` int(11) NOT NULL,
`transaction_id` int(11) NOT NULL,
`state_user_id` int(11) NOT NULL,
`amount` bigint(20) NOT NULL,
`ident_hash` binary(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,8 @@
CREATE TABLE `transaction_group_addaddress` (
`id` int(11) NOT NULL,
`transaction_id` int(11) NOT NULL,
`address_type_id` int(11) NOT NULL,
`public_key` binary(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,8 @@
CREATE TABLE `transaction_group_allowtrades` (
`id` int(11) NOT NULL,
`transaction_id` int(11) NOT NULL,
`group_id` int(11) NOT NULL,
`allow` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,9 @@
CREATE TABLE `transaction_group_creates` (
`id` int(11) NOT NULL,
`transaction_id` int(11) NOT NULL,
`group_public_key` binary(32) NOT NULL,
`state_group_id` int(11) COLLATE utf8_bin NOT NULL,
`name` varchar(64) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,11 @@
CREATE TABLE `transaction_send_coins` (
`id` int(11) NOT NULL,
`transaction_id` int(11) NOT NULL,
`state_user_id` int(11) NOT NULL,
`receiver_public_key` binary(32) NOT NULL,
`receiver_user_id` varbinary(64) NOT NULL,
`amount` bigint(20) NOT NULL,
`sender_final_balance` bigint(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,7 @@
CREATE TABLE `transaction_signatures` (
`id` int(11) NOT NULL,
`transaction_id` int(11) NOT NULL,
`signature` binary(64) NOT NULL,
`pubkey` binary(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,6 @@
CREATE TABLE `transaction_types` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(24) NOT NULL,
`text` VARCHAR(255) NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,9 @@
CREATE TABLE `transactions` (
`id` bigint(20) NOT NULL,
`state_group_id` int(11) NOT NULL,
`transaction_type_id` int(11) NOT NULL,
`tx_hash` binary(32) NOT NULL,
`received` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

View File

@ -0,0 +1,16 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 0.10.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
require 'webroot' . DIRECTORY_SEPARATOR . 'index.php';

@ -0,0 +1 @@
Subproject commit f0b1d113cee2a76e9dbb098b315f4acaf38410d0

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,20 @@
#!/bin/bash
# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# need grpc only for hedera hashgraph
#PHP_PLUGIN="$(which grpc_php_plugin)"
#protoc --proto_path=./src/protobuf/gradido --php_out=./src/ --grpc_out=./src/ --plugin=protoc-gen-grpc=$PHP_PLUGIN ./src/protobuf/gradido/*.proto
protoc --proto_path=./src/protobuf/gradido --php_out=./src/ ./src/protobuf/gradido/*.proto

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
colors="true"
processIsolation="false"
stopOnFailure="false"
bootstrap="tests/bootstrap.php"
>
<php>
<ini name="memory_limit" value="-1"/>
<ini name="apc.enable_cli" value="1"/>
</php>
<!-- Add any additional test suites you want to run here -->
<testsuites>
<testsuite name="app">
<directory>tests/TestCase/</directory>
</testsuite>
<!-- Add plugin test suites here. -->
</testsuites>
<!-- Setup a listener for fixtures -->
<listeners>
<listener
class="\Cake\TestSuite\Fixture\FixtureInjector">
<arguments>
<object class="\Cake\TestSuite\Fixture\FixtureManager" />
</arguments>
</listener>
</listeners>
<!-- Ignore vendor tests in code coverage reports -->
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
<directory suffix=".php">plugins/*/src/</directory>
<exclude>
<file>src/Console/Installer.php</file>
</exclude>
</whitelist>
</filter>
</phpunit>

View File

View File

@ -0,0 +1,11 @@
CREATE TABLE `admin_errors` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`state_user_id` int(11) NOT NULL,
`controller` varchar(255) NOT NULL,
`action` varchar(255) NOT NULL,
`state` varchar(255) NOT NULL,
`msg` varchar(255) NOT NULL,
`details` varchar(255) DEFAULT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

View File

@ -0,0 +1,8 @@
CREATE TABLE `community_profiles` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`state_user_id` int(10) unsigned NOT NULL,
`profile_img` longblob,
`profile_desc` varchar(2000) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `state_user_id` (`state_user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,5 @@
INSERT INTO `transaction_types` (`id`, `name`, `text`) VALUES
(1, 'creation', 'Aktives oder Bedingungsloses Grundeinkommen.'),
(2, 'transfer', 'Einfache Überweisung');

View File

@ -0,0 +1,6 @@
CREATE TABLE `operator_types` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(25) COLLATE utf8mb4_unicode_ci NOT NULL,
`text` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,8 @@
CREATE TABLE `operators` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`user_pubkey` binary(32) NOT NULL,
`data_base64` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,10 @@
CREATE TABLE `pending_transactions` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`transactionID` varchar(25) COLLATE utf8mb4_unicode_ci NOT NULL,
`service` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`method` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
`h_server_id` int(11) NOT NULL,
`timeout` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `transactionID` (`transactionID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,5 @@
CREATE TABLE `roles` (
`id` int UNSIGNED NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,12 @@
CREATE TABLE `server_users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`role` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'admin',
`activated` tinyint(4) NOT NULL DEFAULT '0',
`last_login` datetime DEFAULT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,7 @@
CREATE TABLE `state_balances` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`state_user_id` int(10) unsigned NOT NULL,
`modified` datetime NOT NULL,
`amount` bigint(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,11 @@
CREATE TABLE `state_created` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`transaction_id` int(10) unsigned NOT NULL,
`month` tinyint(3) unsigned NOT NULL,
`year` smallint(5) unsigned NOT NULL,
`state_user_id` int(10) unsigned NOT NULL,
`created` datetime NOT NULL,
`short_ident_hash` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `short_ident_hash` (`short_ident_hash`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,8 @@
CREATE TABLE `state_errors` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`state_user_id` int(10) unsigned NOT NULL,
`transaction_type_id` int(10) unsigned NOT NULL,
`created` datetime NOT NULL,
`message_json` text COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,7 @@
CREATE TABLE `state_group_addresses` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`group_id` int(10) unsigned NOT NULL,
`public_key` binary(32) NOT NULL,
`address_type_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,7 @@
CREATE TABLE `state_group_relationships` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`group1_id` int(10) unsigned NOT NULL,
`group2_id` int(10) unsigned NOT NULL,
`state_relationship_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,8 @@
CREATE TABLE `state_groups` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`index_id` varbinary(64) NOT NULL,
`name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`root_public_key` binary(32) NOT NULL,
`user_count` smallint(5) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,6 @@
CREATE TABLE `state_relationship_types` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(25) COLLATE utf8mb4_unicode_ci NOT NULL,
`text` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,6 @@
CREATE TABLE `state_user_roles` (
`id` int UNSIGNED NOT NULL AUTO_INCREMENT,
`state_user_id` int(11) NOT NULL,
`role_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,13 @@
CREATE TABLE `state_users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`index_id` smallint(6) NOT NULL DEFAULT '0',
`group_id` int(10) unsigned NOT NULL DEFAULT '0',
`public_key` binary(32) NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`first_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`last_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`username` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`disabled` tinyint(4) DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `public_key` (`public_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,9 @@
CREATE TABLE `transaction_creations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`transaction_id` int(10) unsigned NOT NULL,
`state_user_id` int(10) unsigned NOT NULL,
`amount` bigint(20) NOT NULL,
`ident_hash` binary(32) NOT NULL,
`target_date` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,7 @@
CREATE TABLE `transaction_group_addaddress` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`transaction_id` int(10) unsigned NOT NULL,
`address_type_id` int(10) unsigned NOT NULL,
`public_key` binary(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,7 @@
CREATE TABLE `transaction_group_allowtrades` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`transaction_id` int(10) unsigned NOT NULL,
`remote_group_id` varbinary(64) NOT NULL,
`allow` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,8 @@
CREATE TABLE `transaction_group_creates` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`transaction_id` int(10) unsigned NOT NULL,
`group_public_key` binary(32) NOT NULL,
`group_id` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,10 @@
CREATE TABLE `transaction_send_coins` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`transaction_id` int(10) unsigned NOT NULL,
`state_user_id` int(10) unsigned NOT NULL,
`receiver_public_key` binary(32) NOT NULL,
`receiver_user_id` int(10) unsigned NOT NULL,
`amount` bigint(20) NOT NULL,
`sender_final_balance` bigint(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,7 @@
CREATE TABLE `transaction_signatures` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`transaction_id` int(10) unsigned NOT NULL,
`signature` binary(64) NOT NULL,
`pubkey` binary(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,6 @@
CREATE TABLE `transaction_types` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(24) COLLATE utf8mb4_unicode_ci NOT NULL,
`text` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,9 @@
CREATE TABLE `transactions` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`state_group_id` int(10) unsigned DEFAULT NULL,
`transaction_type_id` int(10) unsigned NOT NULL,
`tx_hash` binary(32) DEFAULT NULL,
`memo` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`received` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

View File

@ -0,0 +1,119 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.3.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App;
use Cake\Core\Configure;
use Cake\Core\Exception\MissingPluginException;
use Cake\Error\Middleware\ErrorHandlerMiddleware;
use Cake\Http\BaseApplication;
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Middleware\AssetMiddleware;
use Cake\Routing\Middleware\RoutingMiddleware;
/**
* Application setup class.
*
* This defines the bootstrapping logic and middleware layers you
* want to use in your application.
*/
class Application extends BaseApplication
{
/**
* {@inheritDoc}
*/
public function bootstrap()
{
// Call parent to load bootstrap from files.
parent::bootstrap();
if (PHP_SAPI === 'cli') {
$this->bootstrapCli();
}
/*
* Only try to load DebugKit in development mode
* Debug Kit should not be installed on a production system
*/
if (Configure::read('debug')) {
$this->addPlugin(\DebugKit\Plugin::class);
}
// Load more plugins here
}
/**
* Setup the middleware queue your application will use.
*
* @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup.
* @return \Cake\Http\MiddlewareQueue The updated middleware queue.
*/
public function middleware($middlewareQueue)
{
//$csrf = new CsrfProtectionMiddleware();
// Token check will be skipped when callback returns `true`.
/*$csrf->whitelistCallback(function ($request) {
// Skip token check for API URLs.
//if ($request->getParam('prefix') === 'api') {
if($request->getAttribute('base') === 'TransactionJsonRequestHandler') {
return true;
}
});
*/
// Ensure routing middleware is added to the queue before CSRF protection middleware.
//$middlewareQueue->;
$middlewareQueue
// ->add($csrf)
// Catch any exceptions in the lower layers,
// and make an error page/response
->add(new ErrorHandlerMiddleware(null, Configure::read('Error')))
// Handle plugin/theme assets like CakePHP normally does.
->add(new AssetMiddleware([
'cacheTime' => Configure::read('Asset.cacheTime')
]))
// Add routing middleware.
// If you have a large number of routes connected, turning on routes
// caching in production could improve performance. For that when
// creating the middleware instance specify the cache config name by
// using it's second constructor argument:
// `new RoutingMiddleware($this, '_cake_routes_')`
->add(new RoutingMiddleware($this));
return $middlewareQueue;
}
/**
* @return void
*/
protected function bootstrapCli()
{
try {
$this->addPlugin('Bake');
} catch (MissingPluginException $e) {
// Do not halt if the plugin is missing
}
$this->addPlugin('Migrations');
// Load more plugins here
}
}

View File

@ -0,0 +1,246 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App\Console;
if (!defined('STDIN')) {
define('STDIN', fopen('php://stdin', 'r'));
}
use Cake\Utility\Security;
use Composer\Script\Event;
use Exception;
/**
* Provides installation hooks for when this application is installed via
* composer. Customize this class to suit your needs.
*/
class Installer
{
/**
* An array of directories to be made writable
*/
const WRITABLE_DIRS = [
'logs',
'tmp',
'tmp/cache',
'tmp/cache/models',
'tmp/cache/persistent',
'tmp/cache/views',
'tmp/sessions',
'tmp/tests'
];
/**
* Does some routine installation tasks so people don't have to.
*
* @param \Composer\Script\Event $event The composer event object.
* @throws \Exception Exception raised by validator.
* @return void
*/
public static function postInstall(Event $event)
{
$io = $event->getIO();
$rootDir = dirname(dirname(__DIR__));
static::createAppConfig($rootDir, $io);
static::createWritableDirectories($rootDir, $io);
// ask if the permissions should be changed
if ($io->isInteractive()) {
$validator = function ($arg) {
if (in_array($arg, ['Y', 'y', 'N', 'n'])) {
return $arg;
}
throw new Exception('This is not a valid answer. Please choose Y or n.');
};
$setFolderPermissions = $io->askAndValidate(
'<info>Set Folder Permissions ? (Default to Y)</info> [<comment>Y,n</comment>]? ',
$validator,
10,
'Y'
);
if (in_array($setFolderPermissions, ['Y', 'y'])) {
static::setFolderPermissions($rootDir, $io);
}
} else {
static::setFolderPermissions($rootDir, $io);
}
static::setSecuritySalt($rootDir, $io);
$class = 'Cake\Codeception\Console\Installer';
if (class_exists($class)) {
$class::customizeCodeceptionBinary($event);
}
}
/**
* Create the config/app.php file if it does not exist.
*
* @param string $dir The application's root directory.
* @param \Composer\IO\IOInterface $io IO interface to write to console.
* @return void
*/
public static function createAppConfig($dir, $io)
{
$appConfig = $dir . '/config/app.php';
$defaultConfig = $dir . '/config/app.default.php';
if (!file_exists($appConfig)) {
copy($defaultConfig, $appConfig);
$io->write('Created `config/app.php` file');
}
}
/**
* Create the `logs` and `tmp` directories.
*
* @param string $dir The application's root directory.
* @param \Composer\IO\IOInterface $io IO interface to write to console.
* @return void
*/
public static function createWritableDirectories($dir, $io)
{
foreach (static::WRITABLE_DIRS as $path) {
$path = $dir . '/' . $path;
if (!file_exists($path)) {
mkdir($path);
$io->write('Created `' . $path . '` directory');
}
}
}
/**
* Set globally writable permissions on the "tmp" and "logs" directory.
*
* This is not the most secure default, but it gets people up and running quickly.
*
* @param string $dir The application's root directory.
* @param \Composer\IO\IOInterface $io IO interface to write to console.
* @return void
*/
public static function setFolderPermissions($dir, $io)
{
// Change the permissions on a path and output the results.
$changePerms = function ($path) use ($io) {
$currentPerms = fileperms($path) & 0777;
$worldWritable = $currentPerms | 0007;
if ($worldWritable == $currentPerms) {
return;
}
$res = chmod($path, $worldWritable);
if ($res) {
$io->write('Permissions set on ' . $path);
} else {
$io->write('Failed to set permissions on ' . $path);
}
};
$walker = function ($dir) use (&$walker, $changePerms) {
$files = array_diff(scandir($dir), ['.', '..']);
foreach ($files as $file) {
$path = $dir . '/' . $file;
if (!is_dir($path)) {
continue;
}
$changePerms($path);
$walker($path);
}
};
$walker($dir . '/tmp');
$changePerms($dir . '/tmp');
$changePerms($dir . '/logs');
}
/**
* Set the security.salt value in the application's config file.
*
* @param string $dir The application's root directory.
* @param \Composer\IO\IOInterface $io IO interface to write to console.
* @return void
*/
public static function setSecuritySalt($dir, $io)
{
$newKey = hash('sha256', Security::randomBytes(64));
static::setSecuritySaltInFile($dir, $io, $newKey, 'app.php');
}
/**
* Set the security.salt value in a given file
*
* @param string $dir The application's root directory.
* @param \Composer\IO\IOInterface $io IO interface to write to console.
* @param string $newKey key to set in the file
* @param string $file A path to a file relative to the application's root
* @return void
*/
public static function setSecuritySaltInFile($dir, $io, $newKey, $file)
{
$config = $dir . '/config/' . $file;
$content = file_get_contents($config);
$content = str_replace('__SALT__', $newKey, $content, $count);
if ($count == 0) {
$io->write('No Security.salt placeholder to replace.');
return;
}
$result = file_put_contents($config, $content);
if ($result) {
$io->write('Updated Security.salt value in config/' . $file);
return;
}
$io->write('Unable to update Security.salt value.');
}
/**
* Set the APP_NAME value in a given file
*
* @param string $dir The application's root directory.
* @param \Composer\IO\IOInterface $io IO interface to write to console.
* @param string $appName app name to set in the file
* @param string $file A path to a file relative to the application's root
* @return void
*/
public static function setAppNameInFile($dir, $io, $appName, $file)
{
$config = $dir . '/config/' . $file;
$content = file_get_contents($config);
$content = str_replace('__APP_NAME__', $appName, $content, $count);
if ($count == 0) {
$io->write('No __APP_NAME__ placeholder to replace.');
return;
}
$result = file_put_contents($config, $content);
if ($result) {
$io->write('Updated __APP_NAME__ value in config/' . $file);
return;
}
$io->write('Unable to update __APP_NAME__ value.');
}
}

View File

@ -0,0 +1,107 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\I18n\Number;
/**
* AddressTypes Controller
*
* @property \App\Model\Table\AddressTypesTable $AddressTypes
*
* @method \App\Model\Entity\AddressType[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class AddressTypesController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$addressTypes = $this->paginate($this->AddressTypes);
$this->set(compact('addressTypes'));
}
/**
* View method
*
* @param string|null $id Address Type id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$addressType = $this->AddressTypes->get($id, [
'contain' => ['StateGroupAddresses', 'TransactionGroupAddaddress']
]);
$this->set('addressType', $addressType);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$addressType = $this->AddressTypes->newEntity();
if ($this->request->is('post')) {
$addressType = $this->AddressTypes->patchEntity($addressType, $this->request->getData());
if ($this->AddressTypes->save($addressType)) {
$this->Flash->success(__('The address type has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The address type could not be saved. Please, try again.'));
}
$this->set(compact('addressType'));
}
/**
* Edit method
*
* @param string|null $id Address Type id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$addressType = $this->AddressTypes->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$addressType = $this->AddressTypes->patchEntity($addressType, $this->request->getData());
if ($this->AddressTypes->save($addressType)) {
$this->Flash->success(__('The address type has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The address type could not be saved. Please, try again.'));
}
$this->set(compact('addressType'));
}
/**
* Delete method
*
* @param string|null $id Address Type id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$addressType = $this->AddressTypes->get($id);
if ($this->AddressTypes->delete($addressType)) {
$this->Flash->success(__('The address type has been deleted.'));
} else {
$this->Flash->error(__('The address type could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,111 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* AdminErrors Controller
*
* @property \App\Model\Table\AdminErrorsTable $AdminErrors
*
* @method \App\Model\Entity\AdminError[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class AdminErrorsController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => ['StateUsers']
];
$adminErrors = $this->paginate($this->AdminErrors);
$this->set(compact('adminErrors'));
}
/**
* View method
*
* @param string|null $id Admin Error id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$adminError = $this->AdminErrors->get($id, [
'contain' => ['StateUsers']
]);
$this->set('adminError', $adminError);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$adminError = $this->AdminErrors->newEntity();
if ($this->request->is('post')) {
$adminError = $this->AdminErrors->patchEntity($adminError, $this->request->getData());
if ($this->AdminErrors->save($adminError)) {
$this->Flash->success(__('The admin error has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The admin error could not be saved. Please, try again.'));
}
$stateUsers = $this->AdminErrors->StateUsers->find('list', ['limit' => 200]);
$this->set(compact('adminError', 'stateUsers'));
}
/**
* Edit method
*
* @param string|null $id Admin Error id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$adminError = $this->AdminErrors->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$adminError = $this->AdminErrors->patchEntity($adminError, $this->request->getData());
if ($this->AdminErrors->save($adminError)) {
$this->Flash->success(__('The admin error has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The admin error could not be saved. Please, try again.'));
}
$stateUsers = $this->AdminErrors->StateUsers->find('list', ['limit' => 200]);
$this->set(compact('adminError', 'stateUsers'));
}
/**
* Delete method
*
* @param string|null $id Admin Error id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$adminError = $this->AdminErrors->get($id);
if ($this->AdminErrors->delete($adminError)) {
$this->Flash->success(__('The admin error has been deleted.'));
} else {
$this->Flash->error(__('The admin error could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,341 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 0.2.9
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App\Controller;
use Cake\Controller\Controller;
//use Cake\Event\Event;
use Cake\Http\Client;
use Cake\Routing\Router;
use Cake\ORM\TableRegistry;
use Cake\Core\Configure;
use Cake\I18n\Time;
use Cake\I18n\I18n;
/**
* Application Controller
*
* Add your application-wide methods in the class below, your controllers
* will inherit them.
*
* @link https://book.cakephp.org/3.0/en/controllers.html#the-app-controller
*/
class AppController extends Controller
{
var $loginServerUrl = '';
/**
* Initialization hook method.
*
* Use this method to add common initialization code like loading components.
*
* e.g. `$this->loadComponent('Security');`
*
* @return void
*/
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler', [
'enableBeforeRedirect' => false,
]);
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'ServerUsers',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Transactions',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'gradido'
],
'authenticate' => [
'all' => ['userModel' => 'ServerUsers'],
'Form' => [
'userModel' => 'ServerUsers',
]
]
]);
$this->Auth->deny(['index']);
/*
* Enable the following component for recommended CakePHP security settings.
* see https://book.cakephp.org/3.0/en/controllers/components/security.html
*/
//$this->loadComponent('Security');
// load current balance
$session = $this->getRequest()->getSession();
$state_user_id = $session->read('StateUser.id');
if ($state_user_id) {
$stateBalancesTable = TableRegistry::getTableLocator()->get('stateBalances');
$stateBalanceQuery = $stateBalancesTable
->find('all')
->select('amount')
->contain(false)
->where(['state_user_id' => $state_user_id]);
if ($stateBalanceQuery->count() == 1) {
//var_dump($stateBalanceEntry->first());
$session->write('StateUser.balance', $stateBalanceQuery->first()->amount);
//echo "stateUser.balance: " . $session->read('StateUser.balance');
}
}
// load error count
if ($state_user_id) {
$stateErrorsTable = TableRegistry::getTableLocator()->get('stateErrors');
$stateErrorQuery = $stateErrorsTable
->find('all')
->select('id')
->contain(false)
->where(['state_user_id' => $state_user_id]);
$session->write('StateUser.errorCount', $stateErrorQuery->count());
}
//echo "initialize";
// put current page into global for navi
$GLOBALS["passed"] = null;
$side = $this->request->getParam('controller');
$GLOBALS["side"] = $side;
$subside = $this->request->getParam('action');
$passedArguments = $this->request->getParam('pass');
if ($passedArguments) {
$GLOBALS["passed"] = $passedArguments[0];
}
$GLOBALS["subside"] = $subside;
// server login
if ($this->Auth->user('id')) {
$GLOBALS['ServerUser'] = $this->Auth->user();
}
// login server url
$loginServer = Configure::read('LoginServer');
if ($loginServer && isset($loginServer['url'])) {
$this->loginServerUrl = $loginServer['url'] . '/';
} else {
$this->loginServerUrl = Router::url('/', true);
}
}
protected function requestLogin($session_id = 0)
{
$session = $this->getRequest()->getSession();
// check login
// disable encryption for cookies
//$this->Cookie->configKey('User', 'encryption', false);
if(!$session_id) {
$session_id = intval($this->request->getCookie('GRADIDO_LOGIN', ''));
}
$ip = $this->request->clientIp();
if (!$session->check('client_ip')) {
$session->write('client_ip', $ip);
}
// login server cannot detect host ip
// TODO: update login server, recognize nginx real ip header
$loginServer = Configure::read('LoginServer');
if ($session_id != 0) {
$userStored = $session->read('StateUser');
$transactionPendings = $session->read('Transaction.pending');
$transactionExecutings = $session->read('Transaction.executing');
if ($session->read('session_id') != $session_id ||
( $userStored && (!isset($userStored['id']) || !$userStored['email_checked'])) ||
intval($transactionPendings) > 0 ||
intval($transactionExecutings) > 0) {
$http = new Client();
try {
$url = $loginServer['host'] . ':' . $loginServer['port'];
$response = $http->get($url . '/login', ['session_id' => $session_id]);
$json = $response->getJson();
if (isset($json) && count($json) > 0) {
if ($json['state'] === 'success') {
//echo "email checked: " . $json['user']['email_checked'] . "; <br>";
if ($session->read('session_id') != $session_id ||
( $userStored && !isset($userStored['id']))) {
$session->destroy();
}
foreach ($json['user'] as $key => $value) {
$session->write('StateUser.' . $key, $value);
}
//var_dump($json);
$transactionPendings = $json['Transaction.pending'];
$transactionExecuting = $json['Transaction.executing'];
//echo "read transaction pending: $transactionPendings<br>";
$session->write('Transaction.pending', $transactionPendings);
$session->write('Transaction.executing', $transactionExecuting);
$session->write('session_id', $session_id);
$stateUserTable = TableRegistry::getTableLocator()->get('StateUsers');
if (isset($json['user']['public_hex']) && $json['user']['public_hex'] != '') {
$public_key_bin = hex2bin($json['user']['public_hex']);
$stateUserQuery = $stateUserTable
->find('all')
->where(['public_key' => $public_key_bin])
->contain(['StateBalances']);
if ($stateUserQuery->count() == 1) {
$stateUser = $stateUserQuery->first();
if ($stateUser->first_name != $json['user']['first_name'] ||
$stateUser->last_name != $json['user']['last_name'] ||
$stateUser->disabled != intval($json['user']['disabled']) ||
//$stateUser->username != $json['user']['username'] ||
// -> throws error
$stateUser->email != $json['user']['email']
) {
$stateUser->first_name = $json['user']['first_name'];
$stateUser->last_name = $json['user']['last_name'];
$stateUser->disabled = intval($json['user']['disabled']);
//$stateUser->username = $json['user']['username'];
$stateUser->email = $json['user']['email'];
if (!$stateUserTable->save($stateUser)) {
$this->Flash->error(__('error updating state user ' . json_encode($stateUser->errors())));
}
}
//var_dump($stateUser);
if (count($stateUser->state_balances) > 0) {
$session->write('StateUser.balance', $stateUser->state_balances[0]->amount);
}
$session->write('StateUser.id', $stateUser->id);
//echo $stateUser['id'];
} else {
$newStateUser = $stateUserTable->newEntity();
$newStateUser->public_key = $public_key_bin;
$newStateUser->first_name = $json['user']['first_name'];
$newStateUser->last_name = $json['user']['last_name'];
$newStateUser->disabled = intval($json['user']['disabled']);
//$newStateUser->username = $json['user']['username'];
$newStateUser->email = $json['user']['email'];
if (!$stateUserTable->save($newStateUser)) {
$this->Flash->error(__('error saving state user ' . json_encode($newStateUser->errors())));
}
$session->write('StateUser.id', $newStateUser->id);
//echo $newStateUser->id;
}
} else {
// we haven't get a pubkey? something seems to gone wrong on the login-server
$this->Flash->error(__('no pubkey'));
//var_dump($json);
return $this->redirect($this->loginServerUrl . 'account/error500/noPubkey', 303);
}
} else {
if ($json['state'] === 'not found') {
$this->Flash->error(__('invalid session'));
} else {
$this->Flash->error(__('Konto ist nicht aktiviert!'));
}
//die(json_encode($json));
return $this->redirect($this->loginServerUrl . 'account/', 303);
}
}
} catch (\Exception $e) {
$msg = $e->getMessage();
$this->Flash->error(__('error http request: ') . $msg);
return $this->redirect(['controller' => 'Dashboard', 'action' => 'errorHttpRequest']);
//continue;
}
}
} else {
// no login
//die("no login");
if (isset($loginServer['path'])) {
return $this->redirect($loginServer['path'], 303);
} else {
return $this->redirect($this->loginServerUrl . 'account/', 303);
}
}
return true;
}
/*
public function beforeFilter(Event $event)
{
//$this->Auth->allow(['display']);
}
*/
public function addAdminError($controller, $action, array $returnTable, $state_user_id)
{
if (!is_array($returnTable)) {
$this->addAdminError('AppController', 'addAdminError', ['state' => 'error', 'msg' => 'returnTable isn\'t array', 'details' => gettype($returnTable)], $state_user_id);
return false;
}
$adminErrorTable = TableRegistry::getTableLocator()->get('AdminErrors');
$adminErrorEntity = $adminErrorTable->newEntity();
$adminErrorEntity->state_user_id = $state_user_id;
$adminErrorEntity->controller = $controller;
$adminErrorEntity->action = $action;
$adminErrorEntity->state = $returnTable['state'];
if (isset($returnTable['msg'])) {
$adminErrorEntity->msg = $returnTable['msg'];
} else {
$adminErrorEntity->msg = __('(Leere Message)');
}
if (isset($returnTable['details'])) {
$adminErrorEntity->details = $returnTable['details'];
} else {
$adminErrorEntity->details = __('(Leere Details)');
}
if (!$adminErrorTable->save($adminErrorEntity)) {
$this->Flash->error(
__('Serious error, couldn\'t save to db, please write the admin: ' . $this->getAdminEmailLink()),
['escape' => false]
);
}
return true;
}
public function getAdminEmailLink($text = '')
{
$serverAdminEmail = Configure::read('ServerAdminEmail');
return '<a href="mailto:' . $serverAdminEmail . '">'. $serverAdminEmail . '</a>';
}
public function returnJsonEncoded($json)
{
$this->autoRender = false;
$response = $this->response->withType('application/json');
return $response->withStringBody($json);
}
public function returnJson($array)
{
$this->autoRender = false;
$response = $this->response->withType('application/json');
return $response->withStringBody(json_encode($array));
}
public function getStartEndForMonth($month, $year)
{
$timeString = $year . '-' . $month . '-01 00:00';
$firstDay = new Time($timeString);
$lastDay = new Time($timeString);
$lastDay = $lastDay->addMonth(1);
return [$firstDay, $lastDay];
}
}

View File

@ -0,0 +1,106 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* CommunityProfiles Controller
*
* @property \App\Model\Table\CommunityProfilesTable $CommunityProfiles
*
* @method \App\Model\Entity\CommunityProfile[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class CommunityProfilesController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$communityProfiles = $this->paginate($this->CommunityProfiles);
$this->set(compact('communityProfiles'));
}
/**
* View method
*
* @param string|null $id Community Profile id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$communityProfile = $this->CommunityProfiles->get($id, [
'contain' => [],
]);
$this->set('communityProfile', $communityProfile);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$communityProfile = $this->CommunityProfiles->newEntity();
if ($this->request->is('post')) {
$communityProfile = $this->CommunityProfiles->patchEntity($communityProfile, $this->request->getData());
if ($this->CommunityProfiles->save($communityProfile)) {
$this->Flash->success(__('The community profile has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The community profile could not be saved. Please, try again.'));
}
$this->set(compact('communityProfile'));
}
/**
* Edit method
*
* @param string|null $id Community Profile id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$communityProfile = $this->CommunityProfiles->get($id, [
'contain' => [],
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$communityProfile = $this->CommunityProfiles->patchEntity($communityProfile, $this->request->getData());
if ($this->CommunityProfiles->save($communityProfile)) {
$this->Flash->success(__('The community profile has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The community profile could not be saved. Please, try again.'));
}
$this->set(compact('communityProfile'));
}
/**
* Delete method
*
* @param string|null $id Community Profile id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$communityProfile = $this->CommunityProfiles->get($id);
if ($this->CommunityProfiles->delete($communityProfile)) {
$this->Flash->success(__('The community profile has been deleted.'));
} else {
$this->Flash->error(__('The community profile could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,33 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace App\Controller\Component;
use Cake\Controller\Component;
class GradidoNumberComponent extends Component
{
// input can be from 0,01 or 0.01 up to big number be anything
public function parseInputNumberToCentNumber($inputNumber)
{
//$filteredInputNumber = preg_replace('/,/', '.', $inputNumber);
$parts = preg_split('/(,|\.)/', (string)$inputNumber);
$result = intval($parts[0]) * 10000;
if(count($parts) == 2) {
$result += intval($parts[1]) * 100;
}
return $result;
}
public function centToPrint($centAmount)
{
}
}

View File

@ -0,0 +1,143 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace App\Controller\Component;
use App\Model\Validation\GenericValidation;
use Cake\Controller\Component;
use Cake\Http\Client;
use Cake\Core\Configure;
class JsonRequestClientComponent extends Component
{
public function sendTransaction($session_id, $base64Message, $user_balance = 0) {
if(!is_numeric($session_id)) {
return ['state' => 'error', 'type' => 'parameter error', 'msg' => 'session_id isn\'t numeric'];
}
if(!is_numeric($user_balance) || intval($user_balance) < 0) {
return ['state' => 'error', 'type' => 'parameter error', 'msg' => 'user_balance invalid'];
}
if(is_array($base64Message)) {
foreach($base64Message as $singleMessage) {
if(!$this->is_base64($singleMessage)) {
return ['state' => 'error', 'type' => 'parameter error', 'msg' => 'at least one base64Message contain invalid base64 characters'];
}
}
} else if(!$this->is_base64($base64Message)) {
return ['state' => 'error', 'type' => 'parameter error', 'msg' => 'base64Message contain invalid base64 characters'];
}
return $this->sendRequest(json_encode([
'session_id' => $session_id,
'transaction_base64' => $base64Message,
'balance' => $user_balance
]), '/checkTransaction');
}
public function getRunningUserTasks($email)
{
if($email == "") {
return ['state' => 'error', 'type' => 'parameter error', 'msg' => 'email is empty'];
}
if(!GenericValidation::email($email, [])) {
return ['state' => 'error', 'type' => 'parameter error', 'msg' => 'email is invalid'];
}
return $this->sendRequest(json_encode([
'email' => $email
]), '/getRunningUserTasks');
}
public function getUsers($session_id, $searchString)
{
if($searchString == "") {
return ['state' => 'error', 'type' => 'parameter error', 'msg' => 'search string is empty'];
}
if(!is_numeric($session_id)) {
return ['state' => 'error', 'type' => 'parameter error', 'msg' => 'session_id isn\'t numeric'];
}
return $this->sendRequest(json_encode([
'session_id' => $session_id,
'search' => $searchString
]), '/getUsers');
}
public function sendRequest($transactionBody, $url_last_part) {
$http = new Client();
$response = $http->post($this->getLoginServerUrl() . $url_last_part, $transactionBody, ['type' => 'json']);
$responseStatus = $response->getStatusCode();
if($responseStatus != 200) {
return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response status code isn\'t 200', 'details' => $responseStatus];
}
//$responseType = $response->getType();
//if($responseType != 'application/json') {
// return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response isn\'t json', 'details' => $responseType];
// }
$json = $response->getJson();
if($json == null) {
//$responseType = $response->getType();
return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response isn\'t valid json'];
}
return ['state' => 'success', 'data' => $json];
}
public function sendRequestGDT($transactionBody, $url) {
$http = new Client();
$gdtServerHost = $this->getGDTServerUrl();
if(!$gdtServerHost) {
return ['state' => 'warning', 'msg' => 'gdt server not configured'];
}
$fullUrl = $gdtServerHost . DS . $url;
$response = $http->post($this->getGDTServerUrl() . DS . $url, $transactionBody, ['type' => 'json']);
$responseStatus = $response->getStatusCode();
if($responseStatus != 200) {
return [
'state' => 'error',
'type' => 'request error',
'msg' => 'server response status code isn\'t 200',
'details' => $responseStatus,
'fullUrl' => $fullUrl
];
}
//$responseType = $response->getType();
//if($responseType != 'application/json') {
// return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response isn\'t json', 'details' => $responseType];
// }
$json = $response->getJson();
if($json == null) {
//$responseType = $response->getType();
return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response isn\'t valid json'];
}
return ['state' => 'success', 'data' => $json];
}
static public function getLoginServerUrl()
{
$loginServer = Configure::read('LoginServer');
return $loginServer['host'] . ':' . $loginServer['port'];
}
static public function getGDTServerUrl()
{
$gdtServer = Configure::read('GDTServer');
if(isset($gdtServer['host'])) {
return $gdtServer['host'];
}
return false;
}
static public function is_base64($s)
{
return (bool) preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s);
}
}

View File

@ -0,0 +1,71 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Http\Client;
use Cake\Core\Configure;
use Datto\JsonRpc\Client as JsonRpcClient;
//App\Controller\Component\ComponentRegistry
class JsonRpcRequestClientComponent extends Component
{
var $rpcClient = null;
public function __construct($registry, array $config = array()) {
parent::__construct($registry, $config);
$this->rpcClient = new JsonRpcClient();
}
// @param id: if id = 0 call rand for it
public function request($method, $params = [], $id = 0)
{
if(0 == $id) {
$id = random_int(1, 12000);
}
$this->rpcClient->query($id, $method, $params);
$message = $this->rpcClient->encode();
return $this->sendRequest($message);
// message: {"jsonrpc":"2.0","method":"add","params":[1,2],"id":1}
}
public function sendRequest($message) {
$http = new Client();
$response = $http->post($this->getGradidoNodeUrl(), $message, ['type' => 'json']);
$responseStatus = $response->getStatusCode();
if($responseStatus != 200) {
return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response status code isn\'t 200', 'details' => $responseStatus];
}
//$responseType = $response->getType();
//if($responseType != 'application/json') {
// return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response isn\'t json', 'details' => $responseType];
// }
$json = $response->getJson();
if($json == null) {
//$responseType = $response->getType();
return ['state' => 'error', 'type' => 'request error', 'msg' => 'server response isn\'t valid json'];
}
return $json;
//return ['state' => 'success', 'data' => $json];
}
static public function getGradidoNodeUrl()
{
$gradidoNode = Configure::read('GradidoNode');
return $gradidoNode['host'] . ':' . $gradidoNode['port'];
}
}

View File

@ -0,0 +1,78 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
//use Cake\Routing\Router;
use Cake\ORM\TableRegistry;
use Model\Navigation\NaviHierarchy;
use Model\Navigation\NaviHierarchyEntry;
/**
* StateUsers Controller
*
* @property \App\Model\Table\StateUsersTable $StateUsers
*
* @method \App\Model\Entity\StateUser[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class DashboardController extends AppController
{
public function initialize()
{
parent::initialize();
//$this->Auth->allow(['add', 'edit']);
$this->Auth->allow(['index', 'errorHttpRequest']);
$this->set(
'naviHierarchy',
(new NaviHierarchy())->
add(new NaviHierarchyEntry(__('Startseite'), 'Dashboard', 'index', true))
);
}
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend');
$session = $this->getRequest()->getSession();
$result = $this->requestLogin();
if($result !== true) {
return $result;
}
$user = $session->read('StateUser');
$serverUser = $this->Auth->user('id');
if($serverUser) {
$adminErrorsTable = TableRegistry::getTableLocator()->get('AdminErrors');
$adminErrorCount = $adminErrorsTable->find('all')->count();
$this->set('adminErrorCount', $adminErrorCount);
}
$this->set('user', $user);
$this->set('serverUser', $serverUser);
$this->set('timeUsed', microtime(true) - $startTime);
}
public function serverIndex()
{
$startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend');
$adminErrorsTable = TableRegistry::getTableLocator()->get('AdminErrors');
$adminErrorCount = $adminErrorsTable->find('all')->count();
$this->set('adminErrorCount', $adminErrorCount);
$this->set('timeUsed', microtime(true) - $startTime);
}
public function errorHttpRequest()
{
$startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend');
$this->set('timeUsed', microtime(true) - $startTime);
}
}

View File

@ -0,0 +1,165 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Datasource\ConnectionManager;
use Cake\I18n\Time;
//use Cake\I18n\Date;
use Cake\ORM\TableRegistry;
/**
* ElopageBuys Controller
*
* @property \App\Model\Table\ElopageBuysTable $ElopageBuys
*
* @method \App\Model\Entity\ElopageBuy[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class ElopageBuysController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => false,
];
$elopageBuys = $this->paginate($this->ElopageBuys);
$this->set(compact('elopageBuys'));
}
public function statistics()
{
$this->viewBuilder()->setLayout('frontend');
$connection = ConnectionManager::get('loginServer');
$dates = $connection->execute('SELECT success_date FROM elopage_buys group by CAST(success_date as DATE)')->fetchAll('assoc');
$datesTree = [];
foreach($dates as $i => $date) {
$date = new Time($date['success_date']);
if(!isset($datesTree[$date->year])) {
$datesTree[$date->year] = [];
}
if(!isset($datesTree[$date->year][$date->month])) {
$datesTree[$date->year][$date->month] = true;
}
}
//var_dump($datesTree);
$now = Time::now();
$lastDay = Time::now();
$lastDay->day = 1;
$now->day = 1;
$lastDay->setTime(0,0,0,0);
$now->setTime(0,0,0,0);
// only for test
$now->month = 11;
$lastDay->month = 11;
$now->year = 2019;
$lastDay->year = 2019;
// var_dump($now);
$lastDay = $lastDay->addMonth(1);
$sortDate = $this->getStartEndForMonth(11, 2019);
$elopageBuys = $this->ElopageBuys
->find('all')
->where(['success_date >=' => $sortDate[0], 'success_date <' => $sortDate[1]]);
$users = [];
foreach($elopageBuys as $elopageEntry) {
array_push($users, $elopageEntry->payer_email);
}
$unique_users = array_unique($users);
$userTable = TableRegistry::getTableLocator()->get('Users');
$users = $userTable->find('all')
->where(['created >=' => $sortDate[0], 'created <' => $sortDate[1]]);
$this->set(compact('elopageBuys', 'users'));
}
/**
* View method
*
* @param string|null $id Elopage Buy id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$elopageBuy = $this->ElopageBuys->get($id, [
'contain' => false,
]);
$this->set('elopageBuy', $elopageBuy);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$elopageBuy = $this->ElopageBuys->newEntity();
if ($this->request->is('post')) {
$elopageBuy = $this->ElopageBuys->patchEntity($elopageBuy, $this->request->getData());
if ($this->ElopageBuys->save($elopageBuy)) {
$this->Flash->success(__('The elopage buy has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The elopage buy could not be saved. Please, try again.'));
}
$this->set(compact('elopageBuy'));
}
/**
* Edit method
*
* @param string|null $id Elopage Buy id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$elopageBuy = $this->ElopageBuys->get($id, [
'contain' => false,
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$elopageBuy = $this->ElopageBuys->patchEntity($elopageBuy, $this->request->getData());
if ($this->ElopageBuys->save($elopageBuy)) {
$this->Flash->success(__('The elopage buy has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The elopage buy could not be saved. Please, try again.'));
}
$this->set(compact('elopageBuy'));
}
/**
* Delete method
*
* @param string|null $id Elopage Buy id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$elopageBuy = $this->ElopageBuys->get($id);
if ($this->ElopageBuys->delete($elopageBuy)) {
$this->Flash->success(__('The elopage buy has been deleted.'));
} else {
$this->Flash->error(__('The elopage buy could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,51 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace App\Controller;
use App\Controller\AppController;
class ElopageWebhookController extends AppController
{
public function initialize()
{
parent::initialize();
$this->Auth->allow(['put']);
}
public function put()
{
$this->autoRender = false;
$data = $this->request->getData();
$response = $this->response->withType('text/plain');
$dataString = http_build_query($data);
//$this->recursiveArrayToString($data, $dataString);
// %5B => [
// %5D => ]
$dataString = preg_replace(['/\%5B/', '/\%5D/'], ['[', ']'], $dataString);
//var_dump($dataString);
//2020-02-27T13:52:32+01:00
$dateString = date('c');
$fh = fopen('/etc/grd_login/php_elopage_requests.txt', 'a');
if($fh === FALSE) {
return $response->withStringBody('400 ERROR');
}
fwrite($fh, $dateString);
fwrite($fh, "\n");
fwrite($fh, $dataString);
fwrite($fh, "\n");
fclose($fh);
return $response->withStringBody('200 OK');
}
}

View File

@ -0,0 +1,70 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 3.3.4
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App\Controller;
use Cake\Event\Event;
/**
* Error Handling Controller
*
* Controller used by ExceptionRenderer to render error responses.
*/
class ErrorController extends AppController
{
/**
* Initialization hook method.
*
* @return void
*/
public function initialize()
{
$this->loadComponent('RequestHandler', [
'enableBeforeRedirect' => false,
]);
}
/**
* beforeFilter callback.
*
* @param \Cake\Event\Event $event Event.
* @return \Cake\Http\Response|null|void
*/
public function beforeFilter(Event $event)
{
}
/**
* beforeRender callback.
*
* @param \Cake\Event\Event $event Event.
* @return \Cake\Http\Response|null|void
*/
public function beforeRender(Event $event)
{
parent::beforeRender($event);
$this->viewBuilder()->setTemplatePath('Error');
}
/**
* afterFilter callback.
*
* @param \Cake\Event\Event $event Event.
* @return \Cake\Http\Response|null|void
*/
public function afterFilter(Event $event)
{
}
}

View File

@ -0,0 +1,261 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Routing\Router;
use Cake\Http\Client;
use Cake\Core\Configure;
use Model\Transactions\TransactionTransfer;
use Model\Transactions\Transaction;
/*!
* @author: Dario Rekowski#
*
* @date: 03.11.2019
*
* @desc: Handle requests from other server put or request transaction
*/
class JsonRequestHandlerController extends AppController {
public function initialize()
{
parent::initialize();
$this->loadComponent('JsonRequestClient');
//$this->Auth->allow(['add', 'edit']);
$this->Auth->allow('index');
}
public function index()
{
if($this->request->is('get')) {
$method = $this->request->getQuery('method');
switch($method) {
case 'getRunningUserTasks': return $this->getRunningUserTasks();
}
return $this->returnJson(['state' => 'error', 'msg' => 'unknown method for get', 'details' => $method]);
}
else if($this->request->is('post')) {
$jsonData = $this->request->input('json_decode');
//var_dump($jsonData);
if($jsonData == NULL || !isset($jsonData->method)) {
return $this->returnJson(['state' => 'error', 'msg' => 'parameter error']);
}
$method = $jsonData->method;
switch($method) {
case 'putTransaction':
if(!isset($jsonData->transaction)) {
return $this->returnJson(['state' => 'error', 'msg' => 'parameter error']);
} else {
return $this->putTransaction($jsonData->transaction);
}
case 'userDelete': return $this->userDelete($jsonData->user);
case 'moveTransaction': return $this->moveTransaction($jsonData->pubkeys, $jsonData->memo, $jsonData->session_id);
case 'checkUser': return $this->checkUser($jsonData->email, $jsonData->last_name);
case 'getUsers' : return $this->getUsers($jsonData->page, $jsonData->limit);
case 'getUserBalance': return $this->getUserBalance($jsonData->email, $jsonData->last_name);
case 'errorInTransaction': return $this->errorInTransaction($jsonData->created, $jsonData->transactionGenericHash, $jsonData->error, $jsonData->errorMessage);
}
return $this->returnJson(['state' => 'error', 'msg' => 'unknown method for post', 'details' => $method]);
}
return $this->returnJson(['state' => 'error', 'msg' => 'no post or get']);
}
//! \param $transactionCreated creation of transaction in timestamp in seconds
//! -1 if transaction couldn't decode
//! \param $transactionBodyBase64Sha256 generic hash from transaction body serialized and converted to base64
//! using sodium_crypto_generichash to calculate
// hash also in base64 format
//! \param $error short error name in user language
//! \param $errorDetails more detailed error message in user language
private function errorInTransaction($transactionCreated, $transactionBodyBase64GenericHash, $error, $errorDetails) {
/*
* payload.set("created", created);
* payload.set("id", task_model->getID());
* payload.set("public_key", user_model->getPublicKeyHex());
* payload.set("error", error);
* payload.set("errorMessage", errorDetails);
*/
}
private function putTransaction($transactionBase64) {
$transaction = new Transaction($transactionBase64);
//echo "after new transaction<br>";
if($transaction->hasErrors()) {
return $this->returnJson(['state' => 'error', 'msg' => 'error parsing transaction', 'details' => $transaction->getErrors()]);
}
//echo "after check on errors<br>";
if(!$transaction->validate()) {
return $this->returnJsonSaveError($transaction, ['state' => 'error', 'msg' => 'error validate transaction', 'details' => $transaction->getErrors()]);
}
//echo "after validate <br>";
if ($transaction->save()) {
// success
return $this->returnJson(['state' => 'success']);
} else {
return $this->returnJsonSaveError($transaction, [
'state' => 'error',
'msg' => 'error saving transaction in db',
'details' => json_encode($transaction->getErrors())
]);
}
return $this->returnJson(['state' => 'success']);
}
private function moveTransaction($pubkeys, $memo, $session_id) {
//$pubkeys->sender
//$pubkeys->receiver
$stateUserTable = TableRegistry::getTableLocator()->get('StateUsers');
$user = $stateUserTable->find('all')->where(['public_key' => hex2bin($pubkeys->sender)])->contain(['StateBalances']);
if(!$user->count()) {
return $this->returnJson(['state' => 'not found', 'msg' => 'user not found or empty balance']);
}
$amountCent = $user->first()->state_balances[0]->amount;
//var_dump($user->first());
$builderResult = TransactionTransfer::build(
$amountCent,
$memo,
$pubkeys->receiver,
$pubkeys->sender
);
if($builderResult['state'] === 'success') {
$http = new Client();
try {
$loginServer = Configure::read('LoginServer');
$url = $loginServer['host'] . ':' . $loginServer['port'];
$response = $http->post($url . '/checkTransaction', json_encode([
'session_id' => $session_id,
'transaction_base64' => base64_encode($builderResult['transactionBody']->serializeToString()),
'balance' => $amountCent
]), ['type' => 'json']);
$json = $response->getJson();
if($json['state'] != 'success') {
if($json['msg'] == 'session not found') {
return $this->returnJson(['state' => 'error', 'msg' => 'session not found']);
} else {
//$this->Flash->error(__('login server return error: ' . json_encode($json)));
return $this->returnJson(['state' => 'error', 'msg' => 'login server return error', 'details' => $json]);
}
} else {
return $this->returnJson(['state' => 'success']);
}
} catch(\Exception $e) {
$msg = $e->getMessage();
//$this->Flash->error(__('error http request: ') . $msg);
return $this->returnJson(['state' => 'error', 'msg' => 'error http request', 'details' => $msg]);
}
} else {
return $this->returnJson(['state' => 'error', 'msg' => 'error building transaction']);
}
}
private function userDelete($userPubkeyHex) {
$stateUserTable = TableRegistry::getTableLocator()->get('StateUsers');
$user = $stateUserTable->find('all')->where(['public_key' => hex2bin($userPubkeyHex)]);
if(!$user || $user->count == 0) {
return $this->returnJson(['state' => 'error', 'msg' => 'user not found']);
}
}
private function checkUser($email, $last_name) {
$userTable = TableRegistry::getTableLocator()->get('Users');
$user = $userTable->find('all')
->where(['email' => $email])
->contain([])
->select(['first_name', 'last_name', 'email']);
if(!$user->count()) {
return $this->returnJson(['state' => 'not found', 'msg' => 'user not found']);
}
if($user->count() == 1 && $user->first()->last_name == $last_name) {
return $this->returnJson(['state' => 'success']);
}
return $this->returnJson(['state' => 'not identical', 'user' => $user->toArray()]);
}
private function getUserBalance($email, $last_name) {
$stateUserTable = TableRegistry::getTableLocator()->get('StateUsers');
$stateUsers = $stateUserTable->find('all')->where(['OR' => ['email' => $email, 'last_name' => $last_name]])->contain(['StateBalances']);
$gdds = [];
foreach($stateUsers as $stateUser) {
foreach($stateUser->state_balances as $stateBalance) {
if(!isset($gdds[$stateUser->email])) {
$gdds[$stateUser->email] = [];
}
if(!isset($gdds[$stateUser->email][$stateUser->last_name])) {
$gdds[$stateUser->email][$stateUser->last_name] = 0;
}
$gdds[$stateUser->email][$stateUser->last_name] += $stateBalance->amount;
}
}
return $this->returnJson(['state' => 'success', 'gdds' => $gdds]);
}
private function getUsers($page, $count) {
$userTable = TableRegistry::getTableLocator()->get('Users');
$this->paginate = [
'limit' => $count,
'page' => $page
];
$usersQuery = $userTable->find('all')
->select(['first_name', 'last_name', 'email'])
->order(['id']);
try {
return $this->returnJson(['state' => 'success', 'users' => $this->paginate($usersQuery)]);
} catch (Exception $ex) {
return $this->returnJson(['state' => 'exception', 'msg' => 'error paginate users', 'details' => $ex->getMessage()]);
}
//return $this->returnJson(['state' => 'success', 'users' => $users->toArray()]);
}
private function getRunningUserTasks() {
$session = $this->getRequest()->getSession();
$state_user_email = $session->read('StateUser.email');
$requestResult = $this->JsonRequestClient->getRunningUserTasks($state_user_email);;
return $this->returnJson($requestResult);
}
private function returnJsonSaveError($transaction, $errorArray) {
$json = json_encode($errorArray);
$stateUserTable = TableRegistry::getTableLocator()->get('StateUsers');
$pub = $transaction->getFirstPublic();
$stateUserQuery = $stateUserTable
->find('all')
->where(['public_key' => $pub])
->contain(false);
if($stateUserQuery->count() == 1) {
$stateErrorsTable = TableRegistry::getTableLocator()->get('StateErrors');
$stateErrorEntity = $stateErrorsTable->newEntity();
$stateErrorEntity->state_user_id = $stateUserQuery->first()->id;
$stateErrorEntity->transaction_type_id = $transaction->getTransactionBody()->getTransactionTypeId();
$stateErrorEntity->message_json = $json;
$stateErrorsTable->save($stateErrorEntity);
} else {
$errorArray['user_error'] = "user with $pub not found";
$json = json_encode($errorArray);
}
return $this->returnJsonEncoded($json);
}
}

View File

@ -0,0 +1,106 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* OperatorTypes Controller
*
* @property \App\Model\Table\OperatorTypesTable $OperatorTypes
*
* @method \App\Model\Entity\OperatorType[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class OperatorTypesController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$operatorTypes = $this->paginate($this->OperatorTypes);
$this->set(compact('operatorTypes'));
}
/**
* View method
*
* @param string|null $id Operator Type id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$operatorType = $this->OperatorTypes->get($id, [
'contain' => ['Operators']
]);
$this->set('operatorType', $operatorType);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$operatorType = $this->OperatorTypes->newEntity();
if ($this->request->is('post')) {
$operatorType = $this->OperatorTypes->patchEntity($operatorType, $this->request->getData());
if ($this->OperatorTypes->save($operatorType)) {
$this->Flash->success(__('The operator type has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The operator type could not be saved. Please, try again.'));
}
$this->set(compact('operatorType'));
}
/**
* Edit method
*
* @param string|null $id Operator Type id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$operatorType = $this->OperatorTypes->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$operatorType = $this->OperatorTypes->patchEntity($operatorType, $this->request->getData());
if ($this->OperatorTypes->save($operatorType)) {
$this->Flash->success(__('The operator type has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The operator type could not be saved. Please, try again.'));
}
$this->set(compact('operatorType'));
}
/**
* Delete method
*
* @param string|null $id Operator Type id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$operatorType = $this->OperatorTypes->get($id);
if ($this->OperatorTypes->delete($operatorType)) {
$this->Flash->success(__('The operator type has been deleted.'));
} else {
$this->Flash->error(__('The operator type could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,236 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
//require_once "../../vendor/paragonie/sodium_compat/autoload.php";
/**
* Operators Controller
*
* @property \App\Model\Table\OperatorsTable $Operators
*
* @method \App\Model\Entity\Operator[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class OperatorsController extends AppController
{
public function initialize()
{
parent::initialize();
$this->Auth->allow(['ajaxSave', 'ajaxLoad', 'ajaxDelete']);
}
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => ['OperatorTypes']
];
$operators = $this->paginate($this->Operators);
$this->set(compact('operators'));
}
public function ajaxSave()
{
if ($this->request->is('post')) {
$operatorTypeName = $this->request->getData('operator_type_name');
$username = $this->request->getData('username');
$pubkey_bin = base64_decode($this->request->getData('user_pubkey'));
$data = base64_decode($this->request->getData('data_base64'));
$sign = base64_decode($this->request->getData('sign'));
//$publicKey_hex = bin2hex($pubkey_bin);
//$signature_hex = bin2hex($sign);
if(!sodium_crypto_sign_verify_detached($sign, $data, $pubkey_bin)) {
return $this->returnJson([
'state' => 'wrong signature',
/* 'details' => [
'pubkey' => $publicKey_hex,
'sign' => $signature_hex,
'data' => bin2hex($data)
]
*/
]);
}
$operatorTypeId = $this->Operators->OperatorTypes->
find()
->where(['name' => $operatorTypeName])
->select(['id'])
->first();
// load operator from db if already exist
$operator = $this->Operators
->find()
->where([
'operator_type_id' => $operatorTypeId->id,
'username' => $username,
'user_pubkey' => $pubkey_bin])
->first();
if(!$operator) {
// create new entity
$operator = $this->Operators->newEntity();
} else {
// check if request has valid signature
}
$operator = $this->Operators->patchEntity($operator, $this->request->getData());
$operator->user_pubkey = $pubkey_bin;
$operator->operator_type_id = $operatorTypeId->id;
if ($this->Operators->save($operator)) {
return $this->returnJson(['state' => 'success']);
}
return $this->returnJson(['state' => 'error', 'details' => $operator->getErrors()]);
}
return $this->returnJson(['state' => 'error', 'msg' => 'no post request']);
}
public function ajaxLoad()
{
if ($this->request->is('get')) {
$username = $this->request->getQuery('username');
$operators = $this->Operators
->find()
->where(['username' => $username])
->contain(['OperatorTypes'])
->select(['data_base64', 'OperatorTypes.name'])
->toArray();
;
if($operators) {
return $this->returnJson(['state' => 'success', 'operators' => $operators]);
} else {
return $this->returnJson(['state' => 'not found']);
}
}
return $this->returnJson(['state' => 'error', 'msg' => 'no post request']);
}
function ajaxDelete() {
if ($this->request->is('delete')) {
$operatorTypeName = $this->request->getData('operator_type_name');
$username = $this->request->getData('username');
$pubkey_bin = base64_decode($this->request->getData('user_pubkey'));
$sign = base64_decode($this->request->getData('sign'));
$operatorTypeId = $this->Operators->OperatorTypes->
find()
->where(['name' => $operatorTypeName])
->select(['id'])
->first();
// load operator from db if already exist
$operator = $this->Operators
->find()
->where([
'operator_type_id' => $operatorTypeId->id,
'username' => $username,
'user_pubkey' => $pubkey_bin])
->first();
if(!$operator) {
return $this->returnJson(['state' => 'error', 'msg' => 'not found']);
} else {
$data = base64_decode($operator->data_base64);
// check if request has valid signature
if(!sodium_crypto_sign_verify_detached($sign, $data, $pubkey_bin)) {
return $this->returnJson(['state' => 'error', 'msg' => 'wrong signature']);
}
}
if ($this->Operators->delete($operator)) {
return $this->returnJson(['state' => 'success']);
}
return $this->returnJson(['state' => 'error', 'details' => $operator->getErrors()]);
}
return $this->returnJson(['state' => 'error', 'msg' => 'no post request']);
}
/**
* View method
*
* @param string|null $id Operator id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$operator = $this->Operators->get($id, [
'contain' => ['OperatorTypes']
]);
$this->set('operator', $operator);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$operator = $this->Operators->newEntity();
if ($this->request->is('post')) {
$operator = $this->Operators->patchEntity($operator, $this->request->getData());
if ($this->Operators->save($operator)) {
$this->Flash->success(__('The operator has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The operator could not be saved. Please, try again.'));
}
$operatorTypes = $this->Operators->OperatorTypes->find('list', ['limit' => 200]);
$this->set(compact('operator', 'operatorTypes'));
}
/**
* Edit method
*
* @param string|null $id Operator id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$operator = $this->Operators->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$operator = $this->Operators->patchEntity($operator, $this->request->getData());
if ($this->Operators->save($operator)) {
$this->Flash->success(__('The operator has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The operator could not be saved. Please, try again.'));
}
$operatorTypes = $this->Operators->OperatorTypes->find('list', ['limit' => 200]);
$this->set(compact('operator', 'operatorTypes'));
}
/**
* Delete method
*
* @param string|null $id Operator id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$operator = $this->Operators->get($id);
if ($this->Operators->delete($operator)) {
$this->Flash->success(__('The operator has been deleted.'));
} else {
$this->Flash->error(__('The operator could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,75 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 0.2.9
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace App\Controller;
use Cake\Core\Configure;
use Cake\Http\Exception\ForbiddenException;
use Cake\Http\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
/**
* Static content controller
*
* This controller will render views from Template/Pages/
*
* @link https://book.cakephp.org/3.0/en/controllers/pages-controller.html
*/
class PagesController extends AppController
{
public function initialize()
{
parent::initialize();
$this->Auth->allow(['display']);
}
/**
* Displays a view
*
* @param array ...$path Path segments.
* @return \Cake\Http\Response|null
* @throws \Cake\Http\Exception\ForbiddenException When a directory traversal attempt.
* @throws \Cake\Http\Exception\NotFoundException When the view file could not
* be found or \Cake\View\Exception\MissingTemplateException in debug mode.
*/
public function display(...$path)
{
$count = count($path);
if (!$count) {
return $this->redirect('/');
}
if (in_array('..', $path, true) || in_array('.', $path, true)) {
throw new ForbiddenException();
}
$page = $subpage = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
$this->set(compact('page', 'subpage'));
try {
$this->render(implode('/', $path));
} catch (MissingTemplateException $exception) {
if (Configure::read('debug')) {
throw $exception;
}
throw new NotFoundException();
}
}
}

View File

@ -0,0 +1,206 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
use Model\Navigation\NaviHierarchy;
use Model\Navigation\NaviHierarchyEntry;
use Cake\ORM\TableRegistry;
use Cake\Filesystem\File;
use App\Form\ProfileForm;
/**
* Profile Controller
*/
class ProfileController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('JsonRequestClient');
$this->Auth->allow(['index', 'edit']);
$this->set(
'naviHierarchy',
(new NaviHierarchy())->
add(new NaviHierarchyEntry(__('Startseite'), 'Dashboard', 'index', false))->
add(new NaviHierarchyEntry(__('Mein Profil'), 'Profile', 'index', true))
);
}
/**
* Get binary file data from request data
*
* @return binary data
*/
protected function getFileData($requestData)
{
$binaryFileData = null;
// Get a list of UploadedFile objects
$file = $requestData['profile_img'];
// Read the file data.
$type = $file['type'];
$error = $file['error'];
if ($error === 0 && strpos($type, 'image/') === 0) {
$path = new File($file['tmp_name']);
$binaryFileData = $path->read(true, 'r');
$this->log("binaryFileData: ".$binaryFileData, 'debug');
}
return $binaryFileData;
}
/**
* Update Profile Data
*
* ...which is spread over two tables, plus needs to be promoted to the Login Server.
*
* @throws Exception
*/
protected function updateProfileData($requestData, $userId, $communityProfile)
{
// Update Profile with Form Data!
$usersTable = TableRegistry::getTableLocator()->get('StateUsers');
$stateUserQuery = $usersTable
->find('all')
->select(['id', 'first_name', 'last_name'])
->where(['id' => $userId]);
if ($stateUserQuery->count() == 1) {
$stateUser = $stateUserQuery->first();
$stateUser = $usersTable->patchEntity($stateUser, $requestData);
$profilesTable = TableRegistry::getTableLocator()->get('CommunityProfiles');
// Save old binary data, because the file input is always empty, in HTML!
$oldBinaryData = $communityProfile['profile_img'];
$communityProfile = $profilesTable->patchEntity($communityProfile, $requestData);
$communityProfile['state_user_id'] = $userId;
$binaryFileData = $this->getFileData($requestData);
if ($binaryFileData !== null) {
$this->log("CommunityProfile: Writing binary img data.", 'debug');
$communityProfile['profile_img'] = $binaryFileData;
} else {
$this->log("CommunityProfile: Nothing uploaded!", 'debug');
$communityProfile['profile_img'] = $oldBinaryData;
}
if ($profilesTable->save($communityProfile) &&
$usersTable->save($stateUser)
) {
$session = $this->getRequest()->getSession();
$session_id = $session->read('session_id');
$email = $session->read('StateUser.email');
$this->returnJson(
$this->JsonRequestClient->sendRequest(
json_encode(
[
'session_id' => $session_id,
'email' => $email,
'update' => [
'User.first_name' => $requestData['first_name'],
'User.last_name' => $requestData['last_name']
]
]
),
'/updateUserInfos'
)
);
$this->Flash->success(__('Dein Profil wurde aktualisiert!'));
}
} else {
$this->Flash->error(__("Non-recoverable database problem - state_user doesn't exist or not unique!"));
}
return [$stateUser, $communityProfile];
}
/**
* Get or create CommunityProfile
*
* @return \Cake\ORM\CommunityProfile
*/
protected function getCommunityProfile($userId)
{
$profilesTable = TableRegistry::getTableLocator()->get('CommunityProfiles');
$communityProfileQuery = $profilesTable
->find('all')
->select(['id', 'profile_img', 'profile_desc'])
->where(['state_user_id' => $userId]);
if ($communityProfileQuery->count() != 1) {
$communityProfile = $profilesTable->newEntity();
if ($profilesTable->save($communityProfile)) {
$this->log("CommunityProfile created.", 'debug');
}
} else {
$communityProfile = $communityProfileQuery->first();
}
return $communityProfile;
}
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend');
$session = $this->getRequest()->getSession();
$result = $this->requestLogin();
if ($result !== true) {
return $result;
}
$user = $session->read('StateUser');
$communityProfile = $session->read('CommunityProfile');
if (!$communityProfile) {
$this->log("CommunityProfile not found in session! Loading or creating new one.", 'debug');
$session->write('CommunityProfile', $this->getCommunityProfile($user['id']));
}
$this->set('user', $user);
$this->set('communityProfile', $communityProfile);
$this->set('timeUsed', microtime(true) - $startTime);
}
/**
* Edit method
*
* @return \Cake\Http\Response|null
*/
public function edit()
{
$startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend');
$session = $this->getRequest()->getSession();
$user = $session->read('StateUser');
$communityProfile = $session->read('CommunityProfile');
if (!$user) {
$result = $this->requestLogin();
if ($result !== true) {
return $result;
}
$user = $session->read('StateUser');
}
if (!$communityProfile) {
$this->log("CommunityProfile not found in session! Loading or creating new one.", 'debug');
$session->write('CommunityProfile', $this->getCommunityProfile($user['id']));
}
$profileForm = new ProfileForm();
if ($this->request->is('post')) {
$requestData = $this->request->getData();
if ($profileForm->validate($requestData)) {
[$stateUser, $communityProfile] = $this->updateProfileData($requestData, $user['id'], $communityProfile);
$user['first_name'] = $stateUser['first_name'];
$user['last_name'] = $stateUser['last_name'];
$session->write('StateUser.first_name', $stateUser['first_name']);
$session->write('StateUser.last_name', $stateUser['last_name']);
$session->write('CommunityProfile', $communityProfile);
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Something was invalid, please try again!'));
}
}
$this->set('user', $user);
$this->set('communityProfile', $communityProfile);
$this->set('profileForm', $profileForm);
$this->set('timeUsed', microtime(true) - $startTime);
}
}

View File

@ -0,0 +1,131 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* ServerUsers Controller
*
* @property \App\Model\Table\ServerUsersTable $ServerUsers
*
* @method \App\Model\Entity\ServerUser[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class ServerUsersController extends AppController
{
public function initialize()
{
parent::initialize();
$this->Auth->allow(['add', 'edit']);
$this->Auth->deny('index');
}
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$serverUsers = $this->paginate($this->ServerUsers);
$this->set(compact('serverUsers'));
}
public function login()
{
$startTime = microtime(true);
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
$this->set('timeUsed', microtime(true) - $startTime);
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
/**
* View method
*
* @param string|null $id Server User id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$serverUser = $this->ServerUsers->get($id, [
'contain' => []
]);
$this->set('serverUser', $serverUser);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$serverUser = $this->ServerUsers->newEntity();
if ($this->request->is('post')) {
$serverUser = $this->ServerUsers->patchEntity($serverUser, $this->request->getData());
if ($this->ServerUsers->save($serverUser)) {
$this->Flash->success(__('The server user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The server user could not be saved. Please, try again.'));
}
$this->set(compact('serverUser'));
}
/**
* Edit method
*
* @param string|null $id Server User id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$serverUser = $this->ServerUsers->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$serverUser = $this->ServerUsers->patchEntity($serverUser, $this->request->getData());
if ($this->ServerUsers->save($serverUser)) {
$this->Flash->success(__('The server user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The server user could not be saved. Please, try again.'));
}
$this->set(compact('serverUser'));
}
/**
* Delete method
*
* @param string|null $id Server User id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$serverUser = $this->ServerUsers->get($id);
if ($this->ServerUsers->delete($serverUser)) {
$this->Flash->success(__('The server user has been deleted.'));
} else {
$this->Flash->error(__('The server user could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,477 @@
<?php
namespace App\Controller;
use Cake\ORM\TableRegistry;
use App\Controller\AppController;
use Model\Navigation\NaviHierarchy;
use Model\Navigation\NaviHierarchyEntry;
/**
* StateBalances Controller
*
* @property \App\Model\Table\StateBalancesTable $StateBalances
*
* @method \App\Model\Entity\StateBalance[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class StateBalancesController extends AppController
{
public function initialize()
{
parent::initialize();
//$this->Auth->allow(['add', 'edit']);
$this->Auth->allow(['overview', 'overviewGdt', 'ajaxGetBalance']);
$this->loadComponent('JsonRequestClient');
}
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => ['StateUsers']
];
$stateBalances = $this->paginate($this->StateBalances);
$this->set(compact('stateBalances'));
}
public function overview()
{
$this->set(
'naviHierarchy',
(new NaviHierarchy())->
add(new NaviHierarchyEntry(__('Startseite'), 'Dashboard', 'index', false))->
add(new NaviHierarchyEntry(__('Kontoübersicht'), 'StateBalances', 'overview', true))
);
$startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend');
$session = $this->getRequest()->getSession();
$result = $this->requestLogin();
if ($result !== true) {
return $result;
}
$user = $session->read('StateUser');
// sendRequestGDT
// listPerEmailApi
$gdtSum = 0;
//if('admin' === $user['role']) {
$gdtEntries = $this->JsonRequestClient->sendRequestGDT(['email' => $user['email']], 'GdtEntries' . DS . 'sumPerEmailApi');
//var_dump($gdtEntries);
if('success' == $gdtEntries['state'] && 'success' == $gdtEntries['data']['state']) {
$gdtSum = intval($gdtEntries['data']['sum']);
} else {
if($user) {
$this->addAdminError('StateBalancesController', 'overview', $gdtEntries, $user['id']);
} else {
$this->addAdminError('StateBalancesController', 'overview', $gdtEntries, 0);
}
}
//}
//
//
$creationsTable = TableRegistry::getTableLocator()->get('TransactionCreations');
$creationTransactions = $creationsTable
->find('all')
->where(['state_user_id' => $user['id']])
->contain(['Transactions']);
$transferTable = TableRegistry::getTableLocator()->get('TransactionSendCoins');
$transferTransactions = $transferTable
->find('all')
->where(['OR' => ['state_user_id' => $user['id'], 'receiver_user_id' => $user['id']]])
->contain(['Transactions']);
$involvedUserIds = [];
foreach ($transferTransactions as $sendCoins) {
//var_dump($sendCoins);
if ($sendCoins->state_user_id != $user['id']) {
array_push($involvedUserIds, intval($sendCoins->state_user_id));
} elseif ($sendCoins->receiver_user_id != $user['id']) {
array_push($involvedUserIds, intval($sendCoins->receiver_user_id));
}
}
/*echo "state user from sendCoins: $sendCoins->state_user_id<br>";
echo "receiver user from sendCoins: $sendCoins->receiver_user_id<br>";
echo "user id from logged in user: ".$user['id']. '<br>';
*/
//var_dump($involvedUserIds);
// exchange key with values and drop duplicates
$involvedUser_temp = array_flip($involvedUserIds);
// exchange back
$involvedUserIds = array_flip($involvedUser_temp);
$userTable = TableRegistry::getTableLocator()->get('StateUsers');
$involvedUser = $userTable->find('all', [
'contain' => false,
'where' => ['id IN' => $involvedUserIds],
'fields' => ['id', 'first_name', 'last_name', 'email']
]);
//var_dump($involvedUser->toArray());
$involvedUserIndices = [];
foreach ($involvedUser as $involvedUser) {
$involvedUserIndices[$involvedUser->id] = $involvedUser;
}
// sender or receiver when user has sended money
// group name if creation
// type: gesendet / empfangen / geschöpft
// transaktion nr / id
// date
// balance
$transactions = [];
foreach ($creationTransactions as $creation) {
//var_dump($creation);
array_push($transactions, [
'name' => 'Gradido Akademie',
'type' => 'creation',
'transaction_id' => $creation->transaction_id,
'date' => $creation->transaction->received,
'balance' => $creation->amount,
'memo' => $creation->transaction->memo
]);
}
foreach ($transferTransactions as $sendCoins) {
$type = '';
$otherUser = null;
if ($sendCoins->state_user_id == $user['id']) {
$type = 'send';
if(isset($involvedUserIndices[$sendCoins->receiver_user_id])) {
$otherUser = $involvedUserIndices[$sendCoins->receiver_user_id];
}
} else if ($sendCoins->receiver_user_id == $user['id']) {
$type = 'receive';
if(isset($involvedUserIndices[$sendCoins->state_user_id])) {
$otherUser = $involvedUserIndices[$sendCoins->state_user_id];
}
}
if(null == $otherUser) {
$otherUser = $this->StateBalances->StateUsers->newEntity();
}
array_push($transactions, [
'name' => $otherUser->first_name . ' ' . $otherUser->last_name,
'email' => $otherUser->email,
'type' => $type,
'transaction_id' => $sendCoins->transaction_id,
'date' => $sendCoins->transaction->received,
'balance' => $sendCoins->amount,
'memo' => $sendCoins->transaction->memo
]);
}
uasort($transactions, array($this, 'sortTransactions'));
$this->set('transactions', $transactions);
$this->set('transactionExecutingCount', $session->read('Transaction.executing'));
$this->set('balance', $session->read('StateUser.balance'));
$this->set('timeUsed', microtime(true) - $startTime);
$this->set('gdtSum', $gdtSum);
}
public function ajaxGetBalance($session_id)
{
if(!isset($session_id) || !$session_id) {
return $this->returnJson(['state' => 'error', 'msg' => 'invalid session']);
}
$startTime = microtime(true);
$session = $this->getRequest()->getSession();
$result = $this->requestLogin($session_id);
if ($result !== true) {
return $this->returnJson(['state' => 'error', 'msg' => 'session not found']);
}
$user = $session->read('StateUser');
//var_dump($user);
return $this->returnJson(['state' => 'success', 'balance' => $user['balance']]);
}
public function ajaxListTransactions($session_id, $page, $count)
{
if(!isset($session_id) || !$session_id) {
return $this->returnJson(['state' => 'error', 'msg' => 'invalid session']);
}
$startTime = microtime(true);
$session = $this->getRequest()->getSession();
$result = $this->requestLogin($session_id);
if ($result !== true) {
return $this->returnJson(['state' => 'error', 'msg' => 'session not found']);
}
$user = $session->read('StateUser');
$gdtSum = 0;
$gdtEntries = $this->JsonRequestClient->sendRequestGDT(['email' => $user['email']], 'GdtEntries' . DS . 'sumPerEmailApi');
if('success' == $gdtEntries['state'] && 'success' == $gdtEntries['data']['state']) {
$gdtSum = intval($gdtEntries['data']['sum']);
} else {
if($user) {
$this->addAdminError('StateBalancesController', 'overview', $gdtEntries, $user['id']);
} else {
$this->addAdminError('StateBalancesController', 'overview', $gdtEntries, 0);
}
}
$creationsTable = TableRegistry::getTableLocator()->get('TransactionCreations');
$creationTransactions = $creationsTable
->find('all')
->where(['state_user_id' => $user['id']])
->contain(['Transactions']);
$transferTable = TableRegistry::getTableLocator()->get('TransactionSendCoins');
$transferTransactions = $transferTable
->find('all')
->where(['OR' => ['state_user_id' => $user['id'], 'receiver_user_id' => $user['id']]])
->contain(['Transactions']);
$involvedUserIds = [];
foreach ($transferTransactions as $sendCoins) {
//var_dump($sendCoins);
if ($sendCoins->state_user_id != $user['id']) {
array_push($involvedUserIds, intval($sendCoins->state_user_id));
} elseif ($sendCoins->receiver_user_id != $user['id']) {
array_push($involvedUserIds, intval($sendCoins->receiver_user_id));
}
}
/*echo "state user from sendCoins: $sendCoins->state_user_id<br>";
echo "receiver user from sendCoins: $sendCoins->receiver_user_id<br>";
echo "user id from logged in user: ".$user['id']. '<br>';
*/
//var_dump($involvedUserIds);
// exchange key with values and drop duplicates
$involvedUser_temp = array_flip($involvedUserIds);
// exchange back
$involvedUserIds = array_flip($involvedUser_temp);
$userTable = TableRegistry::getTableLocator()->get('StateUsers');
$involvedUser = $userTable->find('all', [
'contain' => false,
'where' => ['id IN' => $involvedUserIds],
'fields' => ['id', 'first_name', 'last_name', 'email']
]);
//var_dump($involvedUser->toArray());
$involvedUserIndices = [];
foreach ($involvedUser as $involvedUser) {
$involvedUserIndices[$involvedUser->id] = $involvedUser;
}
// sender or receiver when user has sended money
// group name if creation
// type: gesendet / empfangen / geschöpft
// transaktion nr / id
// date
// balance
$transactions = [];
foreach ($creationTransactions as $creation) {
//var_dump($creation);
array_push($transactions, [
'name' => 'Gradido Akademie',
'type' => 'creation',
'transaction_id' => $creation->transaction_id,
'date' => $creation->transaction->received,
'balance' => $creation->amount,
'memo' => $creation->transaction->memo
]);
}
foreach ($transferTransactions as $sendCoins) {
$type = '';
$otherUser = null;
if ($sendCoins->state_user_id == $user['id']) {
$type = 'send';
if(isset($involvedUserIndices[$sendCoins->receiver_user_id])) {
$otherUser = $involvedUserIndices[$sendCoins->receiver_user_id];
}
} else if ($sendCoins->receiver_user_id == $user['id']) {
$type = 'receive';
if(isset($involvedUserIndices[$sendCoins->state_user_id])) {
$otherUser = $involvedUserIndices[$sendCoins->state_user_id];
}
}
if(null == $otherUser) {
$otherUser = $this->StateBalances->StateUsers->newEntity();
}
array_push($transactions, [
'name' => $otherUser->first_name . ' ' . $otherUser->last_name,
'email' => $otherUser->email,
'type' => $type,
'transaction_id' => $sendCoins->transaction_id,
'date' => $sendCoins->transaction->received,
'balance' => $sendCoins->amount,
'memo' => $sendCoins->transaction->memo
]);
}
uasort($transactions, array($this, 'sortTransactions'));
return $this->returnJson([
'state' => 'success',
'transactions' => $transactions,
'transactionExecutingCount' => $session->read('Transaction.executing'),
'count' => count($transactions),
'gdtSum' => $gdtSum,
'timeUsed' => microtime(true) - $startTime
]);
}
public function overviewGdt()
{
$this->set(
'naviHierarchy',
(new NaviHierarchy())->
add(new NaviHierarchyEntry(__('Startseite'), 'Dashboard', 'index', false))->
add(new NaviHierarchyEntry(__('GDT Kontoübersicht'), 'StateBalances', 'overviewGdt', true))
);
$startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend');
$session = $this->getRequest()->getSession();
$result = $this->requestLogin();
if ($result !== true) {
return $result;
}
$user = $session->read('StateUser');
$requestResult = $this->JsonRequestClient->sendRequestGDT(['email' => $user['email']], 'GdtEntries' . DS . 'listPerEmailApi');
//var_dump($requestResult);
if('success' === $requestResult['state'] && 'success' === $requestResult['data']['state']) {
//var_dump(array_keys($requestResult['data']));
$ownEntries = $requestResult['data']['ownEntries'];
//$gdtEntries = $requestResult['data']['entries'];
$gdtSum = 0;
foreach ($ownEntries as $i => $gdtEntry) {
$gdtSum += $gdtEntry['gdt'];
//echo "index: $i<br>";
//var_dump($gdtEntry);
}
if (isset($requestResult['data']['connectEntrys'])) {
$connectEntries = $requestResult['data']['connectEntrys'];
foreach ($connectEntries as $entry) {
//if(!$count) var_dump($entry);
//$count++;
$gdtSum += $entry['connect']['gdt_entry']['gdt'];
}
$this->set('connectEntries', $connectEntries);
}
//echo "gdtSum: $gdtSum<br>";
$this->set('gdtSum', $gdtSum);
$this->set('ownEntries', $ownEntries);
$this->set('gdtSumPerEmail', $requestResult['data']['gdtSumPerEmail']);
$this->set('moreEntrysAsShown', $requestResult['data']['moreEntrysAsShown']);
$this->set('user', $user);
if (isset($requestResult['data']['publishers'])) {
$publishers = $requestResult['data']['publishers'];
$this->set('publishers', $publishers);
}
} else {
$this->addAdminError('StateBalancesController', 'overviewGdt', $requestResult, $user['id']);
$this->Flash->error(__('Fehler beim GDT Server, bitte abwarten oder den Admin benachrichtigen!'));
}
}
public function sortTransactions($a, $b)
{
if ($a['date'] == $b['date']) {
return 0;
}
return ($a['date'] > $b['date']) ? -1 : 1;
}
/**
* View method
*
* @param string|null $id State Balance id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$stateBalance = $this->StateBalances->get($id, [
'contain' => ['StateUsers']
]);
$this->set('stateBalance', $stateBalance);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$stateBalance = $this->StateBalances->newEntity();
if ($this->request->is('post')) {
$stateBalance = $this->StateBalances->patchEntity($stateBalance, $this->request->getData());
if ($this->StateBalances->save($stateBalance)) {
$this->Flash->success(__('The state balance has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state balance could not be saved. Please, try again.'));
}
$stateUsers = $this->StateBalances->StateUsers->find('list', ['limit' => 200]);
$this->set(compact('stateBalance', 'stateUsers'));
}
/**
* Edit method
*
* @param string|null $id State Balance id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$stateBalance = $this->StateBalances->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$stateBalance = $this->StateBalances->patchEntity($stateBalance, $this->request->getData());
if ($this->StateBalances->save($stateBalance)) {
$this->Flash->success(__('The state balance has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state balance could not be saved. Please, try again.'));
}
$stateUsers = $this->StateBalances->StateUsers->find('list', ['limit' => 200]);
$this->set(compact('stateBalance', 'stateUsers'));
}
/**
* Delete method
*
* @param string|null $id State Balance id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$stateBalance = $this->StateBalances->get($id);
if ($this->StateBalances->delete($stateBalance)) {
$this->Flash->success(__('The state balance has been deleted.'));
} else {
$this->Flash->error(__('The state balance could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,113 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* StateCreated Controller
*
* @property \App\Model\Table\StateCreatedTable $StateCreated
*
* @method \App\Model\Entity\StateCreated[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class StateCreatedController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => ['Transactions', 'StateUsers']
];
$stateCreated = $this->paginate($this->StateCreated);
$this->set(compact('stateCreated'));
}
/**
* View method
*
* @param string|null $id State Created id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$stateCreated = $this->StateCreated->get($id, [
'contain' => ['Transactions', 'StateUsers']
]);
$this->set('stateCreated', $stateCreated);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$stateCreated = $this->StateCreated->newEntity();
if ($this->request->is('post')) {
$stateCreated = $this->StateCreated->patchEntity($stateCreated, $this->request->getData());
if ($this->StateCreated->save($stateCreated)) {
$this->Flash->success(__('The state created has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state created could not be saved. Please, try again.'));
}
$transactions = $this->StateCreated->Transactions->find('list', ['limit' => 200]);
$stateUsers = $this->StateCreated->StateUsers->find('list', ['limit' => 200]);
$this->set(compact('stateCreated', 'transactions', 'stateUsers'));
}
/**
* Edit method
*
* @param string|null $id State Created id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$stateCreated = $this->StateCreated->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$stateCreated = $this->StateCreated->patchEntity($stateCreated, $this->request->getData());
if ($this->StateCreated->save($stateCreated)) {
$this->Flash->success(__('The state created has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state created could not be saved. Please, try again.'));
}
$transactions = $this->StateCreated->Transactions->find('list', ['limit' => 200]);
$stateUsers = $this->StateCreated->StateUsers->find('list', ['limit' => 200]);
$this->set(compact('stateCreated', 'transactions', 'stateUsers'));
}
/**
* Delete method
*
* @param string|null $id State Created id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$stateCreated = $this->StateCreated->get($id);
if ($this->StateCreated->delete($stateCreated)) {
$this->Flash->success(__('The state created has been deleted.'));
} else {
$this->Flash->error(__('The state created could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,173 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
use Model\Navigation\NaviHierarchy;
use Model\Navigation\NaviHierarchyEntry;
/**
* StateErrors Controller
*
* @property \App\Model\Table\StateErrorsTable $StateErrors
*
* @method \App\Model\Entity\StateError[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class StateErrorsController extends AppController
{
public function initialize()
{
parent::initialize();
$this->Auth->allow(['showForUser', 'deleteForUser']);
$this->set(
'naviHierarchy',
(new NaviHierarchy())->
add(new NaviHierarchyEntry(__('Startseite'), 'Dashboard', 'index', false))->
add(new NaviHierarchyEntry(__('Fehler'), 'StateErrors', 'ShowForUser', true))
);
}
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => ['StateUsers', 'TransactionTypes']
];
$stateErrors = $this->paginate($this->StateErrors);
$this->set(compact('stateErrors'));
}
public function showForUser()
{
$startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend');
$session = $this->getRequest()->getSession();
$user = $session->read('StateUser');
if(!$user) {
$result = $this->requestLogin();
if($result !== true) {
return $result;
}
$user = $session->read('StateUser');
}
$errors = $this->StateErrors->find('all')->where(['state_user_id' => $user['id']])->contain(false);
$transactionTypes = $this->StateErrors->TransactionTypes->find('all')->select(['id', 'name', 'text'])->order(['id']);
$this->set('errors', $errors);
$this->set('transactionTypes', $transactionTypes->toList());
$this->set('timeUsed', microtime(true) - $startTime);
}
public function deleteForUser($id = null)
{
$this->request->allowMethod(['post', 'delete', 'get']);
$stateError = $this->StateErrors->get($id);
$session = $this->getRequest()->getSession();
$user = $session->read('StateUser');
if($user['id'] != $stateError->state_user_id) {
$this->Flash->error(__('Error belongs to another User, cannot delete'));
}
else if ($this->StateErrors->delete($stateError)) {
$this->Flash->success(__('The state error has been deleted.'));
} else {
$this->Flash->error(__('The state error could not be deleted. Please, try again.'));
}
$errors = $this->StateErrors->find('all')->where(['state_user_id' => $user['id']])->contain(false);
if($errors->count() == 0) {
return $this->redirect(['controller' => 'Dashboard']);
}
return $this->redirect(['action' => 'showForUser']);
}
/**
* View method
*
* @param string|null $id State Error id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$stateError = $this->StateErrors->get($id, [
'contain' => ['StateUsers', 'TransactionTypes']
]);
$this->set('stateError', $stateError);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$stateError = $this->StateErrors->newEntity();
if ($this->request->is('post')) {
$stateError = $this->StateErrors->patchEntity($stateError, $this->request->getData());
if ($this->StateErrors->save($stateError)) {
$this->Flash->success(__('The state error has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state error could not be saved. Please, try again.'));
}
$stateUsers = $this->StateErrors->StateUsers->find('list', ['limit' => 200]);
$transactionTypes = $this->StateErrors->TransactionTypes->find('list', ['limit' => 200]);
$this->set(compact('stateError', 'stateUsers', 'transactionTypes'));
}
/**
* Edit method
*
* @param string|null $id State Error id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$stateError = $this->StateErrors->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$stateError = $this->StateErrors->patchEntity($stateError, $this->request->getData());
if ($this->StateErrors->save($stateError)) {
$this->Flash->success(__('The state error has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state error could not be saved. Please, try again.'));
}
$stateUsers = $this->StateErrors->StateUsers->find('list', ['limit' => 200]);
$transactionTypes = $this->StateErrors->TransactionTypes->find('list', ['limit' => 200]);
$this->set(compact('stateError', 'stateUsers', 'transactionTypes'));
}
/**
* Delete method
*
* @param string|null $id State Error id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$stateError = $this->StateErrors->get($id);
if ($this->StateErrors->delete($stateError)) {
$this->Flash->success(__('The state error has been deleted.'));
} else {
$this->Flash->error(__('The state error could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,113 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* StateGroupAddresses Controller
*
* @property \App\Model\Table\StateGroupAddressesTable $StateGroupAddresses
*
* @method \App\Model\Entity\StateGroupAddress[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class StateGroupAddressesController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => ['StateGroups', 'AddressTypes']
];
$stateGroupAddresses = $this->paginate($this->StateGroupAddresses);
$this->set(compact('stateGroupAddresses'));
}
/**
* View method
*
* @param string|null $id State Group Address id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$stateGroupAddress = $this->StateGroupAddresses->get($id, [
'contain' => ['StateGroups', 'AddressTypes']
]);
$this->set('stateGroupAddress', $stateGroupAddress);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$stateGroupAddress = $this->StateGroupAddresses->newEntity();
if ($this->request->is('post')) {
$stateGroupAddress = $this->StateGroupAddresses->patchEntity($stateGroupAddress, $this->request->getData());
if ($this->StateGroupAddresses->save($stateGroupAddress)) {
$this->Flash->success(__('The state group address has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state group address could not be saved. Please, try again.'));
}
$stateGroups = $this->StateGroupAddresses->StateGroups->find('list', ['limit' => 200]);
$addressTypes = $this->StateGroupAddresses->AddressTypes->find('list', ['limit' => 200]);
$this->set(compact('stateGroupAddress', 'stateGroups', 'addressTypes'));
}
/**
* Edit method
*
* @param string|null $id State Group Address id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$stateGroupAddress = $this->StateGroupAddresses->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$stateGroupAddress = $this->StateGroupAddresses->patchEntity($stateGroupAddress, $this->request->getData());
if ($this->StateGroupAddresses->save($stateGroupAddress)) {
$this->Flash->success(__('The state group address has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state group address could not be saved. Please, try again.'));
}
$stateGroups = $this->StateGroupAddresses->StateGroups->find('list', ['limit' => 200]);
$addressTypes = $this->StateGroupAddresses->AddressTypes->find('list', ['limit' => 200]);
$this->set(compact('stateGroupAddress', 'stateGroups', 'addressTypes'));
}
/**
* Delete method
*
* @param string|null $id State Group Address id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$stateGroupAddress = $this->StateGroupAddresses->get($id);
if ($this->StateGroupAddresses->delete($stateGroupAddress)) {
$this->Flash->success(__('The state group address has been deleted.'));
} else {
$this->Flash->error(__('The state group address could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,115 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* StateGroupRelationships Controller
*
* @property \App\Model\Table\StateGroupRelationshipsTable $StateGroupRelationships
*
* @method \App\Model\Entity\StateGroupRelationship[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class StateGroupRelationshipsController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => ['StateGroup1s', 'StateGroup2s', 'StateRelationships']
];
$stateGroupRelationships = $this->paginate($this->StateGroupRelationships);
$this->set(compact('stateGroupRelationships'));
}
/**
* View method
*
* @param string|null $id State Group Relationship id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$stateGroupRelationship = $this->StateGroupRelationships->get($id, [
'contain' => ['StateGroup1s', 'StateGroup2s', 'StateRelationships']
]);
$this->set('stateGroupRelationship', $stateGroupRelationship);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$stateGroupRelationship = $this->StateGroupRelationships->newEntity();
if ($this->request->is('post')) {
$stateGroupRelationship = $this->StateGroupRelationships->patchEntity($stateGroupRelationship, $this->request->getData());
if ($this->StateGroupRelationships->save($stateGroupRelationship)) {
$this->Flash->success(__('The state group relationship has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state group relationship could not be saved. Please, try again.'));
}
$stateGroup1s = $this->StateGroupRelationships->StateGroup1s->find('list', ['limit' => 200]);
$stateGroup2s = $this->StateGroupRelationships->StateGroup2s->find('list', ['limit' => 200]);
$stateRelationships = $this->StateGroupRelationships->StateRelationships->find('list', ['limit' => 200]);
$this->set(compact('stateGroupRelationship', 'stateGroup1s', 'stateGroup2s', 'stateRelationships'));
}
/**
* Edit method
*
* @param string|null $id State Group Relationship id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$stateGroupRelationship = $this->StateGroupRelationships->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$stateGroupRelationship = $this->StateGroupRelationships->patchEntity($stateGroupRelationship, $this->request->getData());
if ($this->StateGroupRelationships->save($stateGroupRelationship)) {
$this->Flash->success(__('The state group relationship has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state group relationship could not be saved. Please, try again.'));
}
$stateGroup1s = $this->StateGroupRelationships->StateGroup1s->find('list', ['limit' => 200]);
$stateGroup2s = $this->StateGroupRelationships->StateGroup2s->find('list', ['limit' => 200]);
$stateRelationships = $this->StateGroupRelationships->StateRelationships->find('list', ['limit' => 200]);
$this->set(compact('stateGroupRelationship', 'stateGroup1s', 'stateGroup2s', 'stateRelationships'));
}
/**
* Delete method
*
* @param string|null $id State Group Relationship id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$stateGroupRelationship = $this->StateGroupRelationships->get($id);
if ($this->StateGroupRelationships->delete($stateGroupRelationship)) {
$this->Flash->success(__('The state group relationship has been deleted.'));
} else {
$this->Flash->error(__('The state group relationship could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,111 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* StateGroups Controller
*
* @property \App\Model\Table\StateGroupsTable $StateGroups
*
* @method \App\Model\Entity\StateGroup[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class StateGroupsController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => ['Indices']
];
$stateGroups = $this->paginate($this->StateGroups);
$this->set(compact('stateGroups'));
}
/**
* View method
*
* @param string|null $id State Group id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$stateGroup = $this->StateGroups->get($id, [
'contain' => ['Indices', 'StateGroupAddresses', 'StateUsers', 'TransactionGroupCreates', 'Transactions']
]);
$this->set('stateGroup', $stateGroup);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$stateGroup = $this->StateGroups->newEntity();
if ($this->request->is('post')) {
$stateGroup = $this->StateGroups->patchEntity($stateGroup, $this->request->getData());
if ($this->StateGroups->save($stateGroup)) {
$this->Flash->success(__('The state group has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state group could not be saved. Please, try again.'));
}
$indices = $this->StateGroups->Indices->find('list', ['limit' => 200]);
$this->set(compact('stateGroup', 'indices'));
}
/**
* Edit method
*
* @param string|null $id State Group id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$stateGroup = $this->StateGroups->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$stateGroup = $this->StateGroups->patchEntity($stateGroup, $this->request->getData());
if ($this->StateGroups->save($stateGroup)) {
$this->Flash->success(__('The state group has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state group could not be saved. Please, try again.'));
}
$indices = $this->StateGroups->Indices->find('list', ['limit' => 200]);
$this->set(compact('stateGroup', 'indices'));
}
/**
* Delete method
*
* @param string|null $id State Group id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$stateGroup = $this->StateGroups->get($id);
if ($this->StateGroups->delete($stateGroup)) {
$this->Flash->success(__('The state group has been deleted.'));
} else {
$this->Flash->error(__('The state group could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,106 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* StateRelationshipTypes Controller
*
* @property \App\Model\Table\StateRelationshipTypesTable $StateRelationshipTypes
*
* @method \App\Model\Entity\StateRelationshipType[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class StateRelationshipTypesController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$stateRelationshipTypes = $this->paginate($this->StateRelationshipTypes);
$this->set(compact('stateRelationshipTypes'));
}
/**
* View method
*
* @param string|null $id State Relationship Type id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$stateRelationshipType = $this->StateRelationshipTypes->get($id, [
'contain' => []
]);
$this->set('stateRelationshipType', $stateRelationshipType);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$stateRelationshipType = $this->StateRelationshipTypes->newEntity();
if ($this->request->is('post')) {
$stateRelationshipType = $this->StateRelationshipTypes->patchEntity($stateRelationshipType, $this->request->getData());
if ($this->StateRelationshipTypes->save($stateRelationshipType)) {
$this->Flash->success(__('The state relationship type has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state relationship type could not be saved. Please, try again.'));
}
$this->set(compact('stateRelationshipType'));
}
/**
* Edit method
*
* @param string|null $id State Relationship Type id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$stateRelationshipType = $this->StateRelationshipTypes->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$stateRelationshipType = $this->StateRelationshipTypes->patchEntity($stateRelationshipType, $this->request->getData());
if ($this->StateRelationshipTypes->save($stateRelationshipType)) {
$this->Flash->success(__('The state relationship type has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state relationship type could not be saved. Please, try again.'));
}
$this->set(compact('stateRelationshipType'));
}
/**
* Delete method
*
* @param string|null $id State Relationship Type id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$stateRelationshipType = $this->StateRelationshipTypes->get($id);
if ($this->StateRelationshipTypes->delete($stateRelationshipType)) {
$this->Flash->success(__('The state relationship type has been deleted.'));
} else {
$this->Flash->error(__('The state relationship type could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,568 @@
<?php
namespace App\Controller;
use Cake\Routing\Router;
use Cake\I18n\I18n;
use Cake\I18n\FrozenTime;
use Cake\ORM\TableRegistry;
use Cake\Http\Client;
use Cake\Core\Configure;
use App\Controller\AppController;
use App\Form\UserSearchForm;
use App\Model\Validation\GenericValidation;
use Model\Navigation\NaviHierarchy;
use Model\Navigation\NaviHierarchyEntry;
use Model\Transactions\TransactionCreation;
// for translating
__('account created');
__('account not on login-server');
__('email activated');
__('account copied to community');
__('email not activated');
__('account multiple times on login-server');
__('account not on community server');
__('no keys');
/**
* StateUsers Controller
*
* @property \App\Model\Table\StateUsersTable $StateUsers
*
* @method \App\Model\Entity\StateUser[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class StateUsersController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('GradidoNumber');
$this->loadComponent('JsonRequestClient');
$this->Auth->allow([
'search', 'ajaxCopyLoginToCommunity', 'ajaxCopyCommunityToLogin',
'ajaxDelete', 'ajaxCountTransactions', 'ajaxVerificationEmailResend',
'ajaxGetUserEmailVerificationCode', 'ajaxGetCSFRToken'
]);
$this->set(
'naviHierarchy',
(new NaviHierarchy())->
add(new NaviHierarchyEntry(__('Startseite'), 'Dashboard', 'index', false))->add(new NaviHierarchyEntry(__('Benutzer suchen'), 'StateUsers', 'search', true))
);
}
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => []
];
$stateUsers = $this->paginate($this->StateUsers);
$this->set(compact('stateUsers'));
}
public function listIdentHashes()
{
$stateUsers = $this->StateUsers->find('all')->toArray();
foreach ($stateUsers as $i => $user) {
$stateUsers[$i]->identHash = TransactionCreation::DRMakeStringHash($user->email);
}
$this->set('stateUsers', $stateUsers);
}
public function search()
{
$startTime = microtime(true);
I18n::setLocale('de_DE');
$this->viewBuilder()->setLayout('frontend');
$session = $this->getRequest()->getSession();
$result = $this->requestLogin();
if ($result !== true) {
return $result;
}
$user = $session->read('StateUser');
if ($user['role'] != 'admin') {
return $this->redirect(['controller' => 'dashboard', 'action' => 'index']);
}
$searchForm = new UserSearchForm();
$timeUsed = microtime(true) - $startTime;
//$this->set('timeUsed', $timeUsed);
$csfr_token = $this->request->getParam('_csrfToken');
$this->set(compact('timeUsed', 'searchForm', 'csfr_token'));
if ($this->request->is('post')) {
$requestData = $this->request->getData();
if ($searchForm->validate($requestData)) {
//var_dump($requestData);
$searchString = $requestData['search'];
$searchType = 'unknown';
if (GenericValidation::email($searchString, [])) {
$searchType = 'email';
}
// find users on login server
$resultJson = $this->JsonRequestClient->getUsers($session->read('session_id'), $searchString);
$loginServerUser = [];
if ($resultJson['state'] == 'success') {
$dataJson = $resultJson['data'];
if ($dataJson['state'] != 'success') {
if ($dataJson['msg'] == 'session not found') {
$session->destroy();
return $this->redirect(Router::url('/', true) . 'account', 303);
}
}
//var_dump($dataJson);
if (isset($dataJson['users'])) {
$loginServerUser = $dataJson['users'];
}
}
$pubkeySorted = [];
$emptyPubkeys = [];
foreach ($loginServerUser as $u) {
if (!isset($u['public_hex']) || $u['public_hex'] == '') {
array_push($emptyPubkeys, $u);
} else {
if (!isset($pubkeySorted[$u['public_hex']])) {
$pubkeySorted[$u['public_hex']] = ['login' => [], 'community' => []];
}
array_push($pubkeySorted[$u['public_hex']]['login'], $u);
}
}
// find user on community server db
$globalSearch = '%' . $searchString . '%';
$communityUsers = $this->StateUsers
->find('all')
->contain(['StateBalances' => ['fields' => ['amount', 'state_user_id']]]);
$communityUsers->where(['OR' => [
'first_name LIKE' => $globalSearch,
'last_name LIKE' => $globalSearch,
//'username LIKE' => $globalSearch,
'email LIKE' => $globalSearch
]]);
//var_dump($communityUsers->toArray());
foreach ($communityUsers as $u) {
$pubkey_hex = bin2hex(stream_get_contents($u->public_key));
$u->public_hex = $pubkey_hex;
if (!isset($pubkeySorted[$pubkey_hex])) {
$pubkeySorted[$pubkey_hex] = ['login' => [], 'community' => []];
}
array_push($pubkeySorted[$pubkey_hex]['community'], $u);
}
$finalUserEntrys = [];
// detect states
foreach ($pubkeySorted as $pubhex => $user) {
$finalUser = [];
$state = 'account created';
$color = 'secondary';
$finalUser['balance'] = 0;
$finalUser['pubkeyhex'] = $pubhex;
$finalUser['created'] = null;
if (count($user['community']) == 1) {
if (isset($user['community'][0]->state_balances) &&
isset($user['community'][0]->state_balances[0]['amount'])) {
$finalUser['balance'] = $user['community'][0]->state_balances[0]->amount;
}
}
if (count($user['login']) == 0) {
$state = 'account not on login-server';
$color = 'danger';
if (count($user['community']) == 1) {
$c_user = $user['community'][0];
$finalUser['name'] = $c_user->first_name . ' ' . $c_user->last_name;
$finalUser['first_name'] = $c_user->first_name;
$finalUser['last_name'] = $c_user->last_name;
//$finalUser['username'] = $c_user->username;
$finalUser['email'] = $c_user->email;
}
} elseif (count($user['login']) == 1) {
if ($user['login'][0]['email_checked'] == true) {
$state = 'email activated';
$color = 'primary';
if (count($user['community']) == 1) {
$state = 'account copied to community';
$color = 'success';
//var_dump($user['community'][0]->state_balances[0]['amount']);
}
} else {
$state = 'email not activated';
$color = 'warning';
}
$l_user = $user['login'][0];
$finalUser['name'] = $l_user['first_name'] . ' ' . $l_user['last_name'];
$finalUser['first_name'] = $l_user['first_name'];
$finalUser['last_name'] = $l_user['last_name'];
//$finalUser['username'] = $l_user['username'];
$finalUser['email'] = $l_user['email'];
$finalUser['created'] = new FrozenTime($l_user['created']);
} else {
$state = 'account multiple times on login-server';
$color = 'danger';
}
$finalUser['indicator'] = ['name' => $state, 'color' => $color];
array_push($finalUserEntrys, $finalUser);
}
foreach ($emptyPubkeys as $user) {
$finalUser = [];
$state = 'account not on community server';
$color = 'secondary';
if ($user['email_checked'] == false) {
$state = 'email not activated';
$color = 'warning';
} else {
$state = 'no keys';
$color = 'warning';
}
$finalUser['balance'] = 0;
$finalUser['pubkeyhex'] = '';
$finalUser['name'] = $user['first_name'] . ' ' . $user['last_name'];
$finalUser['first_name'] = $user['first_name'];
$finalUser['last_name'] = $user['last_name'];
//$finalUser['username'] = $user['username'];
$finalUser['email'] = $user['email'];
$finalUser['created'] = new FrozenTime($user['created']);
$finalUser['indicator'] = ['name' => $state, 'color' => $color];
array_push($finalUserEntrys, $finalUser);
}
//var_dump($pubkeySorted);
} else {
$this->Flash->error(__('Something was invalid, please try again!'));
}
$this->set('finalUserEntrys', $finalUserEntrys);
}
$timeUsed = microtime(true) - $startTime;
$this->set('timeUsed', $timeUsed);
}
public function ajaxCopyCommunityToLogin()
{
$session = $this->getRequest()->getSession();
$result = $this->requestLogin();
if ($result !== true) {
return $this->returnJson(['state' => 'error', 'msg' => 'invalid session']);
}
$user = $session->read('StateUser');
if ($user['role'] != 'admin') {
return $this->returnJson(['state' => 'error', 'msg' => 'not an admin']);
}
if ($this->request->is('post')) {
$jsonData = $this->request->input('json_decode', true);
}
return $this->returnJson(['state' => 'error', 'msg' => 'no post request']);
}
public function ajaxCopyLoginToCommunity()
{
$session = $this->getRequest()->getSession();
$result = $this->requestLogin();
if ($result !== true) {
return $this->returnJson(['state' => 'error', 'msg' => 'invalid session']);
}
$user = $session->read('StateUser');
if ($user['role'] != 'admin') {
return $this->returnJson(['state' => 'error', 'msg' => 'not an admin']);
}
if ($this->request->is('post')) {
$jsonData = $this->request->input('json_decode', true);
//$user = $jsonData['user'];
//var_dump($jsonData);
$newStateUser = $this->StateUsers->newEntity();
$this->StateUsers->patchEntity($newStateUser, $jsonData);
$newStateUser->public_key = hex2bin($jsonData['pubkeyhex']);
if (!$this->StateUsers->save($newStateUser)) {
return $this->returnJson(['state' => 'error', 'msg' => 'error by saving', 'details' => json_encode($newStateUser->errors())]);
}
return $this->returnJson(['state' => 'success']);
}
return $this->returnJson(['state' => 'error', 'msg' => 'no post request']);
}
public function ajaxVerificationEmailResend()
{
$session = $this->getRequest()->getSession();
$result = $this->requestLogin();
if ($result !== true) {
return $this->returnJson(['state' => 'error', 'msg' => 'invalid session']);
}
$user = $session->read('StateUser');
if ($user['role'] != 'admin') {
return $this->returnJson(['state' => 'error', 'msg' => 'not an admin']);
}
if ($this->request->is('post')) {
$jsonData = $this->request->input('json_decode', true);
$email = $jsonData['email'];
$session_id = $session->read('session_id');
return $this->returnJson($this->JsonRequestClient->sendRequest(json_encode([
'session_id' => $session_id,
'email' => $email
]), '/adminEmailVerificationResend'));
/*return $this->sendRequest(json_encode([
'session_id' => $session_id,
'search' => $searchString
]), '/getUsers');*/
}
return $this->returnJson(['state' => 'error', 'msg' => 'no post request']);
}
public function ajaxGetUserEmailVerificationCode()
{
$session = $this->getRequest()->getSession();
$result = $this->requestLogin();
if ($result !== true) {
return $this->returnJson(['state' => 'error', 'msg' => 'invalid session']);
}
$user = $session->read('StateUser');
if ($user['role'] != 'admin') {
return $this->returnJson(['state' => 'error', 'msg' => 'not an admin']);
}
if ($this->request->is('post')) {
$jsonData = $this->request->input('json_decode', true);
$email = $jsonData['email'];
$session_id = $session->read('session_id');
return $this->returnJson($this->JsonRequestClient->sendRequest(json_encode([
'session_id' => $session_id,
'email' => $email,
'ask' => ['EmailVerificationCode.Register', 'loginServer.path']
]), '/getUserInfos'));
}
return $this->returnJson(['state' => 'error', 'msg' => 'no post request']);
}
public function ajaxDelete()
{
$session = $this->getRequest()->getSession();
$result = $this->requestLogin();
if ($result !== true) {
return $this->returnJson(['state' => 'error', 'msg' => 'invalid session']);
}
$user = $session->read('StateUser');
if ($user['role'] != 'admin') {
return $this->returnJson(['state' => 'error', 'msg' => 'not an admin']);
}
if ($this->request->is('post')) {
$jsonData = $this->request->input('json_decode', true);
//$user = $jsonData['user'];
//var_dump($jsonData);
$pubkey = hex2bin($jsonData['pubkeyhex']);
$stateUsers = $this->StateUsers->find('all')->where(['public_key' => $pubkey]);
if ($stateUsers->count() != 1) {
return $this->returnJson(['state' => 'error', 'msg' => 'invalid result count']);
}
if ($this->StateUsers->delete($stateUsers->first())) {
return $this->returnJson(['state' => 'success']);
} else {
return $this->returnJson(['state' => 'error', 'msg' => 'error by deleting', 'details' => json_encode($stateUser->errors())]);
}
}
return $this->returnJson(['state' => 'error', 'msg' => 'no post request']);
}
public function ajaxCountTransactions()
{
$session = $this->getRequest()->getSession();
$result = $this->requestLogin();
if ($result !== true) {
return $this->returnJson(['state' => 'error', 'msg' => 'invalid session']);
}
$user = $session->read('StateUser');
if ($user['role'] != 'admin') {
return $this->returnJson(['state' => 'error', 'msg' => 'not an admin']);
}
if ($this->request->is('post')) {
$jsonData = $this->request->input('json_decode', true);
//$user = $jsonData['user'];
//var_dump($jsonData);
$pubkey = hex2bin($jsonData['pubkeyhex']);
$stateUsers = $this->StateUsers
->find('all')
->where(['public_key' => $pubkey])
->select(['id']);
if ($stateUsers->count() != 1) {
return $this->returnJson(['state' => 'error', 'msg' => 'invalid result count']);
}
$stateUser = $stateUsers->first();
//var_dump($stateUser);
//var_dump($stateUser->toArray());
$creationsTable = TableRegistry::getTableLocator()->get('TransactionCreations');
$creationTransactions = $creationsTable
->find('all')
->select(['id'])
->where(['state_user_id' => $stateUser->id]);
$transferTable = TableRegistry::getTableLocator()->get('TransactionSendCoins');
$transferTransactions = $transferTable
->find('all')
->where(['OR' => ['state_user_id' => $stateUser->id, 'receiver_user_id' => $stateUser->id]])
->select(['state_user_id', 'receiver_user_id']);
$counts = ['creation' => $creationTransactions->count(), 'receive' => 0, 'sended' => 0];
foreach ($transferTransactions as $transfer) {
//var_dump($transfer);
if ($transfer->state_user_id == $stateUser->id) {
$counts['sended']++;
}
if ($transfer->receiver_user_id == $stateUser->id) {
$counts['receive']++;
}
}
return $this->returnJson(['state' => 'success', 'counts' => $counts]);
}
return $this->returnJson(['state' => 'error', 'msg' => 'no post request']);
}
public function ajaxGetCSFRToken($session_id)
{
if(!isset($session_id) || $session_id == 0) {
$this->returnJson(['state' => 'error', 'msg' => 'no session id']);
}
$client_ip = $this->request->clientIp();
$loginServer = Configure::read('LoginServer');
$url = $loginServer['host'] . ':' . $loginServer['port'];
$http = new Client();
$response = $http->get($url . '/login', ['session_id' => $session_id]);
$json = $response->getJson();
if (isset($json) && count($json) > 0) {
if ($json['state'] === 'success') {
if($json['clientIP'] == $client_ip) {
return $this->returnJson(['state' => 'success', 'csfr' => $this->request->getParam('_csrfToken')]);
} else {
return $this->returnJson([
'state' => 'error',
'msg' => 'client ip mismatch',
'details' => ['login_server' => $json['clientIP'], 'caller' => $client_ip]]);
}
} else {
return $this->returnJson($json);
}
} else {
return $this->returnJson(['state' => 'error', 'invalid response form logins server']);
}
}
/*
getField(vnode, 'receive'),
getField(vnode, 'sended'),
getField(vnode, 'creation'),
*/
/**
* View method
*
* @param string|null $id State User id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$stateUser = $this->StateUsers->get($id, [
'contain' => [
'StateBalances',
'TransactionCreations' => ['Transactions'],
'TransactionSendCoins' => ['Transactions', 'ReceiverUsers'],
'TransactionReceivedCoins' => ['Transactions', 'StateUsers']]
]);
$this->set('stateUser', $stateUser);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$stateUser = $this->StateUsers->newEntity();
if ($this->request->is('post')) {
$stateUser = $this->StateUsers->patchEntity($stateUser, $this->request->getData());
if ($this->StateUsers->save($stateUser)) {
$this->Flash->success(__('The state user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state user could not be saved. Please, try again.'));
}
$indices = $this->StateUsers->Indices->find('list', ['limit' => 200]);
$stateGroups = $this->StateUsers->StateGroups->find('list', ['limit' => 200]);
$this->set(compact('stateUser', 'indices', 'stateGroups'));
}
/**
* Edit method
*
* @param string|null $id State User id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$stateUser = $this->StateUsers->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$stateUser = $this->StateUsers->patchEntity($stateUser, $this->request->getData());
if ($this->StateUsers->save($stateUser)) {
$this->Flash->success(__('The state user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The state user could not be saved. Please, try again.'));
}
$stateGroups = $this->StateUsers->StateGroups->find('list', ['limit' => 200]);
$this->set(compact('stateUser', 'stateGroups'));
}
/**
* Delete method
*
* @param string|null $id State User id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$stateUser = $this->StateUsers->get($id);
if ($this->StateUsers->delete($stateUser)) {
$this->Flash->success(__('The state user has been deleted.'));
} else {
$this->Flash->error(__('The state user could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,518 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Routing\Router;
//use Cake\I18n\Number;
use Cake\Http\Client;
use Cake\Core\Configure;
use Cake\I18n\FrozenDate;
use Cake\Datasource\ConnectionManager;
use Model\Navigation\NaviHierarchy;
use Model\Navigation\NaviHierarchyEntry;
use App\Form\CreationForm;
// protobuf transactions
//use Model\Messages\Gradido\TransactionCreation;
use Model\Transactions\TransactionCreation;
/**
* TransactionCreations Controller
*
* @property \App\Model\Table\TransactionCreationsTable $TransactionCreations
*
* @method \App\Model\Entity\TransactionCreation[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class TransactionCreationsController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('GradidoNumber');
$this->loadComponent('JsonRequestClient');
//$this->Auth->allow(['add', 'edit']);
//$this->Auth->allow('create');
$this->set(
'naviHierarchy',
(new NaviHierarchy())->
add(new NaviHierarchyEntry(__('Startseite'), 'Dashboard', 'index', false))->add(new NaviHierarchyEntry(__('Gradido schöpfen'), 'TransactionCreations', 'create-multi', true))
);
}
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => ['Transactions', 'StateUsers']
];
$transactionCreations = $this->paginate($this->TransactionCreations);
$identHashes = [];
foreach ($transactionCreations as $creation) {
$identHash = TransactionCreation::DRMakeStringHash($creation->state_user->email);
$identHashes[$creation->state_user->id] = $identHash;
}
$this->set(compact('transactionCreations', 'identHashes'));
}
/**
* View method
*
* @param string|null $id Transaction Creation id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$transactionCreation = $this->TransactionCreations->get($id, [
'contain' => ['Transactions', 'StateUsers']
]);
$this->set('transactionCreation', $transactionCreation);
}
public function create()
{
$startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend');
$session = $this->getRequest()->getSession();
$user = $session->read('StateUser');
if (!$user) {
$result = $this->requestLogin();
if ($result !== true) {
return $result;
}
$user = $session->read('StateUser');
}
$creationForm = new CreationForm();
$transactionCreation = $this->TransactionCreations->newEntity();
$transactionCreation->state_user_id = $user['id'];
// adding possible addresses + input field for copy
$stateUserTable = TableRegistry::getTableLocator()->get('StateUsers');
$stateUsers = $stateUserTable->find('all')->contain(false);
$receiverProposal = [];
foreach ($stateUsers as $stateUser) {
$name = $stateUser->email;
$keyHex = bin2hex(stream_get_contents($stateUser->public_key));
if ($name === null) {
$name = $stateUser->first_name . ' ' . $stateUser->last_name;
}
array_push($receiverProposal, ['name' => $name, 'key' => $keyHex, 'email' => $stateUser->email]);
//$stateUser->public_key
}
$timeUsed = microtime(true) - $startTime;
$this->set(compact('transactionCreation', 'timeUsed', 'receiverProposal', 'creationForm'));
if ($this->request->is('post')) {
$requestData = $this->request->getData();
$mode = 'next';
if (isset($requestData['add'])) {
$mode = 'add';
}
if ($creationForm->validate($requestData)) {
$pubKeyHex = '';
$identHash = '';
$amountCent = $this->GradidoNumber->parseInputNumberToCentNumber($requestData['amount']);
$receiverIndex = intval($requestData['receiver'])-1;
if (count($receiverProposal) > $receiverIndex) {
$pubKeyHex = $receiverProposal[$receiverIndex]['key'];
$identHash = TransactionCreation::DRMakeStringHash($receiverProposal[$receiverIndex]['email']);
}
$builderResult = TransactionCreation::build(
$amountCent,
$requestData['memo'],
$pubKeyHex,
$identHash
);
if ($builderResult['state'] == 'success') {
$user_balance = 0;
if (isset($user['balance'])) {
$user_balance = $user['balance'];
}
// $session_id, $base64Message, $user_balance = 0
$requestResult = $this->JsonRequestClient->sendTransaction(
$session->read('session_id'),
base64_encode($builderResult['transactionBody']->serializeToString()),
$user_balance
);
if ($requestResult['state'] != 'success') {
$this->addAdminError('TransactionCreations', 'create', $requestResult, $user['id']);
if ($requestResult['type'] == 'request error') {
$this->Flash->error(__('Error by requesting LoginServer, please try again'));
} else {
$this->Flash->error(__('Error, please wait for the admin to fix it'));
}
} else {
$json = $requestResult['data'];
if ($json['state'] != 'success') {
if ($json['msg'] == 'session not found') {
$session->destroy();
return $this->redirect($this->loginServerUrl . 'account', 303);
} else {
$this->addAdminError('TransactionCreations', 'create', $json, $user['id']);
$this->Flash->error(__('Login Server Error, please wait for the admin to fix it'));
}
} else {
$pendingTransactionCount = $session->read('Transactions.pending');
if ($pendingTransactionCount == null) {
$pendingTransactionCount = 1;
} else {
$pendingTransactionCount++;
}
$session->write('Transactions.pending', $pendingTransactionCount);
if ($mode === 'next') {
return $this->redirect($this->loginServerUrl . 'account/checkTransactions', 303);
} else {
$this->Flash->success(__('Transaction submitted for review.'));
}
}
}
} else {
$this->Flash->error(__('Building transaction failed'));
}
// */
} else {
$this->Flash->error(__('Something was invalid, please try again!'));
}
}
}
public function createMulti($page = 0)
{
$startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend');
$session = $this->getRequest()->getSession();
$result = $this->requestLogin();
$limit = 200;
if ($result !== true) {
return $result;
}
$user = $session->read('StateUser');
$stateUserTable = TableRegistry::getTableLocator()->get('StateUsers');
$connection = ConnectionManager::get('default');
$transactionActiveMonth = $connection->execute(
'SELECT id, received FROM transactions '
. 'where received >= date_sub(date_add(curdate(), interval 1 - day(curdate()) day), interval 2 month) '
. 'AND '
. 'received < date_add(date_add(curdate(), interval 1 - day(curdate()) day), interval 2 month) '
. 'AND '
. 'transaction_type_id = 1'
)->fetchAll('assoc');
$transactionActiveMonthSortedById = [];
foreach ($transactionActiveMonth as $t) {
$transactionActiveMonthSortedById[$t['id']] = $t['received'];
}
$firstDayLastMonth = new FrozenDate();
$firstDayLastMonth = $firstDayLastMonth->day(1)->subMonth(1);
$transactionsLastMonthTargeDate = $this->TransactionCreations
->find('all')
//->select(['state_user_id', 'target_date', 'amount'])
->where(['EXTRACT(YEAR_MONTH FROM target_date) LIKE' => $firstDayLastMonth->format('Ym')])
->group(['state_user_id'])
->contain([]);
$transactionsLastMonthTargeDate->select([
'state_user_id',
'sum_amount' => $transactionsLastMonthTargeDate->func()->sum('amount')
]);
$transactionsLastMonthTargetDateSortedByStateUserId = [];
foreach ($transactionsLastMonthTargeDate as $transactionCreation) {
$transactionsLastMonthTargetDateSortedByStateUserId[$transactionCreation->state_user_id] = $transactionCreation->sum_amount;
}
$requestData = $this->request->getData();
if ($this->request->is('post') &&
isset($requestData['searchButton']) &&
isset($requestData['searchText']) &&
!empty($requestData['searchText'])
) {
$mode = 'search';
$page = 0;
$this->log("search for text: ".$requestData['searchText'], 'debug');
$stateUsers = $stateUserTable
->find('all')
->select(['id', 'first_name', 'last_name', 'email'])
->order(['first_name', 'last_name'])
->where(
['AND' => [
'disabled' => 0,
'OR' => [
'LOWER(first_name) LIKE' => '%'.strtolower($requestData['searchText']).'%',
'LOWER(last_name) LIKE' => '%'.strtolower($requestData['searchText']).'%',
'LOWER(email) LIKE' => '%'.strtolower($requestData['searchText']).'%'
]
]
]
)
->contain(['TransactionCreations' => [
'fields' => [
'TransactionCreations.amount',
'TransactionCreations.transaction_id',
'TransactionCreations.state_user_id'
]
]]);
$this->log("search query: ".$stateUsers, 'debug');
} else {
$stateUsers = $stateUserTable
->find('all')
->select(['id', 'first_name', 'last_name', 'email'])
//->order(['id'])
->where(['disabled' => 0])
->order(['first_name', 'last_name'])
->contain(['TransactionCreations' => [
'fields' => [
'TransactionCreations.amount',
'TransactionCreations.transaction_id',
'TransactionCreations.state_user_id'
]
]]);
}
//var_dump($stateUsers->toArray());
$possibleReceivers = [];
$countUsers = 0;
foreach ($stateUsers as $i => $stateUser) {
$countUsers++;
if ($i < $page * $limit || $i >= ($page + 1) * $limit) {
continue;
}
$sumAmount = 0;
$sumAmount2 = 0;
if (isset($transactionsLastMonthTargetDateSortedByStateUserId[$stateUser->id])) {
$sumAmount2 = $transactionsLastMonthTargetDateSortedByStateUserId[$stateUser->id];
}
foreach ($stateUser->transaction_creations as $transactionCreation) {
//var_dump($transactionCreation);
if (isset($transactionActiveMonthSortedById[$transactionCreation->transaction_id])) {
$sumAmount += $transactionCreation->amount;
}
}
//if($sumAmount < 20000000) {
array_push($possibleReceivers, [
'name' => $stateUser->first_name . '&nbsp;' . $stateUser->last_name,
'id' => $stateUser->id,
'email' => $stateUser->email,
'amount' => $sumAmount,
'amount2' => $sumAmount2
]);
/*} else {
$this->Flash->error(__('Creation above 2.000 GDD for 2 last two month'));
}*/
}
// usort($possibleReceivers, function ($a, $b) {
// return (strtolower($a['name']) <=> strtolower($b['name']));
// });
// -> replaced by SQL "order by" above
$creationForm = new CreationForm();
$timeUsed = microtime(true) - $startTime;
$this->set(compact('timeUsed', 'stateUsers', 'creationForm', 'possibleReceivers'));
$this->set('firstDayLastMonth', $firstDayLastMonth);
$this->set('activeUser', $user);
$this->set('creationForm', $creationForm);
$this->set('transactionExecutingCount', $session->read('Transaction.executing'));
$this->set('timeUsed', microtime(true) - $startTime);
$this->set('countUsers', $countUsers);
$this->set('limit', $limit);
$this->set('page', $page);
if ($this->request->is('post') && (!isset($mode) || !($mode === 'search'))) {
$this->log("real POST", 'debug');
$mode = 'next';
if (isset($requestData['add'])) {
$mode = 'add';
}
$memo = $requestData['memo'];
$amountCent = $this->GradidoNumber->parseInputNumberToCentNumber($requestData['amount']);
//$targetDate = $requestData['target_date'];
if (!isset($requestData['user']) || count($requestData['user']) == 0) {
$this->Flash->error(__('No user selected'));
} else {
$users = $requestData['user'];
if (isset($requestData['user_pending'])) {
$pendings = $requestData['user_pending'];
} else {
$pendings = [];
}
$receiverUsers = $stateUserTable
->find('all')
->where(['id IN' => array_keys($users)])
->select(['public_key', 'email', 'id'])
->contain(false);
$transactions = [];
foreach ($receiverUsers as $receiverUser) {
$localAmountCent = $amountCent;
//$localTargetDate = $targetDate;
$id = $receiverUser->id;
if ($requestData['user_amount'][$id] != '') {
$localAmountCent = $this->GradidoNumber->parseInputNumberToCentNumber($requestData['user_amount'][$id]);
}
if (isset($requestData['user_target_date']) && isset($requestData['user_target_date'][$id])) {
$localTargetDate = $requestData['user_target_date'][$id];
}
if (isset($pendings[$id])) {
$pendings[$id] += $localAmountCent;
} else {
$pendings[$id] = $localAmountCent;
}
$pubKeyHex = bin2hex(stream_get_contents($receiverUser->public_key));
$identHash = TransactionCreation::DRMakeStringHash($receiverUser->email);
$localTargetDateFrozen = FrozenDate::now();
$localTargetDateFrozen = $localTargetDateFrozen
->year($localTargetDate['year'])
->month($localTargetDate['month'])
->day($localTargetDate['day']);
//echo "input: "; var_dump($localTargetDate);echo "<br>";
//echo "output: "; var_dump($localTargetDateFrozen);
//die('a');
$builderResult = TransactionCreation::build(
$localAmountCent,
$memo,
$pubKeyHex,
$identHash,
$localTargetDateFrozen
);
if ($builderResult['state'] == 'success') {
array_push($transactions, base64_encode($builderResult['transactionBody']->serializeToString()));
}
}
/*echo "pendings: ";
var_dump($pendings);
echo "<br>";*/
foreach ($possibleReceivers as $i => $possibleReceiver) {
$id = $possibleReceiver['id'];
if (isset($pendings[$id])) {
$possibleReceivers[$i]['pending'] = $pendings[$id];
}
}
$this->set('possibleReceivers', $possibleReceivers);
$creationTransactionCount = count($transactions);
if ($creationTransactionCount > 0) {
$user_balance = 0;
if (isset($user['balance'])) {
$user_balance = $user['balance'];
}
// $session_id, $base64Message, $user_balance = 0
$requestResult = $this->JsonRequestClient->sendTransaction(
$session->read('session_id'),
$transactions,
$user_balance
);
if ($requestResult['state'] != 'success') {
$this->addAdminError('TransactionCreations', 'createMulti', $requestResult, $user['id']);
if ($requestResult['type'] == 'request error') {
$this->Flash->error(__('Error by requesting LoginServer, please try again'));
} else {
$this->Flash->error(__('Error, please wait for the admin to fix it'));
}
} else {
$json = $requestResult['data'];
if ($json['state'] != 'success') {
if ($json['msg'] == 'session not found') {
$session->destroy();
return $this->redirect($this->loginServerUrl . 'account', 303);
} else {
$this->addAdminError('TransactionCreations', 'createMulti', $json, $user['id']);
$this->Flash->error(__('Login Server Error, please wait for the admin to fix it'));
}
} else {
$pendingTransactionCount = $session->read('Transactions.pending');
if ($pendingTransactionCount == null) {
$pendingTransactionCount = $creationTransactionCount;
} else {
$pendingTransactionCount += $creationTransactionCount;
}
$session->write('Transactions.pending', $pendingTransactionCount);
if ($mode === 'next') {
return $this->redirect($this->loginServerUrl . 'account/checkTransactions', 303);
} else {
$this->Flash->success(__('Transaction submitted for review.'));
}
}
}
}
}
}
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$transactionCreation = $this->TransactionCreations->newEntity();
if ($this->request->is('post')) {
$transactionCreation = $this->TransactionCreations->patchEntity($transactionCreation, $this->request->getData());
if ($this->TransactionCreations->save($transactionCreation)) {
$this->Flash->success(__('The transaction creation has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The transaction creation could not be saved. Please, try again.'));
}
$transactions = $this->TransactionCreations->Transactions->find('list', ['limit' => 200]);
$stateUsers = $this->TransactionCreations->StateUsers->find('list', ['limit' => 200]);
$this->set(compact('transactionCreation', 'transactions', 'stateUsers'));
}
/**
* Edit method
*
* @param string|null $id Transaction Creation id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$transactionCreation = $this->TransactionCreations->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$transactionCreation = $this->TransactionCreations->patchEntity($transactionCreation, $this->request->getData());
if ($this->TransactionCreations->save($transactionCreation)) {
$this->Flash->success(__('The transaction creation has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The transaction creation could not be saved. Please, try again.'));
}
$transactions = $this->TransactionCreations->Transactions->find('list', ['limit' => 200]);
$stateUsers = $this->TransactionCreations->StateUsers->find('list', ['limit' => 200]);
$this->set(compact('transactionCreation', 'transactions', 'stateUsers'));
}
/**
* Delete method
*
* @param string|null $id Transaction Creation id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$transactionCreation = $this->TransactionCreations->get($id);
if ($this->TransactionCreations->delete($transactionCreation)) {
$this->Flash->success(__('The transaction creation has been deleted.'));
} else {
$this->Flash->error(__('The transaction creation could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,113 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* TransactionGroupAddaddress Controller
*
* @property \App\Model\Table\TransactionGroupAddaddressTable $TransactionGroupAddaddress
*
* @method \App\Model\Entity\TransactionGroupAddaddres[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class TransactionGroupAddaddressController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => ['Transactions', 'AddressTypes']
];
$transactionGroupAddaddress = $this->paginate($this->TransactionGroupAddaddress);
$this->set(compact('transactionGroupAddaddress'));
}
/**
* View method
*
* @param string|null $id Transaction Group Addaddres id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$transactionGroupAddaddres = $this->TransactionGroupAddaddress->get($id, [
'contain' => ['Transactions', 'AddressTypes']
]);
$this->set('transactionGroupAddaddres', $transactionGroupAddaddres);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$transactionGroupAddaddres = $this->TransactionGroupAddaddress->newEntity();
if ($this->request->is('post')) {
$transactionGroupAddaddres = $this->TransactionGroupAddaddress->patchEntity($transactionGroupAddaddres, $this->request->getData());
if ($this->TransactionGroupAddaddress->save($transactionGroupAddaddres)) {
$this->Flash->success(__('The transaction group addaddres has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The transaction group addaddres could not be saved. Please, try again.'));
}
$transactions = $this->TransactionGroupAddaddress->Transactions->find('list', ['limit' => 200]);
$addressTypes = $this->TransactionGroupAddaddress->AddressTypes->find('list', ['limit' => 200]);
$this->set(compact('transactionGroupAddaddres', 'transactions', 'addressTypes'));
}
/**
* Edit method
*
* @param string|null $id Transaction Group Addaddres id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$transactionGroupAddaddres = $this->TransactionGroupAddaddress->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$transactionGroupAddaddres = $this->TransactionGroupAddaddress->patchEntity($transactionGroupAddaddres, $this->request->getData());
if ($this->TransactionGroupAddaddress->save($transactionGroupAddaddres)) {
$this->Flash->success(__('The transaction group addaddres has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The transaction group addaddres could not be saved. Please, try again.'));
}
$transactions = $this->TransactionGroupAddaddress->Transactions->find('list', ['limit' => 200]);
$addressTypes = $this->TransactionGroupAddaddress->AddressTypes->find('list', ['limit' => 200]);
$this->set(compact('transactionGroupAddaddres', 'transactions', 'addressTypes'));
}
/**
* Delete method
*
* @param string|null $id Transaction Group Addaddres id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$transactionGroupAddaddres = $this->TransactionGroupAddaddress->get($id);
if ($this->TransactionGroupAddaddress->delete($transactionGroupAddaddres)) {
$this->Flash->success(__('The transaction group addaddres has been deleted.'));
} else {
$this->Flash->error(__('The transaction group addaddres could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

View File

@ -0,0 +1,113 @@
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* TransactionGroupAllowtrades Controller
*
* @property \App\Model\Table\TransactionGroupAllowtradesTable $TransactionGroupAllowtrades
*
* @method \App\Model\Entity\TransactionGroupAllowtrade[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class TransactionGroupAllowtradesController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|null
*/
public function index()
{
$this->paginate = [
'contain' => ['Transactions', 'Groups']
];
$transactionGroupAllowtrades = $this->paginate($this->TransactionGroupAllowtrades);
$this->set(compact('transactionGroupAllowtrades'));
}
/**
* View method
*
* @param string|null $id Transaction Group Allowtrade id.
* @return \Cake\Http\Response|null
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$transactionGroupAllowtrade = $this->TransactionGroupAllowtrades->get($id, [
'contain' => ['Transactions', 'Groups']
]);
$this->set('transactionGroupAllowtrade', $transactionGroupAllowtrade);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$transactionGroupAllowtrade = $this->TransactionGroupAllowtrades->newEntity();
if ($this->request->is('post')) {
$transactionGroupAllowtrade = $this->TransactionGroupAllowtrades->patchEntity($transactionGroupAllowtrade, $this->request->getData());
if ($this->TransactionGroupAllowtrades->save($transactionGroupAllowtrade)) {
$this->Flash->success(__('The transaction group allowtrade has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The transaction group allowtrade could not be saved. Please, try again.'));
}
$transactions = $this->TransactionGroupAllowtrades->Transactions->find('list', ['limit' => 200]);
$groups = $this->TransactionGroupAllowtrades->Groups->find('list', ['limit' => 200]);
$this->set(compact('transactionGroupAllowtrade', 'transactions', 'groups'));
}
/**
* Edit method
*
* @param string|null $id Transaction Group Allowtrade id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$transactionGroupAllowtrade = $this->TransactionGroupAllowtrades->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$transactionGroupAllowtrade = $this->TransactionGroupAllowtrades->patchEntity($transactionGroupAllowtrade, $this->request->getData());
if ($this->TransactionGroupAllowtrades->save($transactionGroupAllowtrade)) {
$this->Flash->success(__('The transaction group allowtrade has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The transaction group allowtrade could not be saved. Please, try again.'));
}
$transactions = $this->TransactionGroupAllowtrades->Transactions->find('list', ['limit' => 200]);
$groups = $this->TransactionGroupAllowtrades->Groups->find('list', ['limit' => 200]);
$this->set(compact('transactionGroupAllowtrade', 'transactions', 'groups'));
}
/**
* Delete method
*
* @param string|null $id Transaction Group Allowtrade id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$transactionGroupAllowtrade = $this->TransactionGroupAllowtrades->get($id);
if ($this->TransactionGroupAllowtrades->delete($transactionGroupAllowtrade)) {
$this->Flash->success(__('The transaction group allowtrade has been deleted.'));
} else {
$this->Flash->error(__('The transaction group allowtrade could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}

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