Conversie codeigniter 4

This commit is contained in:
2026-01-09 11:41:28 +01:00
parent dbd8c8aed2
commit f0b9c6ad40
242 changed files with 20034 additions and 346 deletions
+1
View File
@@ -33,3 +33,4 @@ user_guide_src/cilexer/pycilexer.egg-info/*
/.env /.env
/themeforest /themeforest
/documents /documents
/writable
+166
View File
@@ -0,0 +1,166 @@
# PHP Docker Template
Template voor PHP projecten (CodeIgniter, plain PHP, etc.) met Xdebug support.
## Snelle start
### 1. Kopieer bestanden naar je project
```bash
cp -r docker/ /pad/naar/jouw-project/
cp docker-compose.yml /pad/naar/jouw-project/
cp .env.example /pad/naar/jouw-project/.env
```
### 2. Configureer je project
Pas `.env` aan:
```env
PROJECT_NAME=jouwproject
PROJECT_DOMAIN=jouwproject.test
DB_DATABASE=jouwproject_db
```
### 3. Pas PHP versie aan (indien nodig)
In `docker-compose.yml`, wijzig de PHP_VERSION:
```yaml
args:
PHP_VERSION: "8.2" # Opties: 7.4, 8.0, 8.1, 8.2, 8.3, 8.4
```
### 4. Pas document root aan (indien nodig)
In `docker/nginx.conf`, wijzig root als je project geen `/public` map heeft:
```nginx
# Voor CodeIgniter 3:
root /var/www/html;
# Voor CodeIgniter 4 / Laravel-style:
root /var/www/html/public;
```
### 5. DNS instellen
Voeg toe aan `/etc/hosts`:
```
127.0.0.1 jouwproject.test
```
Of gebruik dnsmasq voor automatische .test domeinen.
### 6. Database aanmaken
```bash
docker exec -it shared-mysql mysql -u root -proot -e "CREATE DATABASE jouwproject_db;"
```
### 7. Start het project
```bash
# Zorg dat shared services draaien
cd /Volumes/development/sites/docker-shared
docker compose up -d
# Start je project
cd /pad/naar/jouw-project
docker compose up -d --build
```
Je project is nu beschikbaar op http://jouwproject.test
---
## Xdebug met PHPStorm
### 1. PHPStorm configureren
1. **Preferences → PHP → Servers**
- Klik op `+`
- Name: `jouwproject.test`
- Host: `jouwproject.test`
- Port: `80`
- Debugger: `Xdebug`
- ✅ Use path mappings
- Map `/pad/naar/jouw-project` → `/var/www/html`
2. **Preferences → PHP → Debug**
- Debug port: `9003`
- ✅ Can accept external connections
3. **Preferences → PHP → Debug → DBGp Proxy**
- IDE key: `PHPSTORM`
### 2. Debugging starten
1. Klik op de telefoon-icoon in PHPStorm: "Start Listening for PHP Debug Connections"
2. Zet een breakpoint
3. Open je pagina in de browser
4. PHPStorm stopt automatisch bij je breakpoint
---
## Handige commando's
```bash
# Start containers
docker compose up -d
# Herbouw na Dockerfile wijzigingen
docker compose up -d --build
# Stop containers
docker compose down
# Bekijk logs
docker compose logs -f
# Shell in PHP container
docker exec -it jouwproject-app bash
# Composer commands
docker exec -it jouwproject-app composer install
docker exec -it jouwproject-app composer update
# Artisan commands (als je Laravel-achtige CLI hebt)
docker exec -it jouwproject-app php artisan migrate
```
---
## Structuur
```
jouw-project/
├── docker/
│ ├── Dockerfile # PHP container configuratie
│ ├── nginx.conf # Nginx configuratie
│ ├── php.ini # PHP settings
│ └── xdebug.ini # Xdebug settings
├── docker-compose.yml # Container orchestratie
├── .env # Project variabelen
└── ... je project bestanden
```
---
## Troubleshooting
### Container kan shared-mysql niet bereiken
Controleer of shared services draaien:
```bash
docker ps | grep shared-mysql
```
### Xdebug werkt niet
1. Check of xdebug actief is:
```bash
docker exec -it jouwproject-app php -m | grep xdebug
```
2. Check PHPStorm luistert op poort 9003
3. Controleer path mapping in PHPStorm
### Permission denied errors
```bash
docker exec -it jouwproject-app chown -R www:www /var/www/html/storage
```
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class App extends BaseConfig
{
/**
* Base Site URL
*/
public string $baseURL = '';
/**
* Allowed Hostnames in the Site URL other than the hostname in the baseURL.
*
* @var list<string>
*/
public array $allowedHostnames = [];
/**
* Index File
*/
public string $indexPage = '';
/**
* URI Protocol
*/
public string $uriProtocol = 'REQUEST_URI';
/**
* Default Locale
*/
public string $defaultLocale = 'nl';
/**
* Negotiate Locale
*/
public bool $negotiateLocale = false;
/**
* Supported Locales
*
* @var list<string>
*/
public array $supportedLocales = ['nl', 'en'];
/**
* Application Timezone
*/
public string $appTimezone = 'Europe/Amsterdam';
/**
* Default Character Set
*/
public string $charset = 'UTF-8';
/**
* Force Global Secure Requests
*/
public bool $forceGlobalSecureRequests = false;
/**
* Reverse Proxy IPs
*
* @var array<string, string>
*/
public array $proxyIPs = [];
/**
* Content Security Policy
*/
public bool $CSPEnabled = false;
public function __construct()
{
parent::__construct();
// Set baseURL from environment
$this->baseURL = $_ENV['APP_URL'] ?? 'http://localhost';
// Force HTTPS in production
if (($_ENV['ENVIRONMENT'] ?? 'development') === 'production') {
$this->forceGlobalSecureRequests = true;
}
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace Config;
use CodeIgniter\Config\AutoloadConfig;
/**
* Autoload
*
* This file defines the namespaces and class maps so the Autoloader
* can find the files as needed.
*/
class Autoload extends AutoloadConfig
{
/**
* PSR-4 style namespaces
*
* @var array<string, list<string>|string>
*/
public $psr4 = [
APP_NAMESPACE => APPPATH,
];
/**
* Class Maps
*
* @var array<string, string>
*/
public $classmap = [];
/**
* Files to be autoloaded.
*
* @var list<string>
*/
public $files = [];
/**
* Helpers to be autoloaded.
*
* @var list<string>
*/
public $helpers = ['common'];
}
+44
View File
@@ -0,0 +1,44 @@
<?php
/**
* CodeIgniter 4 Boot file
*/
use CodeIgniter\Boot;
use Config\Paths;
/*
* ---------------------------------------------------------------
* SETUP OUR PATH CONSTANTS
* ---------------------------------------------------------------
*/
// Ensure $paths is available
if (! isset($paths)) {
$paths = new Paths();
}
// Define ROOTPATH
defined('ROOTPATH') || define('ROOTPATH', realpath($paths->appDirectory . '/..') . DIRECTORY_SEPARATOR);
// Path to the application directory
defined('APPPATH') || define('APPPATH', realpath($paths->appDirectory) . DIRECTORY_SEPARATOR);
// Path to the public directory
defined('PUBLICPATH') || define('PUBLICPATH', realpath($paths->publicDirectory) . DIRECTORY_SEPARATOR);
// Path to the writable directory
defined('WRITEPATH') || define('WRITEPATH', realpath($paths->writableDirectory) . DIRECTORY_SEPARATOR);
// Path to the tests directory
defined('TESTPATH') || define('TESTPATH', realpath($paths->testsDirectory) . DIRECTORY_SEPARATOR);
/*
* ---------------------------------------------------------------
* GRAB THE CODEIGNITER BOOT CLASS
* ---------------------------------------------------------------
*/
require ROOTPATH . 'vendor/codeigniter4/framework/system/Boot.php';
return Boot::bootWeb($paths);
+34
View File
@@ -0,0 +1,34 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| In development, we want to show as many errors as possible to help
| make sure they don't make it to production. And save us hours of
| painful debugging.
|
| If you set 'display_errors' to '1', CI4's detailed error report will show.
*/
error_reporting(E_ALL);
ini_set('display_errors', '1');
/*
|--------------------------------------------------------------------------
| DEBUG BACKTRACES
|--------------------------------------------------------------------------
| If true, this constant will tell the error screens to display debug
| backtraces along with the other error information. If you would
| prefer to not see this, set this value to false.
*/
defined('SHOW_DEBUG_BACKTRACE') || define('SHOW_DEBUG_BACKTRACE', true);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. This will control whether Kint is loaded, and a few other
| items. It can always be used within your own application too.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);
+25
View File
@@ -0,0 +1,25 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| Don't show ANY in production environments. Instead, let the system catch
| it and display a generic error message.
|
| If you set 'display_errors' to '1', CI4's detailed error report will show.
*/
error_reporting(E_ALL & ~E_DEPRECATED);
// If you want to suppress more types of errors.
// error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
ini_set('display_errors', '0');
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. It's not widely used currently, and may not survive
| release of the framework.
*/
defined('CI_DEBUG') || define('CI_DEBUG', false);
+31
View File
@@ -0,0 +1,31 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| In testing, we want to show as many errors as possible to help
| make sure they don't make it to production.
*/
error_reporting(E_ALL);
ini_set('display_errors', '1');
/*
|--------------------------------------------------------------------------
| DEBUG BACKTRACES
|--------------------------------------------------------------------------
| If true, this constant will tell the error screens to display debug
| backtraces along with the other error information. If you would
| prefer to not see this, set this value to false.
*/
defined('SHOW_DEBUG_BACKTRACE') || define('SHOW_DEBUG_BACKTRACE', true);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. This will control whether Kint is loaded, and a few other
| items. It can always be used within your own application too.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class CURLRequest extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CURLRequest Share Options
* --------------------------------------------------------------------------
*
* Whether share options between requests or not.
*
* If true, all the options won't be reset between requests.
* It may cause an error request with unnecessary headers.
*/
public bool $shareOptions = false;
}
+162
View File
@@ -0,0 +1,162 @@
<?php
namespace Config;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Cache\Handlers\DummyHandler;
use CodeIgniter\Cache\Handlers\FileHandler;
use CodeIgniter\Cache\Handlers\MemcachedHandler;
use CodeIgniter\Cache\Handlers\PredisHandler;
use CodeIgniter\Cache\Handlers\RedisHandler;
use CodeIgniter\Cache\Handlers\WincacheHandler;
use CodeIgniter\Config\BaseConfig;
class Cache extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Primary Handler
* --------------------------------------------------------------------------
*
* The name of the preferred handler that should be used. If for some reason
* it is not available, the $backupHandler will be used in its place.
*/
public string $handler = 'file';
/**
* --------------------------------------------------------------------------
* Backup Handler
* --------------------------------------------------------------------------
*
* The name of the handler that will be used in case the first one is
* unreachable. Often, 'file' is used here since the filesystem is
* always available, though that's not always practical for the app.
*/
public string $backupHandler = 'dummy';
/**
* --------------------------------------------------------------------------
* Key Prefix
* --------------------------------------------------------------------------
*
* This string is added to all cache item names to help avoid collisions
* if you run multiple applications with the same cache engine.
*/
public string $prefix = '';
/**
* --------------------------------------------------------------------------
* Default TTL
* --------------------------------------------------------------------------
*
* The default number of seconds to save items when none is specified.
*
* WARNING: This is not used by framework handlers where 60 seconds is
* hard-coded, but may be useful to projects and modules. This will replace
* the hard-coded value in a future release.
*/
public int $ttl = 60;
/**
* --------------------------------------------------------------------------
* Reserved Characters
* --------------------------------------------------------------------------
*
* A string of reserved characters that will not be allowed in keys or tags.
* Strings that violate this restriction will cause handlers to throw.
* Default: {}()/\@:
*
* NOTE: The default set is required for PSR-6 compliance.
*/
public string $reservedCharacters = '{}()/\@:';
/**
* --------------------------------------------------------------------------
* File settings
* --------------------------------------------------------------------------
*
* Your file storage preferences can be specified below, if you are using
* the File driver.
*
* @var array{storePath?: string, mode?: int}
*/
public array $file = [
'storePath' => WRITEPATH . 'cache/',
'mode' => 0640,
];
/**
* -------------------------------------------------------------------------
* Memcached settings
* -------------------------------------------------------------------------
*
* Your Memcached servers can be specified below, if you are using
* the Memcached drivers.
*
* @see https://codeigniter.com/user_guide/libraries/caching.html#memcached
*
* @var array{host?: string, port?: int, weight?: int, raw?: bool}
*/
public array $memcached = [
'host' => '127.0.0.1',
'port' => 11211,
'weight' => 1,
'raw' => false,
];
/**
* -------------------------------------------------------------------------
* Redis settings
* -------------------------------------------------------------------------
*
* Your Redis server can be specified below, if you are using
* the Redis or Predis drivers.
*
* @var array{host?: string, password?: string|null, port?: int, timeout?: int, database?: int}
*/
public array $redis = [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'timeout' => 0,
'database' => 0,
];
/**
* --------------------------------------------------------------------------
* Available Cache Handlers
* --------------------------------------------------------------------------
*
* This is an array of cache engine alias' and class names. Only engines
* that are listed here are allowed to be used.
*
* @var array<string, class-string<CacheInterface>>
*/
public array $validHandlers = [
'dummy' => DummyHandler::class,
'file' => FileHandler::class,
'memcached' => MemcachedHandler::class,
'predis' => PredisHandler::class,
'redis' => RedisHandler::class,
'wincache' => WincacheHandler::class,
];
/**
* --------------------------------------------------------------------------
* Web Page Caching: Cache Include Query String
* --------------------------------------------------------------------------
*
* Whether to take the URL query string into consideration when generating
* output cache files. Valid options are:
*
* false = Disabled
* true = Enabled, take all query parameters into account.
* Please be aware that this may result in numerous cache
* files generated for the same page over and over again.
* ['q'] = Enabled, but only take into account the specified list
* of query parameters.
*
* @var bool|list<string>
*/
public $cacheQueryString = false;
}
+67
View File
@@ -0,0 +1,67 @@
<?php
/*
| --------------------------------------------------------------------
| App Version
| --------------------------------------------------------------------
*/
defined('APP_VERSION') || define('APP_VERSION', '1.00.81');
/*
| --------------------------------------------------------------------
| App Namespace
| --------------------------------------------------------------------
*/
defined('APP_NAMESPACE') || define('APP_NAMESPACE', 'App');
/*
| --------------------------------------------------------------------
| Composer Path
| --------------------------------------------------------------------
*/
defined('COMPOSER_PATH') || define('COMPOSER_PATH', ROOTPATH . 'vendor/autoload.php');
/*
|--------------------------------------------------------------------------
| Timing Constants
|--------------------------------------------------------------------------
*/
defined('SECOND') || define('SECOND', 1);
defined('MINUTE') || define('MINUTE', 60);
defined('HOUR') || define('HOUR', 3600);
defined('DAY') || define('DAY', 86400);
defined('WEEK') || define('WEEK', 604800);
defined('MONTH') || define('MONTH', 2_592_000);
defined('YEAR') || define('YEAR', 31_536_000);
defined('DECADE') || define('DECADE', 315_360_000);
/*
| --------------------------------------------------------------------------
| Exit Status Codes
| --------------------------------------------------------------------------
*/
defined('EXIT_SUCCESS') || define('EXIT_SUCCESS', 0);
defined('EXIT_ERROR') || define('EXIT_ERROR', 1);
defined('EXIT_CONFIG') || define('EXIT_CONFIG', 3);
defined('EXIT_UNKNOWN_FILE') || define('EXIT_UNKNOWN_FILE', 4);
defined('EXIT_UNKNOWN_CLASS') || define('EXIT_UNKNOWN_CLASS', 5);
defined('EXIT_UNKNOWN_METHOD') || define('EXIT_UNKNOWN_METHOD', 6);
defined('EXIT_USER_INPUT') || define('EXIT_USER_INPUT', 7);
defined('EXIT_DATABASE') || define('EXIT_DATABASE', 8);
defined('EXIT__AUTO_MIN') || define('EXIT__AUTO_MIN', 9);
defined('EXIT__AUTO_MAX') || define('EXIT__AUTO_MAX', 125);
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_LOW instead.
*/
define('EVENT_PRIORITY_LOW', 200);
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_NORMAL instead.
*/
define('EVENT_PRIORITY_NORMAL', 100);
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_HIGH instead.
*/
define('EVENT_PRIORITY_HIGH', 10);
+176
View File
@@ -0,0 +1,176 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Stores the default settings for the ContentSecurityPolicy, if you
* choose to use it. The values here will be read in and set as defaults
* for the site. If needed, they can be overridden on a page-by-page basis.
*
* Suggested reference for explanations:
*
* @see https://www.html5rocks.com/en/tutorials/security/content-security-policy/
*/
class ContentSecurityPolicy extends BaseConfig
{
// -------------------------------------------------------------------------
// Broadbrush CSP management
// -------------------------------------------------------------------------
/**
* Default CSP report context
*/
public bool $reportOnly = false;
/**
* Specifies a URL where a browser will send reports
* when a content security policy is violated.
*/
public ?string $reportURI = null;
/**
* Instructs user agents to rewrite URL schemes, changing
* HTTP to HTTPS. This directive is for websites with
* large numbers of old URLs that need to be rewritten.
*/
public bool $upgradeInsecureRequests = false;
// -------------------------------------------------------------------------
// Sources allowed
// NOTE: once you set a policy to 'none', it cannot be further restricted
// -------------------------------------------------------------------------
/**
* Will default to self if not overridden
*
* @var list<string>|string|null
*/
public $defaultSrc;
/**
* Lists allowed scripts' URLs.
*
* @var list<string>|string
*/
public $scriptSrc = 'self';
/**
* Lists allowed stylesheets' URLs.
*
* @var list<string>|string
*/
public $styleSrc = 'self';
/**
* Defines the origins from which images can be loaded.
*
* @var list<string>|string
*/
public $imageSrc = 'self';
/**
* Restricts the URLs that can appear in a page's `<base>` element.
*
* Will default to self if not overridden
*
* @var list<string>|string|null
*/
public $baseURI;
/**
* Lists the URLs for workers and embedded frame contents
*
* @var list<string>|string
*/
public $childSrc = 'self';
/**
* Limits the origins that you can connect to (via XHR,
* WebSockets, and EventSource).
*
* @var list<string>|string
*/
public $connectSrc = 'self';
/**
* Specifies the origins that can serve web fonts.
*
* @var list<string>|string
*/
public $fontSrc;
/**
* Lists valid endpoints for submission from `<form>` tags.
*
* @var list<string>|string
*/
public $formAction = 'self';
/**
* Specifies the sources that can embed the current page.
* This directive applies to `<frame>`, `<iframe>`, `<embed>`,
* and `<applet>` tags. This directive can't be used in
* `<meta>` tags and applies only to non-HTML resources.
*
* @var list<string>|string|null
*/
public $frameAncestors;
/**
* The frame-src directive restricts the URLs which may
* be loaded into nested browsing contexts.
*
* @var list<string>|string|null
*/
public $frameSrc;
/**
* Restricts the origins allowed to deliver video and audio.
*
* @var list<string>|string|null
*/
public $mediaSrc;
/**
* Allows control over Flash and other plugins.
*
* @var list<string>|string
*/
public $objectSrc = 'self';
/**
* @var list<string>|string|null
*/
public $manifestSrc;
/**
* Limits the kinds of plugins a page may invoke.
*
* @var list<string>|string|null
*/
public $pluginTypes;
/**
* List of actions allowed.
*
* @var list<string>|string|null
*/
public $sandbox;
/**
* Nonce tag for style
*/
public string $styleNonceTag = '{csp-style-nonce}';
/**
* Nonce tag for script
*/
public string $scriptNonceTag = '{csp-script-nonce}';
/**
* Replace nonce tag automatically
*/
public bool $autoNonce = true;
}
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use DateTimeInterface;
class Cookie extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Cookie Prefix
* --------------------------------------------------------------------------
*
* Set a cookie name prefix if you need to avoid collisions.
*/
public string $prefix = '';
/**
* --------------------------------------------------------------------------
* Cookie Expires Timestamp
* --------------------------------------------------------------------------
*
* Default expires timestamp for cookies. Setting this to `0` will mean the
* cookie will not have the `Expires` attribute and will behave as a session
* cookie.
*
* @var DateTimeInterface|int|string
*/
public $expires = 0;
/**
* --------------------------------------------------------------------------
* Cookie Path
* --------------------------------------------------------------------------
*
* Typically will be a forward slash.
*/
public string $path = '/';
/**
* --------------------------------------------------------------------------
* Cookie Domain
* --------------------------------------------------------------------------
*
* Set to `.your-domain.com` for site-wide cookies.
*/
public string $domain = '';
/**
* --------------------------------------------------------------------------
* Cookie Secure
* --------------------------------------------------------------------------
*
* Cookie will only be set if a secure HTTPS connection exists.
*/
public bool $secure = false;
/**
* --------------------------------------------------------------------------
* Cookie HTTPOnly
* --------------------------------------------------------------------------
*
* Cookie will only be accessible via HTTP(S) (no JavaScript).
*/
public bool $httponly = true;
/**
* --------------------------------------------------------------------------
* Cookie SameSite
* --------------------------------------------------------------------------
*
* Configure cookie SameSite setting. Allowed values are:
* - None
* - Lax
* - Strict
* - ''
*
* Alternatively, you can use the constant names:
* - `Cookie::SAMESITE_NONE`
* - `Cookie::SAMESITE_LAX`
* - `Cookie::SAMESITE_STRICT`
*
* Defaults to `Lax` for compatibility with modern browsers. Setting `''`
* (empty string) means default SameSite attribute set by browsers (`Lax`)
* will be set on cookies. If set to `None`, `$secure` must also be set.
*
* @var ''|'Lax'|'None'|'Strict'
*/
public string $samesite = 'Lax';
/**
* --------------------------------------------------------------------------
* Cookie Raw
* --------------------------------------------------------------------------
*
* This flag allows setting a "raw" cookie, i.e., its name and value are
* not URL encoded using `rawurlencode()`.
*
* If this is set to `true`, cookie names should be compliant of RFC 2616's
* list of allowed characters.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
* @see https://tools.ietf.org/html/rfc2616#section-2.2
*/
public bool $raw = false;
}
+75
View File
@@ -0,0 +1,75 @@
<?php
namespace Config;
use CodeIgniter\Database\Config;
class Database extends Config
{
/**
* Default database group.
*/
public string $defaultGroup = 'default';
/**
* Default database connection values
*/
public array $default = [
'DSN' => '',
'hostname' => '',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_unicode_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
];
/**
* Test database connection values (for PHPUnit)
*/
public array $tests = [
'DSN' => '',
'hostname' => '127.0.0.1',
'username' => '',
'password' => '',
'database' => ':memory:',
'DBDriver' => 'SQLite3',
'DBPrefix' => 'db_',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => '',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
];
public function __construct()
{
parent::__construct();
// Load from environment variables
$this->default['hostname'] = $_ENV['DB_HOST'] ?? '127.0.0.1';
$this->default['username'] = $_ENV['DB_USER'] ?? '';
$this->default['password'] = $_ENV['DB_PASS'] ?? '';
$this->default['database'] = $_ENV['DB_NAME'] ?? '';
// Debug mode based on environment
$this->default['DBDebug'] = ($_ENV['ENVIRONMENT'] ?? 'development') !== 'production';
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace Config;
class DocTypes
{
/**
* List of valid document types.
*
* @var array<string, string>
*/
public array $list = [
'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'xhtml-basic11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
'html5' => '<!DOCTYPE html>',
'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
'mathml1' => '<!DOCTYPE math SYSTEM "http://www.w3.org/Math/DTD/mathml1/mathml.dtd">',
'mathml2' => '<!DOCTYPE math PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">',
'svg10' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">',
'svg11' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">',
'svg11-basic' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Basic//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd">',
'svg11-tiny' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">',
'xhtml-math-svg-xh' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-math-svg-sh' => '<!DOCTYPE svg:svg PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-rdfa-1' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">',
'xhtml-rdfa-2' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.1//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd">',
];
/**
* Whether to remove the solidus (`/`) character for void HTML elements (e.g. `<input>`)
* for HTML5 compatibility.
*
* Set to:
* `true` - to be HTML5 compatible
* `false` - to be XHTML compatible
*/
public bool $html5 = true;
}
+132
View File
@@ -0,0 +1,132 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
public string $fromEmail = '';
public string $fromName = '';
public string $recipients = '';
/**
* The "user agent"
*/
public string $userAgent = 'CodeIgniter';
/**
* The mail sending protocol: mail, sendmail, smtp
*/
public string $protocol = 'smtp';
/**
* The server path to Sendmail.
*/
public string $mailPath = '/usr/sbin/sendmail';
/**
* SMTP Server Hostname
*/
public string $SMTPHost = '';
/**
* SMTP Username
*/
public string $SMTPUser = '';
/**
* SMTP Password
*/
public string $SMTPPass = '';
/**
* SMTP Port
*/
public int $SMTPPort = 25;
/**
* SMTP Timeout (in seconds)
*/
public int $SMTPTimeout = 5;
/**
* Enable persistent SMTP connections
*/
public bool $SMTPKeepAlive = false;
/**
* SMTP Encryption.
*
* @var string '', 'tls' or 'ssl'. 'tls' will issue a STARTTLS command
* to the server. 'ssl' means implicit SSL. Connection on port
* 465 should set this to ''.
*/
public string $SMTPCrypto = 'tls';
/**
* Enable word-wrap
*/
public bool $wordWrap = true;
/**
* Character count to wrap at
*/
public int $wrapChars = 76;
/**
* Type of mail, either 'text' or 'html'
*/
public string $mailType = 'html';
/**
* Character set (utf-8, iso-8859-1, etc.)
*/
public string $charset = 'UTF-8';
/**
* Whether to validate the email address
*/
public bool $validate = false;
/**
* Email Priority. 1 = highest. 5 = lowest. 3 = normal
*/
public int $priority = 3;
/**
* Newline character. (Use "\r\n" to comply with RFC 822)
*/
public string $CRLF = "\r\n";
/**
* Newline character. (Use "\r\n" to comply with RFC 822)
*/
public string $newline = "\r\n";
/**
* Enable BCC Batch Mode.
*/
public bool $BCCBatchMode = false;
/**
* Number of emails in each BCC batch
*/
public int $BCCBatchSize = 200;
/**
* Enable notify message from server
*/
public bool $DSN = false;
public function __construct()
{
parent::__construct();
// Load from environment
$this->SMTPHost = str_replace(',', '', $_ENV['SMTP_HOST'] ?? '');
$this->SMTPUser = str_replace(',', '', $_ENV['SMTP_USER'] ?? '');
$this->SMTPPass = str_replace(',', '', $_ENV['SMTP_PASS'] ?? '');
$this->SMTPPort = (int) str_replace(',', '', $_ENV['SMTP_PORT'] ?? '587');
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Encryption configuration.
*
* These are the settings used for encryption, if you don't pass a parameter
* array to the encrypter for creation/initialization.
*/
class Encryption extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Encryption Key Starter
* --------------------------------------------------------------------------
*
* If you use the Encryption class you must set an encryption key (seed).
* You need to ensure it is long enough for the cipher and mode you plan to use.
* See the user guide for more info.
*/
public string $key = '';
/**
* --------------------------------------------------------------------------
* Encryption Driver to Use
* --------------------------------------------------------------------------
*
* One of the supported encryption drivers.
*
* Available drivers:
* - OpenSSL
* - Sodium
*/
public string $driver = 'OpenSSL';
/**
* --------------------------------------------------------------------------
* SodiumHandler's Padding Length in Bytes
* --------------------------------------------------------------------------
*
* This is the number of bytes that will be padded to the plaintext message
* before it is encrypted. This value should be greater than zero.
*
* See the user guide for more information on padding.
*/
public int $blockSize = 16;
/**
* --------------------------------------------------------------------------
* Encryption digest
* --------------------------------------------------------------------------
*
* HMAC digest to use, e.g. 'SHA512' or 'SHA256'. Default value is 'SHA512'.
*/
public string $digest = 'SHA512';
/**
* Whether the cipher-text should be raw. If set to false, then it will be base64 encoded.
* This setting is only used by OpenSSLHandler.
*
* Set to false for CI3 Encryption compatibility.
*/
public bool $rawData = true;
/**
* Encryption key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'encryption' for CI3 Encryption compatibility.
*/
public string $encryptKeyInfo = '';
/**
* Authentication key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'authentication' for CI3 Encryption compatibility.
*/
public string $authKeyInfo = '';
/**
* Cipher to use.
* This setting is only used by OpenSSLHandler.
*
* Set to 'AES-128-CBC' to decrypt encrypted data that encrypted
* by CI3 Encryption default configuration.
*/
public string $cipher = 'AES-256-CTR';
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace Config;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use Illuminate\Database\Capsule\Manager as Capsule;
/*
* --------------------------------------------------------------------
* Application Events
* --------------------------------------------------------------------
*/
Events::on('pre_system', static function () {
// Boot Eloquent ORM
bootEloquent();
});
/**
* Bootstrap Eloquent ORM with database configuration from environment
*/
function bootEloquent(): void
{
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'mysql',
'host' => $_ENV['DB_HOST'] ?? '127.0.0.1',
'database' => $_ENV['DB_NAME'] ?? '',
'username' => $_ENV['DB_USER'] ?? '',
'password' => $_ENV['DB_PASS'] ?? '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
]);
// Make this Capsule instance available globally via static methods
$capsule->setAsGlobal();
// Setup the Eloquent ORM
$capsule->bootEloquent();
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\ExceptionHandler;
use CodeIgniter\Debug\ExceptionHandlerInterface;
use Psr\Log\LogLevel;
use Throwable;
class Exceptions extends BaseConfig
{
/**
* Log Exceptions?
*/
public bool $log = true;
/**
* DO NOT log These Exceptions.
*
* @var list<class-string<Throwable>>
*/
public array $ignoreCodes = [404];
/**
* Error Views Path
*/
public string $errorViewPath = APPPATH . 'Views/errors';
/**
* Hide Error Messages?
*/
public bool $hideErrors = false;
/**
* Custom Exception Handler for AJAX requests
*
* @var class-string<ExceptionHandlerInterface>|null
*/
public ?string $handler = null;
/**
* Sensitive Data in Trace
*
* @var list<string>
*/
public array $sensitiveDataInTraceStep = [
'password',
'pass',
'salt'
];
/**
* Sensitive Data in Trace (for deprecated property)
*
* @var list<string>
*/
public array $sensitiveDataInTrace = [
'password',
'pass',
'salt'
];
/**
* Whether to log deprecation warnings.
*/
public bool $logDeprecations = true;
/**
* The log level for deprecation warnings.
*/
public string $deprecationLogLevel = LogLevel::WARNING;
public function handler(int $statusCode, Throwable $exception): ExceptionHandlerInterface
{
return new ExceptionHandler($this);
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Enable/disable backward compatibility breaking features.
*/
class Feature extends BaseConfig
{
/**
* Use improved new auto routing instead of the legacy version.
*/
public bool $autoRoutesImproved = true;
/**
* Use filter execution order in 4.4 or before.
*/
public bool $oldFilterOrder = false;
/**
* The behavior of `limit(0)` in Query Builder.
*
* If true, `limit(0)` returns all records. (the behavior of 4.4.x or before in version 4.x.)
* If false, `limit(0)` returns no records. (the behavior of 3.1.9 or later in version 3.x.)
*/
public bool $limitZeroAsAll = true;
/**
* Use strict location negotiation.
*
* By default, the locale is selected based on a loose comparison of the language code (ISO 639-1)
* Enabling strict comparison will also consider the region code (ISO 3166-1 alpha-2).
*/
public bool $strictLocaleNegotiation = false;
}
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace Config;
use CodeIgniter\Config\Filters as BaseFilters;
use CodeIgniter\Filters\Cors;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\ForceHTTPS;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\PageCache;
use CodeIgniter\Filters\PerformanceMetrics;
use CodeIgniter\Filters\SecureHeaders;
class Filters extends BaseFilters
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* @var array<string, class-string|list<class-string>>
*/
public array $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'cors' => Cors::class,
'forcehttps' => ForceHTTPS::class,
'pagecache' => PageCache::class,
'performance' => PerformanceMetrics::class,
'auth' => \App\Filters\AuthFilter::class,
];
/**
* List of special required filters.
*
* @var array{before: list<string>, after: list<string>}
*/
public array $required = [
'before' => [
'forcehttps',
'pagecache',
],
'after' => [
'pagecache',
'performance',
'toolbar',
],
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array<string, array<string, array<string, string>>>|array<string, list<string>>
*/
public array $globals = [
'before' => [
// 'honeypot',
// 'csrf',
// 'invalidchars',
],
'after' => [
// 'honeypot',
// 'secureheaders',
],
];
/**
* List of filter aliases that works on a
* particular HTTP method (GET, POST, etc.).
*
* @var array<string, list<string>>
*/
public array $methods = [];
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* @var array<string, array<string, list<string>>>
*/
public array $filters = [];
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace Config;
use CodeIgniter\Config\ForeignCharacters as BaseForeignCharacters;
/**
* @immutable
*/
class ForeignCharacters extends BaseForeignCharacters
{
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Format\JSONFormatter;
use CodeIgniter\Format\XMLFormatter;
class Format extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Available Response Formats
* --------------------------------------------------------------------------
*
* When you perform content negotiation with the request, these are the
* available formats that your application supports. This is currently
* only used with the API\ResponseTrait. A valid Formatter must exist
* for the specified format.
*
* These formats are only checked when the data passed to the respond()
* method is an array.
*
* @var list<string>
*/
public array $supportedResponseFormats = [
'application/json',
'application/xml', // machine-readable XML
'text/xml', // human-readable XML
];
/**
* --------------------------------------------------------------------------
* Formatters
* --------------------------------------------------------------------------
*
* Lists the class to use to format responses with of a particular type.
* For each mime type, list the class that should be used. Formatters
* can be retrieved through the getFormatter() method.
*
* @var array<string, string>
*/
public array $formatters = [
'application/json' => JSONFormatter::class,
'application/xml' => XMLFormatter::class,
'text/xml' => XMLFormatter::class,
];
/**
* --------------------------------------------------------------------------
* Formatters Options
* --------------------------------------------------------------------------
*
* Additional Options to adjust default formatters behaviour.
* For each mime type, list the additional options that should be used.
*
* @var array<string, int>
*/
public array $formatterOptions = [
'application/json' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
'application/xml' => 0,
'text/xml' => 0,
];
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Generators extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Generator Commands' Views
* --------------------------------------------------------------------------
*
* This array defines the mapping of generator commands to the view files
* they are using. If you need to customize them for your own, copy these
* view files in your own folder and indicate the location here.
*
* You will notice that the views have special placeholders enclosed in
* curly braces `{...}`. These placeholders are used internally by the
* generator commands in processing replacements, thus you are warned
* not to delete them or modify the names. If you will do so, you may
* end up disrupting the scaffolding process and throw errors.
*
* YOU HAVE BEEN WARNED!
*
* @var array<string, array<string, string>|string>
*/
public array $views = [
'make:cell' => [
'class' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
],
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
'make:entity' => 'CodeIgniter\Commands\Generators\Views\entity.tpl.php',
'make:filter' => 'CodeIgniter\Commands\Generators\Views\filter.tpl.php',
'make:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
'make:model' => 'CodeIgniter\Commands\Generators\Views\model.tpl.php',
'make:seeder' => 'CodeIgniter\Commands\Generators\Views\seeder.tpl.php',
'make:validation' => 'CodeIgniter\Commands\Generators\Views\validation.tpl.php',
'session:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
];
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Honeypot extends BaseConfig
{
/**
* Makes Honeypot visible or not to human
*/
public bool $hidden = true;
/**
* Honeypot Label Content
*/
public string $label = 'Fill This Field';
/**
* Honeypot Field Name
*/
public string $name = 'honeypot';
/**
* Honeypot HTML Template
*/
public string $template = '<label>{label}</label><input type="text" name="{name}" value="">';
/**
* Honeypot container
*
* If you enabled CSP, you can remove `style="display:none"`.
*/
public string $container = '<div style="display:none">{template}</div>';
/**
* The id attribute for Honeypot container tag
*
* Used when CSP is enabled.
*/
public string $containerId = 'hpc';
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Images\Handlers\GDHandler;
use CodeIgniter\Images\Handlers\ImageMagickHandler;
class Images extends BaseConfig
{
/**
* Default handler used if no other handler is specified.
*/
public string $defaultHandler = 'gd';
/**
* The path to the image library.
* Required for ImageMagick, GraphicsMagick, or NetPBM.
*/
public string $libraryPath = '/usr/local/bin/convert';
/**
* The available handler classes.
*
* @var array<string, string>
*/
public array $handlers = [
'gd' => GDHandler::class,
'imagick' => ImageMagickHandler::class,
];
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace Config;
use Kint\Parser\ConstructablePluginInterface;
use Kint\Renderer\Rich\TabPluginInterface;
use Kint\Renderer\Rich\ValuePluginInterface;
/**
* --------------------------------------------------------------------------
* Kint
* --------------------------------------------------------------------------
*
* We use Kint's `RichRenderer` and `CLIRenderer`. This area contains options
* that you can set to customize how Kint works for you.
*
* @see https://kint-php.github.io/kint/ for details on these settings.
*/
class Kint
{
/*
|--------------------------------------------------------------------------
| Global Settings
|--------------------------------------------------------------------------
*/
/**
* @var list<class-string<ConstructablePluginInterface>|ConstructablePluginInterface>|null
*/
public $plugins;
public int $maxDepth = 6;
public bool $displayCalledFrom = true;
public bool $expanded = false;
/*
|--------------------------------------------------------------------------
| RichRenderer Settings
|--------------------------------------------------------------------------
*/
public string $richTheme = 'aante-light.css';
public bool $richFolder = false;
/**
* @var array<string, class-string<ValuePluginInterface>>|null
*/
public $richObjectPlugins;
/**
* @var array<string, class-string<TabPluginInterface>>|null
*/
public $richTabPlugins;
/*
|--------------------------------------------------------------------------
| CLI Settings
|--------------------------------------------------------------------------
*/
public bool $cliColors = true;
public bool $cliForceUTF8 = false;
public bool $cliDetectWidth = true;
public int $cliMinWidth = 40;
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Log\Handlers\FileHandler;
class Logger extends BaseConfig
{
/**
* Error Logging Threshold
*
* @var int|list<int>
*/
public $threshold = 4;
/**
* Date Format for Logs
*/
public string $dateFormat = 'Y-m-d H:i:s';
/**
* Handlers
*
* @var array<class-string, array<string, int|list<string>|string>>
*/
public array $handlers = [
FileHandler::class => [
'handles' => ['critical', 'alert', 'emergency', 'debug', 'error', 'info', 'notice', 'warning'],
'fileExtension' => '',
'filePermissions' => 0644,
'path' => '',
],
];
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Migrations extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Enable/Disable Migrations
* --------------------------------------------------------------------------
*
* Migrations are enabled by default.
*
* You should enable migrations whenever you intend to do a schema migration
* and disable it back when you're done.
*/
public bool $enabled = true;
/**
* --------------------------------------------------------------------------
* Migrations Table
* --------------------------------------------------------------------------
*
* This is the name of the table that will store the current migrations state.
* When migrations runs it will store in a database table which migration
* files have already been run.
*/
public string $table = 'migrations';
/**
* --------------------------------------------------------------------------
* Timestamp Format
* --------------------------------------------------------------------------
*
* This is the format that will be used when creating new migrations
* using the CLI command:
* > php spark make:migration
*
* NOTE: if you set an unsupported format, migration runner will not find
* your migration files.
*
* Supported formats:
* - YmdHis_
* - Y-m-d-His_
* - Y_m_d_His_
*/
public string $timestampFormat = 'Y-m-d-His_';
}
+534
View File
@@ -0,0 +1,534 @@
<?php
namespace Config;
/**
* This file contains an array of mime types. It is used by the
* Upload class to help identify allowed file types.
*
* When more than one variation for an extension exist (like jpg, jpeg, etc)
* the most common one should be first in the array to aid the guess*
* methods. The same applies when more than one mime-type exists for a
* single extension.
*
* When working with mime types, please make sure you have the ´fileinfo´
* extension enabled to reliably detect the media types.
*/
class Mimes
{
/**
* Map of extensions to mime types.
*
* @var array<string, list<string>|string>
*/
public static array $mimes = [
'hqx' => [
'application/mac-binhex40',
'application/mac-binhex',
'application/x-binhex40',
'application/x-mac-binhex40',
],
'cpt' => 'application/mac-compactpro',
'csv' => [
'text/csv',
'text/x-comma-separated-values',
'text/comma-separated-values',
'application/vnd.ms-excel',
'application/x-csv',
'text/x-csv',
'application/csv',
'application/excel',
'application/vnd.msexcel',
'text/plain',
],
'bin' => [
'application/macbinary',
'application/mac-binary',
'application/octet-stream',
'application/x-binary',
'application/x-macbinary',
],
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => [
'application/octet-stream',
'application/vnd.microsoft.portable-executable',
'application/x-dosexec',
'application/x-msdownload',
],
'class' => 'application/octet-stream',
'psd' => [
'application/x-photoshop',
'image/vnd.adobe.photoshop',
],
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => [
'application/pdf',
'application/force-download',
'application/x-download',
],
'ai' => [
'application/pdf',
'application/postscript',
],
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => [
'application/vnd.ms-excel',
'application/msexcel',
'application/x-msexcel',
'application/x-ms-excel',
'application/x-excel',
'application/x-dos_ms_excel',
'application/xls',
'application/x-xls',
'application/excel',
'application/download',
'application/vnd.ms-office',
'application/msword',
],
'ppt' => [
'application/vnd.ms-powerpoint',
'application/powerpoint',
'application/vnd.ms-office',
'application/msword',
],
'pptx' => [
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
],
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'gzip' => 'application/x-gzip',
'php' => [
'application/x-php',
'application/x-httpd-php',
'application/php',
'text/php',
'text/x-php',
'application/x-httpd-php-source',
],
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => [
'application/x-javascript',
'text/plain',
],
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => [
'application/x-tar',
'application/x-gzip-compressed',
],
'z' => 'application/x-compress',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => [
'application/x-zip',
'application/zip',
'application/x-zip-compressed',
'application/s-compressed',
'multipart/x-zip',
],
'rar' => [
'application/vnd.rar',
'application/x-rar',
'application/rar',
'application/x-rar-compressed',
],
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => [
'audio/mpeg',
'audio/mpg',
'audio/mpeg3',
'audio/mp3',
],
'aif' => [
'audio/x-aiff',
'audio/aiff',
],
'aiff' => [
'audio/x-aiff',
'audio/aiff',
],
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => [
'audio/x-wav',
'audio/wave',
'audio/wav',
],
'bmp' => [
'image/bmp',
'image/x-bmp',
'image/x-bitmap',
'image/x-xbitmap',
'image/x-win-bitmap',
'image/x-windows-bmp',
'image/ms-bmp',
'image/x-ms-bmp',
'application/bmp',
'application/x-bmp',
'application/x-win-bitmap',
],
'gif' => 'image/gif',
'jpg' => [
'image/jpeg',
'image/pjpeg',
],
'jpeg' => [
'image/jpeg',
'image/pjpeg',
],
'jpe' => [
'image/jpeg',
'image/pjpeg',
],
'jp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'j2k' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpf' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpg2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpx' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpm' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mj2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mjp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'png' => [
'image/png',
'image/x-png',
],
'webp' => 'image/webp',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'css' => [
'text/css',
'text/plain',
],
'html' => [
'text/html',
'text/plain',
],
'htm' => [
'text/html',
'text/plain',
],
'shtml' => [
'text/html',
'text/plain',
],
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => [
'text/plain',
'text/x-log',
],
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => [
'application/xml',
'text/xml',
'text/plain',
],
'xsl' => [
'application/xml',
'text/xsl',
'text/xml',
],
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => [
'video/x-msvideo',
'video/msvideo',
'video/avi',
'application/x-troff-msvideo',
],
'movie' => 'video/x-sgi-movie',
'doc' => [
'application/msword',
'application/vnd.ms-office',
],
'docx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
'application/x-zip',
],
'dot' => [
'application/msword',
'application/vnd.ms-office',
],
'dotx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
],
'xlsx' => [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/zip',
'application/vnd.ms-excel',
'application/msword',
'application/x-zip',
],
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
'word' => [
'application/msword',
'application/octet-stream',
],
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => [
'application/json',
'text/json',
],
'pem' => [
'application/x-x509-user-cert',
'application/x-pem-file',
'application/octet-stream',
],
'p10' => [
'application/x-pkcs10',
'application/pkcs10',
],
'p12' => 'application/x-pkcs12',
'p7a' => 'application/x-pkcs7-signature',
'p7c' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7m' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'crt' => [
'application/x-x509-ca-cert',
'application/x-x509-user-cert',
'application/pkix-cert',
],
'crl' => [
'application/pkix-crl',
'application/pkcs-crl',
],
'der' => 'application/x-x509-ca-cert',
'kdb' => 'application/octet-stream',
'pgp' => 'application/pgp',
'gpg' => 'application/gpg-keys',
'sst' => 'application/octet-stream',
'csr' => 'application/octet-stream',
'rsa' => 'application/x-pkcs7',
'cer' => [
'application/pkix-cert',
'application/x-x509-ca-cert',
],
'3g2' => 'video/3gpp2',
'3gp' => [
'video/3gp',
'video/3gpp',
],
'mp4' => 'video/mp4',
'm4a' => 'audio/x-m4a',
'f4v' => [
'video/mp4',
'video/x-f4v',
],
'flv' => 'video/x-flv',
'webm' => 'video/webm',
'aac' => 'audio/x-acc',
'm4u' => 'application/vnd.mpegurl',
'm3u' => 'text/plain',
'xspf' => 'application/xspf+xml',
'vlc' => 'application/videolan',
'wmv' => [
'video/x-ms-wmv',
'video/x-ms-asf',
],
'au' => 'audio/x-au',
'ac3' => 'audio/ac3',
'flac' => 'audio/x-flac',
'ogg' => [
'audio/ogg',
'video/ogg',
'application/ogg',
],
'kmz' => [
'application/vnd.google-earth.kmz',
'application/zip',
'application/x-zip',
],
'kml' => [
'application/vnd.google-earth.kml+xml',
'application/xml',
'text/xml',
],
'ics' => 'text/calendar',
'ical' => 'text/calendar',
'zsh' => 'text/x-scriptzsh',
'7zip' => [
'application/x-compressed',
'application/x-zip-compressed',
'application/zip',
'multipart/x-zip',
],
'cdr' => [
'application/cdr',
'application/coreldraw',
'application/x-cdr',
'application/x-coreldraw',
'image/cdr',
'image/x-cdr',
'zz-application/zz-winassoc-cdr',
],
'wma' => [
'audio/x-ms-wma',
'video/x-ms-asf',
],
'jar' => [
'application/java-archive',
'application/x-java-application',
'application/x-jar',
'application/x-compressed',
],
'svg' => [
'image/svg+xml',
'image/svg',
'application/xml',
'text/xml',
],
'vcf' => 'text/x-vcard',
'srt' => [
'text/srt',
'text/plain',
],
'vtt' => [
'text/vtt',
'text/plain',
],
'ico' => [
'image/x-icon',
'image/x-ico',
'image/vnd.microsoft.icon',
],
'stl' => [
'application/sla',
'application/vnd.ms-pki.stl',
'application/x-navistyle',
'model/stl',
'application/octet-stream',
],
];
/**
* Attempts to determine the best mime type for the given file extension.
*
* @return string|null The mime type found, or none if unable to determine.
*/
public static function guessTypeFromExtension(string $extension)
{
$extension = trim(strtolower($extension), '. ');
if (! array_key_exists($extension, static::$mimes)) {
return null;
}
return is_array(static::$mimes[$extension]) ? static::$mimes[$extension][0] : static::$mimes[$extension];
}
/**
* Attempts to determine the best file extension for a given mime type.
*
* @param string|null $proposedExtension - default extension (in case there is more than one with the same mime type)
*
* @return string|null The extension determined, or null if unable to match.
*/
public static function guessExtensionFromType(string $type, ?string $proposedExtension = null)
{
$type = trim(strtolower($type), '. ');
$proposedExtension = trim(strtolower($proposedExtension ?? ''));
if (
$proposedExtension !== ''
&& array_key_exists($proposedExtension, static::$mimes)
&& in_array($type, (array) static::$mimes[$proposedExtension], true)
) {
// The detected mime type matches with the proposed extension.
return $proposedExtension;
}
// Reverse check the mime type list if no extension was proposed.
// This search is order sensitive!
foreach (static::$mimes as $ext => $types) {
if (in_array($type, (array) $types, true)) {
return $ext;
}
}
return null;
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace Config;
use CodeIgniter\Modules\Modules as BaseModules;
/**
* Modules Configuration
*/
class Modules extends BaseModules
{
/**
* Should the application auto-discover resources
* within the modules.
*/
public $enabled = true;
/**
* Should Composer packages be auto-discovered?
*/
public $discoverInComposer = true;
/**
* The Composer packages to auto-discover.
*
* @var list<string>
*/
public $composerPackages = [];
/**
* Aliases
*
* @var array<string, string|null>
*/
public $aliases = [];
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace Config;
/**
* Optimization Configuration.
*
* NOTE: This class does not extend BaseConfig for performance reasons.
* So you cannot replace the property values with Environment Variables.
*/
class Optimize
{
/**
* --------------------------------------------------------------------------
* Config Caching
* --------------------------------------------------------------------------
*
* @see https://codeigniter.com/user_guide/concepts/factories.html#config-caching
*/
public bool $configCacheEnabled = false;
/**
* --------------------------------------------------------------------------
* Config Caching
* --------------------------------------------------------------------------
*
* @see https://codeigniter.com/user_guide/concepts/autoloader.html#file-locator-caching
*/
public bool $locatorCacheEnabled = false;
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Pager extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Templates
* --------------------------------------------------------------------------
*
* Pagination links are rendered out using views to configure their
* appearance. This array contains aliases and the view names to
* use when rendering the links.
*
* Within each view, the Pager object will be available as $pager,
* and the desired group as $pagerGroup;
*
* @var array<string, string>
*/
public array $templates = [
'default_full' => 'CodeIgniter\Pager\Views\default_full',
'default_simple' => 'CodeIgniter\Pager\Views\default_simple',
'default_head' => 'CodeIgniter\Pager\Views\default_head',
];
/**
* --------------------------------------------------------------------------
* Items Per Page
* --------------------------------------------------------------------------
*
* The default number of results shown in a single page.
*/
public int $perPage = 20;
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace Config;
/**
* Paths
*
* Holds the paths that are used by the system to
* locate the main directories. These may be
* modified to more easily work within different
* environments.
*/
class Paths
{
/**
* The path to the application directory.
*/
public string $appDirectory = __DIR__ . '/..';
/**
* The path to the system directory.
*/
public string $systemDirectory = __DIR__ . '/../../vendor/codeigniter4/framework/system';
/**
* The path to the public directory.
* This is where the front controller (index.php) is.
*/
public string $publicDirectory = __DIR__ . '/../../public';
/**
* The path to the writable directory.
*/
public string $writableDirectory = __DIR__ . '/../../writable';
/**
* The path to the tests directory
*/
public string $testsDirectory = __DIR__ . '/../../tests';
/**
* The path to the views directory,
* must have a trailing slash.
*/
public string $viewDirectory = __DIR__ . '/../Views/';
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace Config;
use CodeIgniter\Config\Publisher as BasePublisher;
/**
* Publisher Configuration
*
* Defines basic security restrictions for the Publisher class
* to prevent abuse by injecting malicious files into a project.
*/
class Publisher extends BasePublisher
{
/**
* A list of allowed destinations with a (pseudo-)regex
* of allowed files for each destination.
* Attempts to publish to directories not in this list will
* result in a PublisherException. Files that do no fit the
* pattern will cause copy/merge to fail.
*
* @var array<string, string>
*/
public $restrictions = [
ROOTPATH => '*',
FCPATH => '#\.(s?css|js|map|html?|xml|json|webmanifest|ttf|eot|woff2?|gif|jpe?g|tiff?|png|webp|bmp|ico|svg)$#i',
];
}
+195
View File
@@ -0,0 +1,195 @@
<?php
use CodeIgniter\Router\RouteCollection;
/**
* @var RouteCollection $routes
*/
// Default controller
$routes->setDefaultController('Main');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);
// Main routes
$routes->get('/', 'Main::index');
// Login routes
$routes->match(['get', 'post'], 'login', 'Login::index');
$routes->get('login/logout', 'Login::logout');
$routes->get('login/showVerify2fa', 'Login::showVerify2fa');
$routes->post('login/verify2fa', 'Login::verify2fa');
$routes->post('login/resendOtp', 'Login::resendOtp');
$routes->post('login/changeWeakPassword', 'Login::changeWeakPassword');
$routes->post('login/requestPassword', 'Login::requestPassword');
// Menu
$routes->get('menu', 'Menu::index');
$routes->get('menu/(:any)', 'Menu::$1');
// Beheer (Management) routes
$routes->group('beheer', static function ($routes) {
// Users (support both old CI3 URLs and new URLs)
$routes->get('users', 'Beheer\UsersController::index');
$routes->get('users/(:any)', 'Beheer\UsersController::$1');
$routes->post('users/(:any)', 'Beheer\UsersController::$1');
$routes->get('usersController/(:any)', 'Beheer\UsersController::$1');
$routes->post('usersController/(:any)', 'Beheer\UsersController::$1');
// Customers (support both old CI3 URLs and new URLs)
$routes->get('customers', 'Beheer\CustomersController::index');
$routes->get('customers/(:any)', 'Beheer\CustomersController::$1');
$routes->post('customers/(:any)', 'Beheer\CustomersController::$1');
$routes->get('customersController/(:any)', 'Beheer\CustomersController::$1');
$routes->post('customersController/(:any)', 'Beheer\CustomersController::$1');
// Externals (support both old CI3 URLs and new URLs)
$routes->get('externals', 'Beheer\ExternalsController::index');
$routes->get('externals/(:any)', 'Beheer\ExternalsController::$1');
$routes->post('externals/(:any)', 'Beheer\ExternalsController::$1');
$routes->get('externalsController/(:any)', 'Beheer\ExternalsController::$1');
$routes->post('externalsController/(:any)', 'Beheer\ExternalsController::$1');
// Roles (support both old CI3 URLs and new URLs)
$routes->get('roles', 'Beheer\RolesController::index');
$routes->get('roles/(:any)', 'Beheer\RolesController::$1');
$routes->post('roles/(:any)', 'Beheer\RolesController::$1');
$routes->get('rolesController/(:any)', 'Beheer\RolesController::$1');
$routes->post('rolesController/(:any)', 'Beheer\RolesController::$1');
// Authorisation
$routes->get('authorisation', 'Beheer\AuthorisationController::index');
$routes->get('authorisation/(:any)', 'Beheer\AuthorisationController::$1');
$routes->post('authorisation/(:any)', 'Beheer\AuthorisationController::$1');
$routes->get('authorisationController/(:any)', 'Beheer\AuthorisationController::$1');
$routes->post('authorisationController/(:any)', 'Beheer\AuthorisationController::$1');
$routes->get('AuthorisationController/(:any)', 'Beheer\AuthorisationController::$1');
$routes->post('AuthorisationController/(:any)', 'Beheer\AuthorisationController::$1');
// Two Factor
$routes->get('twofactor', 'Beheer\TwoFactorController::index');
$routes->get('twofactor/(:any)', 'Beheer\TwoFactorController::$1');
$routes->post('twofactor/(:any)', 'Beheer\TwoFactorController::$1');
$routes->get('twofactorController/(:any)', 'Beheer\TwoFactorController::$1');
$routes->post('twofactorController/(:any)', 'Beheer\TwoFactorController::$1');
// Employee Target
$routes->get('employeetarget', 'Beheer\EmployeeTargetController::index');
$routes->get('employeetarget/(:any)', 'Beheer\EmployeeTargetController::$1');
$routes->post('employeetarget/(:any)', 'Beheer\EmployeeTargetController::$1');
$routes->get('employeetargetController/(:any)', 'Beheer\EmployeeTargetController::$1');
$routes->post('employeetargetController/(:any)', 'Beheer\EmployeeTargetController::$1');
// VAT
$routes->get('vat', 'Beheer\VatController::index');
$routes->get('vat/(:any)', 'Beheer\VatController::$1');
$routes->post('vat/(:any)', 'Beheer\VatController::$1');
$routes->get('vatController/(:any)', 'Beheer\VatController::$1');
$routes->post('vatController/(:any)', 'Beheer\VatController::$1');
});
// Projects routes - support both old CI3 URLs (projects/offersController/...) and new URLs
$routes->group('projects', static function ($routes) {
$routes->get('/', 'Projects\ProjectsController::index');
// Legacy CI3 routes with Controller suffix
$routes->get('projectsController/(:any)', 'Projects\ProjectsController::$1');
$routes->post('projectsController/(:any)', 'Projects\ProjectsController::$1');
$routes->get('offersController/(:any)', 'Projects\OffersController::$1');
$routes->post('offersController/(:any)', 'Projects\OffersController::$1');
$routes->get('commentsController/(:any)', 'Projects\CommentsController::$1');
$routes->post('commentsController/(:any)', 'Projects\CommentsController::$1');
$routes->get('documentsController/(:any)', 'Projects\DocumentsController::$1');
$routes->post('documentsController/(:any)', 'Projects\DocumentsController::$1');
$routes->get('employeehoursController/(:any)', 'Projects\EmployeeHoursController::$1');
$routes->post('employeehoursController/(:any)', 'Projects\EmployeeHoursController::$1');
$routes->get('employeeHoursController/(:any)', 'Projects\EmployeeHoursController::$1');
$routes->post('employeeHoursController/(:any)', 'Projects\EmployeeHoursController::$1');
// New style routes
$routes->get('(:any)', 'Projects\ProjectsController::$1');
$routes->post('(:any)', 'Projects\ProjectsController::$1');
});
// Employee Hours
$routes->group('employeehours', static function ($routes) {
$routes->get('/', 'Projects\EmployeeHoursController::index');
$routes->get('employeehoursController/(:any)', 'Projects\EmployeeHoursController::$1');
$routes->post('employeehoursController/(:any)', 'Projects\EmployeeHoursController::$1');
$routes->get('(:any)', 'Projects\EmployeeHoursController::$1');
$routes->post('(:any)', 'Projects\EmployeeHoursController::$1');
});
// Offers
$routes->group('offers', static function ($routes) {
$routes->get('/', 'Projects\OffersController::index');
$routes->get('offersController/(:any)', 'Projects\OffersController::$1');
$routes->post('offersController/(:any)', 'Projects\OffersController::$1');
$routes->get('(:any)', 'Projects\OffersController::$1');
$routes->post('(:any)', 'Projects\OffersController::$1');
});
// Comments
$routes->group('comments', static function ($routes) {
$routes->get('/', 'Projects\CommentsController::index');
$routes->get('commentsController/(:any)', 'Projects\CommentsController::$1');
$routes->post('commentsController/(:any)', 'Projects\CommentsController::$1');
$routes->get('(:any)', 'Projects\CommentsController::$1');
$routes->post('(:any)', 'Projects\CommentsController::$1');
});
// Documents
$routes->group('documents', static function ($routes) {
$routes->get('/', 'Projects\DocumentsController::index');
$routes->get('documentsController/(:any)', 'Projects\DocumentsController::$1');
$routes->post('documentsController/(:any)', 'Projects\DocumentsController::$1');
$routes->get('(:any)', 'Projects\DocumentsController::$1');
$routes->post('(:any)', 'Projects\DocumentsController::$1');
});
// Reports routes
$routes->group('reports', static function ($routes) {
$routes->get('/', 'Reports\ReportsController::index');
$routes->get('reportsController/(:any)', 'Reports\ReportsController::$1');
$routes->post('reportsController/(:any)', 'Reports\ReportsController::$1');
// Reservations controller accessible under reports/
$routes->get('reservationsController/(:any)', 'Reports\ReservationsController::$1');
$routes->post('reservationsController/(:any)', 'Reports\ReservationsController::$1');
// Reportsdefault controller accessible under reports/
$routes->get('reportsdefaultController/(:any)', 'Reports\ReportsdefaultController::$1');
$routes->post('reportsdefaultController/(:any)', 'Reports\ReportsdefaultController::$1');
$routes->get('(:any)', 'Reports\ReportsController::$1');
$routes->post('(:any)', 'Reports\ReportsController::$1');
});
$routes->group('reportsdefault', static function ($routes) {
$routes->get('/', 'Reports\ReportsdefaultController::index');
$routes->get('reportsdefaultController/(:any)', 'Reports\ReportsdefaultController::$1');
$routes->post('reportsdefaultController/(:any)', 'Reports\ReportsdefaultController::$1');
$routes->get('(:any)', 'Reports\ReportsdefaultController::$1');
$routes->post('(:any)', 'Reports\ReportsdefaultController::$1');
});
$routes->group('reservations', static function ($routes) {
$routes->get('/', 'Reports\ReservationsController::index');
$routes->get('reservationsController/(:any)', 'Reports\ReservationsController::$1');
$routes->post('reservationsController/(:any)', 'Reports\ReservationsController::$1');
$routes->get('(:any)', 'Reports\ReservationsController::$1');
$routes->post('(:any)', 'Reports\ReservationsController::$1');
});
// Dashboard
$routes->group('dashboard', static function ($routes) {
$routes->get('/', 'Dashboard\DashboardController::index');
$routes->get('dashboardController/(:any)', 'Dashboard\DashboardController::$1');
$routes->post('dashboardController/(:any)', 'Dashboard\DashboardController::$1');
$routes->get('(:any)', 'Dashboard\DashboardController::$1');
$routes->post('(:any)', 'Dashboard\DashboardController::$1');
});
// File Upload
$routes->post('fileupload/(:any)', 'FileUpload::$1');
// Download DB
$routes->get('downloaddb', 'DownloadDB::index');
$routes->get('downloaddb/(:any)', 'DownloadDB::$1');
+140
View File
@@ -0,0 +1,140 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Config;
use CodeIgniter\Config\Routing as BaseRouting;
/**
* Routing configuration
*/
class Routing extends BaseRouting
{
/**
* For Defined Routes.
* An array of files that contain route definitions.
* Route files are read in order, with the first match
* found taking precedence.
*
* Default: APPPATH . 'Config/Routes.php'
*
* @var list<string>
*/
public array $routeFiles = [
APPPATH . 'Config/Routes.php',
];
/**
* For Defined Routes and Auto Routing.
* The default namespace to use for Controllers when no other
* namespace has been specified.
*
* Default: 'App\Controllers'
*/
public string $defaultNamespace = 'App\Controllers';
/**
* For Auto Routing.
* The default controller to use when no other controller has been
* specified.
*
* Default: 'Home'
*/
public string $defaultController = 'Home';
/**
* For Defined Routes and Auto Routing.
* The default method to call on the controller when no other
* method has been set in the route.
*
* Default: 'index'
*/
public string $defaultMethod = 'index';
/**
* For Auto Routing.
* Whether to translate dashes in URIs for controller/method to underscores.
* Primarily useful when using the auto-routing.
*
* Default: false
*/
public bool $translateURIDashes = false;
/**
* Sets the class/method that should be called if routing doesn't
* find a match. It can be the controller/method name like: Users::index
*
* This setting is passed to the Router class and handled there.
*
* If you want to use a closure, you will have to set it in the
* routes file by calling:
*
* $routes->set404Override(function() {
* // Do something here
* });
*
* Example:
* public $override404 = 'App\Errors::show404';
*/
public ?string $override404 = null;
/**
* If TRUE, the system will attempt to match the URI against
* Controllers by matching each segment against folders/files
* in APPPATH/Controllers, when a match wasn't found against
* defined routes.
*
* If FALSE, will stop searching and do NO automatic routing.
*/
public bool $autoRoute = false;
/**
* For Defined Routes.
* If TRUE, will enable the use of the 'prioritize' option
* when defining routes.
*
* Default: false
*/
public bool $prioritize = false;
/**
* For Defined Routes.
* If TRUE, matched multiple URI segments will be passed as one parameter.
*
* Default: false
*/
public bool $multipleSegmentsOneParam = false;
/**
* For Auto Routing (Improved).
* Map of URI segments and namespaces.
*
* The key is the first URI segment. The value is the controller namespace.
* E.g.,
* [
* 'blog' => 'Acme\Blog\Controllers',
* ]
*
* @var array<string, string>
*/
public array $moduleRoutes = [];
/**
* For Auto Routing (Improved).
* Whether to translate dashes in URIs for controller/method to CamelCase.
* E.g., blog-controller -> BlogController
*
* If you enable this, $translateURIDashes is ignored.
*
* Default: false
*/
public bool $translateUriToCamelCase = true;
}
+86
View File
@@ -0,0 +1,86 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Security extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CSRF Protection Method
* --------------------------------------------------------------------------
*
* Protection Method for Cross Site Request Forgery protection.
*
* @var string 'cookie' or 'session'
*/
public string $csrfProtection = 'cookie';
/**
* --------------------------------------------------------------------------
* CSRF Token Randomization
* --------------------------------------------------------------------------
*
* Randomize the CSRF Token for added security.
*/
public bool $tokenRandomize = false;
/**
* --------------------------------------------------------------------------
* CSRF Token Name
* --------------------------------------------------------------------------
*
* Token name for Cross Site Request Forgery protection.
*/
public string $tokenName = 'csrf_test_name';
/**
* --------------------------------------------------------------------------
* CSRF Header Name
* --------------------------------------------------------------------------
*
* Header name for Cross Site Request Forgery protection.
*/
public string $headerName = 'X-CSRF-TOKEN';
/**
* --------------------------------------------------------------------------
* CSRF Cookie Name
* --------------------------------------------------------------------------
*
* Cookie name for Cross Site Request Forgery protection.
*/
public string $cookieName = 'csrf_cookie_name';
/**
* --------------------------------------------------------------------------
* CSRF Expires
* --------------------------------------------------------------------------
*
* Expiration time for Cross Site Request Forgery protection cookie.
*
* Defaults to two hours (in seconds).
*/
public int $expires = 7200;
/**
* --------------------------------------------------------------------------
* CSRF Regenerate
* --------------------------------------------------------------------------
*
* Regenerate CSRF Token on every submission.
*/
public bool $regenerate = true;
/**
* --------------------------------------------------------------------------
* CSRF Redirect
* --------------------------------------------------------------------------
*
* Redirect to previous page with error on failure.
*
* @see https://codeigniter4.github.io/userguide/libraries/security.html#redirection-on-failure
*/
public bool $redirect = (ENVIRONMENT === 'production');
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseService;
/**
* Services Configuration file.
*
* Services are simply other classes/libraries that the system uses
* to do its job. This is used by CodeIgniter to allow the core of the
* framework to be swapped out easily without affecting the usage within
* the rest of your application.
*/
class Services extends BaseService
{
// Add any custom services here
}
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Session\Handlers\BaseHandler;
use CodeIgniter\Session\Handlers\DatabaseHandler;
use CodeIgniter\Session\Handlers\FileHandler;
class Session extends BaseConfig
{
/**
* Session Driver
*
* The session storage driver to use:
* - `CodeIgniter\Session\Handlers\FileHandler`
* - `CodeIgniter\Session\Handlers\DatabaseHandler`
* - `CodeIgniter\Session\Handlers\MemcachedHandler`
* - `CodeIgniter\Session\Handlers\RedisHandler`
*
* @var class-string<BaseHandler>
*/
public string $driver = DatabaseHandler::class;
/**
* Session Cookie Name
*/
public string $cookieName = 'ci_session';
/**
* Session Expiration
*
* The number of SECONDS you want the session to last.
* Setting to 0 (zero) means expire when the browser is closed.
*/
public int $expiration = 7200;
/**
* Session Save Path
*
* For DatabaseHandler, this is the table name.
*/
public string $savePath = 'ci_sessions';
/**
* Session Match IP
*/
public bool $matchIP = false;
/**
* Session Time to Update
*
* How many seconds between CI regenerating the session ID.
*/
public int $timeToUpdate = 300;
/**
* Session Regenerate Destroy
*
* Whether to destroy session data associated with the old session ID
* when auto-regenerating the session ID.
*/
public bool $regenerateDestroy = false;
/**
* Session Database Group
*
* DB Group for the database session handler
*/
public ?string $DBGroup = null;
}
+122
View File
@@ -0,0 +1,122 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\Toolbar\Collectors\Database;
use CodeIgniter\Debug\Toolbar\Collectors\Events;
use CodeIgniter\Debug\Toolbar\Collectors\Files;
use CodeIgniter\Debug\Toolbar\Collectors\Logs;
use CodeIgniter\Debug\Toolbar\Collectors\Routes;
use CodeIgniter\Debug\Toolbar\Collectors\Timers;
use CodeIgniter\Debug\Toolbar\Collectors\Views;
/**
* --------------------------------------------------------------------------
* Debug Toolbar
* --------------------------------------------------------------------------
*
* The Debug Toolbar provides a way to see information about the performance
* and state of your application during that page display. By default it will
* NOT be displayed under production environments, and will only display if
* `CI_DEBUG` is true, since if it's not, there's not much to display anyway.
*/
class Toolbar extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Toolbar Collectors
* --------------------------------------------------------------------------
*
* List of toolbar collectors that will be called when Debug Toolbar
* fires up and collects data from.
*
* @var list<class-string>
*/
public array $collectors = [
Timers::class,
Database::class,
Logs::class,
Views::class,
// \CodeIgniter\Debug\Toolbar\Collectors\Cache::class,
Files::class,
Routes::class,
Events::class,
];
/**
* --------------------------------------------------------------------------
* Collect Var Data
* --------------------------------------------------------------------------
*
* If set to false var data from the views will not be collected. Useful to
* avoid high memory usage when there are lots of data passed to the view.
*/
public bool $collectVarData = true;
/**
* --------------------------------------------------------------------------
* Max History
* --------------------------------------------------------------------------
*
* `$maxHistory` sets a limit on the number of past requests that are stored,
* helping to conserve file space used to store them. You can set it to
* 0 (zero) to not have any history stored, or -1 for unlimited history.
*/
public int $maxHistory = 20;
/**
* --------------------------------------------------------------------------
* Toolbar Views Path
* --------------------------------------------------------------------------
*
* The full path to the the views that are used by the toolbar.
* This MUST have a trailing slash.
*/
public string $viewsPath = SYSTEMPATH . 'Debug/Toolbar/Views/';
/**
* --------------------------------------------------------------------------
* Max Queries
* --------------------------------------------------------------------------
*
* If the Database Collector is enabled, it will log every query that the
* the system generates so they can be displayed on the toolbar's timeline
* and in the query log. This can lead to memory issues in some instances
* with hundreds of queries.
*
* `$maxQueries` defines the maximum amount of queries that will be stored.
*/
public int $maxQueries = 100;
/**
* --------------------------------------------------------------------------
* Watched Directories
* --------------------------------------------------------------------------
*
* Contains an array of directories that will be watched for changes and
* used to determine if the hot-reload feature should reload the page or not.
* We restrict the values to keep performance as high as possible.
*
* NOTE: The ROOTPATH will be prepended to all values.
*
* @var list<string>
*/
public array $watchedDirectories = [
'app',
];
/**
* --------------------------------------------------------------------------
* Watched File Extensions
* --------------------------------------------------------------------------
*
* Contains an array of file extensions that will be watched for changes and
* used to determine if the hot-reload feature should reload the page or not.
*
* @var list<string>
*/
public array $watchedExtensions = [
'php', 'css', 'js', 'html', 'svg', 'json', 'env',
];
}
+252
View File
@@ -0,0 +1,252 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* -------------------------------------------------------------------
* User Agents
* -------------------------------------------------------------------
*
* This file contains four arrays of user agent data. It is used by the
* User Agent Class to help identify browser, platform, robot, and
* mobile device data. The array keys are used to identify the device
* and the array values are used to set the actual name of the item.
*/
class UserAgents extends BaseConfig
{
/**
* -------------------------------------------------------------------
* OS Platforms
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $platforms = [
'windows nt 10.0' => 'Windows 10',
'windows nt 6.3' => 'Windows 8.1',
'windows nt 6.2' => 'Windows 8',
'windows nt 6.1' => 'Windows 7',
'windows nt 6.0' => 'Windows Vista',
'windows nt 5.2' => 'Windows 2003',
'windows nt 5.1' => 'Windows XP',
'windows nt 5.0' => 'Windows 2000',
'windows nt 4.0' => 'Windows NT 4.0',
'winnt4.0' => 'Windows NT 4.0',
'winnt 4.0' => 'Windows NT',
'winnt' => 'Windows NT',
'windows 98' => 'Windows 98',
'win98' => 'Windows 98',
'windows 95' => 'Windows 95',
'win95' => 'Windows 95',
'windows phone' => 'Windows Phone',
'windows' => 'Unknown Windows OS',
'android' => 'Android',
'blackberry' => 'BlackBerry',
'iphone' => 'iOS',
'ipad' => 'iOS',
'ipod' => 'iOS',
'os x' => 'Mac OS X',
'ppc mac' => 'Power PC Mac',
'freebsd' => 'FreeBSD',
'ppc' => 'Macintosh',
'linux' => 'Linux',
'debian' => 'Debian',
'sunos' => 'Sun Solaris',
'beos' => 'BeOS',
'apachebench' => 'ApacheBench',
'aix' => 'AIX',
'irix' => 'Irix',
'osf' => 'DEC OSF',
'hp-ux' => 'HP-UX',
'netbsd' => 'NetBSD',
'bsdi' => 'BSDi',
'openbsd' => 'OpenBSD',
'gnu' => 'GNU/Linux',
'unix' => 'Unknown Unix OS',
'symbian' => 'Symbian OS',
];
/**
* -------------------------------------------------------------------
* Browsers
* -------------------------------------------------------------------
*
* The order of this array should NOT be changed. Many browsers return
* multiple browser types so we want to identify the subtype first.
*
* @var array<string, string>
*/
public array $browsers = [
'OPR' => 'Opera',
'Flock' => 'Flock',
'Edge' => 'Spartan',
'Edg' => 'Edge',
'Chrome' => 'Chrome',
// Opera 10+ always reports Opera/9.80 and appends Version/<real version> to the user agent string
'Opera.*?Version' => 'Opera',
'Opera' => 'Opera',
'MSIE' => 'Internet Explorer',
'Internet Explorer' => 'Internet Explorer',
'Trident.* rv' => 'Internet Explorer',
'Shiira' => 'Shiira',
'Firefox' => 'Firefox',
'Chimera' => 'Chimera',
'Phoenix' => 'Phoenix',
'Firebird' => 'Firebird',
'Camino' => 'Camino',
'Netscape' => 'Netscape',
'OmniWeb' => 'OmniWeb',
'Safari' => 'Safari',
'Mozilla' => 'Mozilla',
'Konqueror' => 'Konqueror',
'icab' => 'iCab',
'Lynx' => 'Lynx',
'Links' => 'Links',
'hotjava' => 'HotJava',
'amaya' => 'Amaya',
'IBrowse' => 'IBrowse',
'Maxthon' => 'Maxthon',
'Ubuntu' => 'Ubuntu Web Browser',
'Vivaldi' => 'Vivaldi',
];
/**
* -------------------------------------------------------------------
* Mobiles
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $mobiles = [
// legacy array, old values commented out
'mobileexplorer' => 'Mobile Explorer',
// 'openwave' => 'Open Wave',
// 'opera mini' => 'Opera Mini',
// 'operamini' => 'Opera Mini',
// 'elaine' => 'Palm',
'palmsource' => 'Palm',
// 'digital paths' => 'Palm',
// 'avantgo' => 'Avantgo',
// 'xiino' => 'Xiino',
'palmscape' => 'Palmscape',
// 'nokia' => 'Nokia',
// 'ericsson' => 'Ericsson',
// 'blackberry' => 'BlackBerry',
// 'motorola' => 'Motorola'
// Phones and Manufacturers
'motorola' => 'Motorola',
'nokia' => 'Nokia',
'palm' => 'Palm',
'iphone' => 'Apple iPhone',
'ipad' => 'iPad',
'ipod' => 'Apple iPod Touch',
'sony' => 'Sony Ericsson',
'ericsson' => 'Sony Ericsson',
'blackberry' => 'BlackBerry',
'cocoon' => 'O2 Cocoon',
'blazer' => 'Treo',
'lg' => 'LG',
'amoi' => 'Amoi',
'xda' => 'XDA',
'mda' => 'MDA',
'vario' => 'Vario',
'htc' => 'HTC',
'samsung' => 'Samsung',
'sharp' => 'Sharp',
'sie-' => 'Siemens',
'alcatel' => 'Alcatel',
'benq' => 'BenQ',
'ipaq' => 'HP iPaq',
'mot-' => 'Motorola',
'playstation portable' => 'PlayStation Portable',
'playstation 3' => 'PlayStation 3',
'playstation vita' => 'PlayStation Vita',
'hiptop' => 'Danger Hiptop',
'nec-' => 'NEC',
'panasonic' => 'Panasonic',
'philips' => 'Philips',
'sagem' => 'Sagem',
'sanyo' => 'Sanyo',
'spv' => 'SPV',
'zte' => 'ZTE',
'sendo' => 'Sendo',
'nintendo dsi' => 'Nintendo DSi',
'nintendo ds' => 'Nintendo DS',
'nintendo 3ds' => 'Nintendo 3DS',
'wii' => 'Nintendo Wii',
'open web' => 'Open Web',
'openweb' => 'OpenWeb',
// Operating Systems
'android' => 'Android',
'symbian' => 'Symbian',
'SymbianOS' => 'SymbianOS',
'elaine' => 'Palm',
'series60' => 'Symbian S60',
'windows ce' => 'Windows CE',
// Browsers
'obigo' => 'Obigo',
'netfront' => 'Netfront Browser',
'openwave' => 'Openwave Browser',
'mobilexplorer' => 'Mobile Explorer',
'operamini' => 'Opera Mini',
'opera mini' => 'Opera Mini',
'opera mobi' => 'Opera Mobile',
'fennec' => 'Firefox Mobile',
// Other
'digital paths' => 'Digital Paths',
'avantgo' => 'AvantGo',
'xiino' => 'Xiino',
'novarra' => 'Novarra Transcoder',
'vodafone' => 'Vodafone',
'docomo' => 'NTT DoCoMo',
'o2' => 'O2',
// Fallback
'mobile' => 'Generic Mobile',
'wireless' => 'Generic Mobile',
'j2me' => 'Generic Mobile',
'midp' => 'Generic Mobile',
'cldc' => 'Generic Mobile',
'up.link' => 'Generic Mobile',
'up.browser' => 'Generic Mobile',
'smartphone' => 'Generic Mobile',
'cellphone' => 'Generic Mobile',
];
/**
* -------------------------------------------------------------------
* Robots
* -------------------------------------------------------------------
*
* There are hundred of bots but these are the most common.
*
* @var array<string, string>
*/
public array $robots = [
'googlebot' => 'Googlebot',
'msnbot' => 'MSNBot',
'baiduspider' => 'Baiduspider',
'bingbot' => 'Bing',
'slurp' => 'Inktomi Slurp',
'yahoo' => 'Yahoo',
'ask jeeves' => 'Ask Jeeves',
'fastcrawler' => 'FastCrawler',
'infoseek' => 'InfoSeek Robot 1.0',
'lycos' => 'Lycos',
'yandex' => 'YandexBot',
'mediapartners-google' => 'MediaPartners Google',
'CRAZYWEBCRAWLER' => 'Crazy Webcrawler',
'adsbot-google' => 'AdsBot Google',
'feedfetcher-google' => 'Feedfetcher Google',
'curious george' => 'Curious George',
'ia_archiver' => 'Alexa Crawler',
'MJ12bot' => 'Majestic-12',
'Uptimebot' => 'Uptimebot',
];
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Validation\StrictRules\CreditCardRules;
use CodeIgniter\Validation\StrictRules\FileRules;
use CodeIgniter\Validation\StrictRules\FormatRules;
use CodeIgniter\Validation\StrictRules\Rules;
class Validation extends BaseConfig
{
// --------------------------------------------------------------------
// Setup
// --------------------------------------------------------------------
/**
* Stores the classes that contain the
* rules that are available.
*
* @var list<string>
*/
public array $ruleSets = [
Rules::class,
FormatRules::class,
FileRules::class,
CreditCardRules::class,
];
/**
* Specifies the views that are used to display the
* errors.
*
* @var array<string, string>
*/
public array $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
];
// --------------------------------------------------------------------
// Rules
// --------------------------------------------------------------------
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace Config;
use CodeIgniter\Config\View as BaseView;
use CodeIgniter\View\ViewDecoratorInterface;
/**
* @phpstan-type parser_callable (callable(mixed): mixed)
* @phpstan-type parser_callable_string (callable(mixed): mixed)&string
*/
class View extends BaseView
{
/**
* When false, the view method will clear the data between each
* call. This keeps your data safe and ensures there is no accidental
* leaking between calls, so you would need to explicitly pass the data
* to each view. You might prefer to have the data stick around between
* calls so that it is available to all views. If that is the case,
* set $saveData to true.
*
* @var bool
*/
public $saveData = true;
/**
* Parser Filters map a filter name with any PHP callable. When the
* Parser prepares a variable for display, it will chain it
* through the filters in the order defined, inserting any parameters.
* To prevent potential abuse, all filters MUST be defined here
* in order for them to be available for use within the Parser.
*
* Examples:
* { title|esc(js) }
* { created_on|date(Y-m-d)|esc(attr) }
*
* @var array<string, string>
* @phpstan-var array<string, parser_callable_string>
*/
public $filters = [];
/**
* Parser Plugins provide a way to extend the functionality provided
* by the core Parser by creating aliases that will be replaced with
* any callable. Can be single or tag pair.
*
* @var array<string, callable|list<string>|string>
* @phpstan-var array<string, list<parser_callable_string>|parser_callable_string|parser_callable>
*/
public $plugins = [];
/**
* View Decorators are class methods that will be run in sequence to
* have a chance to alter the generated output just prior to caching
* the results.
*
* All classes must implement CodeIgniter\View\ViewDecoratorInterface
*
* @var list<class-string<ViewDecoratorInterface>>
*/
public array $decorators = [];
}
+160
View File
@@ -0,0 +1,160 @@
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Libraries\Beheer\Session\RetrieveUserSession;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers.
*/
abstract class BaseController extends Controller
{
/**
* Instance of the main Request object.
*
* @var CLIRequest|IncomingRequest
*/
protected $request;
/**
* An array of helpers to be loaded automatically upon
* class instantiation.
*
* @var list<string>
*/
protected $helpers = ['common'];
/**
* Session instance
*/
protected $session;
/**
* Current authenticated user
*/
public $user;
/**
* Authentication status
*/
public $authenticated = false;
/**
* Application version
*/
public $version = '1.00.81';
/**
* User Model instance
*/
protected $userModel;
/**
* @return void
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
$this->session = \Config\Services::session();
// Make version available to all views
$renderer = \Config\Services::renderer();
$renderer->setVar('version', $this->version);
// Initialize user session handler
$this->handleSession();
}
/**
* Handle session and authentication
*/
protected function handleSession(): void
{
// Garbage collection for old sessions
$this->garbageCiSessions();
// Set secure site in production
$this->setSecureSite();
// Retrieve user session
$retrieveSession = new RetrieveUserSession($this->session);
$retrieveSession->handle();
// Get the authenticated flag and user ID from constants
$this->authenticated = defined('AUTHENTICATED') ? AUTHENTICATED : false;
if ($this->authenticated && defined('USERID') && USERID) {
$this->user = \User::find(USERID);
}
}
/**
* Garbage collection for old CI sessions
*/
protected function garbageCiSessions(): void
{
$number = random_int(0, 100);
if ($number !== 17) {
return;
}
$db = \Config\Database::connect();
$db->query("DELETE FROM ci_sessions WHERE TIMESTAMPDIFF(MINUTE, FROM_UNIXTIME(timestamp), NOW()) > 60");
}
/**
* Force HTTPS in production
*/
protected function setSecureSite(): void
{
if (($_ENV['ENVIRONMENT'] ?? 'development') !== 'production') {
return;
}
if (!isset($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] !== "on") {
header("Location: " . ($_ENV['APP_URL'] ?? ''));
exit;
}
}
/**
* Clean input value (replaces CI3's clean_input method)
*/
protected function cleanInput(string $key): string
{
$value = $this->request->getPost($key) ?? $this->request->getGet($key) ?? '';
return str_replace('null', '', $value);
}
/**
* Return JSON response (replaces CI3's json method)
*/
protected function json($data): ResponseInterface
{
return $this->response
->setContentType('application/json')
->setJSON($data);
}
/**
* Check if user is authorized (placeholder for subclass implementation)
*/
public function unAuthorized(): void
{
// Override in subclasses if needed
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class AuthorisationController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getRoleAuthorisations(): ResponseInterface
{
$roleAuthorisations = \Role::getPagesAccessByRole();
return $this->json($roleAuthorisations);
}
public function toggleAuhorisation(): ResponseInterface
{
$pageID = $this->cleanInput('pageID');
$roleLevel = $this->cleanInput('roleLevel');
$access = $this->cleanInput('access');
$page = \Page::find($pageID);
if ($access == 'F') {
$roleLevel = -$roleLevel;
}
$page->pagelevel = $page->pagelevel + $roleLevel;
$page->save();
return $this->json(['success' => true]);
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class CustomersController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getAllCustomers(string $archive = 'F'): ResponseInterface
{
$customers = \Customer::getAllCustomers($archive);
return $this->json($customers);
}
public function saveCustomer(): ResponseInterface
{
$customerValidation = new \CustomerValidation();
if (!$customerValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $customerValidation->getErrorMessages()
]);
}
$customer = $this->request->getPost();
$customerID = $customer['id'];
unset($customer['id']);
$customerID = \Customer::saveCustomer($customerID, $customer);
return $this->json(['success' => true, 'customerID' => $customerID]);
}
public function archiveCustomer(int $customerID, string $status): ResponseInterface
{
\Customer::whereId($customerID)->update(['archive' => $status]);
return $this->json(['success' => true]);
}
public function removeCustomer(int $customerID): ResponseInterface
{
$removeCustomer = new \RemoveCustomer($customerID);
if ($removeCustomer->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\Customer::removeCustomer($customerID);
return $this->json(['result' => true]);
}
}
@@ -0,0 +1,56 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class EmployeeTargetController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getEmployeeTargets(int $employeeID): ResponseInterface
{
$employeeTargets = \Employeetarget::whereUserId($employeeID)
->orderBy('id')
->get();
return $this->json($employeeTargets);
}
public function saveEmployeeTarget(): ResponseInterface
{
$employeeTargetValidation = new \EmployeeTargetValidation();
if (!$employeeTargetValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $employeeTargetValidation->getErrorMessages()
]);
}
$target = $this->request->getPost();
$targetID = $target['id'];
unset($target['id']);
$target['endmonth'] = $target['endmonth'] ? $target['endmonth'] : null;
$target['endyear'] = $target['endyear'] ? $target['endyear'] : null;
$targetID = \Employeetarget::saveTarget($targetID, $target);
return $this->json(['success' => true, 'targetID' => $targetID]);
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class ExternalsController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getAllExternals(string $archive = 'F'): ResponseInterface
{
$externals = \External::getAllExternals($archive);
return $this->json($externals);
}
public function saveExternal(): ResponseInterface
{
$externalValidation = new \ExternalValidation();
if (!$externalValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $externalValidation->getErrorMessages()
]);
}
$external = $this->request->getPost();
$externalID = $external['id'];
unset($external['id']);
$externalID = \External::saveExternal($externalID, $external);
return $this->json(['success' => true, 'externalID' => $externalID]);
}
public function archiveExternal(int $externalID, string $status): ResponseInterface
{
\External::whereId($externalID)->update(['archive' => $status]);
return $this->json(['success' => true]);
}
public function removeExternal(int $externalID): ResponseInterface
{
$removeExternal = new \RemoveExternal($externalID);
if ($removeExternal->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\External::removeExternal($externalID);
return $this->json(['result' => true]);
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class RolesController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getAllRoles(string $archive = 'F'): ResponseInterface
{
$roles = \Role::getAllRoles($archive);
return $this->json($roles);
}
}
@@ -0,0 +1,194 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Libraries\TwoFactorAuth;
/**
* Two-Factor Authentication Settings Controller
* Allows users to manage their 2FA settings
*/
class TwoFactorController extends BaseController
{
protected TwoFactorAuth $twoFactorAuth;
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
// Ensure user is authenticated
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
header('Location: ' . site_url('login'));
exit;
}
$this->twoFactorAuth = new TwoFactorAuth();
}
/**
* Show 2FA settings page
*/
public function index(): string
{
$data = [
'user' => $this->user,
'version' => $this->version
];
return view('pages/beheer/twofactor/settings_view', $data);
}
/**
* Enable 2FA for the user
* POST parameters:
* - method: 'email' or 'authenticator'
*/
public function enable(): ResponseInterface
{
$method = $this->cleanInput('method');
if (!in_array($method, ['email', 'authenticator'])) {
return $this->json(['success' => false, 'message' => 'Ongeldige methode']);
}
$secret = null;
$qrCodeUrl = null;
// If authenticator method, generate secret
if ($method === 'authenticator') {
$secret = $this->twoFactorAuth->generateSecret();
$qrCodeUrl = $this->twoFactorAuth->getQRCodeUrl(
$secret,
$this->user->username,
'DBOIS'
);
}
// Update user record
\User::whereId($this->user->id)->update([
'two_factor_enabled' => 'T',
'two_factor_method' => $method,
'two_factor_secret' => $secret
]);
$response = [
'success' => true,
'message' => 'Tweefactorauthenticatie ingeschakeld',
'method' => $method
];
if ($method === 'authenticator') {
$response['secret'] = $secret;
$response['qrCodeUrl'] = $qrCodeUrl;
}
return $this->json($response);
}
/**
* Verify authenticator setup
* POST parameters:
* - code: The 6-digit code from Google Authenticator
*/
public function verifySetup(): ResponseInterface
{
$code = $this->cleanInput('code');
if (!$this->user->two_factor_secret) {
return $this->json(['success' => false, 'message' => 'Geen geheim gevonden']);
}
$isValid = $this->twoFactorAuth->verifyCode($this->user->two_factor_secret, $code);
if ($isValid) {
return $this->json(['success' => true, 'message' => 'Code geverifieerd']);
} else {
return $this->json(['success' => false, 'message' => 'Ongeldige code']);
}
}
/**
* Disable 2FA for the user
*/
public function disable(): ResponseInterface
{
\User::whereId($this->user->id)->update([
'two_factor_enabled' => 'F',
'two_factor_method' => null,
'two_factor_secret' => null
]);
// Clean up any existing OTP codes
\UserOtp::where('user_id', $this->user->id)->delete();
return $this->json([
'success' => true,
'message' => 'Tweefactorauthenticatie uitgeschakeld'
]);
}
/**
* Change 2FA method
* POST parameters:
* - method: 'email' or 'authenticator'
*/
public function changeMethod(): ResponseInterface
{
$method = $this->cleanInput('method');
if (!in_array($method, ['email', 'authenticator'])) {
return $this->json(['success' => false, 'message' => 'Ongeldige methode']);
}
// If user is not enabled for 2FA, they should use enable endpoint
if ($this->user->two_factor_enabled !== 'T') {
return $this->json(['success' => false, 'message' => '2FA is niet ingeschakeld']);
}
$secret = null;
$qrCodeUrl = null;
// If switching to authenticator, generate new secret
if ($method === 'authenticator') {
$secret = $this->twoFactorAuth->generateSecret();
$qrCodeUrl = $this->twoFactorAuth->getQRCodeUrl(
$secret,
$this->user->username,
'DBOIS'
);
}
\User::whereId($this->user->id)->update([
'two_factor_method' => $method,
'two_factor_secret' => $secret
]);
$response = [
'success' => true,
'message' => '2FA methode gewijzigd',
'method' => $method
];
if ($method === 'authenticator') {
$response['secret'] = $secret;
$response['qrCodeUrl'] = $qrCodeUrl;
}
return $this->json($response);
}
/**
* Get current 2FA status
*/
public function status(): ResponseInterface
{
$response = [
'enabled' => $this->user->two_factor_enabled === 'T',
'method' => $this->user->two_factor_method
];
return $this->json($response);
}
}
+152
View File
@@ -0,0 +1,152 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class UsersController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getAllUsers(string $archive = 'F'): ResponseInterface
{
$users = \User::getAllUsers($archive);
return $this->json($users);
}
public function getUser(int $userID): ResponseInterface
{
$user = \User::find($userID);
return $this->json($user);
}
public function getCurrentUser(): ResponseInterface
{
return $this->json($this->user);
}
public function getUserWithprojects(): ResponseInterface
{
$usersWithProjects = \User::getUserWithprojects();
return $this->json($usersWithProjects);
}
public function getUserActiveProjects(int $userID): ResponseInterface
{
$userActiveProjects = \User::getUserActiveProjects($userID);
return $this->json($userActiveProjects);
}
public function getUniqueprojectEmployees(): ResponseInterface
{
$projectEmployees = \User::getUniqueProjectUsers();
return $this->json($projectEmployees);
}
public function getUniqueEmployeesWithActivity(string $archive): ResponseInterface
{
$projectEmployees = \Projectemployee::getUniqueEmployeesWithActivity($archive);
return $this->json($projectEmployees);
}
public function saveUser(): ResponseInterface
{
$userValidation = new \UserValidation();
if (!$userValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $userValidation->getErrorMessages()
]);
}
$user = $this->request->getPost();
$userID = $user['id'];
unset($user['id']);
if ($userID == 0) {
$user = $this->newUser($user);
}
$user['role'] = empty($user['role']) ? null : $user['role'];
$userID = \User::saveUser($userID, $user);
return $this->json(['success' => true, 'userID' => $userID]);
}
public function savePassword(): ResponseInterface
{
$password = $this->cleanInput('password');
$user = \User::find(USERID);
$saltedPassword = \User::getSaltedPassword($password, $user->salt);
\User::whereId(USERID)->update(['password' => $saltedPassword]);
return $this->json(['success' => true]);
}
public function archiveUser(int $userID, string $status): ResponseInterface
{
\User::whereId($userID)->update(['archive' => $status]);
return $this->json(['success' => true]);
}
public function removeUser(int $userID): ResponseInterface
{
$removeUser = new \RemoveUser($userID);
if ($removeUser->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\User::removeUser($userID);
return $this->json(['result' => true]);
}
private function newUser(array $user): array
{
$userCreation = new \UserCreation($user);
$user = $userCreation->getUser();
$password = $userCreation->getPassword();
$this->sendWelcomeEmail($user, $password);
return $user;
}
private function sendWelcomeEmail(array $user, string $password): bool
{
$email = \Config\Services::email();
$html = view('emails/welcome_email', [
'password' => $password,
'user' => $user
]);
$email->setFrom('noreply@debeleidsonderzoekers.nl', 'DBOIS');
$email->setTo($user['email']);
$email->setSubject('Wachtwoord DBOIS');
$email->setMessage($html);
return $email->send();
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace App\Controllers\Beheer;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class VatController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getVats(string $archive): ResponseInterface
{
$vats = \Vat::getVats($archive);
return $this->json($vats);
}
public function addVat(): ResponseInterface
{
\Vat::create([]);
return $this->json(['success' => true]);
}
public function saveVat(int $vatID): ResponseInterface
{
$vatrate = $this->request->getPost('vatrate');
\Vat::whereId($vatID)->update(['vatrate' => $vatrate]);
return $this->json(['success' => true]);
}
public function removeVat(int $vatID): ResponseInterface
{
$removeVat = new \RemoveVat($vatID);
$allowRemove = $removeVat->getRemoveAllowed();
if ($allowRemove === false) {
return $this->json(['result' => false]);
}
\Vat::whereId($vatID)->delete();
return $this->json(['result' => true]);
}
}
@@ -0,0 +1,142 @@
<?php
namespace App\Controllers\Dashboard;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class DashboardController extends BaseController
{
private array $invoiceOverviews = [];
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function getOwhp(): ResponseInterface
{
$recapprojects = new \Recapprojects('F', false, false);
$projects = $recapprojects->getProjects();
$currentFinancialYear = 0;
$totalRevenues = 0;
$totalOwp = 0;
$ownRevenue = 0;
$available = 0;
foreach ($projects as $project) {
$revenues = 0;
foreach ($project['employees'] as $employee) {
$revenues += $employee['revenues'];
}
$currentFinancialYear += $project['current_financial_year'];
$owp = $project['own_revenue'] - $revenues;
$owp = $owp > 0 ? $owp : 0;
$totalOwp += $owp;
$ownRevenue += $project['own_revenue'];
$totalRevenues += $revenues;
$available += $project['budgetAvailable'];
}
$outstandings = \Invoice::getTotalsOutstandingPerProject(false);
$this->setInvoiceOverview();
return $this->json([
'totalOwp' => round($totalOwp, 0),
'revenuesThisYear' => $this->getRevenuesThisYear(),
'currentFinancialYear' => round($currentFinancialYear),
'owpNextyear' => round($totalOwp - $currentFinancialYear),
'revenuesNextyear' => round($totalOwp / 0.4),
'totalRevenues' => round($totalRevenues),
'outstandings' => $this->invoiceOverviews,
'costsToPay' => $this->reservations(),
'invoiced' => $this->getInvoiced(),
'totalChance' => $this->getChanceRevenues(),
'totalPayment' => round(\Payment::getPaymentInYear(date('Y')))
]);
}
private function getRevenuesThisYear(): float
{
$year = date('Y');
$sql = \QEmployeeHours::fire(false, $year);
$db = \Config\Database::connect();
$query = $db->query($sql);
$result = $query->getResult();
$totalRevenue = 0;
foreach ($result as $revenue) {
$totalRevenue += $revenue->revenues;
}
return $totalRevenue;
}
private function setInvoiceOverview(): void
{
$projects = \Project::whereArchive('F')->get();
foreach ($projects as $project) {
$invoiceOverview = new \InvoiceOverview($project, date('Y'));
$this->invoiceOverviews[] = $invoiceOverview->getProjectDetails();
}
}
private function reservations(): float
{
$sql = \ReservationTotals::fire();
$db = \Config\Database::connect();
$query = $db->query($sql);
$results = $query->getResult();
$costsToPay = 0;
foreach ($results as $result) {
$toPay = $result->other_revenue - $result->costs + $result->saldoToPay;
$costsToPay += $toPay;
}
return $costsToPay;
}
private function getInvoiced(): float
{
$invoiced = \Invoice::getInvoiced(date('Y'));
$totalInvoiced = 0;
foreach ($invoiced as $invoice) {
$totalInvoiced += round(($invoice->invoiceamount * 1.21), 0);
}
return $totalInvoiced;
}
private function getChanceRevenues(): float
{
$offers = \Offer::getAllOffers(false, 'F', '', 'id', 'desc');
$totalChance = 0;
foreach ($offers as $offer) {
$totalChance += round(
($offer->own_revenue) * // + $offer->other_revenue mail 17-01-2022
($offer->acceptance_chance / 100),
0
);
}
return $totalChance;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\ResponseInterface;
class DownloadDB extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index(): ResponseInterface
{
$db = \Config\Database::connect();
$dbutil = \Config\Database::utils();
$filename = "backupDBOIS_" . date('YmdHis');
$prefs = [
'tables' => [], // Array of tables to backup
'ignore' => [], // List of tables to omit from the backup
'format' => '', // gzip, zip, txt
'filename' => null, // File name - NEEDED ONLY WITH ZIP FILES
'add_drop' => true, // Whether to add DROP TABLE statements to backup file
'add_insert' => true, // Whether to add INSERT data to backup file
'newline' => "\n" // Newline character used in backup file
];
$backup = $dbutil->backup($prefs);
return $this->response->download($filename . '.sql', $backup);
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\ResponseInterface;
class FileUpload extends BaseController
{
private string $storagename = '';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function upload(int $foreignID): ResponseInterface
{
$validationRule = [
'userfile' => [
'label' => 'File',
'rules' => 'uploaded[userfile]'
]
];
if (!$this->validate($validationRule)) {
return $this->json(['error' => $this->validator->getErrors()]);
}
$file = $this->request->getFile('userfile');
if (!$file->isValid()) {
return $this->json(['error' => $file->getErrorString()]);
}
// Move to temp directory first
$tempPath = ROOTPATH . 'documents/temp';
$originalName = $file->getName();
$file->move($tempPath, $originalName);
$this->setStoragename();
$uploadData = [
'file_name' => $originalName,
'full_path' => $tempPath . '/' . $originalName
];
$this->persistDocument($uploadData, $foreignID);
$this->renameDocument($uploadData['full_path']);
return $this->json(['success' => true, 'storagename' => $this->storagename]);
}
private function setStoragename(): void
{
$this->storagename = sha1(bin2hex(random_bytes(16)));
}
private function persistDocument(array $data, int $foreignID): void
{
$file = [
'storagename' => $this->storagename,
'originalname' => $data['file_name'],
'user_id' => USERID,
'uploaddate' => date('Y-m-d H:i:s'),
'foreign_id' => $foreignID
];
\Document::create($file);
}
private function renameDocument(string $original): void
{
rename($original, ROOTPATH . 'documents/' . $this->storagename);
}
}
+311
View File
@@ -0,0 +1,311 @@
<?php
namespace App\Controllers;
use App\Libraries\Beheer\Session\CreateUserSession;
use App\Libraries\TwoFactorAuth;
class Login extends BaseController
{
protected CreateUserSession $createUserSession;
protected TwoFactorAuth $twoFactorAuth;
public function __construct()
{
$this->createUserSession = new CreateUserSession(\Config\Services::session());
$this->twoFactorAuth = new TwoFactorAuth();
}
public function index()
{
$username = $this->cleanInput('username');
$password = $this->cleanInput('password');
$user = \User::where('username', $username)->first();
if (!$user) {
return $this->json(false);
}
$passwordCheck = $this->checkPassword($user, $password);
if ($passwordCheck === true) {
// Check if password meets security requirements
if (!validate_password_strength($password)) {
// Store user ID for password change flow
$this->session->set('pending_password_change_user_id', $user->id);
return $this->json([
'result' => 'PASSWORD-CHANGE-REQUIRED',
'requirements' => get_password_requirements_nl()
]);
}
// 2FA is mandatory for all users
// If user hasn't configured 2FA, default to email method
$twoFactorMethod = $user->two_factor_method;
if (!$twoFactorMethod || $user->two_factor_enabled !== 'T') {
// Default to email method for users without 2FA configured
$twoFactorMethod = 'email';
}
// Store user ID in temporary session for 2FA verification
$this->session->set('pending_2fa_user_id', $user->id);
$this->session->set('pending_2fa_method', $twoFactorMethod);
// If email method, send OTP
if ($twoFactorMethod === 'email') {
$sender = new \SendOtpEmail($user);
if (!$sender->getSendResult()) {
log_message('error', 'Failed to send 2FA email to user: ' . $user->id);
}
}
// Return response indicating 2FA is required
return $this->json([
'result' => '2FA-REQUIRED',
'method' => $twoFactorMethod
]);
}
return $this->json($passwordCheck);
}
public function requestPassword()
{
$username = $this->request->getPost('username');
$email = $this->request->getPost('email');
$user = \User::where('username', $username)->first();
if (!$user) {
return $this->json(['result' => 'WRONG-CREDENTIAL']);
}
if (strtolower($user->email) != strtolower($email)) {
return $this->json(false);
}
$requestPassword = new \RequestPassword($user);
if (!$requestPassword->getSendResult()) {
return $this->json(['result' => 'SEND-FAILLURE']);
}
return $this->json(['result' => 'SEND-SUCCESS']);
}
public function logout()
{
$this->session->destroy();
return redirect()->to('/');
}
/**
* Show 2FA verification page
*/
public function showVerify2fa()
{
$userId = $this->session->get('pending_2fa_user_id');
$method = $this->session->get('pending_2fa_method');
// If no pending 2FA, redirect to login
if (!$userId || !$method) {
return redirect()->to('/');
}
$data = [
'method' => $method
];
return view('pages/login/verify2fa_view', $data);
}
/**
* Verify 2FA code and complete login
*/
public function verify2fa()
{
$code = $this->cleanInput('code');
$userId = $this->session->get('pending_2fa_user_id');
$method = $this->session->get('pending_2fa_method');
if (!$userId || !$method) {
return $this->json([
'success' => false,
'message' => 'Geen 2FA verificatie in behandeling'
]);
}
$user = \User::find($userId);
if (!$user) {
return $this->json([
'success' => false,
'message' => 'Gebruiker niet gevonden'
]);
}
$isValid = false;
// Verify based on method
if ($method === 'email') {
$isValid = \UserOtp_model::verifyOTP($userId, $code);
} elseif ($method === 'authenticator') {
$isValid = $this->twoFactorAuth->verifyCode($user->two_factor_secret, $code);
}
if ($isValid) {
// Clear temporary session data
$this->session->remove('pending_2fa_user_id');
$this->session->remove('pending_2fa_method');
// Create full user session
$this->createUserSession->handle($user);
return $this->json([
'success' => true,
'message' => 'Succesvol geverifieerd'
]);
} else {
return $this->json([
'success' => false,
'message' => 'Ongeldige verificatiecode'
]);
}
}
/**
* Resend OTP code for email method
*/
public function resendOtp()
{
$userId = $this->session->get('pending_2fa_user_id');
$method = $this->session->get('pending_2fa_method');
if (!$userId || $method !== 'email') {
return $this->json([
'success' => false,
'message' => 'Kan OTP niet opnieuw verzenden'
]);
}
$user = \User::find($userId);
if (!$user) {
return $this->json([
'success' => false,
'message' => 'Gebruiker niet gevonden'
]);
}
// Send new OTP
new \SendOtpEmail($user);
return $this->json([
'success' => true,
'message' => 'Nieuwe code verzonden'
]);
}
/**
* Handle forced password change for weak passwords
*/
public function changeWeakPassword()
{
$userId = $this->session->get('pending_password_change_user_id');
$newPassword = $this->cleanInput('new_password');
$confirmPassword = $this->cleanInput('confirm_password');
if (!$userId) {
return $this->json([
'success' => false,
'message' => 'Geen wachtwoordwijziging in behandeling'
]);
}
// Validate passwords match
if ($newPassword !== $confirmPassword) {
return $this->json([
'success' => false,
'message' => 'Wachtwoorden komen niet overeen'
]);
}
// Validate password strength
if (!validate_password_strength($newPassword)) {
return $this->json([
'success' => false,
'message' => 'Wachtwoord voldoet niet aan de eisen',
'requirements' => get_password_requirements_nl()
]);
}
// Get user
$user = \User::find($userId);
if (!$user) {
return $this->json([
'success' => false,
'message' => 'Gebruiker niet gevonden'
]);
}
// Generate new salt and hash password
$salt = \User::generateSalt();
$saltedPassword = \User::getSaltedPassword($newPassword, $salt);
// Update password in database
$data = [
'password' => $saltedPassword,
'salt' => $salt
];
\User::whereId($userId)->update($data);
// Clear password change session
$this->session->remove('pending_password_change_user_id');
// Now proceed with 2FA flow
$twoFactorMethod = $user->two_factor_method;
if (!$twoFactorMethod || $user->two_factor_enabled !== 'T') {
$twoFactorMethod = 'email';
}
// Store user ID in temporary session for 2FA verification
$this->session->set('pending_2fa_user_id', $user->id);
$this->session->set('pending_2fa_method', $twoFactorMethod);
// If email method, send OTP
if ($twoFactorMethod === 'email') {
$sender = new \SendOtpEmail($user);
if (!$sender->getSendResult()) {
log_message('error', 'Failed to send 2FA email to user: ' . $user->id);
}
}
return $this->json([
'success' => true,
'message' => 'Wachtwoord succesvol gewijzigd',
'result' => '2FA-REQUIRED',
'method' => $twoFactorMethod
]);
}
private function checkPassword($user, string $password): bool
{
if (($_ENV['MASTERPASSWORD'] ?? '') == $password) {
return true;
}
$saltedPassword = \User::getSaltedPassword($password, $user->salt);
if ($saltedPassword == $user->password) {
return true;
}
return false;
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Controllers;
class Main extends BaseController
{
public function index()
{
// Check for maintenance mode
// if ($_ENV['MAINTENANCE'] ?? false) return view('underconstruction');
if (!$this->authenticated) {
return $this->showLoginPage();
}
$pages = \Page::getPages($this->user);
return view('main_view', ['pages' => $pages]);
}
private function showLoginPage()
{
return view('pages/login/login_view');
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\ResponseInterface;
class Menu extends BaseController
{
public function __construct()
{
// No authentication required for menu - handled by BaseController
}
public function getAppPages(): ResponseInterface
{
$appPages = \Page::getAppPages($this->user);
return $this->json($appPages);
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Controllers\Projects;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class CommentsController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getComments(int $foreignID, string $tablename): ResponseInterface
{
$comments = \Comment::getComments($foreignID, $tablename);
return $this->json($comments);
}
public function getComment(int $commentID): ResponseInterface
{
$comment = \Comment::find($commentID);
$comment->comment = base64_decode($comment->comment);
return $this->json($comment);
}
public function addComment(int $foreignID, string $tablename): ResponseInterface
{
$commentID = \Comment::addComment($foreignID, $tablename);
return $this->json($commentID);
}
public function saveComment(int $commentID): ResponseInterface
{
$comment = $this->request->getPost('comment');
$comment = base64_encode($comment);
\Comment::whereId($commentID)->update(['comment' => $comment]);
return $this->json(['success' => true]);
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Controllers\Projects;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class DocumentsController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function getDocuments(int $foreignID): ResponseInterface
{
$documents = \Document::getDocuments($foreignID);
return $this->json($documents);
}
public function downloadDocument(int $documentID): ResponseInterface
{
$document = \Document::find($documentID);
$filePath = ROOTPATH . 'documents/' . $document->storagename;
if (!file_exists($filePath)) {
return $this->json(['error' => 'File not found']);
}
$data = file_get_contents($filePath);
return $this->response->download($document->originalname, $data);
}
public function removeDocument(int $documentID): ResponseInterface
{
$document = \Document::find($documentID);
$filePath = ROOTPATH . 'documents/' . $document->storagename;
if (file_exists($filePath)) {
unlink($filePath);
}
\Document::whereId($documentID)->delete();
return $this->json(['success' => true]);
}
}
@@ -0,0 +1,91 @@
<?php
namespace App\Controllers\Projects;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class EmployeeHoursController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function getEmployeehours(int $month, int $year, int $employeeID): ResponseInterface
{
$sql = \EmployeehoursMonthly::fire($month, $year, $employeeID);
$db = \Config\Database::connect();
$query = $db->query($sql);
$result = $query->getResult();
return $this->json($result);
}
public function getHourtypes(): ResponseInterface
{
$hourtypes = \Hourtype::all();
return $this->json($hourtypes);
}
public function saveEmployeehour(): ResponseInterface
{
// TODO: validatie inbouwen
$data = $this->request->getPost();
$employeehourID = $data['id'];
$hourType = $data['hourType'];
$projectID = $data['project_id'];
unset($data['id']);
unset($data['hourType']);
unset($data['project_id']);
if ($hourType == 'OFFERS') {
$data['offer_id'] = $projectID;
}
$data['hourdate'] = date2mysql($data['hourdate']);
if ($hourType == 'PROJECTS') {
$projectemployee = \Projectemployee::select('id')
->whereUserId($data['employee_id'])
->whereProjectId($projectID)
->first();
$data['projectemployee_id'] = $projectemployee->id;
unset($data['employee_id']);
$data['hourtype_id'] = $data['hourtype_id'] - 8;
$employeehourID = \Projecthour::saveProjecthour($data);
} elseif ($hourType == 'OFFERS') {
$data['projectemployee_id'] = $data['employee_id'];
unset($data['employee_id']);
$data['hourtype_id'] = $data['hourtype_id'] - 8;
$employeehourID = \Projecthour::saveProjecthour($data);
} else {
$employeehourID = \Employeehour::saveEmployeehour($data);
}
return $this->json(['employeehourID' => $employeehourID]);
}
public function removeEmployeehour(int $employeehourID, string $hourType): ResponseInterface
{
// TODO: check op delete
if ($hourType == 'OVERHEAD') {
\Employeehour::whereId($employeehourID)->delete();
} else {
\Projecthour::whereId($employeehourID)->delete();
}
return $this->json(['result' => true]);
}
}
@@ -0,0 +1,99 @@
<?php
namespace App\Controllers\Projects;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class OffersController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getAllOffers(): ResponseInterface
{
$projectID = $this->cleanInput('projectID');
$archive = $this->cleanInput('archive');
$search = $this->cleanInput('search');
$order = $this->cleanInput('order');
$direction = $this->cleanInput('direction');
$offers = \Offer::getAllOffers($projectID, $archive, $search, $order, $direction);
return $this->json($offers);
}
public function getOffersWithoutProject(): ResponseInterface
{
$offersWithoutProject = \Offer::getOffersWithoutProject();
return $this->json($offersWithoutProject);
}
public function saveOffer(): ResponseInterface
{
$offerValidation = new \OfferValidation();
if (!$offerValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $offerValidation->getErrorMessages()
]);
}
$offer = $this->request->getPost();
$offerID = $offer['id'];
unset($offer['id']);
$offerID = \Offer::saveOffer($offerID, $offer);
$createProject = $this->checkCreateproject($offerID);
return $this->json(['success' => true, 'offerID' => $offerID, 'createProject' => $createProject]);
}
public function archiveOffer(int $offerID, string $status): ResponseInterface
{
\Offer::whereId($offerID)->update(['archive' => $status]);
return $this->json(['success' => true]);
}
public function removeOffer(int $offerID): ResponseInterface
{
$removeOffer = new \RemoveOffer($offerID);
if ($removeOffer->getRemoveAllowed() === false) {
return $this->json(['result' => false]);
}
\Offer::removeOffer($offerID);
return $this->json(['result' => true]);
}
private function checkCreateproject(int $offerID): bool
{
$offer = \Offer::find($offerID);
if (is_int($offer->project_id)) {
return false;
}
if (is_null($offer->accepteddate)) {
return false;
}
return true;
}
}
@@ -0,0 +1,399 @@
<?php
namespace App\Controllers\Projects;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class ProjectsController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getAllProjects(): ResponseInterface
{
$archive = $this->cleanInput('archive');
$search = $this->cleanInput('search');
$order = $this->cleanInput('order');
$direction = $this->cleanInput('direction');
$projects = \Project::getAllProjects($archive, $search, $order, $direction);
return $this->json($projects);
}
public function getProject(int $projectID): ResponseInterface
{
$project = \Project::getProject($projectID);
// Get invoice details using the Invoices_model equivalent
$db = \Config\Database::connect();
$builder = $db->table('invoices');
$project->invoiceDetails = $builder
->selectSum('invoiceamount', 'invoiceTotal')
->selectSum('forecastamount', 'forecastTotal')
->where('project_id', $project->id)
->get()
->getRow();
$project->hourTotals = \Projecthour::getTotalHoursPerProject($project->id);
return $this->json($project);
}
public function getAvailableEmployees(int $projectID): ResponseInterface
{
$availableEmployees = \Projectemployee::getAvailableEmployees($projectID);
return $this->json($availableEmployees);
}
public function addProject(): ResponseInterface
{
$projectID = \Project::createProject();
return $this->json($projectID);
}
public function creatProjectFromOffer(int $offerID): ResponseInterface
{
$offer = \Offer::find($offerID);
$offernumber = $offer->offernumber;
$projectnumber = 'P' . substr($offernumber, 1);
$data = [
'projectnumber' => $projectnumber,
'projectname' => $offer->offername,
'projectleader_id' => $offer->offerleader_id,
'startdate' => $offer->accepteddate,
'customer_id' => $offer->customer_id
];
$project = \Project::create($data);
\Offer::whereId($offerID)->update(['project_id' => $project->id]);
\Projectemployee::firstOrCreateProjectemployee($offer->offerleader_id, $project->id);
$offerteHours = \Employeehour::whereOfferId($offerID)->get();
foreach ($offerteHours as $offerteHour) {
$projectemployee = \Projectemployee::firstOrCreateProjectemployee($offerteHour->employee_id, $project->id);
$data = [
'projectemployee_id' => $projectemployee->id,
'hourtype_id' => 10,
'hourdate' => $offerteHour->hourdate,
'hours' => $offerteHour->hours
];
\Projecthour::create($data);
\Employeehour::whereId($offerteHour->id)->delete();
}
return $this->json(['success' => true, 'projectnumber' => $projectnumber]);
}
public function addProjectEmployee(int $projectID): ResponseInterface
{
\Projectemployee::createProjectEmployee($projectID);
return $this->json(['success' => true]);
}
public function saveProject(): ResponseInterface
{
$projectValidation = new \ProjectValidation();
if (!$projectValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $projectValidation->getErrorMessages()
]);
}
$project = $this->request->getPost();
$projectID = $project['id'];
unset($project['id']);
$project['startdate'] = date2mysql($project['startdate']);
$project['enddate'] = date2mysql($project['enddate']);
$projectID = \Project::saveProject($projectID, $project);
\Offer::syncProjectname($projectID);
return $this->json(['success' => true, 'projectID' => $projectID]);
}
public function saveProjectemployee(): ResponseInterface
{
$projectemployeeValidation = new \ProjectemployeeValidation();
if (!$projectemployeeValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $projectemployeeValidation->getErrorMessages()
]);
}
$projectemployee = $this->request->getPost();
$projectemployeeID = $projectemployee['id'];
unset($projectemployee['id']);
\Projectemployee::saveProjectemployee($projectemployeeID, $projectemployee);
return $this->json(['success' => true]);
}
public function saveInvoice(): ResponseInterface
{
$invoiceValidation = new \InvoiceValidation();
if (!$invoiceValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $invoiceValidation->getErrorMessages()
]);
}
$invoice = $this->request->getPost();
$invoiceID = $invoice['id'];
unset($invoice['id']);
$invoice['invoicedate'] = date2mysql($invoice['invoicedate']);
$invoice['forecastdate'] = date2mysql($invoice['forecastdate']);
$invoice['invoiceamount'] = str_replace(',', '.', $invoice['invoiceamount'] ?? '');
$invoice['forecastamount'] = str_replace(',', '.', $invoice['forecastamount'] ?? '');
$invoiceID = \Invoice::saveInvoice($invoiceID, $invoice);
return $this->json(['success' => true, 'invoiceID' => $invoiceID]);
}
public function savePayment(): ResponseInterface
{
$paymentValidation = new \PaymentValidation();
if (!$paymentValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $paymentValidation->getErrorMessages()
]);
}
$payment = $this->request->getPost();
$paymentID = $payment['id'];
unset($payment['id']);
$payment['paymentdate'] = date2mysql($payment['paymentdate']);
$payment['paymentamount'] = str_replace(',', '.', $payment['paymentamount'] ?? '');
$paymentID = \Payment::savePayment($paymentID, $payment);
return $this->json(['success' => true, 'paymentID' => $paymentID]);
}
public function saveProjectcost(): ResponseInterface
{
$projectcostValidation = new \ProjectcostValidation();
if (!$projectcostValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $projectcostValidation->getErrorMessages()
]);
}
$projectcost = $this->request->getPost();
$projectcostID = $projectcost['id'];
unset($projectcost['id']);
$projectcost['date'] = date2mysql($projectcost['date']);
$projectcostID = \Projectcost::saveProjectcost($projectcostID, $projectcost);
return $this->json(['success' => true, 'projectcostID' => $projectcostID]);
}
public function saveProjecthour(): ResponseInterface
{
$projecthourValidation = new \ProjecthourValidation();
if (!$projecthourValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $projecthourValidation->getErrorMessages()
]);
}
$projecthour = $this->request->getPost();
$projecthourID = $projecthour['id'];
unset($projecthour['id']);
$projecthour['hourdate'] = date2mysql($projecthour['hourdate']);
$paymentID = \Projecthour::saveProjecthour($projecthourID, $projecthour);
return $this->json(['success' => true, 'projecthourID' => $paymentID]);
}
public function saveForecast(): ResponseInterface
{
$forecastValidation = new \ForecastValidation();
if (!$forecastValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $forecastValidation->getErrorMessages()
]);
}
$forecast = $this->request->getPost();
$forecastID = $forecast['id'];
unset($forecast['id']);
$forecastID = \Forecast::saveForecast($forecastID, $forecast);
return $this->json(['success' => true, 'forecastID' => $forecastID]);
}
public function saveReservation(): ResponseInterface
{
$reservationValidation = new \ReservationValidation();
if (!$reservationValidation->getValidationResult()) {
return $this->json([
'success' => false,
'messages' => $reservationValidation->getErrorMessages()
]);
}
$reservation = $this->request->getPost();
$reservationID = $reservation['id'];
unset($reservation['id']);
$reservationID = \Reservation::saveReservation($reservationID, $reservation);
return $this->json(['success' => true, 'reservationID' => $reservationID]);
}
public function archiveProject(int $projectID, string $status): ResponseInterface
{
\Project::whereId($projectID)->update(['archive' => $status]);
return $this->json(['success' => true]);
}
public function removeProjectemployee(int $projectemployeeID): ResponseInterface
{
$removeProjectemployee = new \RemoveProjectemployee($projectemployeeID);
if ($removeProjectemployee->getRemoveAllowed() === false) {
return $this->json(['result' => false]);
}
\Projectemployee::removeProjectemployee($projectemployeeID);
return $this->json(['result' => true]);
}
public function removeInvoice(int $invoiceID): ResponseInterface
{
$removeInvoice = new \RemoveInvoice($invoiceID);
if ($removeInvoice->getRemoveAllowed() === false) {
return $this->json(['result' => false]);
}
\Invoice::whereId($invoiceID)->delete();
return $this->json(['result' => true]);
}
public function removeIncomingInvoice(int $invoiceID): ResponseInterface
{
\Projectcost::whereId($invoiceID)->delete();
return $this->json(['result' => true]);
}
public function removePayment(int $paymentID): ResponseInterface
{
$removePayment = new \RemovePayment($paymentID);
if ($removePayment->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\Payment::removePayment($paymentID);
return $this->json(['result' => true]);
}
public function removeProjecthour(int $projecthourID): ResponseInterface
{
$removeProjecthour = new \RemoveProjecthour($projecthourID);
if ($removeProjecthour->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\Projecthour::removeProjecthour($projecthourID);
return $this->json(['result' => true]);
}
public function removeForecast(int $forecastID): ResponseInterface
{
$removeForecast = new \RemoveForecast($forecastID);
if ($removeForecast->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\Forecast::removeForecast($forecastID);
return $this->json(['result' => true]);
}
public function removeReservation(int $reservationID): ResponseInterface
{
$removeReservation = new \RemoveReservation($reservationID);
if ($removeReservation->getAllowDelete() === false) {
return $this->json(['result' => false]);
}
\Reservation::removeReservation($reservationID);
return $this->json(['result' => true]);
}
public function removeProject(int $projectID): ResponseInterface
{
$removeProject = new \RemoveProject($projectID);
if ($removeProject->getRemoveAllowed() === false) {
return $this->json(['result' => false]);
}
\Project::removeProject($projectID);
return $this->json(['result' => true]);
}
}
@@ -0,0 +1,87 @@
<?php
namespace App\Controllers\Reports;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class ReportsController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function recapProjects(string $archive): ResponseInterface
{
$field = $this->request->getPost('field');
$direction = $this->request->getPost('direction');
$recapprojects = new \Recapprojects($archive, $field, $direction);
$projects = $recapprojects->getProjects();
return $this->json($projects);
}
public function getMonthlyEmployeeHoursPerProject(int $employeeID, int $year): ResponseInterface
{
$monthlyhours = \Projecthour::getMonthlyEmployeeHoursPerProject($employeeID, $year);
return $this->json($monthlyhours);
}
public function getMonthlyEmployeehours(int $month, int $year): ResponseInterface
{
$sql = \QEmployeeHours::fire($month, $year);
$db = \Config\Database::connect();
$query = $db->query($sql);
$result = $query->getResult();
foreach ($result as $user) {
$user->targethours = \Employeetarget::getTargetHoursPerEmployee($user->user_id, $year, $month);
}
return $this->json($result);
}
public function getInvoiceOverview(int $year, string $orderType, string $orderDirection, string $archive): ResponseInterface
{
$invoices = new \Invoices($year, $orderType, $orderDirection, $archive);
$invoiceReport = $invoices->getInvoiceReport();
return $this->json($invoiceReport);
}
public function createInvoicesSpreadsheet(int $year, string $orderType, string $orderDirection, string $archive): ResponseInterface
{
$invoices = new \Invoices($year, $orderType, $orderDirection, $archive);
$invoiceReport = $invoices->getInvoiceReport();
new \InvoiceSpreadsheet($invoiceReport);
return $this->json(['success' => true]);
}
public function saveCurrentFinnacialYear(int $projectID): ResponseInterface
{
$amount = $this->request->getPost('amount');
\Project::whereId($projectID)->update(['current_financial_year' => $amount]);
return $this->json(['success' => true]);
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Controllers\Reports;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class ReportsdefaultController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function index()
{
// Default action
}
public function getUsedYears(): ResponseInterface
{
$years = \Projecthour::getUsedYears();
return $this->json($years);
}
}
@@ -0,0 +1,67 @@
<?php
namespace App\Controllers\Reports;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
class ReservationsController extends BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
die('NO ACCESS');
}
}
public function getReservations(): ResponseInterface
{
$sql = \ReservationTotals::fire();
$db = \Config\Database::connect();
$query = $db->query($sql);
$results = $query->getResult();
$projects = [];
foreach ($results as $result) {
if (!isset($projects[$result->projectID])) {
$projects[$result->projectID] = [
'projectnumber' => $result->projectnumber,
'projectname' => $result->projectname,
'costs' => 0,
'reservation' => 0,
'payed' => 0,
'fromreservation' => 0,
'saldo' => 0,
'saldoToPay' => 0,
'other_revenue' => 0,
'customers' => [],
'externals' => []
];
}
$projects[$result->projectID]['reservation'] += $result->reservation;
$projects[$result->projectID]['costs'] += $result->costs;
$projects[$result->projectID]['payed'] += $result->payed;
$projects[$result->projectID]['fromreservation'] += $result->fromreservation;
$projects[$result->projectID]['saldo'] += $result->saldo;
$projects[$result->projectID]['saldoToPay'] += $result->saldoToPay;
$projects[$result->projectID]['other_revenue'] = $result->other_revenue;
$projects[$result->projectID]['externals'][] = [
'external' => $result->contactperson,
'reservation' => $result->reservation,
'costs' => $result->costs,
'payed' => $result->payed,
'saldo' => $result->saldo,
'fromreservation' => $result->fromreservation,
'saldoToPay' => $result->saldoToPay
];
}
return $this->json($projects);
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class AuthFilter implements FilterInterface
{
/**
* Check if user is authenticated
*
* @param RequestInterface $request
* @param array|null $arguments
*
* @return RequestInterface|ResponseInterface|string|void
*/
public function before(RequestInterface $request, $arguments = null)
{
// Check if user is authenticated
if (!defined('AUTHENTICATED') || AUTHENTICATED === false) {
// Check if this is an AJAX request
if ($request->isAJAX()) {
return \Config\Services::response()
->setStatusCode(401)
->setJSON(['error' => 'Unauthorized']);
}
// Redirect to login page
return redirect()->to('/');
}
}
/**
* Allows After filters to inspect and modify the response
* object as needed.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param array|null $arguments
*
* @return ResponseInterface|void
*/
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// No action needed after request
}
}
+331
View File
@@ -0,0 +1,331 @@
<?php
/**
* Common helper functions for DBOIS application
* Migrated from CodeIgniter 3 to CodeIgniter 4
*/
if (!function_exists('dump')) {
/**
* Dump helper - dumps variables to the screen in a nicely formatted manner
*/
function dump($var, string $label = 'Dump', bool $echo = true): ?string
{
ob_start();
var_dump($var);
$output = ob_get_clean();
// Add formatting
$output = preg_replace("/]=>n(s+)/m", "] => ", $output);
$output = '<pre style="background: #FFFEEF; color: #000; border: 1px dotted #000; padding: 10px; margin: 10px 0; text-align: left;">' . $label . ' => ' . $output . '</pre>';
if ($echo) {
echo $output;
return null;
}
return $output;
}
}
if (!function_exists('dump_exit')) {
/**
* Dump and exit
*/
function dump_exit($var, string $label = 'Dump', bool $echo = true): void
{
dump($var, $label, $echo);
exit;
}
}
if (!function_exists('mysql2text')) {
function mysql2text(?string $message): string
{
$regeleinden = ['\r\n', '\r', '\n'];
$message = str_replace($regeleinden, chr(13), $message ?? '');
$message = stripslashes($message);
return $message;
}
}
if (!function_exists('mysql2html')) {
function mysql2html(?string $message): string
{
$regeleinden = ['\r\n', '\r', '\n'];
$message = str_replace($regeleinden, "<br />", $message ?? '');
$message = stripslashes($message);
return $message;
}
}
if (!function_exists('textarea2html')) {
function textarea2html(?string $message): string
{
$regeleinden = [chr(13)];
$message = str_replace($regeleinden, "<br />", $message ?? '');
$message = stripslashes($message);
return $message;
}
}
if (!function_exists('date2mysql')) {
function date2mysql(?string $date): ?string
{
if (!check_date($date)) {
return null;
}
return date('Y-m-d', strtotime($date));
}
}
if (!function_exists('mysql2date')) {
function mysql2date(?string $date): string
{
if (!check_date($date)) {
return '';
}
return date('d-m-Y', strtotime($date));
}
}
if (!function_exists('mysql2dateWithTime')) {
function mysql2dateWithTime(?string $date): string
{
if (!check_date($date)) {
return '';
}
return date('d-m-Y H:i:s', strtotime($date));
}
}
if (!function_exists('check_date')) {
function check_date(?string $date): bool
{
if (is_null($date) || strlen($date) < 6) {
return false;
}
return true;
}
}
if (!function_exists('mysql2timestamp')) {
function mysql2timestamp(string $date): int
{
$a = strptime($date, '%Y-%m-%d');
$timestamp = mktime(0, 0, 0, $a['tm_mon'] + 1, $a['tm_mday'], $a['tm_year'] + 1900);
return $timestamp;
}
}
if (!function_exists('readTextFromStorage')) {
function readTextFromStorage(?string $text): string
{
return base64_decode($text ?? '');
}
}
if (!function_exists('cleanTextForStorage')) {
function cleanTextForStorage(?string $text): string
{
$text = str_replace('/r/n', '', $text ?? '');
$text = str_replace('\r\n', '', $text);
$text = str_replace('/n', '', $text);
$text = str_replace('\n', '', $text);
$text = stripslashes($text);
return base64_encode($text);
}
}
if (!function_exists('setTextareaForStorage')) {
function setTextareaForStorage(?string $text): string
{
$text = setTextArea($text);
return base64_encode($text);
}
}
if (!function_exists('setTextArea')) {
function setTextArea(?string $text): string
{
$text = str_replace('/r/n', chr(13), $text ?? '');
$text = str_replace('\r\n', chr(13), $text);
$text = str_replace('/n', chr(13), $text);
$text = str_replace('\n', chr(13), $text);
$text = str_replace('\r', chr(13), $text);
$text = str_replace('/r', chr(13), $text);
$text = str_replace('\n\n', chr(13) . chr(13), $text);
$text = stripslashes($text);
return $text;
}
}
if (!function_exists('setTextAreaHtml')) {
function setTextAreaHtml(?string $text): string
{
$text = str_replace('/r/n', '<br />', $text ?? '');
$text = str_replace('\r\n', '<br />', $text);
$text = str_replace('/n', '<br />', $text);
$text = str_replace('\n', '<br />', $text);
$text = str_replace('\r', '<br />', $text);
$text = str_replace('/r', '<br />', $text);
$text = str_replace('\n\n', '<br /><br />', $text);
$text = stripslashes($text);
return $text;
}
}
if (!function_exists('checkBsn')) {
function checkBsn(string $bsn): bool
{
return true;
}
}
if (!function_exists('isNotNullOrEmpty')) {
/**
* Validate an object property
*/
function isNotNullOrEmpty($in, ?string $property = null, bool $zeroAllowed = false): bool
{
if ($property === null) {
if (is_object($in) && count((array)$in) === 0) {
return false;
}
$isNotEmpty = $zeroAllowed ? !empty($in) : $in === 0 || $in === '0' || !empty($in);
if (is_string($in)) {
return $isNotEmpty && strtoupper($in) !== 'NULL' && strtoupper($in) !== 'FALSE' && strtoupper($in) !== 'UNDEFINED';
}
return $isNotEmpty;
}
if (!is_object($in)) {
throw new Exception('Provided test $in must be a class instance(object) or a valid classname(string)');
}
if (!property_exists($in, $property)) {
return false;
}
$prop = $in->{$property};
$isNotEmpty = $zeroAllowed ? !empty($prop) : $prop === 0 || $prop === '0' || !empty($prop);
if (is_string($prop)) {
return $isNotEmpty && strtoupper($prop) !== 'NULL' && strtoupper($prop) !== 'FALSE' && strtoupper($prop) !== 'UNDEFINED';
}
return $isNotEmpty;
}
}
if (!function_exists('isNotNullOrEmptyOrZero')) {
function isNotNullOrEmptyOrZero($in, ?string $property = null): bool
{
return isNotNullOrEmpty($in, $property, true);
}
}
if (!function_exists('isNullOrEmpty')) {
function isNullOrEmpty($in, ?string $property = null): bool
{
return !isNotNullOrEmpty($in, $property);
}
}
if (!function_exists('isNullOrEmptyOrZero')) {
function isNullOrEmptyOrZero($in, ?string $property = null): bool
{
return !isNotNullOrEmpty($in, $property, true);
}
}
if (!function_exists('parseNotNullField')) {
function parseNotNullField($in): string
{
if (isNullOrEmpty($in)) {
return '';
}
return (string)$in;
}
}
if (!function_exists('unique_multidim_array')) {
function unique_multidim_array(array $array, string $key): array
{
$temp_array = [];
$key_array = [];
foreach ($array as $val) {
$keyValue = is_array($val) ? $val[$key] : $val->$key;
if (!in_array($keyValue, $key_array)) {
$key_array[] = $keyValue;
$temp_array[] = $val;
}
}
return $temp_array;
}
}
if (!function_exists('validate_password_strength')) {
/**
* Validate password strength
* Password must contain:
* - At least 8 characters
* - At least 1 uppercase letter
* - At least 1 lowercase letter
* - At least 1 number
* - At least 1 special character
*/
function validate_password_strength(string $password): bool
{
if (strlen($password) < 8) {
return false;
}
if (!preg_match('/[A-Z]/', $password)) {
return false;
}
if (!preg_match('/[a-z]/', $password)) {
return false;
}
if (!preg_match('/[0-9]/', $password)) {
return false;
}
if (!preg_match('/[^A-Za-z0-9]/', $password)) {
return false;
}
return true;
}
}
if (!function_exists('get_password_requirements_nl')) {
/**
* Get password validation requirements in Dutch
*/
function get_password_requirements_nl(): array
{
return [
'Minimaal 8 karakters',
'Minimaal 1 hoofdletter',
'Minimaal 1 kleine letter',
'Minimaal 1 cijfer',
'Minimaal 1 speciaal teken (!@#$%^&* etc.)'
];
}
}
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveCustomer {
private $customerID;
private $allowDelete = TRUE;
public function __construct( $userID )
{
$this->setCustomerID( $userID );
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setCustomerID( $customerID )
{
$this->customerID = $customerID;
}
private function handle()
{
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveExternal {
private $externalID;
private $allowDelete = TRUE;
public function __construct( $userID )
{
$this->setExternalID( $userID );
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setExternalID( $externalID )
{
$this->externalID = $externalID;
}
private function handle()
{
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Libraries\Beheer\Session;
use CodeIgniter\Session\Session;
class CreateUserSession
{
private Session $session;
private object $user;
private array $sessionArray = [];
public function __construct(Session $session)
{
$this->session = $session;
}
public function handle(object $user): void
{
$this->setUser($user);
$this->setSessionArray();
$this->createSession();
}
private function setUser(object $user): void
{
$this->user = $user;
}
private function setSessionArray(): void
{
$this->sessionArray = [
'userID' => $this->user->id,
'role' => $this->user->role
];
}
private function createSession(): void
{
$this->session->set($this->sessionArray);
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Libraries\Beheer\Session;
use CodeIgniter\Session\Session;
class RetrieveUserSession
{
private Session $session;
public function __construct(Session $session)
{
$this->session = $session;
}
public function handle(): void
{
$this->setUserID();
$this->setRole();
$this->setAuthenticated();
}
private function setUserID(): void
{
$userId = $this->session->get('userID');
if (!defined('USERID')) {
define('USERID', $userId);
}
}
private function setRole(): void
{
$role = $this->session->get('role');
if (!defined('ROLE')) {
define('ROLE', $role);
}
}
private function setAuthenticated(): void
{
if (!defined('AUTHENTICATED')) {
define('AUTHENTICATED', USERID ? true : false);
}
}
}
@@ -0,0 +1,101 @@
<?php
/**
* Send OTP Email Library
* Generates and sends a one-time password via email for two-factor authentication
*/
class SendOtpEmail
{
private $user;
private $otpCode;
private $sendResult = false;
public function __construct($user)
{
$this->user = $user;
$this->handle();
}
/**
* Get the result of the email send operation
* @return bool True if email was sent successfully
*/
public function getSendResult()
{
return $this->sendResult;
}
/**
* Get the generated OTP code (for testing purposes)
* @return string The OTP code
*/
public function getOtpCode()
{
return $this->otpCode;
}
/**
* Main handler for OTP email process
*/
private function handle()
{
$this->generateOTP();
$this->sendOTPEmail();
}
/**
* Generate a new OTP code
*/
private function generateOTP()
{
// Generate OTP valid for 10 minutes
$this->otpCode = \UserOtp_model::generateOTP($this->user->id, 10);
}
/**
* Send the OTP code via email
*/
private function sendOTPEmail()
{
$email = \Config\Services::email();
// Build email configuration directly from environment variables
$config = [
'protocol' => str_replace(',', '', $_ENV['PROTOCOL'] ?? 'smtp'),
'SMTPHost' => str_replace(',', '', $_ENV['SMTP_HOST'] ?? ''),
'SMTPUser' => str_replace(',', '', $_ENV['SMTP_USER'] ?? ''),
'SMTPPass' => str_replace(',', '', $_ENV['SMTP_PASS'] ?? ''),
'SMTPPort' => (int) str_replace(',', '', $_ENV['SMTP_PORT'] ?? 25),
'SMTPCrypto' => 'tls',
'SMTPTimeout' => 30,
'charset' => 'UTF-8',
'mailType' => 'html',
'newline' => "\r\n",
'CRLF' => "\r\n",
'wordWrap' => true,
];
$email->initialize($config);
$data = [
'username' => $this->user->username,
'firstname' => $this->user->firstname,
'middlename' => $this->user->middlename,
'lastname' => $this->user->lastname,
'otp_code' => $this->otpCode
];
$html = view('emails/twofactor_otp_email', ['user' => $data]);
$email->setFrom('noreply@dbois.nl', 'DBOIS');
$email->setTo($this->user->email);
$email->setSubject('DBOIS Tweefactorauthenticatie - Verificatiecode');
$email->setMessage($html);
$this->sendResult = $email->send();
if (!$this->sendResult) {
log_message('error', 'Failed to send 2FA OTP email to ' . $this->user->email . ': ' . $email->printDebugger());
}
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 26/12/2017
* Time: 12:39
*/
class CreateUser {
public function __construct()
{
}
}
@@ -0,0 +1,99 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 26/12/2017
* Time: 12:40
*/
class PasswordRecipe {
private $password = FALSE;
private $salt = FALSE;
private $saltedPassword;
public function __construct()
{
$this->handle();
}
public function getPassword()
{
return $this->password;
}
public function getSalt()
{
return $this->salt;
}
public function getSaltedPassword()
{
return $this->saltedPassword;
}
public function setPassword( $password )
{
$this->password = $password;
}
public function setSalt( $salt )
{
$this->salt = $salt;
}
private function handle()
{
$this->checkPassword();
$this->checkSalt();
$this->setSaltedPassword();
}
private function checkPassword()
{
if ( ! $this->password ) $this->createPassword();
if ( strlen( $this->password ) < 6 ) return;
}
private function checkSalt()
{
if ( ! $this->salt ) $this->createSalt();
}
private function createPassword()
{
$pass = $this->getRandomString( 8 );
$this->password = $pass;
}
private function createSalt()
{
$salt = $this->getRandomString( 18 );
$this->salt = sha1($salt);
}
private function setSaltedPassword()
{
$this->saltedPassword = User::getSaltedPassword( $this->password, $this->salt);
}
private function getRandomString( $length = 8 )
{
$rand = '';
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$alphaLength = strlen( $alphabet ) - 1; //put the length -1 in cache
for ( $i = 0; $i < $length; $i ++ )
{
$n = rand( 0, $alphaLength );
$rand .= $alphabet[ $n ];
}
return $rand;
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveUser {
private $userID;
private $allowDelete=FALSE;
public function __construct( $userID )
{
$this->setUserID($userID);
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setUserID( $userID )
{
$this->userID = $userID;
}
private function handle()
{
//$this->checkIfUserHasProjects();
}
}
@@ -0,0 +1,104 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 28/07/2018
* Time: 14:31
*/
class RequestPassword {
private $ci;
private $salt;
private $user;
private $password;
private $sendResult;
private $passwordRecipe;
private $saltedPassword;
public function __construct( $user )
{
$this->ci =& get_instance();
$this->user = $user;
$this->ci->load->library( 'email' );
$this->handle();
}
public function getSendResult()
{
return $this->sendResult;
}
private function handle()
{
$this->createPassword();
$this->setPassword();
$this->setSalt();
$this->setSaltedPassword();
$this->persistNewpassword();
$this->sendNewPassword();
}
private function createPassword()
{
$this->passwordRecipe = new PasswordRecipe();
}
private function setPassword()
{
$this->password = $this->passwordRecipe->getPassword();
}
private function setSalt()
{
$this->salt = $this->passwordRecipe->getsalt();
}
private function setSaltedPassword()
{
$this->saltedPassword = $this->passwordRecipe->getSaltedPassword();
}
private function persistNewPassword()
{
$data = [
'password' => $this->saltedPassword,
'salt' => $this->salt
];
User::whereId( $this->user->id )->update( $data );
}
private function sendNewPassword()
{
$data = [
'username' => $this->user->username,
'firstname' => $this->user->firstname,
'middlename' => $this->user->middlename,
'lastname' => $this->user->lastname,
'password' => $this->password
];
$html = $this->ci->load->view( 'emails/requestpassword_email', ['user'=>$data], true );
$this->ci->email->from( 'noreply@dbois.nl', 'DBOIS' );
$this->ci->email->to( $this->user->email );
$this->ci->email->subject( 'Nieuw wachtwoord DBOIS' );
$this->ci->email->message( $html );
$this->ci->email->set_mailtype("html");
$this->ci->email->set_newline("\r\n");
$this->sendResult = $this->ci->email->send();
if( ! $this->sendResult ) log_message( 'error', json_encode($this->ci->email->print_debugger()));
}
}
@@ -0,0 +1,72 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 14:10
*/
class UserCreation {
private $user;
private $passWordRecipe;
private $password;
private $saltedPassword;
private $salt;
public function __construct( $user )
{
$this->setUser( $user );
$this->handle();
}
public function getUser()
{
return $this->user;
}
public function getPassword()
{
return $this->password;
}
private function setUser( $user )
{
$this->user = $user;
}
private function handle()
{
$this->passWordRecipe = new PasswordRecipe();
$this->setPassword();
$this->setSalt();
$this->setSaltedPassword();
$this->enrichUser();
}
private function setPassword()
{
$this->password = $this->passWordRecipe->getPassword();
}
private function setSalt()
{
$this->salt = $this->passWordRecipe->getSalt();
}
private function setSaltedPassword()
{
$this->saltedPassword = $this->passWordRecipe->getSaltedPassword();
}
private function enrichUser()
{
$this->user['password'] = $this->saltedPassword;
$this->user['salt'] = $this->salt;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/06/2018
* Time: 17:06
*/
class RemoveInvoice {
private $invoiceID;
private $payments;
private $removeAllowed;
public function __construct( $invoiceID )
{
$this->setInvoiceID( $invoiceID );
$this->handle();
}
public function getRemoveAllowed()
{
return $this->removeAllowed;
}
private function setInvoiceID( $invoiceID )
{
$this->invoiceID = $invoiceID;
}
private function handle()
{
$this->setPayment();
$this->setRemoveAllowed();
}
private function setPayment()
{
$payments = Payment::whereInvoiceId( $this->invoiceID );
$this->payments = $payments->count() == 0 ? TRUE : FALSE;
}
private function setRemoveAllowed()
{
if ( $this->payments === FALSE ) return $this->removeAllowed = FALSE;
$this->removeAllowed = TRUE;
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/06/2018
* Time: 15:56
*/
class RemoveInvoices {
private $invoiceID;
private $payments;
private $removeAllowed;
public function __construct( $invoiceID )
{
$this->setInvoiceID($invoiceID);
$this->handle();
}
private function setInvoiceID( $invoiceID )
{
$this->invoiceID = $invoiceID;
}
private function handle()
{
$this->setPayments();
$this->setRemoveAllowed();
}
private function setPayments()
{
$payments = Payment::whereInvoiceId($this->invoiceID);
$this->payments = $payments->count() == 0 ? TRUE : FALSE;
}
private function setRemoveAllowed()
{
$this->removeAllowed = $this->payments;
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/06/2018
* Time: 16:28
*/
class RemoveOffer {
private $offerID;
private $project;
private $removeAllowed;
public function __construct($offerID)
{
$this->setOfferID($offerID);
$this->handle();
}
public function getRemoveAllowed()
{
return $this->removeAllowed;
}
private function setOfferID( $offerID )
{
$this->offerID = $offerID;
}
private function handle()
{
$this->setProject();
$this->setRemoveAllowed();
}
private function setProject()
{
$offer = Offer::Find($this->offerID);
$this->project = is_null($offer->project_id) ? TRUE : FALSE;
}
private function setRemoveAllowed()
{
if( $this->project === FALSE ) return $this->removeAllowed = FALSE;
$this->removeAllowed = TRUE;
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/06/2018
* Time: 15:53
*/
class RemoveProject {
private $projectID;
private $forecast;
private $invoices;
private $projectemployees;
private $reservations;
private $removeAllowed;
private $projectcosts;
public function __construct( $projectID )
{
$this->setProjectID( $projectID );
$this->handle();
}
public function getRemoveAllowed()
{
return $this->removeAllowed;
}
private function setProjectID( $projectID )
{
$this->projectID = $projectID;
}
private function handle()
{
$this->setForecast();
$this->setInvoices();
$this->setProjectemployees();
$this->setReservations();
$this->setRemoveAllowed();
$this->setProjectCosts();
}
private function setForecast()
{
$forecast = Forecast::whereProjectId( $this->projectID );
$this->forecast = $forecast->count() == 0 ? TRUE : FALSE;
}
private function setInvoices()
{
$invoices = Invoice::whereProjectId( $this->projectID );
$this->invoices = $invoices->count() == 0 ? TRUE : FALSE;
}
private function setProjectemployees( )
{
$setProjectemployees = Projectemployee::whereProjectId($this->projectID);
$this->projectemployees = $setProjectemployees->count() == 0 ? TRUE : FALSE;
}
private function setReservations( )
{
$reservations = Reservation::whereProjectId($this->projectID);
$this->reservations = $reservations->count() == 0 ? TRUE : FALSE;
}
private function setProjectcosts( )
{
$projectcosts = Projectcost::whereProjectId($this->projectID);
$this->projectcosts = $projectcosts->count() == 0 ? TRUE : FALSE;
}
private function setRemoveAllowed()
{
if( $this->forecast === false ) return $this->removeAllowed = FALSE;
if( $this->invoices === false ) return $this->removeAllowed = FALSE;
if( $this->projectemployees === false ) return $this->removeAllowed = FALSE;
if( $this->reservations === false ) return $this->removeAllowed = FALSE;
if( $this->projectcosts === false ) return $this->removeAllowed = FALSE;
$this->removeAllowed = TRUE;
}
}
@@ -0,0 +1,53 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveProjectemployee {
private $projectemployeeID;
private $removeAllowed;
private $projecthours;
public function __construct( $projectemployeeID )
{
$this->setProjectemployeeID( $projectemployeeID );
$this->handle();
}
public function getRemoveAllowed()
{
return $this->removeAllowed;
}
private function setProjectemployeeID( $projectemployeeID )
{
$this->projectemployeeID = $projectemployeeID;
}
private function handle()
{
$this->setProjectHours();
$this->setRemoveAllowed();
}
private function setProjecthours()
{
$projecthours = Projecthour::whereProjectemployeeId($this->projectemployeeID);
$this->projecthours = $projecthours->count() == 0 ?TRUE : FALSE;
}
private function setRemoveAllowed()
{
if( $this->projecthours === false ) return $this->removeAllowed = FALSE;
$this->removeAllowed = TRUE;
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 10/06/2018
* Time: 17:06
*/
class RemoveVat {
private $vatID;
private $projects;
private $invoices;
private $removeAllowed;
public function __construct( $vatID )
{
$this->setVatID( $vatID );
$this->handle();
}
public function getRemoveAllowed()
{
return $this->removeAllowed;
}
private function setVatID( $vatID )
{
$this->vatID = $vatID;
}
private function handle()
{
$this->setProject();
$this->setInvoices();
$this->setRemoveAllowed();
}
private function setProject()
{
$projects = Project::whereVatId( $this->vatID );
$this->projects = $projects->count() == 0 ? TRUE : FALSE;
}
private function setInvoices()
{
$invoices = Invoice::whereVatId( $this->vatID );
$this->invoices = $invoices->count() == 0 ? TRUE : FALSE;
}
private function setRemoveAllowed()
{
if ( $this->projects === FALSE ) return $this->removeAllowed = FALSE;
if ( $this->invoices === FALSE ) return $this->removeAllowed = FALSE;
$this->removeAllowed = TRUE;
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveForecast {
private $forecastID;
private $allowDelete = TRUE;
public function __construct( $forecastID )
{
$this->setForecastID( $forecastID );
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setForecastID( $forecastID )
{
$this->forecastID = $forecastID;
}
private function handle()
{
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemovePayment {
private $paymentID;
private $allowDelete = TRUE;
public function __construct( $paymentID )
{
$this->setPaymentID( $paymentID );
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setPaymentID( $paymentID )
{
$this->paymentID = $paymentID;
}
private function handle()
{
}
}
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveProjecthour {
private $projecthourID;
private $allowDelete = TRUE;
public function __construct( $projecthourID )
{
$this->setProjecthourID( $projecthourID );
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setProjecthourID( $projecthourID )
{
$this->projecthourID = $projecthourID;
}
private function handle()
{
}
}
@@ -0,0 +1,36 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 27/12/2017
* Time: 17:45
*/
class RemoveReservation {
private $reservationID;
private $allowDelete = TRUE;
public function __construct( $reservationID )
{
$this->setReservationID( $reservationID );
$this->handle();
}
public function getAllowDelete()
{
return $this->allowDelete;
}
private function setReservationID( $reservationID )
{
$this->reservationID = $reservationID;
}
private function handle()
{
}
}
@@ -0,0 +1,75 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 30/07/2018
* Time: 10:48
*/
class InvoiceForecastSheet {
const HEADERS = [
'A' => 'project',
'B' => 'klant',
'C' => 'Nog te factureren incl. btw',
'D' => 'Nog te factureren incl. btw lopend boekjaar incl. btw',
'E' => 'Nog te factureren na lopend boekjaar inc. btw',
'F' => 'Nog te prognotiseren inc. btw'
];
private $invoiceForecast;
private $sheet;
private $row;
public function __construct( $invoiceForecast, $sheet )
{
$this->invoiceForecast = $invoiceForecast;
$this->sheet = $sheet;
$this->handle();
}
private function handle()
{
$this->setHeader();
$this->setBody();
$this->setTotals();
}
private function setHeader()
{
foreach ( self::HEADERS as $cell => $header )
{
$this->sheet->setCellValue( $cell . '1', $header );
$this->sheet->getColumnDimension( $cell )->setAutoSize( TRUE );
}
}
private function setBody()
{
$this->row = 2;
foreach ( $this->invoiceForecast AS $project )
{
$this->sheet->setCellValue( 'A' . $this->row, $project['projectname'] );
$this->sheet->setCellValue( 'B' . $this->row, $project['customer'] );
$this->sheet->setCellValue( 'C' . $this->row, str_replace( '.', '', $project['needInvoice'] ?? '' ) );
$this->sheet->setCellValue( 'D' . $this->row, str_replace( '.', '', $project['forecastThisYear'] ?? '' ) );
$this->sheet->setCellValue( 'E' . $this->row, str_replace( '.', '', $project['forecastOtherYears'] ?? '' ) );
$this->sheet->setCellValue( 'F' . $this->row, str_replace( '.', '', $project['forecastRemaining'] ?? '' ) );
$this->row ++;
}
}
private function setTotals()
{
$lastRow = $this->row - 1;
$this->sheet->setCellValue( 'C' . $this->row, '=SUM(C2:C' . $lastRow . ')' );
$this->sheet->setCellValue( 'D' . $this->row, '=SUM(D2:D' . $lastRow . ')' );
$this->sheet->setCellValue( 'E' . $this->row, '=SUM(E2:E' . $lastRow . ')' );
$this->sheet->setCellValue( 'F' . $this->row, '=SUM(F2:F' . $lastRow . ')' );
}
}
@@ -0,0 +1,80 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 20:40
*/
class InvoiceOverviewSheet {
const HEADERS = [
'A' => 'project',
'B' => 'klant',
'C' => 'Totaal te factureren excl. btw',
'D' => 'Totaal te factureren incl. btw',
'E' => 'Gefactureerd overige jaren incl. btw',
'F' => 'Gefactureerd lopende boekjaar incl. btw',
'G' => 'Gefactureerd totaal incl. btw',
'H' => 'Nog te factureren incl. btw'
];
private $invoiceOverview;
private $sheet;
private $row;
public function __construct( $invoiceOverview, $sheet )
{
$this->invoiceOverview = $invoiceOverview;
$this->sheet = $sheet;
$this->handle();
}
private function handle()
{
$this->setHeader();
$this->setBody();
$this->setTotals();
}
private function setHeader()
{
foreach ( self::HEADERS as $cell => $header )
{
$this->sheet->setCellValue( $cell . '1', $header );
$this->sheet->getColumnDimension( $cell )->setAutoSize( TRUE );
}
}
private function setBody()
{
$this->row = 2;
foreach ( $this->invoiceOverview AS $project )
{
$this->sheet->setCellValue( 'A' . $this->row, $project['projectname'] );
$this->sheet->setCellValue( 'B' . $this->row, $project['customer'] );
$this->sheet->setCellValue( 'C' . $this->row, str_replace( '.', '', $project['totalToInvoicingExcl'] ?? '' ) );
$this->sheet->setCellValue( 'D' . $this->row, str_replace( '.', '', $project['totalToInvoicingIncl'] ?? '' ) );
$this->sheet->setCellValue( 'E' . $this->row, str_replace( '.', '', $project['totalInvoicedOtherYears'] ?? '' ) );
$this->sheet->setCellValue( 'F' . $this->row, str_replace( '.', '', $project['totalInvoicedThisYear'] ?? '' ) );
$this->sheet->setCellValue( 'G' . $this->row, str_replace( '.', '', $project['invoicesTotal'] ?? '' ) );
$this->sheet->setCellValue( 'H' . $this->row, str_replace( '.', '', $project['needInvoice'] ?? '' ) );
$this->row ++;
}
}
private function setTotals()
{
$lastRow = $this->row - 1;
$this->sheet->setCellValue( 'C' . $this->row, '=SUM(C2:C' . $lastRow . ')' );
$this->sheet->setCellValue( 'D' . $this->row, '=SUM(D2:D' . $lastRow . ')' );
$this->sheet->setCellValue( 'E' . $this->row, '=SUM(E2:E' . $lastRow . ')' );
$this->sheet->setCellValue( 'F' . $this->row, '=SUM(F2:F' . $lastRow . ')' );
$this->sheet->setCellValue( 'G' . $this->row, '=SUM(G2:G' . $lastRow . ')' );
$this->sheet->setCellValue( 'H' . $this->row, '=SUM(H2:H' . $lastRow . ')' );
}
}
@@ -0,0 +1,136 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 20:04
*/
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class InvoiceSpreadsheet {
private $invoiceReport;
private $spreadsheet;
private $invoiceSheet;
private $fullpathname;
private $filename;
private $ci;
public function __construct( $invoiceReport )
{
$this->ci =& get_instance();
$this->invoiceReport = $invoiceReport;
$this->ci->load->helper( 'download' );
$this->handle();
}
private function handle()
{
$this->setSpreadsheet();
$this->setInvoiceOverviewSheet();
$this->setInvoiceForecast();
$this->setMonthForecast();
$this->setMonthPayment();
$this->setInvoiced();
$this->setFilename();
$this->setFullPathname();
$this->createFile();
$this->downloadSpreadsheet();
}
private function setSpreadsheet()
{
$this->spreadsheet = new Spreadsheet();
}
private function setInvoiceOverviewSheet()
{
$invoiceSheet = new Worksheet( $this->spreadsheet, 'Facturen' );
$this->invoiceSheet =
$this->spreadsheet->addSheet( $invoiceSheet );
new InvoiceOverviewSheet( $this->invoiceReport['invoiceOverview'], $this->invoiceSheet );
}
private function setInvoiceForecast()
{
$invoiceSheet = new Worksheet( $this->spreadsheet, 'prognose' );
$this->invoiceSheet =
$this->spreadsheet->addSheet( $invoiceSheet );
new InvoiceForecastSheet( $this->invoiceReport['forecasts'], $this->invoiceSheet );
}
private function setMonthForecast()
{
$invoiceSheet = new Worksheet( $this->spreadsheet, 'maandprognose' );
$this->invoiceSheet =
$this->spreadsheet->addSheet( $invoiceSheet );
new MonthForecastSheet( $this->invoiceReport['monthForecasts'], $this->invoiceSheet );
}
private function setMonthPayment()
{
$invoiceSheet = new Worksheet( $this->spreadsheet, 'maand betalingen' );
$this->invoiceSheet =
$this->spreadsheet->addSheet( $invoiceSheet );
new MonthPaymentSheet( $this->invoiceReport['monthPayments'], $this->invoiceSheet );
}
private function setInvoiced()
{
$invoiceSheet = new Worksheet( $this->spreadsheet, 'verstuurde facturen' );
$this->invoiceSheet =
$this->spreadsheet->addSheet( $invoiceSheet );
new InvoicedSheet( $this->invoiceReport['invoiced'], $this->invoiceSheet );
}
private function setFilename()
{
$this->filename = 'facturen' . date( 'YmdHis' ) . '.xlsx';
}
private function setFullPathname()
{
$this->fullpathname = MYROOTPATH . 'documents/spreadsheets/' . $this->filename;
}
private function createFile()
{
$writer = new Xlsx( $this->spreadsheet );
$writer->save( $this->fullpathname );
}
private function downloadSpreadsheet()
{
$data = file_get_contents( $this->fullpathname );
force_download( $this->filename, $data );
}
}
@@ -0,0 +1,67 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 30/07/2018
* Time: 10:48
*/
class InvoicedSheet {
const HEADERS = [
'A' => 'factuurnummer',
'B' => 'project',
'C' => 'klant',
'D' => 'factuurdatum',
'E' => 'exc btw',
'F' => 'btw',
'G' => 'incl btw'
];
private $invoiced;
private $sheet;
private $row;
public function __construct( $invoiced, $sheet )
{
$this->invoiced = $invoiced;
$this->sheet = $sheet;
$this->handle();
}
private function handle()
{
$this->setHeader();
$this->setBody();
}
private function setHeader()
{
foreach ( self::HEADERS as $cell => $header )
{
$this->sheet->setCellValue( $cell . '1', $header );
$this->sheet->getColumnDimension( $cell )->setAutoSize( TRUE );
}
}
private function setBody()
{
$this->row = 2;
foreach ( $this->invoiced AS $invoice )
{
$vat = ROUND($invoice->invoiceamount * 0.21, 2);
$this->sheet->setCellValue( 'A' . $this->row, $invoice->invoicenumber );
$this->sheet->setCellValue( 'B' . $this->row, ($invoice->projectnumber . ' ' . $invoice['projectname']));
$this->sheet->setCellValue( 'C' . $this->row, $invoice->name );
$this->sheet->setCellValue( 'D' . $this->row, $invoice->invoicenumber );
$this->sheet->setCellValue( 'E' . $this->row, $invoice->invoiceamount );
$this->sheet->setCellValue( 'F' . $this->row, $vat );
$this->sheet->setCellValue( 'G' . $this->row, $invoice->invoiceamount + $vat );
$this->row ++;
}
}
}
@@ -0,0 +1,101 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 30/07/2018
* Time: 10:48
*/
class MonthForecastSheet {
const HEADERS = [
'A' => 'project',
'B' => 'klant',
'C' => 'Nog te factureren incl. btw',
'D' => 'januari',
'E' => 'februari',
'F' => 'maart',
'G' => 'april',
'H' => 'mei',
'I' => 'juni',
'J' => 'juli',
'K' => 'augustus',
'L' => 'september',
'M' => 'oktober',
'N' => 'november',
'O' => 'december',
'P' => 'Nog te factureren na lopend boekjaar inc. btw',
'Q' => 'Nog te prognotiseren inc. btw'
];
const MONTH_COLUMNS = ['D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'];
private $invoiceForecast;
private $sheet;
private $row;
public function __construct( $invoiceForecast, $sheet )
{
$this->invoiceForecast = $invoiceForecast;
$this->sheet = $sheet;
$this->handle();
}
private function handle()
{
$this->setHeader();
$this->setBody();
$this->setTotals();
}
private function setHeader()
{
foreach ( self::HEADERS as $cell => $header )
{
$this->sheet->setCellValue( $cell . '1', $header );
$this->sheet->getColumnDimension( $cell )->setAutoSize( TRUE );
}
}
private function setBody()
{
$this->row = 2;
foreach ( $this->invoiceForecast AS $project )
{
$this->sheet->setCellValue( 'A' . $this->row, $project['projectname'] );
$this->sheet->setCellValue( 'B' . $this->row, $project['customer'] );
$this->sheet->setCellValue( 'C' . $this->row, str_replace( '.', '', $project['needInvoice'] ?? '' ) );
$columnCount = 0;
foreach ( $project['forecastMonths'] as $month )
{
$column = self::MONTH_COLUMNS[ $columnCount ];
$forecast = $month['forecastamount'];
$this->sheet->setCellValue( $column . $this->row, $forecast );
$columnCount ++;
}
$this->sheet->setCellValue( 'P' . $this->row, str_replace( '.', '', $project['forecastOtherYears'] ?? '' ) );
$this->sheet->setCellValue( 'Q' . $this->row, str_replace( '.', '', $project['forecastRemaining'] ?? '' ) );
$this->row ++;
}
}
private function setTotals()
{
$lastRow = $this->row - 1;
$this->sheet->setCellValue( 'C' . $this->row, '=SUM(C2:C' . $lastRow . ')' );
$this->sheet->setCellValue( 'D' . $this->row, '=SUM(D2:D' . $lastRow . ')' );
foreach ( self::MONTH_COLUMNS as $column )
{
$this->sheet->setCellValue( $column . $this->row, '=SUM(' . $column . '2:' . $column . $lastRow . ')' );
}
$this->sheet->setCellValue( 'P' . $this->row, '=SUM(P2:P' . $lastRow . ')' );
$this->sheet->setCellValue( 'Q' . $this->row, '=SUM(Q2:Q' . $lastRow . ')' );
}
}
@@ -0,0 +1,95 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 30/07/2018
* Time: 10:48
*/
class MonthPaymentSheet {
const HEADERS = [
'A' => 'project',
'B' => 'klant',
'C' => 'januari',
'D' => 'februari',
'E' => 'maart',
'F' => 'april',
'G' => 'mei',
'H' => 'juni',
'I' => 'juli',
'J' => 'augustus',
'K' => 'september',
'L' => 'oktober',
'M' => 'november',
'N' => 'december',
'O' => 'Totaal betaald lopend boekjaar inc. btw'
];
const MONTH_COLUMNS = ['C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'];
private $invoiceForecast;
private $sheet;
private $row;
public function __construct( $invoiceForecast, $sheet )
{
$this->invoiceForecast = $invoiceForecast;
$this->sheet = $sheet;
$this->handle();
}
private function handle()
{
$this->setHeader();
$this->setBody();
$this->setTotals();
}
private function setHeader()
{
foreach ( self::HEADERS as $cell => $header )
{
$this->sheet->setCellValue( $cell . '1', $header );
$this->sheet->getColumnDimension( $cell )->setAutoSize( TRUE );
}
}
private function setBody()
{
$this->row = 2;
foreach ( $this->invoiceForecast AS $project )
{
$this->sheet->setCellValue( 'A' . $this->row, $project['projectname'] );
$this->sheet->setCellValue( 'B' . $this->row, $project['customer'] );
$columnCount = 0;
foreach ( $project['monthPayments'] as $month )
{
$column = self::MONTH_COLUMNS[ $columnCount ];
$forecast = $month['paymentamount'];
$this->sheet->setCellValue( $column . $this->row, $forecast );
$columnCount ++;
}
$formula = '=SUM(C'.$this->row.':N'.$this->row.')';
$this->sheet->setCellValue( 'O' . $this->row, $formula);
$this->row ++;
}
}
private function setTotals()
{
$lastRow = $this->row - 1;
foreach ( self::MONTH_COLUMNS as $column )
{
$this->sheet->setCellValue( $column . $this->row, '=SUM(' . $column . '2:' . $column . $lastRow . ')' );
}
$this->sheet->setCellValue( 'O' . $this->row, '=SUM(O2:O' . $lastRow . ')' );
}
}
@@ -0,0 +1,125 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 13:14
*/
class InvoiceForecast {
private $year;
private $project;
private $customer;
private $forecast;
private $currentYear;
private $projectname;
private $needInvoice;
private $projectDetails;
private $forecastThisYear = 0;
private $forecastRemaining;
private $forecastOtherYears = 0;
public function __construct( $project, $needInvoice, $year )
{
$this->project = $project;
$this->needInvoice = $needInvoice;
$this->year = $year;
$this->handle();
}
public function getProjectDetails()
{
return $this->projectDetails;
}
public function getNeedInvoice()
{
return $this->needInvoice;
}
public function getForecastOtherYear()
{
return $this->forecastOtherYears;
}
public function getForecastRemaining()
{
return $this->forecastRemaining;
}
private function handle()
{
$this->setCurrentyear();
$this->setProjectname();
$this->setCustomer();
$this->loopForecasts();
$this->setForecastRemaining();
$this->setProjectDetails();
}
private function setCurrentyear()
{
$this->currentYear = date( 'Y' );
}
private function setProjectname()
{
$this->projectname = $this->project->projectname . '(' . $this->project->projectnumber . ')';
}
private function setCustomer()
{
$this->customer = $this->project->customer->name;
}
private function loopForecasts()
{
if ( is_null( $this->project->forecasts ) ) return $this->forecastThisYear = 0;
foreach ( $this->project->forecasts as $this->forecast )
{
$this->setForecastThisYear();
$this->setForecastOtherYears();
}
}
private function setForecastThisYear()
{
if ( $this->forecast->year == $this->year )
$this->forecastThisYear += $this->forecast->forecastamount;
}
private function setForecastOtherYears()
{
if ( $this->forecast->year != $this->year )
$this->forecastOtherYears += $this->forecast->forecastamount;
}
private function setForecastRemaining()
{
$this->forecastRemaining =
$this->needInvoice - $this->forecastThisYear - $this->forecastOtherYears;
}
private function setProjectDetails()
{
$this->projectDetails = [
'projectnumber' => $this->project->projectnumber,
'projectname' => $this->projectname,
'customer' => $this->customer,
'needInvoice' => number_format( $this->needInvoice, 0, ',', '.' ),
'forecastThisYear' => number_format( $this->forecastThisYear, 0, ',', '.' ),
'forecastOtherYears' => number_format( $this->forecastOtherYears, 0, ',', '.' ),
'forecastRemaining' => number_format( $this->forecastRemaining, 0, ',', '.' ),
];
}
}
@@ -0,0 +1,151 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 10:29
*/
class InvoiceOverview {
private $project;
private $year;
private $projectname;
private $customer;
private $totalToInvoicingExcl;
private $totalToInvoicingIncl;
private $totalInvoicedOtherYears;
private $totalInvoicedThisYear;
private $invoicesTotal;
private $needInvoice;
private $projectDetails;
private $projectnumber;
private $projectPayment;
private $invoicesToPay;
public function __construct( $project, $year )
{
$this->project = $project;
$this->year = $year;
$this->handle();
}
public function getProjectDetails()
{
return $this->projectDetails;
}
public function getNeedinvoice()
{
return $this->needInvoice;
}
private function handle()
{
$this->setProjectnumber();
$this->setProjectname();
$this->setCustomer();
$this->setTotalToInvoicingExcl();
$this->setTotalToInvoicingIncl();
$this->setTotalInvoicedOtherYears();
$this->setTotalInvoicedThisYear();
$this->setPaymentPerProject();
$this->setInvoicesTotal();
$this->setInvoicesToPay();
$this->setNeedInvoice();
$this->setProjectDetails();
}
private function setProjectnumber()
{
$this->projectnumber = $this->project->projectnumber;
}
private function setProjectname()
{
$this->projectname = $this->project->projectname;
}
private function setCustomer()
{
$this->customer = $this->project->customer->name;
}
private function setTotalToInvoicingExcl()
{
$offer = $this->project->offer;
$this->totalToInvoicingExcl =
$offer->own_revenue + $offer->other_revenue + $offer->costs;
}
private function setTotalToInvoicingIncl()
{
$this->totalToInvoicingIncl =
$this->totalToInvoicingExcl * ( 1 + ( $this->project->vat->vatrate / 100 ) );
}
private function setTotalInvoicedOtherYears()
{
$this->totalInvoicedOtherYears =
Invoice::invoicePerYear( $this->project->id, $this->year, FALSE );
}
private function setTotalInvoicedThisYear()
{
$this->totalInvoicedThisYear =
Invoice::invoicePerYear( $this->project->id, $this->year, TRUE );
}
private function setPaymentPerProject()
{
$this->projectPayment = Payment::getPaymentPerProject( $this->project->id );
}
private function setInvoicesTotal()
{
$this->invoicesTotal =
$this->totalInvoicedOtherYears + $this->totalInvoicedThisYear;
}
private function setInvoicesToPay()
{
$this->invoicesToPay = $this->invoicesTotal - $this->projectPayment;
}
private function setNeedInvoice()
{
$this->needInvoice =
$this->totalToInvoicingIncl - $this->invoicesTotal;
}
private function setProjectDetails()
{
$this->projectDetails = [
'projectnumber' => $this->projectnumber,
'projectname' => $this->projectname,
'customer' => $this->customer,
'totalToInvoicingExcl' => number_format( $this->totalToInvoicingExcl ?? 0, 0, ',', '.' ),
'totalToInvoicingIncl' => number_format( $this->totalToInvoicingIncl ?? 0, 0, ',', '.' ),
'totalInvoicedOtherYears' => number_format( $this->totalInvoicedOtherYears ?? 0, 0, ',', '.' ),
'totalInvoicedThisYear' => number_format( $this->totalInvoicedThisYear ?? 0, 0, ',', '.' ),
'invoicesTotal' => number_format( $this->invoicesTotal ?? 0, 0, ',', '.' ),
'projectPayment' => number_format( $this->projectPayment ?? 0, 0, ',', '.' ),
'invoiceToPay' => number_format( $this->invoicesToPay ?? 0, 0, ',', '.' ),
'needInvoice' => number_format( $this->needInvoice ?? 0, 0, ',', '.' )
];
}
}
+133
View File
@@ -0,0 +1,133 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 10:19
*/
class Invoices {
private $year;
private $project;
private $projects;
private $monthPayment;
private $monthPayments;
private $monthForecast;
private $monthForecasts;
private $invoiceOverview;
private $invoiceForecast;
private $invoiceForecasts;
private $invoiceOverviews = [];
private $invoiceReport = [];
private $orderType;
private $orderDirection;
private $archive;
private $invoicedYears;
private $invoiced;
public function __construct( $year, $orderType, $orderDirection, $archive )
{
$this->year = $year;
$this->orderType = $orderType;
$this->orderDirection = $orderDirection;
$this->archive = $archive;
$this->handle();
}
public function getInvoiceReport()
{
return $this->invoiceReport;
}
private function handle()
{
$this->setProjects();
$this->loopProjects();
//only projects with payments also archived projects
$this->setMonthPayments();
$this->setInvoicedyears();
$this->setInvoiced();
$this->setInvoiceReport();
}
private function setProjects()
{
$this->projects =
Project::getProjectsForReport( $this->orderType, $this->orderDirection, $this->archive );
}
private function loopProjects()
{
foreach ( $this->projects as $this->project )
{
$this->setInvoiceOverview();
$this->setInvoiceForecasts();
$this->setMonthForecasts();
}
}
private function setInvoiceOverview()
{
$this->invoiceOverview = new InvoiceOverview( $this->project, $this->year );
$this->invoiceOverviews[] = $this->invoiceOverview->getProjectDetails();
}
private function setInvoiceForecasts()
{
$this->invoiceForecast =
new InvoiceForecast( $this->project, $this->invoiceOverview->getNeedinvoice(), $this->year );
$this->invoiceForecasts[] = $this->invoiceForecast->getProjectDetails();
}
public function setMonthForecasts()
{
$this->monthForecast =
new MonthForecast( $this->invoiceForecast, $this->project, $this->year );
$this->monthForecasts[] = $this->monthForecast->getProjectDetails();
}
public function setMonthPayments()
{
$monthPayment = new MonthPayments(
$this->year, $this->orderType, $this->orderDirection );
$this->monthPayments = $monthPayment->getProjectDetails();
}
private function setInvoiced()
{
$this->invoiced = Invoice::getInvoiced( $this->year, $this->orderType, $this->orderDirection );
}
private function setInvoicedYears()
{
$this->invoicedYears = Invoice::selectRaw( 'DATE_FORMAT(invoicedate, "%Y") AS years' )
->distinct()
->orderBy( 'invoicedate' )
->pluck( 'years' );
}
private function setInvoiceReport()
{
$this->invoiceReport = [
'invoiceOverview' => $this->invoiceOverviews,
'forecasts' => $this->invoiceForecasts,
'monthForecasts' => $this->monthForecasts,
'monthPayments' => $this->monthPayments,
'invoicedYears' => $this->invoicedYears,
'invoiced' => $this->invoiced
];
}
}
@@ -0,0 +1,92 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 14:23
*/
class MonthForecast {
private $year;
private $project;
private $forecast;
private $customer;
private $projectname;
private $forecastMonths;
private $projectDetails;
private $invoiceForecast;
public function __construct( InvoiceForecast $invoiceForecast, $project, $year )
{
$this->project = $project;
$this->invoiceForecast = $invoiceForecast;
$this->year = $year;
$this->handle();
}
public function getProjectDetails()
{
return $this->projectDetails;
}
private function handle()
{
$this->setProjectname();
$this->setCustomer();
$this->setInitialsForecastMonths();
$this->loopForecasts();
$this->setProjectDetails();
}
private function setProjectname()
{
$this->projectname = $this->project->projectname . '(' . $this->project->projectnumber . ')';
}
private function setCustomer()
{
$this->customer = $this->project->customer->name;
}
private function setInitialsForecastMonths()
{
for ( $i = 0; $i < 12; $i ++ )
{
$this->forecastMonths[ $i ] = ['forecastamount' => 0];
}
}
private function loopForecasts()
{
foreach ( $this->project->forecasts as $this->forecast )
{
$this->setMonthForecast();
}
}
private function setMonthForecast()
{
if ( $this->forecast->year == $this->year )
$this->forecastMonths[ $this->forecast->month_id ]['forecastamount'] += $this->forecast->forecastamount;
}
private function setProjectDetails()
{
$this->projectDetails = [
'projectnumber' => $this->project->projectnumber,
'projectname' => $this->projectname,
'customer' => $this->customer,
'needInvoice' => number_format( $this->invoiceForecast->getNeedInvoice(), 0, ',', '.' ),
'forecastOtherYears' => number_format( $this->invoiceForecast->getForecastOtherYear(), 0, ',', '.' ),
'forecastRemaining' => number_format( $this->invoiceForecast->getForecastRemaining(), 0, ',', '.' ),
'forecastMonths' => $this->forecastMonths
];
}
}
@@ -0,0 +1,128 @@
<?php
/**
* Created by Pensare Software.
* User: Theo Weijmer
* Date: 29/07/2018
* Time: 14:23
*/
class MonthPayments {
private $year;
private $project;
private $payment;
private $customer;
private $projectname;
private $monthPayments;
private $projectDetails;
private $projectsWithPayments;
private $totalProjectPayments;
private $orderType;
private $orderDirection;
public function __construct( $year, $orderType, $orderDirection )
{
$this->year = $year;
$this->orderType = $orderType;
$this->orderDirection = $orderDirection;
$this->handle();
}
public function getProjectDetails()
{
return $this->projectDetails;
}
private function handle()
{
$this->setProjectsWithPayments();
$this->loopProjectsWithPayments();
}
private function setProjectsWithPayments()
{
$projectsArray = Payment::getProjectsWithPayments( $this->year );
$this->projectsWithPayments =
Project::getProjectsForReport(
$this->orderType, $this->orderDirection, FALSE, $projectsArray );
}
private function loopProjectsWithPayments()
{
foreach ( $this->projectsWithPayments as $this->project )
{
$this->setProjectname();
$this->setCustomer();
$this->setInitialsMonthPayments();
$this->loopPayments();
$this->setProjectDetails();
}
}
private function setProjectname()
{
$this->projectname = $this->project->projectname . '(' . $this->project->projectnumber . ')';
}
private function setCustomer()
{
$this->customer = $this->project->customer->name;
}
private function setInitialsMonthPayments()
{
for ( $i = 1; $i <= 12; $i ++ )
{
$this->monthPayments[ $i ] = ['paymentamount' => 0];
}
}
private function loopPayments()
{
$this->totalProjectPayments = 0;
foreach ( $this->project->invoices as $invoice )
{
foreach ( $invoice->payments as $this->payment )
{
$this->setMonthPayments();
$this->setTotalProjectPayments();
}
}
}
private function setMonthPayments()
{
$paymentYear = date( 'Y', strtotime( $this->payment->paymentdate ) );
$paymentMonth = date( 'n', strtotime( $this->payment->paymentdate ) );
if ( $paymentYear == $this->year )
$this->monthPayments[ $paymentMonth ]['paymentamount'] += $this->payment->paymentamount;
}
private function setTotalProjectPayments()
{
$paymentYear = date( 'Y', strtotime( $this->payment->paymentdate ) );
if ( $paymentYear == $this->year )
$this->totalProjectPayments += $this->payment->paymentamount;
}
private function setProjectDetails()
{
$this->projectDetails[] = [
'projectnumber' => $this->project->projectnumber,
'projectname' => $this->projectname,
'customer' => $this->customer,
'monthPayments' => $this->monthPayments,
'totalProjectPayments' => number_format( $this->totalProjectPayments, 0, ',', '.' )
];
}
}

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