Merge branch 'mod/core_update' into 'main'

Mod/core update

See merge request jjimenez/safekat!230
This commit is contained in:
Ignacio Martinez Navajas
2024-05-07 08:17:21 +00:00
266 changed files with 6544 additions and 10103 deletions

54
.idea/php.xml generated
View File

@ -10,12 +10,64 @@
<option name="highlightLevel" value="WARNING" />
<option name="transferred" value="true" />
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="7.3">
<component name="PhpIncludePathManager">
<include_path>
<path value="$PROJECT_DIR$/ci4/vendor/psr/log" />
<path value="$PROJECT_DIR$/ci4/vendor/psr/container" />
<path value="$PROJECT_DIR$/ci4/vendor/nikic/php-parser" />
<path value="$PROJECT_DIR$/ci4/vendor/phenx/php-svg-lib" />
<path value="$PROJECT_DIR$/ci4/vendor/phenx/php-font-lib" />
<path value="$PROJECT_DIR$/ci4/vendor/dompdf/dompdf" />
<path value="$PROJECT_DIR$/ci4/vendor/laminas/laminas-escaper" />
<path value="$PROJECT_DIR$/ci4/vendor/myclabs/deep-copy" />
<path value="$PROJECT_DIR$/ci4/vendor/phar-io/version" />
<path value="$PROJECT_DIR$/ci4/vendor/phar-io/manifest" />
<path value="$PROJECT_DIR$/ci4/vendor/phpunit/phpunit" />
<path value="$PROJECT_DIR$/ci4/vendor/phpunit/php-timer" />
<path value="$PROJECT_DIR$/ci4/vendor/phpunit/php-invoker" />
<path value="$PROJECT_DIR$/ci4/vendor/phpunit/php-code-coverage" />
<path value="$PROJECT_DIR$/ci4/vendor/phpunit/php-file-iterator" />
<path value="$PROJECT_DIR$/ci4/vendor/phpunit/php-text-template" />
<path value="$PROJECT_DIR$/ci4/vendor/symfony/deprecation-contracts" />
<path value="$PROJECT_DIR$/ci4/vendor/theseer/tokenizer" />
<path value="$PROJECT_DIR$/ci4/vendor/composer" />
<path value="$PROJECT_DIR$/ci4/vendor/doctrine/instantiator" />
<path value="$PROJECT_DIR$/ci4/vendor/fakerphp/faker" />
<path value="$PROJECT_DIR$/ci4/vendor/mikey179/vfsstream" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/diff" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/type" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/version" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/exporter" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/code-unit" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/cli-parser" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/comparator" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/complexity" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/environment" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/global-state" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/lines-of-code" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/object-reflector" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/object-enumerator" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/recursion-context" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/resource-operations" />
<path value="$PROJECT_DIR$/ci4/vendor/sebastian/code-unit-reverse-lookup" />
<path value="$PROJECT_DIR$/ci4/vendor/sabberworm/php-css-parser" />
<path value="$PROJECT_DIR$/ci4/vendor/masterminds/html5" />
<path value="$PROJECT_DIR$/ci4/vendor/codeigniter4/shield" />
<path value="$PROJECT_DIR$/ci4/vendor/codeigniter4/settings" />
<path value="$PROJECT_DIR$/ci4/vendor/codeigniter4/framework" />
</include_path>
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="8.1">
<option name="suggestChangeDefaultLanguageLevel" value="false" />
</component>
<component name="PhpStanOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PhpUnit">
<phpunit_settings>
<PhpUnitSettings custom_loader_path="$PROJECT_DIR$/ci4/vendor/autoload.php" />
</phpunit_settings>
</component>
<component name="PsalmOptionsConfiguration">
<option name="transferred" value="true" />
</component>

8
.idea/safekat.iml generated
View File

@ -1,13 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/ci4/app" isTestSource="false" packagePrefix="App\" />
<sourceFolder url="file://$MODULE_DIR$/ci4/app/Config" isTestSource="false" packagePrefix="Config\" />
<sourceFolder url="file://$MODULE_DIR$/ci4/app/ThirdParty/DatatablesEditor/" isTestSource="false" packagePrefix="DataTables\" />
<sourceFolder url="file://$MODULE_DIR$/ci4/tests" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/ci4/tests/_support" isTestSource="true" packagePrefix="Tests\Support\" />
</content>
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>

View File

