first commit

This commit is contained in:
root 2026-01-10 16:16:39 +03:00
commit 5f5a28e292
154 changed files with 21454 additions and 0 deletions

126
.gitignore vendored Normal file
View File

@ -0,0 +1,126 @@
#-------------------------
# Operating Specific Junk Files
#-------------------------
# OS X
.DS_Store
.AppleDouble
.LSOverride
# OS X Thumbnails
._*
# Windows image file caches
Thumbs.db
ehthumbs.db
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# Linux
*~
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
#-------------------------
# Environment Files
#-------------------------
# These should never be under version control,
# as it poses a security risk.
.env
.vagrant
Vagrantfile
#-------------------------
# Temporary Files
#-------------------------
writable/cache/*
!writable/cache/index.html
writable/logs/*
!writable/logs/index.html
writable/session/*
!writable/session/index.html
writable/uploads/*
!writable/uploads/index.html
writable/debugbar/*
!writable/debugbar/index.html
php_errors.log
#-------------------------
# User Guide Temp Files
#-------------------------
user_guide_src/build/*
user_guide_src/cilexer/build/*
user_guide_src/cilexer/dist/*
user_guide_src/cilexer/pycilexer.egg-info/*
#-------------------------
# Test Files
#-------------------------
tests/coverage*
# Don't save phpunit under version control.
phpunit
#-------------------------
# Composer
#-------------------------
vendor/
#-------------------------
# IDE / Development Files
#-------------------------
# Modules Testing
_modules/*
# phpenv local config
.php-version
# Jetbrains editors (PHPStorm, etc)
.idea/
*.iml
# NetBeans
/nbproject/
/build/
/nbbuild/
/dist/
/nbdist/
/nbactions.xml
/nb-configuration.xml
/.nb-gradle/
# Sublime Text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
*.sublime-workspace
*.sublime-project
.phpintel
/api/
# Visual Studio Code
.vscode/
/results/
/phpunit*.xml

22
LICENSE Normal file
View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2014-2019 British Columbia Institute of Technology
Copyright (c) 2019-present CodeIgniter Foundation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

68
README.md Normal file
View File

@ -0,0 +1,68 @@
# CodeIgniter 4 Application Starter
## What is CodeIgniter?
CodeIgniter is a PHP full-stack web framework that is light, fast, flexible and secure.
More information can be found at the [official site](https://codeigniter.com).
This repository holds a composer-installable app starter.
It has been built from the
[development repository](https://github.com/codeigniter4/CodeIgniter4).
More information about the plans for version 4 can be found in [CodeIgniter 4](https://forum.codeigniter.com/forumdisplay.php?fid=28) on the forums.
You can read the [user guide](https://codeigniter.com/user_guide/)
corresponding to the latest version of the framework.
## Installation & updates
`composer create-project codeigniter4/appstarter` then `composer update` whenever
there is a new release of the framework.
When updating, check the release notes to see if there are any changes you might need to apply
to your `app` folder. The affected files can be copied or merged from
`vendor/codeigniter4/framework/app`.
## Setup
Copy `env` to `.env` and tailor for your app, specifically the baseURL
and any database settings.
## Important Change with index.php
`index.php` is no longer in the root of the project! It has been moved inside the *public* folder,
for better security and separation of components.
This means that you should configure your web server to "point" to your project's *public* folder, and
not to the project root. A better practice would be to configure a virtual host to point there. A poor practice would be to point your web server to the project root and expect to enter *public/...*, as the rest of your logic and the
framework are exposed.
**Please** read the user guide for a better explanation of how CI4 works!
## Repository Management
We use GitHub issues, in our main repository, to track **BUGS** and to track approved **DEVELOPMENT** work packages.
We use our [forum](http://forum.codeigniter.com) to provide SUPPORT and to discuss
FEATURE REQUESTS.
This repository is a "distribution" one, built by our release preparation script.
Problems with it can be raised on our forum, or as issues in the main repository.
## Server Requirements
PHP version 8.1 or higher is required, with the following extensions installed:
- [intl](http://php.net/manual/en/intl.requirements.php)
- [mbstring](http://php.net/manual/en/mbstring.installation.php)
> [!WARNING]
> - The end of life date for PHP 7.4 was November 28, 2022.
> - The end of life date for PHP 8.0 was November 26, 2023.
> - If you are still using PHP 7.4 or 8.0, you should upgrade immediately.
> - The end of life date for PHP 8.1 will be December 31, 2025.
Additionally, make sure that the following extensions are enabled in your PHP:
- json (enabled by default - don't turn it off)
- [mysqlnd](http://php.net/manual/en/mysqlnd.install.php) if you plan to use MySQL
- [libcurl](http://php.net/manual/en/curl.requirements.php) if you plan to use the HTTP\CURLRequest library

6
app/.htaccess Normal file
View File

@ -0,0 +1,6 @@
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>

15
app/Common.php Normal file
View File

@ -0,0 +1,15 @@
<?php
/**
* The goal of this file is to allow developers a location
* where they can overwrite core procedural functions and
* replace them with their own. This file is loaded during
* the bootstrap process and is called during the framework's
* execution.
*
* This can be looked at as a `master helper` file that is
* loaded early on, and may also contain additional functions
* that you'd like to use throughout your entire application
*
* @see: https://codeigniter.com/user_guide/extending/common.html
*/

202
app/Config/App.php Normal file
View File

@ -0,0 +1,202 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class App extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Base Site URL
* --------------------------------------------------------------------------
*
* URL to your CodeIgniter root. Typically, this will be your base URL,
* WITH a trailing slash:
*
* E.g., http://example.com/
*/
public string $baseURL = 'http://localhost:8080/';
/**
* Allowed Hostnames in the Site URL other than the hostname in the baseURL.
* If you want to accept multiple Hostnames, set this.
*
* E.g.,
* When your site URL ($baseURL) is 'http://example.com/', and your site
* also accepts 'http://media.example.com/' and 'http://accounts.example.com/':
* ['media.example.com', 'accounts.example.com']
*
* @var list<string>
*/
public array $allowedHostnames = [];
/**
* --------------------------------------------------------------------------
* Index File
* --------------------------------------------------------------------------
*
* Typically, this will be your `index.php` file, unless you've renamed it to
* something else. If you have configured your web server to remove this file
* from your site URIs, set this variable to an empty string.
*/
public string $indexPage = '';
/**
* --------------------------------------------------------------------------
* URI PROTOCOL
* --------------------------------------------------------------------------
*
* This item determines which server global should be used to retrieve the
* URI string. The default setting of 'REQUEST_URI' works for most servers.
* If your links do not seem to work, try one of the other delicious flavors:
*
* 'REQUEST_URI': Uses $_SERVER['REQUEST_URI']
* 'QUERY_STRING': Uses $_SERVER['QUERY_STRING']
* 'PATH_INFO': Uses $_SERVER['PATH_INFO']
*
* WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
public string $uriProtocol = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible.
|
| By default, only these are allowed: `a-z 0-9~%.:_-`
|
| Set an empty string to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be used as: '/\A[<permittedURIChars>]+\z/iu'
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
public string $permittedURIChars = 'a-z 0-9~%.:_\-';
/**
* --------------------------------------------------------------------------
* Default Locale
* --------------------------------------------------------------------------
*
* The Locale roughly represents the language and location that your visitor
* is viewing the site from. It affects the language strings and other
* strings (like currency markers, numbers, etc), that your program
* should run under for this request.
*/
public string $defaultLocale = 'en';
/**
* --------------------------------------------------------------------------
* Negotiate Locale
* --------------------------------------------------------------------------
*
* If true, the current Request object will automatically determine the
* language to use based on the value of the Accept-Language header.
*
* If false, no automatic detection will be performed.
*/
public bool $negotiateLocale = false;
/**
* --------------------------------------------------------------------------
* Supported Locales
* --------------------------------------------------------------------------
*
* If $negotiateLocale is true, this array lists the locales supported
* by the application in descending order of priority. If no match is
* found, the first locale will be used.
*
* IncomingRequest::setLocale() also uses this list.
*
* @var list<string>
*/
public array $supportedLocales = ['en'];
/**
* --------------------------------------------------------------------------
* Application Timezone
* --------------------------------------------------------------------------
*
* The default timezone that will be used in your application to display
* dates with the date helper, and can be retrieved through app_timezone()
*
* @see https://www.php.net/manual/en/timezones.php for list of timezones
* supported by PHP.
*/
public string $appTimezone = 'UTC';
/**
* --------------------------------------------------------------------------
* Default Character Set
* --------------------------------------------------------------------------
*
* This determines which character set is used by default in various methods
* that require a character set to be provided.
*
* @see http://php.net/htmlspecialchars for a list of supported charsets.
*/
public string $charset = 'UTF-8';
/**
* --------------------------------------------------------------------------
* Force Global Secure Requests
* --------------------------------------------------------------------------
*
* If true, this will force every request made to this application to be
* made via a secure connection (HTTPS). If the incoming request is not
* secure, the user will be redirected to a secure version of the page
* and the HTTP Strict Transport Security (HSTS) header will be set.
*/
public bool $forceGlobalSecureRequests = false;
/**
* --------------------------------------------------------------------------
* Reverse Proxy IPs
* --------------------------------------------------------------------------
*
* If your server is behind a reverse proxy, you must whitelist the proxy
* IP addresses from which CodeIgniter should trust headers such as
* X-Forwarded-For or Client-IP in order to properly identify
* the visitor's IP address.
*
* You need to set a proxy IP address or IP address with subnets and
* the HTTP header for the client IP address.
*
* Here are some examples:
* [
* '10.0.1.200' => 'X-Forwarded-For',
* '192.168.5.0/24' => 'X-Real-IP',
* ]
*
* @var array<string, string>
*/
public array $proxyIPs = [];
/**
* --------------------------------------------------------------------------
* Content Security Policy
* --------------------------------------------------------------------------
*
* Enables the Response's Content Secure Policy to restrict the sources that
* can be used for images, scripts, CSS files, audio, video, etc. If enabled,
* the Response object will populate default values for the policy from the
* `ContentSecurityPolicy.php` file. Controllers can always add to those
* restrictions at run time.
*
* For a better understanding of CSP, see these documents:
*
* @see http://www.html5rocks.com/en/tutorials/security/content-security-policy/
* @see http://www.w3.org/TR/CSP/
*/
public bool $CSPEnabled = false;
}

94
app/Config/Autoload.php Normal file
View File

@ -0,0 +1,94 @@
<?php
namespace Config;
use CodeIgniter\Config\AutoloadConfig;
/**
* -------------------------------------------------------------------
* AUTOLOADER CONFIGURATION
* -------------------------------------------------------------------
*
* This file defines the namespaces and class maps so the Autoloader
* can find the files as needed.
*
* NOTE: If you use an identical key in $psr4 or $classmap, then
* the values in this file will overwrite the framework's values.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Autoload extends AutoloadConfig
{
/**
* -------------------------------------------------------------------
* Namespaces
* -------------------------------------------------------------------
* This maps the locations of any namespaces in your application to
* their location on the file system. These are used by the autoloader
* to locate files the first time they have been instantiated.
*
* The 'Config' (APPPATH . 'Config') and 'CodeIgniter' (SYSTEMPATH) are
* already mapped for you.
*
* You may change the name of the 'App' namespace if you wish,
* but this should be done prior to creating any namespaced classes,
* else you will need to modify all of those classes for this to work.
*
* @var array<string, list<string>|string>
*/
public $psr4 = [
APP_NAMESPACE => APPPATH,
'App\Modules' => APPPATH . 'Modules',
'App\Libraries\Twig' => APPPATH . 'Libraries/Twig',
];
/**
* -------------------------------------------------------------------
* Class Map
* -------------------------------------------------------------------
* The class map provides a map of class names and their exact
* location on the drive. Classes loaded in this manner will have
* slightly faster performance because they will not have to be
* searched for within one or more directories as they would if they
* were being autoloaded through a namespace.
*
* Prototype:
* $classmap = [
* 'MyClass' => '/path/to/class/file.php'
* ];
*
* @var array<string, string>
*/
public $classmap = [];
/**
* -------------------------------------------------------------------
* Files
* -------------------------------------------------------------------
* The files array provides a list of paths to __non-class__ files
* that will be autoloaded. This can be useful for bootstrap operations
* or for loading functions.
*
* Prototype:
* $files = [
* '/path/to/my/file.php',
* ];
*
* @var list<string>
*/
public $files = [];
/**
* -------------------------------------------------------------------
* Helpers
* -------------------------------------------------------------------
* Prototype:
* $helpers = [
* 'form',
* ];
*
* @var list<string>
*/
public $helpers = [];
}

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);

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);

View File

@ -0,0 +1,38 @@
<?php
/*
* The environment testing is reserved for PHPUnit testing. It has special
* conditions built into the framework at various places to assist with that.
* You cant use it for your development.
*/
/*
|--------------------------------------------------------------------------
| 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.
*/
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. It's not widely used currently, and may not survive
| release of the framework.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);

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
app/Config/Cache.php Normal file
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;
}

79
app/Config/Constants.php Normal file
View File

@ -0,0 +1,79 @@
<?php
/*
| --------------------------------------------------------------------
| App Namespace
| --------------------------------------------------------------------
|
| This defines the default Namespace that is used throughout
| CodeIgniter to refer to the Application directory. Change
| this constant to change the namespace that all application
| classes should use.
|
| NOTE: changing this will require manually modifying the
| existing namespaces of App\* namespaced-classes.
*/
defined('APP_NAMESPACE') || define('APP_NAMESPACE', 'App');
/*
| --------------------------------------------------------------------------
| Composer Path
| --------------------------------------------------------------------------
|
| The path that Composer's autoload file is expected to live. By default,
| the vendor folder is in the Root directory, but you can customize that here.
*/
defined('COMPOSER_PATH') || define('COMPOSER_PATH', ROOTPATH . 'vendor/autoload.php');
/*
|--------------------------------------------------------------------------
| Timing Constants
|--------------------------------------------------------------------------
|
| Provide simple ways to work with the myriad of PHP functions that
| require information to be in seconds.
*/
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
| --------------------------------------------------------------------------
|
| Used to indicate the conditions under which the script is exit()ing.
| While there is no universal standard for error codes, there are some
| broad conventions. Three such conventions are mentioned below, for
| those who wish to make use of them. The CodeIgniter defaults were
| chosen for the least overlap with these conventions, while still
| leaving room for others to be defined in future versions and user
| applications.
|
| The three main conventions used for determining exit status codes
| are as follows:
|
| Standard C/C++ Library (stdlibc):
| http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
| (This link also contains other GNU-specific conventions)
| BSD sysexits.h:
| http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits
| Bash scripting:
| http://tldp.org/LDP/abs/html/exitcodes.html
|
*/
defined('EXIT_SUCCESS') || define('EXIT_SUCCESS', 0); // no errors
defined('EXIT_ERROR') || define('EXIT_ERROR', 1); // generic error
defined('EXIT_CONFIG') || define('EXIT_CONFIG', 3); // configuration error
defined('EXIT_UNKNOWN_FILE') || define('EXIT_UNKNOWN_FILE', 4); // file not found
defined('EXIT_UNKNOWN_CLASS') || define('EXIT_UNKNOWN_CLASS', 5); // unknown class
defined('EXIT_UNKNOWN_METHOD') || define('EXIT_UNKNOWN_METHOD', 6); // unknown class member
defined('EXIT_USER_INPUT') || define('EXIT_USER_INPUT', 7); // invalid user input
defined('EXIT_DATABASE') || define('EXIT_DATABASE', 8); // database error
defined('EXIT__AUTO_MIN') || define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code
defined('EXIT__AUTO_MAX') || define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code

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
app/Config/Cookie.php Normal file
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;
}

105
app/Config/Cors.php Normal file
View File

