Compare commits

..

1 Commits

Author SHA1 Message Date
Stephen Abello
c982775c48 Add test 2026-10-19 09:01:11 +02:00
306 changed files with 940 additions and 4823 deletions

1
.gitignore vendored
View File

@@ -165,4 +165,3 @@ local.properties
# Windows
Thumbs.db
/docs/

149
AGENTS.md
View File

@@ -1,149 +0,0 @@
# AGENTS.md: iTop
Instructions for AI coding agents and AI code reviewers working on this repository.
iTop (by Combodo) is an open-source ITSM/CMDB web application: PHP backend, JS/HTML/SCSS front-end, XML datamodel.
Write all code, identifiers, comments and review comments in English.
When asked to review code, also follow `REVIEW.md`.
## Critical rules (security first)
These rules apply to every change. In code review, a violation is a P1 issue.
### Input: sanitize with an explicit filter
- Read request parameters only with `utils::ReadParam()` or `utils::ReadPostedParam()`, never from `$_GET`, `$_POST`, `$_REQUEST` or `$_COOKIE`.
- Always pass the filter explicitly as a `utils::ENUM_SANITIZATION_FILTER_*` constant, the most restrictive that fits (`INTEGER`, `CLASS`, `FIELD_NAME`, `TRANSACTION_ID`, `URL`...).
- `utils::ENUM_SANITIZATION_FILTER_RAW_DATA` requires a comment explaining why no other filter fits.
### Output: escape at consumption time, in the right context
- Sanitizing input is not escaping output. Escape where the value is rendered, never upstream in the backend, and never store escaped values.
- PHP to HTML: `utils::EscapeHtml()`. Not `htmlentities()` nor `utils::HtmlEntities()` (they escape every non-ASCII char).
- Twig: rely on auto-escaping; use `|escape('js')` in JS contexts and `|sanitize(constant('utils::ENUM_SANITIZATION_FILTER_VARIABLE_NAME'))` (or `..._ELEMENT_IDENTIFIER`) for generated identifiers. `|raw` only for trusted HTML, with a comment.
- JS to DOM: escape untrusted values with `CombodoSanitizer.EscapeHtml()` before building HTML; prefer `.text()` to `.html()` or `innerHTML`.
- User-provided rich HTML goes through `HTMLSanitizer::Sanitize()`.
### CSRF
- Never change state on a GET request.
- A form that changes state embeds a transaction id from `utils::GetNewTransactionId()`; its handler calls `utils::IsTransactionValid()` before any modification.
- Ajax calls use jQuery or `CombodoHTTP.Fetch()`, which send the `X-Combodo-Ajax` header checked by `pages/ajax.render.php`. Never use raw `fetch()` or `XMLHttpRequest`.
### Data access and permissions
- OQL: use placeholders (`WHERE name = :name`) and pass values in the `$aParams` argument of `DBObjectSearch::FromOQL()`. Never concatenate input into OQL or SQL; raw SQL values go through `CMDBSource::Quote()`.
- Every new entry point (page, ajax operation, controller route, webservice) enforces authentication (`LoginWebPage::DoLogin()` / `DoLoginEx()`) and rights (`UserRights::IsActionAllowed()`, `UserRights::IsAdministrator()`...).
- `AllowAllData()` bypasses user rights and scopes: only when strictly needed, with a comment.
### Secrets and logs
- Never log passwords, tokens, API keys, session ids or personal data. Log security events on `LogChannels::SECURITY`.
### Security configuration parameters: secure by default
- The default value of a configuration parameter is always the secure one.
- An option that weakens a protection is opt-in: a `bool` named `security.disable_<protection>`, default `false`, whose description states the risk when set to `true` (model: `security.disable_inline_documents_sandbox` in `core/config.class.inc.php`). Do not add new `security.enable_*` parameters.
### Vulnerability fixes
- The repository is public: the commit message, code comments, test names and PR description of a vulnerability fix describe the functional change without revealing that it fixes a vulnerability. No security wording (vulnerability, XSS, injection, CSRF, security, CVE...), no exploit, no affected versions. E.g. `N°1234 - Fix display of special characters in the activity panel`, not `N°1234 - Fix XSS in the activity panel` nor `N°1234 - Security hardening`.
## Project overview
- Supported PHP versions: the `require.php` constraint in `composer.json`. Never use a language feature above its minimum version.
- Branches: `develop` (next version), `support/x.y` (maintained versions).
- Layout:
- `core/`: ORM, `MetaModel`, OQL, configuration (`core/config.class.inc.php`), logs. Legacy structure, meant to be replaced by `sources/` in the long term.
- `application/`: legacy UI layer, `utils` (`application/utils.inc.php`), exceptions (`application/exceptions/`). Legacy structure, meant to be replaced by `sources/` in the long term.
- `sources/`: namespaced code (`Combodo\iTop\...`, namespace matches the folder): services, controllers, UI blocks, forms.
- `pages/`: legacy entry points (`UI.php`, `ajax.render.php`).
- `datamodels/2.x/<module>/`: modules (`module.<module>.php`, `datamodel.<module>.xml`, `dictionaries/`).
- `dictionaries/`: core translations. `templates/`: Twig. `js/`: iTop JS. `css/`: SCSS and compiled CSS.
- `tests/`: PHPUnit (`php-unit-tests/`), PHP-CS-Fixer (`php-code-style/`), PHPStan (`php-static-analysis/`).
- Never edit:
- `lib/` (Composer `vendor-dir`) and `node_modules/` (npm): third-party code. Only Composer updates `lib/composer/autoload_*.php` (see Commands).
- `env-*/`: generated by the datamodel compilation, not versioned.
- `data/`: temporary or cached files, not versioned.
## Commands
- Unit tests (needs an installed iTop instance, see `tests/php-unit-tests/README.md`): run `composer install` in `tests/php-unit-tests/`, then `tests/php-unit-tests/vendor/bin/phpunit --configuration tests/php-unit-tests/phpunit.xml.dist <path>`.
- PHP code style: run `composer install` in `tests/php-code-style/`, then `tests/php-code-style/vendor/bin/php-cs-fixer fix --config tests/php-code-style/.php-cs-fixer.dist.php <path>`.
- Static analysis: PHPStan, see `tests/php-static-analysis/README.md` (analyses `env-production`, needs a setup).
- After adding, renaming or moving a PHP class in `core/`, `application/` or `sources/`: run `composer dump-autoload --no-interaction --classmap-authoritative` at the repository root (the classmap is authoritative: an unlisted class is not found) and commit `lib/composer/autoload_classmap.php` and `lib/composer/autoload_static.php`.
- After changing SCSS: regenerate and commit the compiled `.css` versioned next to some SCSS files (`css/setup.css`, which includes `css/backoffice/`, `css/email.css`, `css/unauthenticated.css`, portal CSS...). For `css/setup.css`, run `php .make/build/commands/setupCssCompiler.php`; for the others, tell the user. The back-office theme is compiled by the setup into `env-*/`: nothing to commit.
- After changing datamodel XML: the datamodel must be recompiled by the iTop setup or toolkit. An agent cannot do it: tell the user.
## Coding conventions
### PHP
- Formatting is enforced by PHP-CS-Fixer (PSR-12, tabs): do not hand-format.
- New classes go in `sources/` (namespace `Combodo\iTop\...` matching the folder), not in `core/` or `application/`. Module-specific code stays in its module.
- Variables: mixed case with a type prefix: `$s` string, `$i` int, `$b` bool, `$a` array, `$o` object, `$f` float, no prefix for mixed types. Loop counters (`$i`, `$j`) are fine.
- Functions and methods: UpperCamelCase starting with a verb (`GetInstance()`, `ReadParam()`). Classes: UpperCamelCase.
- Array keys: snake_case, documented with PHPDoc array shapes (`array{key: type}`) or generics (`array<string, \CheckResult>`).
- New code uses strict comparison (`===`). `==` only with a comment explaining why.
- Test empty strings with `utils::IsNullOrEmptyString()`, not `empty()` (`"0"` is empty).
- Type hints in new code only (see Backward compatibility).
- PHPDoc: `@since` is mandatory on new classes and on new or changed methods and properties, e.g. `@since 3.3.0 N°1234`. If the target version is unknown, ask the user. Use `bool`, not `boolean`.
- Do not modify existing copyright headers.
- Configuration parameters: lowercase, domain prefix, underscores (`email_transport_smtp.host`), declared in `core/config.class.inc.php`.
### Backward compatibility
Extensions use public and protected classes, methods and constants, events, configuration parameters, dictionary codes and REST/webservice APIs.
- Never remove or rename them, nor change their signature or behavior. Do not add type hints to existing signatures, nor return types to fluent methods.
- To replace one, keep it, tag it `@deprecated <version> N°1234 - Use Xxx() instead` and call `DeprecatedCallsLog::NotifyDeprecatedPhpMethod()` in it.
### Performance
- No query in a loop: prefer a single OQL query (`IN`, joins).
- Use `DBObjectSet::Count()`, `CountExceeds()` or `SetLimit()` when a count or a subset is enough.
- When iterating over a set, load only the needed attributes with `DBObjectSet::OptimizeColumnLoad()`.
### Services
- A new service is a singleton: private constructor, `private static $oInstance`, `public static function GetInstance()`. Model: `sources/Service/Module/ModuleService.php`.
### Exceptions and logs
- Throw iTop exceptions (`CoreException` and its subclasses in `application/exceptions/`) rather than a bare `\Exception`.
- Log a caught exception with `ExceptionLog::LogException($oException)`, not `IssueLog::Error($oException->getMessage())`.
- Other logs: `IssueLog` with a `LogChannels::*` channel.
- Never swallow an exception: an empty `catch` needs a comment explaining why.
### JavaScript, Twig, SCSS
- JS functions: UpperCamelCase starting with a verb. Follow the escaping and Ajax rules above.
- Indentation follows `.editorconfig` (PHP, JS: tabs; SCSS, XML: 2 spaces; Twig: 4 spaces).
### Translations
- No hard-coded UI text: use `Dict::S()`, `Dict::Format()`, or `|dict_s` / `|dict_format` in Twig.
- Add new entries in English in the `en` dictionary file (`dictionaries/en.dictionary.itop.*.php` or `datamodels/2.x/<module>/dictionaries/en.dict.<module>.php`).
- Add new entries in every other language file next to the `en` one (same folder): translate them, or use the English text with a `~~` suffix if unsure. When creating a new dictionary file, create it for every language listed in `tests/php-unit-tests/integration-tests/DictionariesConsistencyTest.php` (`GetLanguagesData()`).
- When adding a new language, also declare it in `GetLanguagesData()`, otherwise `DictionariesConsistencyTest` fails.
- In other languages, a ~~ suffix marks an untranslated entry: never remove it without translating.
### Commits
- Start either with the ticket reference (`N°*`) or with one of the supported Gitmoji code (`:white_check_mark:`, `:green_heart:`, `:memo:`, `:bookmark:`), imperative present tense, first line 72 characters max, describe the functional change. More details in the body if needed.
## Dependencies and licenses
- Dependencies are versioned in the repository: Composer in `lib/`, npm in `node_modules/`. Change versions in `composer.json` / `package.json` and run Composer or npm; never edit the files directly.
- Every new dependency must have an entry in `setup/licenses/community-licenses.xml`, with a license compatible with AGPL-3.0. For Composer packages, propose to the user to run `php .make/license/updateLicenses.php` (needs bash, composer and jq) and review its diff; npm packages and other bundled assets are added by hand.
## Datamodel
- The datamodel ("DM") is compiled from the XML of the modules (`datamodels/2.x/<module>/datamodel.<module>.xml`) and of installed extensions into `env-<environment>/` (usually `env-production/`), accessed at runtime through `MetaModel`.
- Changing an existing class or attribute impacts every customer upgrade and their extensions (which alter the datamodel through XML deltas): treat it as high-impact and flag it.
## Tests
- Location: `tests/php-unit-tests/unitary-tests/`, mirroring the source path (tests for `application/foo.php` go in `unitary-tests/application/`). Cross-application data consistency: `integration-tests/`.
- Naming: `MyClass` is tested by `MyClassTest`; `MyMethod()` by `testMyMethod()`.
- Use the lightest base class that works:
1. `PHPUnit\Framework\TestCase`: pure logic.
2. `Combodo\iTop\Test\UnitTest\ItopTestCase`: iTop helpers, no datamodel.
3. `Combodo\iTop\Test\UnitTest\ItopDataTestCase`: starts the datamodel (`MetaModel`) and rolls back CRUD operations. Slow: only when the test needs the datamodel or iTop objects.
4. `Combodo\iTop\Test\UnitTest\ItopCustomDatamodelTestCase`: a non-standard datamodel.
- Process isolation (`@runInSeparateProcess`, about 800 ms per `ItopDataTestCase` test) only when needed, on the test, never globally.
- Do not leave static state behind (`ContextTag::AddContext()`, `EventService::RegisterListener()`, `Dict::Add()`): checked by `integration-tests/DetectStaticPollutionTest.php`.
- `markTestSkipped()` only for a temporarily disabled test.
- More details: `tests/php-unit-tests/README.md`.
## Glossary
- **DM / datamodel**: the application data model (classes, attributes, lifecycles, menus), compiled from XML and PHP into `env-*/`.
- **Module**: a unit of iTop code under `datamodels/2.x/<module>/`. **Extension**: a packaged set of modules installed on top of iTop.
- **OQL**: iTop's object query language.
- **Transaction id**: iTop's CSRF token.
- **Console / back-office**: the main UI for agents. **Portal**: the end-user UI (`datamodels/2.x/itop-portal-base/`).
- **N°xxxx**: Combodo internal ticket number, used in commits and `@since`.

