Skip to content

Add PHPStan rules to forbid some PHP functions #19510

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .phpstan-baseline.php
Original file line number Diff line number Diff line change
Expand Up @@ -1555,6 +1555,18 @@
'count' => 1,
'path' => __DIR__ . '/src/Glpi/Api/API.php',
];
$ignoreErrors[] = [
'message' => '#^You should not use the `exit` function\\. It prevents the execution of post\\-request/post\\-command routines\\.$#',
'identifier' => 'glpi.forbidExit',
'count' => 3,
'path' => __DIR__ . '/src/Glpi/Api/API.php',
];
$ignoreErrors[] = [
'message' => '#^You should not use the `http_response_code` function to change the response code\\. Due to a PHP bug, it may not provide the expected result \\(see https\\://bugs\\.php\\.net/bug\\.php\\?id\\=81451\\)\\.$#',
'identifier' => 'glpi.forbidHttpResponseCode',
'count' => 1,
'path' => __DIR__ . '/src/Glpi/Api/API.php',
];
$ignoreErrors[] = [
'message' => '#^Method Glpi\\\\Api\\\\APIRest\\:\\:parseIncomingParams\\(\\) with return type void returns string but should not return anything\\.$#',
'identifier' => 'return.void',
Expand All @@ -1579,6 +1591,18 @@
'count' => 1,
'path' => __DIR__ . '/src/Glpi/Api/APIRest.php',
];
$ignoreErrors[] = [
'message' => '#^You should not use the `exit` function\\. It prevents the execution of post\\-request/post\\-command routines\\.$#',
'identifier' => 'glpi.forbidExit',
'count' => 3,
'path' => __DIR__ . '/src/Glpi/Api/APIRest.php',
];
$ignoreErrors[] = [
'message' => '#^You should not use the `http_response_code` function to change the response code\\. Due to a PHP bug, it may not provide the expected result \\(see https\\://bugs\\.php\\.net/bug\\.php\\?id\\=81451\\)\\.$#',
'identifier' => 'glpi.forbidHttpResponseCode',
'count' => 1,
'path' => __DIR__ . '/src/Glpi/Api/APIRest.php',
];
$ignoreErrors[] = [
'message' => '#^Call to function is_array\\(\\) with array will always evaluate to true\\.$#',
'identifier' => 'function.alreadyNarrowedType',
Expand Down Expand Up @@ -2173,6 +2197,12 @@
'count' => 1,
'path' => __DIR__ . '/src/Glpi/Dropdown/Dropdown.php',
];
$ignoreErrors[] = [
'message' => '#^You should not use the `http_response_code` function to change the response code\\. Due to a PHP bug, it may not provide the expected result \\(see https\\://bugs\\.php\\.net/bug\\.php\\?id\\=81451\\)\\.$#',
'identifier' => 'glpi.forbidHttpResponseCode',
'count' => 1,
'path' => __DIR__ . '/src/Glpi/Http/Response.php',
];
$ignoreErrors[] = [
'message' => '#^Negated boolean expression is always false\\.$#',
'identifier' => 'booleanNot.alwaysFalse',
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
"friendsoftwig/twigcs": "^6.4",
"glpi-project/tools": "^0.7",
"mikey179/vfsstream": "^1.6",
"nikic/php-parser": "^5.4",
"php-parallel-lint/php-parallel-lint": "^1.4",
"phpstan/extension-installer": "^1.4",
"phpstan/phpstan": "^2.1",
Expand Down
2 changes: 1 addition & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 2 additions & 3 deletions front/_check_webserver_config.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
* http://glpi-project.org
*
* @copyright 2015-2025 Teclib' and contributors.
* @copyright 2003-2014 by the INDEPNET Development Team.
* @licence https://www.gnu.org/licenses/gpl-3.0.html
*
* ---------------------------------------------------------------------
Expand Down Expand Up @@ -36,7 +35,7 @@
if (!class_exists('Glpi\\Kernel\\Kernel', autoload: false)) {
// `Glpi\Kernel\Kernel` class will exists if the request was processed by the `/public/index.php` file,
// and will not be found otherwise.
http_response_code(404);
header('HTTP/1.1 404 Not Found');
readfile(__DIR__ . '/../index.html');
exit();
exit(); // @phpstan-ignore glpi.forbidExit (Script execution should be stopped to prevent further errors)
}
14 changes: 7 additions & 7 deletions front/cron.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
echo "\t" . 'You should run the script as the same user that your web server runs as to avoid file permissions being ruined.' . "\n";
if (!in_array('--allow-superuser', $_SERVER['argv'], true)) {
echo "\t" . 'Use --allow-superuser option to bypass this limitation.' . "\n";
exit(1);
exit(1); // @phpstan-ignore glpi.forbidExit (CLI context)
}
}