@ -0,0 +1,105 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Cross-Origin Resource Sharing (CORS) Configuration
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
*/
class Cors extends BaseConfig
{
/**
* The default CORS configuration.
*
* @var array{
* allowedOrigins: list<string>,
* allowedOriginsPatterns: list<string>,
* supportsCredentials: bool,
* allowedHeaders: list<string>,
* exposedHeaders: list<string>,
* allowedMethods: list<string>,
* maxAge: int,
* }
*/
public array $default = [
/**
* Origins for the `Access-Control-Allow-Origin` header.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
*
* E.g.:
* - ['http://localhost:8080']
* - ['https://www.example.com']
*/
'allowedOrigins' => [],
/**
* Origin regex patterns for the `Access-Control-Allow-Origin` header.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
*
* NOTE: A pattern specified here is part of a regular expression. It will
* be actually `#\A<pattern>\z#`.
*
* E.g.:
* - ['https://\w+\.example\.com']
*/
'allowedOriginsPatterns' => [],
/**
* Weather to send the `Access-Control-Allow-Credentials` header.
*
* The Access-Control-Allow-Credentials response header tells browsers whether
* the server allows cross-origin HTTP requests to include credentials.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
*/
'supportsCredentials' => false,
/**
* Set headers to allow.
*
* The Access-Control-Allow-Headers response header is used in response to
* a preflight request which includes the Access-Control-Request-Headers to
* indicate which HTTP headers can be used during the actual request.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
*/
'allowedHeaders' => [],
/**
* Set headers to expose.
*
* The Access-Control-Expose-Headers response header allows a server to
* indicate which response headers should be made available to scripts running
* in the browser, in response to a cross-origin request.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
*/
'exposedHeaders' => [],
/**
* Set methods to allow.
*
* The Access-Control-Allow-Methods response header specifies one or more
* methods allowed when accessing a resource in response to a preflight
* request.
*
* E.g.:
* - ['GET', 'POST', 'PUT', 'DELETE']
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
*/
'allowedMethods' => [],
/**
* Set how many seconds the results of a preflight request can be cached.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
*/
'maxAge' => 7200,
];
}

204
app/Config/Database.php Normal file
View File

@ -0,0 +1,204 @@
<?php
namespace Config;
use CodeIgniter\Database\Config;
/**
* Database Configuration
*/
class Database extends Config
{
/**
* The directory that holds the Migrations and Seeds directories.
*/
public string $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
/**
* Lets you choose which connection group to use if no other is specified.
*/
public string $defaultGroup = 'default';
/**
* The default database connection.
*
* @var array<string, mixed>
*/
public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
'foundRows' => false,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
// /**
// * Sample database connection for SQLite3.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'database' => 'database.db',
// 'DBDriver' => 'SQLite3',
// 'DBPrefix' => '',
// 'DBDebug' => true,
// 'swapPre' => '',
// 'failover' => [],
// 'foreignKeys' => true,
// 'busyTimeout' => 1000,
// 'synchronous' => null,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for Postgre.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => '',
// 'hostname' => 'localhost',
// 'username' => 'root',
// 'password' => 'root',
// 'database' => 'ci4',
// 'schema' => 'public',
// 'DBDriver' => 'Postgre',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'utf8',
// 'swapPre' => '',
// 'failover' => [],
// 'port' => 5432,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for SQLSRV.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => '',
// 'hostname' => 'localhost',
// 'username' => 'root',
// 'password' => 'root',
// 'database' => 'ci4',
// 'schema' => 'dbo',
// 'DBDriver' => 'SQLSRV',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'utf8',
// 'swapPre' => '',
// 'encrypt' => false,
// 'failover' => [],
// 'port' => 1433,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for OCI8.
// *
// * You may need the following environment variables:
// * NLS_LANG = 'AMERICAN_AMERICA.UTF8'
// * NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// * NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// * NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => 'localhost:1521/XEPDB1',
// 'username' => 'root',
// 'password' => 'root',
// 'DBDriver' => 'OCI8',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'AL32UTF8',
// 'swapPre' => '',
// 'failover' => [],
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
/**
* This database connection is used when running PHPUnit database tests.
*
* @var array<string, mixed>
*/
public array $tests = [
'DSN' => '',
'hostname' => '127.0.0.1',
'username' => '',
'password' => '',
'database' => ':memory:',
'DBDriver' => 'SQLite3',
'DBPrefix' => 'db_', // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE FOR CI DEVS
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => '',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'foreignKeys' => true,
'busyTimeout' => 1000,
'synchronous' => null,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
public function __construct()
{
parent::__construct();
// Ensure that we always set the database group to 'tests' if
// we are currently running an automated test suite, so that
// we don't overwrite live data on accident.
if (ENVIRONMENT === 'testing') {
$this->defaultGroup = 'tests';
}
}
}

43
app/Config/DocTypes.php Normal file
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;
}

121
app/Config/Email.php Normal file
View File

@ -0,0 +1,121 @@
<?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 = 'mail';
/**
* 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 = 'text';
/**
* 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;
}

92
app/Config/Encryption.php Normal file
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';
}

55
app/Config/Events.php Normal file
View File

@ -0,0 +1,55 @@
<?php
namespace Config;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\HotReloader\HotReloader;
/*
* --------------------------------------------------------------------
* Application Events
* --------------------------------------------------------------------
* Events allow you to tap into the execution of the program without
* modifying or extending core files. This file provides a central
* location to define your events, though they can always be added
* at run-time, also, if needed.
*
* You create code that can execute by subscribing to events with
* the 'on()' method. This accepts any form of callable, including
* Closures, that will be executed when the event is triggered.
*
* Example:
* Events::on('create', [$myInstance, 'myMethod']);
*/
Events::on('pre_system', static function (): void {
if (ENVIRONMENT !== 'testing') {
if (ini_get('zlib.output_compression')) {
throw FrameworkException::forEnabledZlibOutputCompression();
}
while (ob_get_level() > 0) {
ob_end_flush();
}
ob_start(static fn ($buffer) => $buffer);
}
/*
* --------------------------------------------------------------------
* Debug Toolbar Listeners.
* --------------------------------------------------------------------
* If you delete, they will no longer be collected.
*/
if (CI_DEBUG && ! is_cli()) {
Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
service('toolbar')->respond();
// Hot Reload route - for framework use on the hot reloader.
if (ENVIRONMENT === 'development') {
service('routes')->get('__hot-reload', static function (): void {
(new HotReloader())->run();
});
}
}
});

106
app/Config/Exceptions.php Normal file
View File

@ -0,0 +1,106 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\ExceptionHandler;
use CodeIgniter\Debug\ExceptionHandlerInterface;
use Psr\Log\LogLevel;
use Throwable;
/**
* Setup how the exception handler works.
*/
class Exceptions extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* LOG EXCEPTIONS?
* --------------------------------------------------------------------------
* If true, then exceptions will be logged
* through Services::Log.
*
* Default: true
*/
public bool $log = true;
/**
* --------------------------------------------------------------------------
* DO NOT LOG STATUS CODES
* --------------------------------------------------------------------------
* Any status codes here will NOT be logged if logging is turned on.
* By default, only 404 (Page Not Found) exceptions are ignored.
*
* @var list<int>
*/
public array $ignoreCodes = [404];
/**
* --------------------------------------------------------------------------
* Error Views Path
* --------------------------------------------------------------------------
* This is the path to the directory that contains the 'cli' and 'html'
* directories that hold the views used to generate errors.
*
* Default: APPPATH.'Views/errors'
*/
public string $errorViewPath = APPPATH . 'Views/errors';
/**
* --------------------------------------------------------------------------
* HIDE FROM DEBUG TRACE
* --------------------------------------------------------------------------
* Any data that you would like to hide from the debug trace.
* In order to specify 2 levels, use "/" to separate.
* ex. ['server', 'setup/password', 'secret_token']
*
* @var list<string>
*/
public array $sensitiveDataInTrace = [];
/**
* --------------------------------------------------------------------------
* WHETHER TO THROW AN EXCEPTION ON DEPRECATED ERRORS
* --------------------------------------------------------------------------
* If set to `true`, DEPRECATED errors are only logged and no exceptions are
* thrown. This option also works for user deprecations.
*/
public bool $logDeprecations = true;
/**
* --------------------------------------------------------------------------
* LOG LEVEL THRESHOLD FOR DEPRECATIONS
* --------------------------------------------------------------------------
* If `$logDeprecations` is set to `true`, this sets the log level
* to which the deprecation will be logged. This should be one of the log
* levels recognized by PSR-3.
*
* The related `Config\Logger::$threshold` should be adjusted, if needed,
* to capture logging the deprecations.
*/
public string $deprecationLogLevel = LogLevel::WARNING;
/*
* DEFINE THE HANDLERS USED
* --------------------------------------------------------------------------
* Given the HTTP status code, returns exception handler that
* should be used to deal with this error. By default, it will run CodeIgniter's
* default handler and display the error information in the expected format
* for CLI, HTTP, or AJAX requests, as determined by is_cli() and the expected
* response format.
*
* Custom handlers can be returned if you want to handle one or more specific
* error codes yourself like:
*
* if (in_array($statusCode, [400, 404, 500])) {
* return new \App\Libraries\MyExceptionHandler();
* }
* if ($exception instanceOf PageNotFoundException) {
* return new \App\Libraries\MyExceptionHandler();
* }
*/
public function handler(int $statusCode, Throwable $exception): ExceptionHandlerInterface
{
return new ExceptionHandler($this);
}
}

37
app/Config/Feature.php Normal file
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;
}

111
app/Config/Filters.php Normal file
View File

@ -0,0 +1,111 @@
<?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>>
*
* [filter_name => classname]
* or [filter_name => [classname1, classname2, ...]]
*/
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,
'org' => \App\Filters\OrganizationFilter::class,
];
/**
* List of special required filters.
*
* The filters listed here are special. They are applied before and after
* other kinds of filters, and always applied even if a route does not exist.
*
* Filters set by default provide framework functionality. If removed,
* those functions will no longer work.
*
* @see https://codeigniter.com/user_guide/incoming/filters.html#provided-filters
*
* @var array{before: list<string>, after: list<string>}
*/
public array $required = [
'before' => [
'forcehttps', // Force Global Secure Requests
'pagecache', // Web Page Caching
],
'after' => [
'pagecache', // Web Page Caching
'performance', // Performance Metrics
'toolbar', // Debug Toolbar
],
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array{
* before: array<string, array{except: list<string>|string}>|list<string>,
* after: array<string, array{except: list<string>|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.).
*
* Example:
* 'POST' => ['foo', 'bar']
*
* If you use this, you should disable auto-routing because auto-routing
* permits any HTTP method to access a controller. Accessing the controller
* with a method you don't expect could bypass the filter.
*
* @var array<string, list<string>>
*/
public array $methods = [];
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*
* @var array<string, array<string, list<string>>>
*/
public array $filters = [];
}

View File

@ -0,0 +1,12 @@
<?php
namespace Config;
use CodeIgniter\Config\ForeignCharacters as BaseForeignCharacters;
/**
* @immutable
*/
class ForeignCharacters extends BaseForeignCharacters
{
}

64
app/Config/Format.php Normal file
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
app/Config/Generators.php Normal file
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
app/Config/Honeypot.php Normal file
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
app/Config/Images.php Normal file
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
app/Config/Kint.php Normal file
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;
}

151
app/Config/Logger.php Normal file
View File

@ -0,0 +1,151 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Log\Handlers\FileHandler;
use CodeIgniter\Log\Handlers\HandlerInterface;
class Logger extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Error Logging Threshold
* --------------------------------------------------------------------------
*
* You can enable error logging by setting a threshold over zero. The
* threshold determines what gets logged. Any values below or equal to the
* threshold will be logged.
*
* Threshold options are:
*
* - 0 = Disables logging, Error logging TURNED OFF
* - 1 = Emergency Messages - System is unusable
* - 2 = Alert Messages - Action Must Be Taken Immediately
* - 3 = Critical Messages - Application component unavailable, unexpected exception.
* - 4 = Runtime Errors - Don't need immediate action, but should be monitored.
* - 5 = Warnings - Exceptional occurrences that are not errors.
* - 6 = Notices - Normal but significant events.
* - 7 = Info - Interesting events, like user logging in, etc.
* - 8 = Debug - Detailed debug information.
* - 9 = All Messages
*
* You can also pass an array with threshold levels to show individual error types
*
* array(1, 2, 3, 8) = Emergency, Alert, Critical, and Debug messages
*
* For a live site you'll usually enable Critical or higher (3) to be logged otherwise
* your log files will fill up very fast.
*
* @var int|list<int>
*/
public $threshold = (ENVIRONMENT === 'production') ? 4 : 9;
/**
* --------------------------------------------------------------------------
* Date Format for Logs
* --------------------------------------------------------------------------
*
* Each item that is logged has an associated date. You can use PHP date
* codes to set your own date formatting
*/
public string $dateFormat = 'Y-m-d H:i:s';
/**
* --------------------------------------------------------------------------
* Log Handlers
* --------------------------------------------------------------------------
*
* The logging system supports multiple actions to be taken when something
* is logged. This is done by allowing for multiple Handlers, special classes
* designed to write the log to their chosen destinations, whether that is
* a file on the getServer, a cloud-based service, or even taking actions such
* as emailing the dev team.
*
* Each handler is defined by the class name used for that handler, and it
* MUST implement the `CodeIgniter\Log\Handlers\HandlerInterface` interface.
*
* The value of each key is an array of configuration items that are sent
* to the constructor of each handler. The only required configuration item
* is the 'handles' element, which must be an array of integer log levels.
* This is most easily handled by using the constants defined in the
* `Psr\Log\LogLevel` class.
*
* Handlers are executed in the order defined in this array, starting with
* the handler on top and continuing down.
*
* @var array<class-string<HandlerInterface>, array<string, int|list<string>|string>>
*/
public array $handlers = [
/*
* --------------------------------------------------------------------
* File Handler
* --------------------------------------------------------------------
*/
FileHandler::class => [
// The log levels that this handler will handle.
'handles' => [
'critical',
'alert',
'emergency',
'debug',
'error',
'info',
'notice',
'warning',
],
/*
* The default filename extension for log files.
* An extension of 'php' allows for protecting the log files via basic
* scripting, when they are to be stored under a publicly accessible directory.
*
* NOTE: Leaving it blank will default to 'log'.
*/
'fileExtension' => '',
/*
* The file system permissions to be applied on newly created log files.
*
* IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
* integer notation (i.e. 0700, 0644, etc.)
*/
'filePermissions' => 0644,
/*
* Logging Directory Path
*
* By default, logs are written to WRITEPATH . 'logs/'
* Specify a different destination here, if desired.
*/
'path' => '',
],
/*
* The ChromeLoggerHandler requires the use of the Chrome web browser
* and the ChromeLogger extension. Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ChromeLoggerHandler' => [
// /*
// * The log levels that this handler will handle.
// */
// 'handles' => ['critical', 'alert', 'emergency', 'debug',
// 'error', 'info', 'notice', 'warning'],
// ],
/*
* The ErrorlogHandler writes the logs to PHP's native `error_log()` function.
* Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ErrorlogHandler' => [
// /* The log levels this handler can handle. */
// 'handles' => ['critical', 'alert', 'emergency', 'debug', 'error', 'info', 'notice', 'warning'],
//
// /*
// * The message type where the error should go. Can be 0 or 4, or use the
// * class constants: `ErrorlogHandler::TYPE_OS` (0) or `ErrorlogHandler::TYPE_SAPI` (4)
// */
// 'messageType' => 0,
// ],
];
}

50
app/Config/Migrations.php Normal file
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
app/Config/Mimes.php Normal file
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;
}
}

82
app/Config/Modules.php Normal file
View File

@ -0,0 +1,82 @@
<?php
namespace Config;
use CodeIgniter\Modules\Modules as BaseModules;
/**
* Modules Configuration.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Modules extends BaseModules
{
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all elements listed in
* $aliases below. If false, no auto-discovery will happen at all,
* giving a slight performance boost.
*
* @var bool
*/
public $enabled = true;
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery Within Composer Packages?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all namespaces loaded
* by Composer, as well as the namespaces configured locally.
*
* @var bool
*/
public $discoverInComposer = true;
/**
* The Composer package list for Auto-Discovery
* This setting is optional.
*
* E.g.:
* [
* 'only' => [
* // List up all packages to auto-discover
* 'codeigniter4/shield',
* ],
* ]
* or
* [
* 'exclude' => [
* // List up packages to exclude.
* 'pestphp/pest',
* ],
* ]
*
* @var array{only?: list<string>, exclude?: list<string>}
*/
public $composerPackages = [];
/**
* --------------------------------------------------------------------------
* Auto-Discovery Rules
* --------------------------------------------------------------------------
*
* Aliases list of all discovery classes that will be active and used during
* the current application request.
*
* If it is not listed, only the base application elements will be used.
*
* @var list<string>
*/
public $aliases = [
'events',
'filters',
'registrars',
'routes',
'services',
];
}