@ -11,52 +11,53 @@ class App extends BaseConfig
* Base Site URL
* --------------------------------------------------------------------------
*
* URL to your CodeIgniter root. Typically this will be your base URL,
* URL to your CodeIgniter root. Typically, this will be your base URL,
* WITH a trailing slash:
*
* http://example.com/
*
* If this is not set then CodeIgniter will try guess the protocol, domain
* and path to your installation. However, you should always configure this
* explicitly and never rely on auto-guessing, especially in production
* environments.
*
* @var string
* E.g., http://example.com/
*/
public $baseURL = '';
public string $baseURL = '';
/**
* 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 are using mod_rewrite to remove the page set this
* variable so that it is blank.
*
* @var string
* 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 $indexPage = '';
public string $indexPage = '';
/**
* --------------------------------------------------------------------------
* URI PROTOCOL
* --------------------------------------------------------------------------
*
* This item determines which getServer global should be used to retrieve the
* URI string. The default setting of 'REQUEST_URI' works for most servers.
* 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']
* '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!
*
* @var string
*/
public $uriProtocol = 'REQUEST_URI';
public string $uriProtocol = 'REQUEST_URI';
/**
* --------------------------------------------------------------------------
@ -67,10 +68,8 @@ class App extends BaseConfig
* 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.
*
* @var string
*/
public $defaultLocale = 'es';
public string $defaultLocale = 'es';
/**
* --------------------------------------------------------------------------
@ -81,10 +80,8 @@ class App extends BaseConfig
* language to use based on the value of the Accept-Language header.
*
* If false, no automatic detection will be performed.
*
* @var bool
*/
public $negotiateLocale = true;
public bool $negotiateLocale = false;
/**
* --------------------------------------------------------------------------
@ -95,9 +92,11 @@ class App extends BaseConfig
* by the application in descending order of priority. If no match is
* found, the first locale will be used.
*
* @var string[]
* IncomingRequest::setLocale() also uses this list.
*
* @var list<string>
*/
public $supportedLocales = ['en','es'];
public array $supportedLocales = ['en', 'es'];
/**
* --------------------------------------------------------------------------
@ -107,9 +106,10 @@ class App extends BaseConfig
* The default timezone that will be used in your application to display
* dates with the date helper, and can be retrieved through app_timezone()
*
* @var string
* @see https://www.php.net/manual/en/timezones.php for list of timezones
* supported by PHP.
*/
public $appTimezone = 'Europe/Madrid';
public string $appTimezone = 'Europe/Madrid';
/**
* --------------------------------------------------------------------------
@ -120,210 +120,20 @@ class App extends BaseConfig
* that require a character set to be provided.
*
* @see http://php.net/htmlspecialchars for a list of supported charsets.
*
* @var string
*/
public $charset = 'UTF-8';
public string $charset = 'UTF-8';
/**
* --------------------------------------------------------------------------
* URI PROTOCOL
* 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 header will be set.
*
* @var bool
* and the HTTP Strict Transport Security (HSTS) header will be set.
*/
public $forceGlobalSecureRequests = false;
/**
* --------------------------------------------------------------------------
* 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 string
*/
public $sessionDriver = 'CodeIgniter\Session\Handlers\FileHandler';
/**
* --------------------------------------------------------------------------
* Session Cookie Name
* --------------------------------------------------------------------------
*
* The session cookie name, must contain only [0-9a-z_-] characters
*
* @var string
*/
public $sessionCookieName = '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.
*
* @var int
*/
public $sessionExpiration = 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!
*
* @var string
*/
public $sessionSavePath = 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.
*
* @var bool
*/
public $sessionMatchIP = false;
/**
* --------------------------------------------------------------------------
* Session Time to Update
* --------------------------------------------------------------------------
*
* How many seconds between CI regenerating the session ID.
*
* @var int
*/
public $sessionTimeToUpdate = 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.
*
* @var bool
*/
public $sessionRegenerateDestroy = false;
/**
* --------------------------------------------------------------------------
* Cookie Prefix
* --------------------------------------------------------------------------
*
* Set a cookie name prefix if you need to avoid collisions.
*
* @var string
*
* @deprecated use Config\Cookie::$prefix property instead.
*/
public $cookiePrefix = '';
/**
* --------------------------------------------------------------------------
* Cookie Domain
* --------------------------------------------------------------------------
*
* Set to `.your-domain.com` for site-wide cookies.
*
* @var string
*
* @deprecated use Config\Cookie::$domain property instead.
*/
public $cookieDomain = '';
/**
* --------------------------------------------------------------------------
* Cookie Path
* --------------------------------------------------------------------------
*
* Typically will be a forward slash.
*
* @var string
*
* @deprecated use Config\Cookie::$path property instead.
*/
public $cookiePath = '/';
/**
* --------------------------------------------------------------------------
* Cookie Secure
* --------------------------------------------------------------------------
*
* Cookie will only be set if a secure HTTPS connection exists.
*
* @var bool
*
* @deprecated use Config\Cookie::$secure property instead.
*/
public $cookieSecure = false;
/**
* --------------------------------------------------------------------------
* Cookie HttpOnly
* --------------------------------------------------------------------------
*
* Cookie will only be accessible via HTTP(S) (no JavaScript).
*
* @var bool
*
* @deprecated use Config\Cookie::$httponly property instead.
*/
public $cookieHTTPOnly = 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`, `$cookieSecure` must also be set.
*
* @var string
*
* @deprecated use Config\Cookie::$samesite property instead.
*/
public $cookieSameSite = 'Lax';
public bool $forceGlobalSecureRequests = false;
/**
* --------------------------------------------------------------------------
@ -332,116 +142,21 @@ class App extends BaseConfig
*
* If your server is behind a reverse proxy, you must whitelist the proxy
* IP addresses from which CodeIgniter should trust headers such as
* HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
* X-Forwarded-For or Client-IP in order to properly identify
* the visitor's IP address.
*
* You can use both an array or a comma-separated list of proxy addresses,
* as well as specifying whole subnets. Here are a few examples:
* You need to set a proxy IP address or IP address with subnets and
* the HTTP header for the client IP address.
*
* Comma-separated: '10.0.1.200,192.168.5.0/24'
* Array: ['10.0.1.200', '192.168.5.0/24']
* Here are some examples:
* [
* '10.0.1.200' => 'X-Forwarded-For',
* '192.168.5.0/24' => 'X-Real-IP',
* ]
*
* @var string|string[]
* @var array<string, string>
*/
public $proxyIPs = '';
/**
* --------------------------------------------------------------------------
* CSRF Token Name
* --------------------------------------------------------------------------
*
* The token name.
*
* @deprecated Use `Config\Security` $tokenName property instead of using this property.
*
* @var string
*/
public $CSRFTokenName = 'csrf_test_name';
/**
* --------------------------------------------------------------------------
* CSRF Header Name
* --------------------------------------------------------------------------
*
* The header name.
*
* @deprecated Use `Config\Security` $headerName property instead of using this property.
*
* @var string
*/
public $CSRFHeaderName = 'X-CSRF-TOKEN';
/**
* --------------------------------------------------------------------------
* CSRF Cookie Name
* --------------------------------------------------------------------------
*
* The cookie name.
*
* @deprecated Use `Config\Security` $cookieName property instead of using this property.
*
* @var string
*/
public $CSRFCookieName = 'csrf_cookie_name';
/**
* --------------------------------------------------------------------------
* CSRF Expire
* --------------------------------------------------------------------------
*
* The number in seconds the token should expire.
*
* @deprecated Use `Config\Security` $expire property instead of using this property.
*
* @var int
*/
public $CSRFExpire = 7200;
/**
* --------------------------------------------------------------------------
* CSRF Regenerate
* --------------------------------------------------------------------------
*
* Regenerate token on every submission?
*
* @deprecated Use `Config\Security` $regenerate property instead of using this property.
*
* @var bool
*/
public $CSRFRegenerate = true;
/**
* --------------------------------------------------------------------------
* CSRF Redirect
* --------------------------------------------------------------------------
*
* Redirect to previous page with error on failure?
*
* @deprecated Use `Config\Security` $redirect property instead of using this property.
*
* @var bool
*/
public $CSRFRedirect = true;
/**
* --------------------------------------------------------------------------
* CSRF SameSite
* --------------------------------------------------------------------------
*
* Setting for CSRF SameSite cookie token. Allowed values are:
* - None
* - Lax
* - Strict
* - ''
*
* Defaults to `Lax` as recommended in this link:
*
* @see https://portswigger.net/web-security/csrf/samesite-cookies
* @deprecated Use `Config\Security` $samesite property instead of using this property.
*
* @var string
*/
public $CSRFSameSite = 'Lax';
public array $proxyIPs = [];
/**
* --------------------------------------------------------------------------
@ -458,9 +173,6 @@ class App extends BaseConfig
*
* @see http://www.html5rocks.com/en/tutorials/security/content-security-policy/
* @see http://www.w3.org/TR/CSP/
*
* @var bool
*/
public $CSPEnabled = false;
public bool $CSPEnabled = false;
}

529
ci4/app/Config/Auth.php Normal file
View File

@ -0,0 +1,529 @@
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter Shield.
*
* (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 App\Models\UserModel;
use CodeIgniter\Shield\Authentication\Passwords\ValidationRules;
use CodeIgniter\Shield\Config\Auth as ShieldAuth;
use CodeIgniter\Shield\Authentication\Actions\ActionInterface;
use CodeIgniter\Shield\Authentication\AuthenticatorInterface;
use CodeIgniter\Shield\Authentication\Authenticators\AccessTokens;
use CodeIgniter\Shield\Authentication\Authenticators\HmacSha256;
use CodeIgniter\Shield\Authentication\Authenticators\Session;
use CodeIgniter\Shield\Authentication\Passwords\CompositionValidator;
use CodeIgniter\Shield\Authentication\Passwords\DictionaryValidator;
use CodeIgniter\Shield\Authentication\Passwords\NothingPersonalValidator;
use CodeIgniter\Shield\Authentication\Passwords\PwnedValidator;
use CodeIgniter\Shield\Authentication\Passwords\ValidatorInterface;
class Auth extends ShieldAuth
{
/**
* ////////////////////////////////////////////////////////////////////
* AUTHENTICATION
* ////////////////////////////////////////////////////////////////////
*/
// Constants for Record Login Attempts. Do not change.
public const RECORD_LOGIN_ATTEMPT_NONE = 0; // Do not record at all
public const RECORD_LOGIN_ATTEMPT_FAILURE = 1; // Record only failures
public const RECORD_LOGIN_ATTEMPT_ALL = 2; // Record all login attempts
/**
* --------------------------------------------------------------------
* View files
* --------------------------------------------------------------------
*/
public array $views = [
'login' => '\App\Views\Shield\login',
'register' => '\App\Views\Shield\register',
'layout' => '\App\Views\Shield\layout',
'action_email_2fa' => '\CodeIgniter\Shield\Views\email_2fa_show',
'action_email_2fa_verify' => '\CodeIgniter\Shield\Views\email_2fa_verify',
'action_email_2fa_email' => '\CodeIgniter\Shield\Views\Email\email_2fa_email',
'action_email_activate_show' => '\CodeIgniter\Shield\Views\email_activate_show',
'action_email_activate_email' => '\CodeIgniter\Shield\Views\Email\email_activate_email',
'magic-link-login' => '\App\Views\Shield\magic_link_form',
'magic-link-message' => '\CodeIgniter\Shield\Views\magic_link_message',
'magic-link-email' => '\CodeIgniter\Shield\Views\Email\magic_link_email',
];
/**
* --------------------------------------------------------------------
* Redirect URLs
* --------------------------------------------------------------------
* The default URL that a user will be redirected to after various auth
* actions. This can be either of the following:
*
* 1. An absolute URL. E.g. http://example.com OR https://example.com
* 2. A named route that can be accessed using `route_to()` or `url_to()`
* 3. A URI path within the application. e.g 'admin', 'login', 'expath'
*
* If you need more flexibility you can override the `getUrl()` method
* to apply any logic you may need.
*/
public array $redirects = [
'register' => '/',
'login' => '/',
'logout' => 'login',
'force_reset' => '/',
'permission_denied' => '/',
'group_denied' => '/',
];
/**
* --------------------------------------------------------------------
* Authentication Actions
* --------------------------------------------------------------------
* Specifies the class that represents an action to take after
* the user logs in or registers a new account at the site.
*
* You must register actions in the order of the actions to be performed.
*
* Available actions with Shield:
* - register: \CodeIgniter\Shield\Authentication\Actions\EmailActivator::class
* - login: \CodeIgniter\Shield\Authentication\Actions\Email2FA::class
*
* @var array<string, class-string<ActionInterface>|null>
*/
public array $actions = [
'register' => null,
'login' => null,
];
/**
* --------------------------------------------------------------------
* Authenticators
* --------------------------------------------------------------------
* The available authentication systems, listed
* with alias and class name. These can be referenced
* by alias in the auth helper:
* auth('tokens')->attempt($credentials);
*
* @var array<string, class-string<AuthenticatorInterface>>
*/
public array $authenticators = [
'tokens' => AccessTokens::class,
'session' => Session::class,
'hmac' => HmacSha256::class,
// 'jwt' => JWT::class,
];
/**
* --------------------------------------------------------------------
* Default Authenticator
* --------------------------------------------------------------------
* The Authenticator to use when none is specified.
* Uses the $key from the $authenticators array above.
*/
public string $defaultAuthenticator = 'session';
/**
* --------------------------------------------------------------------
* Authentication Chain
* --------------------------------------------------------------------
* The Authenticators to test logged in status against
* when using the 'chain' filter. Each Authenticator listed will be checked.
* If no match is found, then the next in the chain will be checked.
*
* @var string[]
* @phpstan-var list<string>
*/
public array $authenticationChain = [
'session',
'tokens',
'hmac',
// 'jwt',
];
/**
* --------------------------------------------------------------------
* Allow Registration
* --------------------------------------------------------------------
* Determines whether users can register for the site.
*/
public bool $allowRegistration = true;
/**
* --------------------------------------------------------------------
* Record Last Active Date
* --------------------------------------------------------------------
* If true, will always update the `last_active` datetime for the
* logged-in user on every page request.
* This feature only works when session/tokens filter is active.
*
* @see https://codeigniter4.github.io/shield/quick_start_guide/using_session_auth/#protecting-pages for set filters.
*/
public bool $recordActiveDate = true;
/**
* --------------------------------------------------------------------
* Allow Magic Link Logins
* --------------------------------------------------------------------
* If true, will allow the use of "magic links" sent via the email
* as a way to log a user in without the need for a password.
* By default, this is used in place of a password reset flow, but
* could be modified as the only method of login once an account
* has been set up.
*/
public bool $allowMagicLinkLogins = true;
/**
* --------------------------------------------------------------------
* Magic Link Lifetime
* --------------------------------------------------------------------
* Specifies the amount of time, in seconds, that a magic link is valid.
* You can use Time Constants or any desired number.
*/
public int $magicLinkLifetime = HOUR;
/**
* --------------------------------------------------------------------
* Session Authenticator Configuration
* --------------------------------------------------------------------
* These settings only apply if you are using the Session Authenticator
* for authentication.
*
* - field The name of the key the current user info is stored in session
* - allowRemembering Does the system allow use of "remember-me"
* - rememberCookieName The name of the cookie to use for "remember-me"
* - rememberLength The length of time, in seconds, to remember a user.
*
* @var array<string, bool|int|string>
*/
public array $sessionConfig = [
'field' => 'user',
'allowRemembering' => true,
'rememberCookieName' => 'remember',
'rememberLength' => 30 * DAY,
];
/**
* --------------------------------------------------------------------
* The validation rules for username
* --------------------------------------------------------------------
*
* Do not use string rules like `required|valid_email`.
*
* @var array<string, array<int, string>|string>
*/
public array $usernameValidationRules = [
'label' => 'Auth.username',
'rules' => [
'required',
'max_length[30]',
'min_length[3]',
'regex_match[/\A[a-zA-Z0-9\.]+\z/]',
],
];
/**
* --------------------------------------------------------------------
* The validation rules for email
* --------------------------------------------------------------------
*
* Do not use string rules like `required|valid_email`.
*
* @var array<string, array<int, string>|string>
*/
public array $emailValidationRules = [
'label' => 'Auth.email',
'rules' => [
'required',
'max_length[254]',
'valid_email',
],
];
/**
* --------------------------------------------------------------------
* Minimum Password Length
* --------------------------------------------------------------------
* The minimum length that a password must be to be accepted.
* Recommended minimum value by NIST = 8 characters.
*/
public int $minimumPasswordLength = 8;
/**
* --------------------------------------------------------------------
* Password Check Helpers
* --------------------------------------------------------------------
* The PasswordValidator class runs the password through all of these
* classes, each getting the opportunity to pass/fail the password.
* You can add custom classes as long as they adhere to the
* CodeIgniter\Shield\Authentication\Passwords\ValidatorInterface.
*
* @var class-string<ValidatorInterface>[]
*/
public array $passwordValidators = [
CompositionValidator::class,
NothingPersonalValidator::class,
DictionaryValidator::class
// PwnedValidator::class,
];
/**
* --------------------------------------------------------------------
* Valid login fields
* --------------------------------------------------------------------
* Fields that are available to be used as credentials for login.
*/
public array $validFields = [
'email',
// 'username',
];
/**
* --------------------------------------------------------------------
* Additional Fields for "Nothing Personal"
* --------------------------------------------------------------------
* The NothingPersonalValidator prevents personal information from
* being used in passwords. The email and username fields are always
* considered by the validator. Do not enter those field names here.
*
* An extended User Entity might include other personal info such as
* first and/or last names. $personalFields is where you can add
* fields to be considered as "personal" by the NothingPersonalValidator.
* For example:
* $personalFields = ['firstname', 'lastname'];
*/
public array $personalFields = [];
/**
* --------------------------------------------------------------------
* Password / Username Similarity
* --------------------------------------------------------------------
* Among other things, the NothingPersonalValidator checks the
* amount of sameness between the password and username.
* Passwords that are too much like the username are invalid.
*
* The value set for $maxSimilarity represents the maximum percentage
* of similarity at which the password will be accepted. In other words, any
* calculated similarity equal to, or greater than $maxSimilarity
* is rejected.
*
* The accepted range is 0-100, with 0 (zero) meaning don't check similarity.
* Using values at either extreme of the *working range* (1-100) is
* not advised. The low end is too restrictive and the high end is too permissive.
* The suggested value for $maxSimilarity is 50.
*
* You may be thinking that a value of 100 should have the effect of accepting
* everything like a value of 0 does. That's logical and probably true,
* but is unproven and untested. Besides, 0 skips the work involved
* making the calculation unlike when using 100.
*
* The (admittedly limited) testing that's been done suggests a useful working range
* of 50 to 60. You can set it lower than 50, but site users will probably start
* to complain about the large number of proposed passwords getting rejected.
* At around 60 or more it starts to see pairs like 'captain joe' and 'joe*captain' as
* perfectly acceptable which clearly they are not.
*
* To disable similarity checking set the value to 0.
* public $maxSimilarity = 0;
*/
public int $maxSimilarity = 50;
/**
* --------------------------------------------------------------------
* Hashing Algorithm to use
* --------------------------------------------------------------------
* Valid values are
* - PASSWORD_DEFAULT (default)
* - PASSWORD_BCRYPT
* - PASSWORD_ARGON2I - As of PHP 7.2 only if compiled with support for it
* - PASSWORD_ARGON2ID - As of PHP 7.3 only if compiled with support for it
*/
public string $hashAlgorithm = PASSWORD_DEFAULT;
/**
* --------------------------------------------------------------------
* ARGON2I/ARGON2ID Algorithm options
* --------------------------------------------------------------------
* The ARGON2I method of hashing allows you to define the "memory_cost",
* the "time_cost" and the number of "threads", whenever a password hash is
* created.
*/
public int $hashMemoryCost = 65536; // PASSWORD_ARGON2_DEFAULT_MEMORY_COST;
public int $hashTimeCost = 4; // PASSWORD_ARGON2_DEFAULT_TIME_COST;
public int $hashThreads = 1; // PASSWORD_ARGON2_DEFAULT_THREADS;
/**
* --------------------------------------------------------------------
* BCRYPT Algorithm options
* --------------------------------------------------------------------
* The BCRYPT method of hashing allows you to define the "cost"
* or number of iterations made, whenever a password hash is created.
* This defaults to a value of 12 which is an acceptable number.
* However, depending on the security needs of your application
* and the power of your hardware, you might want to increase the
* cost. This makes the hashing process takes longer.
*
* Valid range is between 4 - 31.
*/
public int $hashCost = 12;
/**
* ////////////////////////////////////////////////////////////////////
* OTHER SETTINGS
* ////////////////////////////////////////////////////////////////////
*/
/**
* --------------------------------------------------------------------
* Customize the DB group used for each model
* --------------------------------------------------------------------
*/
public ?string $DBGroup = null;
/**
* --------------------------------------------------------------------
* Customize Name of Shield Tables
* --------------------------------------------------------------------
* Only change if you want to rename the default Shield table names
*
* It may be necessary to change the names of the tables for
* security reasons, to prevent the conflict of table names,
* the internal policy of the companies or any other reason.
*
* - users Auth Users Table, the users info is stored.
* - auth_identities Auth Identities Table, Used for storage of passwords, access tokens, social login identities, etc.
* - auth_logins Auth Login Attempts, Table records login attempts.
* - auth_token_logins Auth Token Login Attempts Table, Records Bearer Token type login attempts.
* - auth_remember_tokens Auth Remember Tokens (remember-me) Table.
* - auth_groups_users Groups Users Table.
* - auth_permissions_users Users Permissions Table.
*
* @var array<string, string>
*/
public array $tables = [
'users' => 'users',
'identities' => 'auth_identities',
'logins' => 'auth_logins',
'token_logins' => 'auth_token_logins',
'remember_tokens' => 'auth_remember_tokens',
'groups_users' => 'auth_groups_users',
'permissions_users' => 'auth_permissions_users',
];
/**
* --------------------------------------------------------------------
* User Provider
* --------------------------------------------------------------------
* The name of the class that handles user persistence.
* By default, this is the included UserModel, which
* works with any of the database engines supported by CodeIgniter.
* You can change it as long as they adhere to the
* CodeIgniter\Shield\Models\UserModel.
*
* @var class-string<UserModel>
*/
public string $userProvider = UserModel::class;
/**
* Returns the URL that a user should be redirected
* to after a successful login.
*/
public function loginRedirect(): string
{
$session = session();
$url = $session->getTempdata('beforeLoginUrl') ?? setting('Auth.redirects')['login'];
return $this->getUrl($url);
}
/**
* Returns the URL that a user should be redirected
* to after they are logged out.
*/
public function logoutRedirect(): string
{
$url = setting('Auth.redirects')['logout'];
return $this->getUrl($url);
}
/**
* Returns the URL the user should be redirected to
* after a successful registration.
*/
public function registerRedirect(): string
{
$url = setting('Auth.redirects')['register'];
return $this->getUrl($url);
}
/**
* Returns the URL the user should be redirected to
* if force_reset identity is set to true.
*/
public function forcePasswordResetRedirect(): string
{
$url = setting('Auth.redirects')['force_reset'];
return $this->getUrl($url);
}
/**
* Returns the URL the user should be redirected to
* if permission denied.
*/
public function permissionDeniedRedirect(): string
{
$url = setting('Auth.redirects')['permission_denied'];
return $this->getUrl($url);
}
/**
* Returns the URL the user should be redirected to
* if group denied.
*/
public function groupDeniedRedirect(): string
{
$url = setting('Auth.redirects')['group_denied'];
return $this->getUrl($url);
}
/**
* Accepts a string which can be an absolute URL or
* a named route or just a URI path, and returns the
* full path.
*
* @param string $url an absolute URL or a named route or just URI path
*/
protected function getUrl(string $url): string
{
// To accommodate all url patterns
$final_url = '';
switch (true) {
case strpos($url, 'http://') === 0 || strpos($url, 'https://') === 0: // URL begins with 'http' or 'https'. E.g. http://example.com
$final_url = $url;
break;
case route_to($url) !== false: // URL is a named-route
$final_url = rtrim(url_to($url), '/ ');
break;
default: // URL is a route (URI path)
$final_url = rtrim(site_url($url), '/ ');
break;
}
return $final_url;
}
}

View File

@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter Shield.
*
* (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;
require "RBAC/roles.php";
require "RBAC/permissions.php";
require "RBAC/permissionMatrix.php";
use CodeIgniter\Shield\Config\AuthGroups as ShieldAuthGroups;
class AuthGroups extends ShieldAuthGroups
{
/**
* --------------------------------------------------------------------
* Default Group
* --------------------------------------------------------------------
* The group that a newly registered user is added to.
*/
public string $defaultGroup = 'cliente';
/**
* --------------------------------------------------------------------
* Groups
* --------------------------------------------------------------------
* An associative array of the available groups in the system, where the keys
* are the group names and the values are arrays of the group info.
*
* Whatever value you assign as the key will be used to refer to the group
* when using functions such as:
* $user->addGroup('superadmin');
*
* @var array<string, array<string, string>>
*
* @see https://codeigniter4.github.io/shield/quick_start_guide/using_authorization/#change-available-groups for more info
*/
public array $groups = SK_ROLES;
/**
* --------------------------------------------------------------------
* Permissions
* --------------------------------------------------------------------
* The available permissions in the system.
*
* If a permission is not listed here it cannot be used.
*/
public array $permissions = SK_PERMISSIONS;
/**
* --------------------------------------------------------------------
* Permissions Matrix
* --------------------------------------------------------------------
* Maps permissions to groups.
*
* This defines group-level permissions.
*/
public array $matrix = SK_PERMISSION_MATRIX;
}

View File

@ -0,0 +1,138 @@
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter Shield.
*
* (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\Shield\Config\AuthToken as ShieldAuthToken;
/**
* Configuration for Token Auth and HMAC Auth
*/
class AuthToken extends ShieldAuthToken
{
/**
* --------------------------------------------------------------------
* Record Login Attempts for Token Auth and HMAC Auth
* --------------------------------------------------------------------
* Specify which login attempts are recorded in the database.
*
* Valid values are:
* - Auth::RECORD_LOGIN_ATTEMPT_NONE
* - Auth::RECORD_LOGIN_ATTEMPT_FAILURE
* - Auth::RECORD_LOGIN_ATTEMPT_ALL
*/
public int $recordLoginAttempt = Auth::RECORD_LOGIN_ATTEMPT_FAILURE;
/**
* --------------------------------------------------------------------
* Name of Authenticator Header
* --------------------------------------------------------------------
* The name of Header that the Authorization token should be found.
* According to the specs, this should be `Authorization`, but rare
* circumstances might need a different header.
*/
public array $authenticatorHeader = [
'tokens' => 'Authorization',
'hmac' => 'Authorization',
];
/**
* --------------------------------------------------------------------
* Unused Token Lifetime for Token Auth and HMAC Auth
* --------------------------------------------------------------------
* Determines the amount of time, in seconds, that an unused token can
* be used.
*/
public int $unusedTokenLifetime = YEAR;
/**
* --------------------------------------------------------------------
* Secret2 storage character limit
* --------------------------------------------------------------------
* Database size limit for the identities 'secret2' field.
*/
public int $secret2StorageLimit = 255;
/**
* --------------------------------------------------------------------
* HMAC secret key byte size
* --------------------------------------------------------------------
* Specify in integer the desired byte size of the
* HMAC SHA256 byte size
*/
public int $hmacSecretKeyByteSize = 32;
/**
* --------------------------------------------------------------------
* HMAC encryption Keys
* --------------------------------------------------------------------
* This sets the key to be used when encrypting a user's HMAC Secret Key.
*
* 'keys' is an array of keys which will facilitate key rotation. Valid
* keyTitles must include only [a-zA-Z0-9_] and should be kept to a
* max of 8 characters.
*
* Each keyTitle is an associative array containing the required 'key'
* value, and the optional 'driver' and 'digest' values. If the
* 'driver' and 'digest' values are not specified, the default 'driver'
* and 'digest' values will be used.
*
* Old keys will are used to decrypt existing Secret Keys. It is encouraged
* to run 'php spark shield:hmac reencrypt' to update existing Secret
* Key encryptions.
*
* @see https://codeigniter.com/user_guide/libraries/encryption.html
*
* @var array<string, array{key: string, driver?: string, digest?: string}>|string
*
* NOTE: The value becomes temporarily a string when setting value as JSON
* from environment variable.
*
* [key_name => ['key' => key_value]]
* or [key_name => ['key' => key_value, 'driver' => driver, 'digest' => digest]]
*/
public $hmacEncryptionKeys = [
'k1' => [
'key' => '',
],
];
/**
* --------------------------------------------------------------------
* HMAC Current Encryption Key Selector
* --------------------------------------------------------------------
* This specifies which of the encryption keys should be used.
*/
public string $hmacEncryptionCurrentKey = 'k1';
/**
* --------------------------------------------------------------------
* HMAC Encryption Key Driver
* --------------------------------------------------------------------
* This specifies which of the encryption drivers should be used.
*
* Available drivers:
* - OpenSSL
* - Sodium
*/
public string $hmacEncryptionDefaultDriver = 'OpenSSL';
/**
* --------------------------------------------------------------------
* HMAC Encryption Key Driver
* --------------------------------------------------------------------
* THis specifies the type of encryption to be used.
* e.g. 'SHA512' or 'SHA256'.
*/
public string $hmacEncryptionDefaultDigest = 'SHA512';
}

View File

@ -13,7 +13,12 @@ use CodeIgniter\Config\AutoloadConfig;
* 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.
* 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.
*
* @immutable
*/
class Autoload extends AutoloadConfig
{
@ -31,14 +36,12 @@ class Autoload extends AutoloadConfig
* else you will need to modify all of those classes for this to work.
*
* Prototype:
*```
* $psr4 = [
* 'CodeIgniter' => SYSTEMPATH,
* 'App' => APPPATH
* 'App' => APPPATH
* ];
*```
*
* @var array<string, string>
* @var array<string, list<string>|string>
*/
public $psr4 = [
APP_NAMESPACE => APPPATH, // For custom app namespace
@ -57,11 +60,9 @@ class Autoload extends AutoloadConfig
* were being autoloaded through a namespace.
*
* Prototype:
*```
* $classmap = [
* 'MyClass' => '/path/to/class/file.php'
* ];
*```
*
* @var array<string, string>
*/
@ -76,13 +77,24 @@ class Autoload extends AutoloadConfig
* or for loading functions.
*
* Prototype:
* ```
* $files = [
* '/path/to/my/file.php',
* ];
* ```
* $files = [
* '/path/to/my/file.php',
* ];
*
* @var array<int, string>
* @var list<string>
*/
public $files = [];
/**
* -------------------------------------------------------------------
* Helpers
* -------------------------------------------------------------------
* Prototype:
* $helpers = [
* 'form',
* ];
*
* @var list<string>
*/
public $helpers = ['auth', 'setting'];
}

View File

@ -7,8 +7,10 @@
| 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(-1);
error_reporting(E_ALL);
ini_set('display_errors', '1');
/*

View File

@ -6,6 +6,8 @@
|--------------------------------------------------------------------------
| 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.
*/
ini_set('display_errors', '0');
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);

View File

@ -1,5 +1,11 @@
<?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
@ -8,7 +14,7 @@
| make sure they don't make it to production. And save us hours of
| painful debugging.
*/
error_reporting(-1);
error_reporting(E_ALL);
ini_set('display_errors', '1');
/*

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

View File

@ -2,6 +2,7 @@
namespace Config;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Cache\Handlers\DummyHandler;
use CodeIgniter\Cache\Handlers\FileHandler;
use CodeIgniter\Cache\Handlers\MemcachedHandler;
@ -19,10 +20,8 @@ class Cache extends BaseConfig
*
* 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.
*
* @var string
*/
public $handler = 'file';
public string $handler = 'file';
/**
* --------------------------------------------------------------------------
@ -32,10 +31,8 @@ class Cache extends BaseConfig
* 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.
*
* @var string
*/
public $backupHandler = 'dummy';
public string $backupHandler = 'dummy';
/**
* --------------------------------------------------------------------------
@ -45,11 +42,9 @@ class Cache extends BaseConfig
* The path to where cache files should be stored, if using a file-based
* system.
*
* @var string
*
* @deprecated Use the driver-specific variant under $file
*/
public $storePath = WRITEPATH . 'cache/';
public string $storePath = WRITEPATH . 'cache/';
/**
* --------------------------------------------------------------------------
@ -59,12 +54,12 @@ class Cache extends BaseConfig
* 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.
* array('q') = Enabled, but only take into account the specified list
* of query parameters.
* 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|string[]
*/
@ -77,10 +72,8 @@ class Cache extends BaseConfig
*
* This string is added to all cache item names to help avoid collisions
* if you run multiple applications with the same cache engine.
*
* @var string
*/
public $prefix = '';
public string $prefix = '';
/**
* --------------------------------------------------------------------------
@ -92,10 +85,21 @@ class Cache extends BaseConfig
* 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.
*
* @var int
*/
public $ttl = 60;
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 = '{}()/\@:';
/**
* --------------------------------------------------------------------------
@ -106,7 +110,7 @@ class Cache extends BaseConfig
*
* @var array<string, int|string|null>
*/
public $file = [
public array $file = [
'storePath' => WRITEPATH . 'cache/',
'mode' => 0640,
];
@ -120,9 +124,9 @@ class Cache extends BaseConfig
*
* @see https://codeigniter.com/user_guide/libraries/caching.html#memcached
*
* @var array<string, boolean|int|string>
* @var array<string, bool|int|string>
*/
public $memcached = [
public array $memcached = [
'host' => '127.0.0.1',
'port' => 11211,
'weight' => 1,
@ -138,7 +142,7 @@ class Cache extends BaseConfig
*
* @var array<string, int|string|null>
*/
public $redis = [
public array $redis = [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
@ -154,9 +158,9 @@ class Cache extends BaseConfig
* 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, string>
* @var array<string, class-string<CacheInterface>>
*/
public $validHandlers = [
public array $validHandlers = [
'dummy' => DummyHandler::class,
'file' => FileHandler::class,
'memcached' => MemcachedHandler::class,

View File

@ -38,9 +38,9 @@ defined('MINUTE') || define('MINUTE', 60);
defined('HOUR') || define('HOUR', 3600);
defined('DAY') || define('DAY', 86400);
defined('WEEK') || define('WEEK', 604800);
defined('MONTH') || define('MONTH', 2592000);
defined('YEAR') || define('YEAR', 31536000);
defined('DECADE') || define('DECADE', 315360000);
defined('MONTH') || define('MONTH', 2_592_000);
defined('YEAR') || define('YEAR', 31_536_000);
defined('DECADE') || define('DECADE', 315_360_000);
/*
| --------------------------------------------------------------------------
@ -67,13 +67,28 @@ defined('DECADE') || define('DECADE', 315360000);
| 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_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
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
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_LOW instead.
*/
define('EVENT_PRIORITY_LOW', 200);
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_NORMAL instead.
*/
define('EVENT_PRIORITY_NORMAL', 100);
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_HIGH instead.
*/
define('EVENT_PRIORITY_HIGH', 10);

View File

@ -15,38 +15,32 @@ use CodeIgniter\Config\BaseConfig;
*/
class ContentSecurityPolicy extends BaseConfig
{
//-------------------------------------------------------------------------
// -------------------------------------------------------------------------
// Broadbrush CSP management
//-------------------------------------------------------------------------
// -------------------------------------------------------------------------
/**
* Default CSP report context
*
* @var bool
*/
public $reportOnly = false;
public bool $reportOnly = false;
/**
* Specifies a URL where a browser will send reports
* when a content security policy is violated.
*
* @var string|null
*/
public $reportURI;
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.
*
* @var bool
*/
public $upgradeInsecureRequests = false;
public bool $upgradeInsecureRequests = false;
//-------------------------------------------------------------------------
// -------------------------------------------------------------------------
// Sources allowed
// Note: once you set a policy to 'none', it cannot be further restricted
//-------------------------------------------------------------------------
// NOTE: once you set a policy to 'none', it cannot be further restricted
// -------------------------------------------------------------------------
/**
* Will default to self if not overridden
@ -164,4 +158,19 @@ class ContentSecurityPolicy extends BaseConfig
* @var 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;
}

View File

@ -13,10 +13,8 @@ class Cookie extends BaseConfig
* --------------------------------------------------------------------------
*
* Set a cookie name prefix if you need to avoid collisions.
*
* @var string
*/
public $prefix = '';
public string $prefix = '';
/**
* --------------------------------------------------------------------------
@ -37,10 +35,8 @@ class Cookie extends BaseConfig
* --------------------------------------------------------------------------
*
* Typically will be a forward slash.
*
* @var string
*/
public $path = '/';
public string $path = '/';
/**
* --------------------------------------------------------------------------
@ -48,10 +44,8 @@ class Cookie extends BaseConfig
* --------------------------------------------------------------------------
*
* Set to `.your-domain.com` for site-wide cookies.
*
* @var string
*/
public $domain = '';
public string $domain = '';
/**
* --------------------------------------------------------------------------
@ -59,10 +53,8 @@ class Cookie extends BaseConfig
* --------------------------------------------------------------------------
*
* Cookie will only be set if a secure HTTPS connection exists.
*
* @var bool
*/
public $secure = false;
public bool $secure = false;
/**
* --------------------------------------------------------------------------
@ -70,10 +62,8 @@ class Cookie extends BaseConfig
* --------------------------------------------------------------------------
*
* Cookie will only be accessible via HTTP(S) (no JavaScript).
*
* @var bool
*/
public $httponly = true;
public bool $httponly = true;
/**
* --------------------------------------------------------------------------
@ -95,9 +85,9 @@ class Cookie extends BaseConfig
* (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 string
* @phpstan-var 'None'|'Lax'|'Strict'|''
*/
public $samesite = 'Lax';
public string $samesite = 'Lax';
/**
* --------------------------------------------------------------------------
@ -110,10 +100,8 @@ class Cookie extends BaseConfig
* If this is set to `true`, cookie names should be compliant of RFC 2616's
* list of allowed characters.
*
* @var bool
*
* @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 $raw = false;
public bool $raw = false;
}

View File

@ -12,68 +12,63 @@ class Database extends Config
/**
* The directory that holds the Migrations
* and Seeds directories.
*
* @var string
*/
public $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
public string $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
/**
* Lets you choose which connection group to
* use if no other is specified.
*
* @var string
*/
public $defaultGroup = 'default';
public string $defaultGroup = 'default';
/**
* The default database connection.
*
* @var array
*/
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
];
/**
* This database connection is used when
* running PHPUnit database tests.
*
* @var array
*/
public $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' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
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' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'foreignKeys' => true,
'busyTimeout' => 1000,
];
public function __construct()

View File

@ -2,6 +2,9 @@
namespace Config;
/**
* @immutable
*/
class DocTypes
{
/**
@ -9,7 +12,7 @@ class DocTypes
*
* @var array<string, string>
*/
public $list = [
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">',
@ -30,4 +33,14 @@ class DocTypes
'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;
}

View File

@ -6,165 +6,116 @@ use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
/**
* @var string
*/
public $fromEmail;
/**
* @var string
*/
public $fromName;
/**
* @var string
*/
public $recipients;
public string $fromEmail = 'safekat@imnavajas.es';
public string $fromName = 'Safekat ERP';
public string $recipients = '';
/**
* The "user agent"
*
* @var string
*/
public $userAgent = 'Safekat ERP';
public string $userAgent = 'Safekat SL';
/**
* The mail sending protocol: mail, sendmail, smtp
*
* @var string
*/
public $protocol = 'smtp';
public string $protocol = 'smtp';
/**
* The server path to Sendmail.
*
* @var string
*/
public $mailPath = '/usr/sbin/sendmail';
public string $mailPath = '/usr/sbin/sendmail';
/**
* SMTP Server Address
*
* @var string
* SMTP Server Hostname
*/
public $SMTPHost = "imnavajas.es";
public string $SMTPHost = 'imnavajas.es';
/**
* SMTP Username
*
* @var string
*/
public $SMTPUser = "safekat@imnavajas.es";
public string $SMTPUser = 'safekat@imnavajas.es';
/**
* SMTP Password
*
* @var string
*/
public $SMTPPass = "Etkd9~448";
public string $SMTPPass = 'Etkd9~448';
/**
* SMTP Port
*
* @var int
*/
public $SMTPPort = 25;
public int $SMTPPort = 25;
/**
* SMTP Timeout (in seconds)
*
* @var int
*/
public $SMTPTimeout = 5;
public int $SMTPTimeout = 5;
/**
* Enable persistent SMTP connections
*
* @var bool
*/
public $SMTPKeepAlive = false;
public bool $SMTPKeepAlive = false;
/**
* SMTP Encryption. Either tls or ssl
* SMTP Encryption.
*
* @var string
* @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 $SMTPCrypto = 'tls';
public string $SMTPCrypto = 'tls';
/**
* Enable word-wrap
*
* @var bool
*/
public $wordWrap = true;
public bool $wordWrap = true;
/**
* Character count to wrap at
*
* @var int
*/
public $wrapChars = 76;
public int $wrapChars = 76;
/**
* Type of mail, either 'text' or 'html'
*
* @var string
*/
public $mailType = 'html';
public string $mailType = 'html';
/**
* Character set (utf-8, iso-8859-1, etc.)
*
* @var string
*/
public $charset = 'UTF-8';
public string $charset = 'UTF-8';
/**
* Whether to validate the email address
*
* @var bool
*/
public $validate = false;
public bool $validate = false;
/**
* Email Priority. 1 = highest. 5 = lowest. 3 = normal
*
* @var int
*/
public $priority = 3;
public int $priority = 3;
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*
* @var string
*/
public $CRLF = "\r\n";
public string $CRLF = "\r\n";
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*
* @var string
*/
public $newline = "\r\n";
public string $newline = "\r\n";
/**
* Enable BCC Batch Mode.
*
* @var bool
*/
public $BCCBatchMode = false;
public bool $BCCBatchMode = false;
/**
* Number of emails in each BCC batch
*
* @var int
*/
public $BCCBatchSize = 200;
public int $BCCBatchSize = 200;
/**
* Enable notify message from server
*
* @var bool
*/
public $DSN = false;
public bool $DSN = false;
}

View File

@ -20,10 +20,8 @@ class Encryption extends BaseConfig
* 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.
*
* @var string
*/
public $key = '';
public string $key = '';
/**
* --------------------------------------------------------------------------
@ -35,10 +33,8 @@ class Encryption extends BaseConfig
* Available drivers:
* - OpenSSL
* - Sodium
*
* @var string
*/
public $driver = 'OpenSSL';
public string $driver = 'OpenSSL';
/**
* --------------------------------------------------------------------------
@ -49,10 +45,8 @@ class Encryption extends BaseConfig
* before it is encrypted. This value should be greater than zero.
*
* See the user guide for more information on padding.
*
* @var int
*/
public $blockSize = 16;
public int $blockSize = 16;
/**
* --------------------------------------------------------------------------
@ -60,8 +54,39 @@ class Encryption extends BaseConfig
* --------------------------------------------------------------------------
*
* HMAC digest to use, e.g. 'SHA512' or 'SHA256'. Default value is 'SHA512'.
*
* @var string
*/
public $digest = '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';
}

View File

@ -4,6 +4,7 @@ namespace Config;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\HotReloader\HotReloader;
/*
* --------------------------------------------------------------------
@ -32,9 +33,7 @@ Events::on('pre_system', static function () {
ob_end_flush();
}
ob_start(static function ($buffer) {
return $buffer;
});
ob_start(static fn ($buffer) => $buffer);
}
/*
@ -46,5 +45,22 @@ Events::on('pre_system', static function () {
if (CI_DEBUG && ! is_cli()) {
Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
Services::toolbar()->respond();
// Hot Reload route - for framework use on the hot reloader.
if (ENVIRONMENT === 'development') {
Services::routes()->get('__hot-reload', static function () {
(new HotReloader())->run();
});
}
}
});
Events::on('login', static function ($user) {
helper('logger');
getSystemSettings();
setLog('information','user-login', $user->id);
});
Events::on('logout', static function ($user) {
helper('logger');
setLog('information','user-logout', $user->id);
});

View File

@ -3,6 +3,10 @@
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.
@ -17,10 +21,8 @@ class Exceptions extends BaseConfig
* through Services::Log.
*
* Default: true
*
* @var bool
*/
public $log = true;
public bool $log = true;
/**
* --------------------------------------------------------------------------
@ -28,10 +30,8 @@ class Exceptions extends BaseConfig
* --------------------------------------------------------------------------
* Any status codes here will NOT be logged if logging is turned on.
* By default, only 404 (Page Not Found) exceptions are ignored.
*
* @var array
*/
public $ignoreCodes = [404];
public array $ignoreCodes = [404];
/**
* --------------------------------------------------------------------------
@ -41,10 +41,8 @@ class Exceptions extends BaseConfig
* directories that hold the views used to generate errors.
*
* Default: APPPATH.'Views/errors'
*
* @var string
*/
public $errorViewPath = APPPATH . 'Views/errors';
public string $errorViewPath = APPPATH . 'Views/errors';
/**
* --------------------------------------------------------------------------
@ -53,8 +51,54 @@ class Exceptions extends BaseConfig
* 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 array
*/
public $sensitiveDataInTrace = [];
public array $sensitiveDataInTrace = [];
/**
* --------------------------------------------------------------------------
* LOG DEPRECATIONS INSTEAD OF THROWING?
* --------------------------------------------------------------------------
* By default, CodeIgniter converts deprecations into exceptions. Also,
* starting in PHP 8.1 will cause a lot of deprecated usage warnings.
* Use this option to temporarily cease the warnings and instead log those.
* 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);
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Enable/disable backward compatibility breaking features.
*/
class Feature extends BaseConfig
{
/**
* Enable multiple filters for a route or not.
*
* If you enable this:
* - CodeIgniter\CodeIgniter::handleRequest() uses:
* - CodeIgniter\Filters\Filters::enableFilters(), instead of enableFilter()
* - CodeIgniter\CodeIgniter::tryToRouteIt() uses:
* - CodeIgniter\Router\Router::getFilters(), instead of getFilter()
* - CodeIgniter\Router\Router::handle() uses:
* - property $filtersInfo, instead of $filterInfo
* - CodeIgniter\Router\RouteCollection::getFiltersForRoute(), instead of getFilterForRoute()
*/
public bool $multipleFilters = false;
/**
* Use improved new auto routing instead of the default legacy version.
*/
public bool $autoRoutesImproved = false;
}

View File

@ -2,13 +2,13 @@
namespace Config;
use App\Filters\JWTAuthFilter;
use App\Filters\LoginAuthFilter;
use App\Filters\ThrottlerFilter;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\SecureHeaders;
class Filters extends BaseConfig
{
@ -16,54 +16,40 @@ class Filters extends BaseConfig
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* @var array
* @var array<string, class-string|list<class-string>> [filter_name => classname]
* or [filter_name => [classname1, classname2, ...]]
*/
public $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
public array $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'auth' => JWTAuthFilter::class,
'throttler' => ThrottlerFilter::class,
'login' => LoginAuthFilter::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array
* @var array<string, array<string, array<string, string>>>|array<string, list<string>>
*/
public $globals = [
public array $globals = [
'before' => [
'login' => [
'except' => [
'login',
'login/*',
'oauth',
'oauth/*',
'api',
'api/*',
'cron',
'cron/*',
'lang',
'lang/*',
'language',
'language/*',
'integration',
'integration/*'
]
],
// 'honeypot',
'csrf' => [
// 'csrf',
// 'invalidchars',
'session' => [
'except' => [
'api',
'api/*'
]
'login*',
'register',
'auth/a/*',
'logout']
],
],
'after' => [
'toolbar',
// 'honeypot',
// 'secureheaders',
],
];
@ -72,14 +58,13 @@ class Filters extends BaseConfig
* particular HTTP method (GET, POST, etc.).
*
* Example:
* 'post' => ['csrf', 'throttle']
* 'post' => ['foo', 'bar']
*
* @var array
* 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.
*/
public $methods = [
// 'get' => ['throttler'],
// 'post' => ['throttler']
];
public array $methods = [];
/**
* List of filter aliases that should run on any
@ -87,21 +72,6 @@ class Filters extends BaseConfig
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*
* @var array
*/
public $filters = [
'auth' => [
'before' => [
'api/user/*',
'api/user/'
],
],
'throttler' => [
'before' => [
'api/*',
'api/'
]
]
];
public array $filters = [];
}

View File

@ -4,6 +4,9 @@ namespace Config;
use CodeIgniter\Config\ForeignCharacters as BaseForeignCharacters;
/**
* @immutable
*/
class ForeignCharacters extends BaseForeignCharacters
{
}

View File

@ -4,6 +4,8 @@ namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Format\FormatterInterface;
use CodeIgniter\Format\JSONFormatter;
use CodeIgniter\Format\XMLFormatter;
class Format extends BaseConfig
{
@ -22,7 +24,7 @@ class Format extends BaseConfig
*
* @var string[]
*/
public $supportedResponseFormats = [
public array $supportedResponseFormats = [
'application/json',
'application/xml', // machine-readable XML
'text/xml', // human-readable XML
@ -39,10 +41,10 @@ class Format extends BaseConfig
*
* @var array<string, string>
*/
public $formatters = [
'application/json' => 'CodeIgniter\Format\JSONFormatter',
'application/xml' => 'CodeIgniter\Format\XMLFormatter',
'text/xml' => 'CodeIgniter\Format\XMLFormatter',
public array $formatters = [
'application/json' => JSONFormatter::class,
'application/xml' => XMLFormatter::class,
'text/xml' => XMLFormatter::class,
];
/**
@ -55,7 +57,7 @@ class Format extends BaseConfig
*
* @var array<string, int>
*/
public $formatterOptions = [
public array $formatterOptions = [
'application/json' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
'application/xml' => 0,
'text/xml' => 0,

View File

@ -25,8 +25,11 @@ class Generators extends BaseConfig
*
* @var array<string, string>
*/
public $views = [
public array $views = [
'make:cell' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'make:cell_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',

View File

@ -8,36 +8,35 @@ class Honeypot extends BaseConfig
{
/**
* Makes Honeypot visible or not to human
*
* @var bool
*/
public $hidden = true;
public bool $hidden = true;
/**
* Honeypot Label Content
*
* @var string
*/
public $label = 'Fill This Field';
public string $label = 'Fill This Field';
/**
* Honeypot Field Name
*
* @var string
*/
public $name = 'honeypot';
public string $name = 'honeypot';
/**
* Honeypot HTML Template
*
* @var string
*/
public $template = '<label>{label}</label><input type="text" name="{name}" value=""/>';
public string $template = '<label>{label}</label><input type="text" name="{name}" value="">';
/**
* Honeypot container
*
* @var string
* If you enabled CSP, you can remove `style="display:none"`.
*/
public $container = '<div style="display:none">{template}</div>';
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';
}

View File

@ -10,25 +10,21 @@ class Images extends BaseConfig
{
/**
* Default handler used if no other handler is specified.
*
* @var string
*/
public $defaultHandler = 'gd';
public string $defaultHandler = 'gd';
/**
* The path to the image library.
* Required for ImageMagick, GraphicsMagick, or NetPBM.
*
* @var string
*/
public $libraryPath = '/usr/local/bin/convert';
public string $libraryPath = '/usr/local/bin/convert';
/**
* The available handler classes.
*
* @var array<string, string>
*/
public $handlers = [
public array $handlers = [
'gd' => GDHandler::class,
'imagick' => ImageMagickHandler::class,
];

39
ci4/app/Config/Kint.php Executable file → Normal file
View File

@ -3,7 +3,10 @@
namespace Config;
use CodeIgniter\Config\BaseConfig;
use Kint\Parser\ConstructablePluginInterface;
use Kint\Renderer\AbstractRenderer;
use Kint\Renderer\Rich\TabPluginInterface;
use Kint\Renderer\Rich\ValuePluginInterface;
/**
* --------------------------------------------------------------------------
@ -23,27 +26,32 @@ class Kint extends BaseConfig
|--------------------------------------------------------------------------
*/
/**
* @var list<class-string<ConstructablePluginInterface>|ConstructablePluginInterface>|null
*/
public $plugins;
public $maxDepth = 6;
public $displayCalledFrom = true;
public $expanded = false;
public int $maxDepth = 6;
public bool $displayCalledFrom = true;
public bool $expanded = false;
/*
|--------------------------------------------------------------------------
| RichRenderer Settings
|--------------------------------------------------------------------------
*/
public $richTheme = 'aante-light.css';
public $richFolder = false;
public $richSort = AbstractRenderer::SORT_FULL;
public string $richTheme = 'aante-light.css';
public bool $richFolder = false;
public int $richSort = AbstractRenderer::SORT_FULL;
/**
* @var array<string, class-string<ValuePluginInterface>>|null
*/
public $richObjectPlugins;
/**
* @var array<string, class-string<TabPluginInterface>>|null
*/
public $richTabPlugins;
/*
@ -51,11 +59,8 @@ class Kint extends BaseConfig
| CLI Settings
|--------------------------------------------------------------------------
*/
public $cliColors = true;
public $cliForceUTF8 = false;
public $cliDetectWidth = true;
public $cliMinWidth = 40;
public bool $cliColors = true;
public bool $cliForceUTF8 = false;
public bool $cliDetectWidth = true;
public int $cliMinWidth = 40;
}

View File

@ -3,6 +3,7 @@
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Log\Handlers\FileHandler;
class Logger extends BaseConfig
{
@ -37,7 +38,7 @@ class Logger extends BaseConfig
*
* @var array|int
*/
public $threshold = 4;
public $threshold = (ENVIRONMENT === 'production') ? 4 : 9;
/**
* --------------------------------------------------------------------------
@ -46,10 +47,8 @@ class Logger extends BaseConfig
*
* Each item that is logged has an associated date. You can use PHP date
* codes to set your own date formatting
*
* @var string
*/
public $dateFormat = 'Y-m-d H:i:s';
public string $dateFormat = 'Y-m-d H:i:s';
/**
* --------------------------------------------------------------------------
@ -73,18 +72,14 @@ class Logger extends BaseConfig
*
* Handlers are executed in the order defined in this array, starting with
* the handler on top and continuing down.
*
* @var array
*/
public $handlers = [
public array $handlers = [
/*
* --------------------------------------------------------------------
* File Handler
* --------------------------------------------------------------------
*/
'CodeIgniter\Log\Handlers\FileHandler' => [
FileHandler::class => [
// The log levels that this handler will handle.
'handles' => [
'critical',
@ -102,7 +97,7 @@ class Logger extends BaseConfig
* 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'.
* NOTE: Leaving it blank will default to 'log'.
*/
'fileExtension' => '',
@ -140,14 +135,14 @@ class Logger extends BaseConfig
* 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 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,
// /*
// * 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,
// ],
];
}

View File

@ -15,10 +15,8 @@ class Migrations extends BaseConfig
*
* You should enable migrations whenever you intend to do a schema migration
* and disable it back when you're done.
*
* @var bool
*/
public $enabled = true;
public bool $enabled = true;
/**
* --------------------------------------------------------------------------
@ -27,13 +25,9 @@ class Migrations extends BaseConfig
*
* 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
* level the system is at. It then compares the migration level in this
* table to the $config['migration_version'] if they are not the same it
* will migrate up. This must be set.
*
* @var string
* files have already been run.
*/
public $table = 'migrations';
public string $table = 'migrations';
/**
* --------------------------------------------------------------------------
@ -42,14 +36,15 @@ class Migrations extends BaseConfig
*
* This is the format that will be used when creating new migrations
* using the CLI command:
* > php spark migrate:create
* > php spark make:migration
*
* Typical formats:
* 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_
*
* @var string
*/
public $timestampFormat = 'Y-m-d-His_';
public string $timestampFormat = 'Y-m-d-His_';
}

View File

@ -15,15 +15,15 @@ namespace Config;
*
* When working with mime types, please make sure you have the ´fileinfo´
* extension enabled to reliably detect the media types.
*
* @immutable
*/
class Mimes
{
/**
* Map of extensions to mime types.
*
* @var array
*/
public static $mimes = [
public static array $mimes = [
'hqx' => [
'application/mac-binhex40',
'application/mac-binhex',
@ -55,6 +55,8 @@ class Mimes
'lzh' => 'application/octet-stream',
'exe' => [
'application/octet-stream',
'application/vnd.microsoft.portable-executable',
'application/x-dosexec',
'application/x-msdownload',
],
'class' => 'application/octet-stream',
@ -102,8 +104,6 @@ class Mimes
],
'pptx' => [
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/x-zip',
'application/zip',
],
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
@ -260,6 +260,7 @@ class Mimes
'image/png',
'image/x-png',
],
'webp' => 'image/webp',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'css' => [
@ -509,22 +510,21 @@ class Mimes
{
$type = trim(strtolower($type), '. ');
$proposedExtension = trim(strtolower($proposedExtension));
$proposedExtension = trim(strtolower($proposedExtension ?? ''));
if ($proposedExtension !== '') {
if (array_key_exists($proposedExtension, static::$mimes) && in_array($type, is_string(static::$mimes[$proposedExtension]) ? [static::$mimes[$proposedExtension]] : static::$mimes[$proposedExtension], true)) {
// The detected mime type matches with the proposed extension.
return $proposedExtension;
}
// An extension was proposed, but the media type does not match the mime type list.
return null;
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 ((is_string($types) && $types === $type) || (is_array($types) && in_array($type, $types, true))) {
if (in_array($type, (array) $types, true)) {
return $ext;
}
}

View File

@ -4,6 +4,14 @@ namespace Config;
use CodeIgniter\Modules\Modules as BaseModules;
/**
* Modules Configuration.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*
* @immutable
*/
class Modules extends BaseModules
{
/**
@ -31,6 +39,29 @@ class Modules extends BaseModules
*/
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
@ -41,7 +72,7 @@ class Modules extends BaseModules
*
* If it is not listed, only the base application elements will be used.
*
* @var string[]
* @var list<string>
*/
public $aliases = [
'events',

View File

@ -20,7 +20,7 @@ class Pager extends BaseConfig
*
* @var array<string, string>
*/
public $templates = [
public array $templates = [
'default_full' => 'CodeIgniter\Pager\Views\default_full',
'default_simple' => 'CodeIgniter\Pager\Views\default_simple',
'default_head' => 'CodeIgniter\Pager\Views\default_head',
@ -32,8 +32,6 @@ class Pager extends BaseConfig
* --------------------------------------------------------------------------
*
* The default number of results shown in a single page.
*
* @var int
*/
public $perPage = 20;
public int $perPage = 20;
}

View File

@ -22,10 +22,8 @@ class Paths
*
* This must contain the name of your "system" folder. Include
* the path if the folder is not in the same directory as this file.
*
* @var string
*/
public $systemDirectory = __DIR__ . '/../../vendor/codeigniter4/framework/system';
public string $systemDirectory = __DIR__ . '/../../vendor/codeigniter4/framework/system';
/**
* ---------------------------------------------------------------
@ -34,14 +32,12 @@ class Paths
*
* 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 getServer. If
* you do, use a full getServer path.
* 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
*
* @var string
*/
public $appDirectory = __DIR__ . '/..';
public string $appDirectory = __DIR__ . '/..';
/**
* ---------------------------------------------------------------
@ -53,10 +49,8 @@ class Paths
* 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.
*
* @var string
*/
public $writableDirectory = __DIR__ . '/../../writable';
public string $writableDirectory = __DIR__ . '/../../writable';
/**
* ---------------------------------------------------------------
@ -64,10 +58,8 @@ class Paths
* ---------------------------------------------------------------
*
* This variable must contain the name of your "tests" directory.
*
* @var string
*/
public $testsDirectory = __DIR__ . '/../../tests';
public string $testsDirectory = __DIR__ . '/../../tests';
/**
* ---------------------------------------------------------------
@ -78,8 +70,6 @@ class Paths
* 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()`.
*
* @var string
*/
public $viewDirectory = __DIR__ . '/../Views';
public string $viewDirectory = __DIR__ . '/../Views';
}

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',
];
}

