mirror of
https://github.com/Combodo/iTop.git
synced 2026-12-03 03:58:57 +01:00
Compare commits
32 Commits
feature/13
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7aaf754d5e | ||
|
|
05e564f172 | ||
|
|
7c8cf670c5 | ||
|
|
d28ac820f1 | ||
|
|
b496476ad2 | ||
|
|
c1d0fe3640 | ||
|
|
618cd19dfc | ||
|
|
9059155a1a | ||
|
|
f0206cf924 | ||
|
|
ac8b331a77 | ||
|
|
16dcbb131a | ||
|
|
7021495b21 | ||
|
|
d6428b2101 | ||
|
|
aeea0a98b7 | ||
|
|
28669c0a6e | ||
|
|
2df8af4ade | ||
|
|
801e92929c | ||
|
|
cfc648b67c | ||
|
|
e233e80fb9 | ||
|
|
4f72ef753c | ||
|
|
54eb1ed149 | ||
|
|
05f5cf457b | ||
|
|
16af5e1aab | ||
|
|
82983f8019 | ||
|
|
fb0c58ea73 | ||
|
|
199161318f | ||
|
|
bb31415dd3 | ||
|
|
fb55aa442e | ||
|
|
c63f3e650d | ||
|
|
c5a4433d0e | ||
|
|
d8b9533697 | ||
|
|
cd469d401c |
15
.idea/IntelliLang.xml
generated
15
.idea/IntelliLang.xml
generated
@@ -1,15 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="LanguageInjectionConfiguration">
|
||||
<injection language="InjectablePHP" injector-id="xml">
|
||||
<display-name>iTop - Class method code</display-name>
|
||||
<place><![CDATA[xmlTag().withLocalName(string().equalTo("code"))]]></place>
|
||||
<xpath-condition>name(..) = 'method' and count(/itop_design) = 1</xpath-condition>
|
||||
</injection>
|
||||
<injection language="InjectablePHP" injector-id="xml">
|
||||
<display-name>iTop - Snippet code</display-name>
|
||||
<place><![CDATA[xmlTag().withLocalName(string().equalTo("snippet"))]]></place>
|
||||
<xpath-condition>name(..) = 'snippets' and count(/itop_design) = 1</xpath-condition>
|
||||
</injection>
|
||||
</component>
|
||||
</project>
|
||||
28
AGENTS.md
28
AGENTS.md
@@ -3,6 +3,7 @@
|
||||
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)
|
||||
|
||||
@@ -37,6 +38,9 @@ These rules apply to every change. In code review, a violation is a P1 issue.
|
||||
- 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.
|
||||
@@ -50,7 +54,7 @@ These rules apply to every change. In code review, a violation is a P1 issue.
|
||||
- `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.
|
||||
- `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.
|
||||
|
||||
@@ -59,24 +63,35 @@ These rules apply to every change. In code review, a violation is a P1 issue.
|
||||
- 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` (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 (the pre-commit hook rejects SCSS without CSS).
|
||||
- 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. Do not add them to existing signatures (it breaks extensions) nor return types to fluent methods.
|
||||
- PHPDoc: `@since` is mandatory on new classes and on new or changed methods and properties, e.g. `@since 3.3.0 N°1234 - Short description`. Use `bool`, not `boolean`.
|
||||
- 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`.
|
||||
|
||||
@@ -93,7 +108,8 @@ These rules apply to every change. In code review, a violation is a P1 issue.
|
||||
### 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 other existing languages as well.
|
||||
- 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
|
||||
|
||||
23
REVIEW.md
23
REVIEW.md
@@ -4,27 +4,28 @@ For automated reviewers (GitHub Copilot code review, Greptile, ...). Project con
|
||||
|
||||
## Output
|
||||
- Write every comment in English.
|
||||
- Start each comment with its priority: `[P1-Security]`, `[P2-Regression]`, `[P2-Performance]`, `[P2-Architecture]` or `[P3]`.
|
||||
- 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.
|
||||
- Put test suggestions in a single `[Tests]` comment; it does not count toward the P3 limit.
|
||||
- If nothing is above P3, say so in one sentence. No praise, no file-by-file summary.
|
||||
- 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 Regression**: behavior change in an API extensions rely on (public classes and methods, extension interfaces, events, configuration parameters, REST/webservices); change to an existing datamodel class or attribute; removed or renamed dictionary entry.
|
||||
3. **P2 Performance**: queries inside loops, loading whole object sets when a count or a subset is enough, loading all attributes of an object in a loop instead of calling `\DBObjectSet::OptimizeColumnLoad`, repeated expensive calls.
|
||||
4. **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 the compiled CSS.
|
||||
5. **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.
|
||||
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/`.
|
||||
- Propose missing test cases to ensure maximum coverage of the new code, and that it is not broken by future changes.
|
||||
- Check readability, and 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.
|
||||
- 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.
|
||||
|
||||
## Vulnerability fixes
|
||||
This repository is public. If a change seems to fix an existing vulnerability, never describe the vulnerability, how to exploit it, or which versions are affected: neither in comments nor in the PR summary. Review it as an ordinary change. If the fix looks incomplete, describe only the missing check in neutral technical terms (for example "this value is not escaped here").
|
||||
## 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").
|
||||
@@ -35,8 +35,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -35,10 +35,14 @@ 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)
|
||||
{
|
||||
@@ -57,7 +61,14 @@ 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)) {
|
||||
$aData = json_decode($value, true); // true means decode as a hash array (not an object)
|
||||
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);
|
||||
}
|
||||
} else {
|
||||
$aData = $value;
|
||||
}
|
||||
@@ -66,9 +77,6 @@ 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) {
|
||||
|
||||
@@ -704,14 +704,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);
|
||||
$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['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['subject'] = MetaModel::ApplyParams($this->Get('subject'), $aContextArgs);
|
||||
$sBody = $this->BuildMessageBody(false);
|
||||
$aMessageContent['body'] = MetaModel::ApplyParams($sBody, $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);
|
||||
|
||||
$oObj = $aContextArgs['this->object()'];
|
||||
$aMessageContent['message_id'] = $this->GenerateIdentifierForHeaders($oObj, static::ENUM_HEADER_NAME_MESSAGE_ID);
|
||||
@@ -832,14 +832,16 @@ 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
|
||||
protected function BuildMessageBody(bool $bHighlightPlaceholders = false, ?string $sBody = null): 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">
|
||||
{$this->Get('body')}
|
||||
{$sBody}
|
||||
</div>
|
||||
HTML;
|
||||
|
||||
|
||||
@@ -2619,9 +2619,11 @@ 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 boolean True otherwise throws an Exception
|
||||
* @return bool True otherwise throws an Exception
|
||||
*
|
||||
* @throws \ConfigException
|
||||
*/
|
||||
@@ -2735,7 +2737,7 @@ class Config
|
||||
$aParserValue = null;
|
||||
}
|
||||
$sSeenAs = self::PrettyVarExport($aParserValue, $aSettingInfo['value'], "\t");
|
||||
fwrite($hFile, "\t'$sPropCode' => $sSeenAs,\n");
|
||||
fwrite($hFile, "\t".var_export((string) $sPropCode, true)." => $sSeenAs,\n");
|
||||
}
|
||||
}
|
||||
fwrite($hFile, ");\n");
|
||||
@@ -2744,10 +2746,10 @@ class Config
|
||||
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");
|
||||
fwrite($hFile, "\t".var_export((string) $sModule, true)." => 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\t".var_export((string) $sProperty, true)." => $sNiceExport,\n");
|
||||
}
|
||||
fwrite($hFile, "\t),\n");
|
||||
}
|
||||
|
||||
@@ -320,9 +320,9 @@
|
||||
$bIsAsync = $this->IsAsynchronous();
|
||||
[$sPreviousLanguage, $aPreviousPluginProperties] = $this->SetNotificationLanguage();
|
||||
|
||||
$sMessage = MetaModel::ApplyParams($this->Get('message'), $aContextArgs);
|
||||
$sTitle = MetaModel::ApplyParams($this->Get('title'), $aContextArgs);
|
||||
$sUrl = MetaModel::ApplyParams($this->Get('url'), $aContextArgs);
|
||||
$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);
|
||||
$iObjectId = 0;
|
||||
$sObjectClass = null;
|
||||
if (array_key_exists('this->object()', $aContextArgs)) {
|
||||
|
||||
@@ -5615,7 +5615,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);
|
||||
$sValue = MetaModel::ApplyParams($sRawValue, $aContext, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
|
||||
$this->Set($sAttCode, $sValue);
|
||||
break;
|
||||
|
||||
@@ -5639,7 +5639,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);
|
||||
$sAddendum = MetaModel::ApplyParams($sRawAddendum, $aContext, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
|
||||
$this->Set($sAttCode, $this->Get($sAttCode).$sAddendum);
|
||||
break;
|
||||
|
||||
|
||||
@@ -323,6 +323,7 @@ class HTMLDOMSanitizer extends DOMSanitizer
|
||||
|
||||
protected static $aAttrsWhiteList = [
|
||||
'src' => '/^(http:|https:|data:)/i',
|
||||
'href' => '/^(https?:|ftps?:|mailto:|\$|%24)/i',
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -354,30 +355,6 @@ 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;
|
||||
|
||||
@@ -1303,6 +1303,40 @@ 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
|
||||
*
|
||||
|
||||
@@ -118,6 +118,12 @@ 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
|
||||
@@ -6701,14 +6707,23 @@ 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)
|
||||
public static function ApplyParams($sInput, $aParams, ?string $sApplySanitizeMode = null)
|
||||
{
|
||||
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
|
||||
@@ -6796,7 +6811,14 @@ abstract class MetaModel
|
||||
}
|
||||
}
|
||||
|
||||
return str_replace($aSearches, $aReplacements, $sInput);
|
||||
$sTemplate = str_replace($aSearches, $aReplacements, $sInput);
|
||||
|
||||
// HTML sanitization
|
||||
if ($sApplySanitizeMode === self::APPLY_PARAMS_SANITIZE_HTML) {
|
||||
$sTemplate = DOMSanitizer::Sanitize($sTemplate);
|
||||
}
|
||||
|
||||
return $sTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -18,105 +18,146 @@
|
||||
* 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');
|
||||
|
||||
/**
|
||||
* @param \Combodo\iTop\Application\WebPage\AjaxPage $oPage
|
||||
* @param int $iTransactionId
|
||||
* AddAttachment.
|
||||
*
|
||||
* @throws \ArchivedObjectException
|
||||
* @throws \CoreException
|
||||
* @throws \OQLException
|
||||
* @return void
|
||||
* @throws ArchivedObjectException
|
||||
* @throws CoreCannotSaveObjectException
|
||||
* @throws CoreException
|
||||
* @throws CoreUnexpectedValue
|
||||
* @throws CoreWarning
|
||||
* @throws MySQLException
|
||||
* @throws OQLException
|
||||
*/
|
||||
function RenderAttachments(AjaxPage $oPage, $iTransactionId)
|
||||
function AddAttachment(): void
|
||||
{
|
||||
$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', []);
|
||||
$oPage = new JsonPage();
|
||||
$oPage->SetOutputDataOnly(true);
|
||||
|
||||
$oPage->SetContentType('text/html');
|
||||
$oAttachmentsRenderer = AttachmentsRendererFactory::GetInstance($oPage, $sClass, $sId, $iTransactionId);
|
||||
// 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)
|
||||
);
|
||||
|
||||
$bIsReadOnlyState = (is_null($oObject))
|
||||
? false
|
||||
: AttachmentPlugIn::IsReadonlyState($oObject, $oObject->GetState(), AttachmentPlugIn::ENUM_GUI_BACKOFFICE);
|
||||
$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);
|
||||
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.
|
||||
|
||||
$oPage = new AjaxPage("");
|
||||
// No user portal should access this endpoint.
|
||||
LoginWebPage::DoLogin();
|
||||
|
||||
$sOperation = utils::ReadParam('operation', '');
|
||||
// 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)
|
||||
);
|
||||
|
||||
switch ($sOperation) {
|
||||
|
||||
case 'add':
|
||||
$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);
|
||||
AddAttachment();
|
||||
break;
|
||||
|
||||
case 'refresh_attachments_render':
|
||||
$sTempId = utils::ReadParam('temp_id', '', false, 'transaction_id');
|
||||
RenderAttachments($oPage, $sTempId);
|
||||
RenderAttachments();
|
||||
break;
|
||||
|
||||
default:
|
||||
$oPage->p("Missing argument 'operation'");
|
||||
}
|
||||
|
||||
$oPage->output();
|
||||
} catch (SecurityException $e) {
|
||||
HttpResponse::SendTextPlainUnauthorizedResponseAndExit();
|
||||
} catch (HttpBadRequestException $e) {
|
||||
HttpResponse::SendTextPlainBadRequestResponseAndExit();
|
||||
} catch (Exception $e) {
|
||||
// note: transform to cope with XSS attacks
|
||||
echo utils::EscapeHtml($e->GetMessage());
|
||||
IssueLog::Error($e->getMessage());
|
||||
HttpResponse::SendTextPlainFatalResponseAndExit();
|
||||
}
|
||||
|
||||
@@ -217,6 +217,7 @@ abstract class AbstractAttachmentsRenderer
|
||||
objclass: '$sClass',
|
||||
objkey: $sId,
|
||||
temp_id: '$this->sTransactionId',
|
||||
transaction_id: '$this->sTransactionId',
|
||||
edit_mode: 1,
|
||||
attachments_deleted: aAttachmentsDeletedIds
|
||||
},
|
||||
@@ -231,7 +232,12 @@ abstract class AbstractAttachmentsRenderer
|
||||
|
||||
$('#file').fileupload({
|
||||
url: GetAbsoluteUrlModulesRoot()+'itop-attachments/ajax.itop-attachment.php',
|
||||
formData: { operation: 'add', temp_id: '$this->sTransactionId', obj_class: '$sClass' },
|
||||
formData: {
|
||||
operation: 'add',
|
||||
temp_id: '$this->sTransactionId',
|
||||
obj_class: '$sClass',
|
||||
transaction_id: '$this->sTransactionId'
|
||||
},
|
||||
dataType: 'json',
|
||||
pasteZone: null, // Don't accept files via Chrome's copy/paste
|
||||
done: function(e, data) {
|
||||
@@ -437,12 +443,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],
|
||||
];
|
||||
|
||||
@@ -537,16 +543,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) {
|
||||
@@ -561,6 +567,6 @@ JS
|
||||
$aAttachmentLine['delete'] = $oBlockRenderer->RenderHtml();
|
||||
}
|
||||
|
||||
return $aAttachmentLine;
|
||||
return $aAttachmentLine;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<?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;
|
||||
}
|
||||
@@ -14,10 +14,7 @@ if (PHP_VERSION_ID < 50600) {
|
||||
echo $err;
|
||||
}
|
||||
}
|
||||
trigger_error(
|
||||
$err,
|
||||
E_USER_ERROR
|
||||
);
|
||||
throw new RuntimeException($err);
|
||||
}
|
||||
|
||||
require_once __DIR__ . '/composer/autoload_real.php';
|
||||
|
||||
@@ -6,6 +6,7 @@ $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',
|
||||
);
|
||||
|
||||
@@ -7,20 +7,21 @@ 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',
|
||||
);
|
||||
|
||||
@@ -139,6 +139,10 @@ return array(
|
||||
'Combodo\\iTop\\Application\\Helper\\SearchHelper' => $baseDir . '/sources/Application/Helper/SearchHelper.php',
|
||||
'Combodo\\iTop\\Application\\Helper\\SynchroReplicaHelper' => $baseDir . '/sources/Application/Helper/SynchroReplicaHelper.php',
|
||||
'Combodo\\iTop\\Application\\Helper\\WebResourcesHelper' => $baseDir . '/sources/Application/Helper/WebResourcesHelper.php',
|
||||
'Combodo\\iTop\\Application\\Http\\HttpBadRequestException' => $baseDir . '/sources/Application/Http/HttpBadRequestException.php',
|
||||
'Combodo\\iTop\\Application\\Http\\HttpRequest' => $baseDir . '/sources/Application/Http/HttpRequest.php',
|
||||
'Combodo\\iTop\\Application\\Http\\HttpResponse' => $baseDir . '/sources/Application/Http/HttpResponse.php',
|
||||
'Combodo\\iTop\\Application\\Http\\RequestParamDTO' => $baseDir . '/sources/Application/Http/RequestParamDTO.php',
|
||||
'Combodo\\iTop\\Application\\Newsroom\\iTopNewsroomProvider' => $baseDir . '/sources/Application/Newsroom/iTopNewsroomProvider.php',
|
||||
'Combodo\\iTop\\Application\\Search\\AjaxSearchException' => $baseDir . '/sources/Application/Search/ajaxsearchexception.class.inc.php',
|
||||
'Combodo\\iTop\\Application\\Search\\CriterionConversionAbstract' => $baseDir . '/sources/Application/Search/criterionconversionabstract.class.inc.php',
|
||||
|
||||
@@ -540,6 +540,10 @@ class ComposerStaticInitfc0e9e9dea11dcbb6272414776c30685
|
||||
'Combodo\\iTop\\Application\\Helper\\SearchHelper' => __DIR__ . '/../..' . '/sources/Application/Helper/SearchHelper.php',
|
||||
'Combodo\\iTop\\Application\\Helper\\SynchroReplicaHelper' => __DIR__ . '/../..' . '/sources/Application/Helper/SynchroReplicaHelper.php',
|
||||
'Combodo\\iTop\\Application\\Helper\\WebResourcesHelper' => __DIR__ . '/../..' . '/sources/Application/Helper/WebResourcesHelper.php',
|
||||
'Combodo\\iTop\\Application\\Http\\HttpBadRequestException' => __DIR__ . '/../..' . '/sources/Application/Http/HttpBadRequestException.php',
|
||||
'Combodo\\iTop\\Application\\Http\\HttpRequest' => __DIR__ . '/../..' . '/sources/Application/Http/HttpRequest.php',
|
||||
'Combodo\\iTop\\Application\\Http\\HttpResponse' => __DIR__ . '/../..' . '/sources/Application/Http/HttpResponse.php',
|
||||
'Combodo\\iTop\\Application\\Http\\RequestParamDTO' => __DIR__ . '/../..' . '/sources/Application/Http/RequestParamDTO.php',
|
||||
'Combodo\\iTop\\Application\\Newsroom\\iTopNewsroomProvider' => __DIR__ . '/../..' . '/sources/Application/Newsroom/iTopNewsroomProvider.php',
|
||||
'Combodo\\iTop\\Application\\Search\\AjaxSearchException' => __DIR__ . '/../..' . '/sources/Application/Search/ajaxsearchexception.class.inc.php',
|
||||
'Combodo\\iTop\\Application\\Search\\CriterionConversionAbstract' => __DIR__ . '/../..' . '/sources/Application/Search/criterionconversionabstract.class.inc.php',
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
|
||||
use Combodo\iTop\Application\Helper\Session;
|
||||
use Combodo\iTop\Application\Helper\WebResourcesHelper;
|
||||
use Combodo\iTop\Application\Http\HttpRequest;
|
||||
use Combodo\iTop\Application\Http\HttpResponse;
|
||||
use Combodo\iTop\Application\TwigBase\Twig\TwigHelper;
|
||||
use Combodo\iTop\Application\UI\Base\Component\Html\Html;
|
||||
use Combodo\iTop\Application\UI\Base\Component\Title\TitleUIBlockFactory;
|
||||
@@ -61,15 +63,10 @@ try {
|
||||
|
||||
// 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)
|
||||
if (!isset($_SERVER['HTTP_X_COMBODO_AJAX']) && $_SERVER['REQUEST_METHOD'] !== 'GET') {
|
||||
$sTransactionId = utils::ReadPostedParam("transaction_id");
|
||||
if (!utils::IsTransactionValid($sTransactionId, false)) { // if a form is submitted without header but contains a token... should be exceptional
|
||||
$sReferer = $_SERVER['HTTP_REFERER'];
|
||||
$sErrorMsg = 'Unauthorized access. Please see https://www.itophub.io/wiki/page?id=3_2_0:release:developer#checking_for_the_presence_of_specific_header_in_the_post_to_enhance_protection_against_csrf_attacks';
|
||||
IssueLog::Error("Unprotected ajax call : $sErrorMsg", LogChannels::SECURITY, ['referer' => $sReferer]);
|
||||
header('HTTP/1.1 401 Unauthorized');
|
||||
die($sErrorMsg);
|
||||
}
|
||||
try {
|
||||
HttpRequest::CheckAjaxEndpoint('GET');
|
||||
} catch (SecurityException $e) {
|
||||
HttpResponse::SendTextPlainUnauthorizedResponseAndExit();
|
||||
}
|
||||
|
||||
$oKPI->ComputeAndReport('User login');
|
||||
@@ -100,8 +97,7 @@ try {
|
||||
|
||||
// Response is a WebPage, let's handle it like legacy operations
|
||||
$oPage = $mResponse;
|
||||
}
|
||||
// Otherwise, use legacy operation
|
||||
} // Otherwise, use legacy operation
|
||||
else {
|
||||
// Default for most operations, but can be switch to a JsonPage, DownloadPage or else if the operation requires it
|
||||
$oPage = new AjaxPage("");
|
||||
|
||||
22
sources/Application/Http/HttpBadRequestException.php
Normal file
22
sources/Application/Http/HttpBadRequestException.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2024 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Application\Http;
|
||||
|
||||
use CoreException;
|
||||
|
||||
/**
|
||||
* Class
|
||||
* HttpBadRequestException
|
||||
*
|
||||
* @since 3.2.4, 3.3.1, 3.4.0
|
||||
* @package Combodo\iTop\Application\Http
|
||||
*
|
||||
*/
|
||||
class HttpBadRequestException extends CoreException
|
||||
{
|
||||
}
|
||||
92
sources/Application/Http/HttpRequest.php
Normal file
92
sources/Application/Http/HttpRequest.php
Normal file
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2024 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Application\Http;
|
||||
|
||||
use IssueLog;
|
||||
use LogChannels;
|
||||
use SecurityException;
|
||||
use utils;
|
||||
|
||||
/**
|
||||
* Class
|
||||
* HttpRequest
|
||||
*
|
||||
* @since 3.2.4, 3.3.1, 3.4.0
|
||||
* @package Combodo\iTop\Application\Http
|
||||
*
|
||||
*/
|
||||
class HttpRequest
|
||||
{
|
||||
/**
|
||||
* 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)
|
||||
*
|
||||
* @param array $aBypassMethods list of methods that can bypass the check (e.g. GET)
|
||||
*
|
||||
* @throws SecurityException
|
||||
*/
|
||||
public static function CheckAjaxEndpoint(string...$aBypassMethods): void
|
||||
{
|
||||
if (!isset($_SERVER['HTTP_X_COMBODO_AJAX']) && !in_array($_SERVER['REQUEST_METHOD'], $aBypassMethods)) {
|
||||
$sTransactionId = utils::ReadPostedParam('transaction_id', '', utils::ENUM_SANITIZATION_FILTER_TRANSACTION_ID);
|
||||
if (!utils::IsTransactionValid($sTransactionId, false)) { // if a form is submitted without header but contains a token... should be exceptional
|
||||
$sErrorMsg = 'Unauthorized access. Please see https://www.itophub.io/wiki/page?id=3_2_0:release:developer#checking_for_the_presence_of_specific_header_in_the_post_to_enhance_protection_against_csrf_attacks';
|
||||
IssueLog::Error("Unprotected ajax call : $sErrorMsg", LogChannels::SECURITY, [
|
||||
'request_method' => $_SERVER['REQUEST_METHOD'],
|
||||
'request_uri' => $_SERVER['REQUEST_URI'],
|
||||
]);
|
||||
IssueLog::Debug("Unprotected ajax call : $sErrorMsg", LogChannels::SECURITY, [
|
||||
'http_referer' => $_SERVER['HTTP_REFERER'] ?? 'unknown',
|
||||
'transaction_id' => $sTransactionId,
|
||||
]);
|
||||
throw new SecurityException($sErrorMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads parameters and returns an array of values. If a mandatory parameter is missing, it will be logged and return a 400 error.
|
||||
*
|
||||
* @param RequestParamDTO ...$aParam
|
||||
*
|
||||
* @return array
|
||||
* @throws \CoreException
|
||||
*/
|
||||
public static function HandleRequestParam(RequestParamDTO...$aParam): array
|
||||
{
|
||||
$aResult = [];
|
||||
|
||||
foreach ($aParam as $oParam) {
|
||||
|
||||
$mValue = $oParam->bIsPostParam ?
|
||||
utils::ReadPostedParam($oParam->sName, $oParam->oDefaultValue, $oParam->sSanitizationFilter) :
|
||||
utils::ReadParam($oParam->sName, $oParam->oDefaultValue, $oParam->sSanitizationFilter);
|
||||
|
||||
if ($oParam->bIsMandatory && is_null($mValue)) {
|
||||
http_response_code(400);
|
||||
IssueLog::Error('Bad request: Missing mandatory parameter', LogChannels::WEB_REQUEST, [
|
||||
'request_method' => $_SERVER['REQUEST_METHOD'],
|
||||
'request_uri' => $_SERVER['REQUEST_URI'],
|
||||
]);
|
||||
IssueLog::Debug('Bad request: Missing mandatory parameter', LogChannels::WEB_REQUEST, [
|
||||
'parameter_type' => $oParam->bIsPostParam ? 'POST' : 'GET',
|
||||
'parameter' => $oParam->sName,
|
||||
]);
|
||||
throw new HttpBadRequestException('Bad request: Missing mandatory parameter', [
|
||||
'request_method' => $_SERVER['REQUEST_METHOD'],
|
||||
'request_uri' => $_SERVER['REQUEST_URI'],
|
||||
'parameter_type' => $oParam->bIsPostParam ? 'POST' : 'GET',
|
||||
'parameter' => $oParam->sName,
|
||||
]);
|
||||
}
|
||||
$aResult[] = $mValue;
|
||||
}
|
||||
|
||||
return $aResult;
|
||||
}
|
||||
}
|
||||
53
sources/Application/Http/HttpResponse.php
Normal file
53
sources/Application/Http/HttpResponse.php
Normal file
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2024 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Application\Http;
|
||||
|
||||
use Dict;
|
||||
|
||||
/**
|
||||
* Class
|
||||
* HttpResponse
|
||||
*
|
||||
* @since 3.2.4, 3.3.1, 3.4.0
|
||||
* @package Combodo\iTop\Application\Http
|
||||
*
|
||||
*/
|
||||
class HttpResponse
|
||||
{
|
||||
public static function SendJsonResponseAndExit(int $iHttpCode, array $aResponse): void
|
||||
{
|
||||
http_response_code($iHttpCode);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode($aResponse);
|
||||
exit;
|
||||
}
|
||||
|
||||
public static function SendTextPlainResponseAndExit(int $iHttpCode, string $sResponse): void
|
||||
{
|
||||
http_response_code($iHttpCode);
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
echo $sResponse;
|
||||
exit;
|
||||
}
|
||||
|
||||
public static function SendTextPlainFatalResponseAndExit(): void
|
||||
{
|
||||
self::SendTextPlainResponseAndExit(500, Dict::S('UI:PageTitle:FatalError'));
|
||||
}
|
||||
|
||||
public static function SendTextPlainBadRequestResponseAndExit(): void
|
||||
{
|
||||
self::SendTextPlainResponseAndExit(400, Dict::S('Error:HTTP:400'));
|
||||
}
|
||||
|
||||
public static function SendTextPlainUnauthorizedResponseAndExit(): void
|
||||
{
|
||||
self::SendTextPlainResponseAndExit(401, Dict::S('Error:HTTP:401'));
|
||||
}
|
||||
|
||||
}
|
||||
41
sources/Application/Http/RequestParamDTO.php
Normal file
41
sources/Application/Http/RequestParamDTO.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* @copyright Copyright (C) 2010-2024 Combodo SAS
|
||||
* @license http://opensource.org/licenses/AGPL-3.0
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Application\Http;
|
||||
|
||||
use utils;
|
||||
|
||||
/**
|
||||
* Class
|
||||
* RequestParamDTO
|
||||
*
|
||||
* @since 3.2.4, 3.3.1, 3.4.0
|
||||
* @package Combodo\iTop\Application\Http
|
||||
*
|
||||
*/
|
||||
class RequestParamDTO
|
||||
{
|
||||
public static function Create(string $sName, bool $bIsPostParam, string $sSanitizationFilter = utils::ENUM_SANITIZATION_FILTER_PARAMETER, bool $bIsMandatory = false, mixed $oDefaultValue = null): RequestParamDTO
|
||||
{
|
||||
return new RequestParamDTO($sName, $bIsPostParam, $sSanitizationFilter, $bIsMandatory, $oDefaultValue);
|
||||
}
|
||||
|
||||
public static function Post(string $sName, string $sSanitizationFilter = utils::ENUM_SANITIZATION_FILTER_PARAMETER, bool $bIsMandatory = false, mixed $oDefaultValue = null): RequestParamDTO
|
||||
{
|
||||
return new RequestParamDTO($sName, true, $sSanitizationFilter, $bIsMandatory, $oDefaultValue);
|
||||
}
|
||||
|
||||
public static function Get(string $sName, string $sSanitizationFilter = utils::ENUM_SANITIZATION_FILTER_PARAMETER, bool $bIsMandatory = false, mixed $oDefaultValue = null): RequestParamDTO
|
||||
{
|
||||
return new RequestParamDTO($sName, false, $sSanitizationFilter, $bIsMandatory, $oDefaultValue);
|
||||
}
|
||||
|
||||
public function __construct(public readonly string $sName, public readonly bool $bIsPostParam, public readonly string $sSanitizationFilter, public readonly bool $bIsMandatory = false, public readonly mixed $oDefaultValue = null)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,13 @@ use Combodo\iTop\Service\Base\ObjectRepository;
|
||||
use Combodo\iTop\Service\Router\Router;
|
||||
use CoreException;
|
||||
use DBObject;
|
||||
use DBObjectSet;
|
||||
use Dict;
|
||||
use Exception;
|
||||
use IssueLog;
|
||||
use LogChannels;
|
||||
use MetaModel;
|
||||
use SecurityException;
|
||||
use UserRights;
|
||||
use utils;
|
||||
|
||||
@@ -58,12 +62,21 @@ class LinkSetController extends AbstractController
|
||||
// check transaction id
|
||||
if (utils::IsTransactionValid($sTransactionId, false)) {
|
||||
try {
|
||||
$oDeletionPlan = MetaModel::GetObject($sLinkedObjectClass, $sLinkedObjectObjectKey)->DBDelete();
|
||||
$oLinkedObject = MetaModel::GetObject($sLinkedObjectClass, $sLinkedObjectObjectKey);
|
||||
if (UserRights::IsActionAllowed(get_class($oLinkedObject), UR_ACTION_DELETE, DBObjectSet::FromObject($oLinkedObject)) !== UR_ALLOWED_YES) {
|
||||
throw new SecurityException(Dict::S('UI:Delete:NotAllowedToDelete'), ['class' => get_class($oLinkedObject), 'key' => $oLinkedObject->GetKey()]);
|
||||
}
|
||||
$oDeletionPlan = $oLinkedObject->DBDelete();
|
||||
$bOperationSuccess = (count($oDeletionPlan->GetIssues()) === 0);
|
||||
if (!$bOperationSuccess) {
|
||||
$sErrorMessage = json_encode($oDeletionPlan->GetIssues());
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
IssueLog::Error(
|
||||
$e->getMessage(),
|
||||
$e instanceof SecurityException ? LogChannels::SECURITY : LogChannels::CORE,
|
||||
$e instanceof CoreException ? $e->getContextData() : null
|
||||
);
|
||||
$sErrorMessage = $e->getMessage();
|
||||
}
|
||||
} else {
|
||||
@@ -103,10 +116,18 @@ class LinkSetController extends AbstractController
|
||||
if (utils::IsTransactionValid($sTransactionId, false)) {
|
||||
try {
|
||||
$oLinkedObject = MetaModel::GetObject($sLinkedObjectClass, $sLinkedObjectKey);
|
||||
if (UserRights::IsActionAllowed(get_class($oLinkedObject), UR_ACTION_MODIFY, DBObjectSet::FromObject($oLinkedObject)) !== UR_ALLOWED_YES) {
|
||||
throw new SecurityException(Dict::S('UI:Error:ActionNotAllowed'), ['class' => get_class($oLinkedObject), 'key' => $sLinkedObjectKey]);
|
||||
}
|
||||
$oLinkedObject->Set($sExternalKeyAttCode, null);
|
||||
$oLinkedObject->DBWrite();
|
||||
$bOperationSuccess = true;
|
||||
} catch (Exception $e) {
|
||||
IssueLog::Error(
|
||||
$e->getMessage(),
|
||||
$e instanceof SecurityException ? LogChannels::SECURITY : LogChannels::CORE,
|
||||
$e instanceof CoreException ? $e->getContextData() : null
|
||||
);
|
||||
$sErrorMessage = $e->getMessage();
|
||||
}
|
||||
} else {
|
||||
@@ -238,9 +259,10 @@ JS
|
||||
// - When the user submit, redo the same request but with a real class
|
||||
|
||||
$sCurrentParameters = json_encode([
|
||||
'att_code' => $sAttCode,
|
||||
'att_code' => $sAttCode,
|
||||
'host_class' => $sClass,
|
||||
'host_id' => $sId]);
|
||||
'host_id' => $sId,
|
||||
]);
|
||||
$sCurrentUrl = $oRouter->GenerateUrl('linkset.create_linked_object');
|
||||
$oClassForm->SetOnSubmitJsCode(
|
||||
<<<JS
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
use Combodo\iTop\Application\Helper\Session;
|
||||
use Combodo\iTop\Test\UnitTest\ItopDataTestCase;
|
||||
|
||||
/**
|
||||
* @runClassInSeparateProcess Required because PHPUnit outputs something earlier, thus causing the headers to be sent
|
||||
*/
|
||||
class LoginDefaultBeforeTest extends ItopDataTestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
Session::$bAllowCLI = true;
|
||||
Session::Start();
|
||||
$_REQUEST = [];
|
||||
$this->RequireOnceItopFile('application/logindefault.class.inc.php');
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
parent::tearDown();
|
||||
Session::$bAllowCLI = false;
|
||||
}
|
||||
|
||||
public function testOnStart_NoLoginModeRequiredNorStoredInSession()
|
||||
{
|
||||
$this->CallStartAndCheckLoginModeStored(null, null);
|
||||
}
|
||||
|
||||
public function testOnStart_StoreLoginModeRequiredWhenConfigured()
|
||||
{
|
||||
MetaModel::GetConfig()->SetAllowedLoginTypes(["SAML"]);
|
||||
$_REQUEST['login_mode'] = "SAML";
|
||||
|
||||
$this->CallStartAndCheckLoginModeStored("SAML", null);
|
||||
}
|
||||
|
||||
public function testOnStart_SwitchLoginModeWhenNewOneRequiredIsConfigured()
|
||||
{
|
||||
MetaModel::GetConfig()->SetAllowedLoginTypes(["SAML"]);
|
||||
$_REQUEST['login_mode'] = "SAML";
|
||||
|
||||
$this->CallStartAndCheckLoginModeStored("SAML");
|
||||
}
|
||||
|
||||
public function testOnStart_PreserveCurrentLoginModeInSessionWhenNewOneRequiredIsNotConfigured()
|
||||
{
|
||||
$_REQUEST['login_mode'] = "SAML";
|
||||
|
||||
$this->CallStartAndCheckLoginModeStored("previous_mode");
|
||||
}
|
||||
|
||||
public function testOnStart_PreserveCurrentLoginModeInSessionWhenNoOtherRequired()
|
||||
{
|
||||
$this->CallStartAndCheckLoginModeStored('previous_mode');
|
||||
}
|
||||
|
||||
private function CallStartAndCheckLoginModeStored($expected, ?string $sPreviousLoginMode = 'previous_mode')
|
||||
{
|
||||
Session::Set('login_mode', $sPreviousLoginMode);
|
||||
|
||||
$iErrorCode = 666;
|
||||
$res = $this->InvokeNonPublicMethod(LoginDefaultBefore::class, 'OnStart', new LoginDefaultBefore(), [&$iErrorCode]);
|
||||
$this->assertEquals(LoginWebPage::EXIT_CODE_OK, $iErrorCode);
|
||||
$this->assertEquals(LoginWebPage::LOGIN_FSM_CONTINUE, $res);
|
||||
$this->assertEquals($expected, Session::Get('login_mode'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Copyright (C) 2018 Dennis Lassiter
|
||||
*
|
||||
* This file is part of iTop.
|
||||
*
|
||||
* iTop is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* iTop is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with iTop. If not, see <http://www.gnu.org/licenses/>
|
||||
*
|
||||
*/
|
||||
|
||||
namespace Combodo\iTop\Test\UnitTest\Application;
|
||||
|
||||
use Combodo\iTop\Test\UnitTest\ItopDataTestCase;
|
||||
use WizardHelper;
|
||||
use CoreException;
|
||||
|
||||
/**
|
||||
* @covers WizardHelper
|
||||
*/
|
||||
class wizardHelperTest extends ItopDataTestCase
|
||||
{
|
||||
public function testGetTargetObjectWithInvalidLinkSetDataValue()
|
||||
{
|
||||
// test case from N°9392 - [SECU] Stored XSS in subnets_list Parameter
|
||||
$sWizardHelperJSON = '{"m_sClass":"VLAN","m_oFieldsMap":{"vlan_tag":"2_vlan_tag","org_id":"2_org_id","description":"2_description","subnets_list":"2_subnets_list","physicalinterfaces_list":"2_physicalinterfaces_list"},"m_oCurrentValues":{"vlan_tag":null,"org_id":null,"description":null,"subnets_list":"[]oszzt<img src=a onerror=alert(1)>l053a","physicalinterfaces_list":"[]"},"m_aDefaultValueRequested":[],"m_aAllowedValuesRequested":[],"m_oDefaultValue":{},"m_oAllowedValues":{},"m_aStaticValues":[],"m_iFieldsCount":5,"m_sFormPrefix":"","m_sState":"","m_bReturnNotEditableFields":false,"m_sWizHelperJsVarName":null}';
|
||||
$this->expectException(CoreException::class);
|
||||
$this->expectExceptionMessageMatches('/^WizardHelper GetTargetObject: invalid data for linked set attribute/');
|
||||
$oWizardHelper = WizardHelper::FromJSON($sWizardHelperJSON);
|
||||
$oWizardHelper->GetTargetObject();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -50,8 +50,7 @@ class ActionEmailTest extends ItopDataTestCase
|
||||
<tr><td>Formatted eMail</td></tr>
|
||||
<tr><td>\$content\$</td></tr>
|
||||
</body>
|
||||
HTML
|
||||
;
|
||||
HTML;
|
||||
|
||||
static::$oActionEmail->DBInsert();
|
||||
static::$oDocument = new \ormDocument($sHtml, 'text/html', 'sample.html');
|
||||
@@ -180,7 +179,12 @@ HTML
|
||||
['subject' => 'This is a test'],
|
||||
['subject' => 'This is a test'],
|
||||
],
|
||||
'subject-with-placeholder' => [
|
||||
'subject-is-plain-text' => [
|
||||
'EN US',
|
||||
['subject' => 'Ticket <created> & assigned'],
|
||||
['subject' => 'Ticket <created> & assigned'],
|
||||
],
|
||||
'subject-with-placeholder' => [
|
||||
'EN US',
|
||||
['subject' => 'Ticket "$this->title$" created'],
|
||||
['subject' => 'Ticket "Test UserRequest" created'],
|
||||
|
||||
@@ -81,7 +81,7 @@ class MetaModelTest extends ItopDataTestCase
|
||||
|
||||
$aParams['this->object()'] = $oUserRequest;
|
||||
|
||||
$sGeneratedOutput = MetaModel::ApplyParams($sInput, $aParams);
|
||||
$sGeneratedOutput = MetaModel::ApplyParams($sInput, $aParams, MetaModel::APPLY_PARAMS_SANITIZE_NONE);
|
||||
|
||||
$this->assertEquals($sExpectedOutput, $sGeneratedOutput, "ApplyParams test returned $sGeneratedOutput");
|
||||
}
|
||||
@@ -149,6 +149,49 @@ class MetaModelTest extends ItopDataTestCase
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @group itopRequestMgmt
|
||||
* @covers MetaModel::ApplyParams()
|
||||
* @dataProvider ApplyParamsSanitizationProvider
|
||||
*
|
||||
* @param string $sInput
|
||||
* @param array $aParams
|
||||
* @param string $sExpectedOutput
|
||||
* @param string $sApplySanitizeMode
|
||||
*
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function testApplyParamsSanitization($sInput, $aParams, $sExpectedOutput, string $sApplySanitizeMode = MetaModel::APPLY_PARAMS_SANITIZE_NONE)
|
||||
{
|
||||
$sGeneratedOutput = MetaModel::ApplyParams($sInput, $aParams, $sApplySanitizeMode);
|
||||
|
||||
$this->assertEquals($sExpectedOutput, $sGeneratedOutput, "ApplyParams test returned $sGeneratedOutput");
|
||||
}
|
||||
|
||||
public function ApplyParamsSanitizationProvider()
|
||||
{
|
||||
$aParams = [
|
||||
'foo->javascript_injection' => 'javascript:alert(1)/*https://example.com*/',
|
||||
];
|
||||
|
||||
return [
|
||||
'Placeholder with malicious javascript injection (sanitization html)' => [
|
||||
'<a href="$foo->javascript_injection$">Hyperlink</a>',
|
||||
$aParams,
|
||||
'<a>Hyperlink</a>',
|
||||
'sanitize_html',
|
||||
false,
|
||||
],
|
||||
'Placeholder with malicious javascript injection (sanitization none)' => [
|
||||
'<a href="$foo->javascript_injection$">Hyperlink</a>',
|
||||
$aParams,
|
||||
'<a href="javascript:alert(1)/*https://example.com*/">Hyperlink</a>',
|
||||
'sanitize_none',
|
||||
false,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers MetaModel::GetDependentAttributes()
|
||||
* @dataProvider GetDependentAttributesProvider
|
||||
|
||||
@@ -218,6 +218,54 @@ class HTMLDOMSanitizerTest extends AbstractDOMSanitizerTest
|
||||
'expected' => '<ol start="100" reversed="reversed" type="I"><li value="101">Some list item</li></ol>',
|
||||
],
|
||||
|
||||
'link href url' => [
|
||||
'html' => '<a href="https://www.itop.com">Hyperlink</a>',
|
||||
'expected' => '<a href="https://www.itop.com">Hyperlink</a>',
|
||||
],
|
||||
'link href short url without protocol' => [
|
||||
'html' => '<a href="www.itop.com">Hyperlink</a>',
|
||||
'expected' => '<a>Hyperlink</a>',
|
||||
],
|
||||
'link href javascript injection' => [
|
||||
'html' => '<a href="javascript:alert(1)/*https://example.com*/">Hyperlink</a>',
|
||||
'expected' => '<a>Hyperlink</a>',
|
||||
],
|
||||
'link href with placeholder' => [
|
||||
'html' => '<a href="https://www.itop.com/$this->link$">Hyperlink</a>',
|
||||
'expected' => '<a href="https://www.itop.com/%24this->link%24">Hyperlink</a>',
|
||||
],
|
||||
'link href with placeholders combinaison' => [
|
||||
'html' => '<a href="https://www.itop.com/$this->link$/$this->ref$">Hyperlink</a>',
|
||||
'expected' => '<a href="https://www.itop.com/%24this->link%24/%24this->ref%24">Hyperlink</a>',
|
||||
],
|
||||
'link href with placeholder as base ref' => [
|
||||
'html' => '<a href="$this->link$/$this->ref$">Hyperlink</a>',
|
||||
'expected' => '<a href="%24this->link%24/%24this->ref%24">Hyperlink</a>',
|
||||
],
|
||||
'link href with placeholder constant' => [
|
||||
'html' => '<a href="$APPLICATION_URL$">Hyperlink</a>',
|
||||
'expected' => '<a href="%24APPLICATION_URL%24">Hyperlink</a>',
|
||||
],
|
||||
'link href with placeholder mixed' => [
|
||||
'html' => '<a href="$APPLICATION_URL$/$this->link$/$this->ref$">Hyperlink</a>',
|
||||
'expected' => '<a href="%24APPLICATION_URL%24/%24this->link%24/%24this->ref%24">Hyperlink</a>',
|
||||
],
|
||||
'link href with javascript injection and placeholder' => [
|
||||
'html' => '<a href="javascript:alert(1)/*$APPLICATION_URL$*">Hyperlink</a>',
|
||||
'expected' => '<a>Hyperlink</a>',
|
||||
],
|
||||
'link href with vbscript injection and placeholder' => [
|
||||
'html' => '<a href="vbscript:alert(1)/*$APPLICATION_URL$*">Hyperlink</a>',
|
||||
'expected' => '<a>Hyperlink</a>',
|
||||
],
|
||||
'link href with data injection and placeholder' => [
|
||||
'html' => '<a href="data:alert(1)/*$APPLICATION_URL$*">Hyperlink</a>',
|
||||
'expected' => '<a>Hyperlink</a>',
|
||||
],
|
||||
'link href with toto injection and placeholder' => [
|
||||
'html' => '<a href="toto:alert(1)/*$APPLICATION_URL$*">Hyperlink</a>',
|
||||
'expected' => '<a>Hyperlink</a>',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -4,11 +4,16 @@ declare(strict_types=1);
|
||||
|
||||
namespace Combodo\iTop\Test\UnitTest\Module\ItopAttachment;
|
||||
|
||||
use Combodo\iTop\Attachments\Enum\AttachmentAjaxErrorEnum;
|
||||
use Combodo\iTop\Test\UnitTest\ItopDataTestCase;
|
||||
use MetaModel;
|
||||
use UserRequest;
|
||||
use UserRights;
|
||||
use utils;
|
||||
|
||||
class AttachmentAjaxEndpointTest extends ItopDataTestCase
|
||||
{
|
||||
public const USE_TRANSACTION = false;
|
||||
public const USE_TRANSACTION = false;
|
||||
private const AUTHENTICATION_PASSWORD = 'tagada-Secret,007';
|
||||
|
||||
protected function setUp(): void
|
||||
@@ -19,42 +24,153 @@ class AttachmentAjaxEndpointTest extends ItopDataTestCase
|
||||
$this->AddLoginModeAndSaveConfiguration('url');
|
||||
}
|
||||
|
||||
public function testSuccessfullyAddAttachment(): void
|
||||
{
|
||||
$sLogin = 'user-'.uniqid();
|
||||
$this->CreateUser($sLogin, self::$aURP_Profiles['Service Desk Agent'], self::AUTHENTICATION_PASSWORD);
|
||||
|
||||
// log user to get a valid transaction id for the request (otherwise the request will be rejected by the CSRF protection)
|
||||
UserRights::Login($sLogin);
|
||||
|
||||
$sTempId = uniqid();
|
||||
|
||||
$aResponse = $this->CallAttachmentEndpointAs($sLogin, [
|
||||
'operation' => 'add',
|
||||
'obj_class' => UserRequest::class,
|
||||
'temp_id' => $sTempId,
|
||||
'file' => curl_file_create(__FILE__, 'text/plain', 'test.txt'),
|
||||
'transaction_id' => utils::GetNewTransactionId(),
|
||||
]);
|
||||
|
||||
$oAttachment = MetaModel::GetObjectByColumn('Attachment', 'temp_id', $sTempId, false);
|
||||
|
||||
$this->assertNotNull($oAttachment, 'Attachment should have been created in the database');
|
||||
$this->assertSame(200, $aResponse['code'], 'Expected HTTP code 200 for successful attachment addition');
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider AjaxEndpointAccessProvider
|
||||
*/
|
||||
public function testAjaxEndpointAccess(string $sProfile, int $iExpectedHttpCode): void
|
||||
public function testAjaxEndpointAccess(string $sProfile, array $aQueryParams, int $iExpectedHttpCode, mixed $oExpectedResponse = ''): void
|
||||
{
|
||||
$this->RequireOnceItopFile('core/userrights.class.inc.php');
|
||||
|
||||
// create a user with the given profile
|
||||
$sLogin = 'user-'.uniqid();
|
||||
$this->CreateUser($sLogin, self::$aURP_Profiles[$sProfile], self::AUTHENTICATION_PASSWORD);
|
||||
|
||||
$iHttpCode = $this->CallAttachmentEndpointAs($sLogin);
|
||||
// log user to get a valid transaction id for the request (otherwise the request will be rejected by the CSRF protection)
|
||||
UserRights::Login($sLogin);
|
||||
$aQueryParams['transaction_id'] = utils::GetNewTransactionId();
|
||||
|
||||
$this->assertSame($iExpectedHttpCode, $iHttpCode);
|
||||
// call the endpoint with the given parameters and check the response
|
||||
$aResponse = $this->CallAttachmentEndpointAs($sLogin, $aQueryParams);
|
||||
|
||||
if (is_array($oExpectedResponse)) {
|
||||
$aJson = json_decode($aResponse['response'], true);
|
||||
foreach ($oExpectedResponse as $sKey => $sValue) {
|
||||
$this->assertEquals($oExpectedResponse[$sKey], $aJson[$sKey], "Expected JSON key '$sKey' to contain '$sValue'");
|
||||
}
|
||||
} else {
|
||||
$this->assertEquals($oExpectedResponse, $aResponse['response']);
|
||||
}
|
||||
|
||||
$this->assertSame($iExpectedHttpCode, $aResponse['code']);
|
||||
}
|
||||
|
||||
public function AjaxEndpointAccessProvider(): array
|
||||
{
|
||||
$this->RequireOnceItopFile('datamodels/2.x/itop-attachments/src/Enum/AttachmentAjaxErrorEnum.php');
|
||||
|
||||
return [
|
||||
'console user' => ['Service Desk Agent', 200],
|
||||
'portal user' => ['Portal user', 302], // redirect to portal
|
||||
'Service Desk Agent: missing operation' => [
|
||||
'Service Desk Agent',
|
||||
[
|
||||
'obj_class' => UserRequest::class,
|
||||
'temp_id' => '123456',
|
||||
],
|
||||
400,
|
||||
'Bad request',
|
||||
],
|
||||
'Service Desk Agent: missing obj_class' => [
|
||||
'Service Desk Agent',
|
||||
[
|
||||
'operation' => 'add',
|
||||
'temp_id' => '123456',
|
||||
],
|
||||
400,
|
||||
'Bad request',
|
||||
],
|
||||
'Service Desk Agent: missing temp_id' => [
|
||||
'Service Desk Agent',
|
||||
[
|
||||
'operation' => 'add',
|
||||
'obj_class' => UserRequest::class,
|
||||
],
|
||||
400,
|
||||
'Bad request',
|
||||
],
|
||||
'Service Desk Agent: empty file' => [
|
||||
'Service Desk Agent',
|
||||
[
|
||||
'operation' => 'add',
|
||||
'obj_class' => UserRequest::class,
|
||||
'temp_id' => '123456',
|
||||
],
|
||||
200,
|
||||
[
|
||||
'error_code' => AttachmentAjaxErrorEnum::UPLOAD_FILE_EMPTY->value,
|
||||
],
|
||||
],
|
||||
'Service Desk Agent: access restricted' => [
|
||||
'Document author',
|
||||
[
|
||||
'operation' => 'add',
|
||||
'obj_class' => UserRequest::class,
|
||||
'temp_id' => '123456',
|
||||
'file' => curl_file_create(__FILE__, 'text/plain', 'test.txt'),
|
||||
],
|
||||
200,
|
||||
[
|
||||
'error_code' => AttachmentAjaxErrorEnum::ACTION_NOT_ALLOWED->value,
|
||||
],
|
||||
],
|
||||
'portal user' => [
|
||||
'Portal user',
|
||||
[],
|
||||
302, // redirect to portal
|
||||
[],
|
||||
],
|
||||
'Service Desk Agent: preview' => [
|
||||
'Service Desk Agent',
|
||||
[
|
||||
'operation' => 'refresh_attachments_render',
|
||||
'objclass' => 'UserRequest',
|
||||
'objkey' => 101,
|
||||
'temp_id' => '123456',
|
||||
],
|
||||
200,
|
||||
'No attachment.',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private function CallAttachmentEndpointAs(string $sLogin): int
|
||||
private function CallAttachmentEndpointAs(string $sLogin, array $aQueryParams = []): array
|
||||
{
|
||||
$this->CallItopUri(
|
||||
'env-production/itop-attachments/ajax.itop-attachment.php?operation=add&'.http_build_query([
|
||||
$sResponse = $this->CallItopUri(
|
||||
'env-production/itop-attachments/ajax.itop-attachment.php',
|
||||
array_merge($aQueryParams, [
|
||||
'auth_user' => $sLogin,
|
||||
'auth_pwd' => self::AUTHENTICATION_PASSWORD,
|
||||
'auth_pwd' => self::AUTHENTICATION_PASSWORD,
|
||||
]),
|
||||
[],
|
||||
[
|
||||
CURLOPT_HTTPHEADER => ['X-Combodo-Ajax:1'],
|
||||
CURLOPT_POST => 0,
|
||||
],
|
||||
true
|
||||
);
|
||||
|
||||
return $this->aLastCurlGetInfo['http_code'];
|
||||
return [
|
||||
'code' => $this->aLastCurlGetInfo['http_code'],
|
||||
'response' => $sResponse,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace Combodo\iTop\Test\UnitTest\Module\ItopBackup;
|
||||
|
||||
use Combodo\iTop\Test\UnitTest\ItopDataTestCase;
|
||||
use MetaModel;
|
||||
use UserRights;
|
||||
use utils;
|
||||
|
||||
@@ -21,31 +22,31 @@ class BackupAjaxEndpointTest extends ItopDataTestCase
|
||||
$this->AddLoginModeAndSaveConfiguration('url');
|
||||
}
|
||||
|
||||
// public function testDownloadInvalidDownloadPathReturnsHttp500(): void
|
||||
// {
|
||||
// $sLogin = 'test-backup-endpoint-'.uniqid();
|
||||
// $this->CreateUser($sLogin, self::$aURP_Profiles['Administrator'], self::AUTHENTICATION_PASSWORD);
|
||||
//
|
||||
// UserRights::Login($sLogin);
|
||||
//
|
||||
// $this->CallItopUri(
|
||||
// 'env-production/itop-backup/ajax.backup.php?'.http_build_query([
|
||||
// 'operation' => 'download',
|
||||
// 'file' => 'missing-'.uniqid().'.zip',
|
||||
// 'auth_user' => $sLogin,
|
||||
// 'auth_pwd' => self::AUTHENTICATION_PASSWORD,
|
||||
// 'transaction_id' => utils::GetNewTransactionId(),
|
||||
// ]),
|
||||
// [],
|
||||
// [
|
||||
// CURLOPT_HTTPHEADER => ['X-Combodo-Ajax:1'],
|
||||
// CURLOPT_POST => 0,
|
||||
// ],
|
||||
// true
|
||||
// );
|
||||
//
|
||||
// $this->assertSame(422, $this->aLastCurlGetInfo['http_code']);
|
||||
// }
|
||||
public function testDownloadInvalidDownloadPathReturnsHttp500(): void
|
||||
{
|
||||
$sLogin = 'test-backup-endpoint-'.uniqid();
|
||||
$this->CreateUser($sLogin, self::$aURP_Profiles['Administrator'], self::AUTHENTICATION_PASSWORD);
|
||||
|
||||
UserRights::Login($sLogin);
|
||||
|
||||
$sData = $this->CallItopUri(
|
||||
'env-production/itop-backup/ajax.backup.php?'.http_build_query([
|
||||
'operation' => 'download',
|
||||
'file' => 'missing-'.uniqid().'.zip',
|
||||
'auth_user' => $sLogin,
|
||||
'auth_pwd' => self::AUTHENTICATION_PASSWORD,
|
||||
'transaction_id' => utils::GetNewTransactionId(),
|
||||
]),
|
||||
[],
|
||||
[
|
||||
CURLOPT_HTTPHEADER => ['X-Combodo-Ajax:1'],
|
||||
CURLOPT_POST => 0,
|
||||
],
|
||||
true
|
||||
);
|
||||
|
||||
$this->assertSame(422, $this->aLastCurlGetInfo['http_code'], __METHOD__.':'.$sData);
|
||||
}
|
||||
|
||||
public function testRestoreGetTokenInvalidTransactionIdReturnsHttp500(): void
|
||||
{
|
||||
@@ -54,7 +55,7 @@ class BackupAjaxEndpointTest extends ItopDataTestCase
|
||||
|
||||
UserRights::Login($sLogin);
|
||||
|
||||
$this->CallItopUri(
|
||||
$sData = $this->CallItopUri(
|
||||
'env-production/itop-backup/ajax.backup.php?'.http_build_query([
|
||||
'operation' => 'restore_get_token',
|
||||
'auth_user' => $sLogin,
|
||||
@@ -69,34 +70,52 @@ class BackupAjaxEndpointTest extends ItopDataTestCase
|
||||
true
|
||||
);
|
||||
|
||||
$this->assertSame(500, $this->aLastCurlGetInfo['http_code']);
|
||||
$this->assertSame(500, $this->aLastCurlGetInfo['http_code'], __METHOD__.':'.$sData);
|
||||
}
|
||||
|
||||
// public function testRestoreGetToken(): void
|
||||
// {
|
||||
// $sLogin = 'test-backup-endpoint-'.uniqid();
|
||||
// $this->CreateUser($sLogin, self::$aURP_Profiles['Administrator'], self::AUTHENTICATION_PASSWORD);
|
||||
//
|
||||
// UserRights::Login($sLogin);
|
||||
//
|
||||
// $sData = $this->CallItopUri(
|
||||
// 'env-production/itop-backup/ajax.backup.php?'.http_build_query([
|
||||
// 'operation' => 'restore_get_token',
|
||||
// 'auth_user' => $sLogin,
|
||||
// 'auth_pwd' => self::AUTHENTICATION_PASSWORD,
|
||||
// 'transaction_id' => utils::GetNewTransactionId(),
|
||||
// ]),
|
||||
// [],
|
||||
// [
|
||||
// CURLOPT_HTTPHEADER => ['X-Combodo-Ajax:1'],
|
||||
// CURLOPT_POST => 0,
|
||||
// ],
|
||||
// true
|
||||
// );
|
||||
//
|
||||
// $aData = json_decode($sData, true);
|
||||
//
|
||||
// $this->assertSame(200, $this->aLastCurlGetInfo['http_code']);
|
||||
// $this->assertArrayHasKey('token', $aData);
|
||||
// }
|
||||
public function testRestoreGetToken(): void
|
||||
{
|
||||
$sLogin = 'test-backup-endpoint-'.uniqid();
|
||||
$this->CreateUser($sLogin, self::$aURP_Profiles['Administrator'], self::AUTHENTICATION_PASSWORD);
|
||||
|
||||
UserRights::Login($sLogin);
|
||||
|
||||
$sBackupDirectory = APPROOT.'data/backups/';
|
||||
if (!is_dir($sBackupDirectory)) {
|
||||
$this->assertTrue(mkdir($sBackupDirectory, 0770, true) || is_dir($sBackupDirectory));
|
||||
}
|
||||
$sBackupFile = 'backup-'.uniqid().'.zip';
|
||||
$sBackupPath = $sBackupDirectory.$sBackupFile;
|
||||
$oArchive = new \ZipArchive();
|
||||
|
||||
$bArchiveOpen = $oArchive->open($sBackupPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
|
||||
$this->assertTrue($bArchiveOpen);
|
||||
$this->assertTrue($oArchive->addFromString('itop-dump.sql', '-- Test backup'));
|
||||
$sConfigContents = file_get_contents(MetaModel::GetConfig()->GetLoadedFile());
|
||||
$this->assertNotFalse($sConfigContents);
|
||||
$this->assertTrue($oArchive->addFromString('config-itop.php', $sConfigContents));
|
||||
$this->assertTrue($oArchive->close());
|
||||
$this->aFileToClean[] = $sBackupPath;
|
||||
|
||||
$sData = $this->CallItopUri(
|
||||
'env-production/itop-backup/ajax.backup.php?'.http_build_query([
|
||||
'operation' => 'restore_get_token',
|
||||
'auth_user' => $sLogin,
|
||||
'auth_pwd' => self::AUTHENTICATION_PASSWORD,
|
||||
'file' => $sBackupFile,
|
||||
'transaction_id' => utils::GetNewTransactionId(),
|
||||
]),
|
||||
[],
|
||||
[
|
||||
CURLOPT_HTTPHEADER => ['X-Combodo-Ajax:1'],
|
||||
CURLOPT_POST => 0,
|
||||
],
|
||||
true
|
||||
);
|
||||
|
||||
$aData = json_decode($sData, true);
|
||||
$this->assertSame(200, $this->aLastCurlGetInfo['http_code'], __METHOD__.':'.$sData);
|
||||
$this->assertArrayHasKey('token', $aData);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,10 @@ namespace Combodo\iTop\Test\UnitTest\Module\iTopConfig;
|
||||
|
||||
use Combodo\iTop\Test\UnitTest\ItopTestCase;
|
||||
use Config;
|
||||
use PhpParser\ConstExprEvaluator;
|
||||
use PhpParser\Node;
|
||||
use PhpParser\ParserFactory;
|
||||
use utils;
|
||||
|
||||
class ConfigTest extends ItopTestCase
|
||||
{
|
||||
@@ -91,4 +95,105 @@ class ConfigTest extends ItopTestCase
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 3.2.3
|
||||
* @dataProvider ProviderArrayKeys
|
||||
*/
|
||||
public function testWriteToFilePreservesModuleKeys(int|string $key): void
|
||||
{
|
||||
$oConfig = new Config();
|
||||
$oConfig->SetModuleSetting('existing-module', 'existing.property', true);
|
||||
$oConfig->SetModuleSetting($key, 'sample.property', 'value');
|
||||
|
||||
$this->AssertWriteToFilePreservesSettings($oConfig, [
|
||||
'existing-module' => ['existing.property' => true],
|
||||
$key => ['sample.property' => 'value'],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 3.2.3
|
||||
* @dataProvider ProviderArrayKeys
|
||||
*/
|
||||
public function testWriteToFilePreservesPropertyKeys(int|string $key): void
|
||||
{
|
||||
$oConfig = new Config();
|
||||
$oConfig->SetModuleSetting('sample-module', 'existing.property', true);
|
||||
$oConfig->SetModuleSetting('sample-module', $key, [$key => 'value']);
|
||||
|
||||
$this->AssertWriteToFilePreservesSettings($oConfig, [
|
||||
'sample-module' => [
|
||||
'existing.property' => true,
|
||||
$key => [$key => 'value'],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 3.2.3
|
||||
* @return array<string, array{int|string}>
|
||||
*/
|
||||
public static function ProviderArrayKeys(): array
|
||||
{
|
||||
return [
|
||||
'module and property separators' => ['sample-module.setting_1'],
|
||||
'apostrophe' => ["O'Reilly"],
|
||||
'double quote' => ['a"b'],
|
||||
'backslash' => ['a\\b'],
|
||||
'repeated backslashes' => ['a\\\\b'],
|
||||
'trailing backslash' => ['trailing\\'],
|
||||
'backslash before apostrophe' => ["a\\'b"],
|
||||
'unicode' => ["caf\u{00E9}-\u{65E5}\u{672C}"],
|
||||
'line breaks' => ["first\nsecond\rthird"],
|
||||
'dollar sign' => ['$value'],
|
||||
'empty string' => [''],
|
||||
'zero' => [0],
|
||||
'integer' => [7],
|
||||
'negative integer' => [-7],
|
||||
'numeric string' => ['7'],
|
||||
'leading zero' => ['07'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @since 3.2.3
|
||||
* @param array<int|string, array<int|string, mixed>> $aModuleSettings
|
||||
*/
|
||||
private function AssertWriteToFilePreservesSettings(Config $oConfig, array $aModuleSettings): void
|
||||
{
|
||||
$oOriginalConfig = utils::GetConfig();
|
||||
$oParser = (new ParserFactory())->createForNewestSupportedVersion();
|
||||
$oEvaluator = new ConstExprEvaluator();
|
||||
|
||||
try {
|
||||
for ($i = 0; $i < 2; $i++) {
|
||||
$sTargetFile = tempnam(sys_get_temp_dir(), 'config-target');
|
||||
$this->aFileToClean[] = $sTargetFile;
|
||||
$this->assertTrue($oConfig->WriteToFile($sTargetFile));
|
||||
|
||||
$aNodes = $oParser->parse(file_get_contents($sTargetFile));
|
||||
$this->assertCount(3, $aNodes);
|
||||
$aValues = [];
|
||||
foreach ($aNodes as $oNode) {
|
||||
$this->assertInstanceOf(Node\Stmt\Expression::class, $oNode);
|
||||
$this->assertInstanceOf(Node\Expr\Assign::class, $oNode->expr);
|
||||
$this->assertInstanceOf(Node\Expr\Variable::class, $oNode->expr->var);
|
||||
$aValues[$oNode->expr->var->name] = $oEvaluator->evaluateDirectly($oNode->expr->expr);
|
||||
}
|
||||
$this->assertSame(['MySettings', 'MyModuleSettings', 'MyModules'], array_keys($aValues));
|
||||
$this->assertSame($aModuleSettings, $aValues['MyModuleSettings']);
|
||||
$this->assertSame([], $aValues['MyModules']);
|
||||
|
||||
$oConfig = new Config($sTargetFile);
|
||||
foreach ($aModuleSettings as $sModule => $aProperties) {
|
||||
foreach ($aProperties as $sProperty => $value) {
|
||||
$this->assertSame($value, $oConfig->GetModuleSetting($sModule, $sProperty));
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
utils::SetConfig($oOriginalConfig);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user