30
app/Config/Optimize.php Normal file
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;
}

38
app/Config/Pager.php Normal file
View File

@ -0,0 +1,38 @@
<?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_full' => 'App\Views\pager\bootstrap_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;
}

78
app/Config/Paths.php Normal file
View File

@ -0,0 +1,78 @@
<?php
namespace Config;
/**
* Paths
*
* Holds the paths that are used by the system to
* locate the main directories, app, system, etc.
*
* Modifying these allows you to restructure your application,
* share a system folder between multiple applications, and more.
*
* All paths are relative to the project's root folder.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Paths
{
/**
* ---------------------------------------------------------------
* SYSTEM FOLDER NAME
* ---------------------------------------------------------------
*
* This must contain the name of your "system" folder. Include
* the path if the folder is not in the same directory as this file.
*/
public string $systemDirectory = __DIR__ . '/../../vendor/codeigniter4/framework/system';
/**
* ---------------------------------------------------------------
* APPLICATION FOLDER NAME
* ---------------------------------------------------------------
*
* If you want this front controller to use a different "app"
* folder than the default one you can set its name here. The folder
* can also be renamed or relocated anywhere on your server. If
* you do, use a full server path.
*
* @see http://codeigniter.com/user_guide/general/managing_apps.html
*/
public string $appDirectory = __DIR__ . '/..';
/**
* ---------------------------------------------------------------
* WRITABLE DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "writable" directory.
* The writable directory allows you to group all directories that
* need write permission to a single place that can be tucked away
* for maximum security, keeping it out of the app and/or
* system directories.
*/
public string $writableDirectory = __DIR__ . '/../../writable';
/**
* ---------------------------------------------------------------
* TESTS DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "tests" directory.
*/
public string $testsDirectory = __DIR__ . '/../../tests';
/**
* ---------------------------------------------------------------
* VIEW DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of the directory that
* contains the view files used by your application. By
* default this is in `app/Views`. This value
* is used when no value is provided to `Services::renderer()`.
*/
public string $viewDirectory = __DIR__ . '/../Views';
}

28
app/Config/Publisher.php Normal file
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',
];
}

36
app/Config/Routes.php Normal file
View File

@ -0,0 +1,36 @@
<?php
use CodeIgniter\Router\RouteCollection;
/**
* @var RouteCollection $routes
*/
# Публичные маршруты (без фильтра org)
$routes->get('/', 'Home::index');
$routes->get('login', 'Auth::login');
$routes->post('login', 'Auth::login');
$routes->get('register', 'Auth::register');
$routes->post('register', 'Auth::register');
$routes->get('register/success', 'Auth::registerSuccess');
$routes->get('logout', 'Auth::logout');
$routes->get('auth/verify/(:any)', 'Auth::verify/$1');
$routes->get('auth/resend-verification', 'Auth::resendVerification');
$routes->post('auth/resend-verification', 'Auth::resendVerification');
# Защищённые маршруты (с фильтром org)
$routes->group('', ['filter' => 'org'], static function ($routes) {
$routes->get('organizations', 'Organizations::index');
$routes->get('organizations/create', 'Organizations::create');
$routes->post('organizations/create', 'Organizations::create');
$routes->get('organizations/edit/(:num)', 'Organizations::edit/$1');
$routes->post('organizations/edit/(:num)', 'Organizations::edit/$1');
$routes->get('organizations/delete/(:num)', 'Organizations::delete/$1');
$routes->post('organizations/delete/(:num)', 'Organizations::delete/$1');
$routes->get('organizations/switch/(:num)', 'Organizations::switch/$1');
});
# Подключение роутов модулей
require_once APPPATH . 'Modules/Clients/Config/Routes.php';

140
app/Config/Routing.php Normal file
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
app/Config/Security.php Normal file
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_bp';
/**
* --------------------------------------------------------------------------
* 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');
}

32
app/Config/Services.php Normal file
View File

@ -0,0 +1,32 @@
<?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.
*
* This file holds any application-specific services, or service overrides
* that you might need. An example has been included with the general
* method format you should use for your service methods. For more examples,
* see the core Services file at system/Config/Services.php.
*/
class Services extends BaseService
{
/*
* public static function example($getShared = true)
* {
* if ($getShared) {
* return static::getSharedInstance('example');
* }
*
* return new \CodeIgniter\Example();
* }
*/
}

127
app/Config/Session.php Normal file
View File

@ -0,0 +1,127 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Session\Handlers\BaseHandler;
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 = FileHandler::class;
/**
* --------------------------------------------------------------------------
* Session Cookie Name
* --------------------------------------------------------------------------
*
* The session cookie name, must contain only [0-9a-z_-] characters
*/
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
* --------------------------------------------------------------------------
*
* The location to save sessions to and is driver dependent.
*
* For the 'files' driver, it's a path to a writable directory.
* WARNING: Only absolute paths are supported!
*
* For the 'database' driver, it's a table name.
* Please read up the manual for the format with other session drivers.
*
* IMPORTANT: You are REQUIRED to set a valid save path!
*/
public string $savePath = WRITEPATH . 'session';
/**
* --------------------------------------------------------------------------
* Session Match IP
* --------------------------------------------------------------------------
*
* Whether to match the user's IP address when reading the session data.
*
* WARNING: If you're using the database driver, don't forget to update
* your session table's PRIMARY KEY when changing this setting.
*/
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. When set to FALSE, the data
* will be later deleted by the garbage collector.
*/
public bool $regenerateDestroy = false;
/**
* --------------------------------------------------------------------------
* Session Database Group
* --------------------------------------------------------------------------
*
* DB Group for the database session.
*/
public ?string $DBGroup = null;
/**
* --------------------------------------------------------------------------
* Lock Retry Interval (microseconds)
* --------------------------------------------------------------------------
*
* This is used for RedisHandler.
*
* Time (microseconds) to wait if lock cannot be acquired.
* The default is 100,000 microseconds (= 0.1 seconds).
*/
public int $lockRetryInterval = 100_000;
/**
* --------------------------------------------------------------------------
* Lock Max Retries
* --------------------------------------------------------------------------
*
* This is used for RedisHandler.
*
* Maximum number of lock acquisition attempts.
* The default is 300 times. That is lock timeout is about 30 (0.1 * 300)
* seconds.
*/
public int $lockMaxRetries = 300;
}

122
app/Config/Toolbar.php Normal file
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',
];
}

141
app/Config/Twig.php Normal file
View File

@ -0,0 +1,141 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Twig extends \Daycry\Twig\Config\Twig
{
public string $extension = '.twig';
/**
* Optional custom cache directory for compiled Twig templates.
* If null, the library default WRITEPATH.'cache/twig' is used.
*/
public string $cachePath = WRITEPATH . 'cache/twig';
/**
* @var list<string> functions_safe
*/
public array $functions_safe = ['form_open', 'form_close', 'form_hidden', 'form_error', 'json_decode', 'set_value', 'csrf_field'];
/**
* @var list<string> functions_asis
*/
public array $functions_asis = ['session', 'current_url', 'base_url', 'site_url'];
/**
* @var list<array<string,string>|string> paths
*
* A second parameter can be added to indicate the namespace of the view
*
* Example: public array $paths = [[APPPATH.'Module1/Views', 'module1'], APPPATH.'Module2/Views'];
*
* For use templates inside Module1
* $twig->render('@module1/view')
*
* OR
*
* For use templates inside Module2
*
* $twig->render('view')
*/
public array $paths = [
APPPATH . 'Views', // Добавляем стандартную папку Views в первую очередь
[APPPATH . 'Views/components', 'components'], // Компоненты таблиц
[APPPATH . 'Modules/Clients/Views', 'Clients']// Модуль Клиенты
];
/**
* @var array<string,array<mixed,string>|string> filters
*/
public array $filters = [];
/**
* @var list<string> extensions
*/
public array $extensions = [
\App\Libraries\Twig\TwigJsonDecodeExtension::class,
\App\Libraries\Twig\TwigGlobalsExtension::class,
];
/**
* When true, Twig will throw exceptions on undefined variables.
* Mirrors Twig Environment option 'strict_variables'. Default false
* to keep backward-compatible behavior.
*/
public bool $strictVariables = false;
/**
* 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.
*/
public bool $saveData = true;
// Discovery tuning flags removed: discoveryPersistList, discoveryPreload, discoveryUseAPCu, discoveryFingerprintMtimeDepth.
// Behavior now derived automatically from leanMode + overrides (see enableDiscoverySnapshot, etc.).
/**
* Lean Mode: master switch to minimize work and persisted artifacts.
* When true it disables by default:
* - Warmup summary persistence
* - Invalidation history
* - Extended dynamic metrics (name listings)
* - Extended diagnostics bundle
* - (Discovery snapshot) unless forced via override.
* Individual (nullable) overrides may re-enable specific items without leaving Lean mode.
* If leanMode = false the "full" profile enables all features by default. Nullable overrides = null mean
* "use base profile".
*/
public bool $leanMode = false;
/**
* Force (true/false) discovery snapshot regardless of profile.
* null = base profile decision (lean? false : true)
*/
public ?bool $enableDiscoverySnapshot = null;
/**
* Persist warmup summary. null = (lean? false : true)
*/
public ?bool $enableWarmupSummary = null;
/**
* Persist and expose invalidation history. null = (lean? false : true)
*/
public ?bool $enableInvalidationHistory = null;
/**
* Dynamic metrics (counts + names) for functions/filters. If false minimal counts (or zero) are shown.
* null = (lean? false : true)
*/
public ?bool $enableDynamicMetrics = null;
/**
* Extended diagnostics (static/dynamic name lists and non-essential details).
* null = (lean? false : true)
*/
public ?bool $enableExtendedDiagnostics = null;
/**
* @deprecated TTL is still honored if non-zero but auto mode typically uses no expiry (0). Will be simplified later.
*/
public int $cacheTtl = 0;
/**
* Toolbar tuning: when many templates/functions or high traffic, the debug toolbar
* panel can add overhead (name collection, template listing, json encoding, etc.).
* These flags allow trimming what the collector does at runtime.
*/
public bool $toolbarMinimal = false; // If true only core + cache + perf sections; skips discovery/warmup/invalidations/dynamics/template list/capabilities/persistence.
public bool $toolbarShowTemplates = true; // Show templates table (can be heavy if many templates)
public int $toolbarMaxTemplates = 50; // Hard cap for template rows
public bool $toolbarShowCapabilities = true; // Show capabilities panel
public bool $toolbarShowPersistence = true; // Show persistence panel
}

252
app/Config/UserAgents.php Normal file
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
app/Config/Validation.php Normal file
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
app/Config/View.php Normal file
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 = [];
}

270
app/Controllers/Auth.php Normal file
View File

@ -0,0 +1,270 @@
<?php
namespace App\Controllers;
use App\Models\UserModel;
use App\Models\OrganizationModel;
use App\Models\OrganizationUserModel;
use App\Libraries\EmailLibrary;
class Auth extends BaseController
{
protected $emailLibrary;
public function __construct()
{
$this->emailLibrary = new EmailLibrary();
}
public function register()
{
if ($this->request->getMethod() === 'POST') {
log_message('debug', 'POST запрос получен: ' . print_r($this->request->getPost(), true));
// Валидация (упрощенная для примера)
$rules = [
'name' => 'required|min_length[3]',
'email' => 'required|valid_email|is_unique[users.email]',
'password' => 'required|min_length[6]',
];
if (!$this->validate($rules)) {
return redirect()->back()->with('error', 'Ошибка регистрации');
}
$userModel = new UserModel();
$orgModel = new OrganizationModel();
$orgUserModel = new OrganizationUserModel();
// Генерируем токен для подтверждения email
$verificationToken = bin2hex(random_bytes(32));
// 1. Создаем пользователя с токеном верификации
$userData = [
'name' => $this->request->getPost('name'),
'email' => $this->request->getPost('email'),
'password' => $this->request->getPost('password'), // Хешируется в модели
'verification_token' => $verificationToken,
'email_verified' => 0,
];
log_message('debug', 'Registration userData: ' . print_r($userData, true));
$userId = $userModel->insert($userData);
log_message('debug', 'Insert result, userId: ' . $userId);
// 2. Создаем "Личную организацию" (п. 5.2.1 ТЗ)
$orgData = [
'owner_id' => $userId,
'name' => 'Личное пространство',
'type' => 'personal',
];
$orgId = $orgModel->insert($orgData);
// 3. Привязываем пользователя к этой организации (роль owner)
$orgUserModel->insert([
'organization_id' => $orgId,
'user_id' => $userId,
'role' => 'owner',
'status' => 'active',
'joined_at' => date('Y-m-d H:i:s'),
]);
// 4. Отправляем письмо для подтверждения email
$this->emailLibrary->sendVerificationEmail(
$userData['email'],
$userData['name'],
$verificationToken
);
// 5. Показываем сообщение о необходимости подтверждения
session()->setFlashdata('success', 'Регистрация успешна! Пожалуйста, проверьте вашу почту и подтвердите email.');
return redirect()->to('/register/success');
}
return $this->renderTwig('auth/register');
}
/**
* Страница после успешной регистрации
*/
public function registerSuccess()
{
return $this->renderTwig('auth/register_success');
}
/**
* Подтверждение email по токену
*/
public function verify($token)
{
log_message('debug', 'Verify called with token: ' . $token);
if (empty($token)) {
return $this->renderTwig('auth/verify_error', [
'message' => 'Отсутствует токен подтверждения.'
]);
}
$userModel = new UserModel();
// Ищем пользователя по токену
$user = $userModel->where('verification_token', $token)->first();
log_message('debug', 'User found: ' . ($user ? 'yes' : 'no'));
if ($user) {
log_message('debug', 'User email_verified: ' . $user['email_verified']);
}
if (!$user) {
return $this->renderTwig('auth/verify_error', [
'message' => 'Недействительная ссылка для подтверждения. Возможно, ссылка уже была использована или истек срок её действия.'
]);
}
if ($user['email_verified']) {
return $this->renderTwig('auth/verify_error', [
'message' => 'Email уже подтверждён. Вы можете войти в систему.'
]);
}
// Подтверждаем email
$updateData = [
'email_verified' => 1,
'verified_at' => date('Y-m-d H:i:s'),
'verification_token' => null, // Удаляем токен после использования
];
$result = $userModel->update($user['id'], $updateData);
log_message('debug', 'Update result: ' . ($result ? 'success' : 'failed'));
log_message('debug', 'Update data: ' . print_r($updateData, true));
if (!$result) {
log_message('error', 'Update errors: ' . print_r($userModel->errors(), true));
}
// Отправляем приветственное письмо
$this->emailLibrary->sendWelcomeEmail($user['email'], $user['name']);
return $this->renderTwig('auth/verify_success', [
'name' => $user['name']
]);
}
/**
* Повторная отправка письма для подтверждения
*/
public function resendVerification()
{
if ($this->request->getMethod() === 'POST') {
$email = $this->request->getPost('email');
if (empty($email)) {
return redirect()->back()->with('error', 'Введите email');
}
$userModel = new UserModel();
$user = $userModel->where('email', $email)->first();
if (!$user) {
return redirect()->back()->with('error', 'Пользователь с таким email не найден');
}
if ($user['email_verified']) {
return redirect()->to('/login')->with('info', 'Email уже подтверждён. Вы можете войти.');
}
// Генерируем новый токен
$newToken = bin2hex(random_bytes(32));
$userModel->update($user['id'], [
'verification_token' => $newToken
]);
// Отправляем письмо повторно
$this->emailLibrary->sendVerificationEmail(
$user['email'],
$user['name'],
$newToken
);
return redirect()->back()->with('success', 'Письмо для подтверждения отправлено повторно. Проверьте почту.');
}
return $this->renderTwig('auth/resend_verification');
}
public function login()
{
if ($this->request->getMethod() === 'POST') {
$userModel = new \App\Models\UserModel();
$orgUserModel = new \App\Models\OrganizationUserModel();
$email = $this->request->getPost('email');
$password = $this->request->getPost('password');
$user = $userModel->where('email', $email)->first();
if ($user && password_verify($password, $user['password'])) {
// Проверяем, подтвержден ли email
if (!$user['email_verified']) {
session()->setFlashdata('warning', 'Email не подтверждён. Проверьте почту или <a href="/auth/resend-verification">запросите письмо повторно</a>.');
return redirect()->to('/login');
}
// Получаем организации пользователя
$userOrgs = $orgUserModel->where('user_id', $user['id'])->findAll();
if (empty($userOrgs)) {
// Экстремальный случай: если по какой-то причине у пользователя нет организаций
session()->setFlashdata('error', 'Ваш аккаунт не привязан ни к одной организации. Обратитесь к поддержке.');
return redirect()->to('/login');
}
// Базовые данные сессии (пользователь авторизован)
$sessionData = [
'user_id' => $user['id'],
'email' => $user['email'],
'name' => $user['name'],
'isLoggedIn' => true
];
// АВТОМАТИЧЕСКИЙ ВЫБОР ОРГАНИЗАЦИИ
if (count($userOrgs) === 1) {
// Если одна организация — заходим автоматически для удобства
$sessionData['active_org_id'] = $userOrgs[0]['organization_id'];
session()->set($sessionData);
return redirect()->to('/');
}
// ОЧИЩАЕМ active_org_id если несколько организаций
session()->remove('active_org_id');
// Если несколько организаций — отправляем на страницу выбора
session()->set($sessionData);
// (Опционально) Записываем информацию, что пользователь залогинен, но орга не выбрана,
// чтобы страница /organizations не редиректнула его обратно (см. Organizations::index)
session()->setFlashdata('info', 'Выберите пространство для работы');
return redirect()->to('/organizations');
//}
} else {
return redirect()->back()->with('error', 'Неверный логин или пароль');
}
}
return $this->renderTwig('auth/login');
}
public function logout()
{
session()->destroy();
session()->remove('active_org_id');
return redirect()->to('/');
}
}