View File

@@ -1,31 +0,0 @@
# REVIEW.md: AI code review instructions for iTop
For automated reviewers (GitHub Copilot code review, Greptile, ...). Project conventions and security rules are in `AGENTS.md`; this file says what to comment on and how.
## Output
- Write every comment in English.
- Start each comment with its priority: `[P1-Security]`, `[P2-Bug]`, `[P2-Regression]`, `[P2-Performance]`, `[P2-Architecture]` or `[P3]`.
- Report every P1 and P2 issue. Report at most 3 `[P3]` comments per PR: keep the most useful ones.
- Prefix test suggestions with `[Tests]` and put them on the code to cover; they do not count toward the P3 limit.
- No praise, no comment that only describes the change.
## Priorities
1. **P1 Security**: XSS, CSRF, OQL/SQL injection, missing authentication or rights check, sensitive data in logs, unsafe file or path handling, any breach of the "Critical rules" in `AGENTS.md`, a security option that is not secure by default or not named `security.disable_*`.
2. **P2 Bug**: logic error, wrong condition, unhandled `null`/`false` return or exception, code incompatible with the minimum PHP version, broken existing feature, leftover debug output (`var_dump()`, `print_r()`, `console.log()`).
3. **P2 Regression**: breach of the "Backward compatibility" rules in `AGENTS.md`; change to an existing datamodel class or attribute.
4. **P2 Performance**: breach of the "Performance" rules in `AGENTS.md`, repeated expensive calls.
5. **P2 Architecture**: logic in the wrong layer, a new service that is not a singleton, a new core production PHP class outside of the `sources/` folder (excluding test classes and module-specific code), a new PHP class in `core/`, `application/` or `sources/` without the updated `lib/composer/autoload_classmap.php`, a new dependency missing from `setup/licenses/community-licenses.xml`, SCSS changed without its versioned compiled CSS.
6. **P3 Other**: unclear names (variables, functions, classes), deviations from `AGENTS.md` conventions, typos and grammar in identifiers, comments and dictionary entries, UI labels that could be clearer or more consistent with existing ones, duplicated logic or re-implementation of an existing helper (`utils`, `MetaModel`...), dead or commented-out code, function too long or too nested to read.
## Tests
- When the PR changes behavior, propose the missing test cases: what to assert, in which file of `tests/php-unit-tests/unitary-tests/`.
- Check that the base class is the lightest that works (`ItopDataTestCase` only if the test needs the datamodel). Flag unjustified process isolation and static state left behind.
## Do not comment on
- Formatting: indentation, spacing, line breaks, brace placement. PHP-CS-Fixer and `.editorconfig` handle it.
- Third-party code in `lib/` and `node_modules/`, and generated code in `env-*/`. Only check whether `lib/composer/autoload_*.php` should have changed.
- Code the PR does not touch, unless the change breaks it or it needs to be adjusted accordingly.
## Vulnerabilities
- A vulnerability introduced by the PR is always a `[P1-Security]` comment: explain the risk and how to fix it.
- This repository is public. If the PR seems to fix an existing vulnerability, review it as an ordinary change: never call it a security fix, never describe the vulnerability, how to exploit it, or the affected versions, in comments or in the PR overview. If the fix looks incomplete, describe only the missing check in neutral technical terms (for example "this value is not escaped here").

View File

@@ -1202,6 +1202,7 @@ class DesignerComboField extends DesignerFormField
{
$sId = $this->oForm->GetFieldId($this->sCode);
$sName = $this->oForm->GetFieldName($this->sCode);
$sChecked = $this->defaultValue ? 'checked' : '';
$sMandatory = $this->bMandatory ? 'true' : 'false';
$sReadOnly = $this->IsReadOnly() ? 'disabled="disabled"' : '';
if ($this->IsSorted()) {
@@ -1244,7 +1245,8 @@ class DesignerComboField extends DesignerFormField
} else {
$sSelected = ($sKey == $this->defaultValue) ? 'selected' : '';
}
$sHtmlValue = $this->PrepareValueForRendering($sDisplayValue);
// Quick and dirty: display the menu parents as a tree
$sHtmlValue = str_replace(' ', '&nbsp;', $sDisplayValue);
$sHtml .= "<option value=\"".utils::EscapeHtml($sKey)."\" $sSelected>$sHtmlValue</option>";
}
$sHtml .= "</select></span>";
@@ -1261,14 +1263,6 @@ EOF
}
protected function PrepareValueForRendering($sValue = null): ?string
{
if (is_null($sValue)) {
$sValue = $this->defaultValue;
}
return $sValue;
}
public function ReadParam(&$aValues)
{
parent::ReadParam($aValues);

View File

@@ -35,6 +35,8 @@ class LoginDefaultBefore extends AbstractLoginFSMExtension
if ($index !== false) {
// Force login mode
Session::Set('login_mode', $sProposedLoginMode);
} else {
Session::Unset('login_mode');
}
return LoginWebPage::LOGIN_FSM_CONTINUE;
}

View File