View File

@ -0,0 +1,90 @@
<?php
const SK_PERMISSION_MATRIX = [
"admin" => [
"clientes.create",
"clientes.edit",
"clientes.delete",
"clientes.menu",
"plantillaTarifa.create",
"plantillaTarifa.edit",
"plantillaTarifa.delete",
"plantillaTarifa.menu",
"presupuesto.create",
"presupuesto.edit",
"presupuesto.delete",
"presupuesto.menu",
"tarifaPreimpresion.create",
"tarifaPreimpresion.edit",
"tarifaPreimpresion.delete",
"tarifaPreimpresion.menu",
"tarifaManipulado.create",
"tarifaManipulado.edit",
"tarifaManipulado.delete",
"tarifaManipulado.menu",
"tarifaAcabado.create",
"tarifaAcabado.edit",
"tarifaAcabado.delete",
"tarifaAcabado.menu",
"tarifaEncuadernacion.create",
"tarifaEncuadernacion.edit",
"tarifaEncuadernacion.delete",
"tarifaEncuadernacion.menu",
"tarifaEnvio.create",
"tarifaEnvio.edit",
"tarifaEnvio.delete",
"tarifaEnvio.menu",
"proveedores.create",
"proveedores.edit",
"proveedores.delete",
"proveedores.menu",
"ajustes.create",
"ajustes.edit",
"ajustes.delete",
"ajustes.menu",
"actividad.create",
"actividad.edit",
"actividad.delete",
"actividad.menu",
],
"cliente" => [
"token.token",
"token.menu",
"Profile.index",
"Profile.store",
"Profile.menu",
"Activity.index",
"Activity.menu",
"save.save",
"save.menu",
],
"comercial" => [
"token.token",
"token.menu",
],
"produccion" => [
"token.token",
"token.menu",
],
"maquina" => [
"token.token",
"token.menu",
],
"maquetador" => [
"token.token",
"token.menu",
],
"director" => [
"token.token",
"token.menu",
],
"contabilidad" => [
"token.token",
"token.menu",
],
"editor" => [
"token.token",
"token.menu",
"Profile.index",
"Profile.menu",
],
];