Expand All @@ -79,36 +79,36 @@

if ($CFG_GLPI['maintenance_mode'] ?? false) {
echo 'Service is down for maintenance. It will be back shortly.' . PHP_EOL;
exit(1);
exit(1); // @phpstan-ignore glpi.forbidExit (CLI context)
}

if (!($DB instanceof DBmysql)) {
echo sprintf(
'ERROR: The database configuration file "%s" is missing or is corrupted. You have to either restart the install process, or restore this file.',
GLPI_CONFIG_DIR . '/config_db.php'
) . PHP_EOL;
exit(1);
exit(1); // @phpstan-ignore glpi.forbidExit (CLI context)
}

if (!$DB->connected) {
echo 'ERROR: The connection to the SQL server could not be established. Please check your configuration.' . PHP_EOL;
exit(1);
exit(1); // @phpstan-ignore glpi.forbidExit (CLI context)
}

if (!Config::isLegacyConfigurationLoaded()) {
echo 'ERROR: Unable to load the GLPI configuration from the database.' . PHP_EOL;
exit(1);
exit(1); // @phpstan-ignore glpi.forbidExit (CLI context)
}

if (Update::isUpdateMandatory()) {
echo 'The GLPI codebase has been updated. The update of the GLPI database is necessary.' . PHP_EOL;
exit(1);
exit(1); // @phpstan-ignore glpi.forbidExit (CLI context)
}

if (!is_writable(GLPI_LOCK_DIR)) {
echo "\t" . sprintf('ERROR: %s is not writable.' . "\n", GLPI_LOCK_DIR);
echo "\t" . 'Run the script as the same user that your web server runs as.' . "\n";
exit(1);
exit(1); // @phpstan-ignore glpi.forbidExit (CLI context)
}

