Skip to content
Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

- Make the plugin compatible with the Content Security Policy

### Fixed

- Fix the profile rights tab freezing the browser and failing to save with many dashboards, and the collections page querying Metabase once per collection

## [1.4.3] - 2026-10-06

### Fixed
Expand Down
4 changes: 3 additions & 1 deletion front/collections.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,10 @@

echo '<h3>' . __s('Extract questions from metabase:', 'metabase') . '</h3>';
echo "<ul class='metabase_collection_list'>";
// all cards in one query, instead of the full list once per collection
$cards_by_collection = $apiclient->getCardsByCollection();
foreach ($collections as $collection) {
$collection_cards = $apiclient->getCards($collection['id']);
$collection_cards = $cards_by_collection === false ? false : ($cards_by_collection[$collection['id']] ?? []);
if (
$collection_cards !== false
&& count($collection_cards)
Expand Down
36 changes: 23 additions & 13 deletions front/profileright.form.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@
if (
!array_key_exists('profiles_id', $_REQUEST)
|| empty($_REQUEST['profiles_id'])
|| !array_key_exists('dashboard', $_REQUEST)
|| !is_array($_REQUEST['dashboard'])
|| !array_key_exists('dashboards', $_REQUEST)
|| !is_string($_REQUEST['dashboards'])
|| !is_string($_REQUEST['dashboards_read'] ?? '')
) {
Session::addMessageAfterRedirect(
__s('Invalid request.', 'metabase'),
Expand All @@ -45,19 +46,26 @@
Html::back();
}

// displayed dashboards and readable ones, each sent as one comma separated field
$readableUuids = array_flip(array_map('intval', array_filter(explode(',', $_REQUEST['dashboards_read'] ?? ''))));

$rightsByDashboard = [];
$viewableDashboardsUuids = [];
foreach ($_REQUEST['dashboard'] as $dashboardUuid => $rights) {
PluginMetabaseProfileright::setDashboardRightsForProfile(
$_REQUEST['profiles_id'],
$dashboardUuid,
$rights,
);
foreach (array_filter(explode(',', $_REQUEST['dashboards'])) as $dashboardUuid) {
$dashboardUuid = (int) $dashboardUuid;
$rights = isset($readableUuids[$dashboardUuid]) ? READ : 0;

$rightsByDashboard[$dashboardUuid] = $rights;
if (($rights & READ) !== 0) {
$viewableDashboardsUuids[] = $dashboardUuid;
}
}

PluginMetabaseProfileright::setDashboardsRightsForProfile(
$_REQUEST['profiles_id'],
$rightsByDashboard,
);

$apiclient = new PluginMetabaseAPIClient();
$apiclient->enableDashboardsEmbeddedDisplay($viewableDashboardsUuids);
} elseif (isset($_REQUEST['set_rights_to_all'])) {
Expand All @@ -74,17 +82,19 @@

$apiclient = new PluginMetabaseAPIClient();

$rightsByDashboard = [];
$viewableDashboardsUuids = [];
foreach ($apiclient->getDashboards() as $dashboard) {
PluginMetabaseProfileright::setDashboardRightsForProfile(
$_REQUEST['profiles_id'],
$dashboard['id'],
$_REQUEST['set_rights_to_all'],
);
$rightsByDashboard[$dashboard['id']] = $_REQUEST['set_rights_to_all'];

$viewableDashboardsUuids[] = $dashboard['id'];
}

PluginMetabaseProfileright::setDashboardsRightsForProfile(
$_REQUEST['profiles_id'],
$rightsByDashboard,
);

$apiclient->enableDashboardsEmbeddedDisplay($viewableDashboardsUuids);
}

Expand Down
48 changes: 32 additions & 16 deletions inc/apiclient.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,15 +97,11 @@ public function connect()

public function checkSession()
{
// do a simple query
$this->getCurrentUser(true);

// check session token, if set, we still have a valid token
// a stored token is used as is: an expired one is renewed by httpQuery() on the 401 answer
if (isset($_SESSION['metabase']['session_token'])) {
return true;
}

// so reconnect
$this->connect();
// check again session token, if set, we now have a valid token
return isset($_SESSION['metabase']['session_token']);
Expand Down Expand Up @@ -647,6 +643,21 @@ public function retrieveCard($card_name, $collection_id)
* @return boolean|array Array of cards, false if an error occurs.
*/
public function getCards($collection_id = null)
{
$cards_by_collection = $this->getCardsByCollection();
if ($cards_by_collection === false) {
return false;
}

return $cards_by_collection[$collection_id ?? 'root'] ?? [];
}

/**
* Retrieve all cards, grouped by collection.
*
* @return false|array<int|string, array> Cards indexed by collection id ("root" for the root collection), false if an error occurs.
*/
public function getCardsByCollection()
{
if (!$this->checkSession()) {
return false;
Expand All @@ -659,17 +670,15 @@ public function getCards($collection_id = null)
}

// Metabase's API returns id:"root" for the root collection, but cards
// in it have collection_id: null - normalize before comparing.
$normalized_id = $collection_id === 'root' ? null : $collection_id;

$cards = array_filter(
$cards,
fn($card) => is_array($card)
&& array_key_exists('collection_id', $card)
&& $normalized_id === $card['collection_id'],
);
// in it have collection_id: null.
$cards_by_collection = [];
foreach ($cards as $card) {
if (is_array($card) && array_key_exists('collection_id', $card)) {
$cards_by_collection[$card['collection_id'] ?? 'root'][] = $card;
}
}

return $cards;
return $cards_by_collection;
Comment on lines +662 to +681

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getCards() can reuse the new method, so the root/null mapping lives in one place:

Suggested change
if (!$this->checkSession()) {
return false;
}
$cards = $this->httpQuery('card');
if (!is_array($cards)) {
return $cards;
}
// Metabase's API returns id:"root" for the root collection, but cards
// in it have collection_id: null.
$cards_by_collection = [];
foreach ($cards as $card) {
if (is_array($card) && array_key_exists('collection_id', $card)) {
$cards_by_collection[$card['collection_id'] ?? 'root'][] = $card;
}
}
return $cards_by_collection;
public function getCards($collection_id = null)
{
$cards_by_collection = $this->getCardsByCollection();
if ($cards_by_collection === false) {
return false;
}
return $cards_by_collection[$collection_id ?? 'root'] ?? [];
}

}

/**
Expand Down Expand Up @@ -815,11 +824,13 @@ public function getAPIBaseUri()
* @param string $method Http verb (ex: GET, POST, etc)
* @return array|false data returned by the api
*/
public function httpQuery($resource = '', $params = [], $method = 'GET')
public function httpQuery($resource = '', $params = [], $method = 'GET', bool $is_retry = false)
{
/** @var array $CFG_GLPI */
global $CFG_GLPI;

$query_params = $params;

// declare default params
$default_params = [
'_with_metadata' => false,
Expand Down Expand Up @@ -886,6 +897,11 @@ public function httpQuery($resource = '', $params = [], $method = 'GET')
// session with metabase ko, unset our token
if ($response->getStatusCode() == 401) {
unset($_SESSION['metabase']['session_token']);

// expired token: log in again and replay the query once
if (!$is_retry && $resource !== 'session' && $this->connect()) {
return $this->httpQuery($resource, $query_params, $method, true);
}
}
}
}
Expand Down
8 changes: 3 additions & 5 deletions inc/dashboard.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,12 @@ public static function showForCentral(Central $item, $withtemplate = 0, $is_help

$dashboards = $apiclient->getDashboards();
if (is_array($dashboards)) {
$rights = PluginMetabaseProfileright::getProfileRights($_SESSION['glpiactiveprofile']['id']);
$dashboards = array_filter(
$dashboards,
function ($dashboard) {
function ($dashboard) use ($rights) {
$isEmbeddingEnabled = $dashboard['enable_embedding'];
$canView = PluginMetabaseProfileright::canProfileViewDashboard(
$_SESSION['glpiactiveprofile']['id'],
$dashboard['id'],
);
$canView = (($rights[$dashboard['id']] ?? 0) & READ) !== 0;

return $isEmbeddingEnabled && $canView;
},
Expand Down
139 changes: 115 additions & 24 deletions inc/profileright.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,21 +93,14 @@ public function showForm($id, $options = [])
return false;
}

echo '<form method="post" action="' . self::getFormURL() . '">';
echo '<div class="spaced" id="tabsbody">';
echo '<table class="tab_cadre_fixe" id="mainformtable">';

echo '<tr class="headerRow"><th colspan="2">' . self::getTypeName() . '</th></tr>';

Plugin::doHook('pre_item_form', ['item' => $this, 'options' => &$options]);

echo '<tr><th colspan="2">' . __s('Rights management', 'metabase') . '</th></tr>';

echo '<input type="hidden" name="profiles_id" value="' . $id . '" />';
$rights = self::getProfileRights($id);
$rand = mt_rand();

if (Session::haveRight('profile', UPDATE)) {
echo '<tr class="tab_bg_4">';
echo '<td colspan="2" class="center">';
// own form: these buttons must not send the rights of every dashboard
echo '<form method="post" action="' . self::getFormURL() . '">';
echo '<input type="hidden" name="profiles_id" value="' . $id . '" />';
echo '<div class="center mb-2">';
echo '<button type="submit" class="btn btn-outline-secondary" name="set_rights_to_all" value="1">'
. "<i class='ti ti-check'></i>"
. '<span>' . __s('Allow access to all', 'metabase') . '</span>'
Expand All @@ -117,23 +110,34 @@ public function showForm($id, $options = [])
. "<i class='ti ti-forbid'></i>"
. '<span>' . __s('Disallow access to all', 'metabase') . '</span>'
. '</button>';
echo '</td>';
echo '</tr>';
echo '</div>';
Html::closeForm();
}

echo '<form method="post" action="' . self::getFormURL() . '" id="metabase_rights_form' . $rand . '">';
echo '<div class="spaced" id="tabsbody">';
echo '<table class="tab_cadre_fixe" id="mainformtable">';

echo '<tr class="headerRow"><th colspan="2">' . self::getTypeName() . '</th></tr>';

Plugin::doHook('pre_item_form', ['item' => $this, 'options' => &$options]);

echo '<tr><th colspan="2">' . __s('Rights management', 'metabase') . '</th></tr>';

echo '<input type="hidden" name="profiles_id" value="' . $id . '" />';
// one field for all the dashboards, to stay below max_input_vars
echo '<input type="hidden" name="dashboards" value="' . implode(',', array_map('intval', array_column($dashboards, 'id'))) . '" />';
echo '<input type="hidden" name="dashboards_read" value="" />';

foreach ($dashboards as $dashboard) {
$checked = (($rights[$dashboard['id']] ?? 0) & READ) !== 0 ? ' checked' : '';
echo '<tr class="tab_bg_1">';
echo '<td>' . $dashboard['name'] . '</td>';
echo '<td>';
Profile::dropdownRight(
sprintf('dashboard[%d]', $dashboard['id']),
[
'value' => self::getProfileRightForDashboard($id, $dashboard['id']),
'nonone' => 0,
'noread' => 0,
'nowrite' => 1,
],
);
echo '<label class="form-check mb-0">';
echo '<input type="checkbox" class="form-check-input metabase_dashboard_read" value="' . (int) $dashboard['id'] . '"' . $checked . ' />';
echo '<span class="form-check-label">' . __s('Read') . '</span>';
echo '</label>';
echo '</td>';
echo '</tr>';
}
Expand All @@ -155,6 +159,15 @@ public function showForm($id, $options = [])

Html::closeForm();

echo Html::scriptBlock(<<<JS
$('#metabase_rights_form{$rand}').on('submit', function () {
const read = $(this).find('input.metabase_dashboard_read:checked').map(function () {
return this.value;
}).get();
$(this).find('input[name=dashboards_read]').val(read.join(','));
});
JS);

return true;
}

Expand Down Expand Up @@ -188,6 +201,84 @@ public static function canProfileViewDashboards($profileId)
return false;
}

/**
* Returns the rights of a profile on all dashboards.
*
* @param integer $profileId
*
* @return array<int, int> rights indexed by dashboard uuid
*/
public static function getProfileRights($profileId)
{
/** @var DBmysql $DB */
global $DB;

$iterator = $DB->request(
[
'SELECT' => ['dashboard_uuid', 'rights'],
'FROM' => self::getTable(),
'WHERE' => [
'profiles_id' => $profileId,
],
],
);

$rights = [];
foreach ($iterator as $right) {
$rights[(int) $right['dashboard_uuid']] = (int) $right['rights'];
}

return $rights;
}

/**
* Defines profile rights for several dashboards, writing only the rights that change.
*
* @param integer $profileId
* @param array<int, int> $rightsByDashboard rights indexed by dashboard uuid
*
* @return void
*/
public static function setDashboardsRightsForProfile($profileId, array $rightsByDashboard)
{
/** @var DBmysql $DB */
global $DB;

$existing = [];
$iterator = $DB->request(
[
'SELECT' => ['id', 'dashboard_uuid', 'rights'],
'FROM' => self::getTable(),
'WHERE' => [
'profiles_id' => $profileId,
],
],
);
foreach ($iterator as $right) {
$existing[(int) $right['dashboard_uuid']] = $right;
}

$profileRight = new self();
foreach ($rightsByDashboard as $dashboardUuid => $rights) {
if (!isset($existing[$dashboardUuid])) {
$profileRight->add(
[
'profiles_id' => $profileId,
'dashboard_uuid' => $dashboardUuid,
'rights' => $rights,
],
);
} elseif ((int) $existing[$dashboardUuid]['rights'] !== (int) $rights) {
$profileRight->update(
[
'id' => $existing[$dashboardUuid]['id'],
'rights' => $rights,
],
);
}
}
}

/**
* Check if profile is able to view given dashboard.
*
Expand Down
Loading