View File

@ -0,0 +1,48 @@
<?php
const SK_PERMISSIONS = [
'clientes.create' => 'Can create',
'clientes.edit' => 'Can edit',
'clientes.delete' => 'Can delete',
'clientes.menu' => 'Menu shall be visualize',
'plantillaTarifa.create' => 'Can create',
'plantillaTarifa.edit' => 'Can edit',
'plantillaTarifa.delete' => 'Can delete',
'plantillaTarifa.menu' => 'Menu shall be visualize',
'presupuesto.create' => 'Can create',
'presupuesto.edit' => 'Can edit',
'presupuesto.delete' => 'Can delete',
'presupuesto.menu' => 'Menu shall be visualize',
'tarifaPreimpresion.create' => 'Can create',
'tarifaPreimpresion.edit' => 'Can edit',
'tarifaPreimpresion.delete' => 'Can delete',
'tarifaPreimpresion.menu' => 'Menu shall be visualize',
'tarifaManipulado.create' => 'Can create',
'tarifaManipulado.edit' => 'Can edit',
'tarifaManipulado.delete' => 'Can delete',
'tarifaManipulado.menu' => 'Menu shall be visualize',
'tarifaAcabado.create' => 'Can create',
'tarifaAcabado.edit' => 'Can edit',
'tarifaAcabado.delete' => 'Can delete',
'tarifaAcabado.menu' => 'Menu shall be visualize',
'tarifaEncuadernacion.create' => 'Can create',
'tarifaEncuadernacion.edit' => 'Can edit',
'tarifaEncuadernacion.delete' => 'Can delete',
'tarifaEncuadernacion.menu' => 'Menu shall be visualize',
'tarifaEnvio.create' => 'Can create',
'tarifaEnvio.edit' => 'Can edit',
'tarifaEnvio.delete' => 'Can delete',
'tarifaEnvio.menu' => 'Menu shall be visualize',
'proveedores.create' => 'Can create',
'proveedores.edit' => 'Can edit',
'proveedores.delete' => 'Can delete',
'proveedores.menu' => 'Menu shall be visualize',
'ajustes.create' => 'Can create',
'ajustes.edit' => 'Can edit',
'ajustes.delete' => 'Can delete',
'ajustes.menu' => 'Menu shall be visualize',
'actividad.create' => 'Can create',
'actividad.edit' => 'Can edit',
'actividad.delete' => 'Can delete',
'actividad.menu' => 'Menu shall be visualize',
];

View File

@ -0,0 +1,40 @@
<?php
const SK_ROLES = [
'admin' => [
'title' => 'Administrador',
'description' => 'Describeme',
],
'cliente' => [
'title' => 'Cliente',
'description' => '',
],
'comercial' => [
'title' => 'Comercial',
'description' => '',
],
'produccion' => [
'title' => 'Producción',
'description' => '',
],
'maquina' => [
'title' => 'Máquina',
'description' => '',
],
'maquetador' => [
'title' => 'Maquetador',
'description' => '',
],
'director' => [
'title' => 'Director',
'description' => '',
],
'contabilidad' => [
'title' => 'Contabilidad',
'description' => '',
],
'editor' => [
'title' => 'Editor',
'description' => '',
],
];

View File

@ -1,28 +1,13 @@
<?php
namespace Config;
use CodeIgniter\Router\RouteCollection;
// Create a new instance of our RouteCollection class.
$routes = Services::routes();
// Load the system's routing file first, so that the app and ENVIRONMENT
// can override as needed.
if (file_exists(SYSTEMPATH . 'Config/Routes.php')) {
require SYSTEMPATH . 'Config/Routes.php';
}
/*
* --------------------------------------------------------------------
* Router Setup
* --------------------------------------------------------------------
/**
* @var RouteCollection $routes
*/
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);
//service('auth')->routes($routes, ['except' => ['login', 'register']]);
service('auth')->routes($routes);
//WEB ROUTER ------------------------------------------------------
//------------------------------------------------------------------
@ -30,19 +15,16 @@ $routes->get('/', 'Home::index');
$routes->get('lang/{locale}', 'Language::index');
$routes->get('viewmode/(:alpha)', 'Viewmode::index/$1');
//API ROUTER ------------------------------------------------------
//------------------------------------------------------------------
$routes->get('api/', 'Api::index');
$routes->get('api/status', 'Api::status');
$routes->post('api/signIn', 'Api::signIn');
//API ROUTER USER ------------------------------------------------------
//------------------------------------------------------------------
$routes->get('api/user/', 'Api::user/all');
$routes->get('api/user/(:segment)', 'Api::user/id/$1');
$routes->post('api/user/', 'Api::user/add');
$routes->put('api/user/(:segment)', 'Api::user/edit/$1');
$routes->delete('api/user/(:segment)', 'Api::user/delete/$1');
$routes->group('activity', ['namespace' => 'App\Controllers\Sistema'], function ($routes) {
$routes->get('', 'Actividad::index', ['as' => 'activityList']);
$routes->post('datatable', 'Actividad::datatable', ['as' => 'dataTableOfActividad']);
});
$routes->group('settings', ['namespace' => 'App\Controllers\Sistema'], function ($routes) {
$routes->get('', 'Ajustes::settings', ['as' => 'settingsEdit']);
$routes->post('', 'Ajustes::settings', ['as' => 'settingsPost']);
});
/*

112
ci4/app/Config/Routing.php Normal file
View File

@ -0,0 +1,112 @@
<?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
{
/**
* 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'
*/
public array $routeFiles = [
APPPATH . 'Config/Routes.php',
];
/**
* The default namespace to use for Controllers when no other
* namespace has been specified.
*
* Default: 'App\Controllers'
*/
public string $defaultNamespace = 'App\Controllers';
/**
* The default controller to use when no other controller has been
* specified.
*
* Default: 'Home'
*/
public string $defaultController = 'Home';
/**
* The default method to call on the controller when no other
* method has been set in the route.
*
* Default: 'index'
*/
public string $defaultMethod = 'index';
/**
* Whether to translate dashes in URIs 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 = true;
/**
* If TRUE, will enable the use of the 'prioritize' option
* when defining routes.
*
* Default: false
*/
public bool $prioritize = false;
/**
* Map of URI segments and namespaces. For Auto Routing (Improved).
*
* The key is the first URI segment. The value is the controller namespace.
* E.g.,
* [
* 'blog' => 'Acme\Blog\Controllers',
* ]
*
* @var array [ uri_segment => namespace ]
*/
public array $moduleRoutes = [];
}

View File

@ -0,0 +1,74 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Safekat extends BaseConfig
{
public string $appName = 'ERP Safekat 2.0';
public string $i18n = 'es-ES';
public $vista_impresion = 'impresion';
public $vista_maquetacion = 'maquetacion';
public $vista_digitalizacion = 'digitalizacion';
public array $languages = [
'en' => 'English',
'es' => 'Spanish',
];
public array $languageFlags = [
'en' => 'us',
'es' => 'es',
];
public $authImplemented = false;
public $theme = [
'name' => 'vuexy',
'body-sm' => false,
'navbar' => [
'bg' => 'gray',
'type' => 'dark',
'border' => true,
'user' => [
'visible' => true,
'shadow' => 0,
],
],
'sidebar' => [
'type' => 'dark',
'shadow' => 4,
'border' => false,
'compact' => true,
'links' => [
'bg' => 'black', // only works with AdminLTE theme
'shadow' => 1,
],
'brand' => [
'bg' => 'gray-dark',
'logo' => [
'icon' => 'favicon.ico', // path to image | this example icon on public root folder.
'text' => 'sk_test',
'shadow' => 2,
],
],
'user' => [
'visible' => true,
'shadow' => 2,
],
],
'footer' => [
'fixed' => false,
'organization' => 'Safekat',
'orglink' => '#',
],
];
}

View File

@ -6,38 +6,52 @@ 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 = 'session';
/**
* --------------------------------------------------------------------------
* 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 cookie.
*
* @var string
* Token name for Cross Site Request Forgery protection.
*/
public $tokenName = 'csrf_test_name';
public string $tokenName = 'csrf_test_name';
/**
* --------------------------------------------------------------------------
* CSRF Header Name
* --------------------------------------------------------------------------
*
* Token name for Cross Site Request Forgery protection cookie.
*
* @var string
* Header name for Cross Site Request Forgery protection.
*/
public $headerName = 'X-CSRF-TOKEN';
public string $headerName = 'X-CSRF-TOKEN';
/**
* --------------------------------------------------------------------------
* CSRF Cookie Name
* --------------------------------------------------------------------------
*
* Cookie name for Cross Site Request Forgery protection cookie.
*
* @var string
* Cookie name for Cross Site Request Forgery protection.
*/
public $cookieName = 'csrf_cookie_name';
public string $cookieName = 'csrf_cookie_name';
/**
* --------------------------------------------------------------------------
@ -47,21 +61,17 @@ class Security extends BaseConfig
* Expiration time for Cross Site Request Forgery protection cookie.
*
* Defaults to two hours (in seconds).
*
* @var int
*/
public $expires = 7200;
public int $expires = 7200;
/**
* --------------------------------------------------------------------------
* CSRF Regenerate
* --------------------------------------------------------------------------
*
* Regenerate CSRF Token on every request.
*
* @var bool
* Regenerate CSRF Token on every submission.
*/
public $regenerate = true;
public bool $regenerate = true;
/**
* --------------------------------------------------------------------------
@ -69,10 +79,8 @@ class Security extends BaseConfig
* --------------------------------------------------------------------------
*
* Redirect to previous page with error on failure.
*
* @var bool
*/
public $redirect = true;
public bool $redirect = false;
/**
* --------------------------------------------------------------------------
@ -87,9 +95,7 @@ class Security extends BaseConfig
*
* @see https://portswigger.net/web-security/csrf/samesite-cookies
*
* @var string
*
* @deprecated
* @deprecated `Config\Cookie` $samesite property is used.
*/
public $samesite = 'Lax';
public string $samesite = 'Lax';
}

102
ci4/app/Config/Session.php Normal file
View File

@ -0,0 +1,102 @@
<?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;
}

51
ci4/app/Config/Toolbar.php Executable file → Normal file
View File

@ -33,7 +33,7 @@ class Toolbar extends BaseConfig
*
* @var string[]
*/
public $collectors = [
public array $collectors = [
Timers::class,
Database::class,
Logs::class,
@ -44,6 +44,16 @@ class Toolbar extends BaseConfig
Events::class,
];
/**
* --------------------------------------------------------------------------
* Collect Var Data
* --------------------------------------------------------------------------
*
* If set to false var data from the views will not be colleted. Useful to
* avoid high memory usage when there are lots of data passed to the view.
*/
public bool $collectVarData = true;
/**
* --------------------------------------------------------------------------
* Max History
@ -52,10 +62,8 @@ class Toolbar extends BaseConfig
* `$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.
*
* @var int
*/
public $maxHistory = 20;
public int $maxHistory = 20;
/**
* --------------------------------------------------------------------------
@ -64,10 +72,8 @@ class Toolbar extends BaseConfig
*
* The full path to the the views that are used by the toolbar.
* This MUST have a trailing slash.
*
* @var string
*/
public $viewsPath = SYSTEMPATH . 'Debug/Toolbar/Views/';
public string $viewsPath = SYSTEMPATH . 'Debug/Toolbar/Views/';
/**
* --------------------------------------------------------------------------
@ -80,8 +86,33 @@ class Toolbar extends BaseConfig
* with hundreds of queries.
*
* `$maxQueries` defines the maximum amount of queries that will be stored.
*
* @var int
*/
public $maxQueries = 100;
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.
*/
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.
*/
public array $watchedExtensions = [
'php', 'css', 'js', 'html', 'svg', 'json', 'env',
];
}

View File

