Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]

### Fixed

- Fix handling of additional information values in the injection form
- Fix model checks on the injection upload and the PDF report export
- Fix rights used by the model field dropdowns
- Fix CSV export of headers and of the model sample file
- Fix file name display in the PDF report header
- Fix temporary error file not being removed when its download fails
- Use the query builder for the remaining queries

## [2.15.13] - 2026-11-13

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion ajax/dropdownChooseField.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
Html::header_nocache();
}

Session::checkCentralAccess();
Session::checkRight(PluginDatainjectionClientInjection::$rightname, READ);
// Reads the session only: release it so that the calls of a tab run in parallel
Session::writeClose();
PluginDatainjectionInjectionType::dropdownFields($_POST);
2 changes: 1 addition & 1 deletion ajax/dropdownMandatory.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
Html::header_nocache();
}

Session::checkCentralAccess();
Session::checkRight(PluginDatainjectionClientInjection::$rightname, READ);
// Reads the session only: release it so that the calls of a tab run in parallel
Session::writeClose();
PluginDatainjectionInjectionType::showMandatoryCheckbox($_POST);
14 changes: 13 additions & 1 deletion front/clientinjection.form.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
* -------------------------------------------------------------------------
*/

use Glpi\Exception\Http\AccessDeniedHttpException;
use Glpi\Exception\Http\BadRequestHttpException;

Session::checkRight("plugin_datainjection_use", READ);

Html::header(
Expand All @@ -43,7 +46,16 @@
PluginDatainjectionClientInjection::showInjectionForm($model, $_SESSION['glpiactive_entity']);
} elseif (isset($_POST['upload'])) {
$model = new PluginDatainjectionModel();
$model->can($_POST['id'], READ);
$models_id = (int) ($_POST['id'] ?? 0);
if ($models_id <= 0) {
throw new BadRequestHttpException();
}

//Injection users may lack the model management right: only check the model itself is visible
if (!$model->getFromDB($models_id) || !$model->canViewItem()) {
throw new AccessDeniedHttpException();
}

$_SESSION['datainjection']['infos'] = ($_POST['info'] ?? []);

//If additional informations provided : check if mandatory infos are present
Expand Down
16 changes: 15 additions & 1 deletion front/export.pdf.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,20 @@
* -------------------------------------------------------------------------
*/

use Glpi\Exception\Http\AccessDeniedHttpException;
use Glpi\Exception\Http\BadRequestHttpException;

Session::checkRight(PluginDatainjectionClientInjection::$rightname, READ);

PluginDatainjectionModel::exportAsPDF($_GET['models_id']);
$models_id = (int) ($_GET['models_id'] ?? 0);
if ($models_id <= 0) {
throw new BadRequestHttpException();
}

//Injection users may lack the model management right: only check the model itself is visible
$model = new PluginDatainjectionModel();
if (!$model->getFromDB($models_id) || !$model->canViewItem()) {
throw new AccessDeniedHttpException();
}

PluginDatainjectionModel::exportAsPDF($models_id);
13 changes: 8 additions & 5 deletions inc/clientinjection.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -328,9 +328,9 @@ public static function showResultsForm(PluginDatainjectionModel $model)
TemplateRenderer::getInstance()->display('@datainjection/clientinjection_result.html.twig', $data);
}

private static function escapeCsvFormula(mixed $value): mixed
public static function escapeCsvFormula(mixed $value): mixed
{
if (is_string($value) && isset($value[0]) && in_array($value[0], ['=', '+', '-', '@'], true)) {
if (is_string($value) && isset($value[0]) && in_array($value[0], ['=', '+', '-', '@', "\t", "\r"], true)) {
return "'" . $value;
}

Expand All @@ -351,7 +351,7 @@ private static function writeErrorsCsv(string $dir, array $error_lines, array $h
$tmpfile = fopen($file, 'w');

if ($headers !== []) {
fputcsv($tmpfile, $headers, $delimiter);
fputcsv($tmpfile, array_map(self::escapeCsvFormula(...), $headers), $delimiter);
}

foreach ($error_lines as $line) {
Expand Down Expand Up @@ -422,8 +422,11 @@ public static function exportErrorsInCSV()
header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
readfile($file);
unlink($file);
try {
readfile($file);
} finally {
unlink($file);
}
}
}
}
19 changes: 10 additions & 9 deletions inc/info.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -365,9 +365,9 @@ public static function showAdditionalInformation(
$value = ($option['default'] ?? '');
}

echo sprintf("<input type='text' name='%s' value='%s'", $name, $value);
echo sprintf("<input type='text' name='%s' value='%s'", htmlescape($name), htmlescape((string) $value));
if (isset($option['size'])) {
echo " size='" . $option['size'] . "'";
echo " size='" . (int) $option['size'] . "'";
}

echo ">";
Expand Down Expand Up @@ -411,7 +411,7 @@ public static function showAdditionalInformation(
break;

case 'multiline_text':
echo sprintf("<textarea cols='45' rows='5' name='%s'>%s</textarea>", $name, $value);
echo sprintf("<textarea cols='45' rows='5' name='%s'>%s</textarea>", htmlescape($name), htmlescape((string) $value));
break;

case 'dropdown_integer':
Expand Down Expand Up @@ -496,13 +496,14 @@ public static function dropdownTemplates($name, $table)

$values = [0 => Dropdown::EMPTY_VALUE];

$sql = "SELECT `id`, `template_name`
FROM `" . $table . "`
WHERE `is_template`=1 " .
getEntitiesRestrictRequest(' AND ', $table) .
"ORDER BY `template_name`";
$iterator = $DB->request([
'SELECT' => ['id', 'template_name'],
'FROM' => $table,
'WHERE' => ['is_template' => 1] + getEntitiesRestrictCriteria($table),
'ORDER' => 'template_name',
]);

foreach ($DB->doQuery($sql) as $data) {
foreach ($iterator as $data) {
$values[$data['id']] = $data['template_name'];
}

Expand Down
11 changes: 6 additions & 5 deletions inc/infocollection.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,13 @@ public function load($models_id)
/** @var DBmysql $DB */
global $DB;

$query = "SELECT *
FROM `glpi_plugin_datainjection_infos`
WHERE `models_id` = '" . $models_id . "'
ORDER BY `itemtype` ASC";
$iterator = $DB->request([
'FROM' => 'glpi_plugin_datainjection_infos',
'WHERE' => ['models_id' => (int) $models_id],
'ORDER' => 'itemtype ASC',
]);

foreach ($DB->doQuery($query) as $data) {
foreach ($iterator as $data) {
$infos = new PluginDatainjectionInfo();
$infos->fields = $data;
$this->infosCollection[] = $infos;
Expand Down
34 changes: 20 additions & 14 deletions inc/mapping.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
*/

use Glpi\Application\View\TemplateRenderer;
use Glpi\DBAL\QueryExpression;

use function Safe\ob_get_clean;
use function Safe\ob_start;
Expand Down Expand Up @@ -151,15 +152,18 @@ public static function getSeveralMappedField($models_id)
global $DB;

$several = [];
$query = "SELECT `value`,
COUNT(*) AS counter
FROM `glpi_plugin_datainjection_mappings`
WHERE `models_id` = '" . $models_id . "'
AND `value` NOT IN ('none')
GROUP BY `value`
HAVING `counter` > 1";

foreach ($DB->doQuery($query) as $mapping) {
$iterator = $DB->request([
'SELECT' => ['value', new QueryExpression('COUNT(*) AS counter')],
'FROM' => 'glpi_plugin_datainjection_mappings',
'WHERE' => [
'models_id' => (int) $models_id,
'NOT' => ['value' => 'none'],
],
'GROUPBY' => 'value',
'HAVING' => ['counter' => ['>', 1]],
]);

foreach ($iterator as $mapping) {
$several[] = $mapping['value'];
}

Expand All @@ -176,11 +180,13 @@ public static function getMappingsSortedByRank($models_id)
global $DB;

$mappings = [];
$query = "SELECT `name`
FROM `glpi_plugin_datainjection_mappings`
WHERE `models_id` = '" . $models_id . "'
ORDER BY `rank` ASC";
foreach ($DB->doQuery($query) as $data) {
$iterator = $DB->request([
'SELECT' => 'name',
'FROM' => 'glpi_plugin_datainjection_mappings',
'WHERE' => ['models_id' => (int) $models_id],
'ORDER' => 'rank ASC',
]);
foreach ($iterator as $data) {
$mappings[] = $data['name'];
}

Expand Down
11 changes: 6 additions & 5 deletions inc/mappingcollection.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,15 @@ public function load($models_id)
/** @var DBmysql $DB */
global $DB;

$sql = "SELECT *
FROM `glpi_plugin_datainjection_mappings`
WHERE `models_id` = '{$models_id}'
ORDER BY `rank` ASC";
$iterator = $DB->request([
'FROM' => 'glpi_plugin_datainjection_mappings',
'WHERE' => ['models_id' => (int) $models_id],
'ORDER' => 'rank ASC',
]);

$this->mappingCollection = [];

foreach ($data = $DB->doQuery($sql) as $data) {
foreach ($iterator as $data) {
$mapping = new PluginDatainjectionMapping();
$mapping->fields = $data;
$this->mappingCollection[] = $mapping;
Expand Down
11 changes: 8 additions & 3 deletions inc/model.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -1205,8 +1205,13 @@ public function isFileCorrect()
),
);
$name_from_db = trim(mb_strtoupper((string) $mapping->getName(), 'UTF-8'));
// Sample and error files are exported with formula-escaped headers
$escaped_name_from_db = trim(mb_strtoupper(
(string) PluginDatainjectionClientInjection::escapeCsvFormula((string) $mapping->getName()),
'UTF-8',
));

if ($name_from_db !== $name_from_file) {
if ($name_from_db !== $name_from_file && $escaped_name_from_db !== $name_from_file) {
if ($error['error_message'] == '') {
$error['error_message'] = __('At least one column is incorrect', 'datainjection');
}
Expand Down Expand Up @@ -1549,8 +1554,8 @@ public static function exportAsPDF($models_id)
$pdf->setHeader(
sprintf(
__('%1$s (%2$s)'),
__('Data injection report', 'datainjection') . ' - <b>' .
PluginDatainjectionSession::getParam('file_name') . '</b>',
__('Data injection report', 'datainjection') . ' - '
. PluginDatainjectionSession::getParam('file_name'),
$model->getName(),
),
);
Expand Down
12 changes: 11 additions & 1 deletion inc/modelcsv.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@

use Glpi\Application\View\TemplateRenderer;

use function Safe\fclose;
use function Safe\fopen;
use function Safe\fputcsv;
use function Safe\rewind;
use function Safe\stream_get_contents;

/**
* -------------------------------------------------------------------------
* DataInjection plugin for GLPI
Expand Down Expand Up @@ -119,7 +125,11 @@ public function showSample(PluginDatainjectionModel $model)
{

$headers = PluginDatainjectionMapping::getMappingsSortedByRank($model->fields['id']);
$sample = '"' . implode('"' . $this->getDelimiter() . '"', $headers) . "\"\n";
$handle = fopen('php://temp', 'r+');
fputcsv($handle, array_map(PluginDatainjectionClientInjection::escapeCsvFormula(...), $headers), $this->getDelimiter());
rewind($handle);
$sample = stream_get_contents($handle);
fclose($handle);

header(
'Content-disposition: attachment; filename="' . str_replace(
Expand Down
26 changes: 7 additions & 19 deletions inc/profile.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,21 +48,6 @@ public static function getAllRights()
];
}

/**
* Clean profiles_id from plugin's profile table
*
* @param int $ID
**/
public function cleanProfiles($ID)
{
/** @var DBmysql $DB */
global $DB;
$query = "DELETE FROM `glpi_profiles`
WHERE `profiles_id`='{$ID}'
AND `name` LIKE '%plugin_datainjection%'";
$DB->doQuery($query);
}

public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0)
{

Expand Down Expand Up @@ -147,10 +132,13 @@ public static function migrateProfiles()

$profiles = getAllDataFromTable('glpi_plugin_datainjection_profiles');
foreach ($profiles as $id => $profile) {
$query = "SELECT `id` FROM `glpi_profiles` WHERE `name`='" . $profile['name'] . "'";
$result = $DB->doQuery($query);
if ($DB->numrows($result) == 1) {
$id = $DB->result($result, 0, 'id');
$iterator = $DB->request([
'SELECT' => 'id',
'FROM' => 'glpi_profiles',
'WHERE' => ['name' => $profile['name']],
]);
if (count($iterator) === 1) {
$id = $iterator->current()['id'];
switch ($profile['model']) {
case 'r':
$value = READ;
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/AdditionalInformationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,23 @@ public function testFormInputIsNamedAfterItemtypeAndField(): void
self::assertStringContainsString("name='info[DeviceProcessor][designation]'", $html);
self::assertStringContainsString(DeviceProcessor::getTypeName(1) . ' - ', $html);
}

public function testPostedValueIsEscaped(): void
{
$this->login();

$info = new PluginDatainjectionInfo();
$info->fields = ['itemtype' => 'DeviceProcessor', 'value' => 'designation', 'is_mandatory' => 0];

$_SESSION['datainjection']['infos'] = ['DeviceProcessor' => ['designation' => "'><script>alert(1)</script>"]];

ob_start();
PluginDatainjectionInfo::displayAdditionalInformation($info);
$html = ob_get_clean();

unset($_SESSION['datainjection']['infos']);

self::assertStringNotContainsString('<script>', $html);
self::assertStringContainsString("value='&#039;&gt;&lt;script&gt;", $html);
}
}
2 changes: 2 additions & 0 deletions tests/unit/ClientInjectionEscapeCsvFormulaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ public static function escapeCsvFormulaProvider(): array
'plus trigger' => ['+1234', "'+1234"],
'minus trigger' => ['-1234', "'-1234"],
'at trigger' => ['@SUM(A1:A2)', "'@SUM(A1:A2)"],
'tab trigger' => ["\t=1", "'\t=1"],
'carriage return trigger' => ["\r=1", "'\r=1"],
'safe value passthrough' => ['normal value', 'normal value'],
'non-string passthrough' => [42, 42],
];
Expand Down
4 changes: 2 additions & 2 deletions tests/unit/ClientInjectionWriteErrorsCsvTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,9 @@ public function testEachCallUsesADistinctFile(): void

public function testContentContainsHeadersAndEscapedLines(): void
{
$file = $this->writeErrorsCsv([['=SUM(A1)', 'safe']], ['name', 'serial']);
$file = $this->writeErrorsCsv([['=SUM(A1)', 'safe']], ['=name', 'serial']);

$this->assertSame("name;serial\n'=SUM(A1);safe\n", file_get_contents($file));
$this->assertSame("'=name;serial\n'=SUM(A1);safe\n", file_get_contents($file));
}

public function testDiscardClosesHandleAndRemovesFile(): void
Expand Down
Loading