View File

@ -0,0 +1,233 @@
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Models\OrganizationModel;
/**
* 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:
* ```
* class Home extends BaseController
* ```
*
* For security, be sure to declare any new methods as protected or private.
*/
abstract class BaseController extends Controller
{
/**
* Be sure to declare properties for any property fetch you initialized.
* The creation of dynamic property is deprecated in PHP 8.2.
*/
protected $session;
/**
* @return void
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Load here all helpers you want to be available in your controllers that extend BaseController.
// Caution: Do not put the this below the parent::initController() call below.
// $this->helpers = ['form', 'url'];
// Caution: Do not edit this line.
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
$this->session = service('session');
}
public function renderTwig($template, $data = [])
{
helper('csrf');
$twig = \Config\Services::twig();
// oldInput из сессии добавляется в данные шаблона
// Расширение TwigGlobalsExtension автоматически добавляет session, alerts, old, currentOrg
$oldInput = $this->session->get('_ci_old_input') ?? [];
$data['old'] = $data['old'] ?? $oldInput;
ob_start();
$twig->display($template, $data);
$content = ob_get_clean();
return $content;
}
// ========================================
// Методы для универсальных таблиц
// ========================================
/**
* Конфигурация таблицы - переопределяется в каждом контроллере
*/
protected function getTableConfig(): array
{
return [
'model' => null,
'columns' => [],
'searchable' => [],
'sortable' => [],
'defaultSort' => 'id',
'order' => 'asc',
'viewPath' => '',
'partialPath' => '',
'itemsKey' => 'items',
'scope' => null, // callable($builder) для дополнительных модификаций
];
}
/**
* Проверка AJAX запроса
*/
protected function isAjax(): bool
{
$header = $this->request->header('X-Requested-With');
$value = $header ? $header->getValue() : '';
return strtolower($value) === 'xmlhttprequest';
}
/**
* Подготовка данных таблицы (общая логика для всех таблиц)
*/
protected function prepareTableData(?array $config = null): array
{
$config = array_merge($this->getTableConfig(), $config ?? []);
$page = (int) ($this->request->getGet('page') ?? 1);
$perPage = (int) ($this->request->getGet('perPage') ?? 10);
$sort = $this->request->getGet('sort') ?? $config['defaultSort'];
$order = $this->request->getGet('order') ?? $config['order'];
// Исправление: получаем фильтры из параметра filters[]
$filters = [];
$rawFilters = $this->request->getGet('filters');
if ($rawFilters) {
if (is_array($rawFilters)) {
$filters = $rawFilters;
} else {
// Для обратной совместимости, если фильтры пришли в строке
parse_str($rawFilters, $filters);
if (isset($filters['filters'])) {
$filters = $filters['filters'];
}
}
} else {
// Старый способ извлечения фильтров для совместимости
foreach ($this->request->getGet() as $key => $value) {
if (str_starts_with($key, 'filters[') && str_ends_with($key, ']')) {
$field = substr($key, 8, -1); // Исправлено: было 9, должно быть 8
$filters[$field] = $value;
}
}
}
$model = $config['model'];
$builder = $model->builder();
// Сбрасываем все предыдущие условия
$builder->resetQuery();
if (isset($config['scope']) && is_callable($config['scope'])) {
$config['scope']($builder);
}
// Применяем фильтры
foreach ($filters as $field => $value) {
if ($value !== '' && in_array($field, $config['searchable'])) {
$builder->like($field, $value);
}
}
// Сортировка
if ($sort && in_array($sort, $config['sortable'])) {
$builder->orderBy($sort, $order);
}
// Исправлено: countAllResults(false) вместо countAll()
// Сохраняем текущее состояние builder для подсчета
$countBuilder = clone $builder;
$total = $countBuilder->countAllResults(false);
// Получаем данные с пагинацией
$builder->select('*');
$items = $builder->limit($perPage, ($page - 1) * $perPage)->get()->getResult();
$from = ($page - 1) * $perPage + 1;
$to = min($page * $perPage, $total);
$pagerData = [
'currentPage' => $page,
'pageCount' => $total > 0 ? (int) ceil($total / $perPage) : 1,
'total' => $total,
'perPage' => $perPage,
'from' => $from,
'to' => $to,
];
$pagerStub = new class($pagerData) {
private $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function getCurrentPage(): int
{
return $this->data['currentPage'] ?? 1;
}
public function getPageCount(): int
{
return $this->data['pageCount'] ?? 1;
}
public function getTotal(): int
{
return $this->data['total'] ?? 0;
}
public function getDetails(): array
{
return $this->data;
}
};
$data = [
$config['itemsKey'] => $items,
'pager' => $pagerStub,
'pagerDetails' => $pagerData,
'perPage' => $perPage,
'sort' => $sort,
'order' => $order,
'filters' => $filters,
'columns' => $config['columns'],
];
// В конце prepareTableData, перед return
log_message('debug', 'Total records calculated: ' . $total);
log_message('debug', 'Organization ID: ' . session()->get('active_org_id'));
log_message('debug', 'SQL Query: ' . $countBuilder->getCompiledSelect());
return $data;
}
/**
* AJAX endpoint для таблицы - возвращает partial (tbody + tfoot)
*/
public function table()
{
$config = $this->getTableConfig();
$data = $this->prepareTableData($config);
if (!$this->isAjax()) {
return redirect()->to('/');
}
return $this->renderTwig($config['partialPath'], $data);
}
}

42
app/Controllers/Home.php Normal file
View File

@ -0,0 +1,42 @@
<?php
namespace App\Controllers;
use App\Models\OrganizationModel;
use App\Models\OrganizationUserModel;
class Home extends BaseController
{
public function index()
{
//log_message('debug', '[HOME INDEX] START: active_org_id = ' . (session()->get('active_org_id') ?? 'NULL'));
if (!session()->get('isLoggedIn')) {
return $this->renderTwig('landing/index');
}
// Получаем текущую организацию из сессии
$orgId = session()->get('active_org_id');
if (empty($orgId)){
session()->remove('active_org_id');
return redirect()->to('/organizations');
}
// Загружаем данные организации для шапки (имя, логотип)
// $orgModel = new OrganizationModel();
// $currentOrg = $orgModel->find($orgId);
// // print_r($currentOrg);
// // die();
// // Если организации нет (сессия слетела), кидаем на выбор
// if (!$currentOrg) {
// session()->remove('active_org_id');
// return redirect()->to('/organizations');
// }
// Передаем данные в шаблон
$data = [
'title' => 'Рабочий стол',
//'currentOrg' => $currentOrg,
];
return $this->renderTwig('dashboard/index', $data);
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace App\Controllers;
class Landing extends BaseController
{
public function index()
{
// Если пользователь уже залогинен, редиректим его сразу на выбор орги
if (session()->get('isLoggedIn')) {
return redirect()->to('/organizations');
}
return $this->renderTwig('landing/index');
}
}

View File

@ -0,0 +1,245 @@
<?php
namespace App\Controllers;
use App\Models\OrganizationModel;
use App\Models\OrganizationUserModel;
class Organizations extends BaseController
{
public function index()
{
$orgModel = new OrganizationModel();
$orgUserModel = new OrganizationUserModel();
$userId = session()->get('user_id');
// Получаем организации пользователя через связующую таблицу
$userOrgLinks = $orgUserModel->where('user_id', $userId)->findAll();
// Нам нужно получить сами данные организаций
$orgIds = array_column($userOrgLinks, 'organization_id');
$organizations = [];
if (!empty($orgIds)) {
$organizations = $orgModel->whereIn('id', $orgIds)->findAll();
}
// Логика автоперехода (как в Auth)
// if (count($organizations) === 1) {
// session()->set('active_org_id', $organizations[0]['id']);
// return redirect()->to('/');
// }
// Если больше 1 или 0, показываем список
return $this->renderTwig('organizations/index', [
'organizations' => $organizations,
'count' => count($organizations)
]);
}
public function create()
{
if ($this->request->getMethod() === 'POST') {
$orgModel = new OrganizationModel();
$orgUserModel = new OrganizationUserModel();
$rules = [
'name' => 'required|min_length[2]',
];
if (!$this->validate($rules)) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
// Собираем реквизиты в JSON
$requisites = [
'inn' => trim($this->request->getPost('inn') ?? ''),
'ogrn' => trim($this->request->getPost('ogrn') ?? ''),
'kpp' => trim($this->request->getPost('kpp') ?? ''),
'legal_address' => trim($this->request->getPost('legal_address') ?? ''),
'actual_address' => trim($this->request->getPost('actual_address') ?? ''),
'phone' => trim($this->request->getPost('phone') ?? ''),
'email' => trim($this->request->getPost('email') ?? ''),
'website' => trim($this->request->getPost('website') ?? ''),
'bank_name' => trim($this->request->getPost('bank_name') ?? ''),
'bank_bik' => trim($this->request->getPost('bank_bik') ?? ''),
'checking_account' => trim($this->request->getPost('checking_account') ?? ''),
'correspondent_account' => trim($this->request->getPost('correspondent_account') ?? ''),
];
// Создаем организацию
$orgId = $orgModel->insert([
'owner_id' => session()->get('user_id'),
'name' => $this->request->getPost('name'),
'type' => 'business',
'requisites' => json_encode($requisites),
'settings' => json_encode([]),
]);
// Привязываем владельца
$orgUserModel->insert([
'organization_id' => $orgId,
'user_id' => session()->get('user_id'),
'role' => 'owner',
'status' => 'active',
'joined_at' => date('Y-m-d H:i:s'),
]);
// Сразу переключаемся на неё
session()->set('active_org_id', $orgId);
session()->setFlashdata('success', 'Организация успешно создана!');
return redirect()->to('/');
}
// GET запрос - форму создания
return $this->renderTwig('organizations/create');
}
/**
* Редактирование организации
*/
public function edit($orgId)
{
$orgModel = new OrganizationModel();
$orgUserModel = new OrganizationUserModel();
$userId = session()->get('user_id');
// Проверяем: имеет ли пользователь доступ к этой организации?
$membership = $orgUserModel->where('organization_id', $orgId)
->where('user_id', $userId)
->first();
if (!$membership) {
session()->setFlashdata('error', 'Доступ запрещен');
return redirect()->to('/organizations');
}
// Получаем организацию
$organization = $orgModel->find($orgId);
if (!$organization) {
session()->setFlashdata('error', 'Организация не найдена');
return redirect()->to('/organizations');
}
// Декодируем requisites для формы
$requisites = json_decode($organization['requisites'] ?? '{}', true);
// Если это POST запрос — обновляем данные
if ($this->request->getMethod() === 'POST') {
$rules = [
'name' => 'required|min_length[2]',
];
if (!$this->validate($rules)) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
// Собираем обновлённые реквизиты
$newRequisites = [
'inn' => trim($this->request->getPost('inn') ?? ''),
'ogrn' => trim($this->request->getPost('ogrn') ?? ''),
'kpp' => trim($this->request->getPost('kpp') ?? ''),
'legal_address' => trim($this->request->getPost('legal_address') ?? ''),
'actual_address' => trim($this->request->getPost('actual_address') ?? ''),
'phone' => trim($this->request->getPost('phone') ?? ''),
'email' => trim($this->request->getPost('email') ?? ''),
'website' => trim($this->request->getPost('website') ?? ''),
'bank_name' => trim($this->request->getPost('bank_name') ?? ''),
'bank_bik' => trim($this->request->getPost('bank_bik') ?? ''),
'checking_account' => trim($this->request->getPost('checking_account') ?? ''),
'correspondent_account' => trim($this->request->getPost('correspondent_account') ?? ''),
];
// Обновляем организацию
$orgModel->update($orgId, [
'name' => $this->request->getPost('name'),
'requisites' => json_encode($newRequisites),
]);
session()->setFlashdata('success', 'Организация успешно обновлена!');
return redirect()->to('/organizations');
}
// GET запрос — форма редактирования
return $this->renderTwig('organizations/edit', [
'organization' => $organization,
'requisites' => $requisites
]);
}
/**
* Удаление организации
*/
public function delete($orgId)
{
$orgModel = new OrganizationModel();
$orgUserModel = new OrganizationUserModel();
$userId = session()->get('user_id');
// Проверяем: имеет ли пользователь доступ к этой организации?
$membership = $orgUserModel->where('organization_id', $orgId)
->where('user_id', $userId)
->first();
if (!$membership) {
session()->setFlashdata('error', 'Доступ запрещен');
return redirect()->to('/organizations');
}
// Проверяем, что пользователь — владелец
if ($membership['role'] !== 'owner') {
session()->setFlashdata('error', 'Только владелец может удалить организацию');
return redirect()->to('/organizations');
}
// Получаем организацию
$organization = $orgModel->find($orgId);
if (!$organization) {
session()->setFlashdata('error', 'Организация не найдена');
return redirect()->to('/organizations');
}
// Если это POST с подтверждением — удаляем
if ($this->request->getMethod() === 'POST') {
// Удаляем связи с пользователями
$orgUserModel->where('organization_id', $orgId)->delete();
// Мягкое удаление организации
$orgModel->delete($orgId);
// Если удаляли активную организацию — очищаем
if (session()->get('active_org_id') == $orgId) {
session()->remove('active_org_id');
}
session()->setFlashdata('success', 'Организация "' . $organization['name'] . '" удалена');
return redirect()->to('/organizations');
}
// GET запрос — страница подтверждения удаления
return $this->renderTwig('organizations/delete', [
'organization' => $organization
]);
}
public function switch($orgId)
{
$userId = session()->get('user_id');
$orgUserModel = new OrganizationUserModel();
// Проверяем: имеет ли пользователь доступ к этой организации?
$membership = $orgUserModel->where('organization_id', $orgId)
->where('user_id', $userId)
->first();
if ($membership) {
session()->set('active_org_id', $orgId);
session()->setFlashdata('success', 'Организация изменена');
return redirect()->to('/');
} else {
session()->setFlashdata('error', 'Доступ запрещен');
return redirect()->to('/organizations');
}
}
}

View File

View File

@ -0,0 +1,58 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateUsersTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'email' => [
'type' => 'VARCHAR',
'constraint' => 255,
'unique' => true,
],
'password' => [
'type' => 'VARCHAR',
'constraint' => 255,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 100,
],
'phone' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => true,
],
'avatar' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('users');
}
public function down()
{
$this->forge->dropTable('users');
}
}

