diff --git a/.twig_cs.dist.php b/.twig_cs.dist.php index 352fe0a6..6041bcf7 100644 --- a/.twig_cs.dist.php +++ b/.twig_cs.dist.php @@ -2,14 +2,16 @@ declare(strict_types=1); -use FriendsOfTwig\Twigcs; +use FriendsOfTwig\Twigcs\Finder\TemplateFinder; +use FriendsOfTwig\Twigcs\Config\Config; +use Glpi\Tools\GlpiTwigRuleset; -$finder = Twigcs\Finder\TemplateFinder::create() +$finder = TemplateFinder::create() ->in(__DIR__ . '/templates') ->name('*.html.twig') ->ignoreVCSIgnored(true); -return Twigcs\Config\Config::create() +return Config::create() ->setFinder($finder) - ->setRuleSet(\Glpi\Tools\GlpiTwigRuleset::class) + ->setRuleSet(GlpiTwigRuleset::class) ; diff --git a/ajax/container.php b/ajax/container.php index d3bf41fb..fdad86a9 100644 --- a/ajax/container.php +++ b/ajax/container.php @@ -28,15 +28,16 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); -Session::checkLoginUser(); +use Glpi\Exception\Http\AccessDeniedHttpException; +use Glpi\Exception\Http\NotFoundHttpException; +Session::checkLoginUser(); if (isset($_GET['action']) && $_GET['action'] === 'get_fields_html') { $right = PluginFieldsProfile::getRightOnContainer($_SESSION['glpiactiveprofile']['id'], $_GET['id']); if ($right < READ) { - throw new \Glpi\Exception\Http\AccessDeniedHttpException(); + throw new AccessDeniedHttpException(); } $containers_id = $_GET['id']; @@ -49,7 +50,7 @@ $dbu = new DbUtils(); $item = $dbu->getItemForItemtype($itemtype); if ($items_id > 0 && !$item->getFromDB($items_id)) { - throw new \Glpi\Exception\Http\NotFoundHttpException(); + throw new NotFoundHttpException(); } $item->input = $input; @@ -65,5 +66,5 @@ echo ''; } } else { - throw new \Glpi\Exception\Http\NotFoundHttpException(); + throw new NotFoundHttpException(); } diff --git a/ajax/container_display_condition.php b/ajax/container_display_condition.php index be7ef2d7..d0aafb91 100644 --- a/ajax/container_display_condition.php +++ b/ajax/container_display_condition.php @@ -27,8 +27,6 @@ * @link https://github.com/pluginsGLPI/fields * ------------------------------------------------------------------------- */ - -include('../../../inc/includes.php'); Session::checkLoginUser(); if (isset($_GET['action'])) { @@ -55,5 +53,5 @@ } } } else { - throw new \RuntimeException('Invalid request', 400); + throw new RuntimeException('Invalid request', 400); } diff --git a/ajax/container_itemtypes_dropdown.php b/ajax/container_itemtypes_dropdown.php index d397e7a2..c527174c 100644 --- a/ajax/container_itemtypes_dropdown.php +++ b/ajax/container_itemtypes_dropdown.php @@ -28,7 +28,6 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); Session::checkLoginUser(); PluginFieldsContainer::showFormItemtype($_REQUEST); diff --git a/ajax/container_subtype_dropdown.php b/ajax/container_subtype_dropdown.php index 7a482bba..0b70b3f9 100644 --- a/ajax/container_subtype_dropdown.php +++ b/ajax/container_subtype_dropdown.php @@ -28,7 +28,6 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); Session::checkLoginUser(); PluginFieldsContainer::showFormSubtype($_REQUEST, true); diff --git a/ajax/field_specific_fields.php b/ajax/field_specific_fields.php index 4e0093bb..7888b672 100644 --- a/ajax/field_specific_fields.php +++ b/ajax/field_specific_fields.php @@ -31,7 +31,6 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); header('Content-Type: text/html; charset=UTF-8'); Html::header_nocache(); Session::checkLoginUser(); @@ -66,11 +65,9 @@ echo implode( ', ', array_map( - function ($itemtype) { - return is_a($itemtype, CommonDBTM::class, true) - ? $itemtype::getTypeName(Session::getPluralNumber()) - : $itemtype; - }, + fn($itemtype) => is_a($itemtype, CommonDBTM::class, true) + ? $itemtype::getTypeName(Session::getPluralNumber()) + : $itemtype, $allowed_itemtypes, ), ); diff --git a/ajax/reorder.php b/ajax/reorder.php index 38ff3c18..67e35c09 100644 --- a/ajax/reorder.php +++ b/ajax/reorder.php @@ -28,7 +28,8 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); +use Glpi\DBAL\QueryExpression; + Session::checkLoginUser(); if ( @@ -37,7 +38,7 @@ || !array_key_exists('new_order', $_POST) ) { // Missing input - throw new \RuntimeException('Missing input', 400); + throw new RuntimeException('Missing input', 400); } $table = PluginFieldsField::getTable(); @@ -62,7 +63,7 @@ if (0 === $field_iterator->count()) { // Unknown field - throw new \RuntimeException('Unknown field', 404); + throw new RuntimeException('Unknown field', 404); } $field_id = $field_iterator->current()['id']; @@ -72,7 +73,7 @@ $DB->update( $table, [ - 'ranking' => new \Glpi\DBAL\QueryExpression($DB->quoteName('ranking') . ' - 1'), + 'ranking' => new QueryExpression($DB->quoteName('ranking') . ' - 1'), ], [ 'plugin_fields_containers_id' => $container_id, @@ -84,7 +85,7 @@ $DB->update( $table, [ - 'ranking' => new \Glpi\DBAL\QueryExpression($DB->quoteName('ranking') . ' + 1'), + 'ranking' => new QueryExpression($DB->quoteName('ranking') . ' + 1'), ], [ 'plugin_fields_containers_id' => $container_id, diff --git a/ajax/status_override.php b/ajax/status_override.php index 0e1d2681..ae780789 100644 --- a/ajax/status_override.php +++ b/ajax/status_override.php @@ -28,7 +28,6 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); Session::checkLoginUser(); if (isset($_GET['action'])) { @@ -43,5 +42,5 @@ $status_override->showForm($_GET['id'], $_GET); } } else { - throw new \RuntimeException('Invalid request', 400); + throw new RuntimeException('Invalid request', 400); } diff --git a/ajax/viewtranslations.php b/ajax/viewtranslations.php index 995f1e9a..96342c86 100644 --- a/ajax/viewtranslations.php +++ b/ajax/viewtranslations.php @@ -32,22 +32,17 @@ * @brief */ -include('../../../inc/includes.php'); header('Content-Type: text/html; charset=UTF-8'); Html::header_nocache(); Session::checkLoginUser(); if (!isset($_POST['itemtype']) || !isset($_POST['items_id']) || !isset($_POST['id'])) { - throw new \RuntimeException('Missing required parameters', 400); + throw new RuntimeException('Missing required parameters', 400); } $translation = new PluginFieldsLabelTranslation(); -if ($_POST['id'] == -1) { - $canedit = $translation->can(-1, CREATE, $_POST); -} else { - $canedit = $translation->can($_POST['id'], UPDATE); -} +$canedit = $_POST['id'] == -1 ? $translation->can(-1, CREATE, $_POST) : $translation->can($_POST['id'], UPDATE); if ($canedit) { $translation->showFormForItem($_POST['itemtype'], $_POST['items_id'], $_POST['id']); } else { diff --git a/front/container.php b/front/container.php index 933fc66a..1ce24fc2 100644 --- a/front/container.php +++ b/front/container.php @@ -28,7 +28,6 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); Session::checkLoginUser(); Html::header( diff --git a/front/containerdisplaycondition.form.php b/front/containerdisplaycondition.form.php index bb8cdda7..e43ddf46 100644 --- a/front/containerdisplaycondition.form.php +++ b/front/containerdisplaycondition.form.php @@ -28,7 +28,6 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); Session::checkRight('config', READ); $status_override = new PluginFieldsContainerDisplayCondition(); diff --git a/front/export_to_yaml.php b/front/export_to_yaml.php index cfd132d4..150cfaa1 100644 --- a/front/export_to_yaml.php +++ b/front/export_to_yaml.php @@ -28,8 +28,7 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); -include('../hook.php'); +include(__DIR__ . '/../hook.php'); Session::checkRight('config', READ); diff --git a/front/field.form.php b/front/field.form.php index da7323ea..01c4d1b5 100644 --- a/front/field.form.php +++ b/front/field.form.php @@ -28,7 +28,6 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); if (empty($_GET['id'])) { $_GET['id'] = ''; diff --git a/front/labeltranslation.form.php b/front/labeltranslation.form.php index 00eabac5..2fe48d14 100644 --- a/front/labeltranslation.form.php +++ b/front/labeltranslation.form.php @@ -28,7 +28,6 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); Session::checkRight('config', UPDATE); $translation = new PluginFieldsLabelTranslation(); diff --git a/front/profile.form.php b/front/profile.form.php index dc769620..1426e606 100644 --- a/front/profile.form.php +++ b/front/profile.form.php @@ -28,7 +28,6 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); Session::checkRight('config', UPDATE); if (isset($_POST['update'])) { diff --git a/front/regenerate_files.php b/front/regenerate_files.php index c6dfa4fe..fdb68bdf 100644 --- a/front/regenerate_files.php +++ b/front/regenerate_files.php @@ -28,8 +28,7 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); -include('../hook.php'); +include(__DIR__ . '/../hook.php'); Session::checkRight('config', READ); diff --git a/front/statusoverride.form.php b/front/statusoverride.form.php index 1fc2b956..49d77a37 100644 --- a/front/statusoverride.form.php +++ b/front/statusoverride.form.php @@ -28,7 +28,6 @@ * ------------------------------------------------------------------------- */ -include('../../../inc/includes.php'); Session::checkRight('config', READ); $status_override = new PluginFieldsStatusOverride(); diff --git a/hook.php b/hook.php index 4daa672f..c38b7619 100644 --- a/hook.php +++ b/hook.php @@ -315,9 +315,9 @@ function plugin_fields_giveItem($itemtype, $ID, $data, $num) //fix glpi default Search::giveItem who for empty date display "--" if ( - strpos($table, 'glpi_plugin_fields') !== false + str_contains($table, 'glpi_plugin_fields') && isset($searchopt[$ID]['datatype']) - && strpos($searchopt[$ID]['datatype'], 'date') !== false + && str_contains($searchopt[$ID]['datatype'], 'date') && empty($data['raw']["ITEM_$num"]) ) { return ' '; @@ -349,7 +349,7 @@ function plugin_datainjection_populate_fields() function plugin_fields_addWhere($link, $nott, $itemtype, $ID, $val, $searchtype) { - /** @var \DBmysql $DB */ + /** @var DBmysql $DB */ global $DB; $searchopt = &Search::getOptions($itemtype); @@ -373,7 +373,7 @@ function plugin_fields_addWhere($link, $nott, $itemtype, $ID, $val, $searchtype) if ($searchtype == 'equals' || $searchtype == 'notequals') { $operator = ($searchtype == 'equals') ? '=' : '!='; if ($nott) { - $link = $link . ' NOT '; + $link .= ' NOT '; } return $link . 'CAST(' . $DB->quoteName("$table" . '_' . "$field") . '.' . $DB->quoteName($field) . ' AS DECIMAL(10,7))' . $operator . ' ' . $DB->quoteValue($val) ; } else { diff --git a/inc/autoload.php b/inc/autoload.php index 4123e862..99397411 100644 --- a/inc/autoload.php +++ b/inc/autoload.php @@ -41,8 +41,8 @@ public function __construct($options = null) public function setOptions($options) { - if (!is_array($options) && !($options instanceof \Traversable)) { - throw new \InvalidArgumentException(); + if (!is_array($options) && !($options instanceof Traversable)) { + throw new InvalidArgumentException(); } foreach ($options as $path) { diff --git a/inc/container.class.php b/inc/container.class.php index 2a98cc66..dc448ff4 100644 --- a/inc/container.class.php +++ b/inc/container.class.php @@ -28,9 +28,12 @@ * ------------------------------------------------------------------------- */ +use Glpi\Features\Clonable; +use Glpi\DBAL\QueryExpression; + class PluginFieldsContainer extends CommonDBTM { - use Glpi\Features\Clonable; + use Clonable; public static $rightname = 'config'; @@ -95,7 +98,7 @@ public static function installBaseData(Migration $migration, $version) KEY `entities_id` (`entities_id`) ) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;"; if (!$DB->doQuery($query)) { - throw new \RuntimeException('Error creating plugin_fields_containers table: ' . $DB->error()); + throw new RuntimeException('Error creating plugin_fields_containers table: ' . $DB->error()); } } @@ -107,7 +110,7 @@ public static function installBaseData(Migration $migration, $version) $DB->update( $table, [ - 'itemtypes' => new \Glpi\DBAL\QueryExpression( + 'itemtypes' => new QueryExpression( sprintf( 'CONCAT(%s, %s, %s)', $DB->quoteValue('[\"'), @@ -122,19 +125,19 @@ public static function installBaseData(Migration $migration, $version) //add display preferences for this class $d_pref = new DisplayPreference(); - $found = $d_pref->find(['itemtype' => __CLASS__]); + $found = $d_pref->find(['itemtype' => self::class]); if (count($found) === 0) { for ($i = 2; $i <= 5; $i++) { $DB->updateOrInsert( DisplayPreference::getTable(), [ - 'itemtype' => __CLASS__, + 'itemtype' => self::class, 'num' => $i, 'rank' => $i - 1, 'users_id' => 0, ], [ - 'itemtype' => __CLASS__, + 'itemtype' => self::class, 'num' => $i, 'users_id' => 0, ], @@ -152,14 +155,14 @@ public static function installBaseData(Migration $migration, $version) // Check GenericObject version $genericobject_info = Plugin::getInfo('genericobject'); if (version_compare($genericobject_info['version'] ?? '0', '3.0.0', '<')) { - throw new \RuntimeException( + throw new RuntimeException( 'GenericObject plugin cannot be migrated. Please update it to the latest version.', ); } // Check glpi_plugin_genericobject_types table if (!$DB->fieldExists('glpi_plugin_genericobject_types', 'itemtype')) { - throw new \RuntimeException( + throw new RuntimeException( 'Integrity error on the glpi_plugin_genericobject_types table from the GenericObject plugin.', ); } @@ -179,7 +182,7 @@ public static function installBaseData(Migration $migration, $version) $result = $DB->request([ 'FROM' => $table, 'WHERE' => [ - new Glpi\DBAL\QueryExpression( + new QueryExpression( $table . ".itemtypes LIKE '%PluginGenericobject%'", ), ], @@ -195,7 +198,7 @@ public static function installBaseData(Migration $migration, $version) if ( $DB->tableExists($old_table) && isset($migration_genericobject_itemtype[$itemtype]) && - strpos($old_table, 'glpi_plugin_fields_plugingenericobject' . $migration_genericobject_itemtype[$itemtype]['genericobject_name']) !== false + str_contains($old_table, 'glpi_plugin_fields_plugingenericobject' . $migration_genericobject_itemtype[$itemtype]['genericobject_name']) ) { $new_table = str_replace('plugingenericobject' . $migration_genericobject_itemtype[$itemtype]['genericobject_name'], 'glpicustomasset' . strtolower($migration_genericobject_itemtype[$itemtype]['name']), $old_table); $migration->renameTable($old_table, $new_table); @@ -333,7 +336,7 @@ public static function installUserData(Migration $migration, $version) $newname = $field['name']; $compfields = $fields->find(['plugin_fields_containers_id' => $comptab, 'name' => $newname]); if ($compfields) { - $newname = $newname . '_os'; + $newname .= '_os'; $DB->update( 'glpi_plugin_fields_fields', [ @@ -446,7 +449,7 @@ public static function uninstall() //delete display preferences for this item $pref = new DisplayPreference(); $pref->deleteByCriteria([ - 'itemtype' => __CLASS__, + 'itemtype' => self::class, ]); return true; @@ -1033,46 +1036,44 @@ public static function showFormItemtype($params = []) public static function showFormSubtype($params, $display = false) { $out = ""; - if (isset($params['type']) && $params['type'] == 'domtab') { - if (class_exists($params['itemtype'])) { - $dbu = new DbUtils(); - $item = $dbu->getItemForItemtype($params['itemtype']); - if ($item !== false) { - $item->getEmpty(); - - $tabs = self::getSubtypes($item); - - if (count($tabs)) { - // delete Log of array (don't work with this tab) - $tabs_to_remove = ['Log$1', 'Document_Item$1']; - foreach ($tabs_to_remove as $tab_to_remove) { - if (isset($tabs[$tab_to_remove])) { - unset($tabs[$tab_to_remove]); - } - } - - // For delete number : - foreach ($tabs as &$value) { - $results = []; - if (preg_match_all('#(.+)#', $value, $results)) { - $value = str_replace($results[0][0], '', $value); - } + if (isset($params['type']) && $params['type'] == 'domtab' && class_exists($params['itemtype'])) { + $dbu = new DbUtils(); + $item = $dbu->getItemForItemtype($params['itemtype']); + if ($item !== false) { + $item->getEmpty(); + + $tabs = self::getSubtypes($item); + + if (count($tabs)) { + // delete Log of array (don't work with this tab) + $tabs_to_remove = ['Log$1', 'Document_Item$1']; + foreach ($tabs_to_remove as $tab_to_remove) { + if (isset($tabs[$tab_to_remove])) { + unset($tabs[$tab_to_remove]); } + } - if (!isset($params['subtype'])) { - $params['subtype'] = null; + // For delete number : + foreach ($tabs as &$value) { + $results = []; + if (preg_match_all('#(.+)#', $value, $results)) { + $value = str_replace($results[0][0], '', $value); } + } - $out .= Dropdown::showFromArray( - 'subtype', - $tabs, - ['value' => $params['subtype'], - 'width' => '100%', - 'display' => false, - ], - ); - $out .= ""; + if (!isset($params['subtype'])) { + $params['subtype'] = null; } + + $out .= Dropdown::showFromArray( + 'subtype', + $tabs, + ['value' => $params['subtype'], + 'width' => '100%', + 'display' => false, + ], + ); + $out .= ""; } } } @@ -1099,9 +1100,7 @@ public static function getItemtypes($is_domtab) foreach ($all_itemtypes as $section => $itemtypes) { $all_itemtypes[$section] = array_filter( $itemtypes, - function ($itemtype) { - return count(self::getSubtypes($itemtype)) > 0; - }, + fn($itemtype) => count(self::getSubtypes($itemtype)) > 0, ARRAY_FILTER_USE_KEY, ); } @@ -1446,7 +1445,7 @@ public static function constructHistory( foreach ($data as $key => $value) { //log only not empty values //do not log if value is empty or if dom name is part of file upload - if (!empty($value) && strpos($key, '_uploader_') === false) { + if (!empty($value) && !str_contains($key, '_uploader_')) { //prepare log $changes = [0, 'N/A', $value]; @@ -1557,6 +1556,7 @@ public static function validateValues($data, $itemtype, $massiveaction) $valid = true; $empty_errors = []; $number_errors = []; + $url_errors = []; $container = new self(); $container->getFromDB($data['plugin_fields_containers_id']); @@ -1615,10 +1615,8 @@ public static function validateValues($data, $itemtype, $massiveaction) $value = $data[$name]; } elseif (isset($data['plugin_fields_' . $name . 'dropdowns_id'])) { $value = $data['plugin_fields_' . $name . 'dropdowns_id']; - } else { - if ($massiveaction) { - continue; - } + } elseif ($massiveaction) { + continue; } //translate label @@ -1648,17 +1646,17 @@ public static function validateValues($data, $itemtype, $massiveaction) } } - if (!empty($empty_errors)) { + if ($empty_errors !== []) { Session::AddMessageAfterRedirect(__('Some mandatory fields are empty', 'fields') . ' : ' . implode(', ', $empty_errors), false, ERROR); } - if (!empty($number_errors)) { + if ($number_errors !== []) { Session::AddMessageAfterRedirect(__('Some numeric fields contains non numeric values', 'fields') . ' : ' . implode(', ', $number_errors), false, ERROR); } - if (!empty($url_errors)) { + if ($url_errors !== []) { Session::AddMessageAfterRedirect(__('Some URL fields contains invalid links', 'fields') . ' : ' . implode(', ', $url_errors), false, ERROR); } @@ -1673,9 +1671,7 @@ public static function findContainer($itemtype, $type = 'tab', $subtype = '') ['type' => $type], ]; - $entity = isset($_SESSION['glpiactiveentities']) - ? $_SESSION['glpiactiveentities'] - : 0; + $entity = $_SESSION['glpiactiveentities'] ?? 0; $condition += getEntitiesRestrictCriteria('', '', $entity, true, true); if ($subtype != '') { @@ -1794,11 +1790,9 @@ public static function preItem(CommonDBTM $item) if ($type == 'domtab') { $subtype = $_REQUEST['_plugin_fields_subtype']; } - if (false === ($c_id = self::findContainer(get_Class($item), $type, $subtype))) { - // tries for 'tab' - if (false === ($c_id = self::findContainer(get_Class($item)))) { - return false; - } + // tries for 'tab' + if (false === ($c_id = self::findContainer(get_Class($item), $type, $subtype)) && false === $c_id = self::findContainer(get_Class($item))) { + return false; } } @@ -1913,7 +1907,6 @@ private static function populateData($c_id, CommonDBTM $item) $item->input[$input] = str_replace(',', '.', $item->input[$input]); } $data[$input] = $item->input[$input]; - if ($field['type'] === 'richtext') { $filename_input = sprintf('_%s', $input); $prefix_input = sprintf('_prefix_%s', $input); @@ -1923,43 +1916,40 @@ private static function populateData($c_id, CommonDBTM $item) $data[$prefix_input] = $item->input[$prefix_input] ?? []; $data[$tag_input] = $item->input[$tag_input] ?? []; } - } else { + } elseif ($field['multiple']) { //the absence of the field in the input may be due to the fact that the input allows multiple selection // ex my_dom[] //in these conditions, the input is never sent by the browser - if ($field['multiple']) { - $data['multiple_dropdown_action'] = $_POST['multiple_dropdown_action'] ?? 'assign'; - //handle multi dropdown field - if ($field['type'] == 'dropdown') { - $multiple_key = sprintf('plugin_fields_%sdropdowns_id', $field['name']); - $multiple_key_defined = '_' . $multiple_key . '_defined'; - //values are defined by user - if (isset($item->input[$multiple_key])) { - $data[$multiple_key] = $item->input[$multiple_key]; - $has_fields = true; - } elseif ( - isset($item->input[$multiple_key_defined]) - && $item->input[$multiple_key_defined] - ) { //multi dropdown is empty or has been emptied - $data[$multiple_key] = []; + $data['multiple_dropdown_action'] = $_POST['multiple_dropdown_action'] ?? 'assign'; + //handle multi dropdown field + if ($field['type'] == 'dropdown') { + $multiple_key = sprintf('plugin_fields_%sdropdowns_id', $field['name']); + $multiple_key_defined = '_' . $multiple_key . '_defined'; + //values are defined by user + if (isset($item->input[$multiple_key])) { + $data[$multiple_key] = $item->input[$multiple_key]; + $has_fields = true; + } elseif ( + isset($item->input[$multiple_key_defined]) + && $item->input[$multiple_key_defined] + ) { //multi dropdown is empty or has been emptied + $data[$multiple_key] = []; + $has_fields = true; + } elseif (isset($_REQUEST['massiveaction'])) { // called from massiveaction + if (isset($_POST[$multiple_key])) { + $data[$multiple_key] = $_POST[$multiple_key]; $has_fields = true; - } elseif (isset($_REQUEST['massiveaction'])) { // called from massiveaction - if (isset($_POST[$multiple_key])) { - $data[$multiple_key] = $_POST[$multiple_key]; - $has_fields = true; - } } } - - //managed multi GLPI item dropdown field - if (preg_match('/^dropdown-(?.+)$/', $field['type'], $match) === 1) { - //values are defined by user - if (isset($item->input[$field['name']])) { - $data[$field['name']] = $item->input[$field['name']]; - $has_fields = true; - } else { //multi dropdown is empty or has been emptied - $data[$field['name']] = []; - } + } + //managed multi GLPI item dropdown field + if (preg_match('/^dropdown-(?.+)$/', $field['type'], $match) === 1) { + //values are defined by user + if (isset($item->input[$field['name']])) { + $data[$field['name']] = $item->input[$field['name']]; + $has_fields = true; + } else { //multi dropdown is empty or has been emptied + $data[$field['name']] = []; } } } @@ -2001,7 +1991,7 @@ public static function getAddSearchOptions($itemtype, $containers_id = false) 'glpi_plugin_fields_containers.label AS container_label', ( Session::isCron() - ? new \Glpi\DBAL\QueryExpression(sprintf('%s AS %s', READ + CREATE, $DB->quoteName('right'))) + ? new QueryExpression(sprintf('%s AS %s', READ + CREATE, $DB->quoteName('right'))) : 'glpi_plugin_fields_profiles.right' ), ], diff --git a/inc/containerdisplaycondition.class.php b/inc/containerdisplaycondition.class.php index 3ce821ff..71109c05 100644 --- a/inc/containerdisplaycondition.class.php +++ b/inc/containerdisplaycondition.class.php @@ -27,14 +27,12 @@ * @link https://github.com/pluginsGLPI/fields * ------------------------------------------------------------------------- */ - +use Glpi\Features\Clonable; use Glpi\Application\View\TemplateRenderer; -use Glpi\Toolbox\Sanitizer; -use GlpiPlugin\Scim\Controller\Common; class PluginFieldsContainerDisplayCondition extends CommonDBChild { - use Glpi\Features\Clonable; + use Clonable; public static $itemtype = PluginFieldsContainer::class; public static $items_id = 'plugin_fields_containers_id'; @@ -216,7 +214,7 @@ private static function getItemtypesForContainer(int $container_id): array ], ]); - if (count($iterator)) { + if (count($iterator) > 0) { $itemtypes = $iterator->current()['itemtypes']; $itemtypes = importArrayFromDB($itemtypes); foreach ($itemtypes as $itemtype) { @@ -262,7 +260,7 @@ public static function showSearchOptionCondition($searchoption_id, $itemtype, ?s $itemtypetable = $itemtype::getTable(); $twig_params = [ - 'rand' => rand(), + 'rand' => random_int(0, mt_getrandmax()), 'is_dropdown' => false, 'is_specific' => false, 'is_list_values' => false, @@ -366,7 +364,7 @@ public static function removeBlackListedOption($array, $itemtype_class) $allowed_table = [getTableForItemType($itemtype_class), User::getTable(), Group::getTable()]; if ($itemtype_object->maybeLocated()) { - array_push($allowed_table, Location::getTable()); + $allowed_table[] = Location::getTable(); } //use relation.constant.php to allow some tables (exclude Location which is managed using `CommonDBTM::maybeLocated()`) @@ -464,10 +462,8 @@ public function checkCondition($item) break; case self::SHOW_CONDITION_REGEX: //'regex'; - if (self::checkRegex($value)) { - if (preg_match_all($value . 'i', $fields[$searchOption['linkfield']]) > 0) { - return false; - } + if (self::checkRegex($value) && preg_match_all($value . 'i', $fields[$searchOption['linkfield']]) > 0) { + return false; } break; case self::SHOW_CONDITION_UNDER: @@ -490,10 +486,8 @@ public function checkCondition($item) public static function checkRegex($regex) { // Avoid php notice when validating the regular expression - set_error_handler(function ($errno, $errstr, $errfile, $errline) { - return true; - }); - $isValid = !(preg_match($regex, '') === false); + set_error_handler(fn($errno, $errstr, $errfile, $errline) => true); + $isValid = preg_match($regex, '') !== false; restore_error_handler(); return $isValid; diff --git a/inc/dropdown.class.php b/inc/dropdown.class.php index ad964d76..c7048821 100644 --- a/inc/dropdown.class.php +++ b/inc/dropdown.class.php @@ -92,7 +92,7 @@ public static function uninstall() //remove dropdown tables and files if ($DB->tableExists('glpi_plugin_fields_fields')) { - require_once 'field.class.php'; + require_once __DIR__ . '/field.class.php'; $field = new PluginFieldsField(); $dropdowns = $field->find(['type' => 'dropdown']); foreach ($dropdowns as $dropdown) { @@ -178,32 +178,23 @@ public static function destroy($dropdown_name) } //remove class file for this dropdown - if (file_exists($class_filename)) { - if (unlink($class_filename) === false) { - Toolbox::logDebug('Error : dropdown class file creation - ' . $dropdown_name . 'dropdown.class.php'); - - return false; - } + if (file_exists($class_filename) && unlink($class_filename) === false) { + Toolbox::logDebug('Error : dropdown class file creation - ' . $dropdown_name . 'dropdown.class.php'); + return false; } //remove front file for this dropdown $front_filename = PLUGINFIELDS_FRONT_PATH . '/' . $dropdown_name . 'dropdown.php'; - if (file_exists($front_filename)) { - if (unlink($front_filename) === false) { - Toolbox::logDebug('Error : dropdown front file removing - ' . $dropdown_name . 'dropdown.php'); - - return false; - } + if (file_exists($front_filename) && unlink($front_filename) === false) { + Toolbox::logDebug('Error : dropdown front file removing - ' . $dropdown_name . 'dropdown.php'); + return false; } //remove front.form file for this dropdown $form_filename = PLUGINFIELDS_FRONT_PATH . '/' . $dropdown_name . 'dropdown.form.php'; - if (file_exists($form_filename)) { - if (unlink($form_filename) === false) { - Toolbox::logDebug('Error : dropdown form file removing - ' . $dropdown_name . 'dropdown.form.php'); - - return false; - } + if (file_exists($form_filename) && unlink($form_filename) === false) { + Toolbox::logDebug('Error : dropdown form file removing - ' . $dropdown_name . 'dropdown.form.php'); + return false; } return true; @@ -216,7 +207,7 @@ public static function getClassname($system_name) public static function multipleDropdownAddWhere($link, $tablefield, $field, $val, $searchtype, $field_field = []) { - /** @var \DBmysql $DB */ + /** @var DBmysql $DB */ global $DB; // Determines the default value diff --git a/inc/field.class.php b/inc/field.class.php index 1acb2c88..21b5dfc4 100644 --- a/inc/field.class.php +++ b/inc/field.class.php @@ -27,13 +27,13 @@ * @link https://github.com/pluginsGLPI/fields * ------------------------------------------------------------------------- */ - +use Glpi\Features\Clonable; +use Glpi\DBAL\QueryExpression; use Glpi\Application\View\TemplateRenderer; -use Glpi\Toolbox\Sanitizer; class PluginFieldsField extends CommonDBChild { - use Glpi\Features\Clonable; + use Clonable; /** * Starting index for search options. @@ -93,7 +93,7 @@ public static function installBaseData(Migration $migration, $version) KEY `is_readonly` (`is_readonly`) ) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;"; if (!$DB->doQuery($query)) { - throw new \RuntimeException('Error creating plugin_fields_fields table: ' . $DB->error()); + throw new RuntimeException('Error creating plugin_fields_fields table: ' . $DB->error()); } } @@ -346,7 +346,7 @@ private function cleanDisplayPreferences($itemtype, $so_id) public function pre_deleteItem() { /** - * @var \DBmysql $DB + * @var DBmysql $DB */ global $DB; @@ -368,10 +368,8 @@ public function pre_deleteItem() if ($so_value['linkfield'] == 'plugin_fields_' . $this->fields['name'] . 'dropdowns_id') { $this->cleanDisplayPreferences($itemtype, $so_id); } - } else { - if ($so_value['field'] == $this->fields['name']) { - $this->cleanDisplayPreferences($itemtype, $so_id); - } + } elseif ($so_value['field'] == $this->fields['name']) { + $this->cleanDisplayPreferences($itemtype, $so_id); } } } @@ -426,14 +424,14 @@ public function post_purgeItem() /** @var DBmysql $DB */ global $DB; - $table = getTableForItemType(__CLASS__); + $table = getTableForItemType(self::class); $old_container = $this->fields['plugin_fields_containers_id']; $old_ranking = $this->fields['ranking']; $DB->update( $table, [ - 'ranking' => new \Glpi\DBAL\QueryExpression($DB->quoteName('ranking') . ' - 1'), + 'ranking' => new QueryExpression($DB->quoteName('ranking') . ' - 1'), ], [ 'plugin_fields_containers_id' => $old_container, @@ -494,7 +492,7 @@ public function prepareName($input, bool $prevent_duplicated = true) // but there is a bug when trying to drop the column and the real max len is 53 chars // FIXME: see: https://bugs.mysql.com/bug.php?id=107165 if (strlen($field_name) > 52) { - $rand = rand(); + $rand = random_int(0, mt_getrandmax()); $field_name = substr($field_name, 0, 52 - strlen((string) $rand)) . $rand; } @@ -512,7 +510,7 @@ public function getNextRanking() global $DB; $iterator = $DB->request([ - 'SELECT' => new \Glpi\DBAL\QueryExpression( + 'SELECT' => new QueryExpression( 'max(' . $DB->quoteName('ranking') . ') AS ' . $DB->quoteName('rank'), ), 'FROM' => self::getTable(), @@ -534,8 +532,8 @@ public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { if (!$withtemplate) { switch ($item->getType()) { - case __CLASS__: - return $this->getTypeName(1); + case self::class: + return static::getTypeName(1); } } @@ -593,7 +591,7 @@ public function showSummary($container) echo "
"; $ajax_params = [ - 'type' => __CLASS__, + 'type' => self::class, 'parenttype' => PluginFieldsContainer::class, 'plugin_fields_containers_id' => $cID, 'id' => -1, @@ -655,19 +653,15 @@ public function showSummary($container) $item = new $itemtype(); if ($this->fields['multiple']) { $values = json_decode($this->fields['default_value']); - $names = []; foreach ($values as $value) { if ($item->getFromDB($value)) { $names[] = $item->getName(); } } - echo implode(', ', $names); - } else { - if ($item->getFromDB($this->fields['default_value'])) { - echo $item->getName(); - } + } elseif ($item->getFromDB($this->fields['default_value'])) { + echo $item->getName(); } } } elseif ($this->fields['type'] === 'dropdown' && !empty($this->fields['default_value'])) { @@ -898,8 +892,8 @@ public static function showForTab($params) $item = $params['item']; $functions = array_column(debug_backtrace(), 'function'); - $subtype = isset($_SESSION['glpi_tabs'][strtolower($item::getType())]) ? $_SESSION['glpi_tabs'][strtolower($item::getType())] : ''; - $type = substr($subtype, -strlen('$main')) === '$main' + $subtype = $_SESSION['glpi_tabs'][strtolower($item::getType())] ?? ''; + $type = str_ends_with($subtype, '$main') || in_array('showForm', $functions) || in_array('showPrimaryForm', $functions) || in_array('showFormHelpdesk', $functions) @@ -949,11 +943,11 @@ public static function showForTab($params) } $current_url = $_SERVER['REQUEST_URI']; if ( - strpos($current_url, '.form.php') === false - && strpos($current_url, '.injector.php') === false - && strpos($current_url, '.public.php') === false - && strpos($current_url, 'ajax/planning') === false - && strpos($current_url, 'ajax/timeline.php') === false // ITILSolution load from timeline + !str_contains($current_url, '.form.php') + && !str_contains($current_url, '.injector.php') + && !str_contains($current_url, '.public.php') + && !str_contains($current_url, 'ajax/planning') + && !str_contains($current_url, 'ajax/timeline.php') // ITILSolution load from timeline ) { return; } @@ -967,7 +961,7 @@ public static function showForTab($params) } $html_id = 'plugin_fields_container_' . mt_rand(); - if (strpos($current_url, 'helpdesk.public.php') !== false) { + if (str_contains($current_url, 'helpdesk.public.php')) { echo "
"; echo "
"; $field_options = [ @@ -987,7 +981,7 @@ public static function showForTab($params) $field_options ?? [], ); } - if (strpos($current_url, 'helpdesk.public.php') !== false) { + if (str_contains($current_url, 'helpdesk.public.php')) { echo '
'; } echo '
'; @@ -1217,13 +1211,11 @@ public static function prepareHtmlFields( } elseif (isset($item->input['items_id_' . $field['name']])) { $value['items_id'] = $item->input['items_id_' . $field['name']] ?? ''; } - } else { - if (isset($_SESSION['plugin']['fields']['values_sent'][$field['name']])) { - $value = $_SESSION['plugin']['fields']['values_sent'][$field['name']]; - } elseif (isset($item->input[$field['name']])) { - // find from $item->input due to ajax refresh container - $value = $item->input[$field['name']]; - } + } elseif (isset($_SESSION['plugin']['fields']['values_sent'][$field['name']])) { + $value = $_SESSION['plugin']['fields']['values_sent'][$field['name']]; + } elseif (isset($item->input[$field['name']])) { + // find from $item->input due to ajax refresh container + $value = $item->input[$field['name']]; } } @@ -1244,15 +1236,13 @@ public static function prepareHtmlFields( } } - if ($field['multiple']) { - if (!is_array($value)) { - // Value may be set: - // - either from a default value in DB (it will be a JSON string), - // - either from a previous input (it will be an array). - // - // -> Decode it only if it is not already an array. - $value = json_decode($value); - } + if ($field['multiple'] && !is_array($value)) { + // Value may be set: + // - either from a default value in DB (it will be a JSON string), + // - either from a previous input (it will be an array). + // + // -> Decode it only if it is not already an array. + $value = json_decode($value); } $field['value'] = $value; diff --git a/inc/labeltranslation.class.php b/inc/labeltranslation.class.php index 54cae675..9f4b48e6 100644 --- a/inc/labeltranslation.class.php +++ b/inc/labeltranslation.class.php @@ -28,9 +28,11 @@ * ------------------------------------------------------------------------- */ +use Glpi\Features\Clonable; + class PluginFieldsLabelTranslation extends CommonDBChild { - use Glpi\Features\Clonable; + use Clonable; public static $itemtype = 'itemtype'; public static $items_id = 'items_id'; @@ -70,7 +72,7 @@ public static function installBaseData(Migration $migration, $version) UNIQUE KEY `unicity` (`itemtype`, `items_id`, `language`) ) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;"; if (!$DB->doQuery($query)) { - throw new \RuntimeException('Error creating plugin_fields_labeltranslations table: ' . $DB->error()); + throw new RuntimeException('Error creating plugin_fields_labeltranslations table: ' . $DB->error()); } } @@ -169,7 +171,7 @@ public static function showTranslations(CommonDBTM $item) echo "
"; $ajax_params = [ - 'type' => __CLASS__, + 'type' => self::class, 'itemtype' => $item::getType(), 'items_id' => $item->fields['id'], 'id' => -1, @@ -199,8 +201,8 @@ public static function showTranslations(CommonDBTM $item) if (count($found) > 0) { if ($canedit) { - Html::openMassiveActionsForm('mass' . __CLASS__ . $rand); - $massiveactionparams = ['container' => 'mass' . __CLASS__ . $rand]; + Html::openMassiveActionsForm('mass' . self::class . $rand); + $massiveactionparams = ['container' => 'mass' . self::class . $rand]; Html::showMassiveActions($massiveactionparams); } echo "
"; @@ -208,7 +210,7 @@ public static function showTranslations(CommonDBTM $item) echo "" . __('List of translations') . ''; if ($canedit) { echo ""; - echo Html::getCheckAllAsCheckbox('mass' . __CLASS__ . $rand); + echo Html::getCheckAllAsCheckbox('mass' . self::class . $rand); echo ''; } echo '' . __('Language', 'fields') . ''; @@ -218,13 +220,13 @@ public static function showTranslations(CommonDBTM $item) onClick=\"viewEditTranslation" . $data['id'] . "$rand();\"" : '') . '>'; if ($canedit) { echo ""; - Html::showMassiveActionCheckBox(__CLASS__, $data['id']); + Html::showMassiveActionCheckBox(self::class, $data['id']); echo ''; } echo ''; if ($canedit) { $ajax_params = [ - 'type' => __CLASS__, + 'type' => self::class, 'itemtype' => $item::getType(), 'items_id' => $item->getID(), 'id' => $data['id'], diff --git a/inc/migration.class.php b/inc/migration.class.php index 81a32048..ebfdd404 100644 --- a/inc/migration.class.php +++ b/inc/migration.class.php @@ -58,11 +58,7 @@ public static function getSQLFields(string $field_name, string $field_type, arra if ($field_type === 'dropdown') { $field_name = getForeignKeyFieldForItemType(PluginFieldsDropdown::getClassname($field_name)); } - if ($options['multiple'] ?? false) { - $fields[$field_name] = 'LONGTEXT'; - } else { - $fields[$field_name] = "INT {$default_key_sign} NOT NULL DEFAULT 0"; - } + $fields[$field_name] = $options['multiple'] ?? false ? 'LONGTEXT' : "INT {$default_key_sign} NOT NULL DEFAULT 0"; break; case $field_type === 'textarea': case $field_type === 'url': @@ -210,9 +206,7 @@ private static function getCustomFieldsInContainerTable( return array_filter( $fields, - function (string $field) use ($basic_fields) { - return !in_array($field, $basic_fields); - }, + fn(string $field) => !in_array($field, $basic_fields), ); } } diff --git a/inc/profile.class.php b/inc/profile.class.php index 587eaf66..300fabc9 100644 --- a/inc/profile.class.php +++ b/inc/profile.class.php @@ -28,9 +28,11 @@ * ------------------------------------------------------------------------- */ +use Glpi\Features\Clonable; + class PluginFieldsProfile extends CommonDBRelation { - use Glpi\Features\Clonable; + use Clonable; public static $itemtype_1 = PluginFieldsContainer::class; public static $items_id_1 = 'plugin_fields_containers_id'; @@ -69,7 +71,7 @@ public static function installBaseData(Migration $migration, $version) KEY `plugin_fields_containers_id` (`plugin_fields_containers_id`) ) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;"; if (!$DB->doQuery($query)) { - throw new \RuntimeException('Error creating plugin_fields_profiles table: ' . $DB->error()); + throw new RuntimeException('Error creating plugin_fields_profiles table: ' . $DB->error()); } } diff --git a/inc/statusoverride.class.php b/inc/statusoverride.class.php index cc68e194..d8c95592 100644 --- a/inc/statusoverride.class.php +++ b/inc/statusoverride.class.php @@ -27,12 +27,12 @@ * @link https://github.com/pluginsGLPI/fields * ------------------------------------------------------------------------- */ - +use Glpi\Features\Clonable; use Glpi\Application\View\TemplateRenderer; class PluginFieldsStatusOverride extends CommonDBChild { - use Glpi\Features\Clonable; + use Clonable; public static $itemtype = PluginFieldsField::class; public static $items_id = 'plugin_fields_fields_id'; @@ -70,7 +70,7 @@ public static function installBaseData(Migration $migration, $version) KEY `plugin_fields_fields_id` (`plugin_fields_fields_id`) ) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;"; if (!$DB->doQuery($query)) { - throw new \RuntimeException('Error creating plugin_fields_statusoverrides table: ' . $DB->error()); + throw new RuntimeException('Error creating plugin_fields_statusoverrides table: ' . $DB->error()); } } @@ -252,9 +252,7 @@ public static function getOverridesForItemtypeAndStatus(int $container_id, strin $overrides = self::getOverridesForContainer($container_id); - return array_filter($overrides, static function ($override) use ($itemtype, $status) { - return $override['itemtype'] === $itemtype && in_array($status, $override['states'], false); - }); + return array_filter($overrides, static fn($override) => $override['itemtype'] === $itemtype && in_array($status, $override['states'], false)); } private static function getItemtypesForContainer(int $container_id): array @@ -270,14 +268,12 @@ private static function getItemtypesForContainer(int $container_id): array ], ]); - if (count($iterator)) { + if (count($iterator) > 0) { $itemtypes = $iterator->current()['itemtypes']; $itemtypes = importArrayFromDB($itemtypes); $status_itemtypes = self::getStatusItemtypes(); // Get only itemtypes that exist and have a status field - $itemtypes = array_filter($itemtypes, static function ($itemtype) use ($status_itemtypes) { - return class_exists($itemtype) && in_array($itemtype, $status_itemtypes, true); - }); + $itemtypes = array_filter($itemtypes, static fn($itemtype) => class_exists($itemtype) && in_array($itemtype, $status_itemtypes, true)); $results = []; foreach ($itemtypes as $itemtype) { $results[$itemtype] = $itemtype::getTypeName(); @@ -337,9 +333,7 @@ private static function addStatusNames(array &$overrides): void foreach ($overrides as &$override) { $names = $statuses[$override['itemtype']] ?? $statuses['Other']; - $override['status_names'] = array_filter($names, static function ($name, $id) use ($override) { - return in_array($id, $override['states']); - }, ARRAY_FILTER_USE_BOTH); + $override['status_names'] = array_filter($names, static fn($name, $id) => in_array($id, $override['states']), ARRAY_FILTER_USE_BOTH); } } diff --git a/inc/toolbox.class.php b/inc/toolbox.class.php index 8f4e6da0..fc424eba 100644 --- a/inc/toolbox.class.php +++ b/inc/toolbox.class.php @@ -28,6 +28,8 @@ * ------------------------------------------------------------------------- */ +use Glpi\Socket; + class PluginFieldsToolbox { /** @@ -49,7 +51,7 @@ public function getSystemNameFromLabel($label) // 3. if empty, uses a random number if (strlen($name) == 0) { - $name = rand(); + $name = random_int(0, mt_getrandmax()); } // 4. replace numbers by letters @@ -228,7 +230,7 @@ public static function getGlpiItemtypes(): array PDU::class, PassiveDCEquipment::class, Cable::class, - Glpi\Socket::class, + Socket::class, ]; $assistance_itemtypes = [ diff --git a/rector.php b/rector.php new file mode 100644 index 00000000..22ba2dd0 --- /dev/null +++ b/rector.php @@ -0,0 +1,98 @@ +. + * ------------------------------------------------------------------------- + * @copyright Copyright (C) 2013-2023 by Fields plugin team. + * @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html + * @link https://github.com/pluginsGLPI/fields + * ------------------------------------------------------------------------- + */ + +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; + +return RectorConfig::configure() + ->withPaths([ + __DIR__ . '/ajax', + __DIR__ . '/inc', + __DIR__ . '/front', + ]) + ->withPhpVersion(PhpVersion::PHP_82) + ->withCache( + cacheClass: FileCacheStorage::class, + cacheDirectory: sys_get_temp_dir() . '/fields-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 +; diff --git a/setup.php b/setup.php index 55aebf66..66988334 100644 --- a/setup.php +++ b/setup.php @@ -135,7 +135,7 @@ function plugin_init_fields() //include js and css $debug = (isset($_SESSION['glpi_use_mode']) - && $_SESSION['glpi_use_mode'] == Session::DEBUG_MODE ? true : false); + && $_SESSION['glpi_use_mode'] == Session::DEBUG_MODE); if (!$debug && file_exists(__DIR__ . '/public/css/fields.min.css')) { $PLUGIN_HOOKS['add_css']['fields'][] = 'css/fields.min.css'; } else { @@ -209,7 +209,7 @@ function plugin_fields_script_endswith($scriptname) $scriptname = 'fields/front/' . $scriptname; $script_name = $_SERVER['SCRIPT_NAME']; - return substr($script_name, -strlen($scriptname)) === $scriptname; + return str_ends_with($script_name, $scriptname); } @@ -298,91 +298,84 @@ function plugin_fields_exportBlockAsYaml($container_id = null) 'container' => [], ]; - if ( - isset($_SESSION['glpiactiveentities']) - && Session::getLoginUserID() - && Plugin::isPluginActive('fields') - ) { - if ($DB->tableExists(PluginFieldsContainer::getTable())) { - $where = []; - $where['is_active'] = true; - if ($container_id != null) { - $where['id'] = $container_id; - } - $container_obj = new PluginFieldsContainer(); - $containers = $container_obj->find($where); - - foreach ($containers as $container) { - $itemtypes = (strlen($container['itemtypes']) > 0) - ? json_decode($container['itemtypes'], true) - : []; - - foreach ($itemtypes as $itemtype) { - $fields_obj = new PluginFieldsField(); - // to get translation - $container['itemtype'] = PluginFieldsContainer::getType(); - $yaml_conf['container'][$container['id'] . '-' . $itemtype] = [ - 'id' => (int) $container['id'], - 'name' => PluginFieldsLabelTranslation::getLabelFor($container), - 'itemtype' => $itemtype, - 'type' => $container['type'], - 'subtype' => $container['subtype'], - 'fields' => [], - ]; - $fields = $fields_obj->find(['plugin_fields_containers_id' => $container['id'], - 'is_active' => true, - 'is_readonly' => false, - ]); - if (count($fields)) { - foreach ($fields as $field) { - $tmp_field = []; - $tmp_field['id'] = (int) $field['id']; - - //to get translation - $field['itemtype'] = PluginFieldsField::getType(); - $tmp_field['label'] = PluginFieldsLabelTranslation::getLabelFor($field); - $tmp_field['xml_node'] = strtoupper($field['name']); - $tmp_field['type'] = $field['type']; - $tmp_field['ranking'] = $field['ranking']; - $tmp_field['default_value'] = $field['default_value']; - $tmp_field['mandatory'] = $field['mandatory']; - $tmp_field['possible_value'] = ''; - - switch ($field['type']) { - case 'dropdown': - $dbu = new DbUtils(); - $obj = $dbu->getItemForItemtype($itemtype); - $obj->getEmpty(); - - $dropdown_itemtype = PluginFieldsDropdown::getClassname($field['name']); - $tmp_field['xml_node'] = strtoupper(getForeignKeyFieldForItemType($dropdown_itemtype)); - - $dropdown_obj = $dbu->getItemForItemtype($dropdown_itemtype); - $dropdown_datas = $dropdown_obj->find(); - $datas = []; - foreach ($dropdown_datas as $value) { - $items = []; - $items['id'] = (int) $value['id']; - $items['value'] = $value['name']; - $datas[] = $items; - } - $tmp_field['possible_value'] = $datas; - break; - case 'yesno': - $datas = []; - $datas['0']['id'] = 0; - $datas['0']['value'] = __('No'); - $datas['1']['id'] = 1; - $datas['1']['value'] = __('Yes'); - $tmp_field['possible_value'] = $datas; - break; - case 'dropdownuser': - $datas = Dropdown::getDropdownUsers(['is_active' => 1, 'is_deleted' => 0], false); - $tmp_field['possible_value'] = $datas['results']; - break; - } - $yaml_conf['container'][$container['id'] . '-' . $itemtype]['fields'][] = $tmp_field; + if (isset($_SESSION['glpiactiveentities']) && Session::getLoginUserID() && Plugin::isPluginActive('fields') && $DB->tableExists(PluginFieldsContainer::getTable())) { + $where = []; + $where['is_active'] = true; + if ($container_id != null) { + $where['id'] = $container_id; + } + $container_obj = new PluginFieldsContainer(); + $containers = $container_obj->find($where); + foreach ($containers as $container) { + $itemtypes = (strlen($container['itemtypes']) > 0) + ? json_decode($container['itemtypes'], true) + : []; + + foreach ($itemtypes as $itemtype) { + $fields_obj = new PluginFieldsField(); + // to get translation + $container['itemtype'] = PluginFieldsContainer::getType(); + $yaml_conf['container'][$container['id'] . '-' . $itemtype] = [ + 'id' => (int) $container['id'], + 'name' => PluginFieldsLabelTranslation::getLabelFor($container), + 'itemtype' => $itemtype, + 'type' => $container['type'], + 'subtype' => $container['subtype'], + 'fields' => [], + ]; + $fields = $fields_obj->find(['plugin_fields_containers_id' => $container['id'], + 'is_active' => true, + 'is_readonly' => false, + ]); + if (count($fields)) { + foreach ($fields as $field) { + $tmp_field = []; + $tmp_field['id'] = (int) $field['id']; + + //to get translation + $field['itemtype'] = PluginFieldsField::getType(); + $tmp_field['label'] = PluginFieldsLabelTranslation::getLabelFor($field); + $tmp_field['xml_node'] = strtoupper($field['name']); + $tmp_field['type'] = $field['type']; + $tmp_field['ranking'] = $field['ranking']; + $tmp_field['default_value'] = $field['default_value']; + $tmp_field['mandatory'] = $field['mandatory']; + $tmp_field['possible_value'] = ''; + + switch ($field['type']) { + case 'dropdown': + $dbu = new DbUtils(); + $obj = $dbu->getItemForItemtype($itemtype); + $obj->getEmpty(); + + $dropdown_itemtype = PluginFieldsDropdown::getClassname($field['name']); + $tmp_field['xml_node'] = strtoupper(getForeignKeyFieldForItemType($dropdown_itemtype)); + + $dropdown_obj = $dbu->getItemForItemtype($dropdown_itemtype); + $dropdown_datas = $dropdown_obj->find(); + $datas = []; + foreach ($dropdown_datas as $value) { + $items = []; + $items['id'] = (int) $value['id']; + $items['value'] = $value['name']; + $datas[] = $items; + } + $tmp_field['possible_value'] = $datas; + break; + case 'yesno': + $datas = []; + $datas['0']['id'] = 0; + $datas['0']['value'] = __('No'); + $datas['1']['id'] = 1; + $datas['1']['value'] = __('Yes'); + $tmp_field['possible_value'] = $datas; + break; + case 'dropdownuser': + $datas = Dropdown::getDropdownUsers(['is_active' => 1, 'is_deleted' => 0], false); + $tmp_field['possible_value'] = $datas['results']; + break; } + $yaml_conf['container'][$container['id'] . '-' . $itemtype]['fields'][] = $tmp_field; } } }