Files
wordpress-sso/includes/class-of-sso-admin.php
Polyedre 6b54fd524b OpenFlyers SSO WordPress plugin 1.2.0
Read the member name and email from a custom report (profile_report_id).
2026-11-18 20:30:16 +01:00

602 lines
27 KiB
PHP

<?php
/**
* class-of-sso-admin.php
*
* Settings screen, member linking field and configuration diagnostics.
*
* @package OpenFlyers_SSO
*
* @link https://doc4-fr.openflyers.com/Plugin-WordPress Documentation publique
* @link https://work.openflyers.com/OF4-WordPress-SSO-plugin Fiche interne
*/
// Prevent direct access.
if (!defined('ABSPATH')) {
exit;
}
/**
* Class OF_SSO_Admin
*/
class OF_SSO_Admin
{
/**
* Register the admin hooks.
*
* @return void
*/
public static function init()
{
add_action('admin_menu', array(__CLASS__, 'addMenu'));
add_action('admin_init', array(__CLASS__, 'registerSettings'));
add_action('show_user_profile', array(__CLASS__, 'renderUserField'));
add_action('edit_user_profile', array(__CLASS__, 'renderUserField'));
add_action('personal_options_update', array(__CLASS__, 'saveUserField'));
add_action('edit_user_profile_update', array(__CLASS__, 'saveUserField'));
}
/**
* Add the settings page under the Settings menu.
*
* @return void
*/
public static function addMenu()
{
add_options_page(
__('OpenFlyers SSO', 'openflyers-sso'),
__('OpenFlyers SSO', 'openflyers-sso'),
'manage_options',
'openflyers-sso',
array(__CLASS__, 'renderPage')
);
}
/**
* Declare the option and its sanitize callback.
*
* @return void
*/
public static function registerSettings()
{
register_setting(
'of_sso_settings_group',
OF_SSO_OPTION,
array('sanitize_callback' => array(__CLASS__, 'sanitize'))
);
}
/**
* Sanitize the submitted settings.
*
* @param array $input Raw submitted values.
* @return array
*/
public static function sanitize($input)
{
$input = is_array($input) ? $input : array();
$current = of_sso_get_settings();
$output = array();
$textKeys = array('platform', 'client_id', 'default_role');
foreach ($textKeys as $key) {
$output[$key] = isset($input[$key]) ? sanitize_text_field($input[$key]) : '';
}
$urlKeys = array('base_url', 'redirect_uri', 'redirect_after_login');
foreach ($urlKeys as $key) {
$output[$key] = isset($input[$key]) ? esc_url_raw(trim($input[$key])) : '';
}
// Paths are kept as-is apart from trimming: they point outside the web root on purpose.
$pathKeys = array('cert_dir', 'auth_cert', 'auth_key', 'sign_cert', 'sign_key', 'ca_cert', 'server_sign_cert');
foreach ($pathKeys as $key) {
$output[$key] = isset($input[$key]) ? trim(wp_strip_all_tags($input[$key])) : '';
}
// 0 means "no report": members then keep the technical name built from their identifier.
$output['profile_report_id'] = isset($input['profile_report_id']) ? absint($input['profile_report_id']) : 0;
$boolKeys = array('send_x_ssl_cert', 'auto_create', 'show_login_button', 'debug');
foreach ($boolKeys as $key) {
$output[$key] = empty($input[$key]) ? 0 : 1;
}
// An empty secret field means "keep the stored value", so a secret is never wiped by accident.
foreach (array('client_secret', 'key_passphrase') as $key) {
$submitted = isset($input[$key]) ? trim($input[$key]) : '';
$output[$key] = ($submitted === '') ? $current[$key] : $submitted;
}
if (empty($output['base_url'])) {
$output['base_url'] = 'https://openflyers.com';
}
return $output;
}
/**
* Render the settings page.
*
* @return void
*/
public static function renderPage()
{
if (!current_user_can('manage_options')) {
return;
}
$settings = of_sso_get_settings();
$verdict = self::handleConnectionTest();
?>
<div class="wrap">
<h1><?php esc_html_e('OpenFlyers SSO', 'openflyers-sso'); ?></h1>
<p><?php esc_html_e('URL de redirection a declarer dans OpenFlyers (Administration > Configuration de l\'API) :', 'openflyers-sso'); ?></p>
<p><code><?php echo esc_html(of_sso_get_redirect_uri()); ?></code></p>
<?php self::renderConnectionTest($verdict); ?>
<form method="post" action="options.php">
<?php settings_fields('of_sso_settings_group'); ?>
<h2><?php esc_html_e('Plateforme et client', 'openflyers-sso'); ?></h2>
<table class="form-table" role="presentation">
<?php
self::textRow('platform', __('Code plateforme', 'openflyers-sso'), $settings['platform'], 'acat-lfcl');
self::descriptionRow(__('A laisser vide si la plateforme repond directement a la racine du domaine, ce qui est le cas des installations dediees.', 'openflyers-sso'));
self::textRow('base_url', __('URL de base OpenFlyers', 'openflyers-sso'), $settings['base_url'], 'https://openflyers.com');
self::textRow('client_id', __('client_id', 'openflyers-sso'), $settings['client_id'], '');
self::secretRow('client_secret', __('Passphrase (client_secret)', 'openflyers-sso'), $settings['client_secret']);
self::textRow('redirect_uri', __('URL de redirection (facultatif)', 'openflyers-sso'), $settings['redirect_uri'], of_sso_get_redirect_uri());
?>
</table>
<h2><?php esc_html_e('Certificats', 'openflyers-sso'); ?></h2>
<p class="description">
<?php esc_html_e('Indiquez le dossier ou vous avez depose les six fichiers fournis par OpenFlyers. Ce dossier doit etre hors de la racine web et lisible par PHP uniquement.', 'openflyers-sso'); ?>
</p>
<table class="form-table" role="presentation">
<?php
self::textRow('cert_dir', __('Dossier des certificats', 'openflyers-sso'), $settings['cert_dir'], '/home/site/of-certs');
self::secretRow('key_passphrase', __('Passphrase des cles privees (si protegees)', 'openflyers-sso'), $settings['key_passphrase']);
self::checkboxRow('send_x_ssl_cert', __('Envoyer l\'en-tete X-SSL-CERT', 'openflyers-sso'), $settings['send_x_ssl_cert'], __('A activer uniquement si OpenFlyers repond invalid_certificate alors que les certificats sont corrects.', 'openflyers-sso'));
?>
</table>
<p class="description">
<?php esc_html_e('Noms de fichiers attendus dans ce dossier :', 'openflyers-sso'); ?>
<code><?php echo implode('</code>, <code>', array_map('esc_html', of_sso_cert_file_names())); ?></code>
</p>
<details>
<summary style="cursor:pointer;margin:12px 0">
<?php esc_html_e('Chemins personnalises (avance)', 'openflyers-sso'); ?>
</summary>
<p class="description">
<?php esc_html_e('A remplir uniquement si un fichier porte un autre nom ou se trouve ailleurs. Un champ vide utilise le dossier ci-dessus.', 'openflyers-sso'); ?>
</p>
<table class="form-table" role="presentation">
<?php
$resolved = of_sso_resolve_cert_paths($settings);
self::textRow('auth_cert', __('Certificat TLS mutuel', 'openflyers-sso'), $settings['auth_cert'], $resolved['auth_cert']);
self::textRow('auth_key', __('Cle privee TLS mutuel', 'openflyers-sso'), $settings['auth_key'], $resolved['auth_key']);
self::textRow('sign_cert', __('Certificat de signature HTTP', 'openflyers-sso'), $settings['sign_cert'], $resolved['sign_cert']);
self::textRow('sign_key', __('Cle privee de signature HTTP', 'openflyers-sso'), $settings['sign_key'], $resolved['sign_key']);
self::textRow('ca_cert', __('Autorite de certification OpenFlyers', 'openflyers-sso'), $settings['ca_cert'], $resolved['ca_cert']);
self::textRow('server_sign_cert', __('Certificat de signature du serveur', 'openflyers-sso'), $settings['server_sign_cert'], $resolved['server_sign_cert']);
?>
</table>
</details>
<h2><?php esc_html_e('Comptes WordPress', 'openflyers-sso'); ?></h2>
<table class="form-table" role="presentation">
<?php
self::checkboxRow('auto_create', __('Creer automatiquement les comptes', 'openflyers-sso'), $settings['auto_create'], __('Si decoche, seuls les membres deja associes a un compte WordPress peuvent se connecter.', 'openflyers-sso'));
self::roleRow('default_role', __('Role des comptes crees', 'openflyers-sso'), $settings['default_role']);
self::textRow('redirect_after_login', __('Page apres connexion', 'openflyers-sso'), $settings['redirect_after_login'], home_url('/espace-membres/'));
self::textRow('profile_report_id', __('Rapport des coordonnees des membres', 'openflyers-sso'), $settings['profile_report_id'] ? $settings['profile_report_id'] : '', '');
self::descriptionRow(__('Numero du rapport personnalise OpenFlyers qui renvoie le prenom, le nom et l\'e-mail du membre connecte (filtre sur $connectedPersonId). Ils sont alors mis a jour a chaque connexion. Laisser vide pour ne pas les recuperer.', 'openflyers-sso'));
self::checkboxRow('show_login_button', __('Bouton sur la page de connexion WordPress', 'openflyers-sso'), $settings['show_login_button'], '');
self::checkboxRow('debug', __('Journalisation', 'openflyers-sso'), $settings['debug'], __('Ecrit les erreurs dans le journal PHP (error_log).', 'openflyers-sso'));
?>
</table>
<?php submit_button(); ?>
</form>
<h2><?php esc_html_e('Diagnostic', 'openflyers-sso'); ?></h2>
<?php self::renderDiagnostics($settings); ?>
</div>
<?php
}
/**
* Run the connection test when its button was pressed.
*
* @return array|null Verdict returned by the client, or null when no test was requested.
*/
private static function handleConnectionTest()
{
if (empty($_POST['of_sso_test_connection']) or !current_user_can('manage_options')) {
return null;
}
if (!isset($_POST['of_sso_test_nonce'])
or !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['of_sso_test_nonce'])), 'of_sso_test_connection')
) {
return array('status' => 'unknown', 'detail' => __('Jeton de securite invalide, merci de recharger la page.', 'openflyers-sso'));
}
$client = of_sso_get_client();
if (!$client) {
return array('status' => 'unknown', 'detail' => __('Renseignez au moins le code plateforme et le client_id.', 'openflyers-sso'));
}
return $client->testConnection(of_sso_get_redirect_uri());
}
/**
* Render the connection test button and the verdict of the last run.
*
* @param array|null $verdict Verdict returned by handleConnectionTest().
* @return void
*/
private static function renderConnectionTest($verdict)
{
if (is_array($verdict)) {
// Every status but 'ok' names the exact link in the chain that refused the call.
$messages = array(
'ok' => array('success', __('Connexion a OpenFlyers reussie. Le certificat TLS, la signature et les identifiants du client sont acceptes : un membre peut se connecter.', 'openflyers-sso')),
'network' => array('error', __('Le serveur OpenFlyers n\'a pas pu etre contacte. Verifiez que l\'hebergeur autorise les connexions sortantes avec un certificat client, et que la cle privee est lisible par PHP.', 'openflyers-sso')),
'server_ca' => array('error', __('Le certificat du serveur OpenFlyers n\'a pas pu etre verifie avec le fichier ca.crt fourni. Ce fichier sert a valider le serveur, pas votre client : s\'il ne convient pas, retirez ca.crt du dossier des certificats pour utiliser le magasin d\'autorites du systeme.', 'openflyers-sso')),
'tls' => array('error', __('Le certificat TLS a ete refuse. Il ne correspond pas a celui enregistre dans OpenFlyers. Si les fichiers sont les bons, votre hebergeur termine sans doute le TLS sur un proxy : activez l\'option X-SSL-CERT.', 'openflyers-sso')),
'signature' => array('error', __('La signature HTTP a ete refusee. Verifiez la cle de signature, et surtout que l\'horloge du serveur est a l\'heure (NTP).', 'openflyers-sso')),
'client' => array('error', __('Le client_id ou la passphrase sont incorrects.', 'openflyers-sso')),
'grant_type' => array('error', __('Ce client n\'est pas declare avec le type d\'autorisation authorization_code dans OpenFlyers.', 'openflyers-sso')),
'unknown' => array('warning', __('Reponse inattendue d\'OpenFlyers.', 'openflyers-sso')),
);
$status = isset($messages[$verdict['status']]) ? $verdict['status'] : 'unknown';
list($noticeType, $text) = $messages[$status];
printf(
'<div class="notice notice-%s"><p><strong>%s</strong></p>%s</div>',
esc_attr($noticeType),
esc_html($text),
empty($verdict['detail'])
? ''
: '<p><code>' . esc_html($verdict['detail']) . '</code></p>'
);
}
?>
<form method="post">
<?php wp_nonce_field('of_sso_test_connection', 'of_sso_test_nonce'); ?>
<p>
<button type="submit" name="of_sso_test_connection" value="1" class="button button-secondary">
<?php esc_html_e('Tester la connexion a OpenFlyers', 'openflyers-sso'); ?>
</button>
<span class="description">
<?php esc_html_e('Verifie le certificat, la signature et les identifiants du client sans qu\'un membre ait a se connecter.', 'openflyers-sso'); ?>
</span>
</p>
</form>
<?php
}
/**
* Render the configuration checks.
*
* @param array $settings Current settings.
* @return void
*/
private static function renderDiagnostics(array $settings)
{
$checks = array();
$checks[] = array(
__('Extension cURL', 'openflyers-sso'),
function_exists('curl_init'),
__('Requise pour le TLS mutuel.', 'openflyers-sso'),
);
$checks[] = array(
__('Extension OpenSSL', 'openflyers-sso'),
function_exists('openssl_sign'),
__('Requise pour la signature HTTP.', 'openflyers-sso'),
);
$files = array(
'auth_cert' => __('Certificat TLS mutuel', 'openflyers-sso'),
'auth_key' => __('Cle privee TLS mutuel', 'openflyers-sso'),
'sign_cert' => __('Certificat de signature HTTP', 'openflyers-sso'),
'sign_key' => __('Cle privee de signature HTTP', 'openflyers-sso'),
'ca_cert' => __('Autorite de certification', 'openflyers-sso'),
'server_sign_cert' => __('Certificat de signature du serveur', 'openflyers-sso'),
);
// The folder setting and the per-file overrides both land here.
$paths = of_sso_resolve_cert_paths($settings);
foreach ($files as $key => $label) {
$path = $paths[$key];
$comment = '';
if (!empty($path) and is_readable($path) and substr($key, -4) === 'cert') {
$parsed = openssl_x509_parse((string) file_get_contents($path));
if (!empty($parsed['validTo_time_t'])) {
$comment = sprintf(
/* translators: %s: certificate expiry date. */
__('Expire le %s', 'openflyers-sso'),
date_i18n(get_option('date_format'), $parsed['validTo_time_t'])
);
}
}
// ca.crt only overrides the bundle used to validate the OpenFlyers server; without it
// the system store applies, which is what most hosts want.
if ($key === 'ca_cert' and empty($path)) {
$checks[] = array(
$label,
true,
__('Absent : le magasin d\'autorites du systeme sera utilise.', 'openflyers-sso'),
);
continue;
}
if (empty($path)) {
$comment = __('Aucun chemin : renseignez le dossier des certificats.', 'openflyers-sso');
} elseif (!is_readable($path)) {
$comment = sprintf(
/* translators: %s: expected file path. */
__('Introuvable ou illisible : %s', 'openflyers-sso'),
$path
);
}
$checks[] = array($label, !empty($path) && is_readable($path), $comment);
}
// A certificate paired with the wrong key fails at handshake time with an obscure error.
$pairs = array(
'auth' => array('auth_cert', 'auth_key', __('Le certificat TLS et sa cle correspondent', 'openflyers-sso')),
'sign' => array('sign_cert', 'sign_key', __('Le certificat de signature et sa cle correspondent', 'openflyers-sso')),
);
foreach ($pairs as $pair) {
list($certKey, $keyKey, $label) = $pair;
if (empty($paths[$certKey]) or empty($paths[$keyKey])
or !is_readable($paths[$certKey]) or !is_readable($paths[$keyKey])
) {
continue;
}
$privateKey = empty($settings['key_passphrase'])
? openssl_get_privatekey((string) file_get_contents($paths[$keyKey]))
: openssl_get_privatekey((string) file_get_contents($paths[$keyKey]), $settings['key_passphrase']);
$matches = $privateKey
? openssl_x509_check_private_key((string) file_get_contents($paths[$certKey]), $privateKey)
: false;
$checks[] = array(
$label,
$matches,
$matches ? '' : __('La cle ne correspond pas au certificat, ou la passphrase est incorrecte.', 'openflyers-sso'),
);
}
// A private key readable by anyone on a shared host is the main risk of this setup.
// Skipped on Windows, where fileperms() says nothing about the actual ACL.
foreach (array('auth_key', 'sign_key') as $key) {
if (DIRECTORY_SEPARATOR === '\\') {
break;
}
if (!empty($paths[$key]) and is_readable($paths[$key])) {
$perms = substr(sprintf('%o', fileperms($paths[$key])), -3);
$checks[] = array(
sprintf(
/* translators: %s: setting label. */
__('Permissions de %s', 'openflyers-sso'),
$key
),
in_array($perms, array('600', '400'), true),
sprintf(
/* translators: %s: octal file permissions. */
__('Actuellement %s, attendu 600.', 'openflyers-sso'),
$perms
),
);
}
}
echo '<table class="widefat striped" style="max-width:900px">';
foreach ($checks as $check) {
list($label, $ok, $comment) = $check;
printf(
'<tr><td style="width:320px">%s</td><td style="width:60px">%s</td><td>%s</td></tr>',
esc_html($label),
$ok ? '<span style="color:#00a32a">&#10003;</span>' : '<span style="color:#d63638">&#10007;</span>',
esc_html($comment)
);
}
echo '</table>';
}
/**
* Render a text input row.
*
* @param string $key Setting key.
* @param string $label Field label.
* @param string $value Current value.
* @param string $placeholder Placeholder text.
* @return void
*/
private static function textRow($key, $label, $value, $placeholder)
{
printf(
'<tr><th scope="row"><label for="of_sso_%1$s">%2$s</label></th>'
. '<td><input type="text" class="regular-text" id="of_sso_%1$s" name="%3$s[%1$s]" value="%4$s" placeholder="%5$s" /></td></tr>',
esc_attr($key),
esc_html($label),
esc_attr(OF_SSO_OPTION),
esc_attr($value),
esc_attr($placeholder)
);
}
/**
* Render a full-width note under the previous field.
*
* @param string $text Help text.
* @return void
*/
private static function descriptionRow($text)
{
printf('<tr><th scope="row"></th><td><p class="description">%s</p></td></tr>', esc_html($text));
}
/**
* Render a write-only secret row.
*
* @param string $key Setting key.
* @param string $label Field label.
* @param string $value Current value.
* @return void
*/
private static function secretRow($key, $label, $value)
{
printf(
'<tr><th scope="row"><label for="of_sso_%1$s">%2$s</label></th>'
. '<td><input type="password" class="regular-text" id="of_sso_%1$s" name="%3$s[%1$s]" value="" autocomplete="new-password" />'
. '<p class="description">%4$s</p></td></tr>',
esc_attr($key),
esc_html($label),
esc_attr(OF_SSO_OPTION),
empty($value)
? esc_html__('Non renseigne.', 'openflyers-sso')
: esc_html__('Deja enregistre. Laisser vide pour conserver la valeur actuelle.', 'openflyers-sso')
);
}
/**
* Render a checkbox row.
*
* @param string $key Setting key.
* @param string $label Field label.
* @param int $value Current value.
* @param string $description Help text.
* @return void
*/
private static function checkboxRow($key, $label, $value, $description)
{
printf(
'<tr><th scope="row">%2$s</th><td><label><input type="checkbox" id="of_sso_%1$s" name="%3$s[%1$s]" value="1" %4$s /> %2$s</label>'
. '<p class="description">%5$s</p></td></tr>',
esc_attr($key),
esc_html($label),
esc_attr(OF_SSO_OPTION),
checked(1, (int) $value, false),
esc_html($description)
);
}
/**
* Render the role selector.
*
* @param string $key Setting key.
* @param string $label Field label.
* @param string $value Current value.
* @return void
*/
private static function roleRow($key, $label, $value)
{
printf(
'<tr><th scope="row"><label for="of_sso_%1$s">%2$s</label></th><td><select id="of_sso_%1$s" name="%3$s[%1$s]">',
esc_attr($key),
esc_html($label),
esc_attr(OF_SSO_OPTION)
);
// wp_roles() is always available, unlike wp_dropdown_roles() which needs the admin includes.
foreach (wp_roles()->get_names() as $role => $name) {
printf(
'<option value="%s" %s>%s</option>',
esc_attr($role),
selected($role, $value, false),
esc_html(translate_user_role($name))
);
}
echo '</select></td></tr>';
}
/**
* Display the OpenFlyers identifier on the user profile screen.
*
* @param WP_User $user User being edited.
* @return void
*/
public static function renderUserField($user)
{
if (!current_user_can('edit_users') and get_current_user_id() !== $user->ID) {
return;
}
$value = get_user_meta($user->ID, OF_SSO_USER_META, true);
$editable = current_user_can('edit_users');
?>
<h2><?php esc_html_e('OpenFlyers', 'openflyers-sso'); ?></h2>
<table class="form-table" role="presentation">
<tr>
<th><label for="of_sso_user_id"><?php esc_html_e('Identifiant du membre', 'openflyers-sso'); ?></label></th>
<td>
<?php if ($editable) : ?>
<?php wp_nonce_field('of_sso_user_field', 'of_sso_user_nonce'); ?>
<input type="text" id="of_sso_user_id" name="of_sso_user_id" value="<?php echo esc_attr($value); ?>" class="regular-text" />
<p class="description"><?php esc_html_e('Identifiant OpenFlyers du membre. Necessaire pour associer ce compte WordPress a un compte OpenFlyers.', 'openflyers-sso'); ?></p>
<?php else : ?>
<code><?php echo esc_html($value ? $value : '-'); ?></code>
<?php endif; ?>
</td>
</tr>
</table>
<?php
}
/**
* Save the OpenFlyers identifier from the user profile screen.
*
* @param int $userId Edited user identifier.
* @return void
*/
public static function saveUserField($userId)
{
if (!current_user_can('edit_users')) {
return;
}
if (!isset($_POST['of_sso_user_nonce'])
or !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['of_sso_user_nonce'])), 'of_sso_user_field')
) {
return;
}
$value = isset($_POST['of_sso_user_id']) ? sanitize_text_field(wp_unslash($_POST['of_sso_user_id'])) : '';
if ($value === '') {
delete_user_meta($userId, OF_SSO_USER_META);
return;
}
update_user_meta($userId, OF_SSO_USER_META, (string) absint($value));
}
}