View File

@ -0,0 +1,71 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateOrganizationsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'owner_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 255,
],
'type' => [
'type' => 'ENUM',
'constraint' => ['business', 'personal'],
'default' => 'business',
],
'logo' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => true,
],
'requisites' => [
'type' => 'JSON',
'null' => true, // Для хранения ИНН, ОГРН, адреса
],
'trial_ends_at' => [
'type' => 'DATETIME',
'null' => true, // Дата окончания триала (14 дней по ТЗ)
],
'settings' => [
'type' => 'JSON',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
'deleted_at' => [
'type' => 'DATETIME',
'null' => true, // Для мягкого удаления
],
]);
$this->forge->addKey('id', true);
$this->forge->addForeignKey('owner_id', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('organizations');
}
public function down()
{
$this->forge->dropTable('organizations');
}
}

View File

@ -0,0 +1,61 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateOrganizationUsersTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'organization_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'user_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'role' => [
'type' => 'ENUM',
'constraint' => ['owner', 'admin', 'manager', 'guest'],
'default' => 'manager',
],
'status' => [
'type' => 'ENUM',
'constraint' => ['active', 'invited', 'blocked'],
'default' => 'active',
],
'joined_at' => [
'type' => 'DATETIME',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
// Защита от дублей: один юзер не может быть дважды в одной организации
$this->forge->addUniqueKey(['organization_id', 'user_id']);
$this->forge->addForeignKey('organization_id', 'organizations', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('organization_users');
}
public function down()
{
$this->forge->dropTable('organization_users');
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateOrganizationSubscriptionsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'organization_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'module_code' => [
'type' => 'VARCHAR',
'constraint' => 50, // 'crm', 'booking', 'proof', 'tasks'
],
'status' => [
'type' => 'ENUM',
'constraint' => ['trial', 'active', 'expired', 'cancelled'],
'default' => 'trial',
],
'expires_at' => [
'type' => 'DATETIME',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
// Организация не может иметь две активные подписки на один модуль одновременно
$this->forge->addUniqueKey(['organization_id', 'module_code']);
$this->forge->addForeignKey('organization_id', 'organizations', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('organization_subscriptions');
}
public function down()
{
$this->forge->dropTable('organization_subscriptions');
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddEmailVerificationToUsers extends Migration
{
public function up()
{
// Добавляем поля для верификации email
$fields = [
'verification_token' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => true,
'comment' => 'Токен для подтверждения email',
],
'email_verified' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 0,
'comment' => 'Статус подтверждения email (0 - не подтвержден, 1 - подтвержден)',
],
'verified_at' => [
'type' => 'DATETIME',
'null' => true,
'comment' => 'Дата и время подтверждения email',
],
];
$this->forge->addColumn('users', $fields);
}
public function down()
{
$this->forge->dropColumn('users', ['verification_token', 'email_verified', 'verified_at']);
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateOrganizationsClientsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'organization_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 255,
],
'email' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => true,
],
'phone' => [
'type' => 'VARCHAR',
'constraint' => 50,
'null' => true,
],
'notes' => [
'type' => 'TEXT',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
'deleted_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('organization_id');
$this->forge->addForeignKey('organization_id', 'organizations', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('organizations_clients');
}
public function down()
{
$this->forge->dropTable('organizations_clients');
}
}

View File

0
app/Filters/.gitkeep Normal file
View File

View File

@ -0,0 +1,79 @@
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class OrganizationFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
$session = session();
$uri = $request->getUri();
$currentPath = $uri->getPath();
// === БЛОК ДЛЯ ГОСТЕЙ (НЕЗАЛОГИНЕННЫХ) ===
if (!$session->get('isLoggedIn')) {
// Список публичных маршрутов для гостей
$publicRoutes = [
'/',
'/login',
'/register',
'/register/success',
'/auth/verify',
'/auth/resend-verification',
];
if (!in_array($currentPath, $publicRoutes)) {
// Если гость лезет не туда (например /organizations) — на главную
return redirect()->to('/');
}
// Иначе пропускаем
return;
}
// =======================================
// === БЛОК ДЛЯ ЗАЛОГИНЕННЫХ ===
// Список маршрутов, доступных БЕЗ выбранной организации
$publicAuthRoutes = [
'/login',
'/register',
'/logout',
'/register/success',
'/auth/verify',
'/auth/resend-verification',
'/organizations',
'/organizations/create',
'/organizations/switch' // Начало пути для переключения
];
// Если мы на этих маршрутах — проверка orgId не нужна (мы просто выбираем её)
if (in_array($currentPath, $publicAuthRoutes) || strpos($currentPath, '/organizations/switch') === 0) {
return;
}
// Если мы попадаем сюда — значит пользователь идет на закрытую страницу (например /crm)
// или на главную (/).
// Главную страницу (/) мы проверяем на уровне контроллера Home::index,
// поэтому фильтр для '/' можно пропускать, ИЛИ проверить здесь.
// Пропустим '/', чтобы контроллер сам решил: редиректить на /organizations или показывать дашборд.
if ($currentPath === '/') {
return;
}
// Для всех остальных закрытых страниц проверяем active_org_id
if (empty(session()->get('active_org_id'))) {
return redirect()->to('/organizations');
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do nothing
}
}

0
app/Helpers/.gitkeep Normal file
View File

0
app/Language/.gitkeep Normal file
View File

View File

@ -0,0 +1,4 @@
<?php
// override core en language system validation or define your own en language validation message
return [];

0
app/Libraries/.gitkeep Normal file
View File

View File

@ -0,0 +1,68 @@
<?php
namespace App\Libraries;
use CodeIgniter\Email\Email;
use Config\Services;
class EmailLibrary
{
/**
* Отправить письмо для подтверждения email
*/
public function sendVerificationEmail(string $email, string $name, string $token): bool
{
$emailConfig = config('Email');
// Генерируем URL для подтверждения
$verificationUrl = base_url('/auth/verify/' . $token);
// Рендерим HTML письма через Twig
$twig = Services::twig();
$htmlBody = $twig->render('emails/verification', [
'name' => $name,
'verification_url' => $verificationUrl,
'app_name' => $emailConfig->fromName ?? 'Бизнес.Точка',
]);
$emailer = Services::email($emailConfig);
$emailer->setTo($email);
$emailer->setFrom($emailConfig->fromEmail, $emailConfig->fromName);
$emailer->setSubject('Подтверждение регистрации');
$emailer->setMessage($htmlBody);
try {
return $emailer->send();
} catch (\Exception $e) {
log_message('error', 'Ошибка отправки email: ' . $e->getMessage());
return false;
}
}
/**
* Отправить уведомление об успешной регистрации (после подтверждения)
*/
public function sendWelcomeEmail(string $email, string $name): bool
{
$emailConfig = config('Email');
$twig = Services::twig();
$htmlBody = $twig->render('emails/welcome', [
'name' => $name,
'app_name' => $emailConfig->fromName ?? 'Бизнес.Точка',
]);
$emailer = Services::email($emailConfig);
$emailer->setTo($email);
$emailer->setFrom($emailConfig->fromEmail, $emailConfig->fromName);
$emailer->setSubject('Добро пожаловать!');
$emailer->setMessage($htmlBody);
try {
return $emailer->send();
} catch (\Exception $e) {
log_message('error', 'Ошибка отправки email: ' . $e->getMessage());
return false;
}
}
}

View File