@ -23,7 +23,7 @@ class UserAgents extends BaseConfig
*
* @var array<string, string>
*/
public $platforms = [
public array $platforms = [
'windows nt 10.0' => 'Windows 10',
'windows nt 6.3' => 'Windows 8.1',
'windows nt 6.2' => 'Windows 8',
@ -78,7 +78,7 @@ class UserAgents extends BaseConfig
*
* @var array<string, string>
*/
public $browsers = [
public array $browsers = [
'OPR' => 'Opera',
'Flock' => 'Flock',
'Edge' => 'Spartan',
@ -119,7 +119,7 @@ class UserAgents extends BaseConfig
*
* @var array<string, string>
*/
public $mobiles = [
public array $mobiles = [
// legacy array, old values commented out
'mobileexplorer' => 'Mobile Explorer',
// 'openwave' => 'Open Wave',
@ -228,7 +228,7 @@ class UserAgents extends BaseConfig
*
* @var array<string, string>
*/
public $robots = [
public array $robots = [
'googlebot' => 'Googlebot',
'msnbot' => 'MSNBot',
'baiduspider' => 'Baiduspider',

View File

@ -2,16 +2,17 @@
namespace Config;
use CodeIgniter\Validation\CreditCardRules;
use CodeIgniter\Validation\FileRules;
use CodeIgniter\Validation\FormatRules;
use CodeIgniter\Validation\Rules;
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
class Validation extends BaseConfig
{
//--------------------------------------------------------------------
// --------------------------------------------------------------------
// Setup
//--------------------------------------------------------------------
// --------------------------------------------------------------------
/**
* Stores the classes that contain the
@ -19,12 +20,11 @@ class Validation
*
* @var string[]
*/
public $ruleSets = [
public array $ruleSets = [
Rules::class,
FormatRules::class,
FileRules::class,
CreditCardRules::class,
\App\Validation\ApiAuthRules::class,
];
/**
@ -33,14 +33,13 @@ class Validation
*
* @var array<string, string>
*/
public $templates = [
public array $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
'bootstrap_style' => 'themes/_commonPartialsBs/_form_validation_errors',
];
//--------------------------------------------------------------------
// --------------------------------------------------------------------
// Rules
//--------------------------------------------------------------------
// --------------------------------------------------------------------
}

View File

@ -3,7 +3,12 @@
namespace Config;
use CodeIgniter\Config\View as BaseView;
use CodeIgniter\View\ViewDecoratorInterface;
/**
* @phpstan-type ParserCallable (callable(mixed): mixed)
* @phpstan-type ParserCallableString (callable(mixed): mixed)&string
*/
class View extends BaseView
{
/**
@ -29,7 +34,8 @@ class View extends BaseView
* { title|esc(js) }
* { created_on|date(Y-m-d)|esc(attr) }
*
* @var array
* @var array<string, string>
* @phpstan-var array<string, ParserCallableString>
*/
public $filters = [];
@ -38,7 +44,19 @@ class View extends BaseView
* by the core Parser by creating aliases that will be replaced with
* any callable. Can be single or tag pair.
*
* @var array
* @var array<string, array<string>|callable|string>
* @phpstan-var array<string, array<ParserCallableString>|ParserCallableString|ParserCallable>
*/
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 class-string<ViewDecoratorInterface>[]
*/
public array $decorators = [];
}

View File

@ -1,81 +0,0 @@
<?php
namespace App\Controllers;
use App\Models\ActivityModel;
use App\Models\Usuarios\UserModel;
class Activity extends BaseController
{
private $user_model;
private $activity_model;
function __construct()
{
$this->user_model = new UserModel();
$this->activity_model = new ActivityModel();
}
public function index()
{
$session = session();
$data['title'] = [
'module' => lang("App.activity_title"),
'page' => lang("App.activity_subtitle"),
'icon' => 'fas fa-list'
];
$data['breadcrumb'] = [
['title' => lang("App.menu_activity"), 'route' => site_url('activity'), 'active' => true]
];
$data['logs'] = $this->activity_model->select('SUM( IF( os LIKE "%Windows%", 1, 0 ) ) AS windows,
SUM( IF( os = "Mac OS X", 1, 0 ) ) AS mac,
SUM( IF( os = "Linux", 1, 0 ) ) AS linux,
SUM( IF( os = "Android", 1, 0 ) ) AS android,
SUM( IF( os = "iOS", 1, 0 ) ) AS iphone,
SUM( IF( browser LIKE "%Chrome%", 1, 0 ) ) AS chrome,
SUM( IF( browser LIKE "%Firefox%", 1, 0 ) ) AS firefox,
SUM( IF( browser LIKE "%Safari%", 1, 0 ) ) AS safari,
SUM( IF( browser LIKE "%Internet Explorer%", 1, 0 ) ) AS ie,
SUM( IF( browser LIKE "%Edge%", 1, 0 ) ) AS edge,
SUM( IF( browser LIKE "%Opera%", 1, 0 ) ) AS opera')->where('auth_activity.user',$session->get('token'))->first();
$data['all'] = "";
echo view(getenv('theme.path').'form/activity/index',$data);
}
public function all()
{
$session = session();
$dashboard = $session->get('dashboard')??'user';
if($dashboard != 'admin'){
return redirect()->to('/activity');
}
$data['title'] = [
'module' => lang("App.activity_title"),
'page' => lang("App.activity_subtitle"),
'icon' => 'fas fa-list'
];
$data['breadcrumb'] = [
['title' => lang("App.menu_dashboard"), 'route' => "/home", 'active' => false],
['title' => lang("App.activity_title"), 'route' => "", 'active' => true]
];
$data['logs'] = $this->activity_model->select('SUM( IF( os LIKE "%Windows%", 1, 0 ) ) AS windows,
SUM( IF( os = "Mac OS X", 1, 0 ) ) AS mac,
SUM( IF( os = "Linux", 1, 0 ) ) AS linux,
SUM( IF( os = "Android", 1, 0 ) ) AS android,
SUM( IF( os = "iOS", 1, 0 ) ) AS iphone,
SUM( IF( browser LIKE "%Chrome%", 1, 0 ) ) AS chrome,
SUM( IF( browser LIKE "%Firefox%", 1, 0 ) ) AS firefox,
SUM( IF( browser LIKE "%Safari%", 1, 0 ) ) AS safari,
SUM( IF( browser LIKE "%Internet Explorer%", 1, 0 ) ) AS ie,
SUM( IF( browser LIKE "%Edge%", 1, 0 ) ) AS edge,
SUM( IF( browser LIKE "%Opera%", 1, 0 ) ) AS opera')->first();
$data['all'] = "/all";
echo view(getenv('theme.path').'form/activity/index',$data);
}
}

View File

@ -5,8 +5,8 @@ namespace App\Controllers;
use App\Models\CronTabModel;
use App\Models\NotificationModel;
use App\Models\Usuarios\UserModel;
use App\Models\Usuarios\UserGroupModel;
use App\Models\Usuarios\GroupUserModel;
use App\Models\Usuarios\GroupModel;
use App\Models\Usuarios\GroupsUsersModel;
use App\Models\ActivityModel;
use CodeIgniter\RESTful\ResourceController;
@ -24,8 +24,8 @@ class Ajax extends ResourceController
function __construct()
{
$this->user_model = new UserModel();
$this->group_model = new UserGroupModel();
$this->group_user_model = new GroupUserModel();
$this->group_model = new GroupModel();
$this->group_user_model = new GroupsUsersModel();
$this->activity_model = new ActivityModel();
$this->crontab_model = new CronTabModel();
$this->notification_model = new NotificationModel();
@ -56,20 +56,20 @@ class Ajax extends ResourceController
//Total number of records without filtering
$totalRecords = $this->user_model->select('id_user')
//->join('auth_user_group','auth_user_group.token = auth_user.group')
//->join('auth_groups','auth_groups.token = auth_user.group')
->countAllResults();
//Total number of records with filtering
$totalRecordwithFilter = $this->user_model->select('id_user')
//->join('auth_user_group','auth_user_group.token = auth_user.group')
//->join('auth_groups','auth_groups.token = auth_user.group')
->orLike('first_name', $searchValue)
->orLike('email', $searchValue)
->countAllResults();
//Fetch records
//$records = $this->user_model->select('auth_user.*,auth_user_group.title')
//$records = $this->user_model->select('auth_user.*,auth_groups.title')
$records = $this->user_model->select('auth_user.*')
//->join('auth_user_group','auth_user_group.token = auth_user.group')
//->join('auth_groups','auth_groups.token = auth_user.group')
->orLike('first_name', $searchValue)
->orLike('email', $searchValue)
->orderBy($columnName,$columnSortOrder)

View File

@ -1,273 +0,0 @@
<?php
namespace App\Controllers;
use App\Libraries\PasswordHash;
use App\Models\SettingsModel;
use App\Models\Usuarios\UserModel;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\Validation\Exceptions\ValidationException;
use Config\Services;
class Api extends ResourceController
{
private $user_model;
private $settings_model;
private $data_format;
function __construct()
{
$this->user_model = new UserModel();
$this->settings_model = new SettingsModel();
$this->data_format = getenv('api.return')??'json';
}
public function index()
{
return $this->response->setJSON([
'message' => 'Welcome!'
]);
}
public function status()
{
return $this->response->setJSON([
'status' => true,
'message' => 'The system is running!'
]);
}
public function signIn()
{
$rules = [
'email' => 'required|valid_email|validateAuthPermission[email]',
'password' => 'required|validateAuthPassword[email, password]'
];
$errors = [
'email' => [
'required' => 'The email field is required.',
'valid_email' => 'Invalid email.',
'validateAuthPermission' => 'This user {value} does not have access permission.'
],
'password' => [
'required' => 'The password field is required.',
'validateAuthPassword' => 'Invalid password.'
]
];
$input = $this->baseRequest($this->request);
if (!$this->baseValidateRequest($input, $rules, $errors)) {
return $this->baseResponse($this->validator->getErrors(),ResponseInterface::HTTP_BAD_REQUEST);
}
return $this->generateCredential($input['email']);
}
private function generateCredential(string $email, int $responseCode = ResponseInterface::HTTP_OK){
try {
helper('jwt');
return $this->baseResponse([
'access_token' => jwtSignature($email)
]);
} catch (\Exception $exception) {
return $this->baseResponse(['error' => $exception->getMessage()], $responseCode);
}
}
private function baseResponse(array $responseBody, int $code = ResponseInterface::HTTP_OK)
{
if($this->data_format == 'json'){
return $this->response->setStatusCode($code)->setJSON($responseBody)??'';
}else{
return $this->response->setStatusCode($code)->setXML($responseBody)??'';
}
}
private function baseRequest(IncomingRequest $request){
return $request->getVar()??[];
}
private function baseValidateRequest(array $input, array $rules, array $messages = []){
$this->validator = Services::Validation()->setRules($rules);
if (is_string($rules)) {
$validation = config('Validation');
if (!isset($validation->$rules)) {
throw ValidationException::forRuleNotFound($rules);
}
if (!$messages) {
$errorName = $rules . '_errors';
$messages = $validation->$errorName ?? [];
}
$rules = $validation->$rules;
}
return $this->validator->setRules($rules, $messages)->run($input);
}
public function user($method = null, $key = null)
{
switch ($method):
/**
* Return all users.
*/
case 'all':
try {
$data = $this->user_model->select('token,first_name,last_name,date_birth,email,mobile,picture,language,address,address,state,country,zip_code,status,created_at,updated_at')->findAll()??[];
return $this->setResponseFormat($this->data_format)->respond($data);
} catch (\Exception $exception) {
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => $exception->getMessage()
]);
}
/**
* Return user for token id.
*/
case 'id':
try {
$data = $this->user_model->select('token,first_name,last_name,date_birth,email,mobile,picture,language,address,address,state,country,zip_code,status,created_at,updated_at')->where('token',$key)->first()??[];
return $this->setResponseFormat($this->data_format)->respond($data);
} catch (\Exception $exception) {
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => $exception->getMessage()
]);
}
/**
* Return add user.
*/
case 'add':
try {
$body = $this->request->getVar() == [] ? (array) $this->request->getJSON() : $this->request->getVar();
if(empty($body["first_name"]??"")){
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => 'The first name parameter is null or empty.'
]);
}
if(empty($body["last_name"]??"")){
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => 'The last name parameter is null or empty.'
]);
}
if(empty($body["email"]??"")){
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => 'The email parameter is null or empty.'
]);
}else{
$validate = $this->user_model->where('email',$body["email"]??"")->countAllResults();
if($validate > 0){
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => 'Email already registered!'
]);
}
}
if(empty($body["password"]??"")){
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => 'The password parameter is null or empty.'
]);
}else{
if(strlen($body["password"]??"") < 8){
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => 'Password must be at least 8 characters long.'
]);
}
}
$settings = $this->settings_model->first()??[];
$phpass = new PasswordHash(8, true);
$token = md5(uniqid(rand(), true));
$this->user_model->save([
'group' => $settings['default_role'],
'first_name' => $body['first_name'],
'last_name' => $body['last_name'],
'mobile' => '',
'picture' => '/assets/img/default-user.png',
'email' => $body['email'],
'password' => $phpass->HashPassword($body['password']),
'last_access' => date('Y-m-d h:i:s'),
'last_ip' => '::1',
'language' => $settings['default_language'],
'token' => $token,
'status' => true
]);
$data = $this->user_model->select('token,first_name,last_name,date_birth,email,mobile,picture,language,address,address,state,country,zip_code,status,created_at,updated_at')->where('token',$token)->first()??[];
return $this->setResponseFormat($this->data_format)->respond([
'error' => false,
'message' => 'Added successfully!',
'data' => $data??[]
]);
} catch (\Exception $exception) {
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => $exception->getMessage()
]);
}
/**
* Return edit user.
*/
case 'edit':
try {
$data = $this->user_model->where('token',$key)->first()??[];
if($data == []){
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => 'User not found!'
]);
}
$body = $this->request->getVar() == [] ? (array) $this->request->getJSON() : $this->request->getVar();
$this->user_model->save([
'id_user' => $data['id_user'],
'first_name' => empty($body["first_name"]??"")?$data['first_name']:$body["first_name"]??"",
'last_name' => empty($body["last_name"]??"")?$data['last_name']:$body["last_name"]??"",
'date_birth' => empty($body["date_birth"]??"")?$data['date_birth']:$body["date_birth"]??"",
'address' => empty($body["address"]??"")?$data['address']:$body["address"]??"",
'city' => empty($body["city"]??"")?$data['city']:$body["city"]??"",
'state' => empty($body["state"]??"")?$data['state']:$body["state"]??"",
'country' => empty($body["country"]??"")?$data['country']:$body["country"]??"",
'zip_code' => empty($body["zip_code"]??"")?$data['zip_code']:$body["zip_code"]??"",
'mobile' => empty($body["mobile"]??"")?$data['mobile']:$body["mobile"]??"",
'status' => empty($body["status"]??"")?$data['status']:$body["status"]??""
]);
$data = $this->user_model->select('token,first_name,last_name,date_birth,email,mobile,picture,language,address,address,state,country,zip_code,status,created_at,updated_at')->where('token',$key)->first()??[];
return $this->setResponseFormat($this->data_format)->respond([
'error' => false,
'message' => 'Successfully Edited!',
'data' => $data??[]
]);
} catch (\Exception $exception) {
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => $exception->getMessage()
]);
}
/**
* Return delete user.
*/
case 'delete':
try {
$this->user_model->where('token', $key)->delete();
return $this->setResponseFormat($this->data_format)->respond([
'error' => false,
'message' => 'Successfully deleted!'
]);
} catch (\Exception $exception) {
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => $exception->getMessage()
]);
}
/**
* Return Default.
*/
default:
return $this->setResponseFormat($this->data_format)->respond([
'error' => true,
'message' => 'Method call is invalid.'
]);
endswitch;
}
}

View File

@ -37,7 +37,7 @@ class BaseController extends Controller
*
* @var array
*/
protected $helpers = ['general','jwt'];
protected $helpers = ['general', 'go_common'];
/**
* Constructor.
@ -57,24 +57,7 @@ class BaseController extends Controller
$language->setLocale($session->lang);
// Set TimeZone
if(empty($session->get('settings'))){
$settingsModel = new SettingsModel();
$settings = $settingsModel->select('default_timezone')->first()??[];
date_default_timezone_set($settings['default_timezone']??'America/Sao_Paulo');
}else{
date_default_timezone_set($session->get('settings')['default_timezone']??'America/Sao_Paulo');
}
date_default_timezone_set('Europe/Madrid');
// Get notification
if(!empty($session->get('token'))) {
$notificationModel = new NotificationModel();
$pulse = $notificationModel->where('user_recipient',$session->get('token'))->where('is_read',false)->countAllResults() ?? 0;
$notification = $notificationModel->select('token,title,is_read,created_at')->where('user_recipient',$session->get('token'))->orderBy('created_at','desc')->findAll(5) ?? [];
$session->set('notification', $notification);
$session->set('pulse', $pulse);
}else{
$session->set('notification', []);
$session->set('pulse', 0);
}
}
}

View File

@ -8,7 +8,7 @@ use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
abstract class GoBaseResourceController extends \CodeIgniter\RESTful\ResourceController
abstract class BaseResourceController extends \CodeIgniter\RESTful\ResourceController
{
/**
*
@ -85,7 +85,7 @@ abstract class GoBaseResourceController extends \CodeIgniter\RESTful\ResourceCon
*
* @var array
*/
protected $helpers = ['session', 'go_common', 'form', 'text', 'general','jwt']; //JJO
protected $helpers = ['session', 'go_common', 'form', 'text', 'general']; //JJO
/**
* Initializer method.

View File

@ -1,7 +1,6 @@
<?php namespace App\Controllers\Clientes;
use App\Controllers\GoBaseResourceController;
use App\Models\Collection;
@ -9,17 +8,11 @@ use App\Entities\Clientes\ClienteEntity;
use App\Models\Clientes\ClienteModel;
use App\Models\Configuracion\ProvinciaModel;
use App\Models\Configuracion\UserModel;
use App\Models\Configuracion\ComunidadAutonomaModel;
use App\Models\Configuracion\FormaPagoModel;
use App\Models\Configuracion\PaisModel;
class Cliente extends \App\Controllers\GoBaseResourceController
class Cliente extends \App\Controllers\BaseResourceController
{
protected $modelName = ClienteModel::class;
@ -78,12 +71,8 @@ class Cliente extends \App\Controllers\GoBaseResourceController
public function add()
{
// JJO
$session = session();
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -92,7 +81,7 @@ class Cliente extends \App\Controllers\GoBaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_created_id'] = $session->id_user;
$sanitizedData['user_created_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
@ -151,8 +140,6 @@ class Cliente extends \App\Controllers\GoBaseResourceController
public function edit($requestedId = null)
{
// JJO
$session = session();
if ($requestedId == null) :
return $this->redirect2listView();
@ -165,9 +152,9 @@ class Cliente extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -188,7 +175,7 @@ class Cliente extends \App\Controllers\GoBaseResourceController
}
// JJO
$sanitizedData['user_updated_id'] = $session->id_user;
$sanitizedData['user_updated_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Clientes;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -14,7 +14,7 @@ use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;
class Clientecontactos extends \App\Controllers\GoBaseResourceController
class Clientecontactos extends \App\Controllers\BaseResourceController
{
protected $modelName = ClienteContactoModel::class;
@ -60,9 +60,9 @@ class Clientecontactos extends \App\Controllers\GoBaseResourceController
public function add()
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -134,9 +134,9 @@ class Clientecontactos extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -10,7 +10,7 @@ use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;
class Clientedirecciones extends \App\Controllers\GoBaseResourceController
class Clientedirecciones extends \App\Controllers\BaseResourceController
{
protected $modelName = ClienteDireccionesModel::class;
protected $format = 'json';

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Clientes;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
use App\Entities\Clientes\ClientePlantillaPreciosEntity;
@ -9,7 +9,7 @@ use App\Entities\Clientes\ClientePlantillaPreciosEntity;
use App\Models\Clientes\ClientePlantillaPreciosModel;
class Clienteplantillaprecios extends \App\Controllers\GoBaseResourceController
class Clienteplantillaprecios extends \App\Controllers\BaseResourceController
{
protected $modelName = ClientePlantillaPreciosModel::class;
@ -70,9 +70,9 @@ class Clienteplantillaprecios extends \App\Controllers\GoBaseResourceController
// plantilla desde la lista
public function update($requestedId = null)
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
if ($requestedId == null) :
return;
@ -94,12 +94,10 @@ class Clienteplantillaprecios extends \App\Controllers\GoBaseResourceController
public function add()
{
// JJO
$session = session();
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -110,7 +108,7 @@ class Clienteplantillaprecios extends \App\Controllers\GoBaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_created_id'] = $session->id_user;
$sanitizedData['user_created_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
@ -172,8 +170,6 @@ class Clienteplantillaprecios extends \App\Controllers\GoBaseResourceController
public function edit($requestedId = null)
{
// JJO
$session = session();
if ($requestedId == null) :
return $this->redirect2listView();
@ -186,9 +182,9 @@ class Clienteplantillaprecios extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -197,7 +193,7 @@ class Clienteplantillaprecios extends \App\Controllers\GoBaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_updated_id'] = $session->id_user;
$sanitizedData['user_updated_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Clientes;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
use App\Entities\Clientes\ClientePlantillaPreciosLineasEntity;
@ -13,7 +13,7 @@ use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;
class Clienteplantillaprecioslineas extends \App\Controllers\GoBaseResourceController
class Clienteplantillaprecioslineas extends \App\Controllers\BaseResourceController
{
protected $modelName = ClientePlantillaPreciosLineasModel::class;
@ -49,9 +49,9 @@ class Clienteplantillaprecioslineas extends \App\Controllers\GoBaseResourceContr
public function update($requestedId = null){
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
if ($requestedId == null) :
return;

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Clientes;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
use App\Entities\Clientes\ClientePreciosEntity;
@ -12,7 +12,7 @@ use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;
class ClientePrecios extends \App\Controllers\GoBaseResourceController
class ClientePrecios extends \App\Controllers\BaseResourceController
{
protected $modelName = ClientePreciosModel::class;
@ -47,9 +47,9 @@ class ClientePrecios extends \App\Controllers\GoBaseResourceController
public function update($requestedId = null)
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
if ($requestedId == null) :
return;

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Clientes;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Clientes\ClienteUsuariosModel;
use App\Models\Collection;
@ -15,7 +15,7 @@ use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;
class Clienteusuarios extends \App\Controllers\GoBaseResourceController
class Clienteusuarios extends \App\Controllers\BaseResourceController
{
protected $modelName = ClienteUsuariosModel::class;

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Compras;
use stdClass;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -9,7 +9,7 @@ use App\Entities\Compras\ProveedorEntity;
use App\Models\Compras\ProveedorModel;
class Proveedores extends \App\Controllers\GoBaseResourceController {
class Proveedores extends \App\Controllers\BaseResourceController {
protected $modelName = ProveedorModel::class;
protected $format = 'json';
@ -69,9 +69,9 @@ class Proveedores extends \App\Controllers\GoBaseResourceController {
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -157,9 +157,9 @@ class Proveedores extends \App\Controllers\GoBaseResourceController {
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Compras;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -9,7 +9,7 @@ use App\Entities\Compras\ProveedorTipoEntity;
use App\Models\Compras\ProveedorTipoModel;
class ProveedoresTipos extends \App\Controllers\GoBaseResourceController {
class ProveedoresTipos extends \App\Controllers\BaseResourceController {
protected $modelName = ProveedorTipoModel::class;
protected $format = 'json';
@ -21,7 +21,7 @@ class ProveedoresTipos extends \App\Controllers\GoBaseResourceController {
protected static $controllerSlug = 'proveedorestipos';
protected static $viewPath = 'themes/backend/vuexy/form/compras/proveedores/';
protected static $viewPath = 'themes/backend/vuexy/form/compras/proveedores/';
protected $indexRoute = 'proveedorTipoList';
@ -54,9 +54,9 @@ class ProveedoresTipos extends \App\Controllers\GoBaseResourceController {
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -128,9 +128,9 @@ class ProveedoresTipos extends \App\Controllers\GoBaseResourceController {
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -1,25 +0,0 @@
<?php
namespace App\Controllers\Configuracion;
use App\Controllers\BaseController;
class Calendario extends BaseController
{
function __construct()
{
}
public function index()
{
echo 'Calendario';
}
public function edit()
{
}
}

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -11,7 +11,7 @@ use App\Models\Configuracion\PaisModel;
use App\Models\Configuracion\ComunidadAutonomaModel;
class Comunidadesautonomas extends \App\Controllers\GoBaseResourceController
class Comunidadesautonomas extends \App\Controllers\BaseResourceController
{
protected $modelName = ComunidadAutonomaModel::class;
@ -58,9 +58,9 @@ class Comunidadesautonomas extends \App\Controllers\GoBaseResourceController
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -132,9 +132,9 @@ class Comunidadesautonomas extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -9,7 +9,7 @@ use App\Entities\Configuracion\FormaPagoEntity;
use App\Models\Configuracion\FormaPagoModel;
class Formaspagos extends \App\Controllers\GoBaseResourceController
class Formaspagos extends \App\Controllers\BaseResourceController
{
protected $modelName = FormaPagoModel::class;
@ -56,9 +56,9 @@ class Formaspagos extends \App\Controllers\GoBaseResourceController
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -129,9 +129,9 @@ class Formaspagos extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -1,17 +1,16 @@
<?php namespace App\Controllers\Configuracion;
use App\Entities\Usuarios\UserGroupEntity;
use App\Controllers\GoBaseResourceController;
use App\Models\Usuarios\UserGroupModel;
use App\Models\Usuarios\GroupUserModel;
use App\Models\Usuarios\GroupModel;
use App\Models\Usuarios\GroupsUsersModel;
use App\Models\Usuarios\PermisosModel;
class Group extends \App\Controllers\GoBaseController
{
use \CodeIgniter\API\ResponseTrait;
protected static $primaryModelName = 'App\Models\Usuarios\UserGroupModel';
protected $modelName = UserGroupModel::class;
protected static $primaryModelName = 'App\Models\Usuarios\GroupModel';
protected $modelName = GroupModel::class;
protected static $singularObjectNameCc = 'userGroup';
protected static $singularObjectName = 'Group';
@ -22,13 +21,16 @@ class Group extends \App\Controllers\GoBaseController
protected $indexRoute = 'userGroupList';
private $group_user_model;
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Group.moduleTitle');
self::$viewPath = getenv('theme.path') . 'form/group/';
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => "Home", 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_permission_group"), 'route' => site_url("configuracion/group"), 'active' => true]
];
parent::initController($request, $response, $logger);
}
@ -38,8 +40,7 @@ class Group extends \App\Controllers\GoBaseController
$this->viewData['usingClientSideDataTable'] = true;
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Groups.group')]);
// IMN
$this->group_user_model = new GroupUserModel();
$this->viewData['model'] = $this->group_user_model;
$this->viewData['model'] = $this->model;
parent::index();
}
@ -47,54 +48,37 @@ class Group extends \App\Controllers\GoBaseController
public function add()
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
if ($this->request->getPost()) :
$postData = $this->request->getPost();
$temp_data['id'] = $groupEntity->id;
$temp_data['title'] = $postData['title'];
$temp_data['description'] = $postData['description'];
$title = $postData['title'];
$dashboard = $postData['dashboard'];
// Clear not rules fields
unset($postData['safekat_token']);
unset($postData['id']);
unset($postData['title']);
unset($postData['dashboard']);
unset($postData['id_group']);
unset($postData['description']);
unset($postData['save']);
unset($postData['selectAll']);
$controller = null;
$rules_access = null;
$rules_access = [];
foreach ($postData as $key => $value) {
$exp = explode('_', $key);
$controller[] = $exp[0];
}
if ($controller != null) {
foreach (array_unique($controller) as $item) {
$rules_access[$item] = [];
foreach ($postData as $key => $value) {
$exp = explode('_', $key);
if ($exp[0] == $item) {
array_push($rules_access[$item], str_replace($exp[0] . '_', '', $key));
}
}
if (!isset($rules_access[$exp[0]])) {
$rules_access[$exp[0]] = [];
}
array_push($rules_access[$exp[0]], str_replace($exp[0] . '_', '', $key));
}
$temp_data['rules'] = json_encode($rules_access ?? '{}');
$temp_data['token'] = md5(uniqid(rand(), true));;
$temp_data['title'] = $title;
$temp_data['dashboard'] = $dashboard;
$sanitizedData = $this->sanitized($temp_data, $nullIfEmpty);
$sanitizedData = $this->sanitized($temp_data, true);
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($successfulResult = $this->canValidate()) :
if ($this->canValidate()) :
try {
@ -130,13 +114,10 @@ class Group extends \App\Controllers\GoBaseController
endif; // ($requestMethod === 'post')
$this->viewData['group'] = isset($sanitizedData) ? new UserGroupModel($sanitizedData) : new UserGroupModel();
$this->viewData['group'] = isset($sanitizedData) ? new GroupModel($sanitizedData) : new GroupModel();
$this->viewData['permisos'] = (new PermisosModel())->find();
$this->viewData['formAction'] = route_to('createGroup');
$this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Group.moduleTitle') . ' ' . lang('Basic.global.addNewSuffix');
return $this->displayForm(__METHOD__);
}
@ -145,7 +126,6 @@ class Group extends \App\Controllers\GoBaseController
{
helper('general');
$session = session();
if ($requestedId == null) :
return $this->redirect2listView();
@ -158,56 +138,37 @@ class Group extends \App\Controllers\GoBaseController
return $this->redirect2listView('errorMessage', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
if ($this->request->getPost()) :
$postData = $this->request->getPost();
$id_group = $groupEntity->id_group;
$token = $groupEntity->token;
$title = $postData['title'];
$dashboard = $postData['dashboard'];
$temp_data['id'] = $groupEntity->id;
$temp_data['title'] = $postData['title'];
$temp_data['description'] = $postData['description'];
unset($postData['id_group']);
// Clear not rules fields
unset($postData['safekat_token']);
unset($postData['id']);
unset($postData['title']);
unset($postData['dashboard']);
$controller = null;
$rules_access = null;
unset($postData['description']);
unset($postData['save']);
unset($postData['selectAll']);
$rules_access = [];
foreach ($postData as $key => $value) {
$exp = explode('_', $key);
$controller[] = $exp[0];
}
if ($controller != null) {
foreach (array_unique($controller) as $item) {
$rules_access[$item] = [];
foreach ($postData as $key => $value) {
$exp = explode('_', $key);
if ($exp[0] == $item) {
array_push($rules_access[$item], str_replace($exp[0] . '_', '', $key));
}
}
if (!isset($rules_access[$exp[0]])) {
$rules_access[$exp[0]] = [];
}
array_push($rules_access[$exp[0]], str_replace($exp[0] . '_', '', $key));
}
$temp_data['id_group'] = $id_group;
$temp_data['rules'] = json_encode($rules_access ?? '{}');
$temp_data['token'] = $token;
$temp_data['title'] = $title;
$temp_data['dashboard'] = $dashboard;
$sanitizedData = $this->sanitized($temp_data, $nullIfEmpty);
$sanitizedData = $this->sanitized($temp_data, true);
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($successfulResult = $this->canValidate()) :
if ($this->canValidate()) :
try {
@ -226,13 +187,11 @@ class Group extends \App\Controllers\GoBaseController
$thenRedirect = false;
endif;
if ($noException && $successfulResult) :
$id = $groupEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
if ($session->get('group') == $this->request->getPost('token')) {
$session->set('rules', $temp_data['rules']);
}
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('successMessage', $message);
@ -247,12 +206,9 @@ class Group extends \App\Controllers\GoBaseController
endif; // ($requestMethod === 'post')
$this->viewData['group'] = $groupEntity;
$this->viewData['permisos'] = (new PermisosModel())->find();
$this->viewData['formAction'] = route_to('updateGroup', $id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Group.userGroup') . ' ' . lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id);
} // end function edit(...)

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -9,7 +9,7 @@ use App\Entities\Configuracion\Imposicion;
use App\Models\Configuracion\ImposicionModel;
class Imposiciones extends \App\Controllers\GoBaseResourceController
class Imposiciones extends \App\Controllers\BaseResourceController
{
protected $modelName = ImposicionModel::class;
@ -56,9 +56,9 @@ class Imposiciones extends \App\Controllers\GoBaseResourceController
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -130,9 +130,9 @@ class Imposiciones extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -9,7 +9,7 @@ use App\Entities\Configuracion\Maquina;
use App\Models\Configuracion\MaquinaModel;
class Maquinas extends \App\Controllers\GoBaseResourceController
class Maquinas extends \App\Controllers\BaseResourceController
{
protected $modelName = MaquinaModel::class;
@ -69,12 +69,10 @@ class Maquinas extends \App\Controllers\GoBaseResourceController
public function add()
{
// JJO
$session = session();
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -83,7 +81,7 @@ class Maquinas extends \App\Controllers\GoBaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_created_id'] = $session->id_user;
$sanitizedData['user_created_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
@ -139,8 +137,6 @@ class Maquinas extends \App\Controllers\GoBaseResourceController
public function edit($requestedId = null)
{
// JJO
$session = session();
if ($requestedId == null) :
return $this->redirect2listView();
@ -153,9 +149,9 @@ class Maquinas extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -173,7 +169,7 @@ class Maquinas extends \App\Controllers\GoBaseResourceController
}
// JJO
$sanitizedData['user_updated_id'] = $session->id_user;
$sanitizedData['user_updated_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -13,7 +13,7 @@ use
DataTables\Editor\Field;
class Maquinascalles extends \App\Controllers\GoBaseResourceController
class Maquinascalles extends \App\Controllers\BaseResourceController
{
protected static $controllerSlug = 'maquinascalles';

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -11,7 +11,7 @@ use App\Models\Configuracion\MaquinaModel;
use App\Models\Configuracion\MaquinasDefectoModel;
class Maquinasdefecto extends \App\Controllers\GoBaseResourceController
class Maquinasdefecto extends \App\Controllers\BaseResourceController
{
protected $modelName = MaquinasDefectoModel::class;
@ -63,12 +63,10 @@ class Maquinasdefecto extends \App\Controllers\GoBaseResourceController
public function add()
{
// JJO
$session = session();
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -77,7 +75,7 @@ class Maquinasdefecto extends \App\Controllers\GoBaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_created_id'] = $session->id_user;
$sanitizedData['user_created_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
@ -140,8 +138,6 @@ class Maquinasdefecto extends \App\Controllers\GoBaseResourceController
public function edit($requestedId = null)
{
// JJO
$session = session();
if ($requestedId == null) :
return $this->redirect2listView();
@ -154,9 +150,9 @@ class Maquinasdefecto extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -165,7 +161,7 @@ class Maquinasdefecto extends \App\Controllers\GoBaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_updated_id'] = $session->id_user;
$sanitizedData['user_updated_id'] = auth()->user()->id;
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -24,7 +24,7 @@ use
DataTables\Editor\Validate,
DataTables\Editor\ValidateOptions;
class Maquinaspapelesimpresion extends \App\Controllers\GoBaseResourceController {
class Maquinaspapelesimpresion extends \App\Controllers\BaseResourceController {
protected $modelName = MaquinasPapelesImpresionModel::class;

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -15,7 +15,7 @@ use
DataTables\Editor,
DataTables\Editor\Field;
class Maquinastarifasimpresion extends \App\Controllers\GoBaseResourceController
class Maquinastarifasimpresion extends \App\Controllers\BaseResourceController
{
protected $modelName = MaquinasTarifasImpresionModel::class;
@ -69,9 +69,9 @@ class Maquinastarifasimpresion extends \App\Controllers\GoBaseResourceController
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -145,9 +145,9 @@ class Maquinastarifasimpresion extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -9,7 +9,7 @@ use App\Entities\Configuracion\PaisEntity;
use App\Models\Configuracion\PaisModel;
class Paises extends \App\Controllers\GoBaseResourceController
class Paises extends \App\Controllers\BaseResourceController
{
protected $modelName = PaisModel::class;
@ -56,9 +56,9 @@ class Paises extends \App\Controllers\GoBaseResourceController
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -129,9 +129,9 @@ class Paises extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -3,7 +3,7 @@
namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -11,7 +11,7 @@ use App\Entities\Configuracion\PapelGenerico;
use App\Models\Configuracion\PapelGenericoModel;
class Papelesgenericos extends \App\Controllers\GoBaseResourceController
class Papelesgenericos extends \App\Controllers\BaseResourceController
{
protected $modelName = PapelGenericoModel::class;
@ -72,9 +72,9 @@ class Papelesgenericos extends \App\Controllers\GoBaseResourceController
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -144,9 +144,9 @@ class Papelesgenericos extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -3,7 +3,7 @@
namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
// DataTables PHP library
@ -36,7 +36,7 @@ use App\Models\Configuracion\MaquinasPapelesImpresionModel;
use App\Models\Configuracion\MaquinaModel;
class Papelesimpresion extends \App\Controllers\GoBaseResourceController
class Papelesimpresion extends \App\Controllers\BaseResourceController
{
protected $modelName = PapelImpresionModel::class;
@ -96,9 +96,9 @@ class Papelesimpresion extends \App\Controllers\GoBaseResourceController
public function add()
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = false; // !(phpversion() >= '8.1');
@ -159,8 +159,6 @@ class Papelesimpresion extends \App\Controllers\GoBaseResourceController
public function edit($requestedId = null)
{
// JJO
$session = session();
if ($requestedId == null) :
return $this->redirect2listView();
@ -173,9 +171,9 @@ class Papelesimpresion extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -184,7 +182,7 @@ class Papelesimpresion extends \App\Controllers\GoBaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_updated_id'] = $session->id_user;
$sanitizedData['user_updated_id'] = auth()->user()->id;
if ($this->request->getPost('defecto') == null) {

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -9,7 +9,7 @@ use App\Entities\Configuracion\PapelFormatoEntity;
use App\Models\Configuracion\PapelFormatoModel;
class Papelformato extends \App\Controllers\GoBaseResourceController {
class Papelformato extends \App\Controllers\BaseResourceController {
protected $modelName = PapelFormatoModel::class;
protected $format = 'json';
@ -54,9 +54,9 @@ class Papelformato extends \App\Controllers\GoBaseResourceController {
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -128,9 +128,9 @@ class Papelformato extends \App\Controllers\GoBaseResourceController {
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -19,7 +19,7 @@ use
DataTables\Editor\ValidateOptions;
class Papelimpresionmargenes extends \App\Controllers\GoBaseResourceController
class Papelimpresionmargenes extends \App\Controllers\BaseResourceController
{
protected $modelName = PapelImpresionMargenModel::class;

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -23,7 +23,7 @@ use
DataTables\Editor\ValidateOptions;
class Papelimpresiontipologias extends \App\Controllers\GoBaseResourceController {
class Papelimpresiontipologias extends \App\Controllers\BaseResourceController {
protected $modelName = PapelImpresionTipologiaModel::class;
protected $format = 'json';
@ -68,9 +68,9 @@ class Papelimpresiontipologias extends \App\Controllers\GoBaseResourceController
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -154,9 +154,9 @@ class Papelimpresiontipologias extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Configuracion;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -11,7 +11,7 @@ use App\Models\Configuracion\PaisModel;
use App\Models\Configuracion\ProvinciaModel;
class Provincias extends \App\Controllers\GoBaseResourceController
class Provincias extends \App\Controllers\BaseResourceController
{
protected $modelName = ProvinciaModel::class;
@ -58,9 +58,9 @@ class Provincias extends \App\Controllers\GoBaseResourceController
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -132,9 +132,9 @@ class Provincias extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -41,9 +41,9 @@ class Tipologias extends \App\Controllers\GoBaseController
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -113,9 +113,9 @@ class Tipologias extends \App\Controllers\GoBaseController
return $this->redirect2listView('errorMessage', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -3,11 +3,9 @@
use App\Entities\Usuarios\UserEntity;
use App\Models\Usuarios\UserGroupModel;
use App\Models\Usuarios\GroupUserModel;
use App\Models\Usuarios\UserModel;
use App\Libraries\PasswordHash;
use App\Models\Usuarios\GroupModel;
use App\Models\Usuarios\GroupsUsersModel;
use App\Models\UserModel;
class Users extends \App\Controllers\GoBaseController {
@ -18,7 +16,7 @@ class Users extends \App\Controllers\GoBaseController {
use \CodeIgniter\API\ResponseTrait;
protected static $primaryModelName = 'App\Models\Usuarios\UserModel';
protected static $primaryModelName = 'App\Models\UserModel';
protected static $singularObjectNameCc = 'user';
protected static $singularObjectName = 'User';
@ -33,8 +31,8 @@ class Users extends \App\Controllers\GoBaseController {
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) {
$this->group_model = new UserGroupModel();
$this->group_user_model = new GroupUserModel();
$this->group_model = new GroupModel();
$this->group_user_model = new GroupsUsersModel();
$this->user_model = new UserModel();
$this->viewData['pageTitle'] = lang('Users.moduleTitle');
@ -56,9 +54,9 @@ class Users extends \App\Controllers\GoBaseController {
public function add() {
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -153,9 +151,9 @@ class Users extends \App\Controllers\GoBaseController {
return $this->redirect2listView('errorMessage', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

View File

@ -1,88 +0,0 @@
<?php
namespace App\Controllers;
use App\Models\ActivityModel;
use App\Models\BackupModel;
use App\Models\CronTabModel;
use App\Models\NotificationModel;
use App\Models\SettingsModel;
use App\Models\Usuarios\UserModel;
class Cron extends BaseController
{
private $integration;
private $user_model;
private $notification_model;
private $crontab_model;
private $settings_model;
private $activity_model;
private $backup_model;
function __construct()
{
$this->integration = new Integration();
$this->user_model = new UserModel();
$this->notification_model = new NotificationModel();
$this->settings_model = new SettingsModel();
$this->crontab_model = new CronTabModel();
$this->activity_model = new ActivityModel();
$this->backup_model = new BackupModel();
}
public function index()
{
$settings = $this->settings_model->first()??[];
// Cron Notification E-mail
try {
$email_list = $this->notification_model
->select('notification.id_notification, recipient.email, notification.title, notification.body')
->join('user AS recipient','notification.user_recipient = recipient.token','left')
->where('send_email_notification',true)
->where('is_send_email',false)
->orderBy('notification.id_notification','desc')
->findAll(25);
foreach ($email_list as $item){
if($this->integration->send_email($item['email'],$item['title'],$item['body'])){
$this->notification_model->save(['id_notification' => $item['id_notification'],'is_send_email' => true]);
}
}
}catch (\Exception $e){
$this->crontab_model->save(['routine'=>'Notification Email','error'=>$e->getMessage()]);
}
// Cron Backup
if(date('Y-m-d') > date('Y-m-d',strtotime($settings['backup_latest']))){
if(date('H:i:s') >= date('H:i:s',strtotime($settings['backup_time']))){
try {
$this->settings_model->save([
'id_settings' => $settings['id_settings'],
'backup_latest' => date('Y-m-d H:i:s')
]);
$this->integration->create_backup();
}catch (\Exception $e){
$this->crontab_model->save(['routine'=>'Backup','error'=>$e->getMessage()]);
}
}
}
// Cron Log Delete
if(date('Y-m-d') >= date('Y-m-d',strtotime(date($settings['remove_log_latest']) . ' +'.$settings['remove_log_time'].' day'))){
try {
$this->settings_model->save([
'id_settings' => $settings['id_settings'],
'remove_log_latest' => date('Y-m-d H:i:s')
]);
$dateStart = date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s') . ' -5 year'));
$dateEnd = date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s') . ' -30 day'));
$this->crontab_model->where('created_at between "'.$dateStart.'" and "'.$dateEnd.'"')->delete();
$this->activity_model->where('created_at between "'.$dateStart.'" and "'.$dateEnd.'"')->delete();
$this->backup_model->where('created_at between "'.$dateStart.'" and "'.$dateEnd.'"')->delete();
}catch (\Exception $e){
$this->crontab_model->save(['routine'=>'Delete Log','error'=>$e->getMessage()]);
}
}
}
}

View File

@ -19,134 +19,7 @@ class Home extends BaseController
public function index()
{
$session = session();
echo view(getenv('theme.path').'main/defaultlayout');
/*
//echo view(getenv('theme.path').'main/header');
//echo view(getenv('theme.path').'main/menu');
//echo view(getenv('theme.path').'form/dashboard/index');
//echo view(getenv('theme.path').'main/footer');
/*switch ($session->get('dashboard')):
case 'admin':
$data['title'] = [
'module' => lang("App.dashboard_hello").' '.$name,
'page' => lang("App.dashboard_indicators"),
'icon' => ''
];
$data['breadcrumb'] = [
['title' => lang("App.menu_dashboard"), 'route' => "", 'active' => true]
];
//Cards Top
$initialDate = date('Y-m-d H:i:s', strtotime('-1 day', time()));
$finalDate = date('Y-m-d H:i:s');
$data['total_user'] = $this->user_model->countAllResults();
$data['total_new'] = $this->user_model->where('created_at between \''.$initialDate.'\' and \''.$finalDate.'\'')->countAllResults();
$data['total_enabled'] = $this->user_model->where('status',true)->countAllResults();
$data['total_disabled'] = $this->user_model->where('status',false)->countAllResults();
//Char Bar
$titles_char_bar["labels"] = explode(',',lang("App.dashboard_chart_months"));
$value_char_bar["series"] = [];
$return_char_bar_geral = $this->user_model->select("DATE_FORMAT(created_at,'%m') AS month,COUNT(DATE_FORMAT(created_at,'%m')) AS total")
->where("DATE_FORMAT(NOW(),'%Y') = DATE_FORMAT(created_at,'%Y')")
->groupBy("DATE_FORMAT(created_at,'%Y-%m')")
->findAll();
$return_char_bar_enabled = $this->user_model->select("DATE_FORMAT(created_at,'%m') AS month,COUNT(DATE_FORMAT(created_at,'%m')) AS total")
->where("DATE_FORMAT(NOW(),'%Y') = DATE_FORMAT(created_at,'%Y') AND status = true")
->groupBy("DATE_FORMAT(created_at,'%Y-%m')")
->findAll();
$return_char_bar_disabled = $this->user_model->select("DATE_FORMAT(updated_at,'%m') AS month,COUNT(DATE_FORMAT(updated_at,'%m')) AS total")
->where("DATE_FORMAT(NOW(),'%Y') = DATE_FORMAT(updated_at,'%Y') AND status = false")
->groupBy("DATE_FORMAT(updated_at,'%Y-%m')")
->findAll();
$year = [];
for ($i = 1; $i <= 12; $i++) {
$notFound = true;
foreach ($return_char_bar_geral as $item){
if($i == intval($item->month)){
array_push($year,intval($item->total));
$notFound = false;
break;
}
}
if($notFound){
array_push($year,0);
}
}
array_push($value_char_bar["series"],$year);
$year = [];
for ($i = 1; $i <= 12; $i++) {
$notFound = true;
foreach ($return_char_bar_enabled as $item){
if($i == intval($item->month)){
array_push($year,intval($item->total));
$notFound = false;
break;
}
}
if($notFound){
array_push($year,0);
}
}
array_push($value_char_bar["series"],$year);
$year = [];
for ($i = 1; $i <= 12; $i++) {
$notFound = true;
foreach ($return_char_bar_disabled as $item){
if($i == intval($item->month)){
array_push($year,intval($item->total));
$notFound = false;
break;
}
}
if($notFound){
array_push($year,0);
}
}
array_push($value_char_bar["series"],$year);
$data['data_char_bar'] = json_encode(array_merge($titles_char_bar,$value_char_bar));
$data['data_user'] = $this->user_model->select('picture,first_name,last_name,email,created_at')
->orderBy('id_user','DESC')
->findAll(15);
$data['data_activity'] = $this->activity_model
->select('auth_user.first_name,auth_user.email,auth_activity.detail,auth_activity.created_at')
->join('auth_user','auth_user.token=auth_activity.user')
->orderBy('auth_activity.id_activity','DESC')
->findAll(30);
echo view(getenv('theme.path').'main/header');
//echo view(getenv('theme.path').'form/dashboard/admin',$data);
echo view(getenv('theme.path').'main/footer');
break;
case 'user':
$data['title'] = [
'module' => lang("App.dashboard_hello").' '.$name,
'page' => lang("App.dashboard_indicators"),
'icon' => ''
];
$data['breadcrumb'] = [
['title' => lang("App.menu_dashboard"), 'route' => "", 'active' => true]
];
echo view(getenv('theme.path').'main/header');
//echo view(getenv('theme.path').'form/dashboard/user',$data);
echo view(getenv('theme.path').'main/footer');
break;
default:
echo view(getenv('theme.path').'main/header');
//echo view(getenv('theme.path').'form/dashboard/index');
echo view(getenv('theme.path').'main/footer');
endswitch;
*/
echo view(getenv('theme.path') . 'main/defaultlayout');
}

View File

@ -1,627 +0,0 @@
<?php
namespace App\Controllers;
use App\Libraries\Authenticator;
use App\Libraries\PasswordHash;
use App\Models\ActivityModel;
use App\Models\ConfirmationTokenModel;
use App\Models\NotificationModel;
use App\Models\PasswordRecoveryModel;
use App\Models\SettingsModel;
use App\Models\TemplateModel;
use App\Models\Usuarios\UserModel;
use App\Models\Usuarios\UserGroupModel;
use App\Models\Usuarios\GroupUserModel;
class login extends BaseController
{
private $user_model;
private $group_model;
private $settings_model;
private $pass_recovery_model;
private $activity_model;
private $notification_model;
private $template_model;
private $confirmation_model;
private $integration;
private $group_user_model;
function __construct()
{
$this->user_model = new UserModel();
$this->group_model = new UserGroupModel();
$this->settings_model = new SettingsModel();
$this->pass_recovery_model = new PasswordRecoveryModel();
$this->activity_model = new ActivityModel();
$this->notification_model = new NotificationModel();
$this->template_model = new TemplateModel();
$this->confirmation_model = new ConfirmationTokenModel();
$this->integration = new Integration();
// Get Settings
$loginAuthFilter = new \App\Filters\LoginAuthFilter();
$loginAuthFilter->getSettings();
$this->group_user_model = new GroupUserModel();
}
public function index()
{
$session = session();
$data['settings'] = $session->get('settings');
$header['title'] = lang("App.login_title");
echo view(getenv('theme.path').'login/header',$header);
echo view(getenv('theme.path').'form/login/index',$data);
echo view(getenv('theme.path').'login/footer');
}
public function forgot_password()
{
$session = session();
if($session->get('settings')['forgot_password']??false){
$data['settings'] = $session->get('settings');
$header['title'] = lang("App.login_title_forgot_password");
echo view(getenv('theme.path').'login/header',$header);
echo view(getenv('theme.path').'form/login/forgot_password',$data);
echo view(getenv('theme.path').'login/footer');
}else{
return redirect()->to('/login');
}
}
public function authenticate()
{
$session = session();
$settings = $session->get('settings');
if(!empty($session->get('oauth'))){
// Data obtained by oAuth
$login = $this->user_model->where('email', $session->get('oauth')->email)->first();
} else {
// Data obtained by Form
$getVar = $this->request->getvar();
$login = $this->user_model->where('email', $getVar['email']??'')->first();
// Captcha Validation
if($settings['captcha_login']??false){
if($settings['captcha_gateway'] == 'recaptcha'){
if(isset($getVar['g-recaptcha-response'])){
$captcha = $getVar['g-recaptcha-response'];
$url = 'https://www.google.com/recaptcha/api/siteverify?secret='.urlencode($settings['captcha_secret_key']??'').'&response='.urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
if(!$responseKeys["success"]) {
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_invalid")]);
return redirect()->to('login');
}
}else{
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_not_found")]);
return redirect()->to('login');
}
}
if($settings['captcha_gateway'] == 'hcaptcha'){
if(isset($getVar['h-captcha-response'])){
$captcha = $getVar['h-captcha-response'];
$url = 'https://hcaptcha.com/siteverify?secret='.urlencode($settings['captcha_secret_key']??'').'&response='.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR'];
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
if(!$responseKeys["success"]) {
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_invalid")]);
return redirect()->to('login');
}
}else{
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_not_found")]);
return redirect()->to('login');
}
}
}
// Remember Me Validation
if($settings['remember_me']??false){
if($getVar['remember']??'' == 'on') {
$params = session_get_cookie_params();
setcookie(session_name(), $_COOKIE[session_name()], time() + 60*60*24*30, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
}
}
}
if(!empty($login))
{
// Blocked Validation
if($login->blocked!=null){
$dateBlocked = date($login->blocked);
$dateNow = date('Y-m-d H:i:s');
if($dateBlocked > $dateNow){
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_user_blocked").$settings['throttle_auth_lockour_time'].' '.lang("App.global_hours")]);
return redirect()->to('login');
}else{
$this->user_model->save([
'id_user' => $login->id_user,
'blocked' => null
]);
}
}
// Get Ip Address
$request = \Config\Services::request();
$last_ip = $request->getIPAddress();
if(empty($session->get('oauth'))){
// Check user password
$phpass = new PasswordHash(8, true);
if(!$phpass->CheckPassword($getVar['password']??'', $login->password)){
// Throttling Validation
if($settings['throttle_auth']??false){
$initialDate = date('Y-m-d H:i:s', strtotime('-12 hour', time()));
$finalDate = date('Y-m-d H:i:s');
$amount = $this->activity_model->where('user',$login->token)->where('level','throttling')->where('created_at between \''.$initialDate.'\' and \''.$finalDate.'\'')->countAllResults();
if($amount >= intval($settings['throttle_auth_max_attempts']??'')){
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_user_blocked").$settings['throttle_auth_lockour_time'].' '.lang("App.global_hours")]);
$blocked = date('Y-m-d H:i:s', strtotime('+'.$settings['throttle_auth_lockour_time'].' hour', time()));
$this->user_model->save([
'id_user' => $login->id_user,
'blocked' => $blocked
]);
return redirect()->to('login');
}else{
// Register Throttling Log
$this->integration->setLog('throttling','login-authenticate',$login->token);
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_pass_invalid_2"). ($amount+1) .lang("App.login_alert_pass_attempt"). $settings['throttle_auth_max_attempts']??0]);
return redirect()->to('login');
}
}
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_pass_invalid")]);
return redirect()->to('login');
}
// Check email confirmed
if($settings['email_confirmation']??false){
if(!$login->email_confirmed){
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.user_alert_email_confirmed")]);
return redirect()->to('login');
}
}
}
// Check user status
if(!$login->status){
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_disabled_access")]);
return redirect()->to('/login');
}
// Get access rules
#$rules = $this->group_model->where('token', $login->'group'])->first();
$groups = $this->group_user_model
->select('token_group')
->where('token_user',$login->token)->findAll();
if (sizeof($groups)>1){
$rules = $this->group_model->select('rules')->where('token',$groups[0])->first()->rules;
$rules = json_decode(html_entity_decode($rules), true);
if($rules==null){
// group doesn't exists now -> then delete from group-user
$groups = $this->group_user_model
->where('token_group',$groups[0])
->delete();
}
for ($i=1; $i<sizeof($groups); $i++){
$temp_rules = $this->group_model->select('rules')->where('token',$groups[$i])->first();
if($temp_rules==null){
// group doesn't exists now -> then delete from group-user
$groups = $this->group_user_model
->where('token_group',$groups[$i])
->delete();
}
else{
$temp_rules=$temp_rules->rules;
foreach ($rules as $key => $value){
if (array_key_exists($key, json_decode(html_entity_decode($temp_rules), true))){
$value2 = json_decode(html_entity_decode($temp_rules), true)[$key];
$rules[$key] = array_unique(array_merge($value, $value2));
}
else{
$rules[$key]= $value;
}
}
foreach (json_decode(html_entity_decode($temp_rules), true) as $key2 => $value2){
if (!array_key_exists($key2, $rules)){
$rules[$key2] = $value2;
}
}
}
}
}
else{
$rules = json_decode($this->group_model->select('rules')->where('token',$groups[0])->first()->rules);
}
// Save data in session
$session->set('id_user', $login->id_user);
//$session->set('group', $login->'group']);
$session->set('first_name', $login->first_name);
$session->set('last_name', $login->last_name);
$session->set('email', $login->email);
$session->set('token', $login->token);
// JJO
$dashboard = 'user';
foreach ($groups as $group){
if($this->group_model->select('dashboard')->where('token',$group)->first()->dashboard == 'admin')
$dashboard = 'admin';
}
$session->set('dashboard', $dashboard);
$session->set('rules', html_entity_decode(json_encode($rules)));
$session->set('picture', $login->picture);
$session->set('tfa', $login->tfa);
$session->set('tfa_secret', $login->tfa_secret);
$session->set('tfa_code', $login->tfa_code);
$session->set('lang', $login->language ?? 'en');
// Update last access
$last_access = date('Y-m-d H:i:s');
$this->user_model->set('last_access', $last_access)->set('last_ip', $last_ip)->where('id_user', $session->get('id_user'))->update();
// Register Access Log
$integration = new \App\Controllers\Integration;
$integration->setLog('information','login-authenticate');
// Check if it has two factors
if($login->tfa??false){
return redirect()->to('/login/authentication');
}else{
return redirect()->to('home');
}
}
else
{
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_user_not_found")]);
return redirect()->to('login');
}
}
public function logout()
{
// Destroy the session
$session = session();
$lang = $session->get('lang');
$session->destroy();
return redirect()->to('/lang/'.$lang);
}
public function signup()
{
$session = session();
helper('form');
$data['settings'] = $session->get('settings');
$header['title'] = lang("App.login_title_signup");
echo view(getenv('theme.path').'login/header',$header);
echo view(getenv('theme.path').'form/login/signup',$data);
echo view(getenv('theme.path').'login/footer');
}
public function authentication()
{
$session = session();
if($session->get('tfa')??false){
$header['title'] = lang("App.login_title_otp");
echo view(getenv('theme.path').'login/header',$header);
echo view(getenv('theme.path').'form/login/authentication');
echo view(getenv('theme.path').'login/footer');
}else{
return redirect()->to('/login');
}
}
public function otp()
{
$session = session();
$tfa_secret = $session->get('tfa_secret');
$tfa_code = $session->get('tfa_code');
$pin = $this->request->getVar();
$otp = "";
foreach ($pin as $key=>$value){
if(strpos($key, 'pin') !== false){
$otp .= $value;
}
}
$tfa = new Authenticator();
$backup_pass = false;
$checkResult = $tfa->verify($tfa_secret??'', $otp);
if($tfa_code??'') {
$backup_codes = explode(',' , $tfa_code??'');
if (in_array($otp, $backup_codes)) {
$backup_pass = true;
$key = array_search($otp, $backup_codes);
unset($backup_codes[$key]);
}
}
if($checkResult || $backup_pass == true) {
$session->set('tfa',false);
$session->set('tfa_secret','');
$session->set('tfa_code','');
return redirect()->to('/home');
} else {
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_code_invalid")]);
return redirect()->to('/login/authentication');
}
}
public function store()
{
$session = session();
$settings = $session->get('settings');
helper('form');
helper('text');
$rules = [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|valid_email|is_unique[auth_user.email]',
'password' => 'required|min_length[8]'
];
$rules_error = [
'first_name' => [
'required' => lang("App.login_rules_first_name_r")
],
'last_name' => [
'required' => lang("App.login_rules_last_name_r")
],
'email' => [
'required' => lang("App.login_rules_email_r"),
'is_unique' => lang("App.login_rules_email_i"),
'valid_email' => lang("App.login_rules_email_v"),
],
'password' => [
'required' => lang("App.login_rules_password_r"),
'min_length' => lang("App.login_rules_password_m")
]
];
if ($this->validate($rules,$rules_error)){
if($listPost = $this->request->getPost()) {
if($settings['captcha_register']??false){
if($settings['captcha_gateway'] == 'recaptcha'){
if(isset($listPost['g-recaptcha-response'])){
$captcha = $listPost['g-recaptcha-response'];
$url = 'https://www.google.com/recaptcha/api/siteverify?secret='.urlencode($settings['captcha_secret_key']??'').'&response='.urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
if(!$responseKeys["success"]) {
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_invalid")]);
$this->signup();
die();
}
}else{
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_not_found")]);
$this->signup();
die();
}
}
if($settings['captcha_gateway'] == 'hcaptcha'){
if(isset($listPost['h-captcha-response'])){
$captcha = $listPost['h-captcha-response'];
$url = 'https://hcaptcha.com/siteverify?secret='.urlencode($settings['captcha_secret_key']??'').'&response='.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR'];
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
if(!$responseKeys["success"]) {
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_invalid")]);
$this->signup();
die();
}
}else{
$session->setFlashdata('toast', ['error',lang("App.login_alert"),lang("App.login_alert_captcha_not_found")]);
$this->signup();
die();
}
}
}
$phpass = new PasswordHash(8, true);
$userToken = md5(uniqid(rand(), true));
$this->user_model->skipValidation(true)->save([
//'group' => $settings['default_role'],
'first_name' => $listPost['first_name'],
'last_name' => $listPost['last_name'],
'mobile' => '',
'picture' => '/assets/img/default-user.png',
'email' => $listPost['email'],
'password' => $phpass->HashPassword($listPost['password']),
'last_access' => date('Y-m-d h:i:s'),
'last_ip' => '::1',
'language' => $settings['default_language'],
'token' => $userToken,
'status' => 1,
'address' => '',
'city' => '',
'state' => '',
'country' => '',
'zip_code' => '',
]);
//Get Data Template
$templates = $this->template_model->findAll();
//Notification E-mail User Welcome
if($settings['send_email_welcome']??false){
$template = templateSelect($templates,'template_label_welcome','email');
if($template != null){
try {
$this->integration->send_email($listPost['email'],$template['subject'],$template['body'],$phpass->HashPassword(MD5($listPost['email'])));
}catch (\Exception $e){
}
}
}
//E-mail Account Confirmation
if($settings['email_confirmation']??false){
$template = templateSelect($templates,'template_label_confirmation_email','email');
if($template != null){
$token = random_string("alnum", 50);
$url = base_url().'/login/confirmation/'.$token;
$body = str_replace('[link_confirmation]',$url,$template['body']);
try {
$this->integration->send_email($listPost['email'],$template['subject'],$body,$phpass->HashPassword(MD5($listPost['email'])));
$this->confirmation_model->save([
'id_confirmation' => null,
'user' => $userToken,
'token' => $token,
'confirmed' => false,
'type' => 'email'
]);
}catch (\Exception $e){
}
}
}
//Notification New Register
if($settings['send_notification_register']??false){
$template = templateSelect($templates,'template_label_notification','email');
if($template != null){
if(!empty($settings['send_user_register']??null)){
$data = [
'id_notification' => null,
'user_sender' => $settings['send_user_register']??null,
'user_recipient' => $settings['send_user_register']??null,
'title' => $template['subject'],
'body' => $template['body'],
'is_read' => false,
'is_send_email' => false,
'send_email_notification' => $settings['send_email_register']??false,
'token' => md5(uniqid(rand(), true))
];
$this->notification_model->save($data);
}
}
}else{
$userAdm = $this->user_model->where('token',$settings['send_user_register']??null)->first();
if($settings['send_email_register']??false){
$template = templateSelect($templates,'template_label_notification','email');
if($template != null){
try {
$this->integration->send_email($userAdm['email'],$template['subject'],$template['body'],$phpass->HashPassword(MD5($listPost['email'])));
}catch (\Exception $e){
}
}
}
}
$session = session();
$session->setFlashdata('toast', ['success', lang("App.login_alert_success"), lang("App.login_alert_success_register")]);
return redirect()->to('/login');
}else{
$session->setFlashdata('toast', ['error', lang("App.login_alert"),lang("App.login_alert_parameter_invalid")]);
$this->signup();
}
}else{
$session = session();
$session->setFlashdata('error','error');
$this->signup();
}
}
public function recovery($token=null)
{
$session = session();
if(!empty($token) && $session->get('settings')['forgot_password']??false){
$pass_recovery = $this->pass_recovery_model->where('token',$token)->where('changed',false)->first();
if($pass_recovery != null){
$data['token'] = $token;
$data['user'] = $pass_recovery['user'];
$header['title'] = lang("App.login_title_recovery");
echo view(getenv('theme.path').'login/header',$header);
echo view(getenv('theme.path').'form/login/password_recovery',$data);
echo view(getenv('theme.path').'login/footer');
}else{
$session->setFlashdata('toast', ['error', lang("App.login_alert"), lang("App.login_alert_invalid_token")]);
return redirect()->to('/login');
}
}else{
$session->setFlashdata('toast', ['error', lang("App.login_alert"), lang("App.login_alert_empty_token")]);
return redirect()->to('/login');
}
}
public function recovery_store()
{
$session = session();
helper('form');
$rules = [
'password' => 'required|min_length[8]'
];
$rules_error = [
'password' => [
'required' => lang("App.login_rules_password_r"),
'min_length' => lang("App.login_rules_password_m")
]
];
if ($this->validate($rules,$rules_error)){
if($listPost = $this->request->getPost()) {
$pass_recovery = $this->pass_recovery_model->where('user',$listPost['user'])->where('token',$listPost['token'])->where('changed',false)->first();
if($pass_recovery != null){
$user = $this->user_model->select('id_user')->where('token',$listPost['user'])->first();
if($user != null){
$phpass = new PasswordHash(8, true);
$this->user_model->save([
'id_user' => $user->id_user,
'password' => $phpass->HashPassword($listPost['password'])
]);
$this->pass_recovery_model->save([
'id_pass_recovery' => $pass_recovery['id_pass_recovery'],
'changed' => true
]);
$session->setFlashdata('toast', ['success', lang("App.login_alert_success"), lang("App.login_alert_success_recovery")]);
}
}
return redirect()->to('/login');
}else{
$session->setFlashdata('toast', ['error', lang("App.login_alert"), lang("App.login_alert_parameter_invalid")]);
$this->recovery($this->request->getVar('token'));
}
}else{
$session->setFlashdata('error','error');
$this->recovery($this->request->getVar('token'));
}
}
public function confirmation($token=null)
{
$session = session();
if(!empty($token)){
$confirmation = $this->confirmation_model->where('token',$token)->where('confirmed',false)->first();
if($confirmation != null){
$user = $this->user_model->select('id_user')->where('token',$confirmation['user'])->first();
if($confirmation['type'] == 'email'){
$this->user_model->save([
'id_user'=>$user['id_user'],
'email_confirmed'=>true
]);
}
$this->confirmation_model->save([
'id_confirmation'=>$confirmation['id_confirmation'],
'confirmed'=>true
]);
$session->setFlashdata('toast', ['success', lang("App.login_alert_success"), lang("App.login_alert_success_confirmation")]);
return redirect()->to('/login');
}else{
$session->setFlashdata('toast', ['error', lang("App.login_alert"), lang("App.login_alert_invalid_token")]);
return redirect()->to('/login');
}
}else{
$session->setFlashdata('toast', ['error', lang("App.login_alert"), lang("App.login_alert_empty_token")]);
return redirect()->to('/login');
}
}
}

View File

@ -1,24 +0,0 @@
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use Throwable;
class Migrate extends Controller
{
public function index()
{
$migrate = \Config\Services::migrations();
$file = 'Database\\Migrations\\2023-04-25-161753_RemoveGroupFromUser.php';
try {
$migrate->force($file);
} catch (\Exception $e) {
echo $e->getMessage();
}
}
}

View File

@ -1,190 +0,0 @@
<?php
namespace App\Controllers;
use App\Models\CountriesModel;
use App\Models\Usuarios\UserModel;
use App\Models\NotificationModel;
class Notification extends BaseController
{
private $user_model;
private $countries_model;
private $id_user;
private $token_user;
private $notification_model;
function __construct()
{
$this->user_model = new UserModel();
$this->countries_model = new CountriesModel();
$this->id_user = session()->get('id_user');
$this->token_user = session()->get('token');
$this->notification_model = new NotificationModel();
}
public function index()
{
$data['title'] = [
'module' => lang("App.notification_title"),
'page' => lang("App.notification_subtitle"),
'icon' => 'fas fa-bell'
];
$data['breadcrumb'] = [
['title' => lang("App.menu_dashboard"), 'route' => "/home", 'active' => false],
['title' => lang("App.notification_title"), 'route' => "", 'active' => true]
];
$data['btn_add'] = [
'title' => lang("App.notification_btn_add"),
'route' => '/notification/add',
'class' => 'btn btn-lg btn-primary float-md-right',
'icon' => 'fas fa-plus'
];
echo view(getenv('theme.path').'main/header');
echo view(getenv('theme.path').'form/notification/index',$data);
echo view(getenv('theme.path').'main/footer');
}
public function add()
{
helper('form');
$data['title'] = [
'module' => lang("App.notification_add_title"),
'page' => lang("App.notification_add_subtitle"),
'icon' => 'far fa-plus-square'
];
$data['breadcrumb'] = [
['title' => lang("App.menu_dashboard"), 'route' => "/home", 'active' => false],
['title' => lang("App.notification_title"), 'route' => "/user", 'active' => false],
['title' => lang("App.notification_add_title"), 'route' => "", 'active' => true]
];
$data['btn_return'] = [
'title' => lang("App.global_come_back"),
'route' => '/notification',
'class' => 'btn btn-dark mr-1',
'icon' => 'fas fa-angle-left'
];
$data['btn_submit'] = [
'title' => lang("App.global_save"),
'route' => '',
'class' => 'btn btn-primary mr-1',
'icon' => 'fas fa-save'
];
$data['user'] = $this->user_model->where('status',true)->findAll();
echo view(getenv('theme.path').'main/header');
echo view(getenv('theme.path').'form/notification/form',$data);
echo view(getenv('theme.path').'main/footer');
}
public function store()
{
//Demo Mode
if(env('demo.mode')??false){
session()->setFlashdata('sweet', ['warning',lang("App.general_demo_mode")]);
return redirect()->to('/notification');
}
$session = session();
helper('form');
$rules = [
'title' => 'required',
'body' => 'required'
];
$rules_error = [
'title' => [
'required' => lang("App.notification_rules_title_r"),
],
'body' => [
'required' => lang("App.notification_rules_body_r"),
]
];
if ($this->validate($rules,$rules_error)){
if($listPost = $this->request->getPost()){
$listPost['send_email_notification'] = isset($listPost['send_email_notification']) && $listPost['send_email_notification'] == 'on';
if(!empty($listPost['user_recipient'])){
$user = $this->user_model->where('token',$session->get('token'))->first();
foreach (keywordEmail()??[] as $item){
$field = str_replace(['[','user_',']'],'',$item);
$listPost['title'] = str_replace('['.$item.']',$user[$field],$listPost['title']);
$listPost['body'] = str_replace('['.$item.']',$user[$field],$listPost['body']);
}
$listPost['token'] = md5(uniqid(rand(), true));
$listPost['user_sender'] = $session->get('token');
$this->notification_model->save($listPost);
}else{
$users = $this->user_model->where('status',true)->findAll();
$data = [];
foreach ($users as $user){
$title = $listPost['title'];
$template = $listPost['body'];
foreach (keywordEmail()??[] as $item){
$field = str_replace(['[','user_',']'],'',$item);
$title = str_replace('['.$item.']',$user[$field],$title);
$template = str_replace('['.$item.']',$user[$field],$template);
}
array_push($data,[
'id_notification' => null,
'user_sender' => $session->get('token'),
'user_recipient' => $user['token'],
'title' => $title,
'body' => $template,
'is_read' => false,
'is_send_email' => false,
'send_email_notification' => $listPost['send_email_notification'],
'token' => md5(uniqid(rand(), true)),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
]);
}
if(count($data)>0){
$this->notification_model->insertBatch($data);
}
}
if(empty($this->request->getPost('id_notification'))){
$session->setFlashdata('sweet', ['success',lang("App.notification_alert_add")]);
return redirect()->to('/notification');
}else{
$session->setFlashdata('sweet', ['success',lang("App.notification_alert_edit")]);
return redirect()->to('/notification');
}
}
}else{
$session->setFlashdata('error','error');
$this->add();
}
}
public function delete($token)
{
//Demo Mode
if(env('demo.mode')??false){
session()->setFlashdata('sweet', ['warning',lang("App.general_demo_mode")]);
return redirect()->to('/notification');
}
$session = session();
if(!empty($session->get('token'))){
$this->notification_model->where('token', $token)->delete();
$session->setFlashdata('sweet', ['success',lang("App.notification_alert_delete")]);
return redirect()->to('/notification');
}else{
return redirect()->to('/login');
}
}
}

View File

@ -2,7 +2,7 @@
namespace App\Controllers\Presupuestos;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Entities\Configuracion\Maquina;
use App\Models\Collection;
@ -19,7 +19,7 @@ use App\Models\Configuracion\PapelImpresionModel;
use App\Models\Configuracion\MaquinaModel;
use Exception;
class Buscador extends \App\Controllers\GoBaseResourceController
class Buscador extends \App\Controllers\BaseResourceController
{
protected $modelName = "BuscadorModel";

View File

@ -2,7 +2,7 @@
namespace App\Controllers\Presupuestos;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Entities\Configuracion\Maquina;
use App\Models\Collection;
@ -24,7 +24,7 @@ use App\Models\Configuracion\PapelImpresionModel;
use App\Models\Configuracion\MaquinaModel;
use Exception;
class Cosidotapablanda extends \App\Controllers\GoBaseResourceController
class Cosidotapablanda extends \App\Controllers\BaseResourceController
{
protected $modelName = "PresupuestoModel";
@ -83,12 +83,10 @@ class Cosidotapablanda extends \App\Controllers\GoBaseResourceController
public function add($tipo_impresion_id = null)
{
// JJO
$session = session();
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -97,7 +95,7 @@ class Cosidotapablanda extends \App\Controllers\GoBaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_created_id'] = $session->id_user;
$sanitizedData['user_created_id'] = auth()->user()->id;
if (!isset($sanitizedData['papel_formato_id']) || $sanitizedData['papel_formato_id'] == null) {
$sanitizedData['papel_formato_id'] = 0;
@ -170,8 +168,6 @@ class Cosidotapablanda extends \App\Controllers\GoBaseResourceController
public function edit($requestedId = null)
{
// JJO
$session = session();
if ($requestedId == null) :
return $this->redirect2listView();
@ -184,9 +180,9 @@ class Cosidotapablanda extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -197,7 +193,7 @@ class Cosidotapablanda extends \App\Controllers\GoBaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_updated_id'] = $session->id_user;
$sanitizedData['user_updated_id'] = auth()->user()->id;
if ($this->request->getPost('is_duplicado') == null) {
$sanitizedData['is_duplicado'] = 0;

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Presupuestos;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -10,7 +10,7 @@ use App\Models\Presupuestos\PresupuestoAcabadosModel;
class Presupuestoacabados extends \App\Controllers\GoBaseResourceController
class Presupuestoacabados extends \App\Controllers\BaseResourceController
{
protected $modelName = PresupuestoAcabadosModel::class;

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Presupuestos;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -10,7 +10,7 @@ use App\Models\Presupuestos\PresupuestoDireccionesModel;
class Presupuestodirecciones extends \App\Controllers\GoBaseResourceController
class Presupuestodirecciones extends \App\Controllers\BaseResourceController
{
protected $modelName = PresupuestoDireccionesModel::class;

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Presupuestos;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -10,7 +10,7 @@ use DataTables\Editor;
use DataTables\Editor\Field;
use DataTables\Editor\Validate;
class Presupuestoencuadernaciones extends \App\Controllers\GoBaseResourceController
class Presupuestoencuadernaciones extends \App\Controllers\BaseResourceController
{
protected $modelName = PresupuestoEncuadernacionesModel::class;

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Presupuestos;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -11,7 +11,7 @@ use App\Models\Clientes\ClienteModel;
use App\Models\Presupuestos\PresupuestoManipuladosModel;
class Presupuestomanipulados extends \App\Controllers\GoBaseResourceController
class Presupuestomanipulados extends \App\Controllers\BaseResourceController
{
protected $modelName = PresupuestoManipuladosModel::class;

View File

@ -6,7 +6,7 @@ use App\Models\Collection;
use App\Models\Presupuestos\PresupuestoPreimpresionesModel;
class Presupuestopreimpresiones extends \App\Controllers\GoBaseResourceController
class Presupuestopreimpresiones extends \App\Controllers\BaseResourceController
{
protected $modelName = PresupuestoPreimpresionesModel::class;

View File

@ -6,7 +6,7 @@ use App\Models\Collection;
use App\Models\Presupuestos\PresupuestoServiciosExtraModel;
class Presupuestoserviciosextra extends \App\Controllers\GoBaseResourceController
class Presupuestoserviciosextra extends \App\Controllers\BaseResourceController
{
protected $modelName = PresupuestoServiciosExtraModel::class;

View File

@ -3,13 +3,13 @@
namespace App\Controllers\Presupuestos;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
use App\Services\PresupuestoService;
class Presupuestotiradasalternativas extends \App\Controllers\GoBaseResourceController
class Presupuestotiradasalternativas extends \App\Controllers\BaseResourceController
{
protected $modelName = PresupuestoManipuladosModel::class;

View File

@ -1,204 +0,0 @@
<?php
namespace App\Controllers;
use App\Models\CountriesModel;
use App\Models\CronTabModel;
use App\Models\CurrencyModel;
use App\Models\SettingsModel;
use App\Models\TemplateModel;
use App\Models\ThemeModel;
use App\Models\TimezoneModel;
use App\Models\Usuarios\UserGroupModel;
use App\Models\Usuarios\UserModel;
class Settings extends BaseController
{
private $settings_model;
private $countries_model;
private $theme_model;
private $currency_model;
private $timezone_model;
private $group_model;
private $template_model;
private $user_model;
private $crontab_model;
private $integration;
function __construct()
{
$this->settings_model = new SettingsModel();
$this->countries_model = new CountriesModel();
$this->theme_model = new ThemeModel();
$this->currency_model = new CurrencyModel();
$this->timezone_model = new TimezoneModel();
$this->group_model = new UserGroupModel();
$this->template_model = new TemplateModel();
$this->user_model = new UserModel();
$this->crontab_model = new CronTabModel();
$this->integration = new Integration();
}
public function index()
{
helper('form');
$data['title'] = [
'module' => lang("App.settings_title"),
'page' => lang("App.settings_subtitle"),
'icon' => 'fas fa-sliders-h'
];
$data['breadcrumb'] = [
['title' => lang("App.menu_settings"), 'route' => site_url('settings'), 'active' => true]
];
$data['obj'] = $this->settings_model->first();
$data['countries'] = $this->countries_model->select('id_country,code,name')->where('data_lang',session()->get('lang')??'en')->findAll();
$data['theme'] = $this->theme_model->select('id_theme,type,name')->findAll();
$data['currency'] = $this->currency_model->select('id_currency,code,name')->findAll();
$data['timezone'] = $this->timezone_model->select('id_timezone,timezone,description')->findAll();
$data['group'] = $this->group_model->select('token,title')->findAll();
$db = db_connect('default');
$data['tables'] = $db->listTables();
$data['user'] = $this->user_model->select('token,first_name,email')->where('status',true)->findAll();
echo view(getenv('theme.path').'form/settings/index', $data);
}
public function store()
{
//Demo Mode
if(env('demo.mode')??false){
session()->setFlashdata('sweet', ['warning',lang("App.general_demo_mode")]);
return redirect()->to('/settings');
}
helper('form');
$session = session();
if($listPost = $this->request->getPost()){
$listPost['id_settings'] = 1;
$listPost['captcha_register'] = isset($listPost['captcha_register']) && $listPost['captcha_register'] == 'on';
$listPost['captcha_login'] = isset($listPost['captcha_login']) && $listPost['captcha_login'] == 'on';
$listPost['captcha_recovery'] = isset($listPost['captcha_recovery']) && $listPost['captcha_recovery'] == 'on';
$listPost['registration'] = isset($listPost['registration']) && $listPost['registration'] == 'on';
$listPost['terms_conditions'] = isset($listPost['terms_conditions']) && $listPost['terms_conditions'] == 'on';
$listPost['email_confirmation'] = isset($listPost['email_confirmation']) && $listPost['email_confirmation'] == 'on';
$listPost['send_email_register'] = isset($listPost['send_email_register']) && $listPost['send_email_register'] == 'on';
$listPost['send_notification_register'] = isset($listPost['send_notification_register']) && $listPost['send_notification_register'] == 'on';
$listPost['send_email_welcome'] = isset($listPost['send_email_welcome']) && $listPost['send_email_welcome'] == 'on';
$listPost['remember_me'] = isset($listPost['remember_me']) && $listPost['remember_me'] == 'on';
$listPost['forgot_password'] = isset($listPost['forgot_password']) && $listPost['forgot_password'] == 'on';
$listPost['two_factor_auth'] = isset($listPost['two_factor_auth']) && $listPost['two_factor_auth'] == 'on';
$listPost['throttle_auth'] = isset($listPost['throttle_auth']) && $listPost['throttle_auth'] == 'on';
$listPost['enable_api'] = isset($listPost['enable_api']) && $listPost['enable_api'] == 'on';
$listPost['block_external_api'] = isset($listPost['block_external_api']) && $listPost['block_external_api'] == 'on';
$listPost['remove_log'] = isset($listPost['remove_log']) && $listPost['remove_log'] == 'on';
$listPost['backup_notification_email'] = isset($listPost['backup_notification_email']) && $listPost['backup_notification_email'] == 'on';
$listPost['backup_automatic'] = isset($listPost['backup_automatic']) && $listPost['backup_automatic'] == 'on';
$listPost['backup_table'] = implode(",",$listPost['backup_table']??[]);
$this->settings_model->save($listPost);
$settings = $this->settings_model->first()??[];
$session->set('settings', $settings);
$session->set('lang', $settings['default_language'] ?? 'es');
$session->setFlashdata('sweet', ['success',lang("App.settings_alert_add")]);
return redirect()->to('/settings');
} else{
$session->setFlashdata('sweet', ['error',lang("App.settings_alert_error")]);
return redirect()->to('/settings');
}
}
public function template()
{
helper('form');
$data['title'] = [
'module' => lang("App.template_title"),
'page' => lang("App.template_subtitle"),
'icon' => 'fas fa-mail-bulk'
];
$data['breadcrumb'] = [
['title' => lang("App.menu_dashboard"), 'route' => "/home", 'active' => false],
['title' => lang("App.menu_settings"), 'route' => "/settings", 'active' => false],
['title' => lang("App.template_title"), 'route' => "", 'active' => true]
];
$data['btn_return'] = [
'title' => lang("App.global_come_back"),
'route' => '/home',
'class' => 'btn btn-dark mr-1',
'icon' => 'fas fa-angle-left'
];
$data['btn_submit'] = [
'title' => lang("App.global_save"),
'route' => '',
'class' => 'btn btn-primary mr-1',
'icon' => 'fas fa-save'
];
$data['template'] = $this->template_model->findAll();
echo view(getenv('theme.path').'main/header');
echo view(getenv('theme.path').'form/settings/template', $data);
echo view(getenv('theme.path').'main/footer');
}
public function template_store()
{
//Demo Mode
if(env('demo.mode')??false){
session()->setFlashdata('sweet', ['warning',lang("App.general_demo_mode")]);
return redirect()->to('/settings/template');
}
$session = session();
helper('form');
if($field = $this->request->getPost()){
$ids = [];
$template = [];
unset($field['files']);
foreach ($field as $key=>$value){
$id = explode('_',$key);
array_push($ids,$id[2]);
}
foreach (array_unique($ids) as $item){
$template[$item] = [];
foreach ($field as $key=>$value){
$id = explode('_',$key);
if($id[2] == $item){
if(empty($template[$item])){
$template[$item] = array_merge( $template[$item],['id_template' => intval($id[2])]);
$template[$item] = array_merge( $template[$item],['subject' => ""]);
$template[$item] = array_merge( $template[$item],['body' => ""]);
}
switch($id[1])
{
case 'email';
switch($id[0])
{
case 'title';
$template[$item] = array_merge( $template[$item],['subject' => $value]);
break;
default;
$template[$item] = array_merge( $template[$item],[$id[0] => $value]);
break;
}
break;
}
}
}
}
$this->template_model->updateBatch($template,'id_template');
$session->setFlashdata('sweet', ['success',lang("App.template_alert_add")]);
return redirect()->to('/settings/template');
} else{
$session->setFlashdata('sweet', ['error',lang("App.template_alert_error")]);
return redirect()->to('/settings/template');
}
}
}

View File

@ -0,0 +1,83 @@
<?php namespace App\Controllers\Sistema;
use App\Controllers\BaseResourceController;
use App\Entities\Sistema\ActivityEntity;
use App\Models\CollectionModel;
use App\Models\Sistema\ActivityModel;
class Actividad extends BaseResourceController
{
protected $modelName = ActivityModel::class;
protected $format = 'json';
protected static $controllerSlug = 'activity';
protected static $viewPath = 'themes/backend/vuexy/form/activity/';
protected static $indexRoute = 'activityList';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Paises.moduleTitle');
// Breadcrumbs
$this->viewData['breadcrumb'] = [
['title' => "Home", 'route' => "javascript:void(0);", 'active' => false],
['title' => lang("App.menu_activity"), 'route' => route_to('activityList'), 'active' => true]
];
parent::initController($request, $response, $logger);
}
public function index()
{
$viewData = [
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Paises.pais')]),
'activityEntity' => new ActivityEntity(),
'usingServerSideDataTable' => true,
'logs' => $this->model->getLogs()->get()->getResultArray()[0] // MEJORAR!!!
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath . static::$indexRoute, $viewData);
}
public function datatable()
{
if ($this->request->isAJAX()) {
$reqData = $this->request->getPost();
if (!isset($reqData['draw']) || !isset($reqData['columns'])) {
$errstr = 'No data available in response to this specific request.';
$response = $this->respond(CollectionModel::datatable([], 0, 0, $errstr), 400, $errstr);
return $response;
}
$start = $reqData['start'] ?? 0;
$length = $reqData['length'] ?? 5;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$order = ActivityModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
return $this->respond(CollectionModel::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),
$this->model->getResource($search)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -0,0 +1,103 @@
<?php namespace App\Controllers\Sistema;
use App\Controllers\BaseResourceController;
use App\Models\Sistema\SettingsModel;
class Ajustes extends BaseResourceController
{
protected $modelName = SettingsModel::class;
protected $format = 'json';
protected static $controllerSlug = 'settings';
protected static $viewPath = 'themes/backend/vuexy/form/settings/';
protected static string $formViewName = 'settingsForm';
protected static $singularObjectName = 'settings';
protected static $singularObjectNameCc = 'settings';
protected $indexRoute = 'settingForm';
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
$this->viewData['pageTitle'] = lang('Provincias.moduleTitle');
$this->viewData['usingSweetAlert'] = true;
parent::initController($request, $response, $logger);
}
public function settings()
{
$id = 1;
$settingsEntity = $this->model->find($id);
if (!$settingsEntity) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Provincias.provincia')), $id]);
return $this->redirect2listView('sweet-error', $message);
endif;
if ($this->request->is('post')) :
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, true);
$noException = true;
if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) :
if ($this->canValidate()) :
try {
$successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData);
} catch (\Exception $e) {
$noException = false;
$this->dealWithException($e);
}
else:
$this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Provincias.provincia'))]);
$this->session->setFlashdata('formErrors', $this->model->errors());
endif;
$settingsEntity->fill($sanitizedData);
$thenRedirect = false;
endif;
if ($noException && $successfulResult) :
$id = $settingsEntity->id ?? $id;
$message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.';
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to($this->indexRoute))->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
endif;
else:
$this->session->setFlashData('sweet-success', $message);
endif;
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['settingsEntity'] = $settingsEntity;
$this->viewData['formAction'] = route_to('settingsEdit');
$this->viewData['tables'] = db_connect()->listTables();
return $this->displayForm(__METHOD__, $id);
} // end function settings(...)
}

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\tarifas;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -9,7 +9,7 @@ use App\Entities\Tarifas\TarifaacabadoEntity;
use App\Models\Tarifas\TarifaacabadoModel;
class Tarifaacabado extends \App\Controllers\GoBaseResourceController
class Tarifaacabado extends \App\Controllers\BaseResourceController
{
protected $modelName = TarifaacabadoModel::class;
@ -22,7 +22,7 @@ class Tarifaacabado extends \App\Controllers\GoBaseResourceController
protected static $controllerSlug = 'tarifasacabado';
protected static $viewPath = 'themes/backend/vuexy/form/tarifas/acabado/';
protected static $viewPath = 'themes/backend/vuexy/form/tarifas/acabado/';
protected $indexRoute = 'tarifaAcabadoList';
@ -69,12 +69,7 @@ class Tarifaacabado extends \App\Controllers\GoBaseResourceController
public function add()
{
// JJO
$session = session();
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -83,7 +78,7 @@ class Tarifaacabado extends \App\Controllers\GoBaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_created_id'] = $session->id_user;
$sanitizedData['user_created_id'] = auth()->user()->id;
if ($this->request->getPost('mostrar_en_presupuesto') == null) {
$sanitizedData['mostrar_en_presupuesto'] = false;
@ -149,8 +144,6 @@ class Tarifaacabado extends \App\Controllers\GoBaseResourceController
public function edit($requestedId = null)
{
// JJO
$session = session();
if ($requestedId == null) :
return $this->redirect2listView();
@ -163,9 +156,7 @@ class Tarifaacabado extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -174,7 +165,7 @@ class Tarifaacabado extends \App\Controllers\GoBaseResourceController
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
// JJO
$sanitizedData['user_updated_id'] = $session->id_user;
$sanitizedData['user_updated_id'] = auth()->user()->id;
if ($this->request->getPost('mostrar_en_presupuesto') == null) {
$sanitizedData['mostrar_en_presupuesto'] = false;

View File

@ -1,7 +1,7 @@
<?php namespace App\Controllers\Tarifas;
use App\Controllers\GoBaseResourceController;
use App\Controllers\BaseResourceController;
use App\Models\Collection;
@ -24,7 +24,7 @@ use
use function PHPUnit\Framework\isEmpty;
class Tarifaacabadolineas extends \App\Controllers\GoBaseResourceController
class Tarifaacabadolineas extends \App\Controllers\BaseResourceController
{
protected $modelName = TarifaAcabadoLineaModel::class;
@ -76,9 +76,9 @@ class Tarifaacabadolineas extends \App\Controllers\GoBaseResourceController
{
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');
@ -150,9 +150,9 @@ class Tarifaacabadolineas extends \App\Controllers\GoBaseResourceController
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
if ($requestMethod === 'post') :
if ($this->request->getPost()) :
$nullIfEmpty = true; // !(phpversion() >= '8.1');

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