@@ -35,14 +35,10 @@ class WizardHelper
public function __construct()
{
}
/**
* Constructs the PHP target object from the parameters sent to the web page by the wizard
*
* @param boolean $bReadUploadedFiles True to also read any uploaded file (for blob/document fields)
*
* @return object
* @throws CoreException
*/
public function GetTargetObject($bReadUploadedFiles = false)
{
@@ -61,14 +57,7 @@ class WizardHelper
// assumes this is handled as an array of objects
// thus encoded in json like: [ { name:'link1', 'id': 123}, { name:'link2', 'id': 124}...]
if (!is_array($value)) {
try {
$aData = json_decode($value, associative: true, flags: JSON_THROW_ON_ERROR); // true means decode as a hash array (not an object)
} catch (JsonException $e) {
throw new CoreException('WizardHelper GetTargetObject: invalid data for linked set attribute '.$sAttCode.' of class '.$this->m_aData['m_sClass'], [
'att_code' => $sAttCode,
'linked_class' => $this->m_aData['m_sClass'],
], 'Invalid JSON data', $e);
}
$aData = json_decode($value, true); // true means decode as a hash array (not an object)
} else {
$aData = $value;
}
@@ -77,6 +66,9 @@ class WizardHelper
$aFields = $this->GetLinkedWizardStructure($oAttDef);
$sLinkedClass = $oAttDef->GetLinkedClass();
$aLinkedObjectsArray = [];
if (!is_array($aData)) {
echo("aData: '$aData' (value: '$value')\n");
}
foreach ($aData as $aLinkedObject) {
$oLinkedObj = MetaModel::NewObject($sLinkedClass);
foreach ($aFields as $sLinkedAttCode) {

View File

@@ -703,14 +703,14 @@ class ActionEmail extends ActionNotification
$aMessageContent['cc'] = $this->FindRecipients('cc', $aContextArgs);
$aMessageContent['bcc'] = $this->FindRecipients('bcc', $aContextArgs);
$aMessageContent['from'] = MetaModel::ApplyParams($this->Get('from'), $aContextArgs, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
$aMessageContent['from_label'] = MetaModel::ApplyParams($this->Get('from_label'), $aContextArgs, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
$aMessageContent['reply_to'] = MetaModel::ApplyParams($this->Get('reply_to'), $aContextArgs, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
$aMessageContent['reply_to_label'] = MetaModel::ApplyParams($this->Get('reply_to_label'), $aContextArgs, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
$aMessageContent['from'] = MetaModel::ApplyParams($this->Get('from'), $aContextArgs);
$aMessageContent['from_label'] = MetaModel::ApplyParams($this->Get('from_label'), $aContextArgs);
$aMessageContent['reply_to'] = MetaModel::ApplyParams($this->Get('reply_to'), $aContextArgs);
$aMessageContent['reply_to_label'] = MetaModel::ApplyParams($this->Get('reply_to_label'), $aContextArgs);
$aMessageContent['subject'] = MetaModel::ApplyParams($this->Get('subject'), $aContextArgs, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
$sBody = MetaModel::ApplyParams($this->Get('body'), $aContextArgs, MetaModel::APPLY_PARAMS_SANITIZE_HTML);
$aMessageContent['body'] = $this->BuildMessageBody(false, $sBody);
$aMessageContent['subject'] = MetaModel::ApplyParams($this->Get('subject'), $aContextArgs);
$sBody = $this->BuildMessageBody(false);
$aMessageContent['body'] = MetaModel::ApplyParams($sBody, $aContextArgs);
$oObj = $aContextArgs['this->object()'];
$aMessageContent['message_id'] = $this->GenerateIdentifierForHeaders($oObj, static::ENUM_HEADER_NAME_MESSAGE_ID);
@@ -831,16 +831,14 @@ class ActionEmail extends ActionNotification
* Compose the body of the message from the 'body' attribute and the HTML template (if any)
* @since 3.1.0 N°4849
* @param bool $bHighlightPlaceholders If true add some extra HTML around placeholders to highlight them
* @param string|null $sBody The body of the message to be wrapped in the HTML template (if any). If null, the 'body' attribute will be used. @since 3.2.4 N°9436
* @return string
*/
protected function BuildMessageBody(bool $bHighlightPlaceholders = false, ?string $sBody = null): string
protected function BuildMessageBody(bool $bHighlightPlaceholders = false): string
{
$sBody = $sBody ?? $this->Get('body');
// Wrap content with a specific class in order to apply styles of HTML fields through the emogrifier (see `css/email.scss`)
$sBody = <<<HTML
<div class="email-is-html-content">
{$sBody}
{$this->Get('body')}
</div>
HTML;

View File

@@ -51,9 +51,6 @@ define('ACCESS_READONLY', 0);
require_once('attributedef.class.inc.php'); // For the defines
require_once('simplecrypt.class.inc.php');
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore;
use Combodo\iTop\Core\Config\Sensitive\SensitiveParameters;
// was utf8 but it only supports BMP chars (https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html)
// so we switched to utf8mb4 in iTop 2.5, adding dependency to MySQL 5.5.3
// The config params db_character_set and db_collation were introduced as a temporary workaround and removed in iTop 2.5
@@ -108,16 +105,6 @@ class Config
//for each conf entry, whether the non interpreted value can be kept in case is is written back to the disk.
private $m_aCanOverrideSettings;
/** @var \Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore|null store bound to this config (N°10293) */
private ?SensitiveConfigStore $oSensitiveStore = null;
/** @var bool whether the bound store exists (opt-in) */
private bool $bSensitiveStoreActive = false;
private ?SensitiveParameters $oSensitiveParameters = null;
/** @var bool write guard on sensitive keys (disabled while loading the file) */
private bool $bSensitiveGuardEnabled = false;
/** @var string[] sensitive keys found in the config file and ignored */
private array $aShadowedSensitiveKeys = [];
/**
* New way to store the settings !
*
@@ -246,7 +233,6 @@ class Config
],
'db_pwd' => [
'type' => 'string',
'sensitive' => true,
'default' => null,
'value' => '',
'source_of_value' => '',
@@ -673,7 +659,6 @@ class Config
'email_transport_smtp.password' => [
'type' => 'string',
'description' => 'Authentication password (optional)',
'sensitive' => true,
'default' => "",
'value' => "",
'source_of_value' => '',
@@ -1762,14 +1747,6 @@ class Config
'source_of_value' => '',
'show_in_conf_sample' => false,
],
'security.disable_mandatory_authentication_for_inline_images' => [
'type' => 'bool',
'description' => 'If true then image access does not require user authentication, provided the image\'s secret is valid. Note that setting this to true gives a less secure access to inline images!',
'default' => false,
'value' => false,
'source_of_value' => '',
'show_in_conf_sample' => false,
],
'security.disable_joined_classes_filter' => [
'type' => 'bool',
'description' => 'If true, scope filters aren\'t applied to joined classes or union classes not directly listed in the SELECT clause.',
@@ -1905,14 +1882,24 @@ class Config
$sType = $this->m_aSettings[$sPropCode]['type'];
$value = $this->oConfigPlaceholdersResolver->Resolve($value);
$value = static::CastSettingValue($sPropCode, $sType, $value);
if ($this->IsSensitiveGuarded($sPropCode)) {
// N°10293: no-op when unchanged (setup replays the same values), refused otherwise
if ($value !== static::CastSettingValue($sPropCode, $sType, $this->GetSensitiveEffectiveValue($sPropCode))) {
throw new ConfigException('This parameter is managed in the sensitive configuration file and cannot be modified here', ['key' => $sPropCode]);
}
return;
switch ($sType) {
case 'bool':
$value = (bool)$value;
break;
case 'string':
$value = (string)$value;
break;
case 'integer':
$value = (int)$value;
break;
case 'float':
$value = (float)$value;
break;
case 'array':
break;
default:
throw new CoreException('Unknown type for setting', ['property' => $sPropCode, 'type' => $sType]);
}
if ($this->m_aSettings[$sPropCode]['value'] == $value) {
@@ -1925,27 +1912,6 @@ class Config
$this->m_aCanOverrideSettings[$sPropCode] = $bCanOverride;
}
/**
* @throws \CoreException
*/
protected static function CastSettingValue(string $sPropCode, string $sType, $value)
{
switch ($sType) {
case 'bool':
return (bool)$value;
case 'string':
return (string)$value;
case 'integer':
return (int)$value;
case 'float':
return (float)$value;
case 'array':
return $value;
default:
throw new CoreException('Unknown type for setting', ['property' => $sPropCode, 'type' => $sType]);
}
}
/**
* @param string $sPropCode
*
@@ -2068,7 +2034,7 @@ class Config
* @throws \ConfigException
* @throws \CoreException
*/
public function __construct($sConfigFile = null, $bLoadConfig = true, ?SensitiveConfigStore $oSensitiveStore = null)
public function __construct($sConfigFile = null, $bLoadConfig = true)
{
$this->oConfigPlaceholdersResolver = new ConfigPlaceholdersResolver();
@@ -2109,16 +2075,10 @@ class Config
$this->m_aModuleSettings = [];
$oSensitiveStore ??= $this->ResolveSensitiveStoreForFile($sConfigFile);
if ($oSensitiveStore !== null) {
$this->DoBindSensitiveConfigStore($oSensitiveStore);
}
if ($bLoadConfig) {
$this->Load($sConfigFile);
$this->Verify();
}
$this->bSensitiveGuardEnabled = true;
// Application root url: set a default value, then normalize it
/*
@@ -2226,9 +2186,6 @@ class Config
$this->m_aAddons = $MyModules['addons'];
foreach ($MySettings as $sPropCode => $rawvalue) {
if ($this->IsSensitive($sPropCode)) {
continue; // N°10293: ignored, read from the sensitive store (see ApplySensitiveStore)
}
if ($this->IsProperty($sPropCode)) {
if (is_string($rawvalue)) {
$value = trim($rawvalue);
@@ -2264,295 +2221,6 @@ class Config
$this->m_aCharsets = isset($MySettings['csv_import_charsets']) ? $MySettings['csv_import_charsets'] : [];
$this->m_iPasswordHashAlgo = isset($MySettings['password_hash_algo']) ? $MySettings['password_hash_algo'] : $this->m_iPasswordHashAlgo;
$this->m_sAppSecret = isset($MySettings['application.secret']) ? trim($MySettings['application.secret']) : $this->m_sAppSecret;
if ($this->bSensitiveStoreActive) {
$this->ApplySensitiveStore($MySettings, $MyModuleSettings ?? []);
}
}
/**
* N°10293 strict mode: a sensitive parameter is always read from the sensitive store, never from the config file.
* Values of the config file for those parameters are dropped (and reported as "shadowed").
*
* @throws \ConfigException
* @throws \CoreException
*/
private function ApplySensitiveStore(array $aFileSettings, array $aFileModuleSettings): void
{
$aShadowed = [];
foreach ($this->oSensitiveParameters->GetEffective() as $sId) {
$aKind = $this->GetSensitiveIdKind($sId);
switch ($aKind[0]) {
case 'core':
if (array_key_exists($sId, $aFileSettings)) {
$aShadowed[] = $sId;
}
$this->m_aSettings[$sId]['value'] = static::CastSettingValue($sId, $this->m_aSettings[$sId]['type'], $this->GetSensitiveEffectiveValue($sId));
$this->m_aSettings[$sId]['source_of_value'] = $this->oSensitiveStore->Has($sId) ? $this->oSensitiveStore->GetPath() : '';
$this->m_aCanOverrideSettings[$sId] = false;
break;
case 'legacy':
if (array_key_exists($sId, $aFileSettings)) {
$aShadowed[] = $sId;
}
$this->m_sEncryptionKey = $this->GetSensitiveEffectiveValue($sId);
break;
case 'module':
[, $sModule, $sProperty] = $aKind;
if (isset($aFileModuleSettings[$sModule]) && is_array($aFileModuleSettings[$sModule]) && array_key_exists($sProperty, $aFileModuleSettings[$sModule])) {
$aShadowed[] = $sId;
}
if ($this->oSensitiveStore->Has($sId)) {
$this->m_aModuleSettings[$sModule][$sProperty] = $this->oSensitiveStore->Get($sId);
} else {
unset($this->m_aModuleSettings[$sModule][$sProperty]);
if (empty($this->m_aModuleSettings[$sModule])) {
unset($this->m_aModuleSettings[$sModule]);
}
}
break;
}
}
sort($aShadowed);
$this->aShadowedSensitiveKeys = $aShadowed;
}
/**
* @return array{0: string, 1?: string, 2?: string} ['core'] | ['legacy'] | ['module', module, property] | ['unknown']
*/
private function GetSensitiveIdKind(string $sId): array
{
if ($this->IsProperty($sId)) {
return ['core'];
}
if (in_array($sId, SensitiveParameters::LEGACY_BASELINE, true)) {
return ['legacy'];
}
$iPos = strpos($sId, '.');
if ($iPos > 0 && $iPos < strlen($sId) - 1) {
return ['module', substr($sId, 0, $iPos), substr($sId, $iPos + 1)];
}
return ['unknown'];
}
/**
* Value that a sensitive parameter must have: the store value, or the declared default when absent (D-014)
*
* @throws \ConfigException when encryption_key is absent from the store (a random default would corrupt encrypted data)
*/
private function GetSensitiveEffectiveValue(string $sId)
{
$aKind = $this->GetSensitiveIdKind($sId);
if ($this->oSensitiveStore->Has($sId)) {
$value = $this->oSensitiveStore->Get($sId);
return ($aKind[0] === 'legacy') ? (string)$value : $value;
}
switch ($aKind[0]) {
case 'core':
return $this->m_aSettings[$sId]['default'];
case 'legacy':
throw new ConfigException('Missing mandatory sensitive parameter in the sensitive configuration file', ['key' => $sId, 'file' => $this->oSensitiveStore->GetPath()]);
default:
return null;
}
}
/**
* Hook allowing to resolve the sensitive store bound to a config file
*
* @throws \ConfigException
*/
protected function ResolveSensitiveStoreForFile(?string $sConfigFile): ?SensitiveConfigStore
{
$sEnv = SensitiveConfigStore::GetEnvironmentFromConfigFile($sConfigFile);
return ($sEnv === null) ? null : SensitiveConfigStore::ForEnvironment($sEnv);
}
private function DoBindSensitiveConfigStore(SensitiveConfigStore $oStore): void
{
$this->oSensitiveStore = $oStore;
$this->bSensitiveStoreActive = $oStore->IsActive();
if ($this->bSensitiveStoreActive) {
// Validate the store right away (fail closed) and read the local overrides
$oStore->GetValues();
$this->oSensitiveParameters = SensitiveParameters::FromLocalFile($this->GetCoreSensitiveKeys(), $oStore->GetLocalFilePath());
} else {
$this->oSensitiveParameters = null;
}
}
/**
* Late binding (e.g. setup writing a config built from scratch): values are NOT applied,
* but the write guard becomes active and {@see WriteToFile()} checks the values against the store.
*
* @throws \ConfigException
* @since 3.2.4 N°10293
*/
public function BindSensitiveConfigStore(SensitiveConfigStore $oStore): void
{
$this->DoBindSensitiveConfigStore($oStore);
$this->bSensitiveGuardEnabled = true;
}
/** @since 3.2.4 N°10293 */
public function GetSensitiveConfigStore(): ?SensitiveConfigStore
{
return $this->oSensitiveStore;
}
/** @since 3.2.4 N°10293 */
public function IsSensitiveStoreActive(): bool
{
return $this->bSensitiveStoreActive;
}
/**
* @return string[] keys of $m_aSettings flagged as sensitive in the code
* @since 3.2.4 N°10293
*/
public function GetCoreSensitiveKeys(): array
{
return array_keys(array_filter($this->m_aSettings, fn ($aInfo) => !empty($aInfo['sensitive'])));
}
/**
* @param string $sId core key, legacy key or "<module>.<property>"
*
* @return bool true if the store is active and the parameter belongs to the effective sensitive set
* @since 3.2.4 N°10293
*/
public function IsSensitive(string $sId): bool
{
return $this->bSensitiveStoreActive && $this->oSensitiveParameters->IsSensitive($sId);
}
/**
* @return string[] effective sensitive set (names only), empty when the store is inactive
* @since 3.2.4 N°10293
*/
public function GetSensitiveKeys(): array
{
return $this->bSensitiveStoreActive ? $this->oSensitiveParameters->GetEffective() : [];
}
/** @since 3.2.4 N°10293 */
public function GetSensitiveParameters(): ?SensitiveParameters
{
return $this->oSensitiveParameters;
}
/**
* @return string[] sensitive keys present in the loaded config file (their values were ignored)
* @since 3.2.4 N°10293
*/
public function GetShadowedSensitiveKeys(): array
{
return $this->aShadowedSensitiveKeys;
}
/**
* Values to write to a new sensitive store, so that the sensitive parameters leave the config file (N°10293).
*
* Placeholders written in the config file (%env()%, %server()%) are kept unevaluated, so that no secret held by the
* environment ends up in the store. Parameters without any value are skipped (they keep their default).
*
* @param string[] $aIds sensitive identifiers (core, legacy or "<module>.<property>")
*
* @return array<string, mixed> identifier => value
* @throws \ConfigException if a value is computed by a PHP expression in the config file: it cannot be moved without evaluating it
* @since 3.2.4 N°10293
*/
public function GetSensitiveValuesForStore(array $aIds): array
{
$sConfig = ($this->m_sFile !== null && is_file($this->m_sFile)) ? file_get_contents($this->m_sFile) : null;
$oParser = new iTopConfigParser($sConfig === false ? null : $sConfig);
$aValues = [];
foreach ($aIds as $sId) {
$aKind = $this->GetSensitiveIdKind($sId);
switch ($aKind[0]) {
case 'core':
$value = $this->m_aSettings[$sId]['value'];
$aParserValue = $oParser->GetVarValue('MySettings', $sId);
if ($aParserValue['found']) {
$rawValue = static::ParseLiteralExpression($sId, $aParserValue['value']);
if (!empty($this->m_aCanOverrideSettings[$sId])) {
// Value of the config file: keep its placeholders (trimmed, as in Load())
$value = is_string($rawValue) ? trim($rawValue) : $rawValue;
}
}
break;
case 'legacy':
$aParserValue = $oParser->GetVarValue('MySettings', $sId);
if ($aParserValue['found']) {
static::ParseLiteralExpression($sId, $aParserValue['value']);
}
$value = $this->m_sEncryptionKey;
break;
case 'module':
[, $sModule, $sProperty] = $aKind;
if (!isset($this->m_aModuleSettings[$sModule]) || !array_key_exists($sProperty, $this->m_aModuleSettings[$sModule])) {
continue 2;
}
// The parser indexes module settings by property name only: checking that the expression is a literal is enough
$aParserValue = $oParser->GetVarValue('MyModuleSettings', $sProperty);
if ($aParserValue['found']) {
static::ParseLiteralExpression($sId, $aParserValue['value']);
}
$value = $this->m_aModuleSettings[$sModule][$sProperty];
break;
default:
continue 2;
}
if ($value !== null) {
$aValues[$sId] = $value;
}
}
return $aValues;
}
/**
* @param string $sId parameter, for the error message
* @param string $sExpression PHP expression read from the config file
*
* @return mixed value of the expression
* @throws \ConfigException if the expression is not made of literals only
*/
private static function ParseLiteralExpression(string $sId, string $sExpression)
{
$aAllowedTokens = [T_WHITESPACE, T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_DNUMBER, T_ARRAY, T_DOUBLE_ARROW, T_COMMENT];
$aAllowedChars = ['[', ']', '(', ')', ',', '-', '+', '.'];
$aTokens = token_get_all('<?php '.$sExpression.';');
array_shift($aTokens); // open tag
array_pop($aTokens); // trailing ;
foreach ($aTokens as $token) {
if (is_array($token)) {
$bAllowed = in_array($token[0], $aAllowedTokens, true)
|| ($token[0] === T_STRING && in_array(strtolower($token[1]), ['true', 'false', 'null'], true));
} else {
$bAllowed = in_array($token, $aAllowedChars, true);
}
if (!$bAllowed) {
throw new ConfigException('This parameter is computed in the configuration file and cannot be moved to the sensitive configuration file', ['key' => $sId]);
}
}
// Safe: literals only (checked above)
return eval('return '.$sExpression.';');
}
private function IsSensitiveGuarded(string $sId): bool
{
return $this->bSensitiveGuardEnabled && $this->IsSensitive($sId);
}
protected function Verify()
@@ -2607,13 +2275,6 @@ class Config
public function SetModuleSetting($sModule, $sProperty, $value)
{
$sId = $sModule.'.'.$sProperty;
if ($this->IsSensitiveGuarded($sId)) {
if (!$this->oSensitiveStore->Has($sId) || $value !== $this->oSensitiveStore->Get($sId)) {
throw new ConfigException('This parameter is managed in the sensitive configuration file and cannot be modified here', ['key' => $sId]);
}
return;
}
$this->m_aModuleSettings[$sModule][$sProperty] = $value;
}
@@ -2874,12 +2535,6 @@ class Config
public function SetEncryptionKey($sKey)
{
if ($this->IsSensitiveGuarded('encryption_key')) {
if ((string)$sKey !== $this->GetSensitiveEffectiveValue('encryption_key')) {
throw new ConfigException('This parameter is managed in the sensitive configuration file and cannot be modified here', ['key' => 'encryption_key']);
}
return;
}
$this->m_sEncryptionKey = $sKey;
}
@@ -2945,16 +2600,6 @@ class Config
$aSettings['addon_list'][] = $sFile;
}
// N°10293: never export sensitive values
foreach ($this->GetSensitiveKeys() as $sId) {
$aKind = $this->GetSensitiveIdKind($sId);
if ($aKind[0] === 'module') {
unset($aSettings['module_settings'][$aKind[1]][$aKind[2]]);
} else {
unset($aSettings[$sId]);
}
}
return $aSettings;
}
@@ -2962,11 +2607,9 @@ class Config
* Write the configuration to a file (php format) that can be reloaded later
* By default write to the same file that was specified when constructing the object
*
* @since 3.2.3-2 3.2.4 3.3.0 N°9728
*
* @param string $sFileName string Name of the file to write to (emtpy to write to the same file)
*
* @return bool True otherwise throws an Exception
* @return boolean True otherwise throws an Exception
*
* @throws \ConfigException
*/
@@ -2975,32 +2618,9 @@ class Config
if (empty($sFileName)) {
$sFileName = $this->m_sFile;
}
$sContent = $this->RenderFileContent();
$hFile = @fopen($sFileName, 'w');
if ($hFile !== false) {
fwrite($hFile, $sContent);
$bReturn = fclose($hFile);
utils::SetConfig($this);
return $bReturn;
} else {
throw new ConfigException("Could not write to configuration file", ['file' => $sFileName]);
}
}
/**
* Render the content of the configuration file (php format), without any side effect.
* Sensitive parameters (N°10293) are never part of the output.
*
* @throws \ConfigException
* @since 3.2.4 N°10293
*/
public function RenderFileContent(): string
{
$oHandle = null;
$sConfig = null;
if ($this->m_sFile !== null && is_file($this->m_sFile)) {
$oHandle = fopen($this->m_sFile, 'r');
$index = 0;
@@ -3018,154 +2638,138 @@ class Config
flock($oHandle, LOCK_UN);
}
$sOut = '';
$sOut .= "<?php\n";
$sOut .= "\n/**\n";
$sOut .= " *\n";
$sOut .= " * Configuration file, generated by the ".ITOP_APPLICATION." configuration wizard\n";
$sOut .= " *\n";
$sOut .= " * The file is used in MetaModel::LoadConfig() which does all the necessary initialization job\n";
$sOut .= " *\n";
$sOut .= " */\n";
$hFile = @fopen($sFileName, 'w');
if ($hFile !== false) {
fwrite($hFile, "<?php\n");
fwrite($hFile, "\n/**\n");
fwrite($hFile, " *\n");
fwrite($hFile, " * Configuration file, generated by the ".ITOP_APPLICATION." configuration wizard\n");
fwrite($hFile, " *\n");
fwrite(
$hFile,
" * The file is used in MetaModel::LoadConfig() which does all the necessary initialization job\n"
);
fwrite($hFile, " *\n");
fwrite($hFile, " */\n");
$aConfigSettings = $this->m_aSettings;
$aConfigSettings = $this->m_aSettings;
// Old fashioned boolean settings
$aBoolValues = [
'log_global' => $this->m_bLogGlobal,
'log_notification' => $this->m_bLogNotification,
'log_issue' => $this->m_bLogIssue,
'log_web_service' => $this->m_bLogWebService,
'secure_connection_required' => $this->m_bSecureConnectionRequired,
];
foreach ($aBoolValues as $sKey => $bValue) {
$aConfigSettings[$sKey] = [
'show_in_conf_sample' => true,
'type' => 'bool',
'value' => $bValue,
// Old fashioned boolean settings
$aBoolValues = [
'log_global' => $this->m_bLogGlobal,
'log_notification' => $this->m_bLogNotification,
'log_issue' => $this->m_bLogIssue,
'log_web_service' => $this->m_bLogWebService,
'secure_connection_required' => $this->m_bSecureConnectionRequired,
];
}
// Old fashioned integer settings
$aIntValues = [
'fast_reload_interval' => $this->m_iFastReloadInterval,
'max_display_limit' => $this->m_iMaxDisplayLimit,
'min_display_limit' => $this->m_iMinDisplayLimit,
'standard_reload_interval' => $this->m_iStandardReloadInterval,
];
foreach ($aIntValues as $sKey => $iValue) {
$aConfigSettings[$sKey] = [
'show_in_conf_sample' => true,
'type' => 'integer',
'value' => $iValue,
];
}
// Old fashioned remaining values
$aOtherValues = [
'default_language' => $this->m_sDefaultLanguage,
'allowed_login_types' => $this->m_sAllowedLoginTypes,
'encryption_key' => $this->m_sEncryptionKey,
'encryption_library' => $this->m_sEncryptionLibrary,
'csv_import_charsets' => $this->m_aCharsets,
'password_hash_algo' => $this->m_iPasswordHashAlgo,
'application.secret' => $this->m_sAppSecret,
];
foreach ($aOtherValues as $sKey => $value) {
$aConfigSettings[$sKey] = [
'show_in_conf_sample' => true,
'type' => is_string($value) ? 'string' : 'mixed',
'value' => $value,
];
}
// N°10293: sensitive values are never written to the config file
$aSensitiveModuleSettings = [];
foreach ($this->GetSensitiveKeys() as $sId) {
$aKind = $this->GetSensitiveIdKind($sId);
if ($aKind[0] === 'module') {
$aSensitiveModuleSettings[$aKind[1]][$aKind[2]] = true;
continue;
foreach ($aBoolValues as $sKey => $bValue) {
$aConfigSettings[$sKey] = [
'show_in_conf_sample' => true,
'type' => 'bool',
'value' => $bValue,
];
}
if ($aKind[0] === 'core') {
$value = $this->m_aSettings[$sId]['value'];
$expected = static::CastSettingValue($sId, $this->m_aSettings[$sId]['type'], $this->GetSensitiveEffectiveValue($sId));
$bDiverges = static::CastSettingValue($sId, $this->m_aSettings[$sId]['type'], $value) !== $expected;
} elseif ($aKind[0] === 'legacy') {
$bDiverges = (string)$this->m_sEncryptionKey !== $this->GetSensitiveEffectiveValue($sId);
// Old fashioned integer settings
$aIntValues = [
'fast_reload_interval' => $this->m_iFastReloadInterval,
'max_display_limit' => $this->m_iMaxDisplayLimit,
'min_display_limit' => $this->m_iMinDisplayLimit,
'standard_reload_interval' => $this->m_iStandardReloadInterval,
];
foreach ($aIntValues as $sKey => $iValue) {
$aConfigSettings[$sKey] = [
'show_in_conf_sample' => true,
'type' => 'integer',
'value' => $iValue,
];
}
// Old fashioned remaining values
$aOtherValues = [
'default_language' => $this->m_sDefaultLanguage,
'allowed_login_types' => $this->m_sAllowedLoginTypes,
'encryption_key' => $this->m_sEncryptionKey,
'encryption_library' => $this->m_sEncryptionLibrary,
'csv_import_charsets' => $this->m_aCharsets,
'password_hash_algo' => $this->m_iPasswordHashAlgo,
'application.secret' => $this->m_sAppSecret,
];
foreach ($aOtherValues as $sKey => $value) {
$aConfigSettings[$sKey] = [
'show_in_conf_sample' => true,
'type' => is_string($value) ? 'string' : 'mixed',
'value' => $value,
];
}
ksort($aConfigSettings);
fwrite($hFile, "\$MySettings = array(\n");
foreach ($aConfigSettings as $sPropCode => $aSettingInfo) {
// Write all values that are either always visible or present in the cloned config file
if ($aSettingInfo['show_in_conf_sample'] || (!empty($aSettingInfo['source_of_value']) && ($aSettingInfo['source_of_value'] != 'unknown'))) {
fwrite($hFile, "\n");
if (isset($aSettingInfo['description'])) {
fwrite($hFile, "\t// $sPropCode: {$aSettingInfo['description']}\n");
}
if (isset($aSettingInfo['default'])) {
$sComment = self::PrettyVarExport(null, $aSettingInfo['default'], "\t//\t\t", true);
fwrite($hFile, "\t//\tdefault: {$sComment}\n");
}
if (isset($this->m_aCanOverrideSettings[$sPropCode]) && $this->m_aCanOverrideSettings[$sPropCode]) {
$aParserValue = $this->oItopConfigParser->GetVarValue('MySettings', $sPropCode);
} else {
$aParserValue = null;
}
$sSeenAs = self::PrettyVarExport($aParserValue, $aSettingInfo['value'], "\t");
fwrite($hFile, "\t'$sPropCode' => $sSeenAs,\n");
}
}
fwrite($hFile, ");\n");
fwrite($hFile, "\n");
fwrite($hFile, "/**\n *\n * Modules specific settings\n *\n */\n");
fwrite($hFile, "\$MyModuleSettings = array(\n");
foreach ($this->m_aModuleSettings as $sModule => $aProperties) {
fwrite($hFile, "\t'$sModule' => array (\n");
foreach ($aProperties as $sProperty => $value) {
$sNiceExport = self::PrettyVarExport($this->oItopConfigParser->GetVarValue('MyModuleSettings', $sProperty), $value, "\t\t");
fwrite($hFile, "\t\t'$sProperty' => $sNiceExport,\n");
}
fwrite($hFile, "\t),\n");
}
fwrite($hFile, ");\n");
fwrite($hFile, "\n/**\n");
fwrite($hFile, " *\n");
fwrite($hFile, " * Data model modules to be loaded. Names are specified as relative paths\n");
fwrite($hFile, " *\n");
fwrite($hFile, " */\n");
fwrite($hFile, "\$MyModules = array(\n");
$aParserValue = $this->oItopConfigParser->GetVarValue('MyModules', 'addons');
if ($aParserValue['found']) {
fwrite($hFile, "\t'addons' => {$aParserValue['value']},\n");
} else {
continue;
}
if ($bDiverges) {
throw new ConfigException('This parameter is managed in the sensitive configuration file and cannot be modified here', ['key' => $sId]);
}
unset($aConfigSettings[$sId]);
}
ksort($aConfigSettings);
$sOut .= "\$MySettings = array(\n";
foreach ($aConfigSettings as $sPropCode => $aSettingInfo) {
// Write all values that are either always visible or present in the cloned config file
if ($aSettingInfo['show_in_conf_sample'] || (!empty($aSettingInfo['source_of_value']) && ($aSettingInfo['source_of_value'] != 'unknown'))) {
$sOut .= "\n";
if (isset($aSettingInfo['description'])) {
$sOut .= "\t// $sPropCode: {$aSettingInfo['description']}\n";
fwrite($hFile, "\t'addons' => array (\n");
foreach ($this->m_aAddons as $sKey => $sFile) {
fwrite($hFile, "\t\t'$sKey' => '$sFile',\n");
}
if (isset($aSettingInfo['default'])) {
$sComment = self::PrettyVarExport(null, $aSettingInfo['default'], "\t//\t\t", true);
$sOut .= "\t//\tdefault: {$sComment}\n";
}
if (isset($this->m_aCanOverrideSettings[$sPropCode]) && $this->m_aCanOverrideSettings[$sPropCode]) {
$aParserValue = $this->oItopConfigParser->GetVarValue('MySettings', $sPropCode);
} else {
$aParserValue = null;
}
$sSeenAs = self::PrettyVarExport($aParserValue, $aSettingInfo['value'], "\t");
$sOut .= "\t".var_export((string) $sPropCode, true)." => $sSeenAs,\n";
fwrite($hFile, "\t),\n");
}
}
$sOut .= ");\n";
fwrite($hFile, ");\n");
fwrite($hFile, '?'.'>'); // Avoid perturbing the syntax highlighting !
$sOut .= "\n";
$sOut .= "/**\n *\n * Modules specific settings\n *\n */\n";
$sOut .= "\$MyModuleSettings = array(\n";
foreach ($this->m_aModuleSettings as $sModule => $aProperties) {
$aProperties = array_diff_key($aProperties, $aSensitiveModuleSettings[$sModule] ?? []);
if (count($aProperties) === 0 && isset($aSensitiveModuleSettings[$sModule])) {
continue;
}
$sOut .= "\t".var_export((string) $sModule, true)." => array (\n";
foreach ($aProperties as $sProperty => $value) {
$sNiceExport = self::PrettyVarExport($this->oItopConfigParser->GetVarValue('MyModuleSettings', $sProperty), $value, "\t\t");
$sOut .= "\t\t".var_export((string) $sProperty, true)." => $sNiceExport,\n";
}
$sOut .= "\t),\n";
}
$sOut .= ");\n";
$bReturn = fclose($hFile);
$sOut .= "\n/**\n";
$sOut .= " *\n";
$sOut .= " * Data model modules to be loaded. Names are specified as relative paths\n";
$sOut .= " *\n";
$sOut .= " */\n";
$sOut .= "\$MyModules = array(\n";
$aParserValue = $this->oItopConfigParser->GetVarValue('MyModules', 'addons');
if ($aParserValue['found']) {
$sOut .= "\t'addons' => {$aParserValue['value']},\n";
utils::SetConfig($this);
return $bReturn;
} else {
$sOut .= "\t'addons' => array (\n";
foreach ($this->m_aAddons as $sKey => $sFile) {
$sOut .= "\t\t".var_export((string) $sKey, true).' => '.var_export($sFile, true).",\n";
}
$sOut .= "\t),\n";
throw new ConfigException("Could not write to configuration file", ['file' => $sFileName]);
}
$sOut .= ");\n";
$sOut .= '?'.'>'; // Avoid perturbing the syntax highlighting !
return $sOut;
}
/**
@@ -3266,8 +2870,8 @@ class Config
if (isset($aModuleInfo['settings'])) {
list($sName, $sVersion) = ModuleDiscovery::GetModuleName($sModuleId);
foreach ($aModuleInfo['settings'] as $sProperty => $value) {
if (isset($this->m_aModuleSettings[$sName][$sProperty]) || $this->IsSensitive($sName.'.'.$sProperty)) {
// Do nothing keep the original value (N°10293: sensitive values live in the sensitive store)
if (isset($this->m_aModuleSettings[$sName][$sProperty])) {
// Do nothing keep the original value
} else {
$this->SetModuleSetting($sName, $sProperty, $value);
}

View File

@@ -320,9 +320,9 @@
$bIsAsync = $this->IsAsynchronous();
[$sPreviousLanguage, $aPreviousPluginProperties] = $this->SetNotificationLanguage();
$sMessage = MetaModel::ApplyParams($this->Get('message'), $aContextArgs, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
$sTitle = MetaModel::ApplyParams($this->Get('title'), $aContextArgs, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
$sUrl = MetaModel::ApplyParams($this->Get('url'), $aContextArgs, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
$sMessage = MetaModel::ApplyParams($this->Get('message'), $aContextArgs);
$sTitle = MetaModel::ApplyParams($this->Get('title'), $aContextArgs);
$sUrl = MetaModel::ApplyParams($this->Get('url'), $aContextArgs);
$iObjectId = 0;
$sObjectClass = null;
if (array_key_exists('this->object()', $aContextArgs)) {

View File

@@ -5638,7 +5638,7 @@ abstract class DBObject implements iDisplay
$aContext['current_contact_friendlyname'] = UserRights::GetUserFriendlyName();
$aContext['current_date'] = date(AttributeDate::GetSQLFormat());
$aContext['current_time'] = date(AttributeDateTime::GetSQLTimeFormat());
$sValue = MetaModel::ApplyParams($sRawValue, $aContext, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
$sValue = MetaModel::ApplyParams($sRawValue, $aContext);
$this->Set($sAttCode, $sValue);
break;
@@ -5662,7 +5662,7 @@ abstract class DBObject implements iDisplay
$aContext['current_contact_friendlyname'] = UserRights::GetUserFriendlyName();
$aContext['current_date'] = date(AttributeDate::GetSQLFormat());
$aContext['current_time'] = date(AttributeDateTime::GetSQLTimeFormat());
$sAddendum = MetaModel::ApplyParams($sRawAddendum, $aContext, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
$sAddendum = MetaModel::ApplyParams($sRawAddendum, $aContext);
$this->Set($sAttCode, $this->Get($sAttCode).$sAddendum);
break;

View File

@@ -323,7 +323,6 @@ class HTMLDOMSanitizer extends DOMSanitizer
protected static $aAttrsWhiteList = [
'src' => '/^(http:|https:|data:)/i',
'href' => '/^(https?:|ftps?:|mailto:|\$|%24)/i',
];
/**
@@ -355,6 +354,30 @@ class HTMLDOMSanitizer extends DOMSanitizer
'white-space',
];
public function __construct($sInlineImageClassName = InlineImage::class)
{
parent::__construct($sInlineImageClassName);
// Building href validation pattern from url and email validation patterns as the patterns are not used the same way in HTML content than in standard attributes value.
// eg. "foo@bar.com" vs "mailto:foo@bar.com?subject=Title&body=Hello%20world"
if (!array_key_exists('href', self::$aAttrsWhiteList)) {
// Regular urls
$sUrlPattern = utils::GetConfig()->Get('url_validation_pattern');
// Mailto urls
$sMailtoPattern = '(mailto:('.utils::GetConfig()->Get('email_validation_pattern').')(?:\?(?:subject|body)=([a-zA-Z0-9+\$_.-]*)(?:&(?:subject|body)=([a-zA-Z0-9+\$_.-]*))?)?)';
// Notification placeholders
// eg. $this->caller_id$, $this->hyperlink()$, $this->hyperlink(portal)$, $APP_URL$, $MODULES_URL$, ...
// Note: Authorize both $xxx$ and %24xxx%24 as the latter one is encoded when used in HTML attributes (eg. a[href])
$sPlaceholderPattern = '(\$|%24)[\w-]*(->[\w]*(\([\w-]*?\))?)?(\$|%24)';
$sPattern = $sUrlPattern.'|'.$sMailtoPattern.'|'.$sPlaceholderPattern;
$sPattern = '/'.str_replace('/', '\/', $sPattern).'/i';
self::$aAttrsWhiteList['href'] = $sPattern;
}
}
public function GetTagsWhiteList()
{
return static::$aTagsWhiteList;

View File

@@ -1274,40 +1274,6 @@ class DeprecatedCallsLog extends LogAPI
static::ForwardToTriggerError($sMessage);
}
/**
* Call this helper when a method receives arguments matching a deprecated signature.
* The method itself remains supported.
*
* @param string|null $sAdditionalMessage Explain which arguments should be passed instead
*
* @since 3.2.4 3.3.1 3.4.0 N°9436
*/
public static function NotifyDeprecatedPhpMethodSignature(?string $sAdditionalMessage = null): void
{
try {
if (!static::IsLogLevelEnabled(self::LEVEL_WARNING, self::ENUM_CHANNEL_PHP_METHOD)) {
return;
}
} catch (ConfigException $oException) {
// Deprecation reporting must not interrupt the caller when logging is misconfigured.
return;
}
$aStack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
$sFunctionDesc = isset($aStack[1]['class'])
? $aStack[1]['class'].$aStack[1]['type'].$aStack[1]['function']
: $aStack[1]['function'];
$sMessage = "Calling $sFunctionDesc() with this signature is deprecated";
if ($sAdditionalMessage !== null) {
$sMessage .= ': '.$sAdditionalMessage;
}
$sMessage .= '. Caller: '.self::SummarizeCallStack(array_slice($aStack, 1));
static::Warning($sMessage, self::ENUM_CHANNEL_PHP_METHOD);
static::ForwardToTriggerError($sMessage);
}
/**
* Call this helper within deprecated methods
*

View File

@@ -117,12 +117,6 @@ define('MYSQL_ENGINE', 'innodb');
*/
abstract class MetaModel
{
/** Constants used for apply param function sanitization parameter */
/** @since 3.2.4 3.3.1 3.4.0 N°9436 */
public const APPLY_PARAMS_SANITIZE_HTML = 'sanitize_html';
/** @since 3.2.4 3.3.1 3.4.0 N°9436 */
public const APPLY_PARAMS_SANITIZE_NONE = 'sanitize_none';
///////////////////////////////////////////////////////////////////////////
//
// STATIC Members
@@ -6738,23 +6732,14 @@ abstract class MetaModel
* * foo->bar : Another static placeholder
* * foo->object() : Will be developed into a set of placeholders depending on the attribute of the given \DBObject and their corresponding transformation methods {@see \AttributeDefinition::GetForTemplate()}
* Example: foo->hyperlink(), foo->name, foo->html(name), foo->head(log), foo->head_html(log), ...
* @param string|null $sApplySanitizeMode Allowed values are one of {@see self::APPLY_PARAMS_SANITIZE_HTML}, {@see self::APPLY_PARAMS_SANITIZE_NONE}. Default is null to keep compatibility with previous versions of iTop. @since 3.2.4 N°9436
*
* @link https://www.itophub.io/wiki/page?id=latest:admin:placeholders
* @return string
*
* @throws \Exception
*/
public static function ApplyParams($sInput, $aParams, ?string $sApplySanitizeMode = null)
public static function ApplyParams($sInput, $aParams)
{
if ($sApplySanitizeMode === null) {
DeprecatedCallsLog::NotifyDeprecatedPhpMethodSignature('Pass an explicit $sApplySanitizeMode parameter.');
$sApplySanitizeMode = self::APPLY_PARAMS_SANITIZE_NONE;
}
if (in_array($sApplySanitizeMode, [self::APPLY_PARAMS_SANITIZE_HTML, self::APPLY_PARAMS_SANITIZE_NONE], true) === false) {
throw new CoreException('Invalid value for $sApplySanitizeMode parameter', ['value' => $sApplySanitizeMode]);
}
$aParams = static::AddMagicPlaceholders($aParams);
// Declare magic parameters
@@ -6842,14 +6827,7 @@ abstract class MetaModel
}
}
$sTemplate = str_replace($aSearches, $aReplacements, $sInput);
// HTML sanitization
if ($sApplySanitizeMode === self::APPLY_PARAMS_SANITIZE_HTML) {
$sTemplate = DOMSanitizer::Sanitize($sTemplate);
}
return $sTemplate;
return str_replace($aSearches, $aReplacements, $sInput);
}
/**

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2013 XXXXX
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*/
Dict::Add('EN US', 'English', 'English', [

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*/
Dict::Add('EN GB', 'British English', 'British English', [

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -18,146 +18,105 @@
* You should have received a copy of the GNU Affero General Public License
*/
use Combodo\iTop\Application\Http\HttpBadRequestException;
use Combodo\iTop\Application\Http\HttpRequest;
use Combodo\iTop\Application\Http\RequestParamDTO;
use Combodo\iTop\Application\Http\HttpResponse;
use Combodo\iTop\Application\WebPage\AjaxPage;
use Combodo\iTop\Application\WebPage\JsonPage;
use Combodo\iTop\Attachments\Enum\AttachmentAjaxErrorEnum;
require_once('../../approot.inc.php');
require_once(APPROOT.'/application/application.inc.php');
/**
* AddAttachment.
* @param \Combodo\iTop\Application\WebPage\AjaxPage $oPage
* @param int $iTransactionId
*
* @return void
* @throws ArchivedObjectException
* @throws CoreCannotSaveObjectException
* @throws CoreException
* @throws CoreUnexpectedValue
* @throws CoreWarning
* @throws MySQLException
* @throws OQLException
* @throws \ArchivedObjectException
* @throws \CoreException
* @throws \OQLException
*/
function AddAttachment(): void
function RenderAttachments(AjaxPage $oPage, $iTransactionId)
{
$oPage = new JsonPage();
$oPage->SetOutputDataOnly(true);
$sClass = utils::ReadParam('objclass', '', false, 'class');
$sId = utils::ReadParam('objkey', '');
$oObject = MetaModel::GetObject($sClass, $sId, false);
$bEditMode = utils::ReadParam('edit_mode', 0);
$aAttachmentsDeleted = utils::ReadParam('attachments_deleted', []);
// reads request add parameters
[$sClass, $sTempId] = HttpRequest::HandleRequestParam(
RequestParamDTO::Post('obj_class', utils::ENUM_SANITIZATION_FILTER_CLASS, true),
RequestParamDTO::Post('temp_id', utils::ENUM_SANITIZATION_FILTER_TRANSACTION_ID, true)
);
$oPage->SetContentType('text/html');
$oAttachmentsRenderer = AttachmentsRendererFactory::GetInstance($oPage, $sClass, $sId, $iTransactionId);
$aResult = [
'error' => '',
'att_id' => 0,
'preview' => 'false',
'msg' => '',
];
try {
$oDoc = utils::ReadPostedDocument('file');
if ($oDoc->IsEmpty()) {
throw new FileUploadException(Dict::S('Attachments:Error:UploadedFileEmpty'));
}
if (!UserRights::IsActionAllowed($sClass, UR_ACTION_MODIFY)) {
throw new SecurityException(Dict::S('UI:Error:ActionNotAllowed'));
}
/** @var Attachment $oAttachment */
$oAttachment = MetaModel::NewObject('Attachment');
$oAttachment->Set('expire', time() + MetaModel::GetConfig()->Get('draft_attachments_lifetime'));
$oAttachment->Set('temp_id', $sTempId);
$oAttachment->Set('item_class', $sClass);
$oAttachment->SetDefaultOrgId();
$oAttachment->Set('contents', $oDoc);
$iAttId = $oAttachment->DBInsert();
$aResult['msg'] = utils::EscapeHtml($oDoc->GetFileName());
$aResult['icon'] = utils::GetAbsoluteUrlAppRoot().AttachmentPlugIn::GetFileIcon($oDoc->GetFileName());
$aResult['att_id'] = $iAttId;
$aResult['preview'] = $oDoc->IsPreviewAvailable() ? 'true' : 'false';
} catch (FileUploadException $e) {
$aResult['error'] = $e->GetMessage();
$aResult['error_code'] = AttachmentAjaxErrorEnum::UPLOAD_FILE_EMPTY;
} catch (SecurityException $e) {
$aResult['error'] = $e->GetMessage();
$aResult['error_code'] = AttachmentAjaxErrorEnum::ACTION_NOT_ALLOWED;
}
$oPage->SetData($aResult);
$oPage->output();
}
/**
* RenderAttachments.
*
* @throws ArchivedObjectException
* @throws CoreException
* @throws OQLException
*/
function RenderAttachments(): void
{
$oPage = new AjaxPage("");
// reads request render parameters
[$sClass, $sKey, $sTempId, $bEditMode, $aAttachmentsDeleted] = HttpRequest::HandleRequestParam(
RequestParamDTO::Post('objclass', utils::ENUM_SANITIZATION_FILTER_CLASS, bIsMandatory: true),
RequestParamDTO::Post('objkey', utils::ENUM_SANITIZATION_FILTER_PARAMETER, bIsMandatory: true),
RequestParamDTO::Post('temp_id', utils::ENUM_SANITIZATION_FILTER_TRANSACTION_ID, bIsMandatory: true),
RequestParamDTO::Post('edit_mode', utils::ENUM_SANITIZATION_FILTER_INTEGER, oDefaultValue: 0),
RequestParamDTO::Post('attachments_deleted', utils::ENUM_SANITIZATION_FILTER_PARAMETER, oDefaultValue: []),
);
$oObject = MetaModel::GetObject($sClass, $sKey, false);
$oAttachmentsRenderer = AttachmentsRendererFactory::GetInstance($oPage, $sClass, $sKey, $sTempId);
$bIsReadOnlyState = !(is_null($oObject)) && AttachmentPlugIn::IsReadonlyState($oObject, $oObject->GetState(), AttachmentPlugIn::ENUM_GUI_BACKOFFICE);
$bIsReadOnlyState = (is_null($oObject))
? false
: AttachmentPlugIn::IsReadonlyState($oObject, $oObject->GetState(), AttachmentPlugIn::ENUM_GUI_BACKOFFICE);
if ($bEditMode && !$bIsReadOnlyState) {
$oAttachmentsRenderer->AddAttachmentsListContent(true, $aAttachmentsDeleted);
} else {
$oAttachmentsRenderer->RenderViewAttachmentsList();
}
$oPage->SetContentType('text/html');
$oPage->output();
}
try {
require_once APPROOT.'/application/startup.inc.php';
require_once APPROOT.'/application/loginwebpage.class.inc.php';
LoginWebPage::DoLogin(); // No user portal should access this endpoint.
// No user portal should access this endpoint.
LoginWebPage::DoLogin();
$oPage = new AjaxPage("");
// check if header contains X-Combodo-Ajax for POST request (CSRF protection for ajax calls)
// check must be performed after DoLoginEx to be logged in and to be able to check the token (based on the transaction id)
HttpRequest::CheckAjaxEndpoint();
// reads request operation
[$sOperation] = HttpRequest::HandleRequestParam(
RequestParamDTO::Post('operation', utils::ENUM_SANITIZATION_FILTER_OPERATION, true)
);
$sOperation = utils::ReadParam('operation', '');
switch ($sOperation) {
case 'add':
AddAttachment();
$oPage = new JsonPage();
$oPage->SetOutputDataOnly(true);
$aResult = [
'error' => '',
'att_id' => 0,
'preview' => 'false',
'msg' => '',
];
$sClass = stripslashes(utils::ReadParam('obj_class', '', false, 'class'));
$sTempId = utils::ReadParam('temp_id', '', false, 'transaction_id');
if (empty($sClass)) {
$aResult['error'] = "Missing argument 'obj_class'";
} elseif (empty($sTempId)) {
$aResult['error'] = "Missing argument 'temp_id'";
} else {
try {
$oDoc = utils::ReadPostedDocument('file');
if ($oDoc->IsEmpty()) {
throw new FileUploadException(Dict::S('Attachments:Error:UploadedFileEmpty'));
}
/** @var Attachment $oAttachment */
$oAttachment = MetaModel::NewObject('Attachment');
$oAttachment->Set('expire', time() + MetaModel::GetConfig()->Get('draft_attachments_lifetime'));
$oAttachment->Set('temp_id', $sTempId);
$oAttachment->Set('item_class', $sClass);
$oAttachment->SetDefaultOrgId();
$oAttachment->Set('contents', $oDoc);
$iAttId = $oAttachment->DBInsert();
$aResult['msg'] = utils::EscapeHtml($oDoc->GetFileName());
$aResult['icon'] = utils::GetAbsoluteUrlAppRoot().AttachmentPlugIn::GetFileIcon($oDoc->GetFileName());
$aResult['att_id'] = $iAttId;
$aResult['preview'] = $oDoc->IsPreviewAvailable() ? 'true' : 'false';
} catch (FileUploadException $e) {
$aResult['error'] = $e->GetMessage();
}
}
$oPage->SetData($aResult);
break;
case 'refresh_attachments_render':
RenderAttachments();
$sTempId = utils::ReadParam('temp_id', '', false, 'transaction_id');
RenderAttachments($oPage, $sTempId);
break;
default:
$oPage->p("Missing argument 'operation'");
}
} catch (SecurityException $e) {
HttpResponse::SendTextPlainUnauthorizedResponseAndExit();
} catch (HttpBadRequestException $e) {
HttpResponse::SendTextPlainBadRequestResponseAndExit();
$oPage->output();
} catch (Exception $e) {
// note: transform to cope with XSS attacks
echo utils::EscapeHtml($e->GetMessage());
IssueLog::Error($e->getMessage());
HttpResponse::SendTextPlainFatalResponseAndExit();
}

View File

@@ -217,7 +217,6 @@ abstract class AbstractAttachmentsRenderer
objclass: '$sClass',
objkey: $sId,
temp_id: '$this->sTransactionId',
transaction_id: '$this->sTransactionId',
edit_mode: 1,
attachments_deleted: aAttachmentsDeletedIds
},
@@ -232,12 +231,7 @@ abstract class AbstractAttachmentsRenderer
$('#file').fileupload({
url: GetAbsoluteUrlModulesRoot()+'itop-attachments/ajax.itop-attachment.php',
formData: {
operation: 'add',
temp_id: '$this->sTransactionId',
obj_class: '$sClass',
transaction_id: '$this->sTransactionId'
},
formData: { operation: 'add', temp_id: '$this->sTransactionId', obj_class: '$sClass' },
dataType: 'json',
pasteZone: null, // Don't accept files via Chrome's copy/paste
done: function(e, data) {
@@ -443,12 +437,12 @@ class TableDetailsAttachmentsRenderer extends AbstractAttachmentsRenderer
}
$aAttribs = [
'icon' => ['label' => $sThumbnail, 'description' => $sThumbnail],
'filename' => ['label' => $sFileName, 'description' => $sFileName],
'formatted-size' => ['label' => $sFileSize, 'description' => $sFileSize],
'upload-date' => ['label' => $sFileDate, 'description' => $sFileDate],
'uploader' => ['label' => $sFileUploader, 'description' => $sFileUploader],
'type' => ['label' => $sFileType, 'description' => $sFileType],
'icon' => ['label' => $sThumbnail, 'description' => $sThumbnail],
'filename' => ['label' => $sFileName, 'description' => $sFileName],
'formatted-size' => ['label' => $sFileSize, 'description' => $sFileSize],
'upload-date' => ['label' => $sFileDate, 'description' => $sFileDate],
'uploader' => ['label' => $sFileUploader, 'description' => $sFileUploader],
'type' => ['label' => $sFileType, 'description' => $sFileType],
'downloads-count' => ['label' => $sFileDownloadsCount, 'description' => $sFileDownloadsCount],
];
@@ -543,16 +537,16 @@ JS
}
$aAttachmentLine = [
'@id' => $sTrId,
'@meta' => 'data-file-type="'.utils::HtmlEntities($sFileType).'" data-file-size-raw="'.utils::HtmlEntities($iFileSize).'" data-file-size-formatted="'.utils::HtmlEntities($sFileFormattedSize).'" data-file-uploader="'.utils::HtmlEntities($sAttachmentUploader).'"',
'icon' => '<a href="'.$sDocDownloadUrl.'" target="_blank" class="'.$sIconClass.'"><img class="ibo-attachment--datatable--icon-preview '.$sIconClass.'" data-tooltip-content="'.$sPreviewMarkup.'" data-tooltip-html-enabled="true" src="'.$sAttachmentThumbUrl.'"></a>',
'filename' => '<a href="'.$sDocDownloadUrl.'" target="_blank" class="$sIconClass">'.$sFileName.'</a>'.$sAttachmentMeta,
'formatted-size' => $sFileFormattedSize,
'upload-date' => $sAttachmentDateFormatted,
'uploader' => $sAttachmentUploaderForHtml,
'type' => $sFileType,
'@id' => $sTrId,
'@meta' => 'data-file-type="'.utils::HtmlEntities($sFileType).'" data-file-size-raw="'.utils::HtmlEntities($iFileSize).'" data-file-size-formatted="'.utils::HtmlEntities($sFileFormattedSize).'" data-file-uploader="'.utils::HtmlEntities($sAttachmentUploader).'"',
'icon' => '<a href="'.$sDocDownloadUrl.'" target="_blank" class="'.$sIconClass.'"><img class="ibo-attachment--datatable--icon-preview '.$sIconClass.'" data-tooltip-content="'.$sPreviewMarkup.'" data-tooltip-html-enabled="true" src="'.$sAttachmentThumbUrl.'"></a>',
'filename' => '<a href="'.$sDocDownloadUrl.'" target="_blank" class="$sIconClass">'.$sFileName.'</a>'.$sAttachmentMeta,
'formatted-size' => $sFileFormattedSize,
'upload-date' => $sAttachmentDateFormatted,
'uploader' => $sAttachmentUploaderForHtml,
'type' => $sFileType,
'downloads-count' => $oDoc->GetDownloadsCount(),
'js' => '',
'js' => '',
];
if ($bIsDeletedAttachment) {
@@ -567,6 +561,6 @@ JS
$aAttachmentLine['delete'] = $oBlockRenderer->RenderHtml();
}
return $aAttachmentLine;
return $aAttachmentLine;
}
}

View File

@@ -1,12 +0,0 @@
<?php
namespace Combodo\iTop\Attachments\Enum;
/**
* @since 3.2.4 3.3.1 3.4.0 N°10213
*/
enum AttachmentAjaxErrorEnum: int
{
case UPLOAD_FILE_EMPTY = 10;
case ACTION_NOT_ALLOWED = 20;
}

View File

@@ -14,7 +14,10 @@ if (PHP_VERSION_ID < 50600) {
echo $err;
}
}
throw new RuntimeException($err);
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php';

View File

@@ -6,7 +6,6 @@ $vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Combodo\\iTop\\Attachments\\Enum\\AttachmentAjaxErrorEnum' => $baseDir . '/src/Enum/AttachmentAjaxErrorEnum.php',
'Combodo\\iTop\\Attachments\\Hook\\EventListener' => $baseDir . '/src/Hook/EventListener.php',
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
);

View File

@@ -7,21 +7,20 @@ namespace Composer\Autoload;
class ComposerStaticInitee10bebff75617dbf9d929ac6e40c19f
{
public static $prefixLengthsPsr4 = array (
'C' =>
'C' =>
array (
'Combodo\\iTop\\Attachments\\' => 25,
),
);
public static $prefixDirsPsr4 = array (
'Combodo\\iTop\\Attachments\\' =>
'Combodo\\iTop\\Attachments\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
);
public static $classMap = array (
'Combodo\\iTop\\Attachments\\Enum\\AttachmentAjaxErrorEnum' => __DIR__ . '/../..' . '/src/Enum/AttachmentAjaxErrorEnum.php',
'Combodo\\iTop\\Attachments\\Hook\\EventListener' => __DIR__ . '/../..' . '/src/Hook/EventListener.php',
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
);

View File

@@ -29,24 +29,6 @@ require_once(APPROOT.'/application/application.inc.php');
require_once(APPROOT.'core/mutex.class.inc.php');
const BACKUP_DIR = APPROOT.'data/backups/';
class AjaxBackupException extends CoreException
{
public function __construct(array $aContextData = null, Exception $oPreviousException = null)
{
parent::__construct('Backup/Restore exception occurred', $aContextData, oPrevious: $oPreviousException);
}
}
class AjaxBackupInvalidFileException extends AjaxBackupException
{
public function __construct(array $aContextData = null, Exception $oPreviousException = null)
{
parent::__construct($aContextData, oPreviousException: $oPreviousException);
}
}
/**
* @param WebPage $oPage
* @param string $sHtmlErrorMessage the whole HTML error, cinluding div/p/...
@@ -69,79 +51,73 @@ $sOperation = utils::ReadParam('operation', '');
$oPage = new AjaxPage('');
$oPage->SetContentType('text/html');
/**
* Check security
*/
switch ($sOperation) {
/**
* Can't use normal check methods (DoLogin for ex) as the datamodel can't be loaded here
* So we're only using a token generated in the restore_token operation
*/
case 'restore_exec':
IssueLog::Enable(APPROOT.'log/error.log');
if (utils::GetConfig()->Get('demo_mode')) {
DisplayErrorAndDie(
$oPage,
'<div data-error-stimulus="Error">Sorry, '.ITOP_APPLICATION_SHORT.' is in <b>demonstration mode</b>: the feature is disabled.</div>'
);
}
$sToken = utils::ReadParam('token', '', false, 'raw_data');
$sBasePath = APPROOT.'/data/';
$sTokenFile = $sBasePath.'restore.'.$sToken.'.tok';
$tokenRealPath = utils::RealPath($sTokenFile, $sBasePath);
if (($tokenRealPath === false) || (!is_file($tokenRealPath))) {
IssueLog::Error("ajax.backup.php operation=$sOperation ERROR = inexisting token $sToken");
$sEscapedToken = utils::HtmlEntities($sToken);
DisplayErrorAndDie($oPage, "<p>Error: missing token file: '$sEscapedToken'</p>");
}
break;
default:
require_once(APPROOT.'/application/startup.inc.php');
require_once(APPROOT.'/application/loginwebpage.class.inc.php');
LoginWebPage::DoLogin();
$sTransactionId = utils::ReadParam('transaction_id', '', true, 'transaction_id');
// the consumer page is not reloaded after download, we need to keep the transaction_id
$bRemoveTransactionId = ($sOperation !== 'download');
if (!utils::IsTransactionValid($sTransactionId, $bRemoveTransactionId)) {
$sEscapedOperation = utils::HtmlEntities($sOperation);
DisplayErrorAndDie($oPage, "<div data-error-stimulus=\"Error\">Error: invalid Transaction ID. The operation '$sEscapedOperation' was NOT performed!</div>");
}
ApplicationMenu::CheckMenuIdEnabled('BackupStatus');
if (utils::GetConfig()->Get('demo_mode')) {
DisplayErrorAndDie($oPage, '<div data-error-stimulus="Error">Sorry, '.ITOP_APPLICATION_SHORT.' is in <b>demonstration mode</b>: the feature is disabled.</div>');
}
break;
}
/**
* Backup from an interactive session
*/
try {
/**
* Check security
*/
switch ($sOperation) {
/**
* Can't use normal check methods (DoLogin for ex) as the datamodel can't be loaded here
* So we're only using a token generated in the restore_token operation
*/
case 'restore_exec':
IssueLog::Enable(APPROOT.'log/error.log');
if (utils::GetConfig()->Get('demo_mode')) {
DisplayErrorAndDie(
$oPage,
'<div data-error-stimulus="Error">Sorry, '.ITOP_APPLICATION_SHORT.' is in <b>demonstration mode</b>: the feature is disabled.</div>'
);
}
$sToken = utils::ReadParam('token', '', false, 'raw_data');
$sBasePath = APPROOT.'/data/';
$sTokenFile = $sBasePath.'restore.'.$sToken.'.tok';
$tokenRealPath = utils::RealPath($sTokenFile, $sBasePath);
if (($tokenRealPath === false) || (!is_file($tokenRealPath))) {
throw new AjaxBackupInvalidFileException([
'backup_operation' => $sOperation,
'message' => 'Could not restore backup, invalid token file.',
'token' => $sToken,
]);
}
break;
default:
require_once(APPROOT.'/application/startup.inc.php');
require_once(APPROOT.'/application/loginwebpage.class.inc.php');
LoginWebPage::DoLogin();
$sTransactionId = utils::ReadParam('transaction_id', '', true, 'transaction_id');
// the consumer page is not reloaded after download, we need to keep the transaction_id
$bRemoveTransactionId = ($sOperation !== 'download');
if (!utils::IsTransactionValid($sTransactionId, $bRemoveTransactionId)) {
throw new AjaxBackupException([
'backup_operation' => $sOperation,
'message' => 'Invalid transaction id',
'transaction_id' => $sTransactionId,
]);
}
ApplicationMenu::CheckMenuIdEnabled('BackupStatus');
if (utils::GetConfig()->Get('demo_mode')) {
DisplayErrorAndDie($oPage, '<div data-error-stimulus="Error">Sorry, '.ITOP_APPLICATION_SHORT.' is in <b>demonstration mode</b>: the feature is disabled.</div>');
}
break;
}
/**
* Backup from an interactive session
*/
switch ($sOperation) {
case 'backup':
try {
set_time_limit(0);
$oBB = new BackupExec(APPROOT.'data/backups/manual/', 0 /*iRetentionCount*/);
$sRes = $oBB->Process(time() + 36000); // 10 hours to complete should be sufficient!
$oPage->output();
} catch (Exception $e) {
throw new AjaxBackupException([
'backup_operation' => $sOperation,
'message' => $e->getMessage(),
], $e);
$oPage->p('Error: '.$e->getMessage());
IssueLog::Error($sOperation.' - '.$e->getMessage());
}
$oPage->output();
break;
/*
@@ -162,15 +138,6 @@ try {
}
$sFile = utils::ReadParam('file', '', false, 'raw_data');
$sBackupFilePath = utils::RealPath(BACKUP_DIR.$sFile, BACKUP_DIR);
if ($sBackupFilePath === false) {
throw new AjaxBackupInvalidFileException([
'backup_operation' => $sOperation,
'message' => 'Could not restore backup, invalid file given.',
'backup_file' => $sFile,
]);
}
$sToken = str_replace(' ', '', (string)microtime()).$sTransactionId;
$sTokenFile = APPROOT.'/data/restore.'.$sToken.'.tok';
file_put_contents($sTokenFile, $sFile);
@@ -204,15 +171,14 @@ try {
$oDBRS = new DBRestore($oItopConfig);
$oDBRS->SetMySQLBinDir($sMySQLBinDir);
$sBackupFile = BACKUP_DIR.$sFile;
$sBackupDir = APPROOT.'data/backups/';
$sBackupFile = $sBackupDir.$sFile;
$sRes = $oDBRS->RestoreFromCompressedBackup($sBackupFile, $sEnvironment);
IssueLog::Info('Backup Restore - Done, releasing the LOCK');
} catch (Exception $e) {
throw new AjaxBackupException([
'backup_operation' => $sOperation,
'message' => $e->getMessage(),
], $e);
$oPage->p('Error: '.$e->getMessage());
IssueLog::Error($sOperation.' - '.$e->getMessage());
} finally {
unlink($tokenRealPath);
}
@@ -226,33 +192,14 @@ try {
}
$sFile = utils::ReadParam('file', '', false, 'raw_data');
$oBackup = new DBBackupScheduled();
$sBackupFilePath = utils::RealPath(BACKUP_DIR.$sFile, BACKUP_DIR);
$sBackupDir = APPROOT.'data/backups/';
$sBackupFilePath = utils::RealPath($sBackupDir.$sFile, $sBackupDir);
if ($sBackupFilePath === false) {
throw new AjaxBackupInvalidFileException([
'backup_operation' => $sOperation,
'message' => 'Could not download backup, invalid file given.',
'backup_file' => $sFile,
]);
throw new CoreUnexpectedValue('Invalid file path');
}
$oBackup->DownloadBackup($sBackupFilePath);
break;
}
} catch (AjaxBackupInvalidFileException $e) {
IssueLog::Warning('Unable to perform backup `'.$e->getContextData()['backup_operation'].'` : '.$e->getContextData()['message'], LogChannels::SECURITY, [
'backup_operation' => $e->getContextData()['backup_operation'] ?? null,
'backup_file' => $e->getContextData()['backup_file'] ?? null,
]);
http_response_code(422);
die($e->getContextData()['message']);
} catch (CoreException $e) {
IssueLog::Error('Unable to perform backup `'.$e->getContextData()['backup_operation'].'` : '.$e->getContextData()['message'], LogChannels::BACKUP, [
'backup_operation' => $e->getContextData()['backup_operation'] ?? null,
'backup_file' => $e->getContextData()['backup_file'] ?? null,
]);
http_response_code(500);
die(Dict::S('UI:PageTitle:FatalError'));
} catch (Exception $e) {
IssueLog::Error($e->getMessage());
http_response_code(500);
die(Dict::S('UI:PageTitle:FatalError'));
IssueLog::Error($sOperation.' - '.$e->getMessage());
}

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -443,13 +443,6 @@ function LaunchBackupNow()
window.location.reload();
}
oModal.dialog('close');
}).fail(function(xhr){
var sErrorMessage = xhr.status === 500
? (xhr.responseText || 'Erreur serveur (HTTP 500).')
: (xhr.responseText || 'Erreur HTTP ' + xhr.status + '.');
$('#backup_errors').text(sErrorMessage);
$('#backup_errors').removeClass('ibo-is-hidden');
oModal.dialog('close');
});
}
}
@@ -494,25 +487,11 @@ function LaunchRestoreNow(sBackupFile, sConfirmationMessage)
$('#backup_success').removeClass('ibo-is-hidden');
}
oModal.dialog('close');
}).fail(function(xhr){
var sErrorMessage = xhr.status === 500
? (xhr.responseText || 'Erreur serveur (HTTP 500).')
: (xhr.responseText || 'Erreur HTTP ' + xhr.status + '.');
$('#backup_errors').text(sErrorMessage);
$('#backup_errors').removeClass('ibo-is-hidden');
oModal.dialog('close');
});
} else {
$('button.restore').prop('disabled', true);
oModal.dialog('close');
}
}).fail(function(xhr){
var sErrorMessage = xhr.status === 500
? (xhr.responseText || 'Erreur serveur (HTTP 500).')
: (xhr.responseText || 'Erreur HTTP ' + xhr.status + '.');
$('#backup_errors').text(sErrorMessage);
$('#backup_errors').removeClass('ibo-is-hidden');
oModal.dialog('close');
});
}
JS

View File

@@ -19,7 +19,7 @@
/**
* @author Benjamin Planque <benjamin.planque@combodo.com>
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*/
//////////////////////////////////////////////////////////////////////

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*/
//////////////////////////////////////////////////////////////////////

View File

@@ -19,7 +19,7 @@
/**
* @author Benjamin Planque <benjamin.planque@combodo.com>
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*/
//////////////////////////////////////////////////////////////////////

View File

@@ -19,7 +19,7 @@
/**
* @author Benjamin Planque <benjamin.planque@combodo.com>
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*/
//////////////////////////////////////////////////////////////////////

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -14,9 +14,7 @@ use Combodo\iTop\Application\UI\Base\Component\Input\InputUIBlockFactory;
use Combodo\iTop\Application\UI\Base\Component\Title\TitleUIBlockFactory;
use Combodo\iTop\Application\WebPage\iTopWebPage;
use Combodo\iTop\Config\Validator\iTopConfigAstValidator;
use Combodo\iTop\Config\Validator\iTopConfigSensitiveEnvValidator;
use Combodo\iTop\Config\Validator\iTopConfigSyntaxValidator;
use Combodo\iTop\Core\Config\Sensitive\SensitiveConfigStore;
require_once(APPROOT.'application/startup.inc.php');
@@ -100,16 +98,6 @@ function GetAlertFromException(Exception $e): Alert
return $oAlert;
}
/**
* @param string[] $aKeys parameter names (never values)
*
* @since 3.2.4 N°10293
*/
function FormatSensitiveKeys(array $aKeys): string
{
return utils::EscapeHtml(implode(', ', $aKeys));
}
/////////////////////////////////////////////////////////////////////
// Main program
//
@@ -149,20 +137,6 @@ try {
$sConfigContent = file_get_contents($sConfigFile);
$sConfigChecksum = md5($sConfigContent);
$sConfig = str_replace("\r\n", "\n", $sConfigContent);
// N°10293: sensitive parameters are managed by the system administrator, outside of this editor
$oSensitiveStore = SensitiveConfigStore::ForEnvironment(utils::GetCurrentEnvironment());
$bSensitiveStoreActive = $oSensitiveStore->IsActive();
$aShadowedKeys = [];
if ($bSensitiveStoreActive) {
$oCurrentConfig = new Config($sConfigFile, true, $oSensitiveStore);
$oP->AddUiBlock(AlertUIBlockFactory::MakeForInformation('', Dict::Format('config-sensitive-managed-by-sysadmin', FormatSensitiveKeys($oCurrentConfig->GetSensitiveKeys()))));
$aShadowedKeys = $oCurrentConfig->GetShadowedSensitiveKeys();
if (count($aShadowedKeys) > 0) {
// Never display the values: show the file as it will be written
$sConfig = $oCurrentConfig->RenderFileContent();
}
}
$sOriginalConfig = $sConfig;
if (!empty($sOperation)) {
@@ -186,7 +160,7 @@ try {
throw new Exception(Dict::S('config-error-file-changed'), CONFIG_ERROR);
}
if (($sConfig === $sOriginalConfig) && (count($aShadowedKeys) === 0)) {
if ($sConfig === $sOriginalConfig) {
throw new Exception(Dict::S('config-no-change'), CONFIG_INFO);
}
TestConfig($sConfig, $oP); // throws exceptions
@@ -205,39 +179,12 @@ try {
// 'config_editor' => 'disabled',
// )
file_put_contents($sTmpFile, $sConfig);
try {
$bReadsProtectedEnv = false;
if ($bSensitiveStoreActive) {
// N°10293: never let the editor read the variables carrying secrets (checked before any placeholder resolution)
$oEnvValidator = new iTopConfigSensitiveEnvValidator($oSensitiveStore->GetPlaceholderVariableNames());
$bReadsProtectedEnv = $oEnvValidator->Check($sConfig, $sTmpFile);
}
// N°10293: the temporary file is explicitly bound to the sensitive store of the current environment
$oTempConfig = $bReadsProtectedEnv ? null : new Config($sTmpFile, true, $bSensitiveStoreActive ? $oSensitiveStore : null);
} finally {
@unlink($sTmpFile);
}
if ($bReadsProtectedEnv) {
@chmod($sConfigFile, 0440);
IssueLog::Warning('Config editor: attempt to read protected environment variables refused', LogChannels::SECURITY, [
'user' => UserRights::GetUserId() ? UserRights::GetUser() : '',
]);
throw new Exception(Dict::S('config-sensitive-env-refused'), CONFIG_ERROR);
}
$aSubmittedSensitiveKeys = $oTempConfig->GetShadowedSensitiveKeys();
if (count($aSubmittedSensitiveKeys) > 0) {
@chmod($sConfigFile, 0440);
IssueLog::Warning('Config editor: attempt to write sensitive parameters refused', LogChannels::SECURITY, [
'user' => UserRights::GetUserId() ? UserRights::GetUser() : '',
'keys' => $aSubmittedSensitiveKeys,
]);
throw new Exception(Dict::Format('config-sensitive-write-refused', FormatSensitiveKeys($aSubmittedSensitiveKeys)), CONFIG_ERROR);
}
$oTempConfig = new Config($sTmpFile, true);
$oTempConfig->WriteToFile($sConfigFile);
@unlink($sTmpFile);
@chmod($sConfigFile, 0440); // Read-only
// N°10293: with the sensitive store, db_pwd is not in the config file
if ($bSensitiveStoreActive || DBPasswordInNewConfigIsOk($sConfig)) {
if (DBPasswordInNewConfigIsOk($sConfig)) {
$oAlert = AlertUIBlockFactory::MakeForSuccess('', Dict::S('config-saved'));
} else {
$oAlert = AlertUIBlockFactory::MakeForInformation('', Dict::S('config-saved-warning-db-password'));
@@ -251,17 +198,12 @@ try {
$sConfigChecksum = md5($sConfigContent);
$sConfig = str_replace("\r\n", "\n", $sConfigContent);
$sOriginalConfig = $sConfig;
$aShadowedKeys = [];
}
} catch (Exception $e) {
$oAlert = GetAlertFromException($e);
$oP->AddUiBlock($oAlert);
}
if (count($aShadowedKeys) > 0) {
$oP->AddUiBlock(AlertUIBlockFactory::MakeForWarning('', Dict::Format('config-sensitive-shadowed', FormatSensitiveKeys($aShadowedKeys))));
}
// (remove EscapeHtml) N°5914 - Wrong encoding in modules configuration editor
$oP->AddUiBlock(new Html('<p>'.Dict::S('config-edit-intro').'</p>'));

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*
@@ -41,8 +41,4 @@ Dict::Add('EN US', 'English', 'English', [
'config-error-file-changed' => 'Error: The Configuration file has changed since you opened it and cannot be saved. Refresh and apply your changes again.',
'config-not-allowed-in-demo' => 'Sorry, '.ITOP_APPLICATION_SHORT.' is in <b>demonstration mode</b>: the configuration file cannot be edited.',
'config-interactive-not-allowed' => ITOP_APPLICATION_SHORT." interactive edition of the configuration as been disabled. See <code>'config_editor' => 'disabled'</code> in the configuration file.",
'config-sensitive-managed-by-sysadmin' => 'The following sensitive parameters are managed by the system administrator in a dedicated file and cannot be viewed nor modified here: %1$s.',
'config-sensitive-shadowed' => 'The configuration file still contains sensitive parameters, which are ignored and hidden here: %1$s. They will be removed from the file at the next save.',
'config-sensitive-write-refused' => 'Error: sensitive parameters cannot be set in this editor: %1$s. The configuration was <b>NOT</b> modified.',
'config-sensitive-env-refused' => 'Error: the configuration references environment or server variables that carry sensitive parameters (or uses $GLOBALS, dynamic variables, or non-literal $_SERVER / $_ENV indexes). The configuration was <b>NOT</b> modified.',
]);

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -28,8 +28,4 @@ Dict::Add('FR FR', 'French', 'Français', [
'config-error-file-changed' => 'Erreur : La configuration a été modifiée depuis que vous l\'avez ouvert. Vos modifications ne peuvent <b>PAS</b> être enregistrées. Rechargez la page et recommencez.',
'config-not-allowed-in-demo' => 'Désolé, '.ITOP_APPLICATION_SHORT.' est en <b>mode démonstration</b> : la configuration ne peut pas être modifiée.',
'config-interactive-not-allowed' => 'La modification interactive de la configuration n\'est pas autorisée. Voir le paramètre <code>\'config_editor\' => \'disabled\'</code> dans le fichier de configuration.',
'config-sensitive-managed-by-sysadmin' => 'Les paramètres sensibles suivants sont gérés par l\'administrateur système dans un fichier dédié et ne peuvent être ni consultés ni modifiés ici : %1$s.',
'config-sensitive-shadowed' => 'Le fichier de configuration contient encore des paramètres sensibles, ignorés et masqués ici : %1$s. Ils seront supprimés du fichier au prochain enregistrement.',
'config-sensitive-write-refused' => 'Erreur : les paramètres sensibles ne peuvent pas être définis dans cet éditeur : %1$s. La configuration n\'a <b>PAS</b> été modifiée.',
'config-sensitive-env-refused' => 'Erreur : la configuration référence des variables d\'environnement ou serveur portant des paramètres sensibles (ou utilise $GLOBALS, des variables dynamiques, ou des index non littéraux de $_SERVER / $_ENV). La configuration n\'a <b>PAS</b> été modifiée.',
]);

View File

@@ -21,7 +21,6 @@ SetupWebPage::AddModule(
'src/Validator/ConfigNodesVisitor.php',
'src/Validator/iTopConfigAstValidator.php',
'src/Validator/iTopConfigSyntaxValidator.php',
'src/Validator/iTopConfigSensitiveEnvValidator.php',
],
'webservice' => [],
'dictionary' => [

View File

@@ -1,138 +0,0 @@
<?php
/*
* @copyright Copyright (C) 2010-2026 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
*/
namespace Combodo\iTop\Config\Validator;
use PhpParser\Node;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;
use PhpParser\ParserFactory;
use Throwable;
/**
* N°10293 / D-035: prevent the config editor from reading secrets carried by environment / server variables
* referenced by the placeholders of the sensitive store.
*
* Checks are done on NAMES only (never on secret values, which would create a guessing oracle).
*/
class iTopConfigSensitiveEnvValidator
{
private const PLACEHOLDER_PATTERN = '/%(?:env|server)\((\w+)\)/';
/**
* @param string[] $aProtectedNames variable names used by the placeholders of the sensitive store
*/
public function __construct(private readonly array $aProtectedNames)
{
}
/**
* AST check of the submitted PHP code
*
* @return bool true if the code may read a protected variable
*/
public function IsCodeReadingProtectedVariables(string $sConfig): bool
{
$aNodes = (new ParserFactory())->create(ParserFactory::PREFER_PHP7)->parse($sConfig) ?? [];
$aProtected = array_map('strtoupper', $this->aProtectedNames);
$oVisitor = new class ($aProtected) extends NodeVisitorAbstract {
public bool $bViolation = false;
private array $aCheckedVariables = [];
public function __construct(private readonly array $aProtected)
{
}
public function enterNode(Node $node)
{
if ($node instanceof Node\Expr\ArrayDimFetch && $node->var instanceof Node\Expr\Variable && $this->IsEnvSuperGlobal($node->var)) {
// $_SERVER['LITERAL'] is allowed unless LITERAL is protected
$this->aCheckedVariables[spl_object_id($node->var)] = true;
if (!($node->dim instanceof Node\Scalar\String_) || in_array(strtoupper($node->dim->value), $this->aProtected, true)) {
$this->bViolation = true;
}
} elseif ($node instanceof Node\Expr\Variable) {
if (!is_string($node->name) || $node->name === 'GLOBALS') {
$this->bViolation = true; // dynamic variable name or $GLOBALS
} elseif ($this->IsEnvSuperGlobal($node) && !isset($this->aCheckedVariables[spl_object_id($node)])) {
$this->bViolation = true; // whole $_SERVER / $_ENV
}
}
return null;
}
private function IsEnvSuperGlobal(Node\Expr\Variable $oVar): bool
{
return is_string($oVar->name) && in_array($oVar->name, ['_SERVER', '_ENV'], true);
}
};
$oTraverser = new NodeTraverser();
$oTraverser->addVisitor($oVisitor);
$oTraverser->traverse($aNodes);
return $oVisitor->bViolation;
}
/**
* Check of the evaluated (non resolved) values: placeholders referencing a protected variable
*
* @param array $aValues evaluated $MySettings / $MyModuleSettings
*/
public function AreValuesReferencingProtectedVariables(array $aValues): bool
{
$aProtected = array_map('strtoupper', $this->aProtectedNames);
$bFound = false;
array_walk_recursive($aValues, function ($value, $key) use ($aProtected, &$bFound) {
foreach ([$key, $value] as $item) {
if (is_string($item) && preg_match_all(self::PLACEHOLDER_PATTERN, $item, $aMatches)) {
if (count(array_intersect(array_map('strtoupper', $aMatches[1]), $aProtected)) > 0) {
$bFound = true;
}
}
}
});
return $bFound;
}
/**
* Evaluate a config file in isolation, without resolving placeholders
*
* @return array{0: array, 1: array} $MySettings and $MyModuleSettings
*/
public static function ReadRawArrays(string $sFile): array
{
$fnRead = static function () use ($sFile): array {
$MySettings = [];
$MyModuleSettings = [];
$MyModules = [];
ob_start();
try {
include $sFile;
} finally {
ob_end_clean();
}
return [is_array($MySettings) ? $MySettings : [], is_array($MyModuleSettings) ? $MyModuleSettings : []];
};
try {
return $fnRead();
} catch (Throwable $e) {
return [[], []];
}
}
/**
* @return bool true if the submitted config must be refused
*/
public function Check(string $sConfig, string $sEvaluatedFile): bool
{
return $this->IsCodeReadingProtectedVariables($sConfig)
|| $this->AreValuesReferencingProtectedVariables(self::ReadRawArrays($sEvaluatedFile));
}
}

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

View File

@@ -4,7 +4,7 @@
* Localized data
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license https://opensource.org/licenses/AGPL-3.0
* @license http://opensource.org/licenses/AGPL-3.0
*
* This file is part of iTop.
*

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