@ -0,0 +1,118 @@
<?php
namespace App\Libraries\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Twig\TwigGlobal;
use App\Models\OrganizationModel;
use Config\Services;
class TwigGlobalsExtension extends AbstractExtension
{
public function getFunctions(): array
{
return [
new TwigFunction('get_session', [$this, 'getSession'], ['is_safe' => ['html']]),
new TwigFunction('get_current_org', [$this, 'getCurrentOrg'], ['is_safe' => ['html']]),
new TwigFunction('get_alerts', [$this, 'getAlerts'], ['is_safe' => ['html']]),
new TwigFunction('render_pager', [$this, 'renderPager'], ['is_safe' => ['html']]),
new TwigFunction('is_active_route', [$this, 'isActiveRoute'], ['is_safe' => ['html']]),
new TwigFunction('get_current_route', [$this, 'getCurrentRoute'], ['is_safe' => ['html']]),
];
}
public function getSession()
{
return session();
}
public function getCurrentOrg()
{
$session = session();
$activeOrgId = $session->get('active_org_id');
if ($activeOrgId) {
$orgModel = new OrganizationModel();
return $orgModel->find($activeOrgId);
}
return null;
}
public function getAlerts(): array
{
$session = session();
$alerts = [];
$types = ['success', 'error', 'warning', 'info'];
foreach ($types as $type) {
if ($msg = $session->getFlashdata($type)) {
$alerts[] = ['type' => $type, 'message' => $msg];
}
}
if ($validationErrors = $session->getFlashdata('errors')) {
foreach ($validationErrors as $error) {
$alerts[] = ['type' => 'error', 'message' => $error];
}
}
return $alerts;
}
public function renderPager($pager)
{
if (!$pager) {
return '';
}
return $pager->links();
}
/**
* Проверяет, является ли текущий маршрут активным
*/
public function isActiveRoute($routes, $exact = false): bool
{
$currentRoute = $this->getCurrentRoute();
if (is_string($routes)) {
$routes = [$routes];
}
foreach ($routes as $route) {
if ($exact) {
// Точное совпадение
if ($currentRoute === $route) {
return true;
}
} else {
// Частичное совпадение (начинается с)
// Исключаем пустую строку, так как она совпадает с любым маршрутом
if ($route === '') {
// Для пустого маршрута проверяем только корень
if ($currentRoute === '') {
return true;
}
} elseif (strpos($currentRoute, $route) === 0) {
return true;
}
}
}
return false;
}
/**
* Получает текущий маршрут без базового URL
*/
public function getCurrentRoute(): string
{
$uri = service('uri');
$route = $uri->getRoutePath();
// Убираем начальный слеш если есть
return ltrim($route, '/');
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Libraries\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class TwigJsonDecodeExtension extends AbstractExtension
{
public function getFilters(): array
{
return [
new TwigFilter('json_decode', [$this, 'jsonDecode']),
];
}
public function jsonDecode(string $json, bool $assoc = true, int $depth = 512, int $flags = 0)
{
return json_decode($json, $assoc, $depth, $flags);
}
}

0
app/Models/.gitkeep Normal file
View File

View File

@ -0,0 +1,29 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class OrganizationModel extends Model
{
protected $table = 'organizations';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $useSoftDeletes = true; // Включаем мягкое удаление (deleted_at)
protected $allowedFields = ['owner_id', 'name', 'type', 'logo', 'requisites', 'trial_ends_at', 'settings'];
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
// Получить организации конкретного пользователя
public function getUserOrganizations(int $userId)
{
// TODO: Здесь мы будем делать JOIN с таблицей organization_users
// Пока упрощенная версия для владельца
return $this->where('owner_id', $userId)->findAll();
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class OrganizationUserModel extends Model
{
protected $table = 'organization_users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $allowedFields = ['organization_id', 'user_id', 'role', 'status', 'joined_at'];
protected $useTimestamps = false; // У нас есть только created_at, можно настроить вручную
}

44
app/Models/UserModel.php Normal file
View File

@ -0,0 +1,44 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = [
'email',
'password',
'name',
'phone',
'avatar',
// Поля для верификации email
'verification_token',
'email_verified',
'verified_at'
];
// Dates
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
// Хеширование пароля перед вставкой
protected $beforeInsert = ['hashPassword'];
protected $beforeUpdate = ['hashPassword'];
protected function hashPassword(array $data)
{
if (isset($data['data']['password'])) {
$data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
}
return $data;
}
}

View File

@ -0,0 +1,12 @@
<?php
// Подключаем роуты модуля Clients
$routes->group('clients', ['filter' => 'org', 'namespace' => 'App\Modules\Clients\Controllers'], static function ($routes) {
$routes->get('/', 'Clients::index');
$routes->get('table', 'Clients::table'); // AJAX endpoint для таблицы
$routes->get('new', 'Clients::new');
$routes->post('create', 'Clients::create');
$routes->get('edit/(:num)', 'Clients::edit/$1');
$routes->post('update/(:num)', 'Clients::update/$1');
$routes->get('delete/(:num)', 'Clients::delete/$1');
});

View File

@ -0,0 +1,177 @@
<?php
namespace App\Modules\Clients\Controllers;
use App\Controllers\BaseController;
use App\Modules\Clients\Models\ClientModel;
class Clients extends BaseController
{
protected $clientModel;
public function __construct()
{
$this->clientModel = new ClientModel();
}
public function index()
{
$config = $this->getTableConfig();
$data = $this->prepareTableData($config);
$data['title'] = 'Клиенты';
return $this->renderTwig($config['viewPath'], $data);
}
/**
* Конфигурация таблицы клиентов
*/
protected function getTableConfig(): array
{
$organizationId = session()->get('active_org_id');
return [
'model' => $this->clientModel,
'columns' => [
'name' => ['label' => 'Имя / Название', 'width' => '40%'],
'email' => ['label' => 'Email', 'width' => '25%'],
'phone' => ['label' => 'Телефон', 'width' => '20%'],
],
'searchable' => ['name', 'email', 'phone'],
'sortable' => ['name', 'email', 'phone', 'created_at'],
'defaultSort' => 'name',
'order' => 'asc',
'viewPath' => '@Clients/index',
'partialPath' => '@Clients/_table',
'itemsKey' => 'clients',
'scope' => function ($builder) use ($organizationId) {
$builder->where('organization_id', $organizationId);
},
];
}
public function table()
{
return parent::table();
}
public function new()
{
$data = [
'title' => 'Добавить клиента',
'client' => null,
];
return $this->renderTwig('@Clients/form', $data);
}
public function create()
{
$organizationId = session()->get('active_org_id');
$rules = [
'name' => 'required|min_length[2]|max_length[255]',
'email' => 'permit_empty|valid_email',
'phone' => 'permit_empty|max_length[50]',
];
if (!$this->validate($rules)) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
$this->clientModel->insert([
'organization_id' => $organizationId,
'name' => $this->request->getPost('name'),
'email' => $this->request->getPost('email') ?? null,
'phone' => $this->request->getPost('phone') ?? null,
'notes' => $this->request->getPost('notes') ?? null,
]);
if ($this->clientModel->errors()) {
return redirect()->back()->withInput()->with('error', 'Ошибка при создании клиента');
}
session()->setFlashdata('success', 'Клиент успешно добавлен');
return redirect()->to('/clients');
}
public function edit($id)
{
$organizationId = session()->get('active_org_id');
$client = $this->clientModel
->where('id', $id)
->where('organization_id', $organizationId)
->first();
if (!$client) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Клиент не найден');
}
$data = [
'title' => 'Редактировать клиента',
'client' => $client,
];
return $this->renderTwig('@Clients/form', $data);
}
public function update($id)
{
$organizationId = session()->get('active_org_id');
// Проверяем что клиент принадлежит организации
$client = $this->clientModel
->where('id', $id)
->where('organization_id', $organizationId)
->first();
if (!$client) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Клиент не найден');
}
$rules = [
'name' => 'required|min_length[2]|max_length[255]',
'email' => 'permit_empty|valid_email',
'phone' => 'permit_empty|max_length[50]',
];
if (!$this->validate($rules)) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
$this->clientModel->update($id, [
'name' => $this->request->getPost('name'),
'email' => $this->request->getPost('email') ?? null,
'phone' => $this->request->getPost('phone') ?? null,
'notes' => $this->request->getPost('notes') ?? null,
]);
if ($this->clientModel->errors()) {
return redirect()->back()->withInput()->with('error', 'Ошибка при обновлении клиента');
}
session()->setFlashdata('success', 'Клиент успешно обновлён');
return redirect()->to('/clients');
}
public function delete($id)
{
$organizationId = session()->get('active_org_id');
// Проверяем что клиент принадлежит организации
$client = $this->clientModel
->where('id', $id)
->where('organization_id', $organizationId)
->first();
if (!$client) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Клиент не найден');
}
$this->clientModel->delete($id);
session()->setFlashdata('success', 'Клиент удалён');
return redirect()->to('/clients');
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace App\Modules\Clients\Models;
use CodeIgniter\Model;
class ClientModel extends Model
{
protected $table = 'organizations_clients';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $useSoftDeletes = true;
protected $allowedFields = ['organization_id', 'name', 'email', 'phone', 'notes'];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
/**
* Получить клиентов организации
*/
public function forOrganization(int $organizationId)
{
return $this->where('organization_id', $organizationId);
}
/**
* Поиск по имени или email
*/
public function search(int $organizationId, string $query = '')
{
$builder = $this->forOrganization($organizationId);
if (!empty($query)) {
$builder->groupStart()
->like('name', $query)
->orLike('email', $query)
->orLike('phone', $query)
->groupEnd();
}
return $builder;
}
}

View File

@ -0,0 +1,92 @@
{# app/Modules/Clients/Views/_table.twig #}
{# Определяем тип запроса: AJAX = только tbody + footer #}
{% set isAjax = app.request.headers.get('X-Requested-With') == 'XMLHttpRequest' %}
{# Настройки пагинации - ИСПОЛЬЗУЕМ pagerDetails напрямую #}
{% if pagerDetails is defined %}
{% set pagination = pagerDetails %}
{% else %}
{# Fallback если pagerDetails нет #}
{% set pagination = {
currentPage: 1,
totalPages: 1,
total: clients|length|default(0),
perPage: perPage|default(10),
from: 1,
to: clients|length|default(0)
} %}
{% endif %}
{# Проверка на пустое состояние #}
{% set isEmpty = clients is empty or clients|length == 0 %}
{# AJAX запрос - tbody + footer #}
<tbody>
{% if isEmpty %}
<tr>
<td colspan="4" class="text-center py-5">
<i class="fa-solid fa-users text-muted mb-3" style="font-size: 3rem;"></i>
<p class="text-muted mb-3">
{% if filters.name or filters.email or filters.phone %}
Клиенты не найдены
{% else %}
Клиентов пока нет
{% endif %}
</p>
<a href="{{ base_url('/clients/new') }}" class="btn btn-primary">
<i class="fa-solid fa-plus me-2"></i>Добавить клиента
</a>
</td>
</tr>
{% else %}
{% for client in clients %}
<tr>
<td>
<div class="d-flex align-items-center">
<div class="bg-primary text-white rounded-circle d-flex justify-content-center align-items-center me-3" style="width:40px;height:40px;">
{{ client.name|first|upper }}
</div>
<div>
<strong>{{ client.name }}</strong>
{% if client.notes %}
<br><small class="text-muted">{{ client.notes|slice(0, 50) }}{{ client.notes|length > 50 ? '...' : '' }}</small>
{% endif %}
</div>
</div>
</td>
<td>
{% if client.email %}
<a href="mailto:{{ client.email }}">{{ client.email }}</a>
{% else %}
<span class="text-muted">—</span>
{% endif %}
</td>
<td>
{% if client.phone %}
<a href="tel:{{ client.phone }}">{{ client.phone }}</a>
{% else %}
<span class="text-muted">—</span>
{% endif %}
</td>
<td class="text-end">
<a href="{{ base_url('/clients/edit/' ~ client.id) }}" class="btn btn-sm btn-outline-primary" title="Редактировать">
<i class="fa-solid fa-pen"></i>
</a>
<a href="{{ base_url('/clients/delete/' ~ client.id) }}" class="btn btn-sm btn-outline-danger" title="Удалить" onclick="return confirm('Вы уверены что хотите удалить этого клиента?');">
<i class="fa-solid fa-trash"></i>
</a>
</td>
</tr>
{% endfor %}
{% endif %}
</tbody>
<tfoot>
<tr>
<td colspan="4">
{{ include('@components/table/pagination.twig', { pagination: pagination, id: 'clients-table' }) }}
</td>
</tr>
</tfoot>

View File

@ -0,0 +1,73 @@
{% extends 'layouts/base.twig' %}
{% import 'macros/forms.twig' as forms %}
{% block content %}
<div class="row justify-content-center">
<div class="col-lg-8">
<div class="card shadow-sm">
<div class="card-header bg-white py-3">
<div class="d-flex align-items-center">
<a href="{{ base_url('/clients') }}" class="btn btn-outline-secondary me-3">
<i class="fa-solid fa-arrow-left"></i>
</a>
<div>
<h1 class="h4 mb-0">{{ title }}</h1>
</div>
</div>
</div>
<div class="card-body">
{{ forms.form_open(client ? base_url('/clients/update/' ~ client.id) : base_url('/clients/create')) }}
<div class="mb-3">
<label for="name" class="form-label fw-bold">Имя / Название *</label>
<input type="text" name="name" id="name" class="form-control {{ errors.name ? 'is-invalid' : '' }}"
value="{{ old.name ?? client.name ?? '' }}" required autofocus>
{% if errors.name %}
<div class="invalid-feedback">{{ errors.name }}</div>
{% endif %}
<div class="form-text">ФИО клиента или название компании</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="email" class="form-label">Email</label>
<input type="email" name="email" id="email" class="form-control {{ errors.email ? 'is-invalid' : '' }}"
value="{{ old.email ?? client.email ?? '' }}">
{% if errors.email %}
<div class="invalid-feedback">{{ errors.email }}</div>
{% endif %}
</div>
<div class="col-md-6 mb-3">
<label for="phone" class="form-label">Телефон</label>
<input type="tel" name="phone" id="phone" class="form-control {{ errors.phone ? 'is-invalid' : '' }}"
value="{{ old.phone ?? client.phone ?? '' }}">
{% if errors.phone %}
<div class="invalid-feedback">{{ errors.phone }}</div>
{% endif %}
</div>
</div>
<div class="mb-4">
<label for="notes" class="form-label">Заметки</label>
<textarea name="notes" id="notes" rows="4" class="form-control {{ errors.notes ? 'is-invalid' : '' }}"
placeholder="Дополнительная информация о клиенте...">{{ old.notes ?? client.notes ?? '' }}</textarea>
{% if errors.notes %}
<div class="invalid-feedback">{{ errors.notes }}</div>
{% endif %}
</div>
<div class="d-flex justify-content-end gap-2">
<a href="{{ base_url('/clients') }}" class="btn btn-secondary">Отмена</a>
<button type="submit" class="btn btn-primary">
<i class="fa-solid fa-check me-2"></i>
{{ client ? 'Сохранить изменения' : 'Добавить клиента' }}
</button>
</div>
{{ forms.form_close() }}
</div>
</div>
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,115 @@
{% extends 'layouts/base.twig' %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="h3 mb-0">Клиенты</h1>
<p class="text-muted mb-0">Управление клиентами вашей организации</p>
</div>
<a href="{{ base_url('/clients/new') }}" class="btn btn-primary">
<i class="fa-solid fa-plus me-2"></i>Добавить клиента
</a>
</div>
<div class="card shadow-sm">
<div class="card-header bg-white py-3">
<div class="d-flex align-items-center justify-content-between">
<div class="text-muted small">
Нажмите на <i class="fa-solid fa-search text-muted"></i> для поиска по столбцу
</div>
</div>
</div>
{# Формируем строки таблицы из клиентов #}
{% set tableRows = [] %}
{% if clients is defined and clients|length > 0 %}
{% for client in clients %}
{% set tableRows = tableRows|merge([{
cells: [
{
content: '<div class="d-flex align-items-center">
<div class="bg-primary text-white rounded-circle d-flex justify-content-center align-items-center me-3" style="width:40px;height:40px;">' ~ client.name|first|upper ~ '</div>
<div><strong>' ~ client.name ~ '</strong>' ~ (client.notes ? '<br><small class="text-muted">' ~ client.notes|slice(0, 50) ~ (client.notes|length > 50 ? '...' : '') ~ '</small>') ~ '</div>
</div>',
class: ''
},
{
content: client.email ? '<a href="mailto:' ~ client.email ~ '">' ~ client.email ~ '</a>' : '<span class="text-muted">—</span>',
class: ''
},
{
content: client.phone ? '<a href="tel:' ~ client.phone ~ '">' ~ client.phone ~ '</a>' : '<span class="text-muted">—</span>',
class: ''
}
],
actions: '<a href="' ~ base_url('/clients/edit/' ~ client.id) ~ '" class="btn btn-sm btn-outline-primary" title="Редактировать"><i class="fa-solid fa-pen"></i></a>
<a href="' ~ base_url('/clients/delete/' ~ client.id) ~ '" class="btn btn-sm btn-outline-danger" title="Удалить" onclick="return confirm(\'Вы уверены что хотите удалить этого клиента?\');"><i class="fa-solid fa-trash"></i></a>'
}]) %}
{% endfor %}
{% endif %}
<div id="clients-table">
{{ include('@components/table/table.twig', {
id: 'clients-table',
url: '/clients/table',
perPage: perPage|default(10),
sort: sort|default(''),
order: order|default('asc'),
filters: filters|default({}),
columns: {
name: { label: 'Имя / Название', width: '40%' },
email: { label: 'Email', width: '25%' },
phone: { label: 'Телефон', width: '20%' }
},
rows: tableRows,
pagerDetails: {
currentPage: pagerDetails.currentPage|default(1),
pageCount: pagerDetails.pageCount|default(1),
total: pagerDetails.total|default(0),
perPage: perPage|default(10),
from: pagerDetails.from|default(1),
to: pagerDetails.to|default(clients|length|default(0))
},
actions: { label: 'Действия', width: '15%' },
emptyMessage: 'Клиентов пока нет',
emptyIcon: 'fa-solid fa-users',
emptyActionUrl: base_url('/clients/new'),
emptyActionLabel: 'Добавить клиента',
emptyActionIcon: 'fa-solid fa-plus'
}) }}
{# CSRF токен для AJAX запросов #}
{{ csrf_field()|raw }}
</div>
</div>
{% endblock %}
{% block stylesheets %}
{{ parent() }}
<link rel="stylesheet" href="/assets/css/modules/data-table.css">
{% endblock %}
{% block scripts %}
{{ parent() }}
<script src="/assets/js/modules/DataTable.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.data-table').forEach(function(container) {
const id = container.id;
const url = container.dataset.url;
const perPage = parseInt(container.dataset.perPage) || 10;
if (window.dataTables && window.dataTables[id]) {
return;
}
const table = new DataTable(id, {
url: url,
perPage: perPage
});
window.dataTables = window.dataTables || {};
window.dataTables[id] = table;
});
});
</script>
{% endblock %}

0
app/ThirdParty/.gitkeep vendored Normal file
View File

32
app/Views/auth/login.twig Normal file
View File

@ -0,0 +1,32 @@
{% extends 'layouts/public.twig' %}
{% block content %}
<div class="card shadow-sm" style="width: 100%; max-width: 400px;">
<div class="card-body p-4">
<div class="text-center mb-4">
<i class="fa-solid fa-circle-nodes fa-3x text-primary mb-2"></i>
<h3>Бизнес.Точка</h3>
<p class="text-muted">Вход в систему</p>
</div>
{{ form_open(base_url('/login'), 'class="needs-validation"') }}
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input type="email" name="email" value="{{ old.email|default('') }}" class="form-control" id="email" required autofocus>
</div>
<div class="mb-3">
<label for="password" class="form-label">Пароль</label>
<input type="password" name="password" value="{{ old.password|default('') }}" class="form-control" id="password" required>
</div>
<button type="submit" class="btn btn-primary w-100">Войти</button>
{{ form_close() }}
<div class="mt-3 text-center">
<small>Нет аккаунта? <a href="{{ base_url('/register') }}">Зарегистрироваться</a></small>
</div>
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,35 @@
{% extends 'layouts/public.twig' %}
{% block content %}
<div class="card shadow-sm" style="width: 100%; max-width: 400px;">
<div class="card-body p-4">
<h3 class="text-center mb-4">Регистрация</h3>
{# ИСПОЛЬЗУЕМ МАКРОС form_open. CSRF добавится АВТОМАТИЧЕСКИ #}
{{ form_open(base_url('/register'), 'class="needs-validation"') }}
<div class="mb-3">
<label for="name" class="form-label">Ваше имя</label>
<input type="text" name="name" class="form-control" id="name" required value="{{ old.name|default('') }}">
</div>
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input type="email" name="email" class="form-control" id="email" required value="{{ old.email|default('') }}">
</div>
<div class="mb-3">
<label for="password" class="form-label">Пароль</label>
<input type="password" name="password" class="form-control" id="password" required minlength="6">
</div>
<button type="submit" class="btn btn-primary w-100">Создать аккаунт</button>
{# ЗАКРЫВАЕМ ФОРМУ МАКРОСОМ #}
{{ form_close() }}
<div class="mt-3 text-center">
<small>Уже есть аккаунт? <a href="{{ base_url('/login') }}">Войти</a></small>
</div>
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,41 @@
{% extends 'layouts/public.twig' %}
{% block content %}
<div class="container d-flex justify-content-center align-items-center" style="min-height: 80vh;">
<div class="card shadow-lg border-0" style="max-width: 500px; width: 100%;">
<div class="card-body p-5 text-center">
<div class="mb-4">
<i class="fa-solid fa-envelope-circle-check display-1 text-primary"></i>
</div>
<h3 class="mb-3">Регистрация успешна!</h3>
<p class="text-muted mb-4">
Мы отправили письмо с ссылкой для подтверждения email на вашу почту.
</p>
<div class="alert alert-info text-start">
<i class="fa-solid fa-info-circle me-2"></i>
<strong>Что делать дальше:</strong>
<ol class="mb-0 mt-2">
<li>Откройте почтовый ящик</li>
<li>Найдите письмо от нас</li>
<li>Нажмите на ссылку для подтверждения</li>
</ol>
</div>
<div class="mb-4">
<a href="/auth/resend-verification" class="text-muted small">
<i class="fa-solid fa-rotate-right me-1"></i>Не получили письмо? Отправить снова
</a>
</div>
<hr class="my-4">
<a href="/" class="btn btn-outline-secondary">
<i class="fa-solid fa-home me-2"></i>На главную
</a>
</div>
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,41 @@
{% extends 'layouts/public.twig' %}
{% block content %}
<div class="container d-flex justify-content-center align-items-center" style="min-height: 80vh;">
<div class="card shadow-lg border-0" style="max-width: 500px; width: 100%;">
<div class="card-body p-5">
<div class="text-center mb-4">
<i class="fa-solid fa-envelope-open-text display-4 text-primary"></i>
<h4 class="mt-3">Повторная отправка письма</h4>
<p class="text-muted">Введите ваш email для получения новой ссылки подтверждения</p>
</div>
{% from 'macros/forms.twig' import form_open, form_close %}
{{ form_open(base_url('/auth/resend-verification')) }}
<div class="mb-3">
<label for="email" class="form-label">Email</label>
<input type="email" name="email" class="form-control {{ errors.email is defined ? 'is-invalid' : '' }}"
id="email" required value="{{ old.email|default('') }}"
placeholder="name@example.com">
{% if errors.email is defined %}
<div class="invalid-feedback">{{ errors.email }}</div>
{% endif %}
</div>
<div class="d-grid gap-2">
<button type="submit" class="btn btn-primary">
<i class="fa-solid fa-paper-plane me-2"></i>Отправить письмо
</button>
<a href="/" class="btn btn-outline-secondary">
На главную
</a>
</div>
{{ form_close() }}
</div>
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,36 @@
{% extends 'layouts/public.twig' %}
{% block content %}
<div class="container d-flex justify-content-center align-items-center" style="min-height: 80vh;">
<div class="card shadow-lg border-0" style="max-width: 500px; width: 100%;">
<div class="card-body p-5 text-center">
<div class="mb-4">
<i class="fa-solid fa-triangle-exclamation display-1 text-warning"></i>
</div>
<h3 class="mb-3">Ошибка подтверждения</h3>
<div class="alert alert-warning text-start">
{{ message|default('Недействительная ссылка для подтверждения.') }}
</div>
<div class="mb-4">
<a href="/auth/resend-verification" class="btn btn-outline-primary">
<i class="fa-solid fa-envelope me-2"></i>Запросить ссылку повторно
</a>
</div>
<hr class="my-4">
<div class="d-flex justify-content-center gap-3">
<a href="/" class="btn btn-outline-secondary">
<i class="fa-solid fa-home me-2"></i>На главную
</a>
<a href="/login" class="btn btn-outline-secondary">
<i class="fa-solid fa-sign-in-alt me-2"></i>Войти
</a>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,33 @@
{% extends 'layouts/public.twig' %}
{% block content %}
<div class="container d-flex justify-content-center align-items-center" style="min-height: 80vh;">
<div class="card shadow-lg border-0" style="max-width: 500px; width: 100%;">
<div class="card-body p-5 text-center">
<div class="mb-4">
<i class="fa-solid fa-circle-check display-1 text-success"></i>
</div>
<h3 class="mb-3">Email подтверждён!</h3>
<p class="text-muted mb-4">
{% if name %}
{{ name }}, спасибо за подтверждение.
{% else %}
Спасибо за подтверждение.
{% endif %}
</p>
<p class="text-muted mb-4">
Теперь вы можете войти в систему и начать работу.
</p>
<div class="d-grid gap-2">
<a href="/login" class="btn btn-primary btn-lg">
<i class="fa-solid fa-sign-in-alt me-2"></i>Войти
</a>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,32 @@
{# app/Views/components/alerts.twig #}
{% set alerts = get_alerts() %}
{% if alerts is not empty %}
<div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 1050">
{% for alert in alerts %}
{# Преобразуем наш тип 'error' в класс Bootstrap 'danger' #}
{% set bs_type = alert.type == 'error' ? 'danger' : alert.type %}
<div class="toast align-items-center text-white bg-{{ bs_type }} border-0" role="alert" aria-live="assertive" aria-atomic="true">
<div class="d-flex">
<div class="toast-body">
{{ alert.message }}
</div>
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
</div>
{% endfor %}
</div>
<script>
// Автоматически показываем все toasts при загрузке страницы
document.addEventListener("DOMContentLoaded", function() {
var toastElList = [].slice.call(document.querySelectorAll('.toast'));
toastElList.forEach(function(toastEl) {
var toast = new bootstrap.Toast(toastEl);
toast.show();
});
});
</script>
{% endif %}

View File

@ -0,0 +1,275 @@
# DataTable Components
Переиспользуемые компоненты для отображения интерактивных таблиц с AJAX-загрузкой, сортировкой и поиском.
## Структура компонентов
```
public/
├── js/
│ └── modules/
│ └── DataTable.js # JS-модуль для инициализации таблиц
└── css/
└── components/
└── data-table.css # Стили для интерактивных таблиц
app/Views/components/table/
├── table.twig # Основной компонент таблицы
├── table_header.twig # Переиспользуемый заголовок
└── pagination.twig # Компонент пагинации
```
## Быстрый старт
### 1. Подключение стилей и скриптов
В вашем шаблоне добавьте:
```twig
{% block stylesheets %}
{{ parent() }}
<link rel="stylesheet" href="/css/components/data-table.css">
{% endblock %}
{% block scripts %}
{{ parent() }}
<script src="/js/modules/DataTable.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
new DataTable('your-table-id', {
url: '/your-module/table',
perPage: 10
});
});
</script>
{% endblock %}
```
### 2. Использование компонента таблицы
```twig
{{ include('@components/table/table.twig', {
id: 'products-table',
url: '/products/table',
perPage: 25,
sort: sort|default(''),
order: order|default('asc'),
filters: filters|default({}),
columns: [
{ name: 'name', label: 'Название', width: '35%' },
{ name: 'sku', label: 'Артикул', width: '15%' },
{ name: 'price', label: 'Цена', width: '15%' },
{ name: 'stock', label: 'Остаток', width: '15%' }
],
actions: { label: 'Действия', width: '20%' },
emptyMessage: 'Товары не найдены'
}) }}
```
## Конфигурация столбцов
Каждый столбец поддерживает следующие параметры:
| Параметр | Тип | Описание |
|----------|-----|----------|
| `name` | string | Идентификатор столбца (используется для сортировки и фильтрации) |
| `label` | string | Отображаемое название столбца |
| `width` | string | Ширина столбца (например, '35%', '200px') |
| `placeholder` | string | Текст-подсказка в поле поиска |
| `searchTitle` | string | Title для иконки поиска |
| `align` | string | CSS-класс выравнивания |
## Конфигурация пагинации
Компонент автоматически получает данные из объекта `pager`:
```php
// В контроллере
$pagination = [
'currentPage' => $pager->getCurrentPage(),
'totalPages' => $pager->getPageCount(),
'totalRecords' => $pager->getTotal(),
'perPage' => $perPage,
'from' => (($pager->getCurrentPage() - 1) * $perPage + 1),
'to' => min($pager->getCurrentPage() * $perPage, $pager->getTotal())
];
```
## Пример контроллера
```php
public function table()
{
$page = (int) ($this->request->getGet('page') ?? 1);
$perPage = (int) ($this->request->getGet('perPage') ?? 10);
$sort = $this->request->getGet('sort') ?? '';
$order = $this->request->getGet('order') ?? 'asc';
// Фильтры
$filters = [
'name' => $this->request->getGet('filters[name]') ?? '',
];
// Построение запроса
$builder = $this->model->builder();
// Применяем фильтры
if (!empty($filters['name'])) {
$builder->like('name', $filters['name']);
}
// Сортировка
if (!empty($sort)) {
$builder->orderBy($sort, $order);
}
// Пагинация
$items = $builder->paginate($perPage, 'default', $page);
$data = [
'items' => $items,
'pager' => $this->model->pager,
'perPage' => $perPage,
'sort' => $sort,
'order' => $order,
'filters' => $filters,
];
return $this->renderTwig('path/to/your/_table', $data);
}
```
## AJAX-ответ
Для AJAX-запросов контроллер должен возвращать только `tbody` и `tfoot`:
```twig
{# _table.twig для модуля #}
{% set isAjax = app.request.headers.get('X-Requested-With') == 'XMLHttpRequest' %}
{% if isAjax %}
{# AJAX: только tbody #}
<tbody>
{% for item in items %}
<tr>
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td class="text-end">
<a href="...">Редактировать</a>
</td>
</tr>
{% endfor %}
</tbody>
{% if items is not empty and pager %}
<tfoot>
<tr>
<td colspan="3">
{{ include('@components/table/pagination.twig', {
pagination: paginationData,
id: 'your-table-id'
}) }}
</td>
</tr>
</tfoot>
{% endif %}
{% else %}
{# Обычный запрос: полная таблица #}
<div class="table-responsive">
{{ include('@components/table/table.twig', {
id: 'your-table-id',
url: '/your-module/table',
perPage: perPage,
columns: columns,
pagination: paginationData,
actions: { label: 'Действия' },
emptyMessage: 'Нет данных'
}) }}
</div>
{% endif %}
```
## API DataTable
### Опции при инициализации
```javascript
new DataTable('container-id', {
url: '/api/endpoint', // URL для AJAX-загрузки
perPage: 10, // Записей на странице по умолчанию
debounceTime: 300, // Задержка поиска в мс
preserveSearchOnSort: true // Сохранять видимость поиска при сортировке
});
```
### Методы
```javascript
const table = new DataTable('my-table', options);
// Установка фильтра
table.setFilter('columnName', 'value');
// Установка количества записей
table.setPerPage(25);
// Переход на страницу
table.goToPage(3);
```
## Доступные CSS-классы
| Класс | Описание |
|-------|----------|
| `.data-table` | Основной контейнер таблицы |
| `.header-content` | Контейнер для элементов заголовка |
| `.header-text` | Текст заголовка столбца |
| `.search-trigger` | Иконка поиска |
| `.sort-icon` | Иконка сортировки |
| `.header-search-input` | Поле ввода поиска |
| `.sort-icon.active` | Активная сортировка |
| `.pagination-wrapper` | Обёртка пагинации |
## Расширение функциональности
### Добавление кастомных действий
Для добавления кнопок действий в строки:
```twig
{% for client in clients %}
<tr>
<td>{{ client.name }}</td>
<td>{{ client.email }}</td>
<td class="actions-cell text-end">
<a href="{{ editUrl }}" class="btn btn-sm btn-outline-primary">
<i class="fa-solid fa-pen"></i>
</a>
</td>
</tr>
{% endfor %}
```
### Кастомные строки
Компонент поддерживает произвольное содержимое ячеек через параметр `rows`:
```twig
{% set rows = [] %}
{% for product in products %}
{% set rows = rows|merge([{
cells: [
{ content: '<strong>' ~ product.name ~ '</strong>', class: '' },
{ content: product.price ~ ' ₽', class: 'text-end' }
],
actions: '<a href="...">Редактировать</a>'
}]) %}
{% endfor %}
{{ include('@components/table/table.twig', {
id: 'products-table',
rows: rows,
columns: columns,
...
}) }}
```

View File

@ -0,0 +1,95 @@
{#
pagination.twig - Универсальный компонент пагинации
Использует встроенный пейджер CodeIgniter 4
Параметры:
- pagination: Объект с данными пагинации (из pager->getDetails())
- currentPage: Текущая страница
- pageCount: Всего страниц
- total: Всего записей
- perPage: Записей на странице
- from: Начальная запись
- to: Конечная запись
- id: ID таблицы для уникальности элементов
#}
{% set currentPage = pagination.currentPage|default(1) %}
{% set totalPages = pagination.pageCount|default(1) %}
{% set totalRecords = pagination.total|default(0) %}
{% set perPage = pagination.perPage|default(10) %}
{% set from = pagination.from|default((currentPage - 1) * perPage + 1) %}
{% set to = pagination.to|default(min(currentPage * perPage, totalRecords)) %}
{# Информация о записях #}
{% set infoText = 'Показано ' ~ from ~ '' ~ to ~ ' из ' ~ totalRecords %}
<div class="pagination-wrapper">
{# Информация о количестве записей #}
<div class="pagination-info">
<span>{{ infoText }}</span>
</div>
{# Кнопки навигации - посередине #}
<nav aria-label="Пагинация" style="float: left;">
<ul class="pagination pagination-sm mb-0">
{# Предыдущая страница #}
<li class="page-item {{ currentPage <= 1 ? 'disabled' }}">
<a class="page-link" href="#" data-nav-page="prev" aria-label="Предыдущая">
<i class="fa-solid fa-chevron-left"></i>
</a>
</li>
{# Номера страниц #}
{% set startPage = max(1, currentPage - 2) %}
{% set endPage = min(totalPages, currentPage + 2) %}
{# Всегда показываем первую страницу если есть #}
{% if startPage > 1 %}
<li class="page-item">
<a class="page-link" href="#" data-page="1">1</a>
</li>
{% if startPage > 2 %}
<li class="page-item disabled">
<span class="page-link">...</span>
</li>
{% endif %}
{% endif %}
{# Страницы вокруг текущей #}
{% for page in startPage..endPage %}
<li class="page-item {{ page == currentPage ? 'active' }}">
<a class="page-link" href="#" data-page="{{ page }}">{{ page }}</a>
</li>
{% endfor %}
{# Всегда показываем последнюю страницу если есть #}
{% if endPage < totalPages %}
{% if endPage < totalPages - 1 %}
<li class="page-item disabled">
<span class="page-link">...</span>
</li>
{% endif %}
<li class="page-item">
<a class="page-link" href="#" data-page="{{ totalPages }}">{{ totalPages }}</a>
</li>
{% endif %}
{# Следующая страница #}
<li class="page-item {{ currentPage >= totalPages ? 'disabled' }}">
<a class="page-link" href="#" data-nav-page="next" aria-label="Следующая">
<i class="fa-solid fa-chevron-right"></i>
</a>
</li>
</ul>
</nav>
{# Выбор количества записей - справа #}
<div class="per-page-selector" style="float: right;">
<label for="per-page-select-{{ id|default('table') }}">Записей на странице:</label>
<select id="per-page-select-{{ id|default('table') }}" class="form-select-sm per-page-select">
<option value="10" {{ perPage == 10 ? 'selected' }}>10</option>
<option value="25" {{ perPage == 25 ? 'selected' }}>25</option>
<option value="50" {{ perPage == 50 ? 'selected' }}>50</option>
<option value="100" {{ perPage == 100 ? 'selected' }}>100</option>
</select>
</div>
</div>

View File

@ -0,0 +1,104 @@
{#
table.twig - Универсальный компонент таблицы с AJAX-загрузкой
Параметры:
- id: ID контейнера таблицы (обязательно)
- url: URL для AJAX-загрузки данных (обязательно)
- perPage: Количество записей на странице (по умолчанию 10)
- columns: Ассоциативный массив ['name' => ['label' => 'Name', 'width' => '40%']]
- sort: Текущий столбец сортировки
- order: Направление сортировки
- filters: Текущие значения фильтров
- items: Массив объектов модели (автоматический рендеринг)
- rows: Предварительно построенные строки (устаревший формат, для совместимости)
- emptyMessage: Сообщение при отсутствии данных
- emptyActionUrl: URL для кнопки действия (опционально)
- emptyActionLabel: Текст кнопки действия (опционально)
- emptyIcon: FontAwesome иконка (опционально)
- tableClass: Дополнительные классы для таблицы
#}
{% set hasRows = (rows is defined and rows|length > 0) or (items is defined and items|length > 0) %}
<div id="{{ id }}" class="data-table" data-url="{{ url }}" data-per-page="{{ perPage|default(10) }}">
<table class="table table-hover mb-0 {{ tableClass|default('') }}">
{# Заголовок таблицы #}
{{ include('@components/table/table_header.twig', {
columns: columns,
sort: sort|default(''),
order: order|default('asc'),
filters: filters|default({}),
actions: actions|default(false)
}) }}
{# Тело таблицы #}
<tbody>
{% if hasRows %}
{% if rows is defined and rows|length > 0 %}
{# Старый формат: предварительно построенные строки #}
{% for row in rows %}
<tr>
{% for cell in row.cells %}
<td class="{{ cell.class|default('') }}">{{ cell.content|raw }}</td>
{% endfor %}
{% if row.actions is defined %}
<td class="actions-cell text-end">
{{ row.actions|raw }}
</td>
{% endif %}
</tr>
{% endfor %}
{% elseif items is defined and items|length > 0 %}
{# Новый формат: автоматический рендеринг из объектов модели #}
{% set columnKeys = columns|keys %}
{% for item in items %}
<tr>
{# Ячейки данных #}
{% for columnKey in columnKeys %}
<td>{{ attribute(item, columnKey)|default('—') }}</td>
{% endfor %}
{# Колонка действий #}
{% if actions is defined and actions %}
<td class="actions-cell text-end">
{% if item.actions is defined %}{{ item.actions|raw }}{% endif %}
</td>
{% endif %}
</tr>
{% endfor %}
{% endif %}
{% else %}
{# Пустое состояние #}
<tr>
<td colspan="{{ columns|length + (actions is defined and actions ? 1 : 0) }}"
class="text-center py-5">
{% if emptyIcon is defined and emptyIcon %}
<div class="mb-3">
<i class="{{ emptyIcon }} text-muted" style="font-size: 3rem;"></i>
</div>
{% endif %}
<p class="text-muted mb-3">{{ emptyMessage|default('Нет данных для отображения') }}</p>
{% if emptyActionUrl is defined and emptyActionUrl %}
<a href="{{ emptyActionUrl }}" class="btn btn-primary">
{% if emptyActionIcon is defined and emptyActionIcon %}
<i class="{{ emptyActionIcon }} me-2"></i>
{% endif %}
{{ emptyActionLabel|default('Добавить') }}
</a>
{% endif %}
</td>
</tr>
{% endif %}
</tbody>
<tfoot>
<tr>
<td colspan="{{ columns|length + 1 }}">
{{ include('@components/table/pagination.twig', {
pagination: pagerDetails,
id: id
}) }}
</td>
</tr>
</tfoot>
</table>
</div>

View File

@ -0,0 +1,51 @@
{#
table_header.twig - Переиспользуемый шаблон заголовка таблицы
Параметры:
- columns: Ассоциативный массив столбцов ['name' => ['label' => 'Name', 'width' => '40%']]
- sort: Текущий столбец сортировки
- order: Направление сортировки (asc/desc)
- filters: Текущие значения фильтров
#}
<thead class="table-light">
<tr>
{% for columnKey, column in columns %}
<th style="width: {{ column.width|default('auto') }};"
class="{{ column.align|default('') }}"
data-sort-column="{{ columnKey }}">
<div class="header-content">
{# Поле поиска - первым, для правильного позиционирования #}
{# Иконка поиска #}
<i class="fa-solid fa-search search-trigger text-muted"
data-search-trigger="{{ columnKey }}"
title="{{ column.searchTitle|default('Поиск по ' ~ column.label|lower) }}"></i>
<input type="text"
class="form-control-sm header-search-input"
data-search-input="{{ columnKey }}"
value="{{ filters[columnKey]|default('') }}"
placeholder="{{ column.placeholder|default('Поиск...') }}"
style="display: none;">
{# Текст заголовка #}
<span class="header-text" data-header-text="{{ columnKey }}">
{{ column.label }}
</span>
{# Иконка сортировки #}
<i class="fa-solid fa-sort sort-icon {{ sort == columnKey ? 'active' : 'text-muted' }}"
data-sort="{{ columnKey }}"
title="{{ sort == columnKey ? (order == 'asc' ? 'Сортировка по возрастанию (нажмите для сортировки по убыванию)' : 'Сортировка по убыванию (нажмите для сортировки по возрастанию)') : 'Сортировка' }}"></i>
</div>
</th>
{% endfor %}
{# Колонка действий (опционально) #}
{% if actions is defined and actions %}
<th class="text-end {{ actions.class|default('') }}" style="width: {{ actions.width|default('auto') }};">
{{ actions.label|default('Действия') }}
</th>
{% endif %}
</tr>
</thead>

View File

@ -0,0 +1,61 @@
{# app/Views/dashboard/index.twig #}
{% extends 'layouts/base.twig' %}
{% block content %}
<div class="container-fluid">
<div class="row mb-4">
<div class="col-12">
<h2>{% if current_org %}Добро пожаловать в {{ current_org.name }}!{% else %}Добро пожаловать!{% endif %}</h2>
<p class="text-muted">Ваш личный кабинет для управления бизнесом.</p>
</div>
</div>
<div class="row">
<!-- Карточки модулей (плейсхолдеры) -->
<div class="col-md-6 col-lg-3 mb-4">
<div class="card h-100 text-center p-3">
<div class="card-body">
<i class="fa-solid fa-users fa-3x text-primary mb-3"></i>
<h5 class="card-title">CRM</h5>
<p class="card-text text-muted">Управление клиентами</p>
<a href="#" class="btn btn-outline-primary btn-sm">Скоро</a>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3 mb-4">
<div class="card h-100 text-center p-3">
<div class="card-body">
<i class="fa-solid fa-calendar-check fa-3x text-success mb-3"></i>
<h5 class="card-title">Booking</h5>
<p class="card-text text-muted">Запись на приём</p>
<a href="#" class="btn btn-outline-success btn-sm">Скоро</a>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3 mb-4">
<div class="card h-100 text-center p-3">
<div class="card-body">
<i class="fa-solid fa-file-signature fa-3x text-warning mb-3"></i>
<h5 class="card-title">Proof</h5>
<p class="card-text text-muted">Согласование файлов</p>
<a href="#" class="btn btn-outline-warning btn-sm">Скоро</a>
</div>
</div>
</div>
<div class="col-md-6 col-lg-3 mb-4">
<div class="card h-100 text-center p-3">
<div class="card-body">
<i class="fa-solid fa-list-check fa-3x text-danger mb-3"></i>
<h5 class="card-title">Tasks</h5>
<p class="card-text text-muted">Задачи и проекты</p>
<a href="#" class="btn btn-outline-danger btn-sm">Скоро</a>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@ -0,0 +1,86 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Подтверждение регистрации</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
color: #333;
margin: 0;
padding: 0;
background-color: #f5f5f5;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.card {
background: white;
border-radius: 8px;
padding: 30px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.logo {
text-align: center;
margin-bottom: 20px;
font-size: 24px;
font-weight: bold;
color: #0d6efd;
}
.btn {
display: inline-block;
padding: 12px 24px;
background-color: #0d6efd;
color: white;
text-decoration: none;
border-radius: 6px;
font-weight: bold;
text-align: center;
}
.btn:hover {
background-color: #0b5ed7;
}
.footer {
text-align: center;
margin-top: 20px;
font-size: 12px;
color: #666;
}
</style>
</head>
<body>
<div class="container">
<div class="card">
<div class="logo">{{ app_name }}</div>
<h2>Добрый день, {{ name }}!</h2>
<p>Спасибо за регистрацию в {{ app_name }}.</p>
<p>Для завершения регистрации и подтверждения вашего email адреса, пожалуйста, нажмите на кнопку ниже:</p>
<p style="text-align: center; margin: 30px 0;">
<a href="{{ verification_url }}" class="btn">Подтвердить email</a>
</p>
<p>Если кнопка не работает, вы можете скопировать ссылку и вставить её в адресную строку браузера:</p>
<p style="word-break: break-all; font-size: 12px; color: #666; background: #f8f9fa; padding: 10px; border-radius: 4px;">
{{ verification_url }}
</p>
<p>Ссылка действительна в течение 24 часов.</p>
<p>Если вы не регистрировались на {{ app_name }}, просто проигнорируйте это письмо.</p>
</div>
<div class="footer">
<p>© {{ "now"|date("Y") }} {{ app_name }}. Все права защищены.</p>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,85 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Добро пожаловать</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
color: #333;
margin: 0;
padding: 0;
background-color: #f5f5f5;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.card {
background: white;
border-radius: 8px;
padding: 30px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.logo {
text-align: center;
margin-bottom: 20px;
font-size: 24px;
font-weight: bold;
color: #198754;
}
.btn {
display: inline-block;
padding: 12px 24px;
background-color: #198754;
color: white;
text-decoration: none;
border-radius: 6px;
font-weight: bold;
text-align: center;
}
.btn:hover {
background-color: #157347;
}
.footer {
text-align: center;
margin-top: 20px;
font-size: 12px;
color: #666;
}
</style>
</head>
<body>
<div class="container">
<div class="card">
<div class="logo">{{ app_name }}</div>
<h2>Добро пожаловать, {{ name }}!</h2>
<p>Поздравляем! Ваш email успешно подтверждён.</p>
<p>Теперь вы можете:</p>
<ul>
<li>Создавать и управлять организациями</li>
<li>Приглашать сотрудников</li>
<li>Использовать все функции платформы</li>
</ul>
<p style="text-align: center; margin: 30px 0;">
<a href="{{ base_url('/') }}" class="btn">Перейти в личный кабинет</a>
</p>
<p>Если у вас возникнут вопросы, наша служба поддержки всегда готова помочь.</p>
<p>С уважением,<br>Команда {{ app_name }}</p>
</div>
<div class="footer">
<p>© {{ "now"|date("Y") }} {{ app_name }}. Все права защищены.</p>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,7 @@
<?php
use CodeIgniter\CLI\CLI;
CLI::error('ERROR: ' . $code);
CLI::write($message);
CLI::newLine();

View File

@ -0,0 +1,65 @@
<?php
use CodeIgniter\CLI\CLI;
// The main Exception
CLI::write('[' . $exception::class . ']', 'light_gray', 'red');
CLI::write($message);
CLI::write('at ' . CLI::color(clean_path($exception->getFile()) . ':' . $exception->getLine(), 'green'));
CLI::newLine();
$last = $exception;
while ($prevException = $last->getPrevious()) {
$last = $prevException;
CLI::write(' Caused by:');
CLI::write(' [' . $prevException::class . ']', 'red');
CLI::write(' ' . $prevException->getMessage());
CLI::write(' at ' . CLI::color(clean_path($prevException->getFile()) . ':' . $prevException->getLine(), 'green'));
CLI::newLine();
}
// The backtrace
if (defined('SHOW_DEBUG_BACKTRACE') && SHOW_DEBUG_BACKTRACE) {
$backtraces = $last->getTrace();
if ($backtraces) {
CLI::write('Backtrace:', 'green');
}
foreach ($backtraces as $i => $error) {
$padFile = ' '; // 4 spaces
$padClass = ' '; // 7 spaces
$c = str_pad($i + 1, 3, ' ', STR_PAD_LEFT);
if (isset($error['file'])) {
$filepath = clean_path($error['file']) . ':' . $error['line'];
CLI::write($c . $padFile . CLI::color($filepath, 'yellow'));
} else {
CLI::write($c . $padFile . CLI::color('[internal function]', 'yellow'));
}
$function = '';
if (isset($error['class'])) {
$type = ($error['type'] === '->') ? '()' . $error['type'] : $error['type'];
$function .= $padClass . $error['class'] . $type . $error['function'];
} elseif (! isset($error['class']) && isset($error['function'])) {
$function .= $padClass . $error['function'];
}
$args = implode(', ', array_map(static fn ($value): string => match (true) {
is_object($value) => 'Object(' . $value::class . ')',
is_array($value) => $value !== [] ? '[...]' : '[]',
$value === null => 'null', // return the lowercased version
default => var_export($value, true),
}, array_values($error['args'] ?? [])));
$function .= '(' . $args . ')';
CLI::write($function);
CLI::newLine();
}
}

View File

@ -0,0 +1,5 @@
<?php
// On the CLI, we still want errors in productions
// so just use the exception template.
include __DIR__ . '/error_exception.php';

View File

@ -0,0 +1,194 @@
:root {
--main-bg-color: #fff;
--main-text-color: #555;
--dark-text-color: #222;
--light-text-color: #c7c7c7;
--brand-primary-color: #DC4814;
--light-bg-color: #ededee;
--dark-bg-color: #404040;
}
body {
height: 100%;
background: var(--main-bg-color);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
color: var(--main-text-color);
font-weight: 300;
margin: 0;
padding: 0;
}
h1 {
font-weight: lighter;
font-size: 3rem;
color: var(--dark-text-color);
margin: 0;
}
h1.headline {
margin-top: 20%;
font-size: 5rem;
}
.text-center {
text-align: center;
}
p.lead {
font-size: 1.6rem;
}
.container {
max-width: 75rem;
margin: 0 auto;
padding: 1rem;
}
.header {
background: var(--light-bg-color);
color: var(--dark-text-color);
margin-top: 2.17rem;
}
.header .container {
padding: 1rem;
}
.header h1 {
font-size: 2.5rem;
font-weight: 500;
}
.header p {
font-size: 1.2rem;
margin: 0;
line-height: 2.5;
}
.header a {
color: var(--brand-primary-color);
margin-left: 2rem;
display: none;
text-decoration: none;
}
.header:hover a {
display: inline;
}
.environment {
background: var(--brand-primary-color);
color: var(--main-bg-color);
text-align: center;
padding: calc(4px + 0.2083vw);
width: 100%;
top: 0;
position: fixed;
}
.source {
background: #343434;
color: var(--light-text-color);
padding: 0.5em 1em;
border-radius: 5px;
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
font-size: 0.85rem;
margin: 0;
overflow-x: scroll;
}
.source span.line {
line-height: 1.4;
}
.source span.line .number {
color: #666;
}
.source .line .highlight {
display: block;
background: var(--dark-text-color);
color: var(--light-text-color);
}
.source span.highlight .number {
color: #fff;
}
.tabs {
list-style: none;
list-style-position: inside;
margin: 0;
padding: 0;
margin-bottom: -1px;
}
.tabs li {
display: inline;
}
.tabs a:link,
.tabs a:visited {
padding: 0 1rem;
line-height: 2.7;
text-decoration: none;
color: var(--dark-text-color);
background: var(--light-bg-color);
border: 1px solid rgba(0,0,0,0.15);
border-bottom: 0;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
display: inline-block;
}
.tabs a:hover {
background: var(--light-bg-color);
border-color: rgba(0,0,0,0.15);
}
.tabs a.active {
background: var(--main-bg-color);
color: var(--main-text-color);
}
.tab-content {
background: var(--main-bg-color);
border: 1px solid rgba(0,0,0,0.15);
}
.content {
padding: 1rem;
}
.hide {
display: none;
}
.alert {
margin-top: 2rem;
display: block;
text-align: center;
line-height: 3.0;
background: #d9edf7;
border: 1px solid #bcdff1;
border-radius: 5px;
color: #31708f;
}
table {
width: 100%;
overflow: hidden;
}
th {
text-align: left;
border-bottom: 1px solid #e7e7e7;
padding-bottom: 0.5rem;
}
td {
padding: 0.2rem 0.5rem 0.2rem 0;
}
tr:hover td {
background: #f1f1f1;
}
td pre {
white-space: pre-wrap;
}
.trace a {
color: inherit;
}
.trace table {
width: auto;
}
.trace tr td:first-child {
min-width: 5em;
font-weight: bold;
}
.trace td {
background: var(--light-bg-color);
padding: 0 1rem;
}
.trace td pre {
margin: 0;
}
.args {
display: none;
}

View File

@ -0,0 +1,116 @@
var tabLinks = new Array();
var contentDivs = new Array();
function init()
{
// Grab the tab links and content divs from the page
var tabListItems = document.getElementById('tabs').childNodes;
console.log(tabListItems);
for (var i = 0; i < tabListItems.length; i ++)
{
if (tabListItems[i].nodeName == "LI")
{
var tabLink = getFirstChildWithTagName(tabListItems[i], 'A');
var id = getHash(tabLink.getAttribute('href'));
tabLinks[id] = tabLink;
contentDivs[id] = document.getElementById(id);
}
}
// Assign onclick events to the tab links, and
// highlight the first tab
var i = 0;
for (var id in tabLinks)
{
tabLinks[id].onclick = showTab;
tabLinks[id].onfocus = function () {
this.blur()
};
if (i == 0)
{
tabLinks[id].className = 'active';
}
i ++;
}
// Hide all content divs except the first
var i = 0;
for (var id in contentDivs)
{
if (i != 0)
{
console.log(contentDivs[id]);
contentDivs[id].className = 'content hide';
}
i ++;
}
}
function showTab()
{
var selectedId = getHash(this.getAttribute('href'));
// Highlight the selected tab, and dim all others.
// Also show the selected content div, and hide all others.
for (var id in contentDivs)
{
if (id == selectedId)
{
tabLinks[id].className = 'active';
contentDivs[id].className = 'content';
}
else
{
tabLinks[id].className = '';
contentDivs[id].className = 'content hide';
}
}
// Stop the browser following the link
return false;
}
function getFirstChildWithTagName(element, tagName)
{
for (var i = 0; i < element.childNodes.length; i ++)
{
if (element.childNodes[i].nodeName == tagName)
{
return element.childNodes[i];
}
}
}
function getHash(url)
{
var hashPos = url.lastIndexOf('#');
return url.substring(hashPos + 1);
}
function toggle(elem)
{
elem = document.getElementById(elem);
if (elem.style && elem.style['display'])
{
// Only works with the "style" attr
var disp = elem.style['display'];
}
else if (elem.currentStyle)
{
// For MSIE, naturally
var disp = elem.currentStyle['display'];
}
else if (window.getComputedStyle)
{
// For most other browsers
var disp = document.defaultView.getComputedStyle(elem, null).getPropertyValue('display');
}
// Toggle the state of the "display" style
elem.style.display = disp == 'block' ? 'none' : 'block';
return false;
}

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