Repository navigation
Expand file tree
/
Copy pathModule.php
More file actions
453 lines (405 loc) · 17 KB
/
Copy pathModule.php
File metadata and controls
453 lines (405 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
<?php
declare(strict_types=1);
/**
* IwacSeo — Omeka S module.
*
* Search-engine optimisation for the Islam West Africa Collection (IWAC,
* islam.zmo.de):
*
* • Injects per-page <title>, meta description, Open Graph + Twitter cards,
* canonical links and schema.org JSON-LD into the <head> — derived
* automatically from each resource's metadata + resource class, set by
* hand for static site pages, with site-wide defaults filling the gaps.
* • Serves /sitemap.xml (index + per-type children) and /robots.txt.
* • Injects the Google Search Console verification tag from a pasted snippet.
* • Optionally pings IndexNow when public content changes.
*
* Settings-only: it owns a handful of `iwac_seo_*` settings and one site setting
* (iwac_seo_pages); install/uninstall just create and drop those. No third-party
* Composer dependencies, so there is no bundled vendor/ — Omeka autoloads the
* IwacSeo\ namespace from src/.
*/
namespace IwacSeo;
use IwacSeo\Service\HeadMetadata;
use IwacSeo\Service\PageSeoStore;
use IwacSeo\Service\PingQueue;
use IwacSeo\Service\ResourceUrl;
use IwacSeo\Service\SettingsGate;
use IwacSeo\Service\SitemapGenerator;
use IwacSeo\Service\SiteResolver;
use Laminas\EventManager\EventInterface;
use Laminas\EventManager\SharedEventManagerInterface;
use Laminas\Mvc\Controller\AbstractController;
use Laminas\Mvc\MvcEvent;
use Laminas\ServiceManager\ServiceLocatorInterface;
use Laminas\View\Renderer\PhpRenderer;
use Omeka\Api\Representation\AbstractResourceEntityRepresentation;
use Omeka\Api\Representation\SitePageRepresentation;
use Omeka\Api\Representation\SiteRepresentation;
use Omeka\Module\AbstractModule;
use Omeka\Permissions\Acl;
class Module extends AbstractModule
{
/** Global settings owned by the module (created on install, dropped on uninstall). */
private const SETTINGS = [
'iwac_seo_gsc_verification',
'iwac_seo_bing_verification',
'iwac_seo_default_description',
'iwac_seo_default_share_image',
'iwac_seo_twitter_site',
'iwac_seo_noindex_site',
'iwac_seo_noindex_browse',
'iwac_seo_jsonld_enabled',
'iwac_seo_citation_meta',
'iwac_seo_unapi',
'iwac_seo_sitemap_enabled',
'iwac_seo_sitemap_ttl',
'iwac_seo_ping_enabled',
'iwac_seo_indexnow_key',
'iwac_seo_ping_pending',
'iwac_seo_ping_last',
];
/** Internal bookkeeping settings — never surfaced in the config form. */
private const INTERNAL_SETTINGS = [
'iwac_seo_ping_pending',
'iwac_seo_ping_last',
];
/** Sensible defaults applied on install. */
private const DEFAULTS = [
'iwac_seo_sitemap_enabled' => '1',
'iwac_seo_jsonld_enabled' => '1',
'iwac_seo_citation_meta' => '1',
'iwac_seo_unapi' => '1',
'iwac_seo_noindex_browse' => '1',
'iwac_seo_sitemap_ttl' => '86400',
];
public function getConfig(): array
{
return include __DIR__ . '/config/module.config.php';
}
public function install(ServiceLocatorInterface $services): void
{
$this->loadLifecycleDependencies();
$this->applyDefaults($services->get('Omeka\Settings'));
(new Service\PingRepository($services->get('Omeka\Connection')))->install();
}
/**
* Re-apply any default that is still unset.
*
* Omeka calls this on a version bump. Without it a default introduced after
* a site's first install (iwac_seo_sitemap_ttl and iwac_seo_noindex_browse
* both arrived after 0.1) would never reach that site: install() runs once,
* and nothing else writes a default. Idempotent, and it never overwrites a
* value an administrator has set.
*/
public function upgrade(
$oldVersion,
$newVersion,
ServiceLocatorInterface $services
): void {
$this->loadLifecycleDependencies();
$this->applyDefaults($services->get('Omeka\Settings'));
$repository = new Service\PingRepository($services->get('Omeka\Connection'));
$repository->install();
$settings = $services->get('Omeka\Settings');
foreach ((array) $settings->get('iwac_seo_ping_pending', []) as $url) {
$repository->push((string) $url);
}
$settings->delete('iwac_seo_ping_pending');
}
private function loadLifecycleDependencies(): void
{
// Omeka invokes install/upgrade while this module is inactive: its src/
// namespace and services have not been registered for the request yet.
require_once __DIR__ . '/src/Service/MetadataValue.php';
require_once __DIR__ . '/src/Service/PingOutboxInterface.php';
require_once __DIR__ . '/src/Service/PingRepository.php';
}
public function uninstall(ServiceLocatorInterface $services): void
{
$services->get('Omeka\Connection')->executeStatement('DROP TABLE IF EXISTS iwac_seo_ping');
$settings = $services->get('Omeka\Settings');
foreach (self::SETTINGS as $key) {
$settings->delete($key);
}
// Remove the cached sitemap files (files/iwac-seo-cache).
try {
$services->get(SitemapGenerator::class)->destroyCache();
} catch (\Throwable $e) {
// best-effort
}
// Drop the per-site static-page overrides too.
try {
$siteSettings = $services->get('Omeka\Settings\Site');
$sites = $services->get('Omeka\ApiManager')->search('sites')->getContent();
foreach ($sites as $site) {
$siteSettings->setTargetId($site->id());
$siteSettings->delete('iwac_seo_pages');
}
} catch (\Throwable $e) {
// best-effort
}
}
/**
* ACL: open the public sitemap/robots/IndexNow endpoints to everyone
* (including anonymous visitors); restrict the admin SEO screens to editors
* and above (the /admin route already enforces authentication).
*/
public function onBootstrap(MvcEvent $event): void
{
parent::onBootstrap($event);
/** @var Acl $acl */
$acl = $event->getApplication()->getServiceManager()->get('Omeka\Acl');
$acl->allow(null, [
Controller\SitemapController::class,
Controller\UnapiController::class,
Controller\CitationController::class,
]);
$acl->allow(
[Acl::ROLE_EDITOR, Acl::ROLE_SITE_ADMIN, Acl::ROLE_GLOBAL_ADMIN],
[Controller\Admin\SeoController::class]
);
}
public function attachListeners(SharedEventManagerInterface $sharedEventManager): void
{
// Resource show pages — derive meta + JSON-LD from the resource.
$resourceControllers = [
'Omeka\Controller\Site\Item',
'Omeka\Controller\Site\ItemSet',
'Omeka\Controller\Site\Media',
];
foreach ($resourceControllers as $controller) {
$sharedEventManager->attach($controller, 'view.show.after', [$this, 'handleResourceShow']);
$sharedEventManager->attach($controller, 'view.browse.after', [$this, 'handleBrowse']);
}
// Static site pages — apply the editor's per-page overrides. The home
// page is rendered by the Index controller, so listen there too (the
// handler no-ops when no $page is in scope).
$sharedEventManager->attach('Omeka\Controller\Site\Page', 'view.show.after', [$this, 'handlePageShow']);
$sharedEventManager->attach('Omeka\Controller\Site\Index', 'view.show.after', [$this, 'handlePageShow']);
// Every public page — site-wide constants + verification + gap-fill.
$sharedEventManager->attach('*', 'view.layout', [$this, 'handleLayout']);
// Sitemap invalidation + auto-ping on content changes. Deletes are
// included: the URL leaves the sitemap, and IndexNow is also the
// fastest way to tell engines a URL vanished (they recrawl → 404).
// Item sets have their own child sitemap, so their edits count too.
$contentAdapters = [
'Omeka\Api\Adapter\ItemAdapter',
'Omeka\Api\Adapter\ItemSetAdapter',
'Omeka\Api\Adapter\SitePageAdapter',
];
foreach ($contentAdapters as $adapter) {
$sharedEventManager->attach($adapter, 'api.create.post', [$this, 'handleContentChange']);
$sharedEventManager->attach($adapter, 'api.update.post', [$this, 'handleContentChange']);
$sharedEventManager->attach($adapter, 'api.delete.post', [$this, 'handleContentChange']);
}
// Changes that alter a sitemap without being a sitemap URL of their
// own: a media's visibility (the items' image entries), a site's
// navigation or homepage (page order and priority). They clear the
// cache and queue no IndexNow ping.
foreach (['Omeka\Api\Adapter\MediaAdapter', 'Omeka\Api\Adapter\SiteAdapter'] as $adapter) {
$sharedEventManager->attach($adapter, 'api.create.post', [$this, 'handleSitemapChange']);
$sharedEventManager->attach($adapter, 'api.update.post', [$this, 'handleSitemapChange']);
$sharedEventManager->attach($adapter, 'api.delete.post', [$this, 'handleSitemapChange']);
}
}
// ─── View listeners ─────────────────────────────────────────────────────
public function handleResourceShow(EventInterface $event): void
{
$view = $this->view($event);
if (!$view) {
return;
}
$site = $this->currentSite($view);
$resource = $view->item ?? $view->itemSet ?? $view->media ?? null;
if (!$site || !$resource instanceof AbstractResourceEntityRepresentation) {
return;
}
// applyResource sets the <head> signals and returns optional body markup
// (the unAPI <abbr class="unapi-id"> element). Omeka's view.show.after
// trigger discards listener return values, so echo it here — this runs
// inside the show template's output buffer, placing it in the page body.
$bodyMarkup = $this->headMetadata()->applyResource($view, $resource, $site);
if ($bodyMarkup !== null && $bodyMarkup !== '') {
echo $bodyMarkup;
}
}
public function handleBrowse(EventInterface $event): void
{
$view = $this->view($event);
if (!$view) {
return;
}
$site = $this->currentSite($view);
if ($site) {
$this->headMetadata()->applyBrowse($view, $site);
}
}
public function handlePageShow(EventInterface $event): void
{
$view = $this->view($event);
if (!$view) {
return;
}
$site = $this->currentSite($view);
$page = $view->page ?? null;
if (!$site || !$page instanceof SitePageRepresentation) {
return;
}
$store = $this->getServiceLocator()->get(PageSeoStore::class);
$store->setSite($site->id());
$overrides = $store->get($page->id());
$homepage = $site->homepage();
$isHomepage = $homepage && $homepage->id() === $page->id();
$this->headMetadata()->applyPage($view, $page, $site, $overrides, (bool) $isHomepage);
}
public function handleLayout(EventInterface $event): void
{
$view = $this->view($event);
if (!$view) {
return;
}
// Public site pages only — skip the admin layout.
$site = $this->currentSite($view);
if (!$site) {
return;
}
$this->headMetadata()->applyGlobals($view, $site);
}
// ─── API listener: queue IndexNow pings ─────────────────────────────────
public function handleContentChange(EventInterface $event): void
{
$services = $this->getServiceLocator();
$response = $event->getParam('response');
$resource = $response ? $response->getContent() : null;
if (!$resource) {
return;
}
$this->invalidateSitemap();
$queue = $services->get(PingQueue::class);
if (!$queue->isEnabled()) {
return;
}
// Creates/updates announce a public URL; a delete is pinged regardless
// of visibility so engines recrawl and drop it. (A public→private
// *update* is not pinged — the previous state isn't in the event — but
// the sitemap invalidation above already stops advertising it.)
$isDelete = (string) $event->getName() === 'api.delete.post';
if (!$isDelete && method_exists($resource, 'isPublic') && !$resource->isPublic()) {
return;
}
$url = $this->resourcePublicUrl($resource);
if ($url === null) {
return;
}
try {
$queue->push($url);
$queue->dispatchIfDue();
} catch (\Throwable $error) {
$services->get('Omeka\Logger')->err('IwacSeo: failed to queue URL: ' . $error->getMessage());
}
}
public function handleSitemapChange(EventInterface $event): void
{
$this->invalidateSitemap();
}
// ─── Module configuration form ──────────────────────────────────────────
public function getConfigForm(PhpRenderer $renderer)
{
$services = $this->getServiceLocator();
$settings = $services->get('Omeka\Settings');
$form = $services->get('FormElementManager')->get(Form\ConfigForm::class);
$data = [];
foreach (self::SETTINGS as $key) {
if (in_array($key, self::INTERNAL_SETTINGS, true)) {
continue;
}
$data[$key] = $settings->get($key, self::DEFAULTS[$key] ?? '');
}
$form->setData($data);
return $renderer->formCollection($form, false);
}
public function handleConfigForm(AbstractController $controller)
{
$services = $this->getServiceLocator();
$settings = $services->get('Omeka\Settings');
$form = $services->get('FormElementManager')->get(Form\ConfigForm::class);
$form->setData($controller->params()->fromPost());
if (!$form->isValid()) {
$controller->messenger()->addErrors($form->getMessages());
return false;
}
$data = $form->getData();
foreach (self::SETTINGS as $key) {
if (in_array($key, self::INTERNAL_SETTINGS, true)) {
continue;
}
if (array_key_exists($key, $data)) {
$settings->set($key, (string) $data[$key]);
}
}
return true;
}
// ─── Internals ──────────────────────────────────────────────────────────
/**
* Invalidate the sitemap cache so a change shows up on the next crawl
* instead of after the TTL. Any create/update can affect the URL set or a
* <lastmod> (including a public→private edit), so there is no public check.
* The clear is debounced per request, so a bulk import pays for it once
* rather than once per saved item.
*/
private function invalidateSitemap(): void
{
$services = $this->getServiceLocator();
if (!$services->get(SettingsGate::class)->isOn('iwac_seo_sitemap_enabled', true)) {
return;
}
try {
$services->get(SitemapGenerator::class)->clearCache();
} catch (\Throwable $e) {
// never let SEO bookkeeping break a save
}
}
/** Set each default that has no stored value yet. */
private function applyDefaults(\Omeka\Settings\Settings $settings): void
{
foreach (self::DEFAULTS as $key => $value) {
if ($settings->get($key) === null) {
$settings->set($key, $value);
}
}
}
private function headMetadata(): HeadMetadata
{
return $this->getServiceLocator()->get(HeadMetadata::class);
}
private function view(EventInterface $event): ?PhpRenderer
{
$view = $event->getParam('view');
if (!$view instanceof PhpRenderer) {
$target = $event->getTarget();
$view = $target instanceof PhpRenderer ? $target : null;
}
return $view;
}
private function currentSite(PhpRenderer $view): ?SiteRepresentation
{
$helpers = $view->getHelperPluginManager();
if (!$helpers->has('currentSite')) {
return null;
}
try {
$site = $view->currentSite();
return $site instanceof SiteRepresentation ? $site : null;
} catch (\Throwable $e) {
return null;
}
}
private function resourcePublicUrl(object $resource): ?string
{
return ResourceUrl::forSite(
$resource,
$this->getServiceLocator()->get(SiteResolver::class)->defaultSlug()
);
}
}