Initial commit
This commit is contained in:
750
includes/class-admin-page.php
Normal file
750
includes/class-admin-page.php
Normal file
@@ -0,0 +1,750 @@
|
||||
<?php
|
||||
/**
|
||||
* Admin Page Class - Handles the admin interface
|
||||
*/
|
||||
|
||||
if (!defined('ABSPATH')) {
|
||||
exit;
|
||||
}
|
||||
|
||||
class Thalim_HAL_Admin_Page {
|
||||
|
||||
private $api;
|
||||
private $message = null;
|
||||
private $wp_users_by_hal_id = null; // Cache: normalized_hal_id => ['id' => int, 'name' => string]
|
||||
|
||||
// Document type labels
|
||||
private const DOC_TYPE_LABELS = [
|
||||
'ART' => 'Article',
|
||||
'COUV' => "Chapitre d'ouvrage",
|
||||
'OUV' => 'Ouvrage',
|
||||
'COMM' => 'Communication',
|
||||
'ISSUE' => 'Direction de numéro',
|
||||
'PROCEEDINGS' => 'Colloque',
|
||||
'THESE' => 'Thèse',
|
||||
'HDR' => 'HDR',
|
||||
'SON' => 'Son',
|
||||
'VIDEO' => 'Vidéo',
|
||||
];
|
||||
|
||||
public function __construct() {
|
||||
$this->api = new Thalim_HAL_API();
|
||||
}
|
||||
|
||||
public function render() {
|
||||
if (!current_user_can('edit_others_posts')) {
|
||||
wp_die('Unauthorized');
|
||||
}
|
||||
$this->handle_actions();
|
||||
echo '<div class="wrap"><h1>THALIM HAL Importer</h1>';
|
||||
$this->render_styles();
|
||||
$this->render_message();
|
||||
$this->render_config();
|
||||
$this->render_preview();
|
||||
$this->render_csv_import();
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
private function handle_actions() {
|
||||
if (!isset($_POST['thalim_hal_action'])) return;
|
||||
if (!wp_verify_nonce($_POST['_wpnonce'] ?? '', 'thalim_hal_action')) {
|
||||
$this->message = ['error', 'Security check failed.'];
|
||||
return;
|
||||
}
|
||||
$action = sanitize_text_field($_POST['thalim_hal_action']);
|
||||
|
||||
if ($action === 'test_api') {
|
||||
$result = $this->api->test_connection();
|
||||
$this->message = is_wp_error($result)
|
||||
? ['error', 'API Error: ' . $result->get_error_message()]
|
||||
: ['success', "Connection OK! Found {$result['total']} publications."];
|
||||
}
|
||||
|
||||
if ($action === 'refresh') {
|
||||
// Clear all preview transients (they are keyed by date range hash)
|
||||
global $wpdb;
|
||||
$wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_thalim_hal_preview_%'");
|
||||
$wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_thalim_hal_preview_%'");
|
||||
$this->message = ['success', 'Preview data refreshed from HAL API.'];
|
||||
}
|
||||
|
||||
if ($action === 'import_pending') {
|
||||
$this->handle_import();
|
||||
}
|
||||
|
||||
if ($action === 'csv_upload') $this->handle_csv_upload();
|
||||
if ($action === 'csv_batch') $this->handle_csv_batch();
|
||||
if ($action === 'csv_cancel') $this->handle_csv_cancel();
|
||||
if ($action === 'csv_download_report') $this->handle_csv_download_report();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle bulk import of ready publications as pending posts.
|
||||
* Uses cached raw HAL docs to avoid a second outbound API call.
|
||||
*/
|
||||
private function handle_import() {
|
||||
$date_from = sanitize_text_field($_POST['hal_date_from'] ?? '');
|
||||
$date_to = sanitize_text_field($_POST['hal_date_to'] ?? '');
|
||||
$author_hal_id = sanitize_text_field($_POST['hal_author_id'] ?? '');
|
||||
|
||||
// Reuse the cached preview data — raw_docs are stored alongside processed docs
|
||||
$preview = $this->get_preview_data($date_from, $date_to, $author_hal_id);
|
||||
if (is_wp_error($preview)) {
|
||||
$this->message = ['error', 'API Error: ' . $preview->get_error_message()];
|
||||
return;
|
||||
}
|
||||
|
||||
$raw_docs = $preview['raw_docs'] ?? [];
|
||||
if (empty($raw_docs)) {
|
||||
$this->message = ['warning', 'Aucune publication dans le cache. Utilisez Filtrer pour charger les données d\'abord.'];
|
||||
return;
|
||||
}
|
||||
|
||||
$this->load_wp_users_hal_ids();
|
||||
$importer = new Thalim_HAL_Importer_Logic();
|
||||
$imported = 0;
|
||||
$skipped = 0;
|
||||
$errors = [];
|
||||
|
||||
foreach ($raw_docs as $doc) {
|
||||
$hal_id = $doc['halId_s'] ?? '';
|
||||
$author_hal_ids = $doc['authIdHal_s'] ?? [];
|
||||
$matched_users = $this->match_authors_to_users($author_hal_ids);
|
||||
|
||||
if (empty($matched_users) || $importer->is_imported($hal_id)) {
|
||||
$skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$post_id = $importer->import($doc, $this->wp_users_by_hal_id);
|
||||
if (is_wp_error($post_id)) {
|
||||
$errors[] = $hal_id . ': ' . $post_id->get_error_message();
|
||||
} else {
|
||||
$imported++;
|
||||
}
|
||||
}
|
||||
|
||||
$msg = sprintf('%d publication(s) importée(s) en statut "En attente".', $imported);
|
||||
if ($skipped) $msg .= sprintf(' %d ignorée(s) (déjà importées ou sans membre THALIM correspondant).', $skipped);
|
||||
if (!empty($errors)) $msg .= ' Erreurs : ' . implode('; ', $errors);
|
||||
|
||||
$this->message = [empty($errors) ? 'success' : 'warning', $msg];
|
||||
}
|
||||
|
||||
private function render_styles() {
|
||||
?>
|
||||
<style>
|
||||
.hal-status-imported { background-color: #d4edda !important; }
|
||||
.hal-status-ready { background-color: #fff3cd !important; }
|
||||
.hal-status-blocked { background-color: #f8d7da !important; }
|
||||
.hal-summary { display: flex; gap: 20px; padding: 15px; background: #f8f9fa; border-radius: 4px; margin-bottom: 20px; }
|
||||
.hal-summary-item { padding: 10px 15px; border-radius: 4px; text-align: center; }
|
||||
.hal-summary-item.total { background: #e3f2fd; border-left: 4px solid #2196f3; }
|
||||
.hal-summary-item.imported { background: #d4edda; border-left: 4px solid #28a745; }
|
||||
.hal-summary-item.ready { background: #fff3cd; border-left: 4px solid #ffc107; }
|
||||
.hal-summary-item.blocked { background: #f8d7da; border-left: 4px solid #dc3545; }
|
||||
.hal-summary-item strong { display: block; font-size: 24px; }
|
||||
.hal-type-badge { padding: 2px 8px; border-radius: 3px; font-size: 11px; font-weight: 500; }
|
||||
.hal-type-ART, .hal-type-ISSUE { background: #e3f2fd; color: #1565c0; }
|
||||
.hal-type-COUV, .hal-type-OUV { background: #f3e5f5; color: #7b1fa2; }
|
||||
.hal-type-PROCEEDINGS { background: #e8f5e9; color: #2e7d32; }
|
||||
.hal-type-THESE, .hal-type-HDR { background: #fff3e0; color: #e65100; }
|
||||
.hal-type-SON, .hal-type-VIDEO { background: #fce4ec; color: #c62828; }
|
||||
.hal-users { font-size: 11px; color: #666; }
|
||||
.hal-users-matched { color: #28a745; font-weight: 500; }
|
||||
.hal-users-none { color: #dc3545; font-style: italic; }
|
||||
.hal-preview-table th { white-space: nowrap; }
|
||||
.hal-preview-table td { vertical-align: top; }
|
||||
</style>
|
||||
<?php
|
||||
}
|
||||
|
||||
private function render_message() {
|
||||
if (!$this->message) return;
|
||||
printf('<div class="notice notice-%s is-dismissible"><p>%s</p></div>',
|
||||
esc_attr($this->message[0]), esc_html($this->message[1]));
|
||||
}
|
||||
|
||||
private function render_config() {
|
||||
?>
|
||||
<div class="card" style="max-width:800px;margin-bottom:20px">
|
||||
<h2>Configuration</h2>
|
||||
<table class="form-table">
|
||||
<tr><th>Structure ID</th><td><code><?php echo THALIM_HAL_STRUCT_ID; ?></code> (THALIM)</td></tr>
|
||||
<tr><th>Document Types</th><td><?php echo implode(', ', THALIM_HAL_DOC_TYPES); ?></td></tr>
|
||||
<tr><th>API Endpoint</th><td><code style="font-size:11px;word-break:break-all;"><?php echo esc_html($this->api->get_api_url(10)); ?></code></td></tr>
|
||||
</table>
|
||||
<form method="post" style="margin-top:15px">
|
||||
<?php wp_nonce_field('thalim_hal_action'); ?>
|
||||
<input type="hidden" name="thalim_hal_action" value="test_api">
|
||||
<button class="button button-primary">Test API Connection</button>
|
||||
</form>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
private function render_preview() {
|
||||
// Read filters from POST (after submit) or GET (page reload with state)
|
||||
$date_from = sanitize_text_field($_POST['hal_date_from'] ?? $_GET['hal_date_from'] ?? '');
|
||||
$date_to = sanitize_text_field($_POST['hal_date_to'] ?? $_GET['hal_date_to'] ?? '');
|
||||
$author_hal_id = sanitize_text_field($_POST['hal_author_id'] ?? $_GET['hal_author_id'] ?? '');
|
||||
|
||||
// Users must be loaded before rendering the dropdown
|
||||
$this->load_wp_users_hal_ids();
|
||||
|
||||
$preview = $this->get_preview_data($date_from, $date_to, $author_hal_id);
|
||||
$ready_count = is_wp_error($preview) ? 0 : $preview['stats']['ready'];
|
||||
?>
|
||||
<div class="card" style="max-width:100%;margin-bottom:20px">
|
||||
<h2>Import Preview</h2>
|
||||
|
||||
<form method="post" style="margin-bottom:20px;display:flex;align-items:center;gap:15px;flex-wrap:wrap">
|
||||
<?php wp_nonce_field('thalim_hal_action'); ?>
|
||||
|
||||
<label style="font-weight:600">Depuis
|
||||
<input type="date" name="hal_date_from" value="<?php echo esc_attr($date_from); ?>" style="width:auto">
|
||||
</label>
|
||||
|
||||
<label style="font-weight:600">Jusqu'au
|
||||
<input type="date" name="hal_date_to" value="<?php echo esc_attr($date_to); ?>" style="width:auto">
|
||||
</label>
|
||||
|
||||
<label style="font-weight:600">Auteur
|
||||
<select name="hal_author_id" style="max-width:220px">
|
||||
<option value="">— Tous —</option>
|
||||
<?php foreach ($this->wp_users_by_hal_id as $user): ?>
|
||||
<option value="<?php echo esc_attr($user['hal_id']); ?>"
|
||||
<?php selected($author_hal_id, $user['hal_id']); ?>>
|
||||
<?php echo esc_html($user['name']); ?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<button class="button button-secondary" name="thalim_hal_action" value="filter">Filtrer</button>
|
||||
<button class="button button-secondary" name="thalim_hal_action" value="refresh" style="margin-left:5px">Rafraîchir</button>
|
||||
<small style="color:#666">Mis en cache 5 min</small>
|
||||
|
||||
<span style="flex:1"></span>
|
||||
|
||||
<button class="button button-primary" name="thalim_hal_action" value="import_pending"
|
||||
<?php if ($ready_count === 0): ?>disabled title="Aucune publication prête à importer"<?php endif; ?>>
|
||||
Importer <?php echo $ready_count; ?> publication(s) (En attente)
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<?php if (is_wp_error($preview)): ?>
|
||||
<div class="notice notice-error"><p><?php echo esc_html($preview->get_error_message()); ?></p></div>
|
||||
<?php else: ?>
|
||||
<?php $this->render_wp_users_debug(); ?>
|
||||
<?php $this->render_summary($preview['stats']); ?>
|
||||
<?php $this->render_preview_table($preview['docs']); ?>
|
||||
<?php $this->render_legend(); ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
private function render_summary($stats) {
|
||||
?>
|
||||
<div class="hal-summary">
|
||||
<div class="hal-summary-item total">
|
||||
<strong><?php echo number_format($stats['total']); ?></strong>
|
||||
<span>Total in HAL</span>
|
||||
</div>
|
||||
<div class="hal-summary-item imported">
|
||||
<strong><?php echo $stats['imported']; ?></strong>
|
||||
<span>Already Imported</span>
|
||||
</div>
|
||||
<div class="hal-summary-item ready">
|
||||
<strong><?php echo $stats['ready']; ?></strong>
|
||||
<span>Ready to Import</span>
|
||||
</div>
|
||||
<div class="hal-summary-item blocked">
|
||||
<strong><?php echo $stats['blocked']; ?></strong>
|
||||
<span>No Matched User</span>
|
||||
</div>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
private function render_preview_table($docs) {
|
||||
if (empty($docs)) {
|
||||
echo '<p>No publications found.</p>';
|
||||
return;
|
||||
}
|
||||
?>
|
||||
<table class="widefat hal-preview-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Statut</th>
|
||||
<th>HAL ID</th>
|
||||
<th>Titre</th>
|
||||
<th>Type</th>
|
||||
<th>Auteurs</th>
|
||||
<th>IDs HAL auteurs</th>
|
||||
<th>Date</th>
|
||||
<th>Membres THALIM</th>
|
||||
<th>Lien HAL</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($docs as $doc): ?>
|
||||
<tr class="<?php echo esc_attr($this->get_row_class($doc)); ?>">
|
||||
<td><?php echo $this->get_status_icon($doc); ?></td>
|
||||
<td><code style="font-size:11px"><?php echo esc_html($doc['hal_id']); ?></code></td>
|
||||
<td>
|
||||
<strong><?php echo esc_html($doc['title']); ?></strong>
|
||||
<?php if ($doc['journal']): ?>
|
||||
<br><small style="color:#666"><?php echo esc_html($doc['journal']); ?></small>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td>
|
||||
<span class="hal-type-badge hal-type-<?php echo esc_attr($doc['type']); ?>">
|
||||
<?php echo esc_html(self::DOC_TYPE_LABELS[$doc['type']] ?? $doc['type']); ?>
|
||||
</span>
|
||||
</td>
|
||||
<td class="hal-users">
|
||||
<?php echo esc_html(implode(', ', $doc['authors'])); ?>
|
||||
</td>
|
||||
<td class="hal-users">
|
||||
<?php if (!empty($doc['author_hal_ids'])): ?>
|
||||
<?php foreach ($doc['author_hal_ids'] as $aid):
|
||||
$normalized = strtolower(trim($aid));
|
||||
$is_match = isset($this->wp_users_by_hal_id[$normalized]);
|
||||
?>
|
||||
<code style="font-size:10px;<?php echo $is_match ? 'background:#d4edda;' : ''; ?>"><?php echo esc_html($aid); ?></code>
|
||||
<?php endforeach; ?>
|
||||
<?php else: ?>
|
||||
<span style="color:#999;font-style:italic">aucun</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td><?php echo esc_html($doc['publication_date'] ?: ($doc['produced_date'] ?: '-')); ?></td>
|
||||
<td>
|
||||
<?php if (!empty($doc['matched_users'])): ?>
|
||||
<span class="hal-users-matched">
|
||||
<?php echo esc_html(implode(', ', $doc['matched_users'])); ?>
|
||||
</span>
|
||||
<?php else: ?>
|
||||
<span class="hal-users-none">Aucun</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td>
|
||||
<a href="<?php echo esc_url($doc['url']); ?>" target="_blank" class="button button-small">Voir sur HAL</a>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
<?php
|
||||
}
|
||||
|
||||
private function render_legend() {
|
||||
?>
|
||||
<div style="margin-top:15px;padding:10px;background:#f8f9fa;border-radius:4px;font-size:12px">
|
||||
<strong>Légende :</strong>
|
||||
<span style="margin-left:15px;"><span style="background:#d4edda;padding:2px 8px;border-radius:3px;">✓ Importé</span></span>
|
||||
<span style="margin-left:15px;"><span style="background:#fff3cd;padding:2px 8px;border-radius:3px;">★ Prêt</span> Membre THALIM identifié</span>
|
||||
<span style="margin-left:15px;"><span style="background:#f8d7da;padding:2px 8px;border-radius:3px;">✗ Bloqué</span> Aucun membre THALIM ne correspond aux IDs auteurs HAL</span>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
private function render_wp_users_debug() {
|
||||
$this->load_wp_users_hal_ids();
|
||||
if (empty($this->wp_users_by_hal_id)) {
|
||||
echo '<div class="notice notice-warning"><p>Aucun utilisateur WordPress n\'a le champ <code>identifiant_hal</code> renseigné.</p></div>';
|
||||
return;
|
||||
}
|
||||
?>
|
||||
<details style="margin-bottom:15px;background:#f0f6fc;padding:10px;border-radius:4px;border-left:4px solid #0073aa">
|
||||
<summary style="cursor:pointer;font-weight:bold">
|
||||
Utilisateurs WordPress avec identifiant HAL (<?php echo count($this->wp_users_by_hal_id); ?> utilisateurs) — Cliquer pour déplier
|
||||
</summary>
|
||||
<table class="widefat" style="margin-top:10px;font-size:12px">
|
||||
<thead><tr><th>Utilisateur</th><th>Identifiant HAL</th><th>Debug (brut)</th><th>Modifier</th></tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($this->wp_users_by_hal_id as $hal_id => $user): ?>
|
||||
<tr>
|
||||
<td><?php echo esc_html($user['name']); ?> <small style="color:#999">(ID : <?php echo esc_html($user['id']); ?>)</small></td>
|
||||
<td><code><?php echo esc_html($hal_id); ?></code></td>
|
||||
<td><code style="background:#ffe;font-size:10px">"<?php echo esc_html($hal_id); ?>" (<?php echo strlen($hal_id); ?> car.)</code></td>
|
||||
<td><a href="<?php echo esc_url(get_edit_user_link($user['id'])); ?>" target="_blank" class="button button-small">Modifier</a></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</details>
|
||||
<?php
|
||||
}
|
||||
|
||||
private function get_preview_data($date_from = '', $date_to = '', $author_hal_id = '') {
|
||||
$cache_key = 'thalim_hal_preview_' . md5($date_from . '|' . $date_to . '|' . $author_hal_id);
|
||||
$cached = get_transient($cache_key);
|
||||
if ($cached !== false) return $cached;
|
||||
|
||||
$rows = ($date_from || $date_to || $author_hal_id) ? 200 : 50;
|
||||
$result = $this->api->fetch_publications($rows, 0, 'producedDate_tdate desc', $date_from, $date_to, $author_hal_id);
|
||||
if (is_wp_error($result)) return $result;
|
||||
|
||||
$importer = new Thalim_HAL_Importer_Logic();
|
||||
$this->load_wp_users_hal_ids();
|
||||
|
||||
$preview = [
|
||||
'stats' => [
|
||||
'total' => $result['response']['numFound'] ?? 0,
|
||||
'imported' => 0,
|
||||
'ready' => 0,
|
||||
'blocked' => 0
|
||||
],
|
||||
'docs' => [],
|
||||
'raw_docs' => [], // Raw HAL docs kept for import, avoids a second API call
|
||||
];
|
||||
|
||||
foreach ($result['response']['docs'] ?? [] as $doc) {
|
||||
$hal_id = $doc['halId_s'] ?? '';
|
||||
$is_imported = $importer->is_imported($hal_id);
|
||||
$author_hal_ids = $doc['authIdHal_s'] ?? [];
|
||||
$matched_users = $this->match_authors_to_users($author_hal_ids);
|
||||
$has_match = !empty($matched_users);
|
||||
|
||||
// Update stats
|
||||
if ($is_imported) {
|
||||
$preview['stats']['imported']++;
|
||||
} elseif ($has_match) {
|
||||
$preview['stats']['ready']++;
|
||||
} else {
|
||||
$preview['stats']['blocked']++;
|
||||
}
|
||||
|
||||
$preview['docs'][] = [
|
||||
'hal_id' => $hal_id,
|
||||
'title' => $doc['title_s'][0] ?? 'N/A',
|
||||
'type' => $doc['docType_s'] ?? '',
|
||||
'authors' => $doc['authFullName_s'] ?? [],
|
||||
'author_hal_ids' => $author_hal_ids,
|
||||
'publication_date' => $doc['publicationDate_s'] ?? '',
|
||||
'produced_date' => $doc['submittedDate_s'] ?? '',
|
||||
'journal' => $doc['journalTitle_s'] ?? $doc['bookTitle_s'] ?? '',
|
||||
'url' => $doc['uri_s'] ?? '',
|
||||
'is_imported' => $is_imported,
|
||||
'matched_users' => $matched_users,
|
||||
'has_match' => $has_match,
|
||||
];
|
||||
$preview['raw_docs'][] = $doc; // Full HAL doc kept for import
|
||||
}
|
||||
|
||||
set_transient($cache_key, $preview, 300);
|
||||
return $preview;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all WordPress users with HAL IDs into cache.
|
||||
* Stores: normalized_hal_id => ['id' => int, 'name' => string]
|
||||
*/
|
||||
private function load_wp_users_hal_ids() {
|
||||
if ($this->wp_users_by_hal_id !== null) return;
|
||||
|
||||
$this->wp_users_by_hal_id = [];
|
||||
$users = get_users([
|
||||
'meta_key' => 'identifiant_hal',
|
||||
'meta_compare' => 'EXISTS'
|
||||
]);
|
||||
|
||||
foreach ($users as $user) {
|
||||
$hal_id = get_user_meta($user->ID, 'identifiant_hal', true);
|
||||
if (!empty($hal_id)) {
|
||||
$normalized = strtolower(trim($hal_id));
|
||||
$this->wp_users_by_hal_id[$normalized] = [
|
||||
'id' => $user->ID,
|
||||
'name' => $user->display_name,
|
||||
'hal_id' => trim($hal_id), // original value for API filter
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Match HAL author IDs to WordPress users.
|
||||
* Returns array of display names (for preview display).
|
||||
*/
|
||||
private function match_authors_to_users($author_hal_ids) {
|
||||
$matched = [];
|
||||
foreach ($author_hal_ids as $hal_id) {
|
||||
$normalized = strtolower(trim($hal_id));
|
||||
if (isset($this->wp_users_by_hal_id[$normalized])) {
|
||||
$matched[] = $this->wp_users_by_hal_id[$normalized]['name'];
|
||||
}
|
||||
}
|
||||
return $matched;
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// CSV bulk import (phase 2 — legacy publications from SPIP)
|
||||
// ========================================================================
|
||||
|
||||
private const CSV_QUEUE_OPTION = 'thalim_hal_csv_queue';
|
||||
private const CSV_BATCH_SIZE = 100;
|
||||
|
||||
private function render_csv_import() {
|
||||
$queue = get_option(self::CSV_QUEUE_OPTION, null);
|
||||
?>
|
||||
<div class="card" style="max-width:100%;margin-bottom:20px">
|
||||
<h2>Import en masse depuis CSV</h2>
|
||||
<p>
|
||||
Uploader le couple <code>hal-to-import.csv</code> + <code>hal-to-import-context.json</code>
|
||||
(généré par <code>php scripts/prepare-csv-context.php</code>) pour importer les publications legacy.
|
||||
Chaque batch traite <?php echo self::CSV_BATCH_SIZE; ?> publications — cliquer plusieurs fois jusqu'à terminaison.
|
||||
</p>
|
||||
|
||||
<?php if (!$queue): ?>
|
||||
<form method="post" enctype="multipart/form-data">
|
||||
<?php wp_nonce_field('thalim_hal_action'); ?>
|
||||
<input type="hidden" name="thalim_hal_action" value="csv_upload">
|
||||
<table class="form-table">
|
||||
<tr>
|
||||
<th>Fichier CSV</th>
|
||||
<td><input type="file" name="csv_file" accept=".csv" required></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Fichier contexte (JSON)</th>
|
||||
<td><input type="file" name="ctx_file" accept=".json" required>
|
||||
<p class="description">Généré par <code>scripts/prepare-csv-context.php</code>.</p></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Statut des posts</th>
|
||||
<td>
|
||||
<label><input type="radio" name="post_status" value="publish" checked> Publié directement</label>
|
||||
<label style="margin-left:15px"><input type="radio" name="post_status" value="pending"> En attente (pour relecture)</label>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Date du post WP</th>
|
||||
<td>
|
||||
<label><input type="checkbox" name="backdate_post" value="1" checked>
|
||||
Utiliser la date HAL (<code>producedDate_s</code>) comme <code>post_date</code></label>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p><button class="button button-primary">Charger le CSV et préparer l'import</button></p>
|
||||
</form>
|
||||
<?php else: ?>
|
||||
<?php $this->render_csv_progress($queue); ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
private function render_csv_progress(array $queue): void {
|
||||
$total = (int) ($queue['total'] ?? 0);
|
||||
$done = (int) ($queue['done'] ?? 0);
|
||||
$remaining = max(0, $total - $done);
|
||||
$pct = $total > 0 ? round(100 * $done / $total, 1) : 0;
|
||||
$report_ct = count($queue['report'] ?? []);
|
||||
?>
|
||||
<div style="padding:15px;background:#f0f6fc;border-left:4px solid #0073aa">
|
||||
<p><strong>File d'attente active</strong> — statut cible : <code><?php echo esc_html($queue['status']); ?></code>
|
||||
— backdate : <?php echo !empty($queue['backdate']) ? 'oui' : 'non'; ?></p>
|
||||
<p>
|
||||
<strong><?php echo number_format($done); ?></strong> / <?php echo number_format($total); ?>
|
||||
publications traitées (<?php echo esc_html($pct); ?>%)
|
||||
— <?php echo number_format($remaining); ?> restantes
|
||||
</p>
|
||||
<?php if (!empty($queue['updated_at'])): ?>
|
||||
<p><small>Dernière mise à jour : <?php echo esc_html($queue['updated_at']); ?></small></p>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if (!empty($queue['last_error'])): ?>
|
||||
<div class="notice notice-error" style="margin:10px 0"><p>
|
||||
Erreur dernier batch : <?php echo esc_html($queue['last_error']); ?>
|
||||
</p></div>
|
||||
<?php endif; ?>
|
||||
|
||||
<form method="post" style="display:inline-block;margin-right:10px">
|
||||
<?php wp_nonce_field('thalim_hal_action'); ?>
|
||||
<input type="hidden" name="thalim_hal_action" value="csv_batch">
|
||||
<button class="button button-primary" <?php if ($remaining === 0) echo 'disabled'; ?>>
|
||||
Traiter le prochain batch (<?php echo min(self::CSV_BATCH_SIZE, $remaining); ?>)
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<?php if ($report_ct > 0): ?>
|
||||
<form method="post" style="display:inline-block;margin-right:10px">
|
||||
<?php wp_nonce_field('thalim_hal_action'); ?>
|
||||
<input type="hidden" name="thalim_hal_action" value="csv_download_report">
|
||||
<button class="button">Télécharger le rapport CSV (<?php echo $report_ct; ?> lignes)</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
|
||||
<form method="post" style="display:inline-block" onsubmit="return confirm('Vraiment annuler l\'import en cours ?');">
|
||||
<?php wp_nonce_field('thalim_hal_action'); ?>
|
||||
<input type="hidden" name="thalim_hal_action" value="csv_cancel">
|
||||
<button class="button button-link-delete">Annuler et réinitialiser</button>
|
||||
</form>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
private function handle_csv_upload(): void {
|
||||
if (empty($_FILES['csv_file']['tmp_name']) || empty($_FILES['ctx_file']['tmp_name'])) {
|
||||
$this->message = ['error', 'CSV ou fichier contexte manquant.'];
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse CSV -> list of hal_ids
|
||||
$fh = fopen($_FILES['csv_file']['tmp_name'], 'r');
|
||||
if (!$fh) { $this->message = ['error', 'Impossible de lire le CSV.']; return; }
|
||||
$header = fgetcsv($fh);
|
||||
$hal_col = array_search('hal_id', $header);
|
||||
$spip_col = array_search('spip_id', $header);
|
||||
if ($hal_col === false) {
|
||||
fclose($fh);
|
||||
$this->message = ['error', 'Header CSV : colonne hal_id manquante.'];
|
||||
return;
|
||||
}
|
||||
$hal_ids = [];
|
||||
$spip_map = []; // hal_id => spip_id
|
||||
while (($row = fgetcsv($fh)) !== false) {
|
||||
$hid = trim($row[$hal_col] ?? '');
|
||||
if ($hid === '') continue;
|
||||
$hal_ids[] = $hid;
|
||||
if ($spip_col !== false) $spip_map[$hid] = trim($row[$spip_col] ?? '');
|
||||
}
|
||||
fclose($fh);
|
||||
$hal_ids = array_values(array_unique($hal_ids));
|
||||
|
||||
// Parse JSON context
|
||||
$ctx_raw = file_get_contents($_FILES['ctx_file']['tmp_name']);
|
||||
$ctx_data = json_decode($ctx_raw, true);
|
||||
if (!is_array($ctx_data) || !isset($ctx_data['ctx'])) {
|
||||
$this->message = ['error', 'Fichier contexte JSON invalide.'];
|
||||
return;
|
||||
}
|
||||
|
||||
$status = ($_POST['post_status'] ?? 'publish') === 'pending' ? 'pending' : 'publish';
|
||||
$backdate = !empty($_POST['backdate_post']);
|
||||
|
||||
$queue = [
|
||||
'hal_ids' => $hal_ids,
|
||||
'spip_map' => $spip_map,
|
||||
'status' => $status,
|
||||
'backdate' => $backdate,
|
||||
'total' => count($hal_ids),
|
||||
'done' => 0,
|
||||
'spip_ctx' => $ctx_data['ctx'],
|
||||
'wp_users_by_hal_id' => $ctx_data['wp_users_by_hal_id'] ?? [],
|
||||
'report' => [],
|
||||
'last_error' => '',
|
||||
'updated_at' => current_time('mysql'),
|
||||
];
|
||||
update_option(self::CSV_QUEUE_OPTION, $queue, false);
|
||||
$this->message = ['success', sprintf(
|
||||
'CSV chargé : %d publications prêtes. Statut cible : %s. Cliquer "Traiter le prochain batch" pour lancer.',
|
||||
count($hal_ids), $status
|
||||
)];
|
||||
}
|
||||
|
||||
private function handle_csv_batch(): void {
|
||||
$queue = get_option(self::CSV_QUEUE_OPTION, null);
|
||||
if (!$queue) { $this->message = ['error', 'Aucune queue active.']; return; }
|
||||
|
||||
$batch = array_slice($queue['hal_ids'], $queue['done'], self::CSV_BATCH_SIZE);
|
||||
if (empty($batch)) {
|
||||
$this->message = ['success', 'Import terminé — tous les batches ont été traités.'];
|
||||
return;
|
||||
}
|
||||
|
||||
$docs = $this->api->fetch_by_hal_ids($batch, self::CSV_BATCH_SIZE);
|
||||
if (is_wp_error($docs)) {
|
||||
$queue['last_error'] = $docs->get_error_message();
|
||||
$queue['updated_at'] = current_time('mysql');
|
||||
update_option(self::CSV_QUEUE_OPTION, $queue, false);
|
||||
$this->message = ['error', 'Erreur HAL API : ' . $docs->get_error_message()];
|
||||
return;
|
||||
}
|
||||
|
||||
// Normalize wp_users_by_hal_id keys to lowercase for the importer
|
||||
$users_map = [];
|
||||
foreach ($queue['wp_users_by_hal_id'] as $hid => $u) {
|
||||
$users_map[strtolower(trim((string) $hid))] = $u;
|
||||
}
|
||||
|
||||
$importer = new Thalim_HAL_Importer_Logic();
|
||||
$batch_imported = 0;
|
||||
$batch_skipped = 0;
|
||||
$batch_errors = 0;
|
||||
|
||||
foreach ($batch as $hal_id) {
|
||||
$spip_id = $queue['spip_map'][$hal_id] ?? '';
|
||||
$doc = $docs[$hal_id] ?? null;
|
||||
$ctx = $queue['spip_ctx'][$hal_id] ?? [];
|
||||
|
||||
if (!$doc) {
|
||||
$queue['report'][] = [$hal_id, $spip_id, '', 'not_found_in_hal', 'false', 'none', 'HAL API did not return this hal_id'];
|
||||
$batch_errors++;
|
||||
continue;
|
||||
}
|
||||
|
||||
$post_id = $importer->import($doc, $users_map, $queue['status'], (bool) $queue['backdate'], $ctx);
|
||||
if (is_wp_error($post_id)) {
|
||||
$code = $post_id->get_error_code();
|
||||
$queue['report'][] = [$hal_id, $spip_id, '', $code, 'false', 'none', $post_id->get_error_message()];
|
||||
if ($code === 'exists') $batch_skipped++;
|
||||
else $batch_errors++;
|
||||
} else {
|
||||
$source = $importer->last_axes_source;
|
||||
$has_axe = $source !== 'none' ? 'true' : 'false';
|
||||
$queue['report'][] = [$hal_id, $spip_id, (string) $post_id, 'imported', $has_axe, $source, ''];
|
||||
$batch_imported++;
|
||||
}
|
||||
}
|
||||
|
||||
$queue['done'] += count($batch);
|
||||
$queue['last_error'] = '';
|
||||
$queue['updated_at'] = current_time('mysql');
|
||||
update_option(self::CSV_QUEUE_OPTION, $queue, false);
|
||||
|
||||
$this->message = ['success', sprintf(
|
||||
'Batch traité : %d importé(s), %d déjà importé(s), %d erreur(s). Progression : %d / %d.',
|
||||
$batch_imported, $batch_skipped, $batch_errors,
|
||||
$queue['done'], $queue['total']
|
||||
)];
|
||||
}
|
||||
|
||||
private function handle_csv_cancel(): void {
|
||||
delete_option(self::CSV_QUEUE_OPTION);
|
||||
$this->message = ['success', 'Queue CSV annulée.'];
|
||||
}
|
||||
|
||||
private function handle_csv_download_report(): void {
|
||||
$queue = get_option(self::CSV_QUEUE_OPTION, null);
|
||||
if (!$queue || empty($queue['report'])) {
|
||||
$this->message = ['warning', 'Aucun rapport à télécharger.'];
|
||||
return;
|
||||
}
|
||||
$filename = 'hal-import-report-' . date('Ymd-His') . '.csv';
|
||||
header('Content-Type: text/csv; charset=utf-8');
|
||||
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
||||
$out = fopen('php://output', 'w');
|
||||
fputcsv($out, ['hal_id', 'spip_id', 'post_id', 'status', 'has_axe', 'axes_source', 'error']);
|
||||
foreach ($queue['report'] as $row) fputcsv($out, $row);
|
||||
fclose($out);
|
||||
exit;
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// End CSV bulk import
|
||||
// ========================================================================
|
||||
|
||||
private function get_row_class($doc) {
|
||||
if ($doc['is_imported']) return 'hal-status-imported';
|
||||
if ($doc['has_match']) return 'hal-status-ready';
|
||||
return 'hal-status-blocked';
|
||||
}
|
||||
|
||||
private function get_status_icon($doc) {
|
||||
if ($doc['is_imported']) return '<span title="Already imported" style="color:#28a745;font-size:18px">✓</span>';
|
||||
if ($doc['has_match']) return '<span title="Ready to import" style="color:#ffc107;font-size:18px">★</span>';
|
||||
return '<span title="No matched user" style="color:#dc3545;font-size:18px">✗</span>';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user