if (isset($_SERVER['argc']) && ($_SERVER['argc'] > 1)) {
Expand Down
2 changes: 2 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ parameters:
message: '~/(downstream\.php|config_db\.php|config_db_slave\.php)" is not a file or it does not exist.~'
reportUnmatched: false
rules:
- Glpi\Tools\PHPStan\ForbidExitRule
- Glpi\Tools\PHPStan\ForbidHttpResponseCodeRule
- GlpiProject\Tools\PHPStan\Rules\GlobalVarTypeRule

# Copy and uncomment this content into a "phpstan.neon" file to add your own config values
Expand Down
11 changes: 10 additions & 1 deletion src/CommonITILObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -4167,7 +4167,16 @@ public static function showMassiveActionsSubForm(MassiveAction $ma)

switch ($ma->getAction()) {
case 'add_task':
$itemtype = $ma->getItemtype(true);
$itemtype_or_selector = $ma->getItemtype(true);

if (is_bool($itemtype_or_selector)) {
// MassiveAction::getItemtype() will return a boolean if the itemtype selector needs to be displayed.
return $itemtype_or_selector;
}

// MassiveAction::getItemtype() will return a classname if the selector does not need to be displayed.
$itemtype = $itemtype_or_selector;

$tasktype = $itemtype . 'Task';
if ($ttype = getItemForItemtype($tasktype)) {
/** @var CommonITILTask $ttype */
Expand Down
2 changes: 1 addition & 1 deletion src/CronTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ public function signal($signo)
$_SESSION["glpicronuserrunning"] = '';
self::release_lock();
Toolbox::logInFile('cron', __('Action aborted') . "\n");
exit();
exit(); // @phpstan-ignore glpi.forbidExit (CLI context)
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/Glpi/Application/ResourcesChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ public function checkResources(): void
if (!$this->areDependenciesUpToDate()) {
echo 'Application dependencies are not up to date.' . PHP_EOL;
echo 'Run "php bin/console dependencies install" in the glpi tree to fix this.' . PHP_EOL;
exit(1);
exit(1); // @phpstan-ignore glpi.forbidExit (Script execution should be stopped to prevent further errors)
}
if (!$this->areLocalesUpToDate()) {
echo 'Application locales have to be compiled.' . PHP_EOL;
echo 'Run "php bin/console locales:compile" in the glpi tree to fix this.' . PHP_EOL;
exit(1);
exit(1); // @phpstan-ignore glpi.forbidExit (Script execution should be stopped to prevent further errors)
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Glpi/Http/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public static function sendError(int $code, string $message, string $content_typ
Toolbox::logDebug($message);

echo($output);
exit(1);
exit(1); // @phpstan-ignore glpi.forbidExit (Deprecated scope)
}

public function sendHeaders(): Response
Expand Down
2 changes: 1 addition & 1 deletion src/Glpi/Kernel/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ protected function buildContainer(): ContainerBuilder

echo sprintf('Unable to write in the `%s` directory.', $relative_path) . PHP_EOL;
echo 'Files ACL must be fixed.' . PHP_EOL;
exit(1);
exit(1); // @phpstan-ignore glpi.forbidExit (Script execution should be stopped to prevent further errors)
}
}

Expand Down
24 changes: 10 additions & 14 deletions src/MassiveAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -246,8 +246,8 @@ public function __construct(array $POST, array $GET, $stage, ?int $items_id = nu
throw new \Exception(__('Implementation error!'));
}
if ($POST['action'] == -1) {
// Case when no action is choosen
exit();
// Case when no action is choosen
throw new \RuntimeException();
}
if (isset($POST['actions'])) {
// First, get the name of current action !
Expand Down Expand Up @@ -550,11 +550,11 @@ public function getCheckItem($POST)

if ($this->check_item === null && isset($POST['check_itemtype'])) {
if (!($this->check_item = getItemForItemtype($POST['check_itemtype']))) {
exit();
throw new \RuntimeException();
}
if (isset($POST['check_items_id'])) {
if (!$this->check_item->getFromDB($POST['check_items_id'])) {
exit();
throw new \RuntimeException();
} else {
$this->check_item->getEmpty();
}
Expand Down Expand Up @@ -595,7 +595,7 @@ public function addHiddenFields()
*
* @param boolean $display_selector can we display the itemtype selector ?
*
* @return string|boolean the itemtype or false if we cannot define it (and we cannot display the selector)
* @return string|boolean the itemtype, or true if the selector is displayed, or false if we cannot define the itemtype nor display the selector
**/
public function getItemtype($display_selector)
{
Expand Down Expand Up @@ -629,7 +629,7 @@ public function getItemtype($display_selector)
);

echo "<span id='show_itemtype$rand'>&nbsp;</span>";
exit();
return true;
}

return false;
Expand Down Expand Up @@ -1083,15 +1083,11 @@ public static function showMassiveActionsSubForm(MassiveAction $ma)
);
}
// Only display the form for this stage
exit();
return;
}

if (!isset($ma->POST['common_options'])) {
echo "<div class='center'><img src='" . $CFG_GLPI["root_doc"] . "/pics/warning.png' alt='" .
__s('Warning') . "'><br><br>";
echo "<span class='b'>" . __s('Implementation error!') . "</span><br>";
echo "</div>";
exit();
throw new \RuntimeException('Implementation error!');
}

if ($ma->POST['common_options'] == 'false') {
Expand Down Expand Up @@ -1124,7 +1120,7 @@ public static function showMassiveActionsSubForm(MassiveAction $ma)

$itemtype_search_options = SearchOption::getOptionsForItemtype($so_itemtype);
if (!isset($itemtype_search_options[$so_index])) {
exit();
throw new \RuntimeException();
}

$item = $so_item;
Expand All @@ -1133,7 +1129,7 @@ public static function showMassiveActionsSubForm(MassiveAction $ma)
}

if ($item === null) {
exit();
throw new \RuntimeException();
}

$plugdisplay = false;
Expand Down
69 changes: 69 additions & 0 deletions tools/src/PHPStan/ForbidExitRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

/**
* ---------------------------------------------------------------------
*
* GLPI - Gestionnaire Libre de Parc Informatique
*
* http://glpi-project.org
*
* @copyright 2015-2025 Teclib' and contributors.
* @licence https://www.gnu.org/licenses/gpl-3.0.html
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* ---------------------------------------------------------------------
*/

namespace Glpi\Tools\PHPStan;

use PhpParser\Node;
use PhpParser\Node\Expr\Exit_;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;

class ForbidExitRule implements Rule
{
public function getNodeType(): string
{
return Exit_::class;
}

public function processNode(Node $node, Scope $scope): array
{
$name = match ($node->getAttribute('kind')) {
Exit_::KIND_DIE => 'die',
Exit_::KIND_EXIT => 'exit',
default => 'die/exit',
};

return [
RuleErrorBuilder::message(
sprintf(
'You should not use the `%s` function. It prevents the execution of post-request/post-command routines.',
$name
)
)
->identifier('glpi.forbidExit')
->build()
];
}
}
Loading