From 70941a6c42168f23fade7d550a6c0a5a5ae530e5 Mon Sep 17 00:00:00 2001 From: Rom1-B <8530352+Rom1-B@users.noreply.github.com> Date: Fri, 28 Aug 2026 08:08:17 +0200 Subject: [PATCH 1/3] Fix(CI): rector --- ajax/dropdownChooseField.php | 2 +- ajax/dropdownMandatory.php | 2 +- ajax/dropdownSelectModel.php | 2 +- ajax/injection.php | 2 +- ajax/results.php | 2 +- front/clientinjection.form.php | 1 + front/info.form.php | 2 + front/mapping.form.php | 1 + front/model.form.php | 5 +- hook.php | 22 +- inc/backend.class.php | 10 +- inc/backendcsv.class.php | 26 +- inc/categoryinjection.class.php | 2 +- inc/clientinjection.class.php | 17 +- inc/commoninjectionlib.class.php | 227 +++++++++++------- inc/computer_iteminjection.class.php | 37 +-- inc/contact_supplierinjection.class.php | 11 +- inc/contract_iteminjection.class.php | 28 +-- inc/contract_supplierinjection.class.php | 15 +- inc/data.class.php | 4 +- inc/devicecaseinjection.class.php | 1 + inc/devicecontrolinjection.class.php | 1 + inc/devicedriveinjection.class.php | 1 + inc/deviceharddriveinjection.class.php | 1 + inc/devicememoryinjection.class.php | 1 + inc/devicemotherboardinjection.class.php | 1 + inc/devicenetworkcardinjection.class.php | 1 + inc/deviceprocessorinjection.class.php | 1 + inc/dropdown.class.php | 71 +----- inc/engine.class.php | 20 +- inc/entityinjection.class.php | 16 +- inc/info.class.php | 45 ++-- inc/infocollection.class.php | 9 +- inc/infocominjection.class.php | 2 +- inc/injectiontype.class.php | 28 ++- inc/interfacetypeinjection.class.php | 1 + inc/item_operatingsysteminjection.class.php | 6 +- inc/item_softwarelicenseinjection.class.php | 33 +-- inc/item_softwareversioninjection.class.php | 34 +-- inc/mapping.class.php | 3 + inc/mappingcollection.class.php | 12 +- inc/menu.class.php | 2 +- inc/model.class.php | 129 +++++----- inc/modelcsv.class.php | 3 + inc/monitorinjection.class.php | 1 + inc/networknameinjection.class.php | 6 +- inc/networkportinjection.class.php | 18 +- inc/notepadinjection.class.php | 6 +- inc/peripheralinjection.class.php | 1 + inc/phoneinjection.class.php | 1 + inc/printerinjection.class.php | 3 + inc/profile.class.php | 11 +- inc/profileinjection.class.php | 35 +-- inc/session.class.php | 23 +- inc/softwareinjection.class.php | 5 + inc/softwarelicenseinjection.class.php | 4 +- inc/softwareversioninjection.class.php | 11 +- inc/userinjection.class.php | 3 +- rector.php | 87 ++----- setup.php | 5 +- tests/unit/CommonInjectionLibDateTimeTest.php | 1 + .../CommonInjectionLibFloatDetectionTest.php | 4 +- tests/unit/GroupInjectionTest.php | 5 + 63 files changed, 475 insertions(+), 595 deletions(-) diff --git a/ajax/dropdownChooseField.php b/ajax/dropdownChooseField.php index 765bd9c8..4ccde6e0 100644 --- a/ajax/dropdownChooseField.php +++ b/ajax/dropdownChooseField.php @@ -29,7 +29,7 @@ */ // Direct access to file -if (strpos($_SERVER['PHP_SELF'], "dropdownChooseField.php")) { +if (strpos((string) $_SERVER['PHP_SELF'], "dropdownChooseField.php")) { header("Content-Type: text/html; charset=UTF-8"); Html::header_nocache(); } diff --git a/ajax/dropdownMandatory.php b/ajax/dropdownMandatory.php index 6fd57756..1dc0e8f4 100644 --- a/ajax/dropdownMandatory.php +++ b/ajax/dropdownMandatory.php @@ -29,7 +29,7 @@ */ // Direct access to file -if (strpos($_SERVER['PHP_SELF'], "dropdownMandatory.php")) { +if (strpos((string) $_SERVER['PHP_SELF'], "dropdownMandatory.php")) { header("Content-Type: text/html; charset=UTF-8"); Html::header_nocache(); } diff --git a/ajax/dropdownSelectModel.php b/ajax/dropdownSelectModel.php index 5fe9b305..ca7844f4 100644 --- a/ajax/dropdownSelectModel.php +++ b/ajax/dropdownSelectModel.php @@ -29,7 +29,7 @@ */ // Direct access to file -if (strpos($_SERVER['PHP_SELF'], "dropdownSelectModel.php")) { +if (strpos((string) $_SERVER['PHP_SELF'], "dropdownSelectModel.php")) { header("Content-Type: text/html; charset=UTF-8"); Html::header_nocache(); } diff --git a/ajax/injection.php b/ajax/injection.php index 76581502..b8980c12 100644 --- a/ajax/injection.php +++ b/ajax/injection.php @@ -29,7 +29,7 @@ */ // Direct access to file -if (strpos($_SERVER['PHP_SELF'], "injection.php")) { +if (strpos((string) $_SERVER['PHP_SELF'], "injection.php")) { header("Content-Type: text/html; charset=UTF-8"); Html::header_nocache(); } diff --git a/ajax/results.php b/ajax/results.php index 1d64dfb7..6c76fde5 100644 --- a/ajax/results.php +++ b/ajax/results.php @@ -29,7 +29,7 @@ */ // Direct access to file -if (strpos($_SERVER['PHP_SELF'], "results.php")) { +if (strpos((string) $_SERVER['PHP_SELF'], "results.php")) { header("Content-Type: text/html; charset=UTF-8"); Html::header_nocache(); } diff --git a/front/clientinjection.form.php b/front/clientinjection.form.php index 303e3404..4610c796 100644 --- a/front/clientinjection.form.php +++ b/front/clientinjection.form.php @@ -98,6 +98,7 @@ if (isset($_GET['id'])) { // Allow link to a model PluginDatainjectionSession::setParam('models_id', $_GET['id']); } + $clientInjection = new PluginDatainjectionClientInjection(); $clientInjection->title(); $clientInjection->showForm(0); diff --git a/front/info.form.php b/front/info.form.php index 9c0f1f53..5f21cb55 100644 --- a/front/info.form.php +++ b/front/info.form.php @@ -44,7 +44,9 @@ $info->delete($input); } } + Html::back(); } + Session::setActiveTab('PluginDatainjectionModel', 'PluginDatainjectionModel$5'); Html::back(); diff --git a/front/mapping.form.php b/front/mapping.form.php index 5ce50cd5..8e99af94 100644 --- a/front/mapping.form.php +++ b/front/mapping.form.php @@ -80,6 +80,7 @@ ), ); } + unset($_SESSION['datainjection']['lines']); } } diff --git a/front/model.form.php b/front/model.form.php index 0c9d38b6..95f32e3c 100644 --- a/front/model.form.php +++ b/front/model.form.php @@ -48,7 +48,7 @@ //Set display to the advanced options tab Session::setActiveTab('PluginDatainjectionModel', 'PluginDatainjectionModel$3'); - Html::redirect(Toolbox::getItemTypeFormURL('PluginDatainjectionModel') . "?id=$newID"); + Html::redirect(Toolbox::getItemTypeFormURL('PluginDatainjectionModel') . ('?id=' . $newID)); } elseif (isset($_POST["delete"])) { /* delete */ $model->check($_POST['id'], DELETE); @@ -74,7 +74,7 @@ $model->switchReadyToUse(); Html::back(); } elseif (isset($_POST['upload'])) { - if (!empty($_FILES)) { + if ($_FILES !== []) { $model->check($_POST['id'], UPDATE); if ( @@ -95,6 +95,7 @@ ); } } + Html::back(); } elseif (isset($_GET['sample'])) { $model->check($_GET['sample'], READ); diff --git a/hook.php b/hook.php index 9232cc49..05a0a021 100644 --- a/hook.php +++ b/hook.php @@ -251,7 +251,7 @@ function plugin_datainjection_migration_2158_2159(Migration $migration) 'glpi_plugin_datainjection_models', 'entities_id', 'entities_id', - "int {$default_key_sign} NOT NULL default '0'", + sprintf("int %s NOT NULL default '0'", $default_key_sign), ); $migration->executeMigration(); @@ -404,7 +404,7 @@ function plugin_datainjection_update131_14() 'glpi_plugin_data_injection_models', 'user_id', 'FK_users', - "int {$default_key_sign} NOT NULL default '0'", + sprintf("int %s NOT NULL default '0'", $default_key_sign), ); $migration->changeField( 'glpi_plugin_data_injection_models', @@ -510,7 +510,7 @@ function plugin_datainjection_update170_20() 'glpi_plugin_datainjection_models', 'FK_entities', 'entities_id', - "int {$default_key_sign} NOT NULL default '0'", + sprintf("int %s NOT NULL default '0'", $default_key_sign), ); $migration->changeField( 'glpi_plugin_datainjection_models', @@ -522,7 +522,7 @@ function plugin_datainjection_update170_20() 'glpi_plugin_datainjection_models', 'FK_users', 'users_id', - "int {$default_key_sign} NOT NULL default '0'", + sprintf("int %s NOT NULL default '0'", $default_key_sign), ); $migration->changeField( 'glpi_plugin_datainjection_models', @@ -532,6 +532,7 @@ function plugin_datainjection_update170_20() ); $migration->migrationOneTable('glpi_plugin_datainjection_models'); + $query = "UPDATE `glpi_plugin_datainjection_models` SET `step` = '5'"; $DB->doQuery($query); @@ -551,7 +552,7 @@ function plugin_datainjection_update170_20() 'glpi_plugin_datainjection_modelcsvs', 'model_id', 'models_id', - "int {$default_key_sign} NOT NULL default '0'", + sprintf("int %s NOT NULL default '0'", $default_key_sign), ); $migration->changeField( 'glpi_plugin_datainjection_modelcsvs', @@ -585,7 +586,7 @@ function plugin_datainjection_update170_20() 'glpi_plugin_datainjection_mappings', 'model_id', 'models_id', - "int {$default_key_sign} NOT NULL default '0'", + sprintf("int %s NOT NULL default '0'", $default_key_sign), ); $migration->changeField( @@ -599,7 +600,7 @@ function plugin_datainjection_update170_20() 'glpi_plugin_datainjection_infos', 'model_id', 'models_id', - "int {$default_key_sign} NOT NULL default '0'", + sprintf("int %s NOT NULL default '0'", $default_key_sign), ); $migration->changeField( 'glpi_plugin_datainjection_infos', @@ -1854,6 +1855,7 @@ function plugin_datainjection_update170_20() ]; $foreignkeys = Plugin::doHookFunction("plugin_datainjection_migratefields", $foreignkeys); + $query = "SELECT `itemtype`, `value` FROM `glpi_plugin_datainjection_mappings` WHERE `itemtype` NOT IN ('none') @@ -1908,6 +1910,7 @@ function plugin_datainjection_update210_220() $DB->doQuery($query); } } + function plugin_datainjection_update220_230() { /** @var DBmysql $DB */ @@ -1942,7 +1945,7 @@ function plugin_datainjection_loadHook($hook_name, $params = []) ); } elseif (isset($PLUGIN_HOOKS['plugin_types'])) { //Browse all plugins - foreach ($PLUGIN_HOOKS['plugin_types'] as $type => $name) { + foreach ($PLUGIN_HOOKS['plugin_types'] as $name) { Plugin::doOneHook($name, 'datainjection_' . $hook_name); } } @@ -1988,6 +1991,7 @@ function plugin_datainjection_addDefaultWhere($itemtype) foreach ($models as $model) { $tab[] = $model['id']; } + return "`glpi_plugin_datainjection_models`.`id` IN ('" . implode("','", $tab) . "')"; } else { return "1 = 0"; //no model available -> force WHERE clause to get no result @@ -1996,4 +2000,6 @@ function plugin_datainjection_addDefaultWhere($itemtype) default: break; } + + return null; } diff --git a/inc/backend.class.php b/inc/backend.class.php index be68d99c..9e49c18f 100644 --- a/inc/backend.class.php +++ b/inc/backend.class.php @@ -37,13 +37,19 @@ abstract class PluginDatainjectionBackend { protected $file = ""; + protected $delimiter = ""; + protected $encoding; + protected $errmsg; + protected $numberOfLines = 0; public const ENCODING_ISO8859_1 = 0; + public const ENCODING_UFT8 = 1; + public const ENCODING_AUTO = 2; @@ -67,6 +73,7 @@ public static function getHeader($injectionData, $header_present) for ($i = 0; $i < $nb; $i++) { $header[] = $i; } + return $header; } @@ -83,7 +90,7 @@ public static function getInstance($type) ]; if (!isset($allowedBackends[$type])) { - throw new InvalidArgumentException("Unknown backend type: $type"); + throw new InvalidArgumentException('Unknown backend type: ' . $type); } return new $allowedBackends[$type](); @@ -118,6 +125,7 @@ public static function toUTF8($string) if (!self::is_utf8($string)) { return Toolbox::encodeInUtf8($string); } + return $string; } } diff --git a/inc/backendcsv.class.php b/inc/backendcsv.class.php index a2863be3..2c579b63 100644 --- a/inc/backendcsv.class.php +++ b/inc/backendcsv.class.php @@ -37,7 +37,8 @@ class PluginDatainjectionBackendcsv extends PluginDatainjectionBackend implements PluginDatainjectionBackendInterface { private $isHeaderPresent = true; - private $file_handler = null; + + private $file_handler; public function __construct() @@ -95,20 +96,14 @@ public static function parseLine($fic, $data, $encoding = 1) $num = count($data); for ($c = 0; $c < $num; $c++) { - $tmp = trim($data[$c]); - switch ($encoding) { - case PluginDatainjectionBackend::ENCODING_ISO8859_1: - $csv[0][] = $tmp === '' || $tmp === '0' ? Toolbox::encodeInUtf8($tmp) : $tmp; - break; - - case PluginDatainjectionBackend::ENCODING_UFT8: - $csv[0][] = $tmp; - break; - - default: - $csv[0][] = PluginDatainjectionBackend::toUTF8($tmp); - } + $tmp = trim((string) $data[$c]); + $csv[0][] = match ($encoding) { + PluginDatainjectionBackend::ENCODING_ISO8859_1 => $tmp === '' || $tmp === '0' ? Toolbox::encodeInUtf8($tmp) : $tmp, + PluginDatainjectionBackend::ENCODING_UFT8 => $tmp, + default => PluginDatainjectionBackend::toUTF8($tmp), + }; } + return $csv; } @@ -175,6 +170,7 @@ public function storeNumberOfLines() } } } + fclose($fic); if ($this->isHeaderPresent) { @@ -229,6 +225,7 @@ public function getNextLine() if ($data === false) { return false; } + $line = []; if ( (count($data) > 1) @@ -236,6 +233,7 @@ public function getNextLine() ) { $line = self::parseLine($this->file_handler, $data, $this->encoding); } + return $line; } diff --git a/inc/categoryinjection.class.php b/inc/categoryinjection.class.php index e5807ee4..192230b1 100644 --- a/inc/categoryinjection.class.php +++ b/inc/categoryinjection.class.php @@ -50,7 +50,7 @@ public function connectedTo() public function isNullable($field) { - return !in_array($field, ['illustration']); + return $field != 'illustration'; } /** diff --git a/inc/clientinjection.class.php b/inc/clientinjection.class.php index 3531b5da..661b8d47 100644 --- a/inc/clientinjection.class.php +++ b/inc/clientinjection.class.php @@ -47,7 +47,9 @@ class PluginDatainjectionClientInjection public static $rightname = "plugin_datainjection_use"; public const STEP_UPLOAD = 0; + public const STEP_PROCESS = 1; + public const STEP_RESULT = 2; /** @@ -153,6 +155,7 @@ public static function showInjectionForm(PluginDatainjectionModel $model, $entit $lines[] = $line; $line = $backend->getNextLine(); } + $backend->closeFile(); //Store lines in session for batch processing @@ -188,14 +191,15 @@ public static function processBatch(int $offset, int $batch_size): array { try { ini_set("max_execution_time", "0"); - } catch (InfoException $e) { - ErrorHandler::logCaughtException($e); + } catch (InfoException $infoException) { + ErrorHandler::logCaughtException($infoException); } Profile::getCurrent()->disable(); $model = PluginDatainjectionSession::unserialize($_SESSION['datainjection']['currentmodel']); $model->loadSpecificModel(); + $entities_id = $_SESSION['glpiactive_entity']; $lines_json = PluginDatainjectionSession::getParam('injection_lines'); $lines = json_decode($lines_json, true); @@ -226,6 +230,7 @@ public static function processBatch(int $offset, int $batch_size): array 'line' => $injectionline, ]; } + $results[] = $result; if ($result['status'] != PluginDatainjectionCommonInjectionLib::SUCCESS) { @@ -314,7 +319,7 @@ public static function showResultsForm(PluginDatainjectionModel $model) 'popup_url' => plugin_datainjection_geturl() . "front/popup.php?popup=log&models_id=" . $model->fields['id'], 'model_id' => $model->fields['id'], 'has_pdf' => $plugin->isActivated('pdf'), - 'has_errors' => !empty($error_lines), + 'has_errors' => !in_array($error_lines, ['', '0', []], true), ]; TemplateRenderer::getInstance()->display('@datainjection/clientinjection_result.html.twig', $data); @@ -325,6 +330,7 @@ private static function escapeCsvFormula(mixed $value): mixed if (is_string($value) && isset($value[0]) && in_array($value[0], ['=', '+', '-', '@'], true)) { return "'" . $value; } + return $value; } @@ -334,7 +340,7 @@ public static function exportErrorsInCSV() $error_lines = json_decode(PluginDatainjectionSession::getParam('error_lines'), true); self::stripslashes_array($error_lines); - if (!empty($error_lines)) { + if (!in_array($error_lines, ['', '0', []], true)) { $model = PluginDatainjectionSession::unserialize(PluginDatainjectionSession::getParam('currentmodel')); $file = PLUGIN_DATAINJECTION_UPLOAD_DIR . basename(PluginDatainjectionSession::getParam('file_name')); @@ -349,8 +355,9 @@ public static function exportErrorsInCSV() //Write lines foreach ($error_lines as $line) { - fputcsv($tmpfile, array_map([self::class, 'escapeCsvFormula'], $line), $model->getBackend()->getDelimiter()); + fputcsv($tmpfile, array_map(self::escapeCsvFormula(...), $line), $model->getBackend()->getDelimiter()); } + fclose($tmpfile); $name = "Error-" . basename(PluginDatainjectionSession::getParam('file_name')); diff --git a/inc/commoninjectionlib.class.php b/inc/commoninjectionlib.class.php index 0464274a..d0b75ea6 100644 --- a/inc/commoninjectionlib.class.php +++ b/inc/commoninjectionlib.class.php @@ -41,17 +41,11 @@ class PluginDatainjectionCommonInjectionLib //Injection results private $results = []; - //Values to inject - private $values = []; - //Fields mandatory for injection private $mandatory_fields = []; private $optional_infos = []; - //Injection class to use - private $injectionClass; - //Primary type to inject private $primary_type; @@ -71,51 +65,76 @@ class PluginDatainjectionCommonInjectionLib //Type of action to perform public const IMPORT_ADD = 0; + public const IMPORT_UPDATE = 1; + public const IMPORT_DELETE = 2; //Action return constants - public const SUCCESS = 10; //Injection OK - public const FAILED = 11; //Error during injection + public const SUCCESS = 10; + + //Injection OK + public const FAILED = 11; + + //Error during injection public const WARNING = 12; //Injection ok but partial //Field check return constants public const TYPE_MISMATCH = 22; + public const MANDATORY = 23; + public const ITEM_NOT_FOUND = 24; //Injection Message public const ERROR_CANNOT_IMPORT = 31; + public const ERROR_CANNOT_UPDATE = 32; + public const WARNING_NOTFOUND = 33; + public const ERROR_FIELDSIZE_EXCEEDED = 37; + public const ERROR_IMPORT_REFUSED = 39; //Dictionnary explicitly refuse import //Empty values public const EMPTY_VALUE = ''; + public const DROPDOWN_EMPTY_VALUE = 0; //Format constants - public const FLOAT_TYPE_COMMA = 0; //xxxx,xx - public const FLOAT_TYPE_DOT = 1; //xxxx.xx + public const FLOAT_TYPE_COMMA = 0; + + //xxxx,xx + public const FLOAT_TYPE_DOT = 1; + + //xxxx.xx public const FLOAT_TYPE_DOT_AND_COM = 2; //xx,xxx.xx //Date management constants public const DATE_TYPE_DDMMYYYY = "dd-mm-yyyy"; + public const DATE_TYPE_MMDDYYYY = "mm-dd-yyyy"; + public const DATE_TYPE_YYYYMMDD = "yyyy-mm-dd"; //Port unicity constants public const UNICITY_NETPORT_LOGICAL_NUMBER = 0; + public const UNICITY_NETPORT_NAME = 1; + public const UNICITY_NETPORT_MACADDRESS = 2; + public const UNICITY_NETPORT_LOGICAL_NUMBER_NAME = 3; + public const UNICITY_NETPORT_LOGICAL_NUMBER_MAC = 4; + public const UNICITY_NETPORT_LOGICAL_NUMBER_NAME_MAC = 5; //Field status must evolve when ticket #2216 will be resolved public const FIELD_INJECTABLE = 1; + public const FIELD_VIRTUAL = 2; @@ -164,7 +183,7 @@ public function setDefaultValues(): void * * @return void nothing **/ - public function __construct($injectionClass, $values = [], $injection_options = []) + public function __construct(private $injectionClass, private $values = [], $injection_options = []) { $this->setDefaultValues(); @@ -180,6 +199,7 @@ public function __construct($injectionClass, $values = [], $injection_options = $this->checks[$key] = $value; } } + if (isset($injection_options['rights'])) { foreach ($injection_options['rights'] as $key => $value) { $this->rights[$key] = $value; @@ -203,12 +223,7 @@ public function __construct($injectionClass, $values = [], $injection_options = ]; } - //Store values to inject - $this->values = $values; - - //Store injectClass & primary_type - $this->injectionClass = $injectionClass; - $this->primary_type = self::getItemtypeByInjectionClass($injectionClass); + $this->primary_type = self::getItemtypeByInjectionClass($this->injectionClass); //If entity is given stores it, then use root entity $this->entity = $injection_options['entities_id'] ?? 0; @@ -268,6 +283,7 @@ public function areTypeMandatoryFieldsOK($injectionClass) __('No mandatory field is defined for this model', 'datainjection'), ]; } + return $status_check; } @@ -303,10 +319,12 @@ public static function getItemtypeInstanceByInjection($injectionClassName) if (!is_a($injectionClassName, PluginDatainjectionInjectionInterface::class, true)) { throw new HttpException(500, 'Class ' . $injectionClassName . ' is not a valid class'); } + $injection = self::getItemtypeByInjectionClass(new $injectionClassName()); if (!is_a($injection, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $injection . ' is not a valid class'); } + return new $injection(); } @@ -323,6 +341,7 @@ public static function getItemtypeByInjection($injectionClassName) if (!is_a($injectionClassName, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $injectionClassName . ' is not a valid class'); } + return self::getItemtypeByInjectionClass(new $injectionClassName()); } @@ -361,6 +380,7 @@ public static function getInjectionClassInstance($itemtype) if (!is_a($injectionClass, PluginDatainjectionInjectionInterface::class, true)) { throw new HttpException(500, 'Class ' . $injectionClass . ' is not a valid class'); } + return new $injectionClass(); } @@ -432,6 +452,7 @@ public static function getBlacklistedOptions($itemtype) if (!is_numeric($raw_option['id'])) { continue; } + $blacklist[] = $raw_option['id']; } @@ -506,7 +527,7 @@ private function getFloatFormat() private function getItemInstance() { - $classname = get_class($this->injectionClass); + $classname = $this->injectionClass::class; return self::getItemtypeInstanceByInjection($classname); } @@ -586,8 +607,6 @@ private function getFieldValue( switch ($searchOption['displaytype']) { case 'tree': - $this->setValueForItemtype($itemtype, $linkfield, $value); - break; case 'decimal': case 'text': @@ -605,6 +624,7 @@ private function getFieldValue( $this->setValueForItemtype($itemtype, $linkfield . "2", $value); } } + break; case 'dropdown': @@ -613,6 +633,7 @@ private function getFieldValue( if (!is_a($tmptype, CommonDBTM::class, true)) { return; } + $item = new $tmptype(); if ($item instanceof CommonTreeDropdown) { // use findID instead of getID @@ -627,6 +648,7 @@ private function getFieldValue( if (strpos($input['completename'], '>')) { $crit = 'completename'; } + $entity = new Entity(); $result = $entity->getFromDBByCrit( [ @@ -637,6 +659,7 @@ private function getFieldValue( if ($result !== false) { $input['entities_id'] = $entity->fields['id']; } + $sons = getSonsOf('glpi_entities', $input['entities_id']); if ($result === false && !empty($sons)) { foreach ($sons as $son_id) { @@ -652,6 +675,7 @@ private function getFieldValue( } } } + $id = $input['entities_id']; } elseif ($item->canCreate() && $this->rights['add_dropdown']) { $id = $item->import($input); @@ -668,34 +692,38 @@ private function getFieldValue( $canadd, ); } else { - $id = self::findSingle($item, $searchOption, $this->entity, $value); + $id = $this->findSingle($item, $searchOption, $this->entity, $value); } + // Use EMPTY_VALUE for Mandatory field check $this->setValueForItemtype($itemtype, $linkfield, ($id > 0 ? $id : self::EMPTY_VALUE)); if ($value && $id <= 0) { $this->results['status'] = self::WARNING; $this->results[self::ACTION_CHECK]['status'] = self::WARNING; $this->results[self::ACTION_CHECK][] = [self::WARNING_NOTFOUND, - $searchOption['name'] . "='$value'", + $searchOption['name'] . sprintf("='%s'", $value), ]; } + break; case 'template': - $id = self::getTemplateIDByName($itemtype, $value); + $id = $this->getTemplateIDByName($itemtype, $value); if ($id) { //Template id is stored into the item's id : when adding the object //glpi will understand that it needs to take fields from the template $this->setValueForItemtype($itemtype, '_oldID', $id); } + break; case 'contact': if ($value === self::EMPTY_VALUE || $value == self::DROPDOWN_EMPTY_VALUE || $value === Dropdown::EMPTY_VALUE) { $id = self::DROPDOWN_EMPTY_VALUE; } else { - $id = self::findContact($value, $this->entity); + $id = $this->findContact($value, $this->entity); } + $this->setValueForItemtype($itemtype, $linkfield, $id); break; @@ -703,8 +731,9 @@ private function getFieldValue( if ($value === self::EMPTY_VALUE || $value == self::DROPDOWN_EMPTY_VALUE || $value === Dropdown::EMPTY_VALUE) { $id = self::DROPDOWN_EMPTY_VALUE; } else { - $id = self::findUser($value, $this->entity); + $id = $this->findUser($value, $this->entity); } + $this->setValueForItemtype($itemtype, $linkfield, $id); break; @@ -763,6 +792,7 @@ private function addExternalDropdownParameters($itemtype) $external[$addvalue] = ''; } } + return $external; } @@ -775,7 +805,7 @@ private function addExternalDropdownParameters($itemtype) * * @return int|string the user ID if found or '' **/ - private static function findUser($value, $entity) + private function findUser($value, $entity) { /** @var DBmysql $DB */ global $DB; @@ -786,9 +816,9 @@ private static function findUser($value, $entity) 'FROM' => 'glpi_users', 'WHERE' => [ 'OR' => [ - new QueryExpression("LOWER(`name`) = $safe_lower"), - new QueryExpression("CONCAT(LOWER(`realname`),' ',LOWER(`firstname`)) = $safe_lower"), - new QueryExpression("CONCAT(LOWER(`firstname`),' ',LOWER(`realname`)) = $safe_lower"), + new QueryExpression('LOWER(`name`) = ' . $safe_lower), + new QueryExpression("CONCAT(LOWER(`realname`),' ',LOWER(`firstname`)) = " . $safe_lower), + new QueryExpression("CONCAT(LOWER(`firstname`),' ',LOWER(`realname`)) = " . $safe_lower), ], ], ]); @@ -799,8 +829,10 @@ private static function findUser($value, $entity) if (in_array($entity, $entities)) { return $ID; } + return self::DROPDOWN_EMPTY_VALUE; } + return self::DROPDOWN_EMPTY_VALUE; } @@ -813,7 +845,7 @@ private static function findUser($value, $entity) * * @return int|string the user ID if found or '' */ - private static function findContact($value, $entity) + private function findContact($value, $entity) { /** @var DBmysql $DB */ global $DB; @@ -825,9 +857,9 @@ private static function findContact($value, $entity) 'WHERE' => [ 'entities_id' => $entity, 'OR' => [ - new QueryExpression("LOWER(`name`) = $safe_lower"), - new QueryExpression("CONCAT(LOWER(`name`),' ',LOWER(`firstname`)) = $safe_lower"), - new QueryExpression("CONCAT(LOWER(`firstname`),' ',LOWER(`name`)) = $safe_lower"), + new QueryExpression('LOWER(`name`) = ' . $safe_lower), + new QueryExpression("CONCAT(LOWER(`name`),' ',LOWER(`firstname`)) = " . $safe_lower), + new QueryExpression("CONCAT(LOWER(`firstname`),' ',LOWER(`name`)) = " . $safe_lower), ], ], ]); @@ -835,6 +867,7 @@ private static function findContact($value, $entity) if (count($result) > 0) { return $result->current()['id']; } + return self::DROPDOWN_EMPTY_VALUE; } @@ -849,7 +882,7 @@ private static function findContact($value, $entity) * * @return int|string the id of the item found **/ - private static function findSingle($item, $searchOption, $entity, $value) + private function findSingle($item, $searchOption, $entity, $value) { /** @var DBmysql $DB */ global $DB; @@ -880,6 +913,7 @@ private static function findSingle($item, $searchOption, $entity, $value) if (count($result) > 0) { return $result->current()['id']; } + return self::DROPDOWN_EMPTY_VALUE; } @@ -911,6 +945,7 @@ private function getValueByItemtypeAndName($itemtype, $field) if ($values) { return ($values[$field] ?? false); } + return false; } @@ -944,6 +979,7 @@ private function setValueForItemtype($itemtype, $field, $value, $fromdb = false) if ($itemtype === User::class && $field === "pdffont" && $fromdb) { return; } + $injectionClass = self::getInjectionClassInstance($itemtype); // TODO awfull hack, text ftom CSV set more than once, so check if "another" value if (isset($this->values[$itemtype][$field]) && $this->values[$itemtype][$field] != $value) { @@ -1004,13 +1040,14 @@ private function setValueForItemtype($itemtype, $field, $value, $fromdb = false) * * @return string|false name of the template or false is no template found **/ - private static function getTemplateIDByName($itemtype, $name) + private function getTemplateIDByName($itemtype, $name) { /** @var DBmysql $DB */ global $DB; if (!is_a($itemtype, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $itemtype . ' is not a valid class'); } + new $itemtype(); $result = $DB->request([ 'SELECT' => ['id'], @@ -1024,6 +1061,7 @@ private static function getTemplateIDByName($itemtype, $name) if (count($result) > 0) { return $result->current()['id']; } + return false; } @@ -1111,22 +1149,22 @@ private function reformatThirdPass() case "date": //If the value is a date, try to reformat it if it's not the good type //(dd-mm-yyyy instead of yyyy-mm-dd) - $date = self::reformatDate($value, $this->getDateFormat()); + $date = $this->reformatDate($value, $this->getDateFormat()); $this->setValueForItemtype($itemtype, $field, $date); break; case "datetime": //Normalize to "Y-m-d H:i:s", stripping ISO8601 microseconds/timezone if present - $datetime = self::reformatDateTime($value, $this->getDateFormat()); + $datetime = $this->reformatDateTime($value, $this->getDateFormat()); $this->setValueForItemtype($itemtype, $field, $datetime); break; case "mac": - $this->setValueForItemtype($itemtype, $field, self::reformatMacAddress($value)); + $this->setValueForItemtype($itemtype, $field, $this->reformatMacAddress($value)); break; case "float": - $float = self::reformatFloat($value, $this->getFloatFormat()); + $float = $this->reformatFloat($value, $this->getFloatFormat()); $this->setValueForItemtype($itemtype, $field, (string) $float); break; @@ -1165,7 +1203,7 @@ private function reformat() * * @return float|array modified as expected in GLPI **/ - private static function reformatFloat($value, $format) + private function reformatFloat($value, $format) { if ($value == self::EMPTY_VALUE) { @@ -1173,23 +1211,17 @@ private static function reformatFloat($value, $format) } //TODO : replace str_replace by a regex - switch ($format) { - case self::FLOAT_TYPE_COMMA: - $value = str_replace( - [" ", ","], - ["","."], - $value, - ); - break; - - case self::FLOAT_TYPE_DOT: - $value = str_replace(" ", "", $value); - break; + $value = match ($format) { + self::FLOAT_TYPE_COMMA => str_replace( + [" ", ","], + ["","."], + $value, + ), + self::FLOAT_TYPE_DOT => str_replace(" ", "", $value), + self::FLOAT_TYPE_DOT_AND_COM => str_replace(",", "", $value), + default => $value, + }; - case self::FLOAT_TYPE_DOT_AND_COM: - $value = str_replace(",", "", $value); - break; - } return $value; } @@ -1202,12 +1234,13 @@ private static function reformatFloat($value, $format) * * @return string the date reformated, if needed **/ - private static function reformatDate($original_date, $date_format) + private function reformatDate($original_date, $date_format) { if (empty($original_date)) { return "NULL"; // required to avoid "0000-00-00" in the DB } + $new_date = ""; switch ($date_format) { case self::DATE_TYPE_YYYYMMDD: @@ -1235,9 +1268,10 @@ private static function reformatDate($original_date, $date_format) break; } - if (preg_match('/[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}/', $new_date) !== 0) { + if (preg_match('/\d{2,4}-\d{1,2}-\d{1,2}/', $new_date) !== 0) { return $new_date; } + return $original_date; } @@ -1252,7 +1286,7 @@ private static function reformatDate($original_date, $date_format) * * @return string the datetime reformated, if needed **/ - private static function reformatDateTime($original_datetime, $date_format) + private function reformatDateTime($original_datetime, $date_format) { if (empty($original_datetime)) { @@ -1271,7 +1305,7 @@ private static function reformatDateTime($original_datetime, $date_format) $time_part = '00:00:00'; } - $new_date = self::reformatDate($date_part, $date_format); + $new_date = $this->reformatDate($date_part, $date_format); if ($new_date === "NULL") { return "NULL"; } @@ -1287,7 +1321,7 @@ private static function reformatDateTime($original_datetime, $date_format) * * @return string the mac address modified, if needed **/ - private static function reformatMacAddress($mac) + private function reformatMacAddress($mac) { $pattern = "/^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})"; @@ -1300,10 +1334,11 @@ private static function reformatMacAddress($mac) unset($results[0]); foreach ($results as $result) { - $mac .= (!$first ? ":" : "") . $result; + $mac .= ($first ? "" : ":") . $result; $first = false; } } + return $mac; } @@ -1357,7 +1392,7 @@ private function check() $mandatory, ); $this->results[self::ACTION_CHECK][] = [$check_result, - $field . "='$value'", + $field . sprintf("='%s'", $value), ]; if ($check_result != self::SUCCESS) { @@ -1417,7 +1452,7 @@ private function checkType($injectionClass, $option, $field_name, $data, $mandat //If no data provided AND this mapping is not mandatory if ( !$mandatory - && ($data == null || $data == "NULL" || $data == self::EMPTY_VALUE) + && (in_array($data, [null, "NULL", self::EMPTY_VALUE])) ) { return self::SUCCESS; } @@ -1428,9 +1463,11 @@ private function checkType($injectionClass, $option, $field_name, $data, $mandat if (isset($option['displaytype']) && $option['displaytype'] == 'multiline_text') { return self::SUCCESS; } - if (strlen($data) > 255) { + + if (strlen((string) $data) > 255) { return self::ERROR_FIELDSIZE_EXCEEDED; } + return self::SUCCESS; case 'integer': @@ -1442,18 +1479,18 @@ private function checkType($injectionClass, $option, $field_name, $data, $mandat case 'date': // Date is already "reformat" according to getDateFormat() - $pat = '/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})$/'; + $pat = '/^(\d{4})-(\d{1,2})-(\d{1,2})$/'; $res = preg_match($pat, $data, $regs); return ($res !== 0 ? self::SUCCESS : self::TYPE_MISMATCH); case 'datetime': // Datetime is already reformated to "Y-m-d H:i:s" by reformatThirdPass() - $pat = '/^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})$/'; + $pat = '/^(\d{4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/'; $res = preg_match($pat, $data, $regs); return ($res !== 0 ? self::SUCCESS : self::TYPE_MISMATCH); case 'ip': - preg_match("/([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/", $data, $regs); + preg_match("/(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/", $data, $regs); return ((count($regs) > 0) ? self::SUCCESS : self::TYPE_MISMATCH); case 'mac': @@ -1468,6 +1505,7 @@ private function checkType($injectionClass, $option, $field_name, $data, $mandat if (!is_numeric($data)) { return self::TYPE_MISMATCH; } + if ($data == 0 || $data == 1) { return self::SUCCESS; } else { @@ -1481,9 +1519,11 @@ private function checkType($injectionClass, $option, $field_name, $data, $mandat if (method_exists($injectionClass, 'checkType')) { return $injectionClass->checkType($field_name, $data, $mandatory); } + return self::SUCCESS; } } + return self::SUCCESS; } @@ -1503,6 +1543,7 @@ private function addNecessaryFields() if (!isset($this->values[$this->primary_type]['entities_id'])) { $this->setValueForItemtype($this->primary_type, 'entities_id', $this->entity); } + if (method_exists($this->injectionClass, 'addSpecificNeededFields')) { $specific_fields = $this->injectionClass->addSpecificNeededFields( $this->primary_type, @@ -1561,7 +1602,7 @@ private function addNeededFields($injectionClass, $itemtype) * * @return bool **/ - private function lastCheckBeforeProcess($injectionClass, $values) + private function lastCheckBeforeProcess($injectionClass) { //Specific reformat action is itemtype needs it @@ -1662,6 +1703,7 @@ public function processAddOrUpdate() //If needed, manage templates $this->addTemplateFields($this->primary_type); } + $values = $this->getValuesForItemtype($this->primary_type); $newID = $this->effectiveAddOrUpdate($this->injectionClass, $item, $values, $add); @@ -1674,7 +1716,7 @@ public function processAddOrUpdate() //If type needs it : process more data after type import $this->processAfterInsertOrUpdate($this->injectionClass, $add); //$this->results['status'] = self::SUCCESS; - $this->results[get_class($item)] = $newID; + $this->results[$item::class] = $newID; //Process other types @@ -1682,7 +1724,7 @@ public function processAddOrUpdate() if (isset($this->values['NetworkPort']) && isset($this->values['NetworkName'])) { $nw = $this->values['NetworkPort']; unset($this->values['NetworkPort']); - $networkNameIndex = array_search('NetworkName', array_keys($this->values)); + $networkNameIndex = array_search('NetworkName', array_keys($this->values), true); $this->values = array_merge( array_slice($this->values, 0, $networkNameIndex), ['NetworkPort' => $nw], @@ -1692,7 +1734,7 @@ public function processAddOrUpdate() foreach ($this->values as $itemtype => $data) { //Do not process primary_type - if ($itemtype != get_class($item)) { + if ($itemtype != $item::class) { $injectionClass = self::getInjectionClassInstance($itemtype); if (is_a($itemtype, CommonDBTM::class, true)) { $item = new $itemtype(); @@ -1706,8 +1748,9 @@ public function processAddOrUpdate() } else { $add = false; } + $values = $this->getValuesForItemtype($itemtype); - if ($this->lastCheckBeforeProcess($injectionClass, $values)) { + if ($this->lastCheckBeforeProcess($injectionClass)) { $tmpID = $this->effectiveAddOrUpdate($injectionClass, $item, $values, $add); $this->processAfterInsertOrUpdate($injectionClass, $add); } @@ -1717,6 +1760,7 @@ public function processAddOrUpdate() } } } + return $this->results; } @@ -1761,6 +1805,7 @@ private function effectiveAddOrUpdate($injectionClass, $item, $values, $add = tr // Skip this field during update if value is empty and field is not nullable continue; } + $toinject[$key] = $value; } @@ -1800,6 +1845,7 @@ private function effectiveAddOrUpdate($injectionClass, $item, $values, $add = tr } else { $toinject['_groups_id'] = [$normalized_value]; } + unset($toinject[$key]); } @@ -1811,12 +1857,7 @@ private function effectiveAddOrUpdate($injectionClass, $item, $values, $add = tr $newID = null; if (method_exists($injectionClass, 'customimport')) { - $newID = call_user_func( - [$injectionClass, 'customimport'], - $toinject, - $add, - $this->rights, - ); + $newID = $injectionClass->customimport($toinject, $add, $this->rights); } elseif ($item instanceof CommonDropdown && $add && !($item instanceof SoftwareLicense)) { $newID = $item->import($toinject); } elseif ($add) { @@ -1829,12 +1870,14 @@ private function effectiveAddOrUpdate($injectionClass, $item, $values, $add = tr if ($item->maybeDynamic()) { unset($toinject['is_dynamic']); } + if ($item->update($toinject)) { $newID = $toinject['id']; self::logAddOrUpdate($item, $add); } } - $this->setValueForItemtype(get_class($item), 'id', $newID); + + $this->setValueForItemtype($item::class, 'id', $newID); return $newID; } @@ -1866,6 +1909,7 @@ private function addOptionalInfos() } else { $this->setValueForItemtype($itemtype, $field, $value); } + $this->addSpecificOptionalInfos($itemtype, $field, $value); } } @@ -1912,7 +1956,7 @@ private function manageRelations() //Get search options associated with the injectionClass $searchOptions = $injectionClass->getOptions($this->primary_type); - foreach ($searchOptions as $id => $option) { + foreach ($searchOptions as $option) { //If it's a relation if ( isset($option['displaytype']) @@ -1979,6 +2023,7 @@ private function dataAlreadyInDB($injectionClass, $itemtype) if (!is_a($itemtype, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $itemtype . ' is not a valid class'); } + $item = new $itemtype(); $where = []; @@ -2000,6 +2045,7 @@ private function dataAlreadyInDB($injectionClass, $itemtype) $source_itemtype = $item::$itemtype_1; $destination_itemtype = $item::$itemtype_2; } + $where[$source_id] = $this->getValueByItemtypeAndName($itemtype, $source_id); $where[$destination_id] = $this->getValueByItemtypeAndName($itemtype, $destination_id); if ($item->isField('itemtype')) { @@ -2068,14 +2114,14 @@ private function dataAlreadyInDB($injectionClass, $itemtype) if (method_exists($injectionClass, 'checkPresent')) { $extra = $injectionClass->checkPresent($this->values, $options); if (is_array($extra)) { - if (count($extra) > 0) { + if ($extra !== []) { $where = array_merge($where, $extra); } } elseif (!empty($extra)) { trigger_error( sprintf( '%s::checkPresent() must return an array, %s returned instead.', - get_class($injectionClass), + $injectionClass::class, gettype($extra), ), E_USER_WARNING, @@ -2094,6 +2140,7 @@ private function dataAlreadyInDB($injectionClass, $itemtype) foreach ($db_fields as $key => $value) { $this->setValueForItemtype($itemtype, $key, $value, true); } + $this->setValueForItemtype($itemtype, 'id', $db_fields['id']); } else { $this->setValueForItemtype($itemtype, 'id', self::ITEM_NOT_FOUND); @@ -2118,6 +2165,7 @@ private function addTemplateFields($itemtype) if (!is_a($itemtype, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $itemtype . ' is not a valid class'); } + $template = new $itemtype(); $template_id = $this->getValueByItemtypeAndName($itemtype, '_oldID'); @@ -2138,6 +2186,7 @@ private function addTemplateFields($itemtype) $this->setValueForItemtype($itemtype, $key, $value); } } + if (isset($this->values[$itemtype]['name'])) { $name = autoName( $this->values[$itemtype]['name'], @@ -2148,6 +2197,7 @@ private function addTemplateFields($itemtype) ); $this->setValueForItemtype($itemtype, 'name', $name); } + if (isset($this->values[$itemtype]['otherserial'])) { $otherserial = autoName( $this->values[$itemtype]['otherserial'], @@ -2179,7 +2229,7 @@ public static function logAddOrUpdate($item, $add = true) $changes[2] = $add ? __('Add from CSV file', 'datainjection') : __('Update from CSV file', 'datainjection'); $changes[1] = ""; - Log::history($item->fields['id'], get_class($item), $changes); + Log::history($item->fields['id'], $item::class, $changes); } } @@ -2289,22 +2339,25 @@ public static function addToSearchOptions( } if (!in_array($id, $options['ignore_fields']) && $id < 1000) { - $type_searchOptions[$id]['injectable'] = !isset($tmp['linkfield']) ? self::FIELD_VIRTUAL : self::FIELD_INJECTABLE; + $type_searchOptions[$id]['injectable'] = isset($tmp['linkfield']) ? self::FIELD_INJECTABLE : self::FIELD_VIRTUAL; //Some injection.class files are missing dropdown options. Set displaytype as dropdown if datatype is dropdown //$tmp['displaytype'] is still empty. Set to prevent overwriting on next IF if ((isset($tmp['datatype']) && $tmp['datatype'] == 'dropdown') && !isset($tmp['displaytype'])) { $type_searchOptions[$id]['displaytype'] = 'dropdown'; $tmp['displaytype'] = 'dropdown'; } + //Some injection.class files are missing checktype for datetime fields. //Without it, the value is never reformated/validated before being sent to the DB. if ((isset($tmp['datatype']) && $tmp['datatype'] == 'datetime') && !isset($tmp['checktype'])) { $type_searchOptions[$id]['checktype'] = 'datetime'; $tmp['checktype'] = 'datetime'; } + if (isset($tmp['linkfield']) && !isset($tmp['displaytype'])) { $type_searchOptions[$id]['displaytype'] = 'text'; } + if (isset($tmp['linkfield']) && !isset($tmp['checktype'])) { $type_searchOptions[$id]['checktype'] = 'text'; } @@ -2359,7 +2412,7 @@ public static function addToSearchOptions( ); $main_itemtype = self::getItemtypeByInjectionClass($injectionClass); - foreach ($type_searchOptions as $key => &$value) { + foreach ($type_searchOptions as &$value) { $value_itemtype = getItemTypeForTable($value['table']); $value_itemtype_name_singular = $value_itemtype::getTypeName(1); $value_itemtype_name_plural = $value_itemtype::getTypeName(Session::getPluralNumber()); @@ -2370,6 +2423,7 @@ public static function addToSearchOptions( ) { continue; } + $value['name'] = $value['name'] . " (" . $value_itemtype_name_singular . ")"; } @@ -2392,6 +2446,7 @@ public static function addTemplateSearchOptions($injectionClass, &$tab) if (!is_a($itemtype, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $itemtype . ' is not a valid class'); } + $item = new $itemtype(); if ($item->maybeTemplate()) { diff --git a/inc/computer_iteminjection.class.php b/inc/computer_iteminjection.class.php index ea4597dd..ee479413 100644 --- a/inc/computer_iteminjection.class.php +++ b/inc/computer_iteminjection.class.php @@ -71,35 +71,7 @@ public function isNullable($field) **/ public function getOptions($primary_type = '') { - - $tab[110]['table'] = 'glpi_computers'; - $tab[110]['field'] = 'name'; - $tab[110]['linkfield'] = 'name'; - $tab[110]['name'] = __('Name'); - $tab[110]['injectable'] = true; - $tab[110]['displaytype'] = 'dropdown'; - $tab[110]['checktype'] = 'text'; - $tab[110]['storevaluein'] = 'computers_id'; - - $tab[111]['table'] = 'glpi_computers'; - $tab[111]['field'] = 'serial'; - $tab[111]['linkfield'] = 'serial'; - $tab[111]['name'] = __('Serial number'); - $tab[111]['injectable'] = true; - $tab[111]['displaytype'] = 'dropdown'; - $tab[111]['checktype'] = 'text'; - $tab[112]['storevaluein'] = 'computers_id'; - - $tab[112]['table'] = 'glpi_computers'; - $tab[112]['field'] = 'otherserial'; - $tab[112]['linkfield'] = 'otherserial'; - $tab[112]['name'] = __('Inventory number'); - $tab[112]['injectable'] = true; - $tab[112]['displaytype'] = 'dropdown'; - $tab[112]['checktype'] = 'text'; - $tab[112]['storevaluein'] = 'computers_id'; - - return $tab; + return [110 => ['table' => 'glpi_computers', 'field' => 'name', 'linkfield' => 'name', 'name' => __('Name'), 'injectable' => true, 'displaytype' => 'dropdown', 'checktype' => 'text', 'storevaluein' => 'computers_id'], 111 => ['table' => 'glpi_computers', 'field' => 'serial', 'linkfield' => 'serial', 'name' => __('Serial number'), 'injectable' => true, 'displaytype' => 'dropdown', 'checktype' => 'text'], 112 => ['storevaluein' => 'computers_id', 'table' => 'glpi_computers', 'field' => 'otherserial', 'linkfield' => 'otherserial', 'name' => __('Inventory number'), 'injectable' => true, 'displaytype' => 'dropdown', 'checktype' => 'text']]; } @@ -121,11 +93,6 @@ public function addOrUpdateObject($values = [], $options = []) **/ public function addSpecificNeededFields($primary_type, $values) { - $fields['items_id_asset'] = $values['id']; - $fields['itemtype_asset'] = Computer::class; - - $fields['items_id_peripheral'] = $values[$primary_type]['id']; - $fields['itemtype_peripheral'] = $primary_type; - return $fields; + return ['items_id_asset' => $values['id'], 'itemtype_asset' => Computer::class, 'items_id_peripheral' => $values[$primary_type]['id'], 'itemtype_peripheral' => $primary_type]; } } diff --git a/inc/contact_supplierinjection.class.php b/inc/contact_supplierinjection.class.php index cedc85ce..e822c5ac 100644 --- a/inc/contact_supplierinjection.class.php +++ b/inc/contact_supplierinjection.class.php @@ -64,16 +64,7 @@ public function isNullable($field) **/ public function getOptions($primary_type = '') { - - $tab[100]['table'] = 'glpi_suppliers'; - $tab[100]['field'] = 'name'; - $tab[100]['linkfield'] = 'suppliers_id'; - $tab[100]['name'] = __('Associated suppliers'); - $tab[100]['displaytype'] = 'relation'; - $tab[100]['relationclass'] = 'Contact_Supplier'; - $tab[100]['injectable'] = true; - - return $tab; + return [100 => ['table' => 'glpi_suppliers', 'field' => 'name', 'linkfield' => 'suppliers_id', 'name' => __('Associated suppliers'), 'displaytype' => 'relation', 'relationclass' => 'Contact_Supplier', 'injectable' => true]]; } diff --git a/inc/contract_iteminjection.class.php b/inc/contract_iteminjection.class.php index 568a2c92..000b304b 100644 --- a/inc/contract_iteminjection.class.php +++ b/inc/contract_iteminjection.class.php @@ -71,28 +71,7 @@ public function isNullable($field) **/ public function getOptions($primary_type = '') { - - $tab[100]['table'] = 'glpi_contracts'; - $tab[100]['field'] = 'name'; - $tab[100]['linkfield'] = 'name'; - $tab[100]['name'] = __('Name'); - $tab[100]['injectable'] = true; - $tab[100]['checktype'] = 'text'; - $tab[100]['displaytype'] = 'relation'; - $tab[100]['relationclass'] = 'Contract_Item'; - $tab[100]['storevaluein'] = 'contracts_id'; - - $tab[101]['table'] = 'glpi_contracts'; - $tab[101]['field'] = 'num'; - $tab[101]['linkfield'] = 'num'; - $tab[101]['name'] = __('Serial number'); - $tab[101]['injectable'] = true; - $tab[101]['checktype'] = 'text'; - $tab[101]['displaytype'] = 'relation'; - $tab[101]['relationclass'] = 'Contract_Item'; - $tab[101]['storevaluein'] = 'contracts_id'; - - return $tab; + return [100 => ['table' => 'glpi_contracts', 'field' => 'name', 'linkfield' => 'name', 'name' => __('Name'), 'injectable' => true, 'checktype' => 'text', 'displaytype' => 'relation', 'relationclass' => 'Contract_Item', 'storevaluein' => 'contracts_id'], 101 => ['table' => 'glpi_contracts', 'field' => 'num', 'linkfield' => 'num', 'name' => __('Serial number'), 'injectable' => true, 'checktype' => 'text', 'displaytype' => 'relation', 'relationclass' => 'Contract_Item', 'storevaluein' => 'contracts_id']]; } @@ -114,9 +93,6 @@ public function addOrUpdateObject($values = [], $options = []) **/ public function addSpecificNeededFields($primary_type, $values) { - - $fields['items_id'] = $values[$primary_type]['id']; - $fields['itemtype'] = $primary_type; - return $fields; + return ['items_id' => $values[$primary_type]['id'], 'itemtype' => $primary_type]; } } diff --git a/inc/contract_supplierinjection.class.php b/inc/contract_supplierinjection.class.php index 65258286..2a11de71 100644 --- a/inc/contract_supplierinjection.class.php +++ b/inc/contract_supplierinjection.class.php @@ -64,20 +64,7 @@ public function isNullable($field) **/ public function getOptions($primary_type = '') { - - $tab[4]['table'] = 'glpi_contracts'; - $tab[4]['field'] = 'name'; - $tab[4]['name'] = __('Contract'); - $tab[4]['checktype'] = 'text'; - $tab[4]['displaytype'] = 'dropdown'; - - $tab[5]['table'] = 'glpi_suppliers'; - $tab[5]['field'] = 'name'; - $tab[5]['name'] = __('Supplier'); - $tab[5]['checktype'] = 'text'; - $tab[5]['displaytype'] = 'dropdown'; - - return $tab; + return [4 => ['table' => 'glpi_contracts', 'field' => 'name', 'name' => __('Contract'), 'checktype' => 'text', 'displaytype' => 'dropdown'], 5 => ['table' => 'glpi_suppliers', 'field' => 'name', 'name' => __('Supplier'), 'checktype' => 'text', 'displaytype' => 'dropdown']]; } diff --git a/inc/data.class.php b/inc/data.class.php index c6813d8f..a95f013d 100644 --- a/inc/data.class.php +++ b/inc/data.class.php @@ -33,9 +33,6 @@ class PluginDatainjectionData private $injectionData; - public function __construct() {} - - /** * @param array $newData **/ @@ -62,6 +59,7 @@ public function getDataAtLine($line_id) if (count($this->injectionData) >= $line_id) { return $this->injectionData[$line_id][0]; } + return []; } } diff --git a/inc/devicecaseinjection.class.php b/inc/devicecaseinjection.class.php index 6349c34f..35ba7328 100644 --- a/inc/devicecaseinjection.class.php +++ b/inc/devicecaseinjection.class.php @@ -93,6 +93,7 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) if (!is_a($class, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $class . ' is not a valid class'); } + $item = new $class(); $foreign = getForeignKeyFieldForTable(getTableForItemType(get_parent_class($this))); diff --git a/inc/devicecontrolinjection.class.php b/inc/devicecontrolinjection.class.php index 93390851..a6992267 100644 --- a/inc/devicecontrolinjection.class.php +++ b/inc/devicecontrolinjection.class.php @@ -94,6 +94,7 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) if (!is_a($class, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $class . ' is not a valid class'); } + $item = new $class(); $foreign = getForeignKeyFieldForTable(getTableForItemType(get_parent_class($this))); diff --git a/inc/devicedriveinjection.class.php b/inc/devicedriveinjection.class.php index 5829840b..83789b35 100644 --- a/inc/devicedriveinjection.class.php +++ b/inc/devicedriveinjection.class.php @@ -94,6 +94,7 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) if (!is_a($class, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $class . ' is not a valid class'); } + $item = new $class(); $foreign = getForeignKeyFieldForTable(getTableForItemType(get_parent_class($this))); diff --git a/inc/deviceharddriveinjection.class.php b/inc/deviceharddriveinjection.class.php index 32defcef..74d6ba83 100644 --- a/inc/deviceharddriveinjection.class.php +++ b/inc/deviceharddriveinjection.class.php @@ -95,6 +95,7 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) if (!is_a($class, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $class . ' is not a valid class'); } + $item = new $class(); $foreign = getForeignKeyFieldForTable(getTableForItemType(get_parent_class($this))); diff --git a/inc/devicememoryinjection.class.php b/inc/devicememoryinjection.class.php index 6d3c8415..0d2cdfa8 100644 --- a/inc/devicememoryinjection.class.php +++ b/inc/devicememoryinjection.class.php @@ -95,6 +95,7 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) if (!is_a($class, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $class . ' is not a valid class'); } + $item = new $class(); $foreign = getForeignKeyFieldForTable(getTableForItemType(get_parent_class($this))); diff --git a/inc/devicemotherboardinjection.class.php b/inc/devicemotherboardinjection.class.php index f48a1ce6..a5276073 100644 --- a/inc/devicemotherboardinjection.class.php +++ b/inc/devicemotherboardinjection.class.php @@ -95,6 +95,7 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) if (!is_a($class, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $class . ' is not a valid class'); } + $item = new $class(); $foreign = getForeignKeyFieldForTable(getTableForItemType(get_parent_class($this))); diff --git a/inc/devicenetworkcardinjection.class.php b/inc/devicenetworkcardinjection.class.php index c64dd880..1b1f089b 100644 --- a/inc/devicenetworkcardinjection.class.php +++ b/inc/devicenetworkcardinjection.class.php @@ -93,6 +93,7 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) if (!is_a($class, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $class . ' is not a valid class'); } + $item = new $class(); $foreign = getForeignKeyFieldForTable(getTableForItemType(get_parent_class($this))); diff --git a/inc/deviceprocessorinjection.class.php b/inc/deviceprocessorinjection.class.php index c237697d..75f0fdb9 100644 --- a/inc/deviceprocessorinjection.class.php +++ b/inc/deviceprocessorinjection.class.php @@ -95,6 +95,7 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) if (!is_a($class, CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $class . ' is not a valid class'); } + $item = new $class(); $foreign = getForeignKeyFieldForTable(getTableForItemType(get_parent_class($this))); diff --git a/inc/dropdown.class.php b/inc/dropdown.class.php index ccd4d0d0..8358fa16 100644 --- a/inc/dropdown.class.php +++ b/inc/dropdown.class.php @@ -32,15 +32,7 @@ class PluginDatainjectionDropdown { public static function dateFormats() { - - $date_format[PluginDatainjectionCommonInjectionLib::DATE_TYPE_DDMMYYYY] - = __('dd-mm-yyyy', 'datainjection'); - $date_format[PluginDatainjectionCommonInjectionLib::DATE_TYPE_MMDDYYYY] - = __('mm-dd-yyyy', 'datainjection'); - $date_format[PluginDatainjectionCommonInjectionLib::DATE_TYPE_YYYYMMDD] - = __('yyyy-mm-dd', 'datainjection'); - - return $date_format; + return ['dd-mm-yyyy' => __('dd-mm-yyyy', 'datainjection'), 'mm-dd-yyyy' => __('mm-dd-yyyy', 'datainjection'), 'yyyy-mm-dd' => __('yyyy-mm-dd', 'datainjection')]; } @@ -54,15 +46,7 @@ public static function getDateFormat($date) public static function floatFormats() { - - $float_format[PluginDatainjectionCommonInjectionLib::FLOAT_TYPE_DOT] - = __('1 234.56', 'datainjection'); - $float_format[PluginDatainjectionCommonInjectionLib::FLOAT_TYPE_COMMA] - = __('1 234,56', 'datainjection'); - $float_format[PluginDatainjectionCommonInjectionLib::FLOAT_TYPE_DOT_AND_COM] - = __('1,234.56', 'datainjection'); - - return $float_format; + return [1 => __('1 234.56', 'datainjection'), 0 => __('1 234,56', 'datainjection'), __('1,234.56', 'datainjection')]; } @@ -79,20 +63,13 @@ public static function getFloatFormat($format) public static function statusLabels() { - - $states[0] = Dropdown::EMPTY_VALUE; - //$states[PluginDatainjectionModel::INITIAL_STEP] = __('Creation of the model on going', 'datainjection'); - $states[PluginDatainjectionModel::FILE_STEP] = __('File to inject', 'datainjection'); - $states[PluginDatainjectionModel::MAPPING_STEP] = __('Mappings', 'datainjection'); - $states[PluginDatainjectionModel::OTHERS_STEP] = __( + return [Dropdown::EMPTY_VALUE, 2 => __('File to inject', 'datainjection'), 3 => __('Mappings', 'datainjection'), 4 => __( 'Additional Information', 'datainjection', - ); - $states[PluginDatainjectionModel::READY_TO_USE_STEP] = __( + ), 5 => __( 'Model available for use', 'datainjection', - ); - return $states; + )]; } @@ -110,46 +87,24 @@ public static function getStatusLabel($step) public static function getStatusColor($step) { - switch ($step) { - case PluginDatainjectionModel::MAPPING_STEP: - case PluginDatainjectionModel::OTHERS_STEP: - return "#ffb832"; - case PluginDatainjectionModel::READY_TO_USE_STEP: - return "#2ec41f"; - default: - return "#ff4e4e"; - } + return match ($step) { + PluginDatainjectionModel::MAPPING_STEP, PluginDatainjectionModel::OTHERS_STEP => "#ffb832", + PluginDatainjectionModel::READY_TO_USE_STEP => "#2ec41f", + default => "#ff4e4e", + }; } public static function getFileEncodingValue() { - - $values[PluginDatainjectionBackend::ENCODING_AUTO] = __('Automatic detection', 'datainjection'); - $values[PluginDatainjectionBackend::ENCODING_UFT8] = __('UTF-8', 'datainjection'); - $values[PluginDatainjectionBackend::ENCODING_ISO8859_1] = __('ISO8859-1', 'datainjection'); - - return $values; + return [2 => __('Automatic detection', 'datainjection'), __('UTF-8', 'datainjection'), 0 => __('ISO8859-1', 'datainjection')]; } public static function portUnicityValues() { - - $values[PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_LOGICAL_NUMBER] - = __('Port number'); - $values[PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_NAME] - = __('Name'); - $values[PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_MACADDRESS] - = __('Mac address'); - $values[PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_LOGICAL_NUMBER_NAME] - = __('Port number') . "+" . __('Name'); - $values[PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_LOGICAL_NUMBER_MAC] - = __('Port number') . "+" . __('Mac address'); - $values[PluginDatainjectionCommonInjectionLib::UNICITY_NETPORT_LOGICAL_NUMBER_NAME_MAC] - = __('Port number') . "+" . __('Name') . "+" . - __('Mac address'); - return $values; + return [__('Port number'), __('Name'), __('Mac address'), __('Port number') . "+" . __('Name'), __('Port number') . "+" . __('Mac address'), __('Port number') . "+" . __('Name') . "+" . + __('Mac address')]; } diff --git a/inc/engine.class.php b/inc/engine.class.php index 6018cbc3..810b93f1 100644 --- a/inc/engine.class.php +++ b/inc/engine.class.php @@ -30,15 +30,6 @@ class PluginDatainjectionEngine { - //Model informations - private $model; - - //Current entity - private $entity; - - //Additional infos to be added - private $infos = []; - //Lines in error private $error_lines = []; @@ -48,18 +39,13 @@ class PluginDatainjectionEngine * @param array $infos array * @param int|string $entity (default 0) */ - public function __construct($model, $infos = [], $entity = 0) + public function __construct(private $model, private $infos = [], private $entity = 0) { - //Instanciate model - $this->model = $model; - //Load model and mappings informations $this->getModel()->loadMappings(); $this->getModel()->populateSeveraltimesMappedFields(); $this->getModel()->loadInfos(); - $this->infos = $infos; - $this->entity = $entity; } @@ -160,6 +146,7 @@ public function injectLine($line, $index) if ($results['status'] != PluginDatainjectionCommonInjectionLib::SUCCESS) { $this->error_lines[] = $line; } + return $results; } @@ -217,8 +204,10 @@ public function addValueToInject( if (isset($fields_toinject[$mapping->getItemtype()][$mapping->getValue()])) { $return_value .= $fields_toinject[$mapping->getItemtype()][$mapping->getValue()]; } + $return_value .= $mapping->getMappingName() . "=" . $value . "\n"; } + $fields_toinject[$mapping->getItemtype()][$mapping->getValue()] = $return_value; } @@ -241,6 +230,7 @@ public function addAdditionalInformations() = $this->infos[$info->getValue()]; } } + return $additional_infos; } diff --git a/inc/entityinjection.class.php b/inc/entityinjection.class.php index 20e45981..34421311 100644 --- a/inc/entityinjection.class.php +++ b/inc/entityinjection.class.php @@ -93,11 +93,12 @@ public function addOrUpdateObject($values = [], $options = []) // Only the `name`, `entities_id`, and `comment` fields are taken into account when creating an entity. // The IF forces an update of the entity to insert the other fields. if ( - count(array_diff_key($values, array_flip(['name', 'entities_id', 'comment']))) > 0 + array_diff_key($values, array_flip(['name', 'entities_id', 'comment'])) !== [] && $data['type'] === PluginDatainjectionCommonInjectionLib::IMPORT_ADD ) { $lib->processAddOrUpdate(); } + return $lib->getInjectionResults(); } @@ -129,8 +130,8 @@ public function customimport($input = [], $add = true, $rights = []) // Check if search start by root entity $root = self::getRootEntityName(); - if (!str_starts_with($search, $root)) { - $search = "$root > $search"; + if (!str_starts_with((string) $search, (string) $root)) { + $search = sprintf('%s > %s', $root, $search); } $results = $em->find(['completename' => $search]); @@ -148,13 +149,13 @@ public function importEntity($input) $em = new Entity(); // Import a full tree from completename - $names = explode('>', $input['completename']); + $names = explode('>', (string) $input['completename']); $i = count($names); $parent = 0; $level = 0; // Remove root entity if specified - if (strcmp(trim($names[0]), trim(self::getRootEntityName())) === 0) { + if (strcmp(trim($names[0]), trim((string) self::getRootEntityName())) === 0) { unset($names[0]); } @@ -163,10 +164,11 @@ public function importEntity($input) $i--; $level++; - if (empty($name)) { + if ($name === '' || $name === '0') { // Skip empty name (completename starting/endind with >, double >, ...) continue; } + $tmp['name'] = $name; if ($i === 0) { @@ -177,6 +179,7 @@ public function importEntity($input) } } } + $tmp['level'] = $level; $tmp['entities_id'] = $parent; @@ -224,6 +227,7 @@ public function customDataAlreadyInDB($injectionClass, $values, $options) if (!isset($values['completename'])) { return false; } + $results = getAllDataFromTable( 'glpi_entities', ['completename' => $values['completename']], diff --git a/inc/info.class.php b/inc/info.class.php index 92150701..c2ffe04f 100644 --- a/inc/info.class.php +++ b/inc/info.class.php @@ -104,8 +104,8 @@ public static function showAddInfo(PluginDatainjectionModel $model, $canedit = f ], ); echo ""; - echo ""; - echo ""; + echo sprintf("", $infos_id); + echo sprintf("", $infos_id); echo ""; echo ""; @@ -122,10 +122,8 @@ public static function showAddInfo(PluginDatainjectionModel $model, $canedit = f /** - * Display additional information form from Model form - * - * @param PluginDatainjectionModel $model - */ + * Display additional information form from Model form + */ public static function showFormInfos(PluginDatainjectionModel $model) { @@ -136,12 +134,13 @@ public static function showFormInfos(PluginDatainjectionModel $model) $nb = count($model->getInfos()); $rand = mt_rand(); if ($nb > 0) { - echo "
"; + echo sprintf(""; echo ""; echo ""; if ($canedit) { echo ""; } + echo ""; echo ""; echo ""; @@ -156,9 +155,11 @@ public static function showFormInfos(PluginDatainjectionModel $model) if (isset($_GET["select"]) && ($_GET["select"] == "all")) { $sel = "checked"; } - echo ""; + + echo "", $sel); echo ""; } + echo ""; - echo ""; - echo ""; + echo sprintf("", $infos_id); + echo sprintf("", $infos_id); } if ($canedit) { @@ -183,19 +184,20 @@ public static function showFormInfos(PluginDatainjectionModel $model) $arrow = "fas fa-level-up-alt"; echo ""; - echo ""; + echo sprintf("", $arrow); echo ""; + echo sprintf("", $formname) . __s('Check all') . ""; echo ""; echo ""; + echo sprintf("", $formname) . __s('Uncheck all') . ""; echo ""; echo "
 " . __s('Tables', 'datainjection') . "" . __s('Fields', 'datainjection') . "" . __s('Mandatory information', 'datainjection') . ""; $rand = PluginDatainjectionInjectionType::dropdownLinkedTypes( $info, @@ -167,8 +168,8 @@ public static function showFormInfos(PluginDatainjectionModel $model) ], ); echo "
"; - echo "" . __s('Check all') . "/"; - echo "" . __s('Uncheck all') . ""; echo " "; + echo 'value="' . addslashes(_sx('button', 'Delete permanently')) . "\" class='btn btn-primary'> "; echo "
"; } + echo ""; Html::closeForm(); } @@ -317,10 +319,8 @@ public static function displayAdditionalInformation(PluginDatainjectionInfo $inf /** * Display command additional informations * - * @param PluginDatainjectionInfo $info * @param array $option * @param PluginDatainjectionInjectionInterface $injectionClass - * * @return void */ public static function showAdditionalInformation( @@ -344,10 +344,12 @@ public static function showAdditionalInformation( if (empty($value)) { $value = ($option['default'] ?? ''); } - echo ""; break; @@ -355,6 +357,7 @@ public static function showAdditionalInformation( if ($value == '') { $value = 0; } + Dropdown::show( getItemTypeForTable($option['table']), ['name' => $name, @@ -367,6 +370,7 @@ public static function showAdditionalInformation( if ($value == '') { $value = 0; } + Dropdown::showYesNo($name, $value); break; @@ -374,6 +378,7 @@ public static function showAdditionalInformation( if ($value == '') { $value = 0; } + User::dropdown( ['name' => $name, 'value' => $value, @@ -386,7 +391,7 @@ public static function showAdditionalInformation( break; case 'multiline_text': - echo ""; + echo sprintf("", $name, $value); break; case 'dropdown_integer': @@ -411,7 +416,7 @@ public static function showAdditionalInformation( break; case 'password': - echo ""; + echo sprintf("", $name); break; default: @@ -455,6 +460,7 @@ public static function keepInfo(PluginDatainjectionInfo $info, $value) return $value != PluginDatainjectionCommonInjectionLib::DROPDOWN_EMPTY_VALUE; } } + return null; } @@ -478,6 +484,7 @@ public static function dropdownTemplates($name, $table) foreach ($DB->doQuery($sql) as $data) { $values[$data['id']] = $data['template_name']; } + Dropdown::showFromArray($name, $values); } } diff --git a/inc/infocollection.class.php b/inc/infocollection.class.php index f914d270..efbc6096 100644 --- a/inc/infocollection.class.php +++ b/inc/infocollection.class.php @@ -30,14 +30,7 @@ class PluginDatainjectionInfoCollection { - public $infosCollection; - - - public function __construct() - { - - $this->infosCollection = []; - } + public $infosCollection = []; //---- Getter ----// diff --git a/inc/infocominjection.class.php b/inc/infocominjection.class.php index 1db66382..243f1a67 100644 --- a/inc/infocominjection.class.php +++ b/inc/infocominjection.class.php @@ -108,7 +108,7 @@ public function getOptions($primary_type = '') $options['ignore_fields'] = array_merge($blacklist, $notimportable); - $key = array_search(19, $options['ignore_fields']); + $key = array_search(19, $options['ignore_fields'], true); unset($options['ignore_fields'][$key]); $options['displaytype'] = ["date" => [4, 5, 23, 24, 25, 27, 28, 159], diff --git a/inc/injectiontype.class.php b/inc/injectiontype.class.php index 9cfb291d..ee8eca2a 100644 --- a/inc/injectiontype.class.php +++ b/inc/injectiontype.class.php @@ -71,17 +71,20 @@ public static function getItemtypes($only_primary = false) if (!$instance->canCreate()) { continue; } + $typename = get_parent_class($type); $name = ''; if ($from != 'datainjection') { $plugin->getFromDBbyDir($from); $name = $plugin->getName() . ': '; } + $name .= call_user_func([$type, 'getTypeName']); $values[$typename] = $name; } } } + asort($values); return $values; } @@ -125,7 +128,7 @@ public static function dropdownLinkedTypes($mapping_or_info, $options = []) $mapping_or_info->fields, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP, ); - $p['called_by'] = get_class($mapping_or_info); + $p['called_by'] = $mapping_or_info::class; $p['fields_update'] = true; foreach ($options as $key => $value) { $p[$key] = $value; @@ -148,6 +151,7 @@ public static function dropdownLinkedTypes($mapping_or_info, $options = []) if (!is_a($p['primary_type'], CommonDBTM::class, true)) { throw new HttpException(500, 'Class ' . $p['primary_type'] . ' is not a valid class'); } + $type = new $p['primary_type'](); $values[$p['primary_type']] = $type->getTypeName(); @@ -163,6 +167,7 @@ public static function dropdownLinkedTypes($mapping_or_info, $options = []) } } } + asort($values); $rand = Dropdown::showFromArray( @@ -174,7 +179,7 @@ public static function dropdownLinkedTypes($mapping_or_info, $options = []) $p['itemtype'] = '__VALUE__'; $di_base_url = plugin_datainjection_geturl(); $url_field = $di_base_url . "ajax/dropdownChooseField.php"; - $toobserve = "dropdown_data[" . $mapping_or_info->getID() . "][itemtype]$rand"; + $toobserve = "dropdown_data[" . $mapping_or_info->getID() . ('][itemtype]' . $rand); $toupdate = "span_field_" . $mappings_id; Ajax::updateItem($toupdate, $url_field, $p, $toobserve); Ajax::updateItemOnSelectEvent($toobserve, $toupdate, $url_field, $p); @@ -222,6 +227,7 @@ public static function dropdownFields($options = []) if ($mapping_or_info['value'] != self::NO_VALUE) { $mapping_value = $mapping_or_info['value']; } + $injectionClass = PluginDatainjectionCommonInjectionLib::getInjectionClassInstance($p['itemtype']); foreach ($injectionClass->getOptions($p['primary_type']) as $option) { @@ -243,8 +249,10 @@ public static function dropdownFields($options = []) } } } + $used = self::getUsedMappingsOrInfos($p); } + asort($fields); $rand = Dropdown::showFromArray( @@ -261,10 +269,10 @@ public static function dropdownFields($options = []) "span_mandatory_" . $mapping_or_info['id'], $url, $p, - "dropdown_data[" . $mapping_or_info['id'] . "][value]$rand", + "dropdown_data[" . $mapping_or_info['id'] . ('][value]' . $rand), ); Ajax::updateItemOnSelectEvent( - "dropdown_data[" . $mapping_or_info['id'] . "][value]$rand", + "dropdown_data[" . $mapping_or_info['id'] . ('][value]' . $rand), "span_mandatory_" . $mapping_or_info['id'], $url, $p, @@ -283,8 +291,8 @@ public static function dropdownFields($options = []) public static function isEqual($option, $mapping) { - $name = strtolower($mapping['name']); - if (self::testBasicEqual(strtolower($mapping['name']), $option)) { + $name = strtolower((string) $mapping['name']); + if (self::testBasicEqual(strtolower((string) $mapping['name']), $option)) { return true; } @@ -307,9 +315,9 @@ public static function isEqual($option, $mapping) public static function testBasicEqual($name, $option = []) { //Basic tests - return (strtolower($option['field']) == $name) - || (strtolower($option['name']) == $name) - || (strtolower($option['linkfield']) == $name); + return (strtolower((string) $option['field']) == $name) + || (strtolower((string) $option['name']) == $name) + || (strtolower((string) $option['linkfield']) == $name); } /** @@ -342,7 +350,7 @@ public static function showMandatoryCheckbox($options = []) && !in_array($options['value'], self::NON_MANDATORY_FIELDS) ) ) { - echo ""; + echo "", $checked); } } diff --git a/inc/interfacetypeinjection.class.php b/inc/interfacetypeinjection.class.php index 774fc776..ac54076a 100644 --- a/inc/interfacetypeinjection.class.php +++ b/inc/interfacetypeinjection.class.php @@ -52,6 +52,7 @@ public function connectedTo() return []; } + public function isNullable($field) { return true; // By default, all fields can be null diff --git a/inc/item_operatingsysteminjection.class.php b/inc/item_operatingsysteminjection.class.php index 5bb6fc8b..34c8078b 100644 --- a/inc/item_operatingsysteminjection.class.php +++ b/inc/item_operatingsysteminjection.class.php @@ -65,6 +65,7 @@ public function getOptions($primary_type = '') } else { $option['linkfield'] = $option['field']; } + $searchoptions[$option['id']] = $option; } } @@ -133,9 +134,6 @@ public function customDataAlreadyInDB($injectionClass, $values, $options) **/ public function addSpecificNeededFields($primary_type, $values) { - $fields['items_id'] = $values[$primary_type]['id']; - $fields['itemtype'] = $primary_type; - - return $fields; + return ['items_id' => $values[$primary_type]['id'], 'itemtype' => $primary_type]; } } diff --git a/inc/item_softwarelicenseinjection.class.php b/inc/item_softwarelicenseinjection.class.php index bcc6e2cf..8c80fcd2 100644 --- a/inc/item_softwarelicenseinjection.class.php +++ b/inc/item_softwarelicenseinjection.class.php @@ -72,42 +72,15 @@ public function isNullable($field) **/ public function getOptions($primary_type = '') { - $tab[110]['table'] = 'glpi_computers'; - $tab[110]['field'] = 'name'; - $tab[110]['linkfield'] = 'name'; - $tab[110]['name'] = sprintf(__('%1$s - %2$s'), self::getTypeName(), __('Name')); - $tab[110]['injectable'] = true; - $tab[110]['displaytype'] = 'dropdown'; - $tab[110]['checktype'] = 'text'; - $tab[110]['storevaluein'] = 'computers_id'; - - $tab[111]['table'] = 'glpi_computers'; - $tab[111]['field'] = 'serial'; - $tab[111]['linkfield'] = 'serial'; - $tab[111]['name'] = sprintf( + return [110 => ['table' => 'glpi_computers', 'field' => 'name', 'linkfield' => 'name', 'name' => sprintf(__('%1$s - %2$s'), self::getTypeName(), __('Name')), 'injectable' => true, 'displaytype' => 'dropdown', 'checktype' => 'text', 'storevaluein' => 'computers_id'], 111 => ['table' => 'glpi_computers', 'field' => 'serial', 'linkfield' => 'serial', 'name' => sprintf( __('%1$s - %2$s'), self::getTypeName(), __('Serial number'), - ); - $tab[111]['injectable'] = true; - $tab[111]['displaytype'] = 'dropdown'; - $tab[111]['checktype'] = 'text'; - $tab[112]['storevaluein'] = 'computers_id'; - - $tab[112]['table'] = 'glpi_computers'; - $tab[112]['field'] = 'otherserial'; - $tab[112]['linkfield'] = 'otherserial'; - $tab[112]['name'] = sprintf( + ), 'injectable' => true, 'displaytype' => 'dropdown', 'checktype' => 'text'], 112 => ['storevaluein' => 'computers_id', 'table' => 'glpi_computers', 'field' => 'otherserial', 'linkfield' => 'otherserial', 'name' => sprintf( __('%1$s - %2$s'), self::getTypeName(), __('Inventory number'), - ); - $tab[112]['injectable'] = true; - $tab[112]['displaytype'] = 'dropdown'; - $tab[112]['checktype'] = 'text'; - $tab[112]['storevaluein'] = 'computers_id'; - - return $tab; + ), 'injectable' => true, 'displaytype' => 'dropdown', 'checktype' => 'text']]; } diff --git a/inc/item_softwareversioninjection.class.php b/inc/item_softwareversioninjection.class.php index bb4029b1..aa2cba7b 100644 --- a/inc/item_softwareversioninjection.class.php +++ b/inc/item_softwareversioninjection.class.php @@ -72,43 +72,15 @@ public function isNullable($field) **/ public function getOptions($primary_type = '') { - - $tab[110]['table'] = 'glpi_computers'; - $tab[110]['field'] = 'name'; - $tab[110]['linkfield'] = 'name'; - $tab[110]['name'] = sprintf(__('%1$s - %2$s'), self::getTypeName(), __('Name')); - $tab[110]['injectable'] = true; - $tab[110]['displaytype'] = 'dropdown'; - $tab[110]['checktype'] = 'text'; - $tab[110]['storevaluein'] = 'computers_id'; - - $tab[111]['table'] = 'glpi_computers'; - $tab[111]['field'] = 'serial'; - $tab[111]['linkfield'] = 'serial'; - $tab[111]['name'] = sprintf( + return [110 => ['table' => 'glpi_computers', 'field' => 'name', 'linkfield' => 'name', 'name' => sprintf(__('%1$s - %2$s'), self::getTypeName(), __('Name')), 'injectable' => true, 'displaytype' => 'dropdown', 'checktype' => 'text', 'storevaluein' => 'computers_id'], 111 => ['table' => 'glpi_computers', 'field' => 'serial', 'linkfield' => 'serial', 'name' => sprintf( __('%1$s - %2$s'), self::getTypeName(), __('Serial number'), - ); - $tab[111]['injectable'] = true; - $tab[111]['displaytype'] = 'dropdown'; - $tab[111]['checktype'] = 'text'; - $tab[112]['storevaluein'] = 'computers_id'; - - $tab[112]['table'] = 'glpi_computers'; - $tab[112]['field'] = 'otherserial'; - $tab[112]['linkfield'] = 'otherserial'; - $tab[112]['name'] = sprintf( + ), 'injectable' => true, 'displaytype' => 'dropdown', 'checktype' => 'text'], 112 => ['storevaluein' => 'computers_id', 'table' => 'glpi_computers', 'field' => 'otherserial', 'linkfield' => 'otherserial', 'name' => sprintf( __('%1$s - %2$s'), self::getTypeName(), __('Inventory number'), - ); - $tab[112]['injectable'] = true; - $tab[112]['displaytype'] = 'dropdown'; - $tab[112]['checktype'] = 'text'; - $tab[112]['storevaluein'] = 'computers_id'; - - return $tab; + ), 'injectable' => true, 'displaytype' => 'dropdown', 'checktype' => 'text']]; } diff --git a/inc/mapping.class.php b/inc/mapping.class.php index d92d314a..d9a3b495 100644 --- a/inc/mapping.class.php +++ b/inc/mapping.class.php @@ -47,6 +47,7 @@ public function equal($field, $value) if (!isset($this->fields[$field])) { return false; } + return $this->fields[$field] == $value; } @@ -158,6 +159,7 @@ public static function getSeveralMappedField($models_id) foreach ($DB->doQuery($query) as $mapping) { $several[] = $mapping['value']; } + return $several; } @@ -178,6 +180,7 @@ public static function getMappingsSortedByRank($models_id) foreach ($DB->doQuery($query) as $data) { $mappings[] = $data['name']; } + return $mappings; } } diff --git a/inc/mappingcollection.class.php b/inc/mappingcollection.class.php index e77d4270..71cb8bfa 100644 --- a/inc/mappingcollection.class.php +++ b/inc/mappingcollection.class.php @@ -30,13 +30,7 @@ class PluginDatainjectionMappingCollection { - private $mappingCollection; - - public function __construct() - { - - $this->mappingCollection = []; - } + private $mappingCollection = []; //---- Getter ----// @@ -52,7 +46,7 @@ public function load($models_id) $sql = "SELECT * FROM `glpi_plugin_datainjection_mappings` - WHERE `models_id` = '$models_id' + WHERE `models_id` = '{$models_id}' ORDER BY `rank` ASC"; $this->mappingCollection = []; @@ -121,6 +115,7 @@ public function getMappingsByField($field, $value) return $mapping; } } + return null; } @@ -194,6 +189,7 @@ public function getMandatoryMappings() $mandatories[] = $mapping; } } + return $mandatories; } diff --git a/inc/menu.class.php b/inc/menu.class.php index 7d5a6f66..6d304cee 100644 --- a/inc/menu.class.php +++ b/inc/menu.class.php @@ -71,7 +71,7 @@ public static function getMenuContent() ]; $model_name = PluginDatainjectionModel::getTypeName(Session::getPluralNumber()); - $image_model = ""; + $image_model = "", $model_name, $model_name); if (Session::haveRight('plugin_datainjection_model', READ)) { $menu['options']['model']['title'] = $model_name; diff --git a/inc/model.class.php b/inc/model.class.php index 112f72f7..09c97de3 100644 --- a/inc/model.class.php +++ b/inc/model.class.php @@ -89,16 +89,22 @@ class PluginDatainjectionModel extends CommonDBTM //Private or public model public const MODEL_PRIVATE = 1; + public const MODEL_PUBLIC = 0; //Step constants public const INITIAL_STEP = 1; + public const FILE_STEP = 2; + public const MAPPING_STEP = 3; + public const OTHERS_STEP = 4; + public const READY_TO_USE_STEP = 5; public const PROCESS = 0; + public const CREATION = 1; @@ -299,6 +305,7 @@ public function getNumberOfMappings() if ($this->mappings) { return count($this->mappings); } + return false; } @@ -331,7 +338,7 @@ public static function dropdown($options = []) $value = $_SESSION['datainjection']['models_id'] ?? 0; $rand = mt_rand(); - echo "\n"; $prev = -2; echo "\n"; @@ -347,26 +354,26 @@ public static function dropdown($options = []) echo "\n"; + ) . '">'; } + $prev = $model['entities_id']; } $selected = $model['id'] == $value ? "selected" : ""; - $comment = $model['comment'] ? "title='" . htmlentities($model['comment'], ENT_QUOTES, 'UTF-8') . "'" : ""; - echo "\n"; + $comment = $model['comment'] ? "title='" . htmlentities((string) $model['comment'], ENT_QUOTES, 'UTF-8') . "'" : ""; + echo "\n"; } if ($prev >= -1) { echo ""; } + echo ""; $url = $CFG_GLPI['root_doc'] . "/plugins/datainjection/ajax/dropdownSelectModel.php"; - Ajax::updateItemOnSelectEvent("dropdown_models$rand", "span_injection", $url, $p); - - return; + Ajax::updateItemOnSelectEvent('dropdown_models' . $rand, "span_injection", $url, $p); } @@ -443,15 +450,10 @@ public static function getModels($user_id, $order = "name", $entity = -1, $all = //Standard functions public function rawSearchOptions() { - - $tab = []; - - $tab[] = [ + return [[ 'id' => 'common', 'name' => self::getTypeName(), - ]; - - $tab[] = [ + ], [ 'id' => 1, 'table' => $this->getTable(), 'field' => 'name', @@ -459,34 +461,26 @@ public function rawSearchOptions() 'datatype' => 'itemlink', 'itemlink_type' => $this->getType(), 'autocomplete' => true, - ]; - - $tab[] = [ + ], [ 'id' => 2, 'table' => $this->getTable(), 'field' => 'id', 'name' => __('ID'), - ]; - - $tab[] = [ + ], [ 'id' => 3, 'table' => $this->getTable(), 'field' => 'behavior_add', 'name' => __('Allow lines creation', 'datainjection'), 'datatype' => 'bool', 'massiveaction' => false, - ]; - - $tab[] = [ + ], [ 'id' => 4, 'table' => $this->getTable(), 'field' => 'behavior_update', 'name' => __('Allow lines update', 'datainjection'), 'datatype' => 'bool', 'massiveaction' => false, - ]; - - $tab[] = [ + ], [ 'id' => 5, 'table' => $this->getTable(), 'field' => 'itemtype', @@ -494,53 +488,41 @@ public function rawSearchOptions() 'datatype' => 'itemtypename', 'nosearch' => true, 'massiveaction' => false, - ]; - - $tab[] = [ + ], [ 'id' => 6, 'table' => $this->getTable(), 'field' => 'can_add_dropdown', 'name' => __('Allow creation of dropdowns (Except Entity)', 'datainjection'), 'datatype' => 'bool', - ]; - - $tab[] = [ + ], [ 'id' => 7, 'table' => $this->getTable(), 'field' => 'date_format', 'name' => __('Dates format', 'datainjection'), 'datatype' => 'specific', 'searchtype' => 'equals', - ]; - - $tab[] = [ + ], [ 'id' => 8, 'table' => $this->getTable(), 'field' => 'float_format', 'name' => __('Float format', 'datainjection'), 'datatype' => 'specific', 'searchtype' => 'equals', - ]; - - $tab[] = [ + ], [ 'id' => 10, 'table' => $this->getTable(), 'field' => 'port_unicity', 'name' => __('Port unicity criteria', 'datainjection'), 'datatype' => 'specific', 'searchtype' => 'equals', - ]; - - $tab[] = [ + ], [ 'id' => 11, 'table' => $this->getTable(), 'field' => 'is_private', 'name' => __('Private'), 'datatype' => 'bool', 'massiveaction' => false, - ]; - - $tab[] = [ + ], [ 'id' => 12, 'table' => $this->getTable(), 'field' => 'step', @@ -548,41 +530,31 @@ public function rawSearchOptions() 'datatype' => 'specific', 'searchtype' => 'equals', 'massiveaction' => false, - ]; - - $tab[] = [ + ], [ 'id' => 16, 'table' => $this->getTable(), 'field' => 'comment', 'name' => __('Comments'), 'datatype' => 'text', - ]; - - $tab[] = [ + ], [ 'id' => 80, 'table' => 'glpi_entities', 'field' => 'completename', 'name' => __('Entity'), 'datatype' => 'dropdown', - ]; - - $tab[] = [ + ], [ 'id' => 86, 'table' => $this->getTable(), 'field' => 'is_recursive', 'name' => __('Child entities'), 'datatype' => 'bool', - ]; - - $tab[] = [ + ], [ 'id' => 87, 'table' => $this->getTable(), 'field' => 'replace_multiline_value', 'name' => __('Replacing the value of multiline text fields', 'datainjection'), 'datatype' => 'bool', - ]; - - return $tab; + ]]; } @@ -599,6 +571,7 @@ public static function getSpecificValueToDisplay($field, $values, array $options if (!is_array($values)) { $values = [$field => $values]; } + switch ($field) { case "port_unicity": return PluginDatainjectionDropdown::getPortUnicityValues($values['port_unicity']); @@ -612,6 +585,7 @@ public static function getSpecificValueToDisplay($field, $values, array $options case "step": return PluginDatainjectionDropdown::getStatusLabel($values['step']); } + return parent::getSpecificValueToDisplay($field, $values, $options); } @@ -630,6 +604,7 @@ public static function getSpecificValueToSelect($field, $name = '', $values = '' if (!is_array($values)) { $values = [$field => $values]; } + $options['display'] = false; switch ($field) { case 'step': @@ -664,6 +639,7 @@ public static function getSpecificValueToSelect($field, $name = '', $values = '' $options, ); } + return parent::getSpecificValueToSelect($field, $name, $values, $options); } @@ -780,6 +756,7 @@ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) if ($canedit) { $tabs[3] = self::createTabEntry(__('File to inject', 'datainjection'), 0, $item::getType(), 'ti ti-file-download'); } + $tabs[4] = self::createTabEntry(__('Mappings', 'datainjection'), 0, $item::getType(), 'ti ti-columns'); if ($item->fields['step'] > self::MAPPING_STEP) { $tabs[5] = self::createTabEntry(__('Additional Information', 'datainjection'), 0, $item::getType(), 'ti ti-code-variable-plus'); @@ -788,6 +765,7 @@ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) } } } + return $tabs; } @@ -820,15 +798,18 @@ public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $ if ($item->fields['step'] > self::MAPPING_STEP) { PluginDatainjectionInfo::showFormInfos($item); } + break; case 6: if ($item->fields['step'] > self::MAPPING_STEP) { $item->showValidationForm(); } + break; } } + return true; } @@ -931,6 +912,7 @@ public function prepareInputForUpdate($input) ); return false; } + return $input; } @@ -947,6 +929,7 @@ public static function getInstance($type) if (is_a($class, CommonDBTM::class, true)) { return new $class(); } + return false; } @@ -956,8 +939,10 @@ public static function getInstanceByModelID($models_id) $model = new self(); $model->getFromDB($models_id); + $specific = self::getInstance($model->getFiletype()); $specific->getFromDBByModelID($models_id); + $model->specific_model = $specific; return $model; } @@ -993,6 +978,7 @@ public function readUploadedFile($options = []) ), ]; } + unset($_FILES['filename']); } @@ -1003,6 +989,7 @@ public function readUploadedFile($options = []) if (!$webservice) { Session::addMessageAfterRedirect($message, true, ERROR, false); } + //unlink($temporary_uniquefilename); return ['status' => ERROR, 'message' => $message, @@ -1031,8 +1018,10 @@ public function readUploadedFile($options = []) if ($delete_file) { $backend->deleteFile(); } + $this->backend = $backend; } + $this->injectionData = $injectionData; return true; } @@ -1077,9 +1066,10 @@ public function processUploadedFile($options = []) } else { $check['status'] = PluginDatainjectionCommonInjectionLib::SUCCESS; } + //There's an error if ($check['status'] != PluginDatainjectionCommonInjectionLib::SUCCESS && $mode == self::PROCESS) { - Session::addMessageAfterRedirect(htmlspecialchars($check['error_message']), true, ERROR); + Session::addMessageAfterRedirect(htmlspecialchars((string) $check['error_message']), true, ERROR); return false; } @@ -1138,7 +1128,7 @@ public function isFileCorrect() //If file columns don't match number of mappings in DB $nb = count($this->getMappings()); - if ($nb != count($header)) { + if ($nb !== count($header)) { $error_message = __('The number of columns of the file is incorrect.', 'datainjection') . "\n"; $error_message .= sprintf( _n('%d awaited column', '%d awaited columns', $nb, 'datainjection'), @@ -1182,13 +1172,13 @@ public function isFileCorrect() //If name of the mapping is not equal in the csv file header and in the DB $name_from_file = trim( mb_strtoupper( - $header[$mapping->getRank()], + (string) $header[$mapping->getRank()], 'UTF-8', ), ); - $name_from_db = trim(mb_strtoupper($mapping->getName(), 'UTF-8')); + $name_from_db = trim(mb_strtoupper((string) $mapping->getName(), 'UTF-8')); - if ($name_from_db != $name_from_file) { + if ($name_from_db !== $name_from_file) { if ($error['error_message'] == '') { $error['error_message'] = __('At least one column is incorrect', 'datainjection'); } @@ -1209,6 +1199,7 @@ public function isFileCorrect() } } } + return $error; } @@ -1243,6 +1234,7 @@ public function checkMandatoryFields($fields) } } } + return $check; } @@ -1299,6 +1291,7 @@ public static function checkRightOnModel($models_id) } } } + return $continue; } @@ -1335,6 +1328,7 @@ public static function showPreviewMappings($models_id) foreach ($mappings as $mapping) { echo"" . htmlescape($mapping->getMappingName()) . ""; } + echo ""; unset($lines[0]); } @@ -1344,9 +1338,11 @@ public static function showPreviewMappings($models_id) foreach ($line[0] as $value) { echo "" . htmlescape($value) . ""; } + echo ""; } } + Html::closeForm(); echo "
"; echo "" . __s('Close') . ""; @@ -1436,6 +1432,7 @@ class_exists('PluginGenericobjectType') } } } + return $todisplay; } @@ -1450,11 +1447,12 @@ public static function showLogResults($models_id) $nblines = 0; // Prépare le résumé - foreach ($logresults as $status => $results) { + foreach ($logresults as $results) { foreach ($results as $result) { if (!isset($resume[$result['status']][$result['type']])) { $resume[$result['status']][$result['type']] = 0; } + $resume[$result['status']][$result['type']]++; $nblines++; } @@ -1545,6 +1543,7 @@ public static function exportAsPDF($models_id) } } } + $pdf->render(); } } diff --git a/inc/modelcsv.class.php b/inc/modelcsv.class.php index 93000163..c643bf00 100644 --- a/inc/modelcsv.class.php +++ b/inc/modelcsv.class.php @@ -61,11 +61,14 @@ class PluginDatainjectionModelcsv extends CommonDBChild { public static $rightname = "plugin_datainjection_model"; + public $specific_fields; // From CommonDBChild public static $itemtype = 'PluginDatainjectionModel'; + public static $items_id = 'models_id'; + public $dohistory = true; diff --git a/inc/monitorinjection.class.php b/inc/monitorinjection.class.php index 1227327c..79d07ee6 100644 --- a/inc/monitorinjection.class.php +++ b/inc/monitorinjection.class.php @@ -110,6 +110,7 @@ public function addSpecificNeededFields($primary_type, $values) if (isset($values[$primary_type]['is_global'])) { $fields['is_global'] = empty($values[$primary_type]['is_global']) ? 0 : $values[$primary_type]['is_global']; } + return $fields; } } diff --git a/inc/networknameinjection.class.php b/inc/networknameinjection.class.php index 4d56937b..95746eed 100644 --- a/inc/networknameinjection.class.php +++ b/inc/networknameinjection.class.php @@ -101,11 +101,7 @@ public function addOrUpdateObject($values = [], $options = []) **/ public function addSpecificNeededFields($primary_type, $values) { - - $fields['items_id'] = $values['NetworkPort']['id']; - $fields['itemtype'] = "NetworkPort"; - - return $fields; + return ['items_id' => $values['NetworkPort']['id'], 'itemtype' => "NetworkPort"]; } diff --git a/inc/networkportinjection.class.php b/inc/networkportinjection.class.php index cdb391a7..79e722e5 100644 --- a/inc/networkportinjection.class.php +++ b/inc/networkportinjection.class.php @@ -135,6 +135,7 @@ public function addSpecificNeededFields($primary_type, $values) } else { $fields['instantiation_type'] = "NetworkPortEthernet"; } + return $fields; } @@ -155,6 +156,7 @@ public function showAdditionalInformation($info = [], $option = []) $instantiations[$inst_type] = call_user_func([$inst_type, 'getTypeName']); } } + Dropdown::showFromArray( 'instantiation_type', $instantiations, @@ -240,13 +242,11 @@ public function checkParameters($fields_toinject, $options) /** - * Build where sql request to look for a network port - * - * @param array $fields_toinject array the fields to insert into DB - * @param array $options array - * - * @return array - **/ + * Build where sql request to look for a network port + * + * @param array $fields_toinject array the fields to insert into DB + * @param array $options array + **/ public function getUnicityRequest($fields_toinject = [], $options = []): array { $where = []; @@ -330,12 +330,15 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) if ($use_name) { $sql .= " AND `glpi_networkequipments`.`name` = '" . $values['NetworkPort']["netname"] . "'"; } + if ($use_logical_number) { $sql .= " AND `glpi_networkports`.`logical_number` = '" . $values['NetworkPort']["netport"] . "'"; } + if ($use_mac) { $sql .= " AND `glpi_networkports`.`mac` = '" . $values['NetworkPort']["netmac"] . "'"; } + $res = $DB->doQuery($sql); //if at least one parameter is given @@ -352,5 +355,6 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) $netport_netport->add($tmp); } } //TODO add injection warning if no port found or more than one + return null; } } diff --git a/inc/notepadinjection.class.php b/inc/notepadinjection.class.php index f5333b76..40726f33 100644 --- a/inc/notepadinjection.class.php +++ b/inc/notepadinjection.class.php @@ -76,6 +76,7 @@ public function getOptions($primary_type = '') } else { $option['linkfield'] = $option['field']; } + $searchoptions[$option['id']] = $option; } } @@ -109,9 +110,6 @@ public function addOrUpdateObject($values = [], $options = []) **/ public function addSpecificNeededFields($primary_type, $values) { - - $fields['items_id'] = $values[$primary_type]['id']; - $fields['itemtype'] = $primary_type; - return $fields; + return ['items_id' => $values[$primary_type]['id'], 'itemtype' => $primary_type]; } } diff --git a/inc/peripheralinjection.class.php b/inc/peripheralinjection.class.php index 1fec9d8a..d40b6fd8 100644 --- a/inc/peripheralinjection.class.php +++ b/inc/peripheralinjection.class.php @@ -108,6 +108,7 @@ public function addSpecificNeededFields($primary_type, $values) if (isset($values[$primary_type]['is_global'])) { $fields['is_global'] = empty($values[$primary_type]['is_global']) ? 0 : $values[$primary_type]['is_global']; } + return $fields; } } diff --git a/inc/phoneinjection.class.php b/inc/phoneinjection.class.php index 756945a1..57e59bbe 100644 --- a/inc/phoneinjection.class.php +++ b/inc/phoneinjection.class.php @@ -109,6 +109,7 @@ public function addSpecificNeededFields($primary_type, $values) if (isset($values[$primary_type]['is_global'])) { $fields['is_global'] = empty($values[$primary_type]['is_global']) ? 0 : $values[$primary_type]['is_global']; } + return $fields; } } diff --git a/inc/printerinjection.class.php b/inc/printerinjection.class.php index 226329d0..caadd3ad 100644 --- a/inc/printerinjection.class.php +++ b/inc/printerinjection.class.php @@ -111,6 +111,7 @@ public function addSpecificNeededFields($primary_type, $values) if (isset($values[$primary_type]['is_global'])) { $fields['is_global'] = empty($values[$primary_type]['is_global']) ? 0 : $values[$primary_type]['is_global']; } + return $fields; } @@ -139,6 +140,7 @@ public function processDictionnariesIfNeeded(&$values) if (isset($res_rule['_ignore_import']) && $res_rule['_ignore_import']) { return false; } + if (isset($res_rule['is_global'])) { $values['Printer']['is_global'] = $res_rule['is_global']; } @@ -152,6 +154,7 @@ public function processDictionnariesIfNeeded(&$values) = Dropdown::getDropdownName('glpi_suppliers', $res_rule['supplier']); } } + return true; } } diff --git a/inc/profile.class.php b/inc/profile.class.php index 8ad92d4b..d2f913da 100644 --- a/inc/profile.class.php +++ b/inc/profile.class.php @@ -35,7 +35,7 @@ class PluginDatainjectionProfile extends Profile public static function getAllRights() { - $rights = [ + return [ ['itemtype' => 'PluginDatainjectionModel', 'label' => __('Model management', 'datainjection'), 'field' => 'plugin_datainjection_model', @@ -46,7 +46,6 @@ public static function getAllRights() 'rights' => [READ => __('Read')], ], ]; - return $rights; } /** @@ -59,7 +58,7 @@ public function cleanProfiles($ID) /** @var DBmysql $DB */ global $DB; $query = "DELETE FROM `glpi_profiles` - WHERE `profiles_id`='$ID' + WHERE `profiles_id`='{$ID}' AND `name` LIKE '%plugin_datainjection%'"; $DB->doQuery($query); } @@ -71,8 +70,10 @@ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) if ($item->fields['interface'] == 'central') { return self::createTabEntry(__('Data injection', 'datainjection'), 0, $item::getType(), 'ti ti-download'); } + return ''; } + return ''; } @@ -90,6 +91,7 @@ public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $ ); $profile->showForm($ID); } + return true; } @@ -161,6 +163,7 @@ public static function migrateProfiles() $value = 0; break; } + self::addDefaultProfileInfos($id, ['plugin_datainjection_model' => $value]); if ($value > 0) { self::addDefaultProfileInfos($id, ['plugin_datainjection_use' => READ]); @@ -169,6 +172,7 @@ public static function migrateProfiles() } } } + return null; } public function showForm($ID, $options = []) @@ -199,6 +203,7 @@ public function showForm($ID, $options = []) echo "
\n"; Html::closeForm(); } + echo ""; return true; diff --git a/inc/profileinjection.class.php b/inc/profileinjection.class.php index bdbb9997..0bcd723d 100644 --- a/inc/profileinjection.class.php +++ b/inc/profileinjection.class.php @@ -77,28 +77,19 @@ public function getOptions($primary_type = '') public function checkType($field_name, $data, $mandatory) { - switch ($field_name) { - case 'right_rw': - return (in_array($data, ['r', 'w']) - ? PluginDatainjectionCommonInjectionLib::SUCCESS - : PluginDatainjectionCommonInjectionLib::TYPE_MISMATCH); - - case 'right_r': - return (($data == 'r') ? PluginDatainjectionCommonInjectionLib::SUCCESS - : PluginDatainjectionCommonInjectionLib::TYPE_MISMATCH); - - case 'right_w': - return (($data == 'w') ? PluginDatainjectionCommonInjectionLib::SUCCESS - : PluginDatainjectionCommonInjectionLib::TYPE_MISMATCH); - - case 'interface': - return (in_array($data, ['helpdesk', 'central']) - ? PluginDatainjectionCommonInjectionLib::SUCCESS - : PluginDatainjectionCommonInjectionLib::TYPE_MISMATCH); - - default: - return PluginDatainjectionCommonInjectionLib::SUCCESS; - } + return match ($field_name) { + 'right_rw' => in_array($data, ['r', 'w']) + ? PluginDatainjectionCommonInjectionLib::SUCCESS + : PluginDatainjectionCommonInjectionLib::TYPE_MISMATCH, + 'right_r' => ($data == 'r') ? PluginDatainjectionCommonInjectionLib::SUCCESS + : PluginDatainjectionCommonInjectionLib::TYPE_MISMATCH, + 'right_w' => ($data == 'w') ? PluginDatainjectionCommonInjectionLib::SUCCESS + : PluginDatainjectionCommonInjectionLib::TYPE_MISMATCH, + 'interface' => in_array($data, ['helpdesk', 'central']) + ? PluginDatainjectionCommonInjectionLib::SUCCESS + : PluginDatainjectionCommonInjectionLib::TYPE_MISMATCH, + default => PluginDatainjectionCommonInjectionLib::SUCCESS, + }; } diff --git a/inc/session.class.php b/inc/session.class.php index ea89a770..a0281787 100644 --- a/inc/session.class.php +++ b/inc/session.class.php @@ -47,6 +47,7 @@ public static function unserialize(string $data) if (function_exists('Safe\unserialize')) { return \Safe\unserialize($data); } + // @phpstan-ignore theCodingMachineSafe.function return unserialize($data); } @@ -65,22 +66,22 @@ public static function getParam($param) if (!isset($_SESSION['datainjection'][$param])) { return false; } + if (in_array($param, ['results', 'error_lines', 'injection_lines', 'injection_results', 'injection_error_lines'])) { $fic = $_SESSION['datainjection'][$param]; return file_get_contents(GLPI_TMP_DIR . '/' . $fic); } + return $_SESSION['datainjection'][$param]; } /** - * Set a parameter in the HTTP session - * - * @param string $param the parameter - * @param array|string|false $results the value to store - * - * @return void - **/ + * Set a parameter in the HTTP session + * + * @param string $param the parameter + * @param array|string|false $results the value to store + **/ public static function setParam($param, $results): void { @@ -91,6 +92,7 @@ public static function setParam($param, $results): void unlink($old_fic); } } + $fic = Session::getLoginUserID() . '_' . $param . '_' . microtime(true); file_put_contents(GLPI_TMP_DIR . '/' . $fic, $results); $_SESSION['datainjection'][$param] = $fic; @@ -101,10 +103,8 @@ public static function setParam($param, $results): void /** - * Remove all parameters from the HTTP session - * - * @return void - */ + * Remove all parameters from the HTTP session + */ public static function removeParams(): void { @@ -117,6 +117,7 @@ public static function removeParams(): void } } } + unset($_SESSION['datainjection']); } } diff --git a/inc/softwareinjection.class.php b/inc/softwareinjection.class.php index fb544cab..526a3eb3 100644 --- a/inc/softwareinjection.class.php +++ b/inc/softwareinjection.class.php @@ -105,20 +105,25 @@ public function processDictionnariesIfNeeded(&$values) if (isset($res_rule['_ignore_import']) && $res_rule['_ignore_import']) { return false; } + if (isset($res_rule['is_helpdesk_visible'])) { $values['Software']['is_helpdesk_visible'] = $res_rule['is_helpdesk_visible']; } + if (isset($res_rule['version'])) { $values['SoftwareVersion']['name'] = $res_rule['version']; } + if (isset($res_rule['name'])) { $values['Software']['name'] = $res_rule['name']; } + if (isset($res_rule['supplier']) && isset($values['supplier'])) { $values['Software']['manufacturers_id'] = Dropdown::getDropdownName('glpi_suppliers', $res_rule['supplier']); } } + return true; } diff --git a/inc/softwarelicenseinjection.class.php b/inc/softwarelicenseinjection.class.php index a5b08f9c..ae1791e0 100644 --- a/inc/softwarelicenseinjection.class.php +++ b/inc/softwarelicenseinjection.class.php @@ -86,7 +86,7 @@ public function getOptions($primary_type = '') $options['ignore_fields'] = array_merge($blacklist, $notimportable); - $key = array_search(2, $options['ignore_fields']); + $key = array_search(2, $options['ignore_fields'], true); unset($options['ignore_fields'][$key]); $options['displaytype'] = ["dropdown" => [5, 6, 7, 110], @@ -193,6 +193,7 @@ public function addSpecificNeededFields($primary_type, $values) if ($primary_type == 'Software') { $fields['softwares_id'] = $values[$primary_type]['id']; } + return $fields; } @@ -210,6 +211,7 @@ public function checkPresent($fields_toinject = [], $options = []): array 'name' => $fields_toinject['SoftwareLicense']['name'], ]; } + return []; } } diff --git a/inc/softwareversioninjection.class.php b/inc/softwareversioninjection.class.php index fc9f2755..202d2029 100644 --- a/inc/softwareversioninjection.class.php +++ b/inc/softwareversioninjection.class.php @@ -83,7 +83,7 @@ public function getOptions($primary_type = '') $options['ignore_fields'] = array_merge($blacklist, $notimportable); - $key = array_search(2, $options['ignore_fields']); + $key = array_search(2, $options['ignore_fields'], true); unset($options['ignore_fields'][$key]); $options['displaytype'] = ["dropdown" => [4,31], @@ -188,15 +188,15 @@ public function addSpecificNeededFields($primary_type, $values) if ($primary_type == 'Software') { $fields['softwares_id'] = $values[$primary_type]['id']; } + return $fields; } /** - * @param array $fields_toinject array - * @param array $options array - * @return array - **/ + * @param array $fields_toinject array + * @param array $options array + **/ public function checkPresent($fields_toinject = [], $options = []): array { if ($options['itemtype'] != 'SoftwareVersion') { @@ -205,6 +205,7 @@ public function checkPresent($fields_toinject = [], $options = []): array 'name' => $fields_toinject['SoftwareVersion']['name'], ]; } + return []; } } diff --git a/inc/userinjection.class.php b/inc/userinjection.class.php index f40cb56e..f215a18c 100644 --- a/inc/userinjection.class.php +++ b/inc/userinjection.class.php @@ -189,7 +189,7 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) if (isset($values['User']['useremails_id']) && $rights['add_dropdown'] && Session::haveRight('user', UPDATE)) { $emails = preg_split('/[\s,;]+/', $values['User']['useremails_id'], -1, PREG_SPLIT_NO_EMPTY); foreach ($emails as $email) { - $email = trim($email); + $email = trim((string) $email); if (filter_var($email, FILTER_VALIDATE_EMAIL) && !countElementsInTable( "glpi_useremails", [ @@ -207,6 +207,7 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) if (!countElementsInTable("glpi_useremails", ['users_id' => $values['User']['id']])) { $tmp['is_default'] = 1; } + $useremail->add($tmp); } } diff --git a/rector.php b/rector.php index 0d45de14..efe32495 100644 --- a/rector.php +++ b/rector.php @@ -28,71 +28,28 @@ * ------------------------------------------------------------------------- */ +use Rector\Configuration\RectorConfigBuilder; + require_once __DIR__ . '/../../src/Plugin.php'; -use Rector\Caching\ValueObject\Storage\FileCacheStorage; -use Rector\CodeQuality\Rector as CodeQuality; -use Rector\Config\RectorConfig; -use Rector\DeadCode\Rector as DeadCode; -use Rector\ValueObject\PhpVersion; +$baseline_file = __DIR__ . '/../../PluginsRector.php'; +if (!file_exists($baseline_file)) { + throw new RuntimeException( + sprintf( + 'Unable to find "%s". Running rector on a plugin requires a GLPI development checkout that ships PluginsRector.php.', + $baseline_file, + ), + ); +} + +$baseline = require $baseline_file; + +/** @var RectorConfigBuilder $config */ +$config = $baseline([ + __DIR__ . '/ajax', + __DIR__ . '/front', + __DIR__ . '/inc', + __DIR__ . '/tests', +]); -return RectorConfig::configure() - ->withPaths([ - __DIR__ . '/ajax', - __DIR__ . '/front', - __DIR__ . '/inc', - ]) - ->withPhpVersion(PhpVersion::PHP_82) - ->withCache( - cacheClass: FileCacheStorage::class, - cacheDirectory: sys_get_temp_dir() . '/datainjection-rector', - ) - ->withRootFiles() - ->withParallel(timeoutSeconds: 300) - ->withImportNames(removeUnusedImports: true) - ->withRules([ - CodeQuality\Assign\CombinedAssignRector::class, - CodeQuality\BooleanAnd\RemoveUselessIsObjectCheckRector::class, - CodeQuality\BooleanAnd\SimplifyEmptyArrayCheckRector::class, - CodeQuality\BooleanNot\ReplaceMultipleBooleanNotRector::class, - CodeQuality\Catch_\ThrowWithPreviousExceptionRector::class, - CodeQuality\Empty_\SimplifyEmptyCheckOnEmptyArrayRector::class, - CodeQuality\Expression\InlineIfToExplicitIfRector::class, - CodeQuality\Expression\TernaryFalseExpressionToIfRector::class, - CodeQuality\For_\ForRepeatedCountToOwnVariableRector::class, - CodeQuality\Foreach_\ForeachItemsAssignToEmptyArrayToAssignRector::class, - CodeQuality\Foreach_\ForeachToInArrayRector::class, - CodeQuality\Foreach_\SimplifyForeachToCoalescingRector::class, - CodeQuality\Foreach_\UnusedForeachValueToArrayKeysRector::class, - CodeQuality\FuncCall\ChangeArrayPushToArrayAssignRector::class, - CodeQuality\FuncCall\CompactToVariablesRector::class, - CodeQuality\FuncCall\InlineIsAInstanceOfRector::class, - CodeQuality\FuncCall\IsAWithStringWithThirdArgumentRector::class, - CodeQuality\FuncCall\RemoveSoleValueSprintfRector::class, - CodeQuality\FuncCall\SetTypeToCastRector::class, - CodeQuality\FuncCall\SimplifyFuncGetArgsCountRector::class, - CodeQuality\FuncCall\SimplifyInArrayValuesRector::class, - CodeQuality\FuncCall\SimplifyStrposLowerRector::class, - CodeQuality\FuncCall\UnwrapSprintfOneArgumentRector::class, - CodeQuality\Identical\BooleanNotIdenticalToNotIdenticalRector::class, - CodeQuality\Identical\SimplifyArraySearchRector::class, - CodeQuality\Identical\SimplifyConditionsRector::class, - CodeQuality\Identical\StrlenZeroToIdenticalEmptyStringRector::class, - CodeQuality\If_\CombineIfRector::class, - CodeQuality\If_\CompleteMissingIfElseBracketRector::class, - CodeQuality\If_\ConsecutiveNullCompareReturnsToNullCoalesceQueueRector::class, - CodeQuality\If_\ExplicitBoolCompareRector::class, - CodeQuality\If_\ShortenElseIfRector::class, - CodeQuality\If_\SimplifyIfElseToTernaryRector::class, - CodeQuality\If_\SimplifyIfNotNullReturnRector::class, - CodeQuality\If_\SimplifyIfNullableReturnRector::class, - CodeQuality\If_\SimplifyIfReturnBoolRector::class, - CodeQuality\Include_\AbsolutizeRequireAndIncludePathRector::class, - CodeQuality\LogicalAnd\AndAssignsToSeparateLinesRector::class, - CodeQuality\LogicalAnd\LogicalToBooleanRector::class, - CodeQuality\NotEqual\CommonNotEqualRector::class, - CodeQuality\Ternary\UnnecessaryTernaryExpressionRector::class, - DeadCode\Assign\RemoveUnusedVariableAssignRector::class, - ]) - ->withPhpSets(php74: true) // apply PHP sets up to PHP 7.4 -; +return $config; diff --git a/setup.php b/setup.php index 7cb92eb0..99293671 100644 --- a/setup.php +++ b/setup.php @@ -64,6 +64,7 @@ function plugin_init_datainjection() if (!plugin_datainjection_checkDirectories()) { @ mkdir(PLUGIN_DATAINJECTION_UPLOAD_DIR); } + $PLUGIN_HOOKS["config_page"]['datainjection'] = "front/clientinjection.form.php"; @@ -109,8 +110,6 @@ function plugin_version_datainjection() /** * Return all types that can be injected using datainjection - * - * @return void */ function getTypesToInject(): void { @@ -234,7 +233,7 @@ function plugin_datainjection_migratetypes_datainjection($types) function plugin_datainjection_checkDirectories() { - return !(!file_exists(PLUGIN_DATAINJECTION_UPLOAD_DIR) || !is_writable(PLUGIN_DATAINJECTION_UPLOAD_DIR)); + return file_exists(PLUGIN_DATAINJECTION_UPLOAD_DIR) && is_writable(PLUGIN_DATAINJECTION_UPLOAD_DIR); } function plugin_datainjection_geturl(): string diff --git a/tests/unit/CommonInjectionLibDateTimeTest.php b/tests/unit/CommonInjectionLibDateTimeTest.php index 263ef07b..f82a2045 100644 --- a/tests/unit/CommonInjectionLibDateTimeTest.php +++ b/tests/unit/CommonInjectionLibDateTimeTest.php @@ -132,6 +132,7 @@ public function testDatetimeWithMicrosecondsAndTimezoneIsInjected(): void ); $lib->processAddOrUpdate(); + $results = $lib->getInjectionResults(); self::assertSame(PluginDatainjectionCommonInjectionLib::SUCCESS, $results['status']); diff --git a/tests/unit/CommonInjectionLibFloatDetectionTest.php b/tests/unit/CommonInjectionLibFloatDetectionTest.php index a02587c2..e694d218 100644 --- a/tests/unit/CommonInjectionLibFloatDetectionTest.php +++ b/tests/unit/CommonInjectionLibFloatDetectionTest.php @@ -50,7 +50,7 @@ */ final class CommonInjectionLibFloatDetectionTest extends DbTestCase { - private static function getFloatDetectionRegex(): string + private function getFloatDetectionRegex(): string { $lib = new PluginDatainjectionCommonInjectionLib(new PluginDatainjectionComputerInjection()); @@ -93,7 +93,7 @@ public static function floatDetectionProvider(): array */ public function testFloatDetectionRegex(string $value, bool $expected_match): void { - $regex = self::getFloatDetectionRegex(); + $regex = $this->getFloatDetectionRegex(); self::assertSame($expected_match, preg_match($regex, $value) !== 0); } diff --git a/tests/unit/GroupInjectionTest.php b/tests/unit/GroupInjectionTest.php index 56f27514..693bb25f 100644 --- a/tests/unit/GroupInjectionTest.php +++ b/tests/unit/GroupInjectionTest.php @@ -114,6 +114,7 @@ public function testAssigneGroupToInjectedAssignableItem( ); $lib->processAddOrUpdate(); + $results = $lib->getInjectionResults(); self::assertSame(PluginDatainjectionCommonInjectionLib::SUCCESS, $results['status']); @@ -197,6 +198,7 @@ public function testGroupIsAssignedToInjectedNonAssignableItem( ); $lib->processAddOrUpdate(); + $results = $lib->getInjectionResults(); self::assertSame(PluginDatainjectionCommonInjectionLib::SUCCESS, $results['status']); @@ -283,6 +285,7 @@ public function testGroupIsUpdatedOnExistingAssignableItem( ); $lib->processAddOrUpdate(); + $results = $lib->getInjectionResults(); self::assertSame(PluginDatainjectionCommonInjectionLib::SUCCESS, $results['status']); @@ -294,6 +297,7 @@ public function testGroupIsUpdatedOnExistingAssignableItem( if (!is_array($field_value)) { $field_value = [$field_value]; } + self::assertContains($group->getID(), $field_value); } @@ -340,6 +344,7 @@ public function testGroupIsUpdatedOnExistingNonAssignableItem(): void ); $lib->processAddOrUpdate(); + $results = $lib->getInjectionResults(); self::assertSame( From 2f44562cfc4593435d5f3cea04e37308f92ebb12 Mon Sep 17 00:00:00 2001 From: Rom1-B <8530352+Rom1-B@users.noreply.github.com> Date: Fri, 28 Aug 2026 09:09:43 +0200 Subject: [PATCH 2/3] fix --- inc/commoninjectionlib.class.php | 6 +++--- inc/info.class.php | 1 + inc/model.class.php | 22 +++++++--------------- inc/networkportinjection.class.php | 4 +++- inc/profile.class.php | 1 + 5 files changed, 15 insertions(+), 19 deletions(-) diff --git a/inc/commoninjectionlib.class.php b/inc/commoninjectionlib.class.php index d0b75ea6..c3e329fd 100644 --- a/inc/commoninjectionlib.class.php +++ b/inc/commoninjectionlib.class.php @@ -1149,7 +1149,7 @@ private function reformatThirdPass() case "date": //If the value is a date, try to reformat it if it's not the good type //(dd-mm-yyyy instead of yyyy-mm-dd) - $date = $this->reformatDate($value, $this->getDateFormat()); + $date = self::reformatDate($value, $this->getDateFormat()); $this->setValueForItemtype($itemtype, $field, $date); break; @@ -1234,7 +1234,7 @@ private function reformatFloat($value, $format) * * @return string the date reformated, if needed **/ - private function reformatDate($original_date, $date_format) + private static function reformatDate($original_date, $date_format) { if (empty($original_date)) { @@ -1305,7 +1305,7 @@ private function reformatDateTime($original_datetime, $date_format) $time_part = '00:00:00'; } - $new_date = $this->reformatDate($date_part, $date_format); + $new_date = self::reformatDate($date_part, $date_format); if ($new_date === "NULL") { return "NULL"; } diff --git a/inc/info.class.php b/inc/info.class.php index c2ffe04f..82758ef6 100644 --- a/inc/info.class.php +++ b/inc/info.class.php @@ -460,6 +460,7 @@ public static function keepInfo(PluginDatainjectionInfo $info, $value) return $value != PluginDatainjectionCommonInjectionLib::DROPDOWN_EMPTY_VALUE; } } + return null; } diff --git a/inc/model.class.php b/inc/model.class.php index 09c97de3..8fbbfd0e 100644 --- a/inc/model.class.php +++ b/inc/model.class.php @@ -572,21 +572,13 @@ public static function getSpecificValueToDisplay($field, $values, array $options $values = [$field => $values]; } - switch ($field) { - case "port_unicity": - return PluginDatainjectionDropdown::getPortUnicityValues($values['port_unicity']); - - case "float_format": - return PluginDatainjectionDropdown::getFloatFormat($values['float_format']); - - case "date_format": - return PluginDatainjectionDropdown::getDateFormat($values['date_format']); - - case "step": - return PluginDatainjectionDropdown::getStatusLabel($values['step']); - } - - return parent::getSpecificValueToDisplay($field, $values, $options); + return match ($field) { + "port_unicity" => PluginDatainjectionDropdown::getPortUnicityValues($values['port_unicity']), + "float_format" => PluginDatainjectionDropdown::getFloatFormat($values['float_format']), + "date_format" => PluginDatainjectionDropdown::getDateFormat($values['date_format']), + "step" => PluginDatainjectionDropdown::getStatusLabel($values['step']), + default => parent::getSpecificValueToDisplay($field, $values, $options), + }; } diff --git a/inc/networkportinjection.class.php b/inc/networkportinjection.class.php index 79e722e5..3b56edf7 100644 --- a/inc/networkportinjection.class.php +++ b/inc/networkportinjection.class.php @@ -354,7 +354,9 @@ public function processAfterInsertOrUpdate($values, $add = true, $rights = []) $tmp['networkports_id_2'] = $netport['id']; $netport_netport->add($tmp); } - } //TODO add injection warning if no port found or more than one + } + + //TODO add injection warning if no port found or more than one return null; } } diff --git a/inc/profile.class.php b/inc/profile.class.php index d2f913da..bd657c27 100644 --- a/inc/profile.class.php +++ b/inc/profile.class.php @@ -172,6 +172,7 @@ public static function migrateProfiles() } } } + return null; } From 4504bec1f50c1cb2b98ab90c04dbc306ac45330b Mon Sep 17 00:00:00 2001 From: Rom1-B <8530352+Rom1-B@users.noreply.github.com> Date: Fri, 28 Aug 2026 13:08:00 +0200 Subject: [PATCH 3/3] fix --- CHANGELOG.md | 2 +- inc/clientinjection.class.php | 4 ++-- inc/commoninjectionlib.class.php | 6 +++--- tests/unit/CommonInjectionLibDateTimeTest.php | 8 +++++++- 4 files changed, 13 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 635162b5..619e4b38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ 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] +## [UNRELEASED] ### Fixed diff --git a/inc/clientinjection.class.php b/inc/clientinjection.class.php index 661b8d47..cf244faf 100644 --- a/inc/clientinjection.class.php +++ b/inc/clientinjection.class.php @@ -342,7 +342,7 @@ public static function exportErrorsInCSV() if (!in_array($error_lines, ['', '0', []], true)) { $model = PluginDatainjectionSession::unserialize(PluginDatainjectionSession::getParam('currentmodel')); - $file = PLUGIN_DATAINJECTION_UPLOAD_DIR . basename(PluginDatainjectionSession::getParam('file_name')); + $file = PLUGIN_DATAINJECTION_UPLOAD_DIR . basename((string) PluginDatainjectionSession::getParam('file_name')); $mappings = $model->getMappings(); $tmpfile = fopen($file, 'w'); @@ -360,7 +360,7 @@ public static function exportErrorsInCSV() fclose($tmpfile); - $name = "Error-" . basename(PluginDatainjectionSession::getParam('file_name')); + $name = "Error-" . basename((string) PluginDatainjectionSession::getParam('file_name')); $name = str_replace(' ', '', $name); header('Content-disposition: attachment; filename=' . $name); header('Content-Type: application/octet-stream'); diff --git a/inc/commoninjectionlib.class.php b/inc/commoninjectionlib.class.php index c3e329fd..d0b75ea6 100644 --- a/inc/commoninjectionlib.class.php +++ b/inc/commoninjectionlib.class.php @@ -1149,7 +1149,7 @@ private function reformatThirdPass() case "date": //If the value is a date, try to reformat it if it's not the good type //(dd-mm-yyyy instead of yyyy-mm-dd) - $date = self::reformatDate($value, $this->getDateFormat()); + $date = $this->reformatDate($value, $this->getDateFormat()); $this->setValueForItemtype($itemtype, $field, $date); break; @@ -1234,7 +1234,7 @@ private function reformatFloat($value, $format) * * @return string the date reformated, if needed **/ - private static function reformatDate($original_date, $date_format) + private function reformatDate($original_date, $date_format) { if (empty($original_date)) { @@ -1305,7 +1305,7 @@ private function reformatDateTime($original_datetime, $date_format) $time_part = '00:00:00'; } - $new_date = self::reformatDate($date_part, $date_format); + $new_date = $this->reformatDate($date_part, $date_format); if ($new_date === "NULL") { return "NULL"; } diff --git a/tests/unit/CommonInjectionLibDateTimeTest.php b/tests/unit/CommonInjectionLibDateTimeTest.php index f82a2045..2cc8e5fe 100644 --- a/tests/unit/CommonInjectionLibDateTimeTest.php +++ b/tests/unit/CommonInjectionLibDateTimeTest.php @@ -89,12 +89,18 @@ public static function reformatDateTimeProvider(): array */ public function testReformatDateTime(string $original, string $date_format, string $expected): void { + $lib = new PluginDatainjectionCommonInjectionLib( + new PluginDatainjectionComputerInjection(), + [], + [], + ); + $reformat_datetime = new ReflectionMethod( PluginDatainjectionCommonInjectionLib::class, 'reformatDateTime', ); - self::assertSame($expected, $reformat_datetime->invoke(null, $original, $date_format)); + self::assertSame($expected, $reformat_datetime->invoke($lib, $original, $date